]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
s12z regen
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
e2882c85 3 Copyright (C) 1988-2018 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
76727919 39#include "observable.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
c0272db5 73#include "record-btrace.h"
325fac50 74#include <algorithm>
2ec845e7 75#include "common/scoped_restore.h"
0a2dde4a 76#include "environ.h"
f6327dcb 77#include "common/byte-vector.h"
9d6eea31 78#include <unordered_map>
35b1e5cc 79
f6ac5f3d
PA
80/* The remote target. */
81
d9f719f1
PA
82static const char remote_doc[] = N_("\
83Use a remote computer via a serial line, using a gdb-specific protocol.\n\
84Specify the serial device it is connected to\n\
85(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
86
6b8edb51
PA
87#define OPAQUETHREADBYTES 8
88
89/* a 64 bit opaque identifier */
90typedef unsigned char threadref[OPAQUETHREADBYTES];
91
92struct gdb_ext_thread_info;
93struct threads_listing_context;
94typedef int (*rmt_thread_action) (threadref *ref, void *context);
95struct protocol_feature;
96struct packet_reg;
97
98struct stop_reply;
99typedef struct stop_reply *stop_reply_p;
100
101DECLARE_QUEUE_P (stop_reply_p);
102DEFINE_QUEUE_P (stop_reply_p);
103
104/* Generic configuration support for packets the stub optionally
105 supports. Allows the user to specify the use of the packet as well
106 as allowing GDB to auto-detect support in the remote stub. */
107
108enum packet_support
109 {
110 PACKET_SUPPORT_UNKNOWN = 0,
111 PACKET_ENABLE,
112 PACKET_DISABLE
113 };
114
115/* Analyze a packet's return value and update the packet config
116 accordingly. */
117
118enum packet_result
119{
120 PACKET_ERROR,
121 PACKET_OK,
122 PACKET_UNKNOWN
123};
124
125struct threads_listing_context;
126struct remote_state;
127
d9f719f1
PA
128static const target_info remote_target_info = {
129 "remote",
130 N_("Remote serial target in gdb-specific protocol"),
131 remote_doc
132};
133
f6ac5f3d
PA
134class remote_target : public target_ops
135{
136public:
137 remote_target ()
138 {
139 to_stratum = process_stratum;
140 }
6b8edb51 141 ~remote_target () override;
f6ac5f3d 142
d9f719f1
PA
143 const target_info &info () const override
144 { return remote_target_info; }
f6ac5f3d
PA
145
146 thread_control_capabilities get_thread_control_capabilities () override
147 { return tc_schedlock; }
148
d9f719f1
PA
149 /* Open a remote connection. */
150 static void open (const char *, int);
151
f6ac5f3d
PA
152 void close () override;
153
154 void detach (inferior *, int) override;
155 void disconnect (const char *, int) override;
156
157 void commit_resume () override;
158 void resume (ptid_t, int, enum gdb_signal) override;
159 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
160
161 void fetch_registers (struct regcache *, int) override;
162 void store_registers (struct regcache *, int) override;
163 void prepare_to_store (struct regcache *) override;
164
165 void files_info () override;
166
167 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
168
169 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
170 enum remove_bp_reason) override;
171
172
57810aa7
PA
173 bool stopped_by_sw_breakpoint () override;
174 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 175
57810aa7 176 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 177
57810aa7 178 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 179
57810aa7 180 bool stopped_by_watchpoint () override;
f6ac5f3d 181
57810aa7 182 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 183
57810aa7 184 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
185
186 int can_use_hw_breakpoint (enum bptype, int, int) override;
187
188 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
189
190 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
191
192 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
193
194 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
195 struct expression *) override;
196
197 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
198 struct expression *) override;
199
200 void kill () override;
201
202 void load (const char *, int) override;
203
204 void mourn_inferior () override;
205
206 void pass_signals (int, unsigned char *) override;
207
208 int set_syscall_catchpoint (int, bool, int,
209 gdb::array_view<const int>) override;
210
211 void program_signals (int, unsigned char *) override;
212
57810aa7 213 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
214
215 const char *thread_name (struct thread_info *) override;
216
217 void update_thread_list () override;
218
219 const char *pid_to_str (ptid_t) override;
220
221 const char *extra_thread_info (struct thread_info *) override;
222
223 ptid_t get_ada_task_ptid (long lwp, long thread) override;
224
225 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
226 int handle_len,
227 inferior *inf) override;
228
229 void stop (ptid_t) override;
230
231 void interrupt () override;
232
233 void pass_ctrlc () override;
234
235 enum target_xfer_status xfer_partial (enum target_object object,
236 const char *annex,
237 gdb_byte *readbuf,
238 const gdb_byte *writebuf,
239 ULONGEST offset, ULONGEST len,
240 ULONGEST *xfered_len) override;
241
242 ULONGEST get_memory_xfer_limit () override;
243
244 void rcmd (const char *command, struct ui_file *output) override;
245
246 char *pid_to_exec_file (int pid) override;
247
248 void log_command (const char *cmd) override
249 {
250 serial_log_command (this, cmd);
251 }
252
253 CORE_ADDR get_thread_local_address (ptid_t ptid,
254 CORE_ADDR load_module_addr,
255 CORE_ADDR offset) override;
256
57810aa7
PA
257 bool has_all_memory () override { return default_child_has_all_memory (); }
258 bool has_memory () override { return default_child_has_memory (); }
259 bool has_stack () override { return default_child_has_stack (); }
260 bool has_registers () override { return default_child_has_registers (); }
261 bool has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
f6ac5f3d 262
57810aa7 263 bool can_execute_reverse () override;
f6ac5f3d
PA
264
265 std::vector<mem_region> memory_map () override;
266
267 void flash_erase (ULONGEST address, LONGEST length) override;
268
269 void flash_done () override;
270
271 const struct target_desc *read_description () override;
272
273 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
274 const gdb_byte *pattern, ULONGEST pattern_len,
275 CORE_ADDR *found_addrp) override;
276
57810aa7 277 bool can_async_p () override;
f6ac5f3d 278
57810aa7 279 bool is_async_p () override;
f6ac5f3d
PA
280
281 void async (int) override;
282
283 void thread_events (int) override;
284
285 int can_do_single_step () override;
286
287 void terminal_inferior () override;
288
289 void terminal_ours () override;
290
57810aa7 291 bool supports_non_stop () override;
f6ac5f3d 292
57810aa7 293 bool supports_multi_process () override;
f6ac5f3d 294
57810aa7 295 bool supports_disable_randomization () override;
f6ac5f3d 296
57810aa7 297 bool filesystem_is_local () override;
f6ac5f3d
PA
298
299
300 int fileio_open (struct inferior *inf, const char *filename,
301 int flags, int mode, int warn_if_slow,
302 int *target_errno) override;
303
304 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
305 ULONGEST offset, int *target_errno) override;
306
307 int fileio_pread (int fd, gdb_byte *read_buf, int len,
308 ULONGEST offset, int *target_errno) override;
309
310 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
311
312 int fileio_close (int fd, int *target_errno) override;
313
314 int fileio_unlink (struct inferior *inf,
315 const char *filename,
316 int *target_errno) override;
317
318 gdb::optional<std::string>
319 fileio_readlink (struct inferior *inf,
320 const char *filename,
321 int *target_errno) override;
322
57810aa7 323 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 324
57810aa7 325 bool supports_string_tracing () override;
f6ac5f3d 326
57810aa7 327 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 328
57810aa7 329 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
330
331 void trace_init () override;
332
333 void download_tracepoint (struct bp_location *location) override;
334
57810aa7 335 bool can_download_tracepoint () override;
f6ac5f3d
PA
336
337 void download_trace_state_variable (const trace_state_variable &tsv) override;
338
339 void enable_tracepoint (struct bp_location *location) override;
340
341 void disable_tracepoint (struct bp_location *location) override;
342
343 void trace_set_readonly_regions () override;
344
345 void trace_start () override;
346
347 int get_trace_status (struct trace_status *ts) override;
348
349 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
350 override;
351
352 void trace_stop () override;
353
354 int trace_find (enum trace_find_type type, int num,
355 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
356
57810aa7 357 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
358
359 int save_trace_data (const char *filename) override;
360
361 int upload_tracepoints (struct uploaded_tp **utpp) override;
362
363 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
364
365 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
366
367 int get_min_fast_tracepoint_insn_len () override;
368
369 void set_disconnected_tracing (int val) override;
370
371 void set_circular_trace_buffer (int val) override;
372
373 void set_trace_buffer_size (LONGEST val) override;
374
57810aa7
PA
375 bool set_trace_notes (const char *user, const char *notes,
376 const char *stopnotes) override;
f6ac5f3d
PA
377
378 int core_of_thread (ptid_t ptid) override;
379
380 int verify_memory (const gdb_byte *data,
381 CORE_ADDR memaddr, ULONGEST size) override;
382
383
57810aa7 384 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
385
386 void set_permissions () override;
387
388 bool static_tracepoint_marker_at (CORE_ADDR,
389 struct static_tracepoint_marker *marker)
390 override;
391
392 std::vector<static_tracepoint_marker>
393 static_tracepoint_markers_by_strid (const char *id) override;
394
395 traceframe_info_up traceframe_info () override;
396
57810aa7
PA
397 bool use_agent (bool use) override;
398 bool can_use_agent () override;
f6ac5f3d
PA
399
400 struct btrace_target_info *enable_btrace (ptid_t ptid,
401 const struct btrace_config *conf) override;
402
403 void disable_btrace (struct btrace_target_info *tinfo) override;
404
405 void teardown_btrace (struct btrace_target_info *tinfo) override;
406
407 enum btrace_error read_btrace (struct btrace_data *data,
408 struct btrace_target_info *btinfo,
409 enum btrace_read_type type) override;
410
411 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 412 bool augmented_libraries_svr4_read () override;
f6ac5f3d
PA
413 int follow_fork (int, int) override;
414 void follow_exec (struct inferior *, char *) override;
415 int insert_fork_catchpoint (int) override;
416 int remove_fork_catchpoint (int) override;
417 int insert_vfork_catchpoint (int) override;
418 int remove_vfork_catchpoint (int) override;
419 int insert_exec_catchpoint (int) override;
420 int remove_exec_catchpoint (int) override;
421 enum exec_direction_kind execution_direction () override;
422
6b8edb51
PA
423public: /* Remote specific methods. */
424
425 void remote_download_command_source (int num, ULONGEST addr,
426 struct command_line *cmds);
427
428 void remote_file_put (const char *local_file, const char *remote_file,
429 int from_tty);
430 void remote_file_get (const char *remote_file, const char *local_file,
431 int from_tty);
432 void remote_file_delete (const char *remote_file, int from_tty);
433
434 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
435 ULONGEST offset, int *remote_errno);
436 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
437 ULONGEST offset, int *remote_errno);
438 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
439 ULONGEST offset, int *remote_errno);
440
441 int remote_hostio_send_command (int command_bytes, int which_packet,
442 int *remote_errno, char **attachment,
443 int *attachment_len);
444 int remote_hostio_set_filesystem (struct inferior *inf,
445 int *remote_errno);
446 /* We should get rid of this and use fileio_open directly. */
447 int remote_hostio_open (struct inferior *inf, const char *filename,
448 int flags, int mode, int warn_if_slow,
449 int *remote_errno);
450 int remote_hostio_close (int fd, int *remote_errno);
451
452 int remote_hostio_unlink (inferior *inf, const char *filename,
453 int *remote_errno);
454
455 struct remote_state *get_remote_state ();
456
457 long get_remote_packet_size (void);
458 long get_memory_packet_size (struct memory_packet_config *config);
459
460 long get_memory_write_packet_size ();
461 long get_memory_read_packet_size ();
462
463 char *append_pending_thread_resumptions (char *p, char *endp,
464 ptid_t ptid);
d9f719f1 465 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d 466 void start_remote (int from_tty, int extended_p);
6b8edb51
PA
467 void remote_detach_1 (int from_tty, struct inferior *inf);
468
469 char *append_resumption (char *p, char *endp,
470 ptid_t ptid, int step, gdb_signal siggnal);
471 int remote_resume_with_vcont (ptid_t ptid, int step,
472 gdb_signal siggnal);
473
474 void add_current_inferior_and_thread (char *wait_status);
475
476 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
477 int options);
478 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
479 int options);
480
481 ptid_t process_stop_reply (struct stop_reply *stop_reply,
482 target_waitstatus *status);
483
484 void remote_notice_new_inferior (ptid_t currthread, int executing);
485
486 void process_initial_stop_replies (int from_tty);
487
488 void remote_add_thread (ptid_t ptid, bool running, bool executing);
489
490 void btrace_sync_conf (const btrace_config *conf);
491
492 void remote_btrace_maybe_reopen ();
493
494 void remove_new_fork_children (threads_listing_context *context);
495 void kill_new_fork_children (int pid);
496 void discard_pending_stop_replies (struct inferior *inf);
497 int stop_reply_queue_length ();
498
499 void check_pending_events_prevent_wildcard_vcont
500 (int *may_global_wildcard_vcont);
501
502 void discard_pending_stop_replies_in_queue ();
503 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
504 struct stop_reply *queued_stop_reply (ptid_t ptid);
505 int peek_stop_reply (ptid_t ptid);
506 void remote_parse_stop_reply (char *buf, stop_reply *event);
507
508 void remote_stop_ns (ptid_t ptid);
509 void remote_interrupt_as ();
510 void remote_interrupt_ns ();
511
512 char *remote_get_noisy_reply ();
513 int remote_query_attached (int pid);
514 inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
515 int try_open_exec);
516
517 ptid_t remote_current_thread (ptid_t oldpid);
518 ptid_t get_current_thread (char *wait_status);
519
520 void set_thread (ptid_t ptid, int gen);
521 void set_general_thread (ptid_t ptid);
522 void set_continue_thread (ptid_t ptid);
523 void set_general_process ();
524
525 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
526
527 int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
528 gdb_ext_thread_info *info);
529 int remote_get_threadinfo (threadref *threadid, int fieldset,
530 gdb_ext_thread_info *info);
531
532 int parse_threadlist_response (char *pkt, int result_limit,
533 threadref *original_echo,
534 threadref *resultlist,
535 int *doneflag);
536 int remote_get_threadlist (int startflag, threadref *nextthread,
537 int result_limit, int *done, int *result_count,
538 threadref *threadlist);
539
540 int remote_threadlist_iterator (rmt_thread_action stepfunction,
541 void *context, int looplimit);
542
543 int remote_get_threads_with_ql (threads_listing_context *context);
544 int remote_get_threads_with_qxfer (threads_listing_context *context);
545 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
546
547 void extended_remote_restart ();
548
549 void get_offsets ();
550
551 void remote_check_symbols ();
552
553 void remote_supported_packet (const struct protocol_feature *feature,
554 enum packet_support support,
555 const char *argument);
556
557 void remote_query_supported ();
558
559 void remote_packet_size (const protocol_feature *feature,
560 packet_support support, const char *value);
561
562 void remote_serial_quit_handler ();
563
564 void remote_detach_pid (int pid);
565
566 void remote_vcont_probe ();
567
568 void remote_resume_with_hc (ptid_t ptid, int step,
569 gdb_signal siggnal);
570
571 void send_interrupt_sequence ();
572 void interrupt_query ();
573
574 void remote_notif_get_pending_events (notif_client *nc);
575
576 int fetch_register_using_p (struct regcache *regcache,
577 packet_reg *reg);
578 int send_g_packet ();
579 void process_g_packet (struct regcache *regcache);
580 void fetch_registers_using_g (struct regcache *regcache);
581 int store_register_using_P (const struct regcache *regcache,
582 packet_reg *reg);
583 void store_registers_using_G (const struct regcache *regcache);
584
585 void set_remote_traceframe ();
586
587 void check_binary_download (CORE_ADDR addr);
588
589 target_xfer_status remote_write_bytes_aux (const char *header,
590 CORE_ADDR memaddr,
591 const gdb_byte *myaddr,
592 ULONGEST len_units,
593 int unit_size,
594 ULONGEST *xfered_len_units,
595 char packet_format,
596 int use_length);
597
598 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
599 const gdb_byte *myaddr, ULONGEST len,
600 int unit_size, ULONGEST *xfered_len);
601
602 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
603 ULONGEST len_units,
604 int unit_size, ULONGEST *xfered_len_units);
605
606 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
607 ULONGEST memaddr,
608 ULONGEST len,
609 int unit_size,
610 ULONGEST *xfered_len);
611
612 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
613 gdb_byte *myaddr, ULONGEST len,
614 int unit_size,
615 ULONGEST *xfered_len);
616
617 packet_result remote_send_printf (const char *format, ...)
618 ATTRIBUTE_PRINTF (2, 3);
619
620 target_xfer_status remote_flash_write (ULONGEST address,
621 ULONGEST length, ULONGEST *xfered_len,
622 const gdb_byte *data);
623
624 int readchar (int timeout);
625
626 void remote_serial_write (const char *str, int len);
627
628 int putpkt (const char *buf);
629 int putpkt_binary (const char *buf, int cnt);
630
631 void skip_frame ();
632 long read_frame (char **buf_p, long *sizeof_buf);
633 void getpkt (char **buf, long *sizeof_buf, int forever);
634 int getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
635 int expecting_notif, int *is_notif);
636 int getpkt_sane (char **buf, long *sizeof_buf, int forever);
637 int getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
638 int *is_notif);
639 int remote_vkill (int pid);
640 void remote_kill_k ();
641
642 void extended_remote_disable_randomization (int val);
643 int extended_remote_run (const std::string &args);
644
645 void send_environment_packet (const char *action,
646 const char *packet,
647 const char *value);
648
649 void extended_remote_environment_support ();
650 void extended_remote_set_inferior_cwd ();
651
652 target_xfer_status remote_write_qxfer (const char *object_name,
653 const char *annex,
654 const gdb_byte *writebuf,
655 ULONGEST offset, LONGEST len,
656 ULONGEST *xfered_len,
657 struct packet_config *packet);
658
659 target_xfer_status remote_read_qxfer (const char *object_name,
660 const char *annex,
661 gdb_byte *readbuf, ULONGEST offset,
662 LONGEST len,
663 ULONGEST *xfered_len,
664 struct packet_config *packet);
665
666 void push_stop_reply (struct stop_reply *new_event);
667
668 bool vcont_r_supported ();
669
670 void packet_command (const char *args, int from_tty);
671
672private: /* data fields */
673
674 std::unique_ptr<struct remote_state> m_remote_state;
f6ac5f3d
PA
675};
676
d9f719f1
PA
677static const target_info extended_remote_target_info = {
678 "extended-remote",
679 N_("Extended remote serial target in gdb-specific protocol"),
680 remote_doc
681};
682
f6ac5f3d
PA
683/* Set up the extended remote target by extending the standard remote
684 target and adding to it. */
685
686class extended_remote_target final : public remote_target
687{
688public:
d9f719f1
PA
689 const target_info &info () const override
690 { return extended_remote_target_info; }
f6ac5f3d 691
d9f719f1
PA
692 /* Open an extended-remote connection. */
693 static void open (const char *, int);
f6ac5f3d
PA
694
695 bool can_create_inferior () override { return true; }
696 void create_inferior (const char *, const std::string &,
697 char **, int) override;
698
699 void detach (inferior *, int) override;
700
701 bool can_attach () override { return true; }
702 void attach (const char *, int) override;
703
704 void post_attach (int) override;
57810aa7 705 bool supports_disable_randomization () override;
f6ac5f3d
PA
706};
707
94585166
DB
708/* Per-program-space data key. */
709static const struct program_space_data *remote_pspace_data;
710
711/* The variable registered as the control variable used by the
712 remote exec-file commands. While the remote exec-file setting is
713 per-program-space, the set/show machinery uses this as the
714 location of the remote exec-file value. */
715static char *remote_exec_file_var;
716
6765f3e5
DJ
717/* The size to align memory write packets, when practical. The protocol
718 does not guarantee any alignment, and gdb will generate short
719 writes and unaligned writes, but even as a best-effort attempt this
720 can improve bulk transfers. For instance, if a write is misaligned
721 relative to the target's data bus, the stub may need to make an extra
722 round trip fetching data from the target. This doesn't make a
723 huge difference, but it's easy to do, so we try to be helpful.
724
725 The alignment chosen is arbitrary; usually data bus width is
726 important here, not the possibly larger cache line size. */
727enum { REMOTE_ALIGN_WRITES = 16 };
728
23860348 729/* Prototypes for local functions. */
c906108c 730
a14ed312 731static int hexnumlen (ULONGEST num);
c906108c 732
a14ed312 733static int stubhex (int ch);
c906108c 734
a14ed312 735static int hexnumstr (char *, ULONGEST);
c906108c 736
a14ed312 737static int hexnumnstr (char *, ULONGEST, int);
2df3850c 738
a14ed312 739static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 740
baa336ce 741static void print_packet (const char *);
c906108c 742
a14ed312 743static int stub_unpack_int (char *buff, int fieldlength);
c906108c 744
5a2468f5 745struct packet_config;
5a2468f5 746
a14ed312 747static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 748
bb572ddd
DJ
749static void show_remote_protocol_packet_cmd (struct ui_file *file,
750 int from_tty,
751 struct cmd_list_element *c,
752 const char *value);
753
256642e8 754static ptid_t read_ptid (const char *buf, const char **obuf);
82f73884 755
74531fed 756struct stop_reply;
74531fed 757static void stop_reply_xfree (struct stop_reply *);
cbb8991c 758
74531fed 759static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 760
d962ef82
DJ
761static int remote_read_description_p (struct target_ops *target);
762
176a6961 763static void remote_console_output (char *msg);
dde08ee1 764
6b8edb51 765static void remote_btrace_reset (remote_state *rs);
221e1a37 766
048094ac
PA
767static void remote_unpush_and_throw (void);
768
a6b151f1
DJ
769/* For "remote". */
770
771static struct cmd_list_element *remote_cmdlist;
772
bb572ddd
DJ
773/* For "set remote" and "show remote". */
774
775static struct cmd_list_element *remote_set_cmdlist;
776static struct cmd_list_element *remote_show_cmdlist;
777
d458bd84
PA
778/* Stub vCont actions support.
779
780 Each field is a boolean flag indicating whether the stub reports
781 support for the corresponding action. */
782
783struct vCont_action_support
784{
785 /* vCont;t */
de44f5a7 786 bool t = false;
c1e36e3e
PA
787
788 /* vCont;r */
de44f5a7 789 bool r = false;
750ce8d1
YQ
790
791 /* vCont;s */
de44f5a7 792 bool s = false;
750ce8d1
YQ
793
794 /* vCont;S */
de44f5a7 795 bool S = false;
d458bd84
PA
796};
797
c1e36e3e
PA
798/* Controls whether GDB is willing to use range stepping. */
799
800static int use_range_stepping = 1;
801
0d031856
TT
802/* About this many threadisds fit in a packet. */
803
804#define MAXTHREADLISTRESULTS 32
805
6f8976bf
YQ
806/* The max number of chars in debug output. The rest of chars are
807 omitted. */
808
809#define REMOTE_DEBUG_MAX_CHAR 512
810
80152258
PA
811/* Data for the vFile:pread readahead cache. */
812
813struct readahead_cache
814{
dd194f6b
PA
815 /* Invalidate the readahead cache. */
816 void invalidate ();
817
818 /* Invalidate the readahead cache if it is holding data for FD. */
819 void invalidate_fd (int fd);
820
821 /* Serve pread from the readahead cache. Returns number of bytes
822 read, or 0 if the request can't be served from the cache. */
823 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
824
80152258
PA
825 /* The file descriptor for the file that is being cached. -1 if the
826 cache is invalid. */
de44f5a7 827 int fd = -1;
80152258
PA
828
829 /* The offset into the file that the cache buffer corresponds
830 to. */
de44f5a7 831 ULONGEST offset = 0;
80152258
PA
832
833 /* The buffer holding the cache contents. */
de44f5a7 834 gdb_byte *buf = nullptr;
80152258
PA
835 /* The buffer's size. We try to read as much as fits into a packet
836 at a time. */
de44f5a7 837 size_t bufsize = 0;
80152258
PA
838
839 /* Cache hit and miss counters. */
de44f5a7
PA
840 ULONGEST hit_count = 0;
841 ULONGEST miss_count = 0;
80152258
PA
842};
843
43c3a0e4
PA
844/* Description of the remote protocol for a given architecture. */
845
846struct packet_reg
847{
848 long offset; /* Offset into G packet. */
849 long regnum; /* GDB's internal register number. */
850 LONGEST pnum; /* Remote protocol register number. */
851 int in_g_packet; /* Always part of G packet. */
852 /* long size in bytes; == register_size (target_gdbarch (), regnum);
853 at present. */
854 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
855 at present. */
856};
857
858struct remote_arch_state
859{
860 explicit remote_arch_state (struct gdbarch *gdbarch);
861
862 /* Description of the remote protocol registers. */
863 long sizeof_g_packet;
864
865 /* Description of the remote protocol registers indexed by REGNUM
866 (making an array gdbarch_num_regs in size). */
867 std::unique_ptr<packet_reg[]> regs;
868
869 /* This is the size (in chars) of the first response to the ``g''
870 packet. It is used as a heuristic when determining the maximum
871 size of memory-read and memory-write packets. A target will
872 typically only reserve a buffer large enough to hold the ``g''
873 packet. The size does not include packet overhead (headers and
874 trailers). */
875 long actual_register_packet_size;
876
877 /* This is the maximum size (in chars) of a non read/write packet.
878 It is also used as a cap on the size of read/write packets. */
879 long remote_packet_size;
880};
881
ea9c271d
DJ
882/* Description of the remote protocol state for the currently
883 connected target. This is per-target state, and independent of the
884 selected architecture. */
885
9d6eea31 886class remote_state
ea9c271d 887{
9d6eea31
PA
888public:
889
de44f5a7
PA
890 remote_state ();
891 ~remote_state ();
892
9d6eea31
PA
893 /* Get the remote arch state for GDBARCH. */
894 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
895
896public: /* data */
897
ea9c271d
DJ
898 /* A buffer to use for incoming packets, and its current size. The
899 buffer is grown dynamically for larger incoming packets.
900 Outgoing packets may also be constructed in this buffer.
901 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
902 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
903 packets. */
904 char *buf;
905 long buf_size;
be2a5f71 906
1e51243a
PA
907 /* True if we're going through initial connection setup (finding out
908 about the remote side's threads, relocating symbols, etc.). */
de44f5a7 909 bool starting_up = false;
1e51243a 910
be2a5f71
DJ
911 /* If we negotiated packet size explicitly (and thus can bypass
912 heuristics for the largest packet size that will not overflow
913 a buffer in the stub), this will be set to that packet size.
914 Otherwise zero, meaning to use the guessed size. */
de44f5a7 915 long explicit_packet_size = 0;
2d717e4f
DJ
916
917 /* remote_wait is normally called when the target is running and
918 waits for a stop reply packet. But sometimes we need to call it
919 when the target is already stopped. We can send a "?" packet
920 and have remote_wait read the response. Or, if we already have
921 the response, we can stash it in BUF and tell remote_wait to
922 skip calling getpkt. This flag is set when BUF contains a
923 stop reply packet and the target is not waiting. */
de44f5a7 924 int cached_wait_status = 0;
a6f3e723
SL
925
926 /* True, if in no ack mode. That is, neither GDB nor the stub will
927 expect acks from each other. The connection is assumed to be
928 reliable. */
de44f5a7 929 bool noack_mode = false;
82f73884
PA
930
931 /* True if we're connected in extended remote mode. */
de44f5a7 932 bool extended = false;
82f73884 933
e24a49d8
PA
934 /* True if we resumed the target and we're waiting for the target to
935 stop. In the mean time, we can't start another command/query.
936 The remote server wouldn't be ready to process it, so we'd
937 timeout waiting for a reply that would never come and eventually
938 we'd close the connection. This can happen in asynchronous mode
939 because we allow GDB commands while the target is running. */
de44f5a7 940 bool waiting_for_stop_reply = false;
74531fed 941
d458bd84 942 /* The status of the stub support for the various vCont actions. */
de44f5a7 943 vCont_action_support supports_vCont;
782b2b07 944
de44f5a7 945 /* True if the user has pressed Ctrl-C, but the target hasn't
3a29589a 946 responded to that. */
de44f5a7 947 bool ctrlc_pending_p = false;
5d93a237 948
048094ac
PA
949 /* True if we saw a Ctrl-C while reading or writing from/to the
950 remote descriptor. At that point it is not safe to send a remote
951 interrupt packet, so we instead remember we saw the Ctrl-C and
952 process it once we're done with sending/receiving the current
953 packet, which should be shortly. If however that takes too long,
954 and the user presses Ctrl-C again, we offer to disconnect. */
de44f5a7 955 bool got_ctrlc_during_io = false;
048094ac 956
5d93a237
TT
957 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
958 remote_open knows that we don't have a file open when the program
959 starts. */
de44f5a7 960 struct serial *remote_desc = nullptr;
47f8a51d
TT
961
962 /* These are the threads which we last sent to the remote system. The
963 TID member will be -1 for all or -2 for not sent yet. */
de44f5a7
PA
964 ptid_t general_thread = null_ptid;
965 ptid_t continue_thread = null_ptid;
262e1174
TT
966
967 /* This is the traceframe which we last selected on the remote system.
968 It will be -1 if no traceframe is selected. */
de44f5a7 969 int remote_traceframe_number = -1;
747dc59d 970
de44f5a7 971 char *last_pass_packet = nullptr;
5e4a05c4
TT
972
973 /* The last QProgramSignals packet sent to the target. We bypass
974 sending a new program signals list down to the target if the new
975 packet is exactly the same as the last we sent. IOW, we only let
976 the target know about program signals list changes. */
de44f5a7 977 char *last_program_signals_packet = nullptr;
b73be471 978
de44f5a7 979 gdb_signal last_sent_signal = GDB_SIGNAL_0;
280ceea3 980
de44f5a7 981 bool last_sent_step = false;
8e88304f 982
3a00c802 983 /* The execution direction of the last resume we got. */
de44f5a7 984 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
3a00c802 985
de44f5a7
PA
986 char *finished_object = nullptr;
987 char *finished_annex = nullptr;
988 ULONGEST finished_offset = 0;
b80fafe3
TT
989
990 /* Should we try the 'ThreadInfo' query packet?
991
992 This variable (NOT available to the user: auto-detect only!)
993 determines whether GDB will use the new, simpler "ThreadInfo"
994 query or the older, more complex syntax for thread queries.
995 This is an auto-detect variable (set to true at each connect,
996 and set to false when the target fails to recognize it). */
de44f5a7
PA
997 bool use_threadinfo_query = false;
998 bool use_threadextra_query = false;
88b496c3 999
de44f5a7
PA
1000 threadref echo_nextthread {};
1001 threadref nextthread {};
1002 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
5965e028
YQ
1003
1004 /* The state of remote notification. */
de44f5a7 1005 struct remote_notif_state *notif_state = nullptr;
f4abbc16
MM
1006
1007 /* The branch trace configuration. */
de44f5a7 1008 struct btrace_config btrace_config {};
15a201c8
GB
1009
1010 /* The argument to the last "vFile:setfs:" packet we sent, used
1011 to avoid sending repeated unnecessary "vFile:setfs:" packets.
1012 Initialized to -1 to indicate that no "vFile:setfs:" packet
1013 has yet been sent. */
de44f5a7 1014 int fs_pid = -1;
80152258
PA
1015
1016 /* A readahead cache for vFile:pread. Often, reading a binary
1017 involves a sequence of small reads. E.g., when parsing an ELF
1018 file. A readahead cache helps mostly the case of remote
1019 debugging on a connection with higher latency, due to the
1020 request/reply nature of the RSP. We only cache data for a single
1021 file descriptor at a time. */
1022 struct readahead_cache readahead_cache;
9d6eea31 1023
6b8edb51
PA
1024 /* The list of already fetched and acknowledged stop events. This
1025 queue is used for notification Stop, and other notifications
1026 don't need queue for their events, because the notification
1027 events of Stop can't be consumed immediately, so that events
1028 should be queued first, and be consumed by remote_wait_{ns,as}
1029 one per time. Other notifications can consume their events
1030 immediately, so queue is not needed for them. */
1031 QUEUE (stop_reply_p) *stop_reply_queue;
1032
1033 /* Asynchronous signal handle registered as event loop source for
1034 when we have pending events ready to be passed to the core. */
1035 struct async_event_handler *remote_async_inferior_event_token = nullptr;
1036
1037 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
1038 ``forever'' still use the normal timeout mechanism. This is
1039 currently used by the ASYNC code to guarentee that target reads
1040 during the initial connect always time-out. Once getpkt has been
1041 modified to return a timeout indication and, in turn
1042 remote_wait()/wait_for_inferior() have gained a timeout parameter
1043 this can go away. */
1044 int wait_forever_enabled_p = 1;
1045
9d6eea31
PA
1046private:
1047 /* Mapping of remote protocol data for each gdbarch. Usually there
1048 is only one entry here, though we may see more with stubs that
1049 support multi-process. */
43c3a0e4 1050 std::unordered_map<struct gdbarch *, remote_arch_state>
9d6eea31 1051 m_arch_states;
ea9c271d
DJ
1052};
1053
7aabaf9d
SM
1054/* Private data that we'll store in (struct thread_info)->priv. */
1055struct remote_thread_info : public private_thread_info
dc146f7c 1056{
7aabaf9d
SM
1057 std::string extra;
1058 std::string name;
1059 int core = -1;
799a2abe 1060
f6327dcb
KB
1061 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1062 sequence of bytes. */
7aabaf9d 1063 gdb::byte_vector thread_handle;
f6327dcb 1064
799a2abe 1065 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1066 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1067
1068 /* This is set to the data address of the access causing the target
1069 to stop for a watchpoint. */
7aabaf9d 1070 CORE_ADDR watch_data_address = 0;
85ad3aaf
PA
1071
1072 /* Fields used by the vCont action coalescing implemented in
1073 remote_resume / remote_commit_resume. remote_resume stores each
1074 thread's last resume request in these fields, so that a later
1075 remote_commit_resume knows which is the proper action for this
1076 thread to include in the vCont packet. */
1077
1078 /* True if the last target_resume call for this thread was a step
1079 request, false if a continue request. */
7aabaf9d 1080 int last_resume_step = 0;
85ad3aaf
PA
1081
1082 /* The signal specified in the last target_resume call for this
1083 thread. */
7aabaf9d 1084 gdb_signal last_resume_sig = GDB_SIGNAL_0;
85ad3aaf
PA
1085
1086 /* Whether this thread was already vCont-resumed on the remote
1087 side. */
7aabaf9d 1088 int vcont_resumed = 0;
dc146f7c
VP
1089};
1090
de44f5a7
PA
1091remote_state::remote_state ()
1092{
1093 /* The default buffer size is unimportant; it will be expanded
1094 whenever a larger buffer is needed. */
1095 this->buf_size = 400;
1096 this->buf = (char *) xmalloc (this->buf_size);
6b8edb51
PA
1097
1098 this->stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
de44f5a7
PA
1099}
1100
1101remote_state::~remote_state ()
1102{
1103 xfree (this->last_pass_packet);
1104 xfree (this->last_program_signals_packet);
1105 xfree (this->buf);
1106 xfree (this->finished_object);
1107 xfree (this->finished_annex);
6b8edb51 1108 QUEUE_free (stop_reply_p, this->stop_reply_queue);
cf792862
TT
1109}
1110
35b1e5cc
SS
1111/* Utility: generate error from an incoming stub packet. */
1112static void
1113trace_error (char *buf)
1114{
1115 if (*buf++ != 'E')
1116 return; /* not an error msg */
1117 switch (*buf)
1118 {
1119 case '1': /* malformed packet error */
1120 if (*++buf == '0') /* general case: */
1121 error (_("remote.c: error in outgoing packet."));
1122 else
1123 error (_("remote.c: error in outgoing packet at field #%ld."),
1124 strtol (buf, NULL, 16));
35b1e5cc
SS
1125 default:
1126 error (_("Target returns error code '%s'."), buf);
1127 }
1128}
1129
1130/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1131
6b8edb51
PA
1132char *
1133remote_target::remote_get_noisy_reply ()
35b1e5cc 1134{
b6bb3468
PA
1135 struct remote_state *rs = get_remote_state ();
1136
35b1e5cc
SS
1137 do /* Loop on reply from remote stub. */
1138 {
1139 char *buf;
a744cf53 1140
0df8b418 1141 QUIT; /* Allow user to bail out with ^C. */
b6bb3468
PA
1142 getpkt (&rs->buf, &rs->buf_size, 0);
1143 buf = rs->buf;
ad91cd99 1144 if (buf[0] == 'E')
35b1e5cc 1145 trace_error (buf);
61012eef 1146 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1147 {
1148 ULONGEST ul;
1149 CORE_ADDR from, to, org_to;
256642e8 1150 const char *p, *pp;
dde08ee1 1151 int adjusted_size = 0;
7556d4a4 1152 int relocated = 0;
dde08ee1
PA
1153
1154 p = buf + strlen ("qRelocInsn:");
1155 pp = unpack_varlen_hex (p, &ul);
1156 if (*pp != ';')
cb91c06a 1157 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1158 from = ul;
1159
1160 p = pp + 1;
a9cbf802 1161 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1162 to = ul;
1163
1164 org_to = to;
1165
492d29ea 1166 TRY
dde08ee1 1167 {
f5656ead 1168 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 1169 relocated = 1;
dde08ee1 1170 }
492d29ea 1171 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
1172 {
1173 if (ex.error == MEMORY_ERROR)
1174 {
1175 /* Propagate memory errors silently back to the
1176 target. The stub may have limited the range of
1177 addresses we can write to, for example. */
1178 }
1179 else
1180 {
1181 /* Something unexpectedly bad happened. Be verbose
1182 so we can tell what, and propagate the error back
1183 to the stub, so it doesn't get stuck waiting for
1184 a response. */
1185 exception_fprintf (gdb_stderr, ex,
1186 _("warning: relocating instruction: "));
1187 }
1188 putpkt ("E01");
1189 }
492d29ea 1190 END_CATCH
7556d4a4
PA
1191
1192 if (relocated)
dde08ee1
PA
1193 {
1194 adjusted_size = to - org_to;
1195
b6bb3468 1196 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1197 putpkt (buf);
1198 }
dde08ee1 1199 }
ad91cd99 1200 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
1201 remote_console_output (buf + 1); /* 'O' message from stub */
1202 else
0df8b418 1203 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1204 }
1205 while (1);
1206}
3c3bea1c 1207
9d6eea31
PA
1208struct remote_arch_state *
1209remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1210{
43c3a0e4
PA
1211 remote_arch_state *rsa;
1212
1213 auto it = this->m_arch_states.find (gdbarch);
1214 if (it == this->m_arch_states.end ())
9d6eea31 1215 {
43c3a0e4
PA
1216 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1217 std::forward_as_tuple (gdbarch),
1218 std::forward_as_tuple (gdbarch));
1219 rsa = &p.first->second;
9d6eea31
PA
1220
1221 /* Make sure that the packet buffer is plenty big enough for
1222 this architecture. */
1223 if (this->buf_size < rsa->remote_packet_size)
1224 {
1225 this->buf_size = 2 * rsa->remote_packet_size;
1226 this->buf = (char *) xrealloc (this->buf, this->buf_size);
1227 }
1228 }
43c3a0e4
PA
1229 else
1230 rsa = &it->second;
1231
1232 return rsa;
d01949b6
AC
1233}
1234
0b83947e
DJ
1235/* Fetch the global remote target state. */
1236
6b8edb51
PA
1237remote_state *
1238remote_target::get_remote_state ()
0b83947e 1239{
6b8edb51
PA
1240 if (m_remote_state == nullptr)
1241 m_remote_state.reset (new remote_state ());
9d6eea31 1242
0b83947e
DJ
1243 /* Make sure that the remote architecture state has been
1244 initialized, because doing so might reallocate rs->buf. Any
1245 function which calls getpkt also needs to be mindful of changes
1246 to rs->buf, but this call limits the number of places which run
1247 into trouble. */
6b8edb51 1248 m_remote_state->get_remote_arch_state (target_gdbarch ());
0b83947e 1249
6b8edb51 1250 return m_remote_state.get ();
0b83947e
DJ
1251}
1252
94585166
DB
1253/* Cleanup routine for the remote module's pspace data. */
1254
1255static void
1256remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1257{
19ba03f4 1258 char *remote_exec_file = (char *) arg;
94585166
DB
1259
1260 xfree (remote_exec_file);
1261}
1262
1263/* Fetch the remote exec-file from the current program space. */
1264
1265static const char *
1266get_remote_exec_file (void)
1267{
1268 char *remote_exec_file;
1269
19ba03f4
SM
1270 remote_exec_file
1271 = (char *) program_space_data (current_program_space,
1272 remote_pspace_data);
94585166
DB
1273 if (remote_exec_file == NULL)
1274 return "";
1275
1276 return remote_exec_file;
1277}
1278
1279/* Set the remote exec file for PSPACE. */
1280
1281static void
1282set_pspace_remote_exec_file (struct program_space *pspace,
1283 char *remote_exec_file)
1284{
19ba03f4 1285 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
1286
1287 xfree (old_file);
1288 set_program_space_data (pspace, remote_pspace_data,
1289 xstrdup (remote_exec_file));
1290}
1291
1292/* The "set/show remote exec-file" set command hook. */
1293
1294static void
eb4c3f4a 1295set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1296 struct cmd_list_element *c)
1297{
1298 gdb_assert (remote_exec_file_var != NULL);
1299 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1300}
1301
1302/* The "set/show remote exec-file" show command hook. */
1303
1304static void
1305show_remote_exec_file (struct ui_file *file, int from_tty,
1306 struct cmd_list_element *cmd, const char *value)
1307{
1308 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1309}
1310
74ca34ce
DJ
1311static int
1312compare_pnums (const void *lhs_, const void *rhs_)
1313{
19ba03f4
SM
1314 const struct packet_reg * const *lhs
1315 = (const struct packet_reg * const *) lhs_;
1316 const struct packet_reg * const *rhs
1317 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
1318
1319 if ((*lhs)->pnum < (*rhs)->pnum)
1320 return -1;
1321 else if ((*lhs)->pnum == (*rhs)->pnum)
1322 return 0;
1323 else
1324 return 1;
1325}
1326
c21236dc
PA
1327static int
1328map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1329{
74ca34ce 1330 int regnum, num_remote_regs, offset;
74ca34ce 1331 struct packet_reg **remote_regs;
ea9c271d 1332
4a22f64d 1333 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1334 {
c21236dc 1335 struct packet_reg *r = &regs[regnum];
baef701f 1336
4a22f64d 1337 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1338 /* Do not try to fetch zero-sized (placeholder) registers. */
1339 r->pnum = -1;
1340 else
1341 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1342
b323314b 1343 r->regnum = regnum;
74ca34ce
DJ
1344 }
1345
1346 /* Define the g/G packet format as the contents of each register
1347 with a remote protocol number, in order of ascending protocol
1348 number. */
1349
224c3ddb 1350 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1351 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1352 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1353 regnum++)
c21236dc
PA
1354 if (regs[regnum].pnum != -1)
1355 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1356
74ca34ce
DJ
1357 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1358 compare_pnums);
1359
1360 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1361 {
1362 remote_regs[regnum]->in_g_packet = 1;
1363 remote_regs[regnum]->offset = offset;
4a22f64d 1364 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1365 }
1366
c21236dc
PA
1367 return offset;
1368}
1369
1370/* Given the architecture described by GDBARCH, return the remote
1371 protocol register's number and the register's offset in the g/G
1372 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1373 If the target does not have a mapping for REGNUM, return false,
1374 otherwise, return true. */
1375
1376int
1377remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1378 int *pnum, int *poffset)
1379{
c21236dc
PA
1380 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1381
b80406ac 1382 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1383
b80406ac 1384 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1385
1386 *pnum = regs[regnum].pnum;
1387 *poffset = regs[regnum].offset;
1388
c21236dc
PA
1389 return *pnum != -1;
1390}
1391
9d6eea31 1392remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1393{
c21236dc
PA
1394 /* Use the architecture to build a regnum<->pnum table, which will be
1395 1:1 unless a feature set specifies otherwise. */
9d6eea31 1396 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1397
74ca34ce
DJ
1398 /* Record the maximum possible size of the g packet - it may turn out
1399 to be smaller. */
9d6eea31
PA
1400 this->sizeof_g_packet
1401 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1402
0df8b418 1403 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1404 remote stubs have a hardwired buffer size of 400 bytes
1405 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1406 as the maximum packet-size to ensure that the packet and an extra
1407 NUL character can always fit in the buffer. This stops GDB
1408 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1409 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1410 this->remote_packet_size = 400 - 1;
d01949b6 1411
ea9c271d 1412 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1413 this->actual_register_packet_size = 0;
ea9c271d
DJ
1414
1415 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1416 default, adjust the size accordingly. Remember that each byte is
1417 encoded as two characters. 32 is the overhead for the packet
1418 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1419 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1420 little. */
9d6eea31
PA
1421 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1422 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1423}
1424
6b8edb51
PA
1425/* Get a pointer to the current remote target. If not connected to a
1426 remote target, return NULL. */
1427
1428static remote_target *
1429get_current_remote_target ()
1430{
1431 target_ops *proc_target = find_target_at (process_stratum);
1432 return dynamic_cast<remote_target *> (proc_target);
1433}
1434
ea9c271d
DJ
1435/* Return the current allowed size of a remote packet. This is
1436 inferred from the current architecture, and should be used to
1437 limit the length of outgoing packets. */
6b8edb51
PA
1438long
1439remote_target::get_remote_packet_size ()
ea9c271d 1440{
be2a5f71 1441 struct remote_state *rs = get_remote_state ();
9d6eea31 1442 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1443
be2a5f71
DJ
1444 if (rs->explicit_packet_size)
1445 return rs->explicit_packet_size;
1446
ea9c271d 1447 return rsa->remote_packet_size;
d01949b6
AC
1448}
1449
ad10f812 1450static struct packet_reg *
5cd63fda
PA
1451packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1452 long regnum)
ad10f812 1453{
5cd63fda 1454 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1455 return NULL;
1456 else
ad10f812 1457 {
ea9c271d 1458 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1459
b323314b
AC
1460 gdb_assert (r->regnum == regnum);
1461 return r;
ad10f812 1462 }
ad10f812
AC
1463}
1464
1465static struct packet_reg *
5cd63fda
PA
1466packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1467 LONGEST pnum)
ad10f812 1468{
b323314b 1469 int i;
a744cf53 1470
5cd63fda 1471 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1472 {
ea9c271d 1473 struct packet_reg *r = &rsa->regs[i];
a744cf53 1474
b323314b
AC
1475 if (r->pnum == pnum)
1476 return r;
ad10f812
AC
1477 }
1478 return NULL;
d01949b6
AC
1479}
1480
9a7071a8
JB
1481/* Allow the user to specify what sequence to send to the remote
1482 when he requests a program interruption: Although ^C is usually
1483 what remote systems expect (this is the default, here), it is
1484 sometimes preferable to send a break. On other systems such
1485 as the Linux kernel, a break followed by g, which is Magic SysRq g
1486 is required in order to interrupt the execution. */
1487const char interrupt_sequence_control_c[] = "Ctrl-C";
1488const char interrupt_sequence_break[] = "BREAK";
1489const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1490static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1491 {
1492 interrupt_sequence_control_c,
1493 interrupt_sequence_break,
1494 interrupt_sequence_break_g,
1495 NULL
1496 };
1497static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1498
1499static void
1500show_interrupt_sequence (struct ui_file *file, int from_tty,
1501 struct cmd_list_element *c,
1502 const char *value)
1503{
1504 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1505 fprintf_filtered (file,
1506 _("Send the ASCII ETX character (Ctrl-c) "
1507 "to the remote target to interrupt the "
1508 "execution of the program.\n"));
1509 else if (interrupt_sequence_mode == interrupt_sequence_break)
1510 fprintf_filtered (file,
1511 _("send a break signal to the remote target "
1512 "to interrupt the execution of the program.\n"));
1513 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1514 fprintf_filtered (file,
1515 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1516 "the remote target to interrupt the execution "
1517 "of Linux kernel.\n"));
1518 else
1519 internal_error (__FILE__, __LINE__,
1520 _("Invalid value for interrupt_sequence_mode: %s."),
1521 interrupt_sequence_mode);
1522}
6426a772 1523
9a7071a8
JB
1524/* This boolean variable specifies whether interrupt_sequence is sent
1525 to the remote target when gdb connects to it.
1526 This is mostly needed when you debug the Linux kernel: The Linux kernel
1527 expects BREAK g which is Magic SysRq g for connecting gdb. */
1528static int interrupt_on_connect = 0;
c906108c 1529
9a7071a8
JB
1530/* This variable is used to implement the "set/show remotebreak" commands.
1531 Since these commands are now deprecated in favor of "set/show remote
1532 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
1533static int remote_break;
1534
9a7071a8 1535static void
eb4c3f4a 1536set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1537{
1538 if (remote_break)
1539 interrupt_sequence_mode = interrupt_sequence_break;
1540 else
1541 interrupt_sequence_mode = interrupt_sequence_control_c;
1542}
1543
1544static void
1545show_remotebreak (struct ui_file *file, int from_tty,
1546 struct cmd_list_element *c,
1547 const char *value)
1548{
1549}
1550
c906108c
SS
1551/* This variable sets the number of bits in an address that are to be
1552 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1553 leading zeros, the entire address would be sent. This variable
c906108c
SS
1554 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1555 initial implementation of remote.c restricted the address sent in
1556 memory packets to ``host::sizeof long'' bytes - (typically 32
1557 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1558 address was never sent. Since fixing this bug may cause a break in
1559 some remote targets this variable is principly provided to
23860348 1560 facilitate backward compatibility. */
c906108c 1561
883b9c6c 1562static unsigned int remote_address_size;
c906108c 1563
11cf8741 1564\f
11cf8741 1565/* User configurable variables for the number of characters in a
ea9c271d
DJ
1566 memory read/write packet. MIN (rsa->remote_packet_size,
1567 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1568 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1569 (speed up transfers). The variables ``preferred_*'' (the user
1570 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1571 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1572
1573struct memory_packet_config
1574{
a121b7c1 1575 const char *name;
11cf8741
JM
1576 long size;
1577 int fixed_p;
1578};
1579
cc0be08f
PA
1580/* The default max memory-write-packet-size, when the setting is
1581 "fixed". The 16k is historical. (It came from older GDB's using
1582 alloca for buffers and the knowledge (folklore?) that some hosts
1583 don't cope very well with large alloca calls.) */
1584#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
1585
1586/* The minimum remote packet size for memory transfers. Ensures we
1587 can write at least one byte. */
1588#define MIN_MEMORY_PACKET_SIZE 20
1589
cc0be08f
PA
1590/* Get the memory packet size, assuming it is fixed. */
1591
1592static long
1593get_fixed_memory_packet_size (struct memory_packet_config *config)
1594{
1595 gdb_assert (config->fixed_p);
1596
1597 if (config->size <= 0)
1598 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1599 else
1600 return config->size;
1601}
1602
11cf8741
JM
1603/* Compute the current size of a read/write packet. Since this makes
1604 use of ``actual_register_packet_size'' the computation is dynamic. */
1605
6b8edb51
PA
1606long
1607remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 1608{
d01949b6 1609 struct remote_state *rs = get_remote_state ();
9d6eea31 1610 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1611
11cf8741
JM
1612 long what_they_get;
1613 if (config->fixed_p)
cc0be08f 1614 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
1615 else
1616 {
ea9c271d 1617 what_they_get = get_remote_packet_size ();
23860348 1618 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1619 if (config->size > 0
1620 && what_they_get > config->size)
1621 what_they_get = config->size;
be2a5f71
DJ
1622
1623 /* Limit it to the size of the targets ``g'' response unless we have
1624 permission from the stub to use a larger packet size. */
1625 if (rs->explicit_packet_size == 0
1626 && rsa->actual_register_packet_size > 0
1627 && what_they_get > rsa->actual_register_packet_size)
1628 what_they_get = rsa->actual_register_packet_size;
11cf8741 1629 }
a5c0808e
PA
1630 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1631 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1632
1633 /* Make sure there is room in the global buffer for this packet
1634 (including its trailing NUL byte). */
1635 if (rs->buf_size < what_they_get + 1)
1636 {
1637 rs->buf_size = 2 * what_they_get;
224c3ddb 1638 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1639 }
1640
11cf8741
JM
1641 return what_they_get;
1642}
1643
0df8b418 1644/* Update the size of a read/write packet. If they user wants
23860348 1645 something really big then do a sanity check. */
11cf8741
JM
1646
1647static void
ac88e2de 1648set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1649{
1650 int fixed_p = config->fixed_p;
1651 long size = config->size;
a744cf53 1652
11cf8741 1653 if (args == NULL)
8a3fe4f8 1654 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1655 else if (strcmp (args, "hard") == 0
1656 || strcmp (args, "fixed") == 0)
1657 fixed_p = 1;
1658 else if (strcmp (args, "soft") == 0
1659 || strcmp (args, "limit") == 0)
1660 fixed_p = 0;
1661 else
1662 {
1663 char *end;
a744cf53 1664
11cf8741
JM
1665 size = strtoul (args, &end, 0);
1666 if (args == end)
8a3fe4f8 1667 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1668
1669 /* Instead of explicitly capping the size of a packet to or
1670 disallowing it, the user is allowed to set the size to
1671 something arbitrarily large. */
11cf8741 1672 }
a5c0808e 1673
23860348 1674 /* Extra checks? */
11cf8741
JM
1675 if (fixed_p && !config->fixed_p)
1676 {
cc0be08f
PA
1677 /* So that the query shows the correct value. */
1678 long query_size = (size <= 0
1679 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1680 : size);
1681
e2e0b3e5
AC
1682 if (! query (_("The target may not be able to correctly handle a %s\n"
1683 "of %ld bytes. Change the packet size? "),
cc0be08f 1684 config->name, query_size))
8a3fe4f8 1685 error (_("Packet size not changed."));
11cf8741 1686 }
23860348 1687 /* Update the config. */
11cf8741
JM
1688 config->fixed_p = fixed_p;
1689 config->size = size;
1690}
1691
1692static void
1693show_memory_packet_size (struct memory_packet_config *config)
1694{
cc0be08f
PA
1695 if (config->size == 0)
1696 printf_filtered (_("The %s is 0 (default). "), config->name);
1697 else
1698 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1699 if (config->fixed_p)
a3f17187 1700 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
cc0be08f 1701 get_fixed_memory_packet_size (config));
11cf8741 1702 else
cc0be08f 1703 {
6b8edb51 1704 remote_target *remote = get_current_remote_target ();
cc0be08f 1705
6b8edb51 1706 if (remote != NULL)
cc0be08f 1707 printf_filtered (_("Packets are limited to %ld bytes.\n"),
6b8edb51 1708 remote->get_memory_packet_size (config));
cc0be08f
PA
1709 else
1710 puts_filtered ("The actual limit will be further reduced "
1711 "dependent on the target.\n");
1712 }
11cf8741
JM
1713}
1714
1715static struct memory_packet_config memory_write_packet_config =
1716{
1717 "memory-write-packet-size",
1718};
1719
1720static void
ac88e2de 1721set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1722{
1723 set_memory_packet_size (args, &memory_write_packet_config);
1724}
1725
1726static void
ac88e2de 1727show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1728{
1729 show_memory_packet_size (&memory_write_packet_config);
1730}
1731
6b8edb51
PA
1732long
1733remote_target::get_memory_write_packet_size ()
11cf8741
JM
1734{
1735 return get_memory_packet_size (&memory_write_packet_config);
1736}
1737
1738static struct memory_packet_config memory_read_packet_config =
1739{
1740 "memory-read-packet-size",
1741};
1742
1743static void
ac88e2de 1744set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1745{
1746 set_memory_packet_size (args, &memory_read_packet_config);
1747}
1748
1749static void
ac88e2de 1750show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1751{
1752 show_memory_packet_size (&memory_read_packet_config);
1753}
1754
6b8edb51
PA
1755long
1756remote_target::get_memory_read_packet_size ()
11cf8741
JM
1757{
1758 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1759
11cf8741
JM
1760 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1761 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1762 increased beyond this. */
1763 if (size > get_remote_packet_size ())
1764 size = get_remote_packet_size ();
11cf8741
JM
1765 return size;
1766}
1767
11cf8741 1768\f
5a2468f5 1769
5a2468f5
JM
1770struct packet_config
1771 {
bb572ddd
DJ
1772 const char *name;
1773 const char *title;
4082afcc
PA
1774
1775 /* If auto, GDB auto-detects support for this packet or feature,
1776 either through qSupported, or by trying the packet and looking
1777 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1778 packet. If false, the packet is disabled. Configs that don't
1779 have an associated command always have this set to auto. */
7f19b9a2 1780 enum auto_boolean detect;
4082afcc
PA
1781
1782 /* Does the target support this packet? */
5a2468f5
JM
1783 enum packet_support support;
1784 };
1785
4082afcc
PA
1786static enum packet_support packet_config_support (struct packet_config *config);
1787static enum packet_support packet_support (int packet);
5a2468f5
JM
1788
1789static void
fba45db2 1790show_packet_config_cmd (struct packet_config *config)
5a2468f5 1791{
a121b7c1 1792 const char *support = "internal-error";
a744cf53 1793
4082afcc 1794 switch (packet_config_support (config))
5a2468f5
JM
1795 {
1796 case PACKET_ENABLE:
1797 support = "enabled";
1798 break;
1799 case PACKET_DISABLE:
1800 support = "disabled";
1801 break;
1802 case PACKET_SUPPORT_UNKNOWN:
1803 support = "unknown";
1804 break;
1805 }
1806 switch (config->detect)
1807 {
7f19b9a2 1808 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1809 printf_filtered (_("Support for the `%s' packet "
1810 "is auto-detected, currently %s.\n"),
37a105a1 1811 config->name, support);
5a2468f5 1812 break;
7f19b9a2
AC
1813 case AUTO_BOOLEAN_TRUE:
1814 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1815 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1816 config->name, support);
8e248173 1817 break;
5a2468f5
JM
1818 }
1819}
1820
1821static void
bb572ddd
DJ
1822add_packet_config_cmd (struct packet_config *config, const char *name,
1823 const char *title, int legacy)
d471ea57 1824{
5a2468f5
JM
1825 char *set_doc;
1826 char *show_doc;
d471ea57 1827 char *cmd_name;
3ed07be4 1828
5a2468f5
JM
1829 config->name = name;
1830 config->title = title;
b435e160
AC
1831 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1832 name, title);
3e43a32a
MS
1833 show_doc = xstrprintf ("Show current use of remote "
1834 "protocol `%s' (%s) packet",
b435e160 1835 name, title);
d471ea57 1836 /* set/show TITLE-packet {auto,on,off} */
b435e160 1837 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1838 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1839 &config->detect, set_doc,
1840 show_doc, NULL, /* help_doc */
4082afcc 1841 NULL,
bb572ddd
DJ
1842 show_remote_protocol_packet_cmd,
1843 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1844 /* The command code copies the documentation strings. */
1845 xfree (set_doc);
1846 xfree (show_doc);
23860348 1847 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1848 if (legacy)
1849 {
1850 char *legacy_name;
a744cf53 1851
b435e160 1852 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1853 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1854 &remote_set_cmdlist);
d471ea57 1855 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1856 &remote_show_cmdlist);
d471ea57 1857 }
5a2468f5
JM
1858}
1859
d471ea57 1860static enum packet_result
a76d924d 1861packet_check_result (const char *buf)
5a2468f5 1862{
d471ea57 1863 if (buf[0] != '\0')
5a2468f5 1864 {
d471ea57 1865 /* The stub recognized the packet request. Check that the
23860348 1866 operation succeeded. */
a76d924d
DJ
1867 if (buf[0] == 'E'
1868 && isxdigit (buf[1]) && isxdigit (buf[2])
1869 && buf[3] == '\0')
1870 /* "Enn" - definitly an error. */
1871 return PACKET_ERROR;
1872
1873 /* Always treat "E." as an error. This will be used for
1874 more verbose error messages, such as E.memtypes. */
1875 if (buf[0] == 'E' && buf[1] == '.')
1876 return PACKET_ERROR;
1877
1878 /* The packet may or may not be OK. Just assume it is. */
1879 return PACKET_OK;
1880 }
1881 else
1882 /* The stub does not support the packet. */
1883 return PACKET_UNKNOWN;
1884}
1885
1886static enum packet_result
1887packet_ok (const char *buf, struct packet_config *config)
1888{
1889 enum packet_result result;
1890
4082afcc
PA
1891 if (config->detect != AUTO_BOOLEAN_TRUE
1892 && config->support == PACKET_DISABLE)
1893 internal_error (__FILE__, __LINE__,
1894 _("packet_ok: attempt to use a disabled packet"));
1895
a76d924d
DJ
1896 result = packet_check_result (buf);
1897 switch (result)
1898 {
1899 case PACKET_OK:
1900 case PACKET_ERROR:
1901 /* The stub recognized the packet request. */
4082afcc 1902 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1903 {
d471ea57
AC
1904 if (remote_debug)
1905 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1906 "Packet %s (%s) is supported\n",
1907 config->name, config->title);
d471ea57 1908 config->support = PACKET_ENABLE;
d471ea57 1909 }
a76d924d
DJ
1910 break;
1911 case PACKET_UNKNOWN:
23860348 1912 /* The stub does not support the packet. */
4082afcc
PA
1913 if (config->detect == AUTO_BOOLEAN_AUTO
1914 && config->support == PACKET_ENABLE)
d471ea57 1915 {
4082afcc
PA
1916 /* If the stub previously indicated that the packet was
1917 supported then there is a protocol error. */
1918 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1919 config->name, config->title);
1920 }
1921 else if (config->detect == AUTO_BOOLEAN_TRUE)
1922 {
1923 /* The user set it wrong. */
1924 error (_("Enabled packet %s (%s) not recognized by stub"),
1925 config->name, config->title);
d471ea57 1926 }
4082afcc
PA
1927
1928 if (remote_debug)
1929 fprintf_unfiltered (gdb_stdlog,
1930 "Packet %s (%s) is NOT supported\n",
1931 config->name, config->title);
1932 config->support = PACKET_DISABLE;
a76d924d 1933 break;
5a2468f5 1934 }
a76d924d
DJ
1935
1936 return result;
5a2468f5
JM
1937}
1938
444abaca
DJ
1939enum {
1940 PACKET_vCont = 0,
1941 PACKET_X,
1942 PACKET_qSymbol,
1943 PACKET_P,
1944 PACKET_p,
1945 PACKET_Z0,
1946 PACKET_Z1,
1947 PACKET_Z2,
1948 PACKET_Z3,
1949 PACKET_Z4,
15a201c8 1950 PACKET_vFile_setfs,
a6b151f1
DJ
1951 PACKET_vFile_open,
1952 PACKET_vFile_pread,
1953 PACKET_vFile_pwrite,
1954 PACKET_vFile_close,
1955 PACKET_vFile_unlink,
b9e7b9c3 1956 PACKET_vFile_readlink,
0a93529c 1957 PACKET_vFile_fstat,
0876f84a 1958 PACKET_qXfer_auxv,
23181151 1959 PACKET_qXfer_features,
c78fa86a 1960 PACKET_qXfer_exec_file,
cfa9d6d9 1961 PACKET_qXfer_libraries,
2268b414 1962 PACKET_qXfer_libraries_svr4,
fd79ecee 1963 PACKET_qXfer_memory_map,
0e7f50da
UW
1964 PACKET_qXfer_spu_read,
1965 PACKET_qXfer_spu_write,
07e059b5 1966 PACKET_qXfer_osdata,
dc146f7c 1967 PACKET_qXfer_threads,
0fb4aa4b 1968 PACKET_qXfer_statictrace_read,
b3b9301e 1969 PACKET_qXfer_traceframe_info,
169081d0 1970 PACKET_qXfer_uib,
711e434b 1971 PACKET_qGetTIBAddr,
444abaca 1972 PACKET_qGetTLSAddr,
be2a5f71 1973 PACKET_qSupported,
bd3eecc3 1974 PACKET_qTStatus,
89be2091 1975 PACKET_QPassSignals,
82075af2 1976 PACKET_QCatchSyscalls,
9b224c5e 1977 PACKET_QProgramSignals,
bc3b087d 1978 PACKET_QSetWorkingDir,
aefd8b33 1979 PACKET_QStartupWithShell,
0a2dde4a
SDJ
1980 PACKET_QEnvironmentHexEncoded,
1981 PACKET_QEnvironmentReset,
1982 PACKET_QEnvironmentUnset,
936d2992 1983 PACKET_qCRC,
08388c79 1984 PACKET_qSearch_memory,
2d717e4f
DJ
1985 PACKET_vAttach,
1986 PACKET_vRun,
a6f3e723 1987 PACKET_QStartNoAckMode,
82f73884 1988 PACKET_vKill,
4aa995e1
PA
1989 PACKET_qXfer_siginfo_read,
1990 PACKET_qXfer_siginfo_write,
0b16c5cf 1991 PACKET_qAttached,
4082afcc
PA
1992
1993 /* Support for conditional tracepoints. */
782b2b07 1994 PACKET_ConditionalTracepoints,
4082afcc
PA
1995
1996 /* Support for target-side breakpoint conditions. */
3788aec7 1997 PACKET_ConditionalBreakpoints,
4082afcc
PA
1998
1999 /* Support for target-side breakpoint commands. */
d3ce09f5 2000 PACKET_BreakpointCommands,
4082afcc
PA
2001
2002 /* Support for fast tracepoints. */
7a697b8d 2003 PACKET_FastTracepoints,
4082afcc
PA
2004
2005 /* Support for static tracepoints. */
0fb4aa4b 2006 PACKET_StaticTracepoints,
4082afcc
PA
2007
2008 /* Support for installing tracepoints while a trace experiment is
2009 running. */
1e4d1764 2010 PACKET_InstallInTrace,
4082afcc 2011
40ab02ce
MS
2012 PACKET_bc,
2013 PACKET_bs,
409873ef 2014 PACKET_TracepointSource,
d914c394 2015 PACKET_QAllow,
78d85199 2016 PACKET_qXfer_fdpic,
03583c20 2017 PACKET_QDisableRandomization,
d1feda86 2018 PACKET_QAgent,
f6f899bf 2019 PACKET_QTBuffer_size,
9accd112
MM
2020 PACKET_Qbtrace_off,
2021 PACKET_Qbtrace_bts,
b20a6524 2022 PACKET_Qbtrace_pt,
9accd112 2023 PACKET_qXfer_btrace,
4082afcc
PA
2024
2025 /* Support for the QNonStop packet. */
2026 PACKET_QNonStop,
2027
65706a29
PA
2028 /* Support for the QThreadEvents packet. */
2029 PACKET_QThreadEvents,
2030
4082afcc
PA
2031 /* Support for multi-process extensions. */
2032 PACKET_multiprocess_feature,
2033
2034 /* Support for enabling and disabling tracepoints while a trace
2035 experiment is running. */
2036 PACKET_EnableDisableTracepoints_feature,
2037
2038 /* Support for collecting strings using the tracenz bytecode. */
2039 PACKET_tracenz_feature,
2040
2041 /* Support for continuing to run a trace experiment while GDB is
2042 disconnected. */
2043 PACKET_DisconnectedTracing_feature,
2044
2045 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2046 PACKET_augmented_libraries_svr4_read_feature,
2047
f4abbc16
MM
2048 /* Support for the qXfer:btrace-conf:read packet. */
2049 PACKET_qXfer_btrace_conf,
2050
d33501a5
MM
2051 /* Support for the Qbtrace-conf:bts:size packet. */
2052 PACKET_Qbtrace_conf_bts_size,
2053
f7e6eed5
PA
2054 /* Support for swbreak+ feature. */
2055 PACKET_swbreak_feature,
2056
2057 /* Support for hwbreak+ feature. */
2058 PACKET_hwbreak_feature,
2059
89245bc0
DB
2060 /* Support for fork events. */
2061 PACKET_fork_event_feature,
2062
2063 /* Support for vfork events. */
2064 PACKET_vfork_event_feature,
2065
b20a6524
MM
2066 /* Support for the Qbtrace-conf:pt:size packet. */
2067 PACKET_Qbtrace_conf_pt_size,
2068
94585166
DB
2069 /* Support for exec events. */
2070 PACKET_exec_event_feature,
2071
750ce8d1
YQ
2072 /* Support for query supported vCont actions. */
2073 PACKET_vContSupported,
2074
de979965
PA
2075 /* Support remote CTRL-C. */
2076 PACKET_vCtrlC,
2077
f2faf941
PA
2078 /* Support TARGET_WAITKIND_NO_RESUMED. */
2079 PACKET_no_resumed,
2080
444abaca
DJ
2081 PACKET_MAX
2082};
506fb367 2083
444abaca 2084static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 2085
f7e6eed5
PA
2086/* Returns the packet's corresponding "set remote foo-packet" command
2087 state. See struct packet_config for more details. */
2088
2089static enum auto_boolean
2090packet_set_cmd_state (int packet)
2091{
2092 return remote_protocol_packets[packet].detect;
2093}
2094
4082afcc
PA
2095/* Returns whether a given packet or feature is supported. This takes
2096 into account the state of the corresponding "set remote foo-packet"
2097 command, which may be used to bypass auto-detection. */
dc8acb97 2098
4082afcc
PA
2099static enum packet_support
2100packet_config_support (struct packet_config *config)
2101{
2102 switch (config->detect)
444abaca 2103 {
4082afcc
PA
2104 case AUTO_BOOLEAN_TRUE:
2105 return PACKET_ENABLE;
2106 case AUTO_BOOLEAN_FALSE:
2107 return PACKET_DISABLE;
2108 case AUTO_BOOLEAN_AUTO:
2109 return config->support;
2110 default:
2111 gdb_assert_not_reached (_("bad switch"));
444abaca 2112 }
4082afcc
PA
2113}
2114
2115/* Same as packet_config_support, but takes the packet's enum value as
2116 argument. */
2117
2118static enum packet_support
2119packet_support (int packet)
2120{
2121 struct packet_config *config = &remote_protocol_packets[packet];
2122
2123 return packet_config_support (config);
dc8acb97
MS
2124}
2125
5a2468f5 2126static void
444abaca
DJ
2127show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2128 struct cmd_list_element *c,
2129 const char *value)
5a2468f5 2130{
444abaca 2131 struct packet_config *packet;
5a2468f5 2132
444abaca
DJ
2133 for (packet = remote_protocol_packets;
2134 packet < &remote_protocol_packets[PACKET_MAX];
2135 packet++)
2136 {
2137 if (&packet->detect == c->var)
2138 {
2139 show_packet_config_cmd (packet);
2140 return;
2141 }
2142 }
9b20d036 2143 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 2144 c->name);
5a2468f5
JM
2145}
2146
d471ea57
AC
2147/* Should we try one of the 'Z' requests? */
2148
2149enum Z_packet_type
2150{
2151 Z_PACKET_SOFTWARE_BP,
2152 Z_PACKET_HARDWARE_BP,
2153 Z_PACKET_WRITE_WP,
2154 Z_PACKET_READ_WP,
2155 Z_PACKET_ACCESS_WP,
2156 NR_Z_PACKET_TYPES
2157};
96baa820 2158
d471ea57 2159/* For compatibility with older distributions. Provide a ``set remote
23860348 2160 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2161
7f19b9a2 2162static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2163
2164static void
eb4c3f4a 2165set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2166 struct cmd_list_element *c)
96baa820 2167{
d471ea57 2168 int i;
a744cf53 2169
d471ea57 2170 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 2171 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
2172}
2173
2174static void
08546159
AC
2175show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2176 struct cmd_list_element *c,
2177 const char *value)
96baa820 2178{
d471ea57 2179 int i;
a744cf53 2180
d471ea57
AC
2181 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2182 {
444abaca 2183 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 2184 }
96baa820
JM
2185}
2186
4082afcc
PA
2187/* Returns true if the multi-process extensions are in effect. */
2188
2189static int
2190remote_multi_process_p (struct remote_state *rs)
2191{
2192 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2193}
2194
de0d863e
DB
2195/* Returns true if fork events are supported. */
2196
2197static int
2198remote_fork_event_p (struct remote_state *rs)
2199{
2200 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2201}
2202
c269dbdb
DB
2203/* Returns true if vfork events are supported. */
2204
2205static int
2206remote_vfork_event_p (struct remote_state *rs)
2207{
2208 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2209}
2210
d46addbb
DB
2211/* Returns true if exec events are supported. */
2212
2213static int
2214remote_exec_event_p (struct remote_state *rs)
2215{
2216 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2217}
2218
cbb8991c
DB
2219/* Insert fork catchpoint target routine. If fork events are enabled
2220 then return success, nothing more to do. */
2221
f6ac5f3d
PA
2222int
2223remote_target::insert_fork_catchpoint (int pid)
cbb8991c
DB
2224{
2225 struct remote_state *rs = get_remote_state ();
2226
2227 return !remote_fork_event_p (rs);
2228}
2229
2230/* Remove fork catchpoint target routine. Nothing to do, just
2231 return success. */
2232
f6ac5f3d
PA
2233int
2234remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2235{
2236 return 0;
2237}
2238
2239/* Insert vfork catchpoint target routine. If vfork events are enabled
2240 then return success, nothing more to do. */
2241
f6ac5f3d
PA
2242int
2243remote_target::insert_vfork_catchpoint (int pid)
cbb8991c
DB
2244{
2245 struct remote_state *rs = get_remote_state ();
2246
2247 return !remote_vfork_event_p (rs);
2248}
2249
2250/* Remove vfork catchpoint target routine. Nothing to do, just
2251 return success. */
2252
f6ac5f3d
PA
2253int
2254remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2255{
2256 return 0;
2257}
2258
d46addbb
DB
2259/* Insert exec catchpoint target routine. If exec events are
2260 enabled, just return success. */
2261
f6ac5f3d
PA
2262int
2263remote_target::insert_exec_catchpoint (int pid)
d46addbb
DB
2264{
2265 struct remote_state *rs = get_remote_state ();
2266
2267 return !remote_exec_event_p (rs);
2268}
2269
2270/* Remove exec catchpoint target routine. Nothing to do, just
2271 return success. */
2272
f6ac5f3d
PA
2273int
2274remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2275{
2276 return 0;
2277}
2278
c906108c
SS
2279\f
2280
79d7f229
PA
2281static ptid_t magic_null_ptid;
2282static ptid_t not_sent_ptid;
2283static ptid_t any_thread_ptid;
2284
0b16c5cf
PA
2285/* Find out if the stub attached to PID (and hence GDB should offer to
2286 detach instead of killing it when bailing out). */
2287
6b8edb51
PA
2288int
2289remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2290{
2291 struct remote_state *rs = get_remote_state ();
bba74b36 2292 size_t size = get_remote_packet_size ();
0b16c5cf 2293
4082afcc 2294 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2295 return 0;
2296
2297 if (remote_multi_process_p (rs))
bba74b36 2298 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 2299 else
bba74b36 2300 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
2301
2302 putpkt (rs->buf);
2303 getpkt (&rs->buf, &rs->buf_size, 0);
2304
2305 switch (packet_ok (rs->buf,
1554e9be 2306 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
2307 {
2308 case PACKET_OK:
2309 if (strcmp (rs->buf, "1") == 0)
2310 return 1;
2311 break;
2312 case PACKET_ERROR:
2313 warning (_("Remote failure reply: %s"), rs->buf);
2314 break;
2315 case PACKET_UNKNOWN:
2316 break;
2317 }
2318
2319 return 0;
2320}
2321
49c62f2e
PA
2322/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2323 has been invented by GDB, instead of reported by the target. Since
2324 we can be connected to a remote system before before knowing about
2325 any inferior, mark the target with execution when we find the first
2326 inferior. If ATTACHED is 1, then we had just attached to this
2327 inferior. If it is 0, then we just created this inferior. If it
2328 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2329 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2330 attempt to open this inferior's executable as the main executable
2331 if no main executable is open already. */
1941c569 2332
6b8edb51
PA
2333inferior *
2334remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2335 int try_open_exec)
1941c569 2336{
1941c569
PA
2337 struct inferior *inf;
2338
0b16c5cf
PA
2339 /* Check whether this process we're learning about is to be
2340 considered attached, or if is to be considered to have been
2341 spawned by the stub. */
2342 if (attached == -1)
2343 attached = remote_query_attached (pid);
2344
f5656ead 2345 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2346 {
2347 /* If the target shares code across all inferiors, then every
2348 attach adds a new inferior. */
2349 inf = add_inferior (pid);
2350
2351 /* ... and every inferior is bound to the same program space.
2352 However, each inferior may still have its own address
2353 space. */
2354 inf->aspace = maybe_new_address_space ();
2355 inf->pspace = current_program_space;
2356 }
2357 else
2358 {
2359 /* In the traditional debugging scenario, there's a 1-1 match
2360 between program/address spaces. We simply bind the inferior
2361 to the program space's address space. */
2362 inf = current_inferior ();
2363 inferior_appeared (inf, pid);
2364 }
1941c569 2365
0b16c5cf 2366 inf->attach_flag = attached;
49c62f2e 2367 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2368
1b6e6f5c
GB
2369 /* If no main executable is currently open then attempt to
2370 open the file that was executed to create this inferior. */
835205d0 2371 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2372 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2373
1941c569
PA
2374 return inf;
2375}
2376
7aabaf9d 2377static remote_thread_info *get_remote_thread_info (thread_info *thread);
85ad3aaf 2378
1941c569
PA
2379/* Add thread PTID to GDB's thread list. Tag it as executing/running
2380 according to RUNNING. */
2381
6b8edb51
PA
2382void
2383remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
c906108c 2384{
b7ea362b 2385 struct remote_state *rs = get_remote_state ();
85ad3aaf 2386 struct thread_info *thread;
b7ea362b
PA
2387
2388 /* GDB historically didn't pull threads in the initial connection
2389 setup. If the remote target doesn't even have a concept of
2390 threads (e.g., a bare-metal target), even if internally we
2391 consider that a single-threaded target, mentioning a new thread
2392 might be confusing to the user. Be silent then, preserving the
2393 age old behavior. */
2394 if (rs->starting_up)
85ad3aaf 2395 thread = add_thread_silent (ptid);
b7ea362b 2396 else
85ad3aaf 2397 thread = add_thread (ptid);
1941c569 2398
7aabaf9d 2399 get_remote_thread_info (thread)->vcont_resumed = executing;
0d5b594f 2400 set_executing (ptid, executing);
1941c569
PA
2401 set_running (ptid, running);
2402}
2403
2404/* Come here when we learn about a thread id from the remote target.
2405 It may be the first time we hear about such thread, so take the
2406 opportunity to add it to GDB's thread list. In case this is the
2407 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2408 GDB's inferior list as well. EXECUTING indicates whether the
2409 thread is (internally) executing or stopped. */
1941c569 2410
6b8edb51
PA
2411void
2412remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 2413{
0d5b594f
PA
2414 /* In non-stop mode, we assume new found threads are (externally)
2415 running until proven otherwise with a stop reply. In all-stop,
2416 we can only get here if all threads are stopped. */
2417 int running = target_is_non_stop_p () ? 1 : 0;
2418
c906108c
SS
2419 /* If this is a new thread, add it to GDB's thread list.
2420 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
2421
2422 if (in_thread_list (currthread) && is_exited (currthread))
2423 {
2424 /* We're seeing an event on a thread id we knew had exited.
2425 This has to be a new thread reusing the old id. Add it. */
0d5b594f 2426 remote_add_thread (currthread, running, executing);
82f73884
PA
2427 return;
2428 }
2429
79d7f229 2430 if (!in_thread_list (currthread))
c0a2216e 2431 {
1941c569 2432 struct inferior *inf = NULL;
bad34192 2433 int pid = ptid_get_pid (currthread);
1941c569 2434
bad34192
PA
2435 if (ptid_is_pid (inferior_ptid)
2436 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
2437 {
2438 /* inferior_ptid has no thread member yet. This can happen
2439 with the vAttach -> remote_wait,"TAAthread:" path if the
2440 stub doesn't support qC. This is the first stop reported
2441 after an attach, so this is the main thread. Update the
2442 ptid in the thread list. */
bad34192
PA
2443 if (in_thread_list (pid_to_ptid (pid)))
2444 thread_change_ptid (inferior_ptid, currthread);
2445 else
2446 {
0d5b594f 2447 remote_add_thread (currthread, running, executing);
bad34192
PA
2448 inferior_ptid = currthread;
2449 }
dc146f7c 2450 return;
c0a2216e 2451 }
82f73884
PA
2452
2453 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
2454 {
2455 /* inferior_ptid is not set yet. This can happen with the
2456 vRun -> remote_wait,"TAAthread:" path if the stub
2457 doesn't support qC. This is the first stop reported
2458 after an attach, so this is the main thread. Update the
2459 ptid in the thread list. */
dc146f7c 2460 thread_change_ptid (inferior_ptid, currthread);
82f73884 2461 return;
c0a2216e 2462 }
82f73884 2463
29c87f7f
PA
2464 /* When connecting to a target remote, or to a target
2465 extended-remote which already was debugging an inferior, we
2466 may not know about it yet. Add it before adding its child
2467 thread, so notifications are emitted in a sensible order. */
2468 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
2469 {
2470 struct remote_state *rs = get_remote_state ();
2471 int fake_pid_p = !remote_multi_process_p (rs);
2472
2473 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 2474 ptid_get_pid (currthread), -1, 1);
49c62f2e 2475 }
29c87f7f 2476
82f73884 2477 /* This is really a new thread. Add it. */
0d5b594f 2478 remote_add_thread (currthread, running, executing);
1941c569
PA
2479
2480 /* If we found a new inferior, let the common code do whatever
2481 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2482 breakpoints), unless we're just setting up an all-stop
2483 connection. */
1941c569 2484 if (inf != NULL)
b7ea362b
PA
2485 {
2486 struct remote_state *rs = get_remote_state ();
2487
6efcd9a8 2488 if (!rs->starting_up)
0d5b594f 2489 notice_new_inferior (currthread, executing, 0);
b7ea362b 2490 }
c0a2216e 2491 }
c906108c
SS
2492}
2493
85ad3aaf 2494/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2495
7aabaf9d
SM
2496static remote_thread_info *
2497get_remote_thread_info (thread_info *thread)
dc146f7c 2498{
85ad3aaf 2499 gdb_assert (thread != NULL);
dc146f7c 2500
85ad3aaf 2501 if (thread->priv == NULL)
7aabaf9d 2502 thread->priv.reset (new remote_thread_info);
dc146f7c 2503
7aabaf9d 2504 return static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2505}
2506
2507/* Return PTID's private thread data, creating it if necessary. */
2508
7aabaf9d
SM
2509static remote_thread_info *
2510get_remote_thread_info (ptid_t ptid)
85ad3aaf
PA
2511{
2512 struct thread_info *info = find_thread_ptid (ptid);
2513
7aabaf9d 2514 return get_remote_thread_info (info);
dc146f7c
VP
2515}
2516
74531fed
PA
2517/* Call this function as a result of
2518 1) A halt indication (T packet) containing a thread id
2519 2) A direct query of currthread
0df8b418 2520 3) Successful execution of set thread */
74531fed
PA
2521
2522static void
47f8a51d 2523record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2524{
47f8a51d 2525 rs->general_thread = currthread;
74531fed
PA
2526}
2527
89be2091
DJ
2528/* If 'QPassSignals' is supported, tell the remote stub what signals
2529 it can simply pass through to the inferior without reporting. */
2530
f6ac5f3d
PA
2531void
2532remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
89be2091 2533{
4082afcc 2534 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2535 {
2536 char *pass_packet, *p;
89be2091 2537 int count = 0, i;
747dc59d 2538 struct remote_state *rs = get_remote_state ();
89be2091
DJ
2539
2540 gdb_assert (numsigs < 256);
2541 for (i = 0; i < numsigs; i++)
2542 {
2455069d 2543 if (pass_signals[i])
89be2091
DJ
2544 count++;
2545 }
224c3ddb 2546 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2547 strcpy (pass_packet, "QPassSignals:");
2548 p = pass_packet + strlen (pass_packet);
2549 for (i = 0; i < numsigs; i++)
2550 {
2455069d 2551 if (pass_signals[i])
89be2091
DJ
2552 {
2553 if (i >= 16)
2554 *p++ = tohex (i >> 4);
2555 *p++ = tohex (i & 15);
2556 if (count)
2557 *p++ = ';';
2558 else
2559 break;
2560 count--;
2561 }
2562 }
2563 *p = 0;
747dc59d 2564 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2565 {
89be2091
DJ
2566 putpkt (pass_packet);
2567 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2568 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2569 if (rs->last_pass_packet)
2570 xfree (rs->last_pass_packet);
2571 rs->last_pass_packet = pass_packet;
89be2091
DJ
2572 }
2573 else
2574 xfree (pass_packet);
2575 }
2576}
2577
82075af2
JS
2578/* If 'QCatchSyscalls' is supported, tell the remote stub
2579 to report syscalls to GDB. */
2580
f6ac5f3d
PA
2581int
2582remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2583 gdb::array_view<const int> syscall_counts)
82075af2 2584{
b80406ac 2585 const char *catch_packet;
82075af2
JS
2586 enum packet_result result;
2587 int n_sysno = 0;
2588
2589 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2590 {
2591 /* Not supported. */
2592 return 1;
2593 }
2594
649a140c 2595 if (needed && any_count == 0)
82075af2 2596 {
649a140c
PA
2597 /* Count how many syscalls are to be caught. */
2598 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2599 {
649a140c 2600 if (syscall_counts[i] != 0)
82075af2
JS
2601 n_sysno++;
2602 }
2603 }
2604
2605 if (remote_debug)
2606 {
2607 fprintf_unfiltered (gdb_stdlog,
2608 "remote_set_syscall_catchpoint "
2609 "pid %d needed %d any_count %d n_sysno %d\n",
2610 pid, needed, any_count, n_sysno);
2611 }
2612
1b81856f 2613 std::string built_packet;
82075af2
JS
2614 if (needed)
2615 {
2616 /* Prepare a packet with the sysno list, assuming max 8+1
2617 characters for a sysno. If the resulting packet size is too
2618 big, fallback on the non-selective packet. */
2619 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2620 built_packet.reserve (maxpktsz);
2621 built_packet = "QCatchSyscalls:1";
649a140c 2622 if (any_count == 0)
82075af2 2623 {
649a140c
PA
2624 /* Add in each syscall to be caught. */
2625 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2626 {
649a140c
PA
2627 if (syscall_counts[i] != 0)
2628 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2629 }
2630 }
1b81856f 2631 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2632 {
2633 /* catch_packet too big. Fallback to less efficient
2634 non selective mode, with GDB doing the filtering. */
b80406ac 2635 catch_packet = "QCatchSyscalls:1";
82075af2 2636 }
b80406ac 2637 else
1b81856f 2638 catch_packet = built_packet.c_str ();
82075af2
JS
2639 }
2640 else
b80406ac 2641 catch_packet = "QCatchSyscalls:0";
82075af2 2642
b80406ac 2643 struct remote_state *rs = get_remote_state ();
82075af2 2644
b80406ac
TT
2645 putpkt (catch_packet);
2646 getpkt (&rs->buf, &rs->buf_size, 0);
2647 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2648 if (result == PACKET_OK)
2649 return 0;
2650 else
2651 return -1;
82075af2
JS
2652}
2653
9b224c5e
PA
2654/* If 'QProgramSignals' is supported, tell the remote stub what
2655 signals it should pass through to the inferior when detaching. */
2656
f6ac5f3d
PA
2657void
2658remote_target::program_signals (int numsigs, unsigned char *signals)
9b224c5e 2659{
4082afcc 2660 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2661 {
2662 char *packet, *p;
2663 int count = 0, i;
5e4a05c4 2664 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2665
2666 gdb_assert (numsigs < 256);
2667 for (i = 0; i < numsigs; i++)
2668 {
2669 if (signals[i])
2670 count++;
2671 }
224c3ddb 2672 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2673 strcpy (packet, "QProgramSignals:");
2674 p = packet + strlen (packet);
2675 for (i = 0; i < numsigs; i++)
2676 {
2677 if (signal_pass_state (i))
2678 {
2679 if (i >= 16)
2680 *p++ = tohex (i >> 4);
2681 *p++ = tohex (i & 15);
2682 if (count)
2683 *p++ = ';';
2684 else
2685 break;
2686 count--;
2687 }
2688 }
2689 *p = 0;
5e4a05c4
TT
2690 if (!rs->last_program_signals_packet
2691 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2692 {
9b224c5e
PA
2693 putpkt (packet);
2694 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2695 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2696 xfree (rs->last_program_signals_packet);
2697 rs->last_program_signals_packet = packet;
9b224c5e
PA
2698 }
2699 else
2700 xfree (packet);
2701 }
2702}
2703
79d7f229
PA
2704/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2705 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2706 thread. If GEN is set, set the general thread, if not, then set
2707 the step/continue thread. */
6b8edb51
PA
2708void
2709remote_target::set_thread (ptid_t ptid, int gen)
c906108c 2710{
d01949b6 2711 struct remote_state *rs = get_remote_state ();
47f8a51d 2712 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2713 char *buf = rs->buf;
79d7f229 2714 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2715
79d7f229 2716 if (ptid_equal (state, ptid))
c906108c
SS
2717 return;
2718
79d7f229
PA
2719 *buf++ = 'H';
2720 *buf++ = gen ? 'g' : 'c';
2721 if (ptid_equal (ptid, magic_null_ptid))
2722 xsnprintf (buf, endbuf - buf, "0");
2723 else if (ptid_equal (ptid, any_thread_ptid))
2724 xsnprintf (buf, endbuf - buf, "0");
2725 else if (ptid_equal (ptid, minus_one_ptid))
2726 xsnprintf (buf, endbuf - buf, "-1");
2727 else
82f73884 2728 write_ptid (buf, endbuf, ptid);
79d7f229 2729 putpkt (rs->buf);
6d820c5c 2730 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2731 if (gen)
47f8a51d 2732 rs->general_thread = ptid;
c906108c 2733 else
47f8a51d 2734 rs->continue_thread = ptid;
c906108c 2735}
79d7f229 2736
6b8edb51
PA
2737void
2738remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
2739{
2740 set_thread (ptid, 1);
2741}
2742
6b8edb51
PA
2743void
2744remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
2745{
2746 set_thread (ptid, 0);
2747}
2748
3c9c4b83
PA
2749/* Change the remote current process. Which thread within the process
2750 ends up selected isn't important, as long as it is the same process
2751 as what INFERIOR_PTID points to.
2752
2753 This comes from that fact that there is no explicit notion of
2754 "selected process" in the protocol. The selected process for
2755 general operations is the process the selected general thread
2756 belongs to. */
2757
6b8edb51
PA
2758void
2759remote_target::set_general_process ()
3c9c4b83
PA
2760{
2761 struct remote_state *rs = get_remote_state ();
2762
2763 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2764 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2765 return;
2766
2767 /* We only need to change the remote current thread if it's pointing
2768 at some other process. */
47f8a51d 2769 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2770 set_general_thread (inferior_ptid);
2771}
2772
c906108c 2773\f
7d1a114c
PA
2774/* Return nonzero if this is the main thread that we made up ourselves
2775 to model non-threaded targets as single-threaded. */
c906108c
SS
2776
2777static int
f6ac5f3d 2778remote_thread_always_alive (ptid_t ptid)
c906108c 2779{
c0a2216e
PA
2780 if (ptid_equal (ptid, magic_null_ptid))
2781 /* The main thread is always alive. */
2782 return 1;
2783
ba348170 2784 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2785 /* The main thread is always alive. This can happen after a
2786 vAttach, if the remote side doesn't support
2787 multi-threading. */
2788 return 1;
2789
7d1a114c
PA
2790 return 0;
2791}
2792
2793/* Return nonzero if the thread PTID is still alive on the remote
2794 system. */
2795
57810aa7 2796bool
f6ac5f3d 2797remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
2798{
2799 struct remote_state *rs = get_remote_state ();
2800 char *p, *endp;
2801
2802 /* Check if this is a thread that we made up ourselves to model
2803 non-threaded targets as single-threaded. */
f6ac5f3d 2804 if (remote_thread_always_alive (ptid))
7d1a114c
PA
2805 return 1;
2806
82f73884
PA
2807 p = rs->buf;
2808 endp = rs->buf + get_remote_packet_size ();
2809
2810 *p++ = 'T';
2811 write_ptid (p, endp, ptid);
2812
2e9f7625 2813 putpkt (rs->buf);
6d820c5c 2814 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2815 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2816}
2817
79efa585
SM
2818/* Return a pointer to a thread name if we know it and NULL otherwise.
2819 The thread_info object owns the memory for the name. */
2820
f6ac5f3d
PA
2821const char *
2822remote_target::thread_name (struct thread_info *info)
79efa585
SM
2823{
2824 if (info->priv != NULL)
a9334058
SM
2825 {
2826 const std::string &name = get_remote_thread_info (info)->name;
2827 return !name.empty () ? name.c_str () : NULL;
2828 }
79efa585
SM
2829
2830 return NULL;
2831}
2832
c906108c
SS
2833/* About these extended threadlist and threadinfo packets. They are
2834 variable length packets but, the fields within them are often fixed
2835 length. They are redundent enough to send over UDP as is the
2836 remote protocol in general. There is a matching unit test module
2837 in libstub. */
2838
23860348 2839/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2840 libstub protocol encoding, and remote.c. It is not particularly
23860348 2841 changable. */
cce74817
JM
2842
2843/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2844 Plan to fix this. */
cce74817 2845
23860348 2846typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2847
9d1f7ab2 2848/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2849 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2850
2851struct gdb_ext_thread_info
c5aa993b 2852 {
23860348 2853 threadref threadid; /* External form of thread reference. */
2bc416ba 2854 int active; /* Has state interesting to GDB?
23860348 2855 regs, stack. */
2bc416ba 2856 char display[256]; /* Brief state display, name,
cedea757 2857 blocked/suspended. */
23860348 2858 char shortname[32]; /* To be used to name threads. */
2bc416ba 2859 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2860 whatever. */
c5aa993b 2861 };
cce74817
JM
2862
2863/* The volume of remote transfers can be limited by submitting
2864 a mask containing bits specifying the desired information.
2865 Use a union of these values as the 'selection' parameter to
0df8b418 2866 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2867
2868#define TAG_THREADID 1
2869#define TAG_EXISTS 2
2870#define TAG_DISPLAY 4
2871#define TAG_THREADNAME 8
c5aa993b 2872#define TAG_MOREDISPLAY 16
cce74817 2873
23860348 2874#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2875
a14ed312 2876static char *unpack_nibble (char *buf, int *val);
cce74817 2877
a14ed312 2878static char *unpack_byte (char *buf, int *value);
cce74817 2879
a14ed312 2880static char *pack_int (char *buf, int value);
cce74817 2881
a14ed312 2882static char *unpack_int (char *buf, int *value);
cce74817 2883
a14ed312 2884static char *unpack_string (char *src, char *dest, int length);
cce74817 2885
23860348 2886static char *pack_threadid (char *pkt, threadref *id);
cce74817 2887
23860348 2888static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2889
23860348 2890void int_to_threadref (threadref *id, int value);
cce74817 2891
23860348 2892static int threadref_to_int (threadref *ref);
cce74817 2893
23860348 2894static void copy_threadref (threadref *dest, threadref *src);
cce74817 2895
23860348 2896static int threadmatch (threadref *dest, threadref *src);
cce74817 2897
2bc416ba 2898static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2899 threadref *id);
cce74817 2900
a14ed312
KB
2901static char *pack_threadlist_request (char *pkt, int startflag,
2902 int threadcount,
23860348 2903 threadref *nextthread);
cce74817 2904
23860348 2905static int remote_newthread_step (threadref *ref, void *context);
cce74817 2906
82f73884
PA
2907
2908/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2909 buffer we're allowed to write to. Returns
2910 BUF+CHARACTERS_WRITTEN. */
2911
6b8edb51
PA
2912char *
2913remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
2914{
2915 int pid, tid;
2916 struct remote_state *rs = get_remote_state ();
2917
2918 if (remote_multi_process_p (rs))
2919 {
2920 pid = ptid_get_pid (ptid);
2921 if (pid < 0)
2922 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2923 else
2924 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2925 }
ba348170 2926 tid = ptid_get_lwp (ptid);
82f73884
PA
2927 if (tid < 0)
2928 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2929 else
2930 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2931
2932 return buf;
2933}
2934
256642e8
PA
2935/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2936 last parsed char. Returns null_ptid if no thread id is found, and
2937 throws an error if the thread id has an invalid format. */
82f73884
PA
2938
2939static ptid_t
256642e8 2940read_ptid (const char *buf, const char **obuf)
82f73884 2941{
256642e8
PA
2942 const char *p = buf;
2943 const char *pp;
82f73884 2944 ULONGEST pid = 0, tid = 0;
82f73884
PA
2945
2946 if (*p == 'p')
2947 {
2948 /* Multi-process ptid. */
2949 pp = unpack_varlen_hex (p + 1, &pid);
2950 if (*pp != '.')
b37520b6 2951 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2952
2953 p = pp;
2954 pp = unpack_varlen_hex (p + 1, &tid);
2955 if (obuf)
2956 *obuf = pp;
ba348170 2957 return ptid_build (pid, tid, 0);
82f73884
PA
2958 }
2959
2960 /* No multi-process. Just a tid. */
2961 pp = unpack_varlen_hex (p, &tid);
2962
c9f35b34
KB
2963 /* Return null_ptid when no thread id is found. */
2964 if (p == pp)
2965 {
2966 if (obuf)
2967 *obuf = pp;
2968 return null_ptid;
2969 }
2970
82f73884 2971 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2972 what's in inferior_ptid, unless it's null at this point. If so,
2973 then since there's no way to know the pid of the reported
2974 threads, use the magic number. */
2975 if (ptid_equal (inferior_ptid, null_ptid))
2976 pid = ptid_get_pid (magic_null_ptid);
2977 else
2978 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2979
2980 if (obuf)
2981 *obuf = pp;
ba348170 2982 return ptid_build (pid, tid, 0);
82f73884
PA
2983}
2984
c906108c 2985static int
fba45db2 2986stubhex (int ch)
c906108c
SS
2987{
2988 if (ch >= 'a' && ch <= 'f')
2989 return ch - 'a' + 10;
2990 if (ch >= '0' && ch <= '9')
2991 return ch - '0';
2992 if (ch >= 'A' && ch <= 'F')
2993 return ch - 'A' + 10;
2994 return -1;
2995}
2996
2997static int
fba45db2 2998stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2999{
3000 int nibble;
3001 int retval = 0;
3002
3003 while (fieldlength)
3004 {
3005 nibble = stubhex (*buff++);
3006 retval |= nibble;
3007 fieldlength--;
3008 if (fieldlength)
3009 retval = retval << 4;
3010 }
3011 return retval;
3012}
3013
c906108c 3014static char *
fba45db2 3015unpack_nibble (char *buf, int *val)
c906108c 3016{
b7589f7d 3017 *val = fromhex (*buf++);
c906108c
SS
3018 return buf;
3019}
3020
c906108c 3021static char *
fba45db2 3022unpack_byte (char *buf, int *value)
c906108c
SS
3023{
3024 *value = stub_unpack_int (buf, 2);
3025 return buf + 2;
3026}
3027
3028static char *
fba45db2 3029pack_int (char *buf, int value)
c906108c
SS
3030{
3031 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3032 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3033 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3034 buf = pack_hex_byte (buf, (value & 0xff));
3035 return buf;
3036}
3037
3038static char *
fba45db2 3039unpack_int (char *buf, int *value)
c906108c
SS
3040{
3041 *value = stub_unpack_int (buf, 8);
3042 return buf + 8;
3043}
3044
23860348 3045#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3046static char *pack_string (char *pkt, char *string);
c906108c
SS
3047
3048static char *
fba45db2 3049pack_string (char *pkt, char *string)
c906108c
SS
3050{
3051 char ch;
3052 int len;
3053
3054 len = strlen (string);
3055 if (len > 200)
23860348 3056 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3057 pkt = pack_hex_byte (pkt, len);
3058 while (len-- > 0)
3059 {
3060 ch = *string++;
3061 if ((ch == '\0') || (ch == '#'))
23860348 3062 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3063 *pkt++ = ch;
3064 }
3065 return pkt;
3066}
3067#endif /* 0 (unused) */
3068
3069static char *
fba45db2 3070unpack_string (char *src, char *dest, int length)
c906108c
SS
3071{
3072 while (length--)
3073 *dest++ = *src++;
3074 *dest = '\0';
3075 return src;
3076}
3077
3078static char *
fba45db2 3079pack_threadid (char *pkt, threadref *id)
c906108c
SS
3080{
3081 char *limit;
3082 unsigned char *altid;
3083
3084 altid = (unsigned char *) id;
3085 limit = pkt + BUF_THREAD_ID_SIZE;
3086 while (pkt < limit)
3087 pkt = pack_hex_byte (pkt, *altid++);
3088 return pkt;
3089}
3090
3091
3092static char *
fba45db2 3093unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
3094{
3095 char *altref;
3096 char *limit = inbuf + BUF_THREAD_ID_SIZE;
3097 int x, y;
3098
3099 altref = (char *) id;
3100
3101 while (inbuf < limit)
3102 {
3103 x = stubhex (*inbuf++);
3104 y = stubhex (*inbuf++);
3105 *altref++ = (x << 4) | y;
3106 }
3107 return inbuf;
3108}
3109
3110/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3111 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3112 to use 64bit thread references internally. This is an adapter
3113 function. */
3114
3115void
fba45db2 3116int_to_threadref (threadref *id, int value)
c906108c
SS
3117{
3118 unsigned char *scan;
3119
3120 scan = (unsigned char *) id;
3121 {
3122 int i = 4;
3123 while (i--)
3124 *scan++ = 0;
3125 }
3126 *scan++ = (value >> 24) & 0xff;
3127 *scan++ = (value >> 16) & 0xff;
3128 *scan++ = (value >> 8) & 0xff;
3129 *scan++ = (value & 0xff);
3130}
3131
3132static int
fba45db2 3133threadref_to_int (threadref *ref)
c906108c
SS
3134{
3135 int i, value = 0;
3136 unsigned char *scan;
3137
cfd77fa1 3138 scan = *ref;
c906108c
SS
3139 scan += 4;
3140 i = 4;
3141 while (i-- > 0)
3142 value = (value << 8) | ((*scan++) & 0xff);
3143 return value;
3144}
3145
3146static void
fba45db2 3147copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3148{
3149 int i;
3150 unsigned char *csrc, *cdest;
3151
3152 csrc = (unsigned char *) src;
3153 cdest = (unsigned char *) dest;
3154 i = 8;
3155 while (i--)
3156 *cdest++ = *csrc++;
3157}
3158
3159static int
fba45db2 3160threadmatch (threadref *dest, threadref *src)
c906108c 3161{
23860348 3162 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3163#if 0
3164 unsigned char *srcp, *destp;
3165 int i, result;
3166 srcp = (char *) src;
3167 destp = (char *) dest;
3168
3169 result = 1;
3170 while (i-- > 0)
3171 result &= (*srcp++ == *destp++) ? 1 : 0;
3172 return result;
3173#endif
3174 return 1;
3175}
3176
3177/*
c5aa993b
JM
3178 threadid:1, # always request threadid
3179 context_exists:2,
3180 display:4,
3181 unique_name:8,
3182 more_display:16
3183 */
c906108c
SS
3184
3185/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3186
3187static char *
fba45db2 3188pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3189{
23860348
MS
3190 *pkt++ = 'q'; /* Info Query */
3191 *pkt++ = 'P'; /* process or thread info */
3192 pkt = pack_int (pkt, mode); /* mode */
c906108c 3193 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3194 *pkt = '\0'; /* terminate */
c906108c
SS
3195 return pkt;
3196}
3197
23860348 3198/* These values tag the fields in a thread info response packet. */
c906108c 3199/* Tagging the fields allows us to request specific fields and to
23860348 3200 add more fields as time goes by. */
c906108c 3201
23860348 3202#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3203#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3204 fetch registers and its stack? */
c5aa993b 3205#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3206#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3207#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3208 the process. */
c906108c 3209
6b8edb51
PA
3210int
3211remote_target::remote_unpack_thread_info_response (char *pkt,
3212 threadref *expectedref,
3213 gdb_ext_thread_info *info)
c906108c 3214{
d01949b6 3215 struct remote_state *rs = get_remote_state ();
c906108c 3216 int mask, length;
cfd77fa1 3217 int tag;
c906108c 3218 threadref ref;
6d820c5c 3219 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
3220 int retval = 1;
3221
23860348 3222 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3223 info->active = 0;
3224 info->display[0] = '\0';
3225 info->shortname[0] = '\0';
3226 info->more_display[0] = '\0';
3227
23860348
MS
3228 /* Assume the characters indicating the packet type have been
3229 stripped. */
c906108c
SS
3230 pkt = unpack_int (pkt, &mask); /* arg mask */
3231 pkt = unpack_threadid (pkt, &ref);
3232
3233 if (mask == 0)
8a3fe4f8 3234 warning (_("Incomplete response to threadinfo request."));
c906108c 3235 if (!threadmatch (&ref, expectedref))
23860348 3236 { /* This is an answer to a different request. */
8a3fe4f8 3237 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3238 return 0;
3239 }
3240 copy_threadref (&info->threadid, &ref);
3241
23860348 3242 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 3243
23860348
MS
3244 /* Packets are terminated with nulls. */
3245 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3246 {
3247 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3248 pkt = unpack_byte (pkt, &length); /* length */
3249 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3250 {
8a3fe4f8 3251 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3252 retval = 0;
3253 break;
3254 }
3255 if (tag == TAG_THREADID)
3256 {
3257 if (length != 16)
3258 {
8a3fe4f8 3259 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3260 retval = 0;
3261 break;
3262 }
3263 pkt = unpack_threadid (pkt, &ref);
3264 mask = mask & ~TAG_THREADID;
3265 continue;
3266 }
3267 if (tag == TAG_EXISTS)
3268 {
3269 info->active = stub_unpack_int (pkt, length);
3270 pkt += length;
3271 mask = mask & ~(TAG_EXISTS);
3272 if (length > 8)
3273 {
8a3fe4f8 3274 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3275 retval = 0;
3276 break;
3277 }
3278 continue;
3279 }
3280 if (tag == TAG_THREADNAME)
3281 {
3282 pkt = unpack_string (pkt, &info->shortname[0], length);
3283 mask = mask & ~TAG_THREADNAME;
3284 continue;
3285 }
3286 if (tag == TAG_DISPLAY)
3287 {
3288 pkt = unpack_string (pkt, &info->display[0], length);
3289 mask = mask & ~TAG_DISPLAY;
3290 continue;
3291 }
3292 if (tag == TAG_MOREDISPLAY)
3293 {
3294 pkt = unpack_string (pkt, &info->more_display[0], length);
3295 mask = mask & ~TAG_MOREDISPLAY;
3296 continue;
3297 }
8a3fe4f8 3298 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3299 break; /* Not a tag we know about. */
c906108c
SS
3300 }
3301 return retval;
3302}
3303
6b8edb51
PA
3304int
3305remote_target::remote_get_threadinfo (threadref *threadid,
3306 int fieldset,
3307 gdb_ext_thread_info *info)
c906108c 3308{
d01949b6 3309 struct remote_state *rs = get_remote_state ();
c906108c 3310 int result;
c906108c 3311
2e9f7625
DJ
3312 pack_threadinfo_request (rs->buf, fieldset, threadid);
3313 putpkt (rs->buf);
6d820c5c 3314 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
3315
3316 if (rs->buf[0] == '\0')
3317 return 0;
3318
2e9f7625 3319 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 3320 threadid, info);
c906108c
SS
3321 return result;
3322}
3323
c906108c
SS
3324/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3325
3326static char *
fba45db2
KB
3327pack_threadlist_request (char *pkt, int startflag, int threadcount,
3328 threadref *nextthread)
c906108c
SS
3329{
3330 *pkt++ = 'q'; /* info query packet */
3331 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3332 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3333 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3334 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3335 *pkt = '\0';
3336 return pkt;
3337}
3338
3339/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3340
6b8edb51
PA
3341int
3342remote_target::parse_threadlist_response (char *pkt, int result_limit,
3343 threadref *original_echo,
3344 threadref *resultlist,
3345 int *doneflag)
c906108c 3346{
d01949b6 3347 struct remote_state *rs = get_remote_state ();
c906108c
SS
3348 char *limit;
3349 int count, resultcount, done;
3350
3351 resultcount = 0;
3352 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 3353 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 3354 /* done parse past here */
c906108c
SS
3355 pkt = unpack_byte (pkt, &count); /* count field */
3356 pkt = unpack_nibble (pkt, &done);
3357 /* The first threadid is the argument threadid. */
3358 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3359 while ((count-- > 0) && (pkt < limit))
3360 {
3361 pkt = unpack_threadid (pkt, resultlist++);
3362 if (resultcount++ >= result_limit)
3363 break;
3364 }
3365 if (doneflag)
3366 *doneflag = done;
3367 return resultcount;
3368}
3369
6dc54d91
PA
3370/* Fetch the next batch of threads from the remote. Returns -1 if the
3371 qL packet is not supported, 0 on error and 1 on success. */
3372
6b8edb51
PA
3373int
3374remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3375 int result_limit, int *done, int *result_count,
3376 threadref *threadlist)
c906108c 3377{
d01949b6 3378 struct remote_state *rs = get_remote_state ();
c906108c
SS
3379 int result = 1;
3380
23860348 3381 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
3382 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3383 >= get_remote_packet_size ())
ea9c271d 3384 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3385
6d820c5c
DJ
3386 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3387 putpkt (rs->buf);
3388 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 3389 if (*rs->buf == '\0')
6dc54d91
PA
3390 {
3391 /* Packet not supported. */
3392 return -1;
3393 }
3394
3395 *result_count =
3396 parse_threadlist_response (rs->buf + 2, result_limit,
3397 &rs->echo_nextthread, threadlist, done);
c906108c 3398
0d031856 3399 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3400 {
23860348
MS
3401 /* FIXME: This is a good reason to drop the packet. */
3402 /* Possably, there is a duplicate response. */
c906108c
SS
3403 /* Possabilities :
3404 retransmit immediatly - race conditions
3405 retransmit after timeout - yes
3406 exit
3407 wait for packet, then exit
3408 */
8a3fe4f8 3409 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3410 return 0; /* I choose simply exiting. */
c906108c
SS
3411 }
3412 if (*result_count <= 0)
3413 {
3414 if (*done != 1)
3415 {
8a3fe4f8 3416 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3417 result = 0;
3418 }
3419 return result; /* break; */
3420 }
3421 if (*result_count > result_limit)
3422 {
3423 *result_count = 0;
8a3fe4f8 3424 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3425 return 0;
3426 }
3427 return result;
3428}
3429
6dc54d91
PA
3430/* Fetch the list of remote threads, with the qL packet, and call
3431 STEPFUNCTION for each thread found. Stops iterating and returns 1
3432 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3433 STEPFUNCTION returns false. If the packet is not supported,
3434 returns -1. */
c906108c 3435
6b8edb51
PA
3436int
3437remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3438 void *context, int looplimit)
c906108c 3439{
0d031856 3440 struct remote_state *rs = get_remote_state ();
c906108c
SS
3441 int done, i, result_count;
3442 int startflag = 1;
3443 int result = 1;
3444 int loopcount = 0;
c906108c
SS
3445
3446 done = 0;
3447 while (!done)
3448 {
3449 if (loopcount++ > looplimit)
3450 {
3451 result = 0;
8a3fe4f8 3452 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3453 break;
3454 }
6dc54d91
PA
3455 result = remote_get_threadlist (startflag, &rs->nextthread,
3456 MAXTHREADLISTRESULTS,
3457 &done, &result_count,
3458 rs->resultthreadlist);
3459 if (result <= 0)
3460 break;
23860348 3461 /* Clear for later iterations. */
c906108c
SS
3462 startflag = 0;
3463 /* Setup to resume next batch of thread references, set nextthread. */
3464 if (result_count >= 1)
0d031856
TT
3465 copy_threadref (&rs->nextthread,
3466 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3467 i = 0;
3468 while (result_count--)
6dc54d91
PA
3469 {
3470 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3471 {
3472 result = 0;
3473 break;
3474 }
3475 }
c906108c
SS
3476 }
3477 return result;
3478}
3479
6dc54d91
PA
3480/* A thread found on the remote target. */
3481
21fe1c75 3482struct thread_item
6dc54d91 3483{
21fe1c75
SM
3484 explicit thread_item (ptid_t ptid_)
3485 : ptid (ptid_)
3486 {}
3487
3488 thread_item (thread_item &&other) = default;
3489 thread_item &operator= (thread_item &&other) = default;
3490
3491 DISABLE_COPY_AND_ASSIGN (thread_item);
3492
6dc54d91
PA
3493 /* The thread's PTID. */
3494 ptid_t ptid;
3495
21fe1c75
SM
3496 /* The thread's extra info. */
3497 std::string extra;
6dc54d91 3498
21fe1c75
SM
3499 /* The thread's name. */
3500 std::string name;
79efa585 3501
6dc54d91 3502 /* The core the thread was running on. -1 if not known. */
21fe1c75 3503 int core = -1;
f6327dcb
KB
3504
3505 /* The thread handle associated with the thread. */
21fe1c75 3506 gdb::byte_vector thread_handle;
21fe1c75 3507};
6dc54d91
PA
3508
3509/* Context passed around to the various methods listing remote
3510 threads. As new threads are found, they're added to the ITEMS
3511 vector. */
3512
3513struct threads_listing_context
3514{
21fe1c75
SM
3515 /* Return true if this object contains an entry for a thread with ptid
3516 PTID. */
6dc54d91 3517
21fe1c75
SM
3518 bool contains_thread (ptid_t ptid) const
3519 {
3520 auto match_ptid = [&] (const thread_item &item)
3521 {
3522 return item.ptid == ptid;
3523 };
80134cf5 3524
21fe1c75
SM
3525 auto it = std::find_if (this->items.begin (),
3526 this->items.end (),
3527 match_ptid);
80134cf5 3528
21fe1c75
SM
3529 return it != this->items.end ();
3530 }
80134cf5 3531
21fe1c75 3532 /* Remove the thread with ptid PTID. */
80134cf5 3533
21fe1c75
SM
3534 void remove_thread (ptid_t ptid)
3535 {
3536 auto match_ptid = [&] (const thread_item &item)
3537 {
3538 return item.ptid == ptid;
3539 };
cbb8991c 3540
21fe1c75
SM
3541 auto it = std::remove_if (this->items.begin (),
3542 this->items.end (),
3543 match_ptid);
cbb8991c 3544
21fe1c75
SM
3545 if (it != this->items.end ())
3546 this->items.erase (it);
3547 }
3548
3549 /* The threads found on the remote target. */
3550 std::vector<thread_item> items;
3551};
cbb8991c 3552
c906108c 3553static int
6dc54d91 3554remote_newthread_step (threadref *ref, void *data)
c906108c 3555{
19ba03f4
SM
3556 struct threads_listing_context *context
3557 = (struct threads_listing_context *) data;
21fe1c75
SM
3558 int pid = inferior_ptid.pid ();
3559 int lwp = threadref_to_int (ref);
3560 ptid_t ptid (pid, lwp);
6dc54d91 3561
21fe1c75 3562 context->items.emplace_back (ptid);
6dc54d91 3563
c906108c
SS
3564 return 1; /* continue iterator */
3565}
3566
3567#define CRAZY_MAX_THREADS 1000
3568
6b8edb51
PA
3569ptid_t
3570remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3571{
d01949b6 3572 struct remote_state *rs = get_remote_state ();
c906108c
SS
3573
3574 putpkt ("qC");
6d820c5c 3575 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3576 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3577 {
256642e8 3578 const char *obuf;
c9f35b34
KB
3579 ptid_t result;
3580
3581 result = read_ptid (&rs->buf[2], &obuf);
3582 if (*obuf != '\0' && remote_debug)
3583 fprintf_unfiltered (gdb_stdlog,
3584 "warning: garbage in qC reply\n");
3585
3586 return result;
3587 }
c906108c
SS
3588 else
3589 return oldpid;
3590}
3591
6dc54d91 3592/* List remote threads using the deprecated qL packet. */
cce74817 3593
6b8edb51
PA
3594int
3595remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3596{
6dc54d91
PA
3597 if (remote_threadlist_iterator (remote_newthread_step, context,
3598 CRAZY_MAX_THREADS) >= 0)
3599 return 1;
3600
3601 return 0;
c906108c
SS
3602}
3603
dc146f7c
VP
3604#if defined(HAVE_LIBEXPAT)
3605
dc146f7c
VP
3606static void
3607start_thread (struct gdb_xml_parser *parser,
3608 const struct gdb_xml_element *element,
4d0fdd9b
SM
3609 void *user_data,
3610 std::vector<gdb_xml_value> &attributes)
dc146f7c 3611{
19ba03f4
SM
3612 struct threads_listing_context *data
3613 = (struct threads_listing_context *) user_data;
3d2c1d41 3614 struct gdb_xml_value *attr;
dc146f7c 3615
4d0fdd9b 3616 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3617 ptid_t ptid = read_ptid (id, NULL);
3618
3619 data->items.emplace_back (ptid);
3620 thread_item &item = data->items.back ();
dc146f7c 3621
3d2c1d41
PA
3622 attr = xml_find_attribute (attributes, "core");
3623 if (attr != NULL)
4d0fdd9b 3624 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3625
79efa585 3626 attr = xml_find_attribute (attributes, "name");
21fe1c75 3627 if (attr != NULL)
4d0fdd9b 3628 item.name = (const char *) attr->value.get ();
79efa585 3629
f6327dcb
KB
3630 attr = xml_find_attribute (attributes, "handle");
3631 if (attr != NULL)
4d0fdd9b 3632 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3633}
3634
3635static void
3636end_thread (struct gdb_xml_parser *parser,
3637 const struct gdb_xml_element *element,
3638 void *user_data, const char *body_text)
3639{
19ba03f4
SM
3640 struct threads_listing_context *data
3641 = (struct threads_listing_context *) user_data;
dc146f7c 3642
21fe1c75
SM
3643 if (body_text != NULL && *body_text != '\0')
3644 data->items.back ().extra = body_text;
dc146f7c
VP
3645}
3646
3647const struct gdb_xml_attribute thread_attributes[] = {
3648 { "id", GDB_XML_AF_NONE, NULL, NULL },
3649 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3650 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3651 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3652 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3653};
3654
3655const struct gdb_xml_element thread_children[] = {
3656 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3657};
3658
3659const struct gdb_xml_element threads_children[] = {
3660 { "thread", thread_attributes, thread_children,
3661 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3662 start_thread, end_thread },
3663 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3664};
3665
3666const struct gdb_xml_element threads_elements[] = {
3667 { "threads", NULL, threads_children,
3668 GDB_XML_EF_NONE, NULL, NULL },
3669 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3670};
3671
3672#endif
3673
6dc54d91 3674/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3675
6b8edb51
PA
3676int
3677remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 3678{
dc146f7c 3679#if defined(HAVE_LIBEXPAT)
4082afcc 3680 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3681 {
9018be22 3682 gdb::optional<gdb::char_vector> xml
6b8edb51 3683 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3684
9018be22 3685 if (xml && (*xml)[0] != '\0')
dc146f7c 3686 {
6dc54d91 3687 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3688 threads_elements, xml->data (), context);
dc146f7c
VP
3689 }
3690
6dc54d91 3691 return 1;
dc146f7c
VP
3692 }
3693#endif
3694
6dc54d91
PA
3695 return 0;
3696}
3697
3698/* List remote threads using qfThreadInfo/qsThreadInfo. */
3699
6b8edb51
PA
3700int
3701remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
3702{
3703 struct remote_state *rs = get_remote_state ();
3704
b80fafe3 3705 if (rs->use_threadinfo_query)
9d1f7ab2 3706 {
256642e8 3707 const char *bufp;
6dc54d91 3708
9d1f7ab2 3709 putpkt ("qfThreadInfo");
6d820c5c 3710 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3711 bufp = rs->buf;
9d1f7ab2 3712 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3713 {
9d1f7ab2
MS
3714 while (*bufp++ == 'm') /* reply contains one or more TID */
3715 {
3716 do
3717 {
21fe1c75
SM
3718 ptid_t ptid = read_ptid (bufp, &bufp);
3719 context->items.emplace_back (ptid);
9d1f7ab2
MS
3720 }
3721 while (*bufp++ == ','); /* comma-separated list */
3722 putpkt ("qsThreadInfo");
6d820c5c 3723 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3724 bufp = rs->buf;
9d1f7ab2 3725 }
6dc54d91
PA
3726 return 1;
3727 }
3728 else
3729 {
3730 /* Packet not recognized. */
3731 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3732 }
3733 }
3734
6dc54d91
PA
3735 return 0;
3736}
3737
e8032dde 3738/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3739 targets. */
3740
f6ac5f3d
PA
3741void
3742remote_target::update_thread_list ()
6dc54d91 3743{
6dc54d91 3744 struct threads_listing_context context;
ab970af1 3745 int got_list = 0;
e8032dde 3746
6dc54d91
PA
3747 /* We have a few different mechanisms to fetch the thread list. Try
3748 them all, starting with the most preferred one first, falling
3749 back to older methods. */
6b8edb51
PA
3750 if (remote_get_threads_with_qxfer (&context)
3751 || remote_get_threads_with_qthreadinfo (&context)
3752 || remote_get_threads_with_ql (&context))
6dc54d91 3753 {
ab970af1
PA
3754 struct thread_info *tp, *tmp;
3755
3756 got_list = 1;
3757
21fe1c75 3758 if (context.items.empty ()
f6ac5f3d 3759 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
3760 {
3761 /* Some targets don't really support threads, but still
3762 reply an (empty) thread list in response to the thread
3763 listing packets, instead of replying "packet not
3764 supported". Exit early so we don't delete the main
3765 thread. */
7d1a114c
PA
3766 return;
3767 }
3768
ab970af1
PA
3769 /* CONTEXT now holds the current thread list on the remote
3770 target end. Delete GDB-side threads no longer found on the
3771 target. */
8a06aea7 3772 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3773 {
21fe1c75 3774 if (!context.contains_thread (tp->ptid))
ab970af1
PA
3775 {
3776 /* Not found. */
3777 delete_thread (tp->ptid);
3778 }
cbb8991c
DB
3779 }
3780
3781 /* Remove any unreported fork child threads from CONTEXT so
3782 that we don't interfere with follow fork, which is where
3783 creation of such threads is handled. */
3784 remove_new_fork_children (&context);
74531fed 3785
ab970af1 3786 /* And now add threads we don't know about yet to our list. */
21fe1c75 3787 for (thread_item &item : context.items)
6dc54d91 3788 {
21fe1c75 3789 if (item.ptid != null_ptid)
6dc54d91 3790 {
6dc54d91 3791 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3792 executing until proven otherwise with a stop reply.
3793 In all-stop, we can only get here if all threads are
6dc54d91 3794 stopped. */
0d5b594f 3795 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3796
21fe1c75 3797 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 3798
7aabaf9d 3799 remote_thread_info *info = get_remote_thread_info (item.ptid);
21fe1c75 3800 info->core = item.core;
7aabaf9d
SM
3801 info->extra = std::move (item.extra);
3802 info->name = std::move (item.name);
3803 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
3804 }
3805 }
3806 }
3807
ab970af1
PA
3808 if (!got_list)
3809 {
3810 /* If no thread listing method is supported, then query whether
3811 each known thread is alive, one by one, with the T packet.
3812 If the target doesn't support threads at all, then this is a
3813 no-op. See remote_thread_alive. */
3814 prune_threads ();
3815 }
9d1f7ab2
MS
3816}
3817
802188a7 3818/*
9d1f7ab2
MS
3819 * Collect a descriptive string about the given thread.
3820 * The target may say anything it wants to about the thread
3821 * (typically info about its blocked / runnable state, name, etc.).
3822 * This string will appear in the info threads display.
802188a7 3823 *
9d1f7ab2
MS
3824 * Optional: targets are not required to implement this function.
3825 */
3826
f6ac5f3d
PA
3827const char *
3828remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 3829{
d01949b6 3830 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3831 int result;
3832 int set;
3833 threadref id;
3834 struct gdb_ext_thread_info threadinfo;
23860348 3835 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3836 int n = 0; /* position in display_buf */
3837
5d93a237 3838 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3839 internal_error (__FILE__, __LINE__,
e2e0b3e5 3840 _("remote_threads_extra_info"));
9d1f7ab2 3841
60e569b9 3842 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3843 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3844 /* This is the main thread which was added by GDB. The remote
3845 server doesn't know about it. */
3846 return NULL;
3847
4082afcc 3848 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3849 {
3850 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3851
7aabaf9d 3852 if (info != NULL && info->priv != NULL)
a9334058
SM
3853 {
3854 const std::string &extra = get_remote_thread_info (info)->extra;
3855 return !extra.empty () ? extra.c_str () : NULL;
3856 }
dc146f7c
VP
3857 else
3858 return NULL;
3859 }
3860
b80fafe3 3861 if (rs->use_threadextra_query)
9d1f7ab2 3862 {
82f73884
PA
3863 char *b = rs->buf;
3864 char *endb = rs->buf + get_remote_packet_size ();
3865
3866 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3867 b += strlen (b);
3868 write_ptid (b, endb, tp->ptid);
3869
2e9f7625 3870 putpkt (rs->buf);
6d820c5c 3871 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3872 if (rs->buf[0] != 0)
9d1f7ab2 3873 {
325fac50 3874 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
2e9f7625 3875 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3876 display_buf [result] = '\0';
9d1f7ab2
MS
3877 return display_buf;
3878 }
0f71a2f6 3879 }
9d1f7ab2
MS
3880
3881 /* If the above query fails, fall back to the old method. */
b80fafe3 3882 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3883 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3884 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3885 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3886 if (remote_get_threadinfo (&id, set, &threadinfo))
3887 if (threadinfo.active)
0f71a2f6 3888 {
9d1f7ab2 3889 if (*threadinfo.shortname)
2bc416ba 3890 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3891 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3892 if (*threadinfo.display)
2bc416ba 3893 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3894 " State: %s,", threadinfo.display);
9d1f7ab2 3895 if (*threadinfo.more_display)
2bc416ba 3896 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3897 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3898
3899 if (n > 0)
c5aa993b 3900 {
23860348 3901 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3902 if (',' == display_buf[n-1])
3903 display_buf[n-1] = ' ';
3904 return display_buf;
c5aa993b 3905 }
0f71a2f6 3906 }
9d1f7ab2 3907 return NULL;
0f71a2f6 3908}
c906108c 3909\f
c5aa993b 3910
f6ac5f3d
PA
3911bool
3912remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3913 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
3914{
3915 struct remote_state *rs = get_remote_state ();
3916 char *p = rs->buf;
3917
bba74b36 3918 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3919 p += strlen (p);
3920 p += hexnumstr (p, addr);
3921 putpkt (rs->buf);
3922 getpkt (&rs->buf, &rs->buf_size, 0);
3923 p = rs->buf;
3924
3925 if (*p == 'E')
3926 error (_("Remote failure reply: %s"), p);
3927
3928 if (*p++ == 'm')
3929 {
256642e8 3930 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 3931 return true;
0fb4aa4b
PA
3932 }
3933
5d9310c4 3934 return false;
0fb4aa4b
PA
3935}
3936
f6ac5f3d
PA
3937std::vector<static_tracepoint_marker>
3938remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
3939{
3940 struct remote_state *rs = get_remote_state ();
5d9310c4 3941 std::vector<static_tracepoint_marker> markers;
256642e8 3942 const char *p;
5d9310c4 3943 static_tracepoint_marker marker;
0fb4aa4b
PA
3944
3945 /* Ask for a first packet of static tracepoint marker
3946 definition. */
3947 putpkt ("qTfSTM");
3948 getpkt (&rs->buf, &rs->buf_size, 0);
3949 p = rs->buf;
3950 if (*p == 'E')
3951 error (_("Remote failure reply: %s"), p);
3952
0fb4aa4b
PA
3953 while (*p++ == 'm')
3954 {
0fb4aa4b
PA
3955 do
3956 {
5d9310c4 3957 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 3958
5d9310c4
SM
3959 if (strid == NULL || marker.str_id == strid)
3960 markers.push_back (std::move (marker));
0fb4aa4b
PA
3961 }
3962 while (*p++ == ','); /* comma-separated list */
3963 /* Ask for another packet of static tracepoint definition. */
3964 putpkt ("qTsSTM");
3965 getpkt (&rs->buf, &rs->buf_size, 0);
3966 p = rs->buf;
3967 }
3968
0fb4aa4b
PA
3969 return markers;
3970}
3971
3972\f
10760264
JB
3973/* Implement the to_get_ada_task_ptid function for the remote targets. */
3974
f6ac5f3d
PA
3975ptid_t
3976remote_target::get_ada_task_ptid (long lwp, long thread)
10760264 3977{
ba348170 3978 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3979}
3980\f
3981
24b06219 3982/* Restart the remote side; this is an extended protocol operation. */
c906108c 3983
6b8edb51
PA
3984void
3985remote_target::extended_remote_restart ()
c906108c 3986{
d01949b6 3987 struct remote_state *rs = get_remote_state ();
c906108c
SS
3988
3989 /* Send the restart command; for reasons I don't understand the
3990 remote side really expects a number after the "R". */
ea9c271d 3991 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3992 putpkt (rs->buf);
c906108c 3993
ad9a8f3f 3994 remote_fileio_reset ();
c906108c
SS
3995}
3996\f
3997/* Clean up connection to a remote debugger. */
3998
f6ac5f3d
PA
3999void
4000remote_target::close ()
c906108c 4001{
048094ac 4002 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4003 terminal_ours ();
ce5ce7ed 4004
ce5ce7ed 4005 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
4006 of all the inferiors and their threads we were controlling.
4007 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4008 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 4009 inferior_ptid = null_ptid;
f67fd822 4010 discard_all_inferiors ();
ce5ce7ed 4011
6b8edb51
PA
4012 trace_reset_local_state ();
4013
4014 delete this;
4015}
4016
4017remote_target::~remote_target ()
4018{
4019 struct remote_state *rs = get_remote_state ();
4020
4021 /* Check for NULL because we may get here with a partially
4022 constructed target/connection. */
4023 if (rs->remote_desc == nullptr)
4024 return;
4025
4026 serial_close (rs->remote_desc);
4027
4028 /* We are destroying the remote target, so we should discard
f48ff2a7 4029 everything of this target. */
6b8edb51 4030 discard_pending_stop_replies_in_queue ();
74531fed 4031
6b8edb51
PA
4032 if (rs->remote_async_inferior_event_token)
4033 delete_async_event_handler (&rs->remote_async_inferior_event_token);
722247f1 4034
5965e028 4035 remote_notif_state_xfree (rs->notif_state);
c906108c
SS
4036}
4037
23860348 4038/* Query the remote side for the text, data and bss offsets. */
c906108c 4039
6b8edb51
PA
4040void
4041remote_target::get_offsets ()
c906108c 4042{
d01949b6 4043 struct remote_state *rs = get_remote_state ();
2e9f7625 4044 char *buf;
085dd6e6 4045 char *ptr;
31d99776
DJ
4046 int lose, num_segments = 0, do_sections, do_segments;
4047 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 4048 struct section_offsets *offs;
31d99776
DJ
4049 struct symfile_segment_data *data;
4050
4051 if (symfile_objfile == NULL)
4052 return;
c906108c
SS
4053
4054 putpkt ("qOffsets");
6d820c5c 4055 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4056 buf = rs->buf;
c906108c
SS
4057
4058 if (buf[0] == '\000')
4059 return; /* Return silently. Stub doesn't support
23860348 4060 this command. */
c906108c
SS
4061 if (buf[0] == 'E')
4062 {
8a3fe4f8 4063 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4064 return;
4065 }
4066
4067 /* Pick up each field in turn. This used to be done with scanf, but
4068 scanf will make trouble if CORE_ADDR size doesn't match
4069 conversion directives correctly. The following code will work
4070 with any size of CORE_ADDR. */
4071 text_addr = data_addr = bss_addr = 0;
4072 ptr = buf;
4073 lose = 0;
4074
61012eef 4075 if (startswith (ptr, "Text="))
c906108c
SS
4076 {
4077 ptr += 5;
4078 /* Don't use strtol, could lose on big values. */
4079 while (*ptr && *ptr != ';')
4080 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4081
61012eef 4082 if (startswith (ptr, ";Data="))
31d99776
DJ
4083 {
4084 ptr += 6;
4085 while (*ptr && *ptr != ';')
4086 data_addr = (data_addr << 4) + fromhex (*ptr++);
4087 }
4088 else
4089 lose = 1;
4090
61012eef 4091 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4092 {
4093 ptr += 5;
4094 while (*ptr && *ptr != ';')
4095 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4096
31d99776
DJ
4097 if (bss_addr != data_addr)
4098 warning (_("Target reported unsupported offsets: %s"), buf);
4099 }
4100 else
4101 lose = 1;
4102 }
61012eef 4103 else if (startswith (ptr, "TextSeg="))
c906108c 4104 {
31d99776
DJ
4105 ptr += 8;
4106 /* Don't use strtol, could lose on big values. */
c906108c 4107 while (*ptr && *ptr != ';')
31d99776
DJ
4108 text_addr = (text_addr << 4) + fromhex (*ptr++);
4109 num_segments = 1;
4110
61012eef 4111 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4112 {
4113 ptr += 9;
4114 while (*ptr && *ptr != ';')
4115 data_addr = (data_addr << 4) + fromhex (*ptr++);
4116 num_segments++;
4117 }
c906108c
SS
4118 }
4119 else
4120 lose = 1;
4121
4122 if (lose)
8a3fe4f8 4123 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4124 else if (*ptr != '\0')
4125 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4126
802188a7 4127 offs = ((struct section_offsets *)
a39a16c4 4128 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 4129 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 4130 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 4131
31d99776
DJ
4132 data = get_symfile_segment_data (symfile_objfile->obfd);
4133 do_segments = (data != NULL);
4134 do_sections = num_segments == 0;
c906108c 4135
28c32713 4136 if (num_segments > 0)
31d99776 4137 {
31d99776
DJ
4138 segments[0] = text_addr;
4139 segments[1] = data_addr;
4140 }
28c32713
JB
4141 /* If we have two segments, we can still try to relocate everything
4142 by assuming that the .text and .data offsets apply to the whole
4143 text and data segments. Convert the offsets given in the packet
4144 to base addresses for symfile_map_offsets_to_segments. */
4145 else if (data && data->num_segments == 2)
4146 {
4147 segments[0] = data->segment_bases[0] + text_addr;
4148 segments[1] = data->segment_bases[1] + data_addr;
4149 num_segments = 2;
4150 }
8d385431
DJ
4151 /* If the object file has only one segment, assume that it is text
4152 rather than data; main programs with no writable data are rare,
4153 but programs with no code are useless. Of course the code might
4154 have ended up in the data segment... to detect that we would need
4155 the permissions here. */
4156 else if (data && data->num_segments == 1)
4157 {
4158 segments[0] = data->segment_bases[0] + text_addr;
4159 num_segments = 1;
4160 }
28c32713
JB
4161 /* There's no way to relocate by segment. */
4162 else
4163 do_segments = 0;
31d99776
DJ
4164
4165 if (do_segments)
4166 {
4167 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4168 offs, num_segments, segments);
4169
4170 if (ret == 0 && !do_sections)
3e43a32a
MS
4171 error (_("Can not handle qOffsets TextSeg "
4172 "response with this symbol file"));
31d99776
DJ
4173
4174 if (ret > 0)
4175 do_sections = 0;
4176 }
c906108c 4177
9ef895d6
DJ
4178 if (data)
4179 free_symfile_segment_data (data);
31d99776
DJ
4180
4181 if (do_sections)
4182 {
4183 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4184
3e43a32a
MS
4185 /* This is a temporary kludge to force data and bss to use the
4186 same offsets because that's what nlmconv does now. The real
4187 solution requires changes to the stub and remote.c that I
4188 don't have time to do right now. */
31d99776
DJ
4189
4190 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4191 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4192 }
c906108c
SS
4193
4194 objfile_relocate (symfile_objfile, offs);
4195}
4196
9a7071a8 4197/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4198
4199void
4200remote_target::send_interrupt_sequence ()
9a7071a8 4201{
5d93a237
TT
4202 struct remote_state *rs = get_remote_state ();
4203
9a7071a8 4204 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4205 remote_serial_write ("\x03", 1);
9a7071a8 4206 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4207 serial_send_break (rs->remote_desc);
9a7071a8
JB
4208 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4209 {
5d93a237 4210 serial_send_break (rs->remote_desc);
c33e31fd 4211 remote_serial_write ("g", 1);
9a7071a8
JB
4212 }
4213 else
4214 internal_error (__FILE__, __LINE__,
4215 _("Invalid value for interrupt_sequence_mode: %s."),
4216 interrupt_sequence_mode);
4217}
4218
3405876a
PA
4219
4220/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4221 and extract the PTID. Returns NULL_PTID if not found. */
4222
4223static ptid_t
4224stop_reply_extract_thread (char *stop_reply)
4225{
4226 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4227 {
256642e8 4228 const char *p;
3405876a
PA
4229
4230 /* Txx r:val ; r:val (...) */
4231 p = &stop_reply[3];
4232
4233 /* Look for "register" named "thread". */
4234 while (*p != '\0')
4235 {
256642e8 4236 const char *p1;
3405876a
PA
4237
4238 p1 = strchr (p, ':');
4239 if (p1 == NULL)
4240 return null_ptid;
4241
4242 if (strncmp (p, "thread", p1 - p) == 0)
4243 return read_ptid (++p1, &p);
4244
4245 p1 = strchr (p, ';');
4246 if (p1 == NULL)
4247 return null_ptid;
4248 p1++;
4249
4250 p = p1;
4251 }
4252 }
4253
4254 return null_ptid;
4255}
4256
b7ea362b
PA
4257/* Determine the remote side's current thread. If we have a stop
4258 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4259 "thread" register we can extract the current thread from. If not,
4260 ask the remote which is the current thread with qC. The former
4261 method avoids a roundtrip. */
4262
6b8edb51
PA
4263ptid_t
4264remote_target::get_current_thread (char *wait_status)
b7ea362b 4265{
6a49a997 4266 ptid_t ptid = null_ptid;
b7ea362b
PA
4267
4268 /* Note we don't use remote_parse_stop_reply as that makes use of
4269 the target architecture, which we haven't yet fully determined at
4270 this point. */
4271 if (wait_status != NULL)
4272 ptid = stop_reply_extract_thread (wait_status);
4273 if (ptid_equal (ptid, null_ptid))
4274 ptid = remote_current_thread (inferior_ptid);
4275
4276 return ptid;
4277}
4278
49c62f2e
PA
4279/* Query the remote target for which is the current thread/process,
4280 add it to our tables, and update INFERIOR_PTID. The caller is
4281 responsible for setting the state such that the remote end is ready
3405876a
PA
4282 to return the current thread.
4283
4284 This function is called after handling the '?' or 'vRun' packets,
4285 whose response is a stop reply from which we can also try
4286 extracting the thread. If the target doesn't support the explicit
4287 qC query, we infer the current thread from that stop reply, passed
4288 in in WAIT_STATUS, which may be NULL. */
49c62f2e 4289
6b8edb51
PA
4290void
4291remote_target::add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
4292{
4293 struct remote_state *rs = get_remote_state ();
4294 int fake_pid_p = 0;
49c62f2e
PA
4295
4296 inferior_ptid = null_ptid;
4297
b7ea362b 4298 /* Now, if we have thread information, update inferior_ptid. */
87215ad1 4299 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4300
87215ad1 4301 if (curr_ptid != null_ptid)
49c62f2e
PA
4302 {
4303 if (!remote_multi_process_p (rs))
4304 fake_pid_p = 1;
49c62f2e
PA
4305 }
4306 else
4307 {
4308 /* Without this, some commands which require an active target
4309 (such as kill) won't work. This variable serves (at least)
4310 double duty as both the pid of the target process (if it has
4311 such), and as a flag indicating that a target is active. */
87215ad1 4312 curr_ptid = magic_null_ptid;
49c62f2e
PA
4313 fake_pid_p = 1;
4314 }
4315
87215ad1 4316 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
49c62f2e 4317
87215ad1
SDJ
4318 /* Add the main thread and switch to it. Don't try reading
4319 registers yet, since we haven't fetched the target description
4320 yet. */
4321 thread_info *tp = add_thread_silent (curr_ptid);
4322 switch_to_thread_no_regs (tp);
49c62f2e
PA
4323}
4324
6efcd9a8
PA
4325/* Print info about a thread that was found already stopped on
4326 connection. */
4327
4328static void
4329print_one_stopped_thread (struct thread_info *thread)
4330{
4331 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4332
4333 switch_to_thread (thread->ptid);
4334 stop_pc = get_frame_pc (get_current_frame ());
4335 set_current_sal_from_frame (get_current_frame ());
4336
4337 thread->suspend.waitstatus_pending_p = 0;
4338
4339 if (ws->kind == TARGET_WAITKIND_STOPPED)
4340 {
4341 enum gdb_signal sig = ws->value.sig;
4342
4343 if (signal_print_state (sig))
76727919 4344 gdb::observers::signal_received.notify (sig);
6efcd9a8 4345 }
76727919 4346 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4347}
4348
221e1a37
PA
4349/* Process all initial stop replies the remote side sent in response
4350 to the ? packet. These indicate threads that were already stopped
4351 on initial connection. We mark these threads as stopped and print
4352 their current frame before giving the user the prompt. */
4353
6b8edb51
PA
4354void
4355remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4356{
4357 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4358 struct inferior *inf;
4359 struct thread_info *thread;
4360 struct thread_info *selected = NULL;
4361 struct thread_info *lowest_stopped = NULL;
4362 struct thread_info *first = NULL;
221e1a37
PA
4363
4364 /* Consume the initial pending events. */
4365 while (pending_stop_replies-- > 0)
4366 {
4367 ptid_t waiton_ptid = minus_one_ptid;
4368 ptid_t event_ptid;
4369 struct target_waitstatus ws;
4370 int ignore_event = 0;
6efcd9a8 4371 struct thread_info *thread;
221e1a37
PA
4372
4373 memset (&ws, 0, sizeof (ws));
4374 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4375 if (remote_debug)
4376 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4377
4378 switch (ws.kind)
4379 {
4380 case TARGET_WAITKIND_IGNORE:
4381 case TARGET_WAITKIND_NO_RESUMED:
4382 case TARGET_WAITKIND_SIGNALLED:
4383 case TARGET_WAITKIND_EXITED:
4384 /* We shouldn't see these, but if we do, just ignore. */
4385 if (remote_debug)
4386 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4387 ignore_event = 1;
4388 break;
4389
4390 case TARGET_WAITKIND_EXECD:
4391 xfree (ws.value.execd_pathname);
4392 break;
4393 default:
4394 break;
4395 }
4396
4397 if (ignore_event)
4398 continue;
4399
6efcd9a8 4400 thread = find_thread_ptid (event_ptid);
221e1a37
PA
4401
4402 if (ws.kind == TARGET_WAITKIND_STOPPED)
4403 {
4404 enum gdb_signal sig = ws.value.sig;
4405
4406 /* Stubs traditionally report SIGTRAP as initial signal,
4407 instead of signal 0. Suppress it. */
4408 if (sig == GDB_SIGNAL_TRAP)
4409 sig = GDB_SIGNAL_0;
6efcd9a8
PA
4410 thread->suspend.stop_signal = sig;
4411 ws.value.sig = sig;
4412 }
221e1a37 4413
6efcd9a8
PA
4414 thread->suspend.waitstatus = ws;
4415
4416 if (ws.kind != TARGET_WAITKIND_STOPPED
4417 || ws.value.sig != GDB_SIGNAL_0)
4418 thread->suspend.waitstatus_pending_p = 1;
4419
4420 set_executing (event_ptid, 0);
4421 set_running (event_ptid, 0);
7aabaf9d 4422 get_remote_thread_info (thread)->vcont_resumed = 0;
6efcd9a8
PA
4423 }
4424
4425 /* "Notice" the new inferiors before anything related to
4426 registers/memory. */
4427 ALL_INFERIORS (inf)
4428 {
4429 if (inf->pid == 0)
4430 continue;
4431
4432 inf->needs_setup = 1;
4433
4434 if (non_stop)
4435 {
4436 thread = any_live_thread_of_process (inf->pid);
4437 notice_new_inferior (thread->ptid,
4438 thread->state == THREAD_RUNNING,
4439 from_tty);
4440 }
4441 }
4442
4443 /* If all-stop on top of non-stop, pause all threads. Note this
4444 records the threads' stop pc, so must be done after "noticing"
4445 the inferiors. */
4446 if (!non_stop)
4447 {
4448 stop_all_threads ();
4449
4450 /* If all threads of an inferior were already stopped, we
4451 haven't setup the inferior yet. */
4452 ALL_INFERIORS (inf)
4453 {
4454 if (inf->pid == 0)
4455 continue;
221e1a37 4456
6efcd9a8
PA
4457 if (inf->needs_setup)
4458 {
4459 thread = any_live_thread_of_process (inf->pid);
4460 switch_to_thread_no_regs (thread);
4461 setup_inferior (0);
4462 }
4463 }
221e1a37 4464 }
6efcd9a8
PA
4465
4466 /* Now go over all threads that are stopped, and print their current
4467 frame. If all-stop, then if there's a signalled thread, pick
4468 that as current. */
4469 ALL_NON_EXITED_THREADS (thread)
4470 {
6efcd9a8
PA
4471 if (first == NULL)
4472 first = thread;
4473
4474 if (!non_stop)
4475 set_running (thread->ptid, 0);
4476 else if (thread->state != THREAD_STOPPED)
4477 continue;
4478
6efcd9a8
PA
4479 if (selected == NULL
4480 && thread->suspend.waitstatus_pending_p)
4481 selected = thread;
4482
5d5658a1
PA
4483 if (lowest_stopped == NULL
4484 || thread->inf->num < lowest_stopped->inf->num
4485 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4486 lowest_stopped = thread;
4487
4488 if (non_stop)
4489 print_one_stopped_thread (thread);
4490 }
4491
4492 /* In all-stop, we only print the status of one thread, and leave
4493 others with their status pending. */
4494 if (!non_stop)
4495 {
4496 thread = selected;
4497 if (thread == NULL)
4498 thread = lowest_stopped;
4499 if (thread == NULL)
4500 thread = first;
4501
4502 print_one_stopped_thread (thread);
4503 }
4504
4505 /* For "info program". */
4506 thread = inferior_thread ();
4507 if (thread->state == THREAD_STOPPED)
4508 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4509}
4510
048094ac
PA
4511/* Start the remote connection and sync state. */
4512
f6ac5f3d
PA
4513void
4514remote_target::start_remote (int from_tty, int extended_p)
c906108c 4515{
c8d104ad
PA
4516 struct remote_state *rs = get_remote_state ();
4517 struct packet_config *noack_config;
2d717e4f 4518 char *wait_status = NULL;
8621d6a9 4519
048094ac
PA
4520 /* Signal other parts that we're going through the initial setup,
4521 and so things may not be stable yet. E.g., we don't try to
4522 install tracepoints until we've relocated symbols. Also, a
4523 Ctrl-C before we're connected and synced up can't interrupt the
4524 target. Instead, it offers to drop the (potentially wedged)
4525 connection. */
4526 rs->starting_up = 1;
4527
522002f9 4528 QUIT;
c906108c 4529
9a7071a8
JB
4530 if (interrupt_on_connect)
4531 send_interrupt_sequence ();
4532
57e12211 4533 /* Ack any packet which the remote side has already sent. */
048094ac 4534 remote_serial_write ("+", 1);
1e51243a 4535
c8d104ad
PA
4536 /* The first packet we send to the target is the optional "supported
4537 packets" request. If the target can answer this, it will tell us
4538 which later probes to skip. */
4539 remote_query_supported ();
4540
d914c394 4541 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4542 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4543 set_permissions ();
d914c394 4544
57809e5e
JK
4545 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4546 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4547 as a reply to known packet. For packet "vFile:setfs:" it is an
4548 invalid reply and GDB would return error in
4549 remote_hostio_set_filesystem, making remote files access impossible.
4550 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4551 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4552 {
4553 const char v_mustreplyempty[] = "vMustReplyEmpty";
4554
4555 putpkt (v_mustreplyempty);
4556 getpkt (&rs->buf, &rs->buf_size, 0);
4557 if (strcmp (rs->buf, "OK") == 0)
4558 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4559 else if (strcmp (rs->buf, "") != 0)
4560 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4561 rs->buf);
4562 }
4563
c8d104ad
PA
4564 /* Next, we possibly activate noack mode.
4565
4566 If the QStartNoAckMode packet configuration is set to AUTO,
4567 enable noack mode if the stub reported a wish for it with
4568 qSupported.
4569
4570 If set to TRUE, then enable noack mode even if the stub didn't
4571 report it in qSupported. If the stub doesn't reply OK, the
4572 session ends with an error.
4573
4574 If FALSE, then don't activate noack mode, regardless of what the
4575 stub claimed should be the default with qSupported. */
4576
4577 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4578 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4579 {
4580 putpkt ("QStartNoAckMode");
4581 getpkt (&rs->buf, &rs->buf_size, 0);
4582 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4583 rs->noack_mode = 1;
4584 }
4585
04bd08de 4586 if (extended_p)
5fe04517
PA
4587 {
4588 /* Tell the remote that we are using the extended protocol. */
4589 putpkt ("!");
4590 getpkt (&rs->buf, &rs->buf_size, 0);
4591 }
4592
9b224c5e
PA
4593 /* Let the target know which signals it is allowed to pass down to
4594 the program. */
4595 update_signals_program_target ();
4596
d962ef82
DJ
4597 /* Next, if the target can specify a description, read it. We do
4598 this before anything involving memory or registers. */
4599 target_find_description ();
4600
6c95b8df
PA
4601 /* Next, now that we know something about the target, update the
4602 address spaces in the program spaces. */
4603 update_address_spaces ();
4604
50c71eaf
PA
4605 /* On OSs where the list of libraries is global to all
4606 processes, we fetch them early. */
f5656ead 4607 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4608 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4609
6efcd9a8 4610 if (target_is_non_stop_p ())
74531fed 4611 {
4082afcc 4612 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4613 error (_("Non-stop mode requested, but remote "
4614 "does not support non-stop"));
74531fed
PA
4615
4616 putpkt ("QNonStop:1");
4617 getpkt (&rs->buf, &rs->buf_size, 0);
4618
4619 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4620 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4621
4622 /* Find about threads and processes the stub is already
4623 controlling. We default to adding them in the running state.
4624 The '?' query below will then tell us about which threads are
4625 stopped. */
f6ac5f3d 4626 this->update_thread_list ();
74531fed 4627 }
4082afcc 4628 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4629 {
4630 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4631 Request it explicitly. */
74531fed
PA
4632 putpkt ("QNonStop:0");
4633 getpkt (&rs->buf, &rs->buf_size, 0);
4634
4635 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4636 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4637 }
4638
a0743c90
YQ
4639 /* Upload TSVs regardless of whether the target is running or not. The
4640 remote stub, such as GDBserver, may have some predefined or builtin
4641 TSVs, even if the target is not running. */
f6ac5f3d 4642 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4643 {
4644 struct uploaded_tsv *uploaded_tsvs = NULL;
4645
f6ac5f3d 4646 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4647 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4648 }
4649
2d717e4f
DJ
4650 /* Check whether the target is running now. */
4651 putpkt ("?");
4652 getpkt (&rs->buf, &rs->buf_size, 0);
4653
6efcd9a8 4654 if (!target_is_non_stop_p ())
2d717e4f 4655 {
74531fed 4656 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4657 {
04bd08de 4658 if (!extended_p)
74531fed 4659 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4660
4661 /* We're connected, but not running. Drop out before we
4662 call start_remote. */
e278ad5b 4663 rs->starting_up = 0;
c35b1492 4664 return;
2d717e4f
DJ
4665 }
4666 else
74531fed 4667 {
74531fed 4668 /* Save the reply for later. */
224c3ddb 4669 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4670 strcpy (wait_status, rs->buf);
4671 }
4672
b7ea362b 4673 /* Fetch thread list. */
e8032dde 4674 target_update_thread_list ();
b7ea362b 4675
74531fed
PA
4676 /* Let the stub know that we want it to return the thread. */
4677 set_continue_thread (minus_one_ptid);
4678
b7ea362b
PA
4679 if (thread_count () == 0)
4680 {
4681 /* Target has no concept of threads at all. GDB treats
4682 non-threaded target as single-threaded; add a main
4683 thread. */
4684 add_current_inferior_and_thread (wait_status);
4685 }
4686 else
4687 {
4688 /* We have thread information; select the thread the target
4689 says should be current. If we're reconnecting to a
4690 multi-threaded program, this will ideally be the thread
4691 that last reported an event before GDB disconnected. */
4692 inferior_ptid = get_current_thread (wait_status);
4693 if (ptid_equal (inferior_ptid, null_ptid))
4694 {
4695 /* Odd... The target was able to list threads, but not
4696 tell us which thread was current (no "thread"
4697 register in T stop reply?). Just pick the first
4698 thread in the thread list then. */
c9f35b34
KB
4699
4700 if (remote_debug)
4701 fprintf_unfiltered (gdb_stdlog,
4702 "warning: couldn't determine remote "
4703 "current thread; picking first in list.\n");
4704
b7ea362b
PA
4705 inferior_ptid = thread_list->ptid;
4706 }
4707 }
74531fed 4708
6e586cc5
YQ
4709 /* init_wait_for_inferior should be called before get_offsets in order
4710 to manage `inserted' flag in bp loc in a correct state.
4711 breakpoint_init_inferior, called from init_wait_for_inferior, set
4712 `inserted' flag to 0, while before breakpoint_re_set, called from
4713 start_remote, set `inserted' flag to 1. In the initialization of
4714 inferior, breakpoint_init_inferior should be called first, and then
4715 breakpoint_re_set can be called. If this order is broken, state of
4716 `inserted' flag is wrong, and cause some problems on breakpoint
4717 manipulation. */
4718 init_wait_for_inferior ();
4719
74531fed
PA
4720 get_offsets (); /* Get text, data & bss offsets. */
4721
d962ef82
DJ
4722 /* If we could not find a description using qXfer, and we know
4723 how to do it some other way, try again. This is not
4724 supported for non-stop; it could be, but it is tricky if
4725 there are no stopped threads when we connect. */
f6ac5f3d 4726 if (remote_read_description_p (this)
f5656ead 4727 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4728 {
4729 target_clear_description ();
4730 target_find_description ();
4731 }
4732
74531fed
PA
4733 /* Use the previously fetched status. */
4734 gdb_assert (wait_status != NULL);
4735 strcpy (rs->buf, wait_status);
4736 rs->cached_wait_status = 1;
4737
f6ac5f3d 4738 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4739 }
4740 else
4741 {
68c97600
PA
4742 /* Clear WFI global state. Do this before finding about new
4743 threads and inferiors, and setting the current inferior.
4744 Otherwise we would clear the proceed status of the current
4745 inferior when we want its stop_soon state to be preserved
4746 (see notice_new_inferior). */
4747 init_wait_for_inferior ();
4748
74531fed
PA
4749 /* In non-stop, we will either get an "OK", meaning that there
4750 are no stopped threads at this time; or, a regular stop
4751 reply. In the latter case, there may be more than one thread
4752 stopped --- we pull them all out using the vStopped
4753 mechanism. */
4754 if (strcmp (rs->buf, "OK") != 0)
4755 {
722247f1 4756 struct notif_client *notif = &notif_client_stop;
2d717e4f 4757
722247f1
YQ
4758 /* remote_notif_get_pending_replies acks this one, and gets
4759 the rest out. */
f48ff2a7 4760 rs->notif_state->pending_event[notif_client_stop.id]
6b8edb51 4761 = remote_notif_parse (this, notif, rs->buf);
722247f1 4762 remote_notif_get_pending_events (notif);
74531fed 4763 }
2d717e4f 4764
74531fed
PA
4765 if (thread_count () == 0)
4766 {
04bd08de 4767 if (!extended_p)
74531fed 4768 error (_("The target is not running (try extended-remote?)"));
82f73884 4769
c35b1492
PA
4770 /* We're connected, but not running. Drop out before we
4771 call start_remote. */
e278ad5b 4772 rs->starting_up = 0;
c35b1492
PA
4773 return;
4774 }
74531fed 4775
74531fed
PA
4776 /* In non-stop mode, any cached wait status will be stored in
4777 the stop reply queue. */
4778 gdb_assert (wait_status == NULL);
f0223081 4779
2455069d 4780 /* Report all signals during attach/startup. */
f6ac5f3d 4781 pass_signals (0, NULL);
221e1a37
PA
4782
4783 /* If there are already stopped threads, mark them stopped and
4784 report their stops before giving the prompt to the user. */
6efcd9a8 4785 process_initial_stop_replies (from_tty);
221e1a37
PA
4786
4787 if (target_can_async_p ())
4788 target_async (1);
74531fed 4789 }
c8d104ad 4790
c8d104ad
PA
4791 /* If we connected to a live target, do some additional setup. */
4792 if (target_has_execution)
4793 {
f4ccffad 4794 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4795 remote_check_symbols ();
c8d104ad 4796 }
50c71eaf 4797
d5551862
SS
4798 /* Possibly the target has been engaged in a trace run started
4799 previously; find out where things are at. */
f6ac5f3d 4800 if (get_trace_status (current_trace_status ()) != -1)
d5551862 4801 {
00bf0b85 4802 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4803
00bf0b85
SS
4804 if (current_trace_status ()->running)
4805 printf_filtered (_("Trace is already running on the target.\n"));
4806
f6ac5f3d 4807 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
4808
4809 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4810 }
4811
c0272db5
TW
4812 /* Possibly the target has been engaged in a btrace record started
4813 previously; find out where things are at. */
4814 remote_btrace_maybe_reopen ();
4815
1e51243a
PA
4816 /* The thread and inferior lists are now synchronized with the
4817 target, our symbols have been relocated, and we're merged the
4818 target's tracepoints with ours. We're done with basic start
4819 up. */
4820 rs->starting_up = 0;
4821
a25a5a45
PA
4822 /* Maybe breakpoints are global and need to be inserted now. */
4823 if (breakpoints_should_be_inserted_now ())
50c71eaf 4824 insert_breakpoints ();
c906108c
SS
4825}
4826
4827/* Open a connection to a remote debugger.
4828 NAME is the filename used for communication. */
4829
f6ac5f3d
PA
4830void
4831remote_target::open (const char *name, int from_tty)
c906108c 4832{
f6ac5f3d 4833 open_1 (name, from_tty, 0);
43ff13b4
JM
4834}
4835
c906108c
SS
4836/* Open a connection to a remote debugger using the extended
4837 remote gdb protocol. NAME is the filename used for communication. */
4838
f6ac5f3d
PA
4839void
4840extended_remote_target::open (const char *name, int from_tty)
c906108c 4841{
f6ac5f3d 4842 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
4843}
4844
ca4f7f8b
PA
4845/* Reset all packets back to "unknown support". Called when opening a
4846 new connection to a remote target. */
c906108c 4847
d471ea57 4848static void
ca4f7f8b 4849reset_all_packet_configs_support (void)
d471ea57
AC
4850{
4851 int i;
a744cf53 4852
444abaca 4853 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4854 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4855}
4856
ca4f7f8b
PA
4857/* Initialize all packet configs. */
4858
4859static void
4860init_all_packet_configs (void)
4861{
4862 int i;
4863
4864 for (i = 0; i < PACKET_MAX; i++)
4865 {
4866 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4867 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4868 }
4869}
4870
23860348 4871/* Symbol look-up. */
dc8acb97 4872
6b8edb51
PA
4873void
4874remote_target::remote_check_symbols ()
dc8acb97
MS
4875{
4876 char *msg, *reply, *tmp;
dc8acb97 4877 int end;
28170b88 4878 long reply_size;
a5c0808e 4879 struct cleanup *old_chain;
dc8acb97 4880
63154eca
PA
4881 /* The remote side has no concept of inferiors that aren't running
4882 yet, it only knows about running processes. If we're connected
4883 but our current inferior is not running, we should not invite the
4884 remote target to request symbol lookups related to its
4885 (unrelated) current process. */
4886 if (!target_has_execution)
4887 return;
4888
4082afcc 4889 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4890 return;
4891
63154eca
PA
4892 /* Make sure the remote is pointing at the right process. Note
4893 there's no way to select "no process". */
3c9c4b83
PA
4894 set_general_process ();
4895
6d820c5c
DJ
4896 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4897 because we need both at the same time. */
224c3ddb 4898 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4899 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4900 reply = (char *) xmalloc (get_remote_packet_size ());
4901 make_cleanup (free_current_contents, &reply);
4902 reply_size = get_remote_packet_size ();
6d820c5c 4903
23860348 4904 /* Invite target to request symbol lookups. */
dc8acb97
MS
4905
4906 putpkt ("qSymbol::");
28170b88
MK
4907 getpkt (&reply, &reply_size, 0);
4908 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4909
61012eef 4910 while (startswith (reply, "qSymbol:"))
dc8acb97 4911 {
77e371c0
TT
4912 struct bound_minimal_symbol sym;
4913
dc8acb97 4914 tmp = &reply[8];
cfd77fa1 4915 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4916 msg[end] = '\0';
4917 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4918 if (sym.minsym == NULL)
ea9c271d 4919 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4920 else
2bbe3cc1 4921 {
f5656ead 4922 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4923 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4924
4925 /* If this is a function address, return the start of code
4926 instead of any data function descriptor. */
f5656ead 4927 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1 4928 sym_addr,
f6ac5f3d 4929 target_stack);
2bbe3cc1
DJ
4930
4931 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4932 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4933 }
4934
dc8acb97 4935 putpkt (msg);
28170b88 4936 getpkt (&reply, &reply_size, 0);
dc8acb97 4937 }
a5c0808e
PA
4938
4939 do_cleanups (old_chain);
dc8acb97
MS
4940}
4941
9db8d71f 4942static struct serial *
baa336ce 4943remote_serial_open (const char *name)
9db8d71f
DJ
4944{
4945 static int udp_warning = 0;
4946
4947 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4948 of in ser-tcp.c, because it is the remote protocol assuming that the
4949 serial connection is reliable and not the serial connection promising
4950 to be. */
61012eef 4951 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4952 {
3e43a32a
MS
4953 warning (_("The remote protocol may be unreliable over UDP.\n"
4954 "Some events may be lost, rendering further debugging "
4955 "impossible."));
9db8d71f
DJ
4956 udp_warning = 1;
4957 }
4958
4959 return serial_open (name);
4960}
4961
d914c394
SS
4962/* Inform the target of our permission settings. The permission flags
4963 work without this, but if the target knows the settings, it can do
4964 a couple things. First, it can add its own check, to catch cases
4965 that somehow manage to get by the permissions checks in target
4966 methods. Second, if the target is wired to disallow particular
4967 settings (for instance, a system in the field that is not set up to
4968 be able to stop at a breakpoint), it can object to any unavailable
4969 permissions. */
4970
4971void
f6ac5f3d 4972remote_target::set_permissions ()
d914c394
SS
4973{
4974 struct remote_state *rs = get_remote_state ();
4975
bba74b36
YQ
4976 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4977 "WriteReg:%x;WriteMem:%x;"
4978 "InsertBreak:%x;InsertTrace:%x;"
4979 "InsertFastTrace:%x;Stop:%x",
4980 may_write_registers, may_write_memory,
4981 may_insert_breakpoints, may_insert_tracepoints,
4982 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4983 putpkt (rs->buf);
4984 getpkt (&rs->buf, &rs->buf_size, 0);
4985
4986 /* If the target didn't like the packet, warn the user. Do not try
4987 to undo the user's settings, that would just be maddening. */
4988 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4989 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4990}
4991
be2a5f71
DJ
4992/* This type describes each known response to the qSupported
4993 packet. */
4994struct protocol_feature
4995{
4996 /* The name of this protocol feature. */
4997 const char *name;
4998
4999 /* The default for this protocol feature. */
5000 enum packet_support default_support;
5001
5002 /* The function to call when this feature is reported, or after
5003 qSupported processing if the feature is not supported.
5004 The first argument points to this structure. The second
5005 argument indicates whether the packet requested support be
5006 enabled, disabled, or probed (or the default, if this function
5007 is being called at the end of processing and this feature was
5008 not reported). The third argument may be NULL; if not NULL, it
5009 is a NUL-terminated string taken from the packet following
5010 this feature's name and an equals sign. */
6b8edb51
PA
5011 void (*func) (remote_target *remote, const struct protocol_feature *,
5012 enum packet_support, const char *);
be2a5f71
DJ
5013
5014 /* The corresponding packet for this feature. Only used if
5015 FUNC is remote_supported_packet. */
5016 int packet;
5017};
5018
be2a5f71 5019static void
6b8edb51
PA
5020remote_supported_packet (remote_target *remote,
5021 const struct protocol_feature *feature,
be2a5f71
DJ
5022 enum packet_support support,
5023 const char *argument)
5024{
5025 if (argument)
5026 {
5027 warning (_("Remote qSupported response supplied an unexpected value for"
5028 " \"%s\"."), feature->name);
5029 return;
5030 }
5031
4082afcc 5032 remote_protocol_packets[feature->packet].support = support;
be2a5f71 5033}
be2a5f71 5034
6b8edb51
PA
5035void
5036remote_target::remote_packet_size (const protocol_feature *feature,
5037 enum packet_support support, const char *value)
be2a5f71
DJ
5038{
5039 struct remote_state *rs = get_remote_state ();
5040
5041 int packet_size;
5042 char *value_end;
5043
5044 if (support != PACKET_ENABLE)
5045 return;
5046
5047 if (value == NULL || *value == '\0')
5048 {
5049 warning (_("Remote target reported \"%s\" without a size."),
5050 feature->name);
5051 return;
5052 }
5053
5054 errno = 0;
5055 packet_size = strtol (value, &value_end, 16);
5056 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5057 {
5058 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5059 feature->name, value);
5060 return;
5061 }
5062
be2a5f71
DJ
5063 /* Record the new maximum packet size. */
5064 rs->explicit_packet_size = packet_size;
5065}
5066
6b8edb51
PA
5067void
5068remote_packet_size (remote_target *remote, const protocol_feature *feature,
5069 enum packet_support support, const char *value)
5070{
5071 remote->remote_packet_size (feature, support, value);
5072}
5073
dc473cfb 5074static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5075 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5076 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5077 PACKET_qXfer_auxv },
c78fa86a
GB
5078 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5079 PACKET_qXfer_exec_file },
23181151
DJ
5080 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5081 PACKET_qXfer_features },
cfa9d6d9
DJ
5082 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5083 PACKET_qXfer_libraries },
2268b414
JK
5084 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5085 PACKET_qXfer_libraries_svr4 },
ced63ec0 5086 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5087 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5088 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5089 PACKET_qXfer_memory_map },
4de6483e
UW
5090 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5091 PACKET_qXfer_spu_read },
5092 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5093 PACKET_qXfer_spu_write },
07e059b5
VP
5094 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5095 PACKET_qXfer_osdata },
dc146f7c
VP
5096 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5097 PACKET_qXfer_threads },
b3b9301e
PA
5098 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5099 PACKET_qXfer_traceframe_info },
89be2091
DJ
5100 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5101 PACKET_QPassSignals },
82075af2
JS
5102 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5103 PACKET_QCatchSyscalls },
9b224c5e
PA
5104 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5105 PACKET_QProgramSignals },
bc3b087d
SDJ
5106 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5107 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5108 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5109 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5110 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5111 PACKET_QEnvironmentHexEncoded },
5112 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5113 PACKET_QEnvironmentReset },
5114 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5115 PACKET_QEnvironmentUnset },
a6f3e723
SL
5116 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5117 PACKET_QStartNoAckMode },
4082afcc
PA
5118 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5119 PACKET_multiprocess_feature },
5120 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5121 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5122 PACKET_qXfer_siginfo_read },
5123 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5124 PACKET_qXfer_siginfo_write },
4082afcc 5125 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5126 PACKET_ConditionalTracepoints },
4082afcc 5127 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5128 PACKET_ConditionalBreakpoints },
4082afcc 5129 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5130 PACKET_BreakpointCommands },
4082afcc 5131 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5132 PACKET_FastTracepoints },
4082afcc 5133 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5134 PACKET_StaticTracepoints },
4082afcc 5135 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5136 PACKET_InstallInTrace},
4082afcc
PA
5137 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5138 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5139 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5140 PACKET_bc },
5141 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5142 PACKET_bs },
409873ef
SS
5143 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5144 PACKET_TracepointSource },
d914c394
SS
5145 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5146 PACKET_QAllow },
4082afcc
PA
5147 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5148 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5149 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5150 PACKET_qXfer_fdpic },
169081d0
TG
5151 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5152 PACKET_qXfer_uib },
03583c20
UW
5153 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5154 PACKET_QDisableRandomization },
d1feda86 5155 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5156 { "QTBuffer:size", PACKET_DISABLE,
5157 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5158 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5159 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5160 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5161 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5162 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5163 PACKET_qXfer_btrace },
5164 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5165 PACKET_qXfer_btrace_conf },
5166 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5167 PACKET_Qbtrace_conf_bts_size },
5168 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5169 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5170 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5171 PACKET_fork_event_feature },
5172 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5173 PACKET_vfork_event_feature },
94585166
DB
5174 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5175 PACKET_exec_event_feature },
b20a6524 5176 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5177 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5178 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5179 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5180 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
5181};
5182
c8d5aac9
L
5183static char *remote_support_xml;
5184
5185/* Register string appended to "xmlRegisters=" in qSupported query. */
5186
5187void
6e39997a 5188register_remote_support_xml (const char *xml)
c8d5aac9
L
5189{
5190#if defined(HAVE_LIBEXPAT)
5191 if (remote_support_xml == NULL)
c4f7c687 5192 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5193 else
5194 {
5195 char *copy = xstrdup (remote_support_xml + 13);
5196 char *p = strtok (copy, ",");
5197
5198 do
5199 {
5200 if (strcmp (p, xml) == 0)
5201 {
5202 /* already there */
5203 xfree (copy);
5204 return;
5205 }
5206 }
5207 while ((p = strtok (NULL, ",")) != NULL);
5208 xfree (copy);
5209
94b0dee1
PA
5210 remote_support_xml = reconcat (remote_support_xml,
5211 remote_support_xml, ",", xml,
5212 (char *) NULL);
c8d5aac9
L
5213 }
5214#endif
5215}
5216
69b6ecb0
TT
5217static void
5218remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5219{
69b6ecb0
TT
5220 if (!msg->empty ())
5221 msg->append (";");
5222 msg->append (append);
c8d5aac9
L
5223}
5224
6b8edb51
PA
5225void
5226remote_target::remote_query_supported ()
be2a5f71
DJ
5227{
5228 struct remote_state *rs = get_remote_state ();
5229 char *next;
5230 int i;
5231 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5232
5233 /* The packet support flags are handled differently for this packet
5234 than for most others. We treat an error, a disabled packet, and
5235 an empty response identically: any features which must be reported
5236 to be used will be automatically disabled. An empty buffer
5237 accomplishes this, since that is also the representation for a list
5238 containing no features. */
5239
5240 rs->buf[0] = 0;
4082afcc 5241 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5242 {
69b6ecb0 5243 std::string q;
c8d5aac9 5244
73b8c1fd 5245 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5246 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5247
f7e6eed5 5248 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5249 remote_query_supported_append (&q, "swbreak+");
f7e6eed5 5250 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5251 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5252
69b6ecb0 5253 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5254
8020350c
DB
5255 if (packet_set_cmd_state (PACKET_fork_event_feature)
5256 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5257 remote_query_supported_append (&q, "fork-events+");
8020350c
DB
5258 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5259 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5260 remote_query_supported_append (&q, "vfork-events+");
8020350c
DB
5261 if (packet_set_cmd_state (PACKET_exec_event_feature)
5262 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5263 remote_query_supported_append (&q, "exec-events+");
89245bc0 5264
750ce8d1 5265 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5266 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5267
65706a29 5268 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5269 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5270
f2faf941 5271 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5272 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5273
b35d5edb
PA
5274 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5275 the qSupported:xmlRegisters=i386 handling. */
7cc244de
PA
5276 if (remote_support_xml != NULL
5277 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
69b6ecb0 5278 remote_query_supported_append (&q, remote_support_xml);
82f73884 5279
69b6ecb0
TT
5280 q = "qSupported:" + q;
5281 putpkt (q.c_str ());
94b0dee1 5282
be2a5f71
DJ
5283 getpkt (&rs->buf, &rs->buf_size, 0);
5284
5285 /* If an error occured, warn, but do not return - just reset the
5286 buffer to empty and go on to disable features. */
5287 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5288 == PACKET_ERROR)
5289 {
5290 warning (_("Remote failure reply: %s"), rs->buf);
5291 rs->buf[0] = 0;
5292 }
5293 }
5294
5295 memset (seen, 0, sizeof (seen));
5296
5297 next = rs->buf;
5298 while (*next)
5299 {
5300 enum packet_support is_supported;
5301 char *p, *end, *name_end, *value;
5302
5303 /* First separate out this item from the rest of the packet. If
5304 there's another item after this, we overwrite the separator
5305 (terminated strings are much easier to work with). */
5306 p = next;
5307 end = strchr (p, ';');
5308 if (end == NULL)
5309 {
5310 end = p + strlen (p);
5311 next = end;
5312 }
5313 else
5314 {
89be2091
DJ
5315 *end = '\0';
5316 next = end + 1;
5317
be2a5f71
DJ
5318 if (end == p)
5319 {
5320 warning (_("empty item in \"qSupported\" response"));
5321 continue;
5322 }
be2a5f71
DJ
5323 }
5324
5325 name_end = strchr (p, '=');
5326 if (name_end)
5327 {
5328 /* This is a name=value entry. */
5329 is_supported = PACKET_ENABLE;
5330 value = name_end + 1;
5331 *name_end = '\0';
5332 }
5333 else
5334 {
5335 value = NULL;
5336 switch (end[-1])
5337 {
5338 case '+':
5339 is_supported = PACKET_ENABLE;
5340 break;
5341
5342 case '-':
5343 is_supported = PACKET_DISABLE;
5344 break;
5345
5346 case '?':
5347 is_supported = PACKET_SUPPORT_UNKNOWN;
5348 break;
5349
5350 default:
3e43a32a
MS
5351 warning (_("unrecognized item \"%s\" "
5352 "in \"qSupported\" response"), p);
be2a5f71
DJ
5353 continue;
5354 }
5355 end[-1] = '\0';
5356 }
5357
5358 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5359 if (strcmp (remote_protocol_features[i].name, p) == 0)
5360 {
5361 const struct protocol_feature *feature;
5362
5363 seen[i] = 1;
5364 feature = &remote_protocol_features[i];
6b8edb51 5365 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5366 break;
5367 }
5368 }
5369
5370 /* If we increased the packet size, make sure to increase the global
5371 buffer size also. We delay this until after parsing the entire
5372 qSupported packet, because this is the same buffer we were
5373 parsing. */
5374 if (rs->buf_size < rs->explicit_packet_size)
5375 {
5376 rs->buf_size = rs->explicit_packet_size;
224c3ddb 5377 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
5378 }
5379
5380 /* Handle the defaults for unmentioned features. */
5381 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5382 if (!seen[i])
5383 {
5384 const struct protocol_feature *feature;
5385
5386 feature = &remote_protocol_features[i];
6b8edb51 5387 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5388 }
5389}
5390
048094ac
PA
5391/* Serial QUIT handler for the remote serial descriptor.
5392
5393 Defers handling a Ctrl-C until we're done with the current
5394 command/response packet sequence, unless:
5395
5396 - We're setting up the connection. Don't send a remote interrupt
5397 request, as we're not fully synced yet. Quit immediately
5398 instead.
5399
5400 - The target has been resumed in the foreground
223ffa71 5401 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5402 packet, and we're blocked waiting for the stop reply, thus a
5403 Ctrl-C should be immediately sent to the target.
5404
5405 - We get a second Ctrl-C while still within the same serial read or
5406 write. In that case the serial is seemingly wedged --- offer to
5407 quit/disconnect.
5408
5409 - We see a second Ctrl-C without target response, after having
5410 previously interrupted the target. In that case the target/stub
5411 is probably wedged --- offer to quit/disconnect.
5412*/
5413
6b8edb51
PA
5414void
5415remote_target::remote_serial_quit_handler ()
048094ac
PA
5416{
5417 struct remote_state *rs = get_remote_state ();
5418
5419 if (check_quit_flag ())
5420 {
5421 /* If we're starting up, we're not fully synced yet. Quit
5422 immediately. */
5423 if (rs->starting_up)
5424 quit ();
5425 else if (rs->got_ctrlc_during_io)
5426 {
5427 if (query (_("The target is not responding to GDB commands.\n"
5428 "Stop debugging it? ")))
5429 remote_unpush_and_throw ();
5430 }
5431 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5432 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5433 interrupt_query ();
5434 /* All-stop protocol, and blocked waiting for stop reply. Send
5435 an interrupt request. */
223ffa71 5436 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5437 target_interrupt ();
048094ac
PA
5438 else
5439 rs->got_ctrlc_during_io = 1;
5440 }
5441}
5442
6b8edb51
PA
5443/* The remote_target that is current while the quit handler is
5444 overridden with remote_serial_quit_handler. */
5445static remote_target *curr_quit_handler_target;
5446
5447static void
5448remote_serial_quit_handler ()
5449{
5450 curr_quit_handler_target->remote_serial_quit_handler ();
5451}
5452
78a095c3
JK
5453/* Remove any of the remote.c targets from target stack. Upper targets depend
5454 on it so remove them first. */
5455
5456static void
5457remote_unpush_target (void)
5458{
915ef8b1 5459 pop_all_targets_at_and_above (process_stratum);
78a095c3 5460}
be2a5f71 5461
048094ac
PA
5462static void
5463remote_unpush_and_throw (void)
5464{
5465 remote_unpush_target ();
5466 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5467}
5468
f6ac5f3d
PA
5469void
5470remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5471{
6b8edb51 5472 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5473
c906108c 5474 if (name == 0)
8a3fe4f8 5475 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5476 "serial device is attached to the remote system\n"
8a3fe4f8 5477 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5478
2d717e4f 5479 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5480 Ask this question first, before target_preopen has a chance to kill
5481 anything. */
6b8edb51 5482 if (curr_remote != NULL && !have_inferiors ())
2d717e4f 5483 {
78a095c3
JK
5484 if (from_tty
5485 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5486 error (_("Still connected."));
5487 }
5488
78a095c3 5489 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5490 target_preopen (from_tty);
5491
ad9a8f3f 5492 remote_fileio_reset ();
1dd41f16
NS
5493 reopen_exec_file ();
5494 reread_symbols ();
5495
6b8edb51
PA
5496 remote_target *remote
5497 = (extended_p ? new extended_remote_target () : new remote_target ());
5498 target_ops_up target_holder (remote);
5499
5500 remote_state *rs = remote->get_remote_state ();
5501
5502 /* See FIXME above. */
5503 if (!target_async_permitted)
5504 rs->wait_forever_enabled_p = 1;
5505
5d93a237
TT
5506 rs->remote_desc = remote_serial_open (name);
5507 if (!rs->remote_desc)
c906108c
SS
5508 perror_with_name (name);
5509
5510 if (baud_rate != -1)
5511 {
5d93a237 5512 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5513 {
9b74d5d3
KB
5514 /* The requested speed could not be set. Error out to
5515 top level after closing remote_desc. Take care to
5516 set remote_desc to NULL to avoid closing remote_desc
5517 more than once. */
5d93a237
TT
5518 serial_close (rs->remote_desc);
5519 rs->remote_desc = NULL;
c906108c
SS
5520 perror_with_name (name);
5521 }
5522 }
5523
236af5e3 5524 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5525 serial_raw (rs->remote_desc);
c906108c
SS
5526
5527 /* If there is something sitting in the buffer we might take it as a
5528 response to a command, which would be bad. */
5d93a237 5529 serial_flush_input (rs->remote_desc);
c906108c
SS
5530
5531 if (from_tty)
5532 {
5533 puts_filtered ("Remote debugging using ");
5534 puts_filtered (name);
5535 puts_filtered ("\n");
5536 }
d9f719f1 5537
6b8edb51
PA
5538 /* Switch to using the remote target now. */
5539 push_target (remote);
5540 /* The target stack owns the target now. */
5541 target_holder.release ();
c906108c 5542
74531fed 5543 /* Register extra event sources in the event loop. */
6b8edb51 5544 rs->remote_async_inferior_event_token
74531fed 5545 = create_async_event_handler (remote_async_inferior_event_handler,
6b8edb51
PA
5546 remote);
5547 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 5548
be2a5f71
DJ
5549 /* Reset the target state; these things will be queried either by
5550 remote_query_supported or as they are needed. */
ca4f7f8b 5551 reset_all_packet_configs_support ();
74531fed 5552 rs->cached_wait_status = 0;
be2a5f71 5553 rs->explicit_packet_size = 0;
a6f3e723 5554 rs->noack_mode = 0;
82f73884 5555 rs->extended = extended_p;
e24a49d8 5556 rs->waiting_for_stop_reply = 0;
3a29589a 5557 rs->ctrlc_pending_p = 0;
048094ac 5558 rs->got_ctrlc_during_io = 0;
802188a7 5559
47f8a51d
TT
5560 rs->general_thread = not_sent_ptid;
5561 rs->continue_thread = not_sent_ptid;
262e1174 5562 rs->remote_traceframe_number = -1;
c906108c 5563
3a00c802
PA
5564 rs->last_resume_exec_dir = EXEC_FORWARD;
5565
9d1f7ab2 5566 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5567 rs->use_threadinfo_query = 1;
5568 rs->use_threadextra_query = 1;
9d1f7ab2 5569
dd194f6b 5570 rs->readahead_cache.invalidate ();
80152258 5571
c6ebd6cf 5572 if (target_async_permitted)
92d1e331 5573 {
92d1e331
DJ
5574 /* FIXME: cagney/1999-09-23: During the initial connection it is
5575 assumed that the target is already ready and able to respond to
0df8b418 5576 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5577 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5578 around this. Eventually a mechanism that allows
92d1e331 5579 wait_for_inferior() to expect/get timeouts will be
23860348 5580 implemented. */
6b8edb51 5581 rs->wait_forever_enabled_p = 0;
92d1e331
DJ
5582 }
5583
23860348 5584 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5585 no_shared_libraries (NULL, 0);
f78f6cf1 5586
74531fed
PA
5587 /* Start afresh. */
5588 init_thread_list ();
5589
36918e70 5590 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5591 target (we'd otherwise be in an inconsistent state) and then
5592 propogate the error on up the exception chain. This ensures that
5593 the caller doesn't stumble along blindly assuming that the
5594 function succeeded. The CLI doesn't have this problem but other
5595 UI's, such as MI do.
36918e70
AC
5596
5597 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5598 this function should return an error indication letting the
ce2826aa 5599 caller restore the previous state. Unfortunately the command
36918e70
AC
5600 ``target remote'' is directly wired to this function making that
5601 impossible. On a positive note, the CLI side of this problem has
5602 been fixed - the function set_cmd_context() makes it possible for
5603 all the ``target ....'' commands to share a common callback
5604 function. See cli-dump.c. */
109c3e39 5605 {
2d717e4f 5606
492d29ea 5607 TRY
04bd08de 5608 {
6b8edb51 5609 remote->start_remote (from_tty, extended_p);
04bd08de 5610 }
492d29ea 5611 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5612 {
c8d104ad
PA
5613 /* Pop the partially set up target - unless something else did
5614 already before throwing the exception. */
6b8edb51 5615 if (ex.error != TARGET_CLOSE_ERROR)
78a095c3 5616 remote_unpush_target ();
109c3e39
AC
5617 throw_exception (ex);
5618 }
492d29ea 5619 END_CATCH
109c3e39 5620 }
c906108c 5621
6b8edb51 5622 remote_btrace_reset (rs);
f4abbc16 5623
c6ebd6cf 5624 if (target_async_permitted)
6b8edb51 5625 rs->wait_forever_enabled_p = 1;
43ff13b4
JM
5626}
5627
de0d863e
DB
5628/* Detach the specified process. */
5629
6b8edb51
PA
5630void
5631remote_target::remote_detach_pid (int pid)
de0d863e
DB
5632{
5633 struct remote_state *rs = get_remote_state ();
5634
5635 if (remote_multi_process_p (rs))
5636 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5637 else
5638 strcpy (rs->buf, "D");
5639
5640 putpkt (rs->buf);
5641 getpkt (&rs->buf, &rs->buf_size, 0);
5642
5643 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5644 ;
5645 else if (rs->buf[0] == '\0')
5646 error (_("Remote doesn't know how to detach"));
5647 else
5648 error (_("Can't detach process."));
5649}
5650
5651/* This detaches a program to which we previously attached, using
5652 inferior_ptid to identify the process. After this is done, GDB
5653 can be used to debug some other program. We better not have left
5654 any breakpoints in the target program or it'll die when it hits
5655 one. */
c906108c 5656
6b8edb51
PA
5657void
5658remote_target::remote_detach_1 (int from_tty, inferior *inf)
c906108c 5659{
82f73884 5660 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5661 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5662 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5663 int is_fork_parent;
c906108c 5664
2d717e4f
DJ
5665 if (!target_has_execution)
5666 error (_("No process to detach from."));
5667
0f48b757 5668 target_announce_detach (from_tty);
7cee1e54 5669
c906108c 5670 /* Tell the remote target to detach. */
de0d863e 5671 remote_detach_pid (pid);
82f73884 5672
8020350c
DB
5673 /* Exit only if this is the only active inferior. */
5674 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5675 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5676
de0d863e
DB
5677 /* Check to see if we are detaching a fork parent. Note that if we
5678 are detaching a fork child, tp == NULL. */
5679 is_fork_parent = (tp != NULL
5680 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5681
5682 /* If doing detach-on-fork, we don't mourn, because that will delete
5683 breakpoints that should be available for the followed inferior. */
5684 if (!is_fork_parent)
f67c0c91 5685 {
249b5733
PA
5686 /* Save the pid as a string before mourning, since that will
5687 unpush the remote target, and we need the string after. */
5688 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
f67c0c91
SDJ
5689
5690 target_mourn_inferior (inferior_ptid);
5691 if (print_inferior_events)
5692 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5693 inf->num, infpid.c_str ());
5694 }
de0d863e
DB
5695 else
5696 {
5697 inferior_ptid = null_ptid;
5698 detach_inferior (pid);
5699 }
2d717e4f
DJ
5700}
5701
f6ac5f3d
PA
5702void
5703remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5704{
6e1e1966 5705 remote_detach_1 (from_tty, inf);
2d717e4f
DJ
5706}
5707
f6ac5f3d
PA
5708void
5709extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5710{
6e1e1966 5711 remote_detach_1 (from_tty, inf);
de0d863e
DB
5712}
5713
5714/* Target follow-fork function for remote targets. On entry, and
5715 at return, the current inferior is the fork parent.
5716
5717 Note that although this is currently only used for extended-remote,
5718 it is named remote_follow_fork in anticipation of using it for the
5719 remote target as well. */
5720
f6ac5f3d
PA
5721int
5722remote_target::follow_fork (int follow_child, int detach_fork)
de0d863e
DB
5723{
5724 struct remote_state *rs = get_remote_state ();
c269dbdb 5725 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5726
c269dbdb
DB
5727 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5728 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5729 {
5730 /* When following the parent and detaching the child, we detach
5731 the child here. For the case of following the child and
5732 detaching the parent, the detach is done in the target-
5733 independent follow fork code in infrun.c. We can't use
5734 target_detach when detaching an unfollowed child because
5735 the client side doesn't know anything about the child. */
5736 if (detach_fork && !follow_child)
5737 {
5738 /* Detach the fork child. */
5739 ptid_t child_ptid;
5740 pid_t child_pid;
5741
5742 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5743 child_pid = ptid_get_pid (child_ptid);
5744
5745 remote_detach_pid (child_pid);
de0d863e
DB
5746 }
5747 }
5748 return 0;
c906108c
SS
5749}
5750
94585166
DB
5751/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5752 in the program space of the new inferior. On entry and at return the
5753 current inferior is the exec'ing inferior. INF is the new exec'd
5754 inferior, which may be the same as the exec'ing inferior unless
5755 follow-exec-mode is "new". */
5756
f6ac5f3d
PA
5757void
5758remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
94585166
DB
5759{
5760 /* We know that this is a target file name, so if it has the "target:"
5761 prefix we strip it off before saving it in the program space. */
5762 if (is_target_filename (execd_pathname))
5763 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5764
5765 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5766}
5767
6ad8ae5c
DJ
5768/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5769
f6ac5f3d
PA
5770void
5771remote_target::disconnect (const char *args, int from_tty)
43ff13b4 5772{
43ff13b4 5773 if (args)
2d717e4f 5774 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5775
8020350c
DB
5776 /* Make sure we unpush even the extended remote targets. Calling
5777 target_mourn_inferior won't unpush, and remote_mourn won't
5778 unpush if there is more than one inferior left. */
f6ac5f3d 5779 unpush_target (this);
8020350c 5780 generic_mourn_inferior ();
2d717e4f 5781
43ff13b4
JM
5782 if (from_tty)
5783 puts_filtered ("Ending remote debugging.\n");
5784}
5785
2d717e4f
DJ
5786/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5787 be chatty about it. */
5788
f6ac5f3d
PA
5789void
5790extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
5791{
5792 struct remote_state *rs = get_remote_state ();
be86555c 5793 int pid;
96ef3384 5794 char *wait_status = NULL;
2d717e4f 5795
74164c56 5796 pid = parse_pid_to_attach (args);
2d717e4f 5797
74164c56
JK
5798 /* Remote PID can be freely equal to getpid, do not check it here the same
5799 way as in other targets. */
2d717e4f 5800
4082afcc 5801 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5802 error (_("This target does not support attaching to a process"));
5803
7cee1e54
PA
5804 if (from_tty)
5805 {
5806 char *exec_file = get_exec_file (0);
5807
5808 if (exec_file)
5809 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5810 target_pid_to_str (pid_to_ptid (pid)));
5811 else
5812 printf_unfiltered (_("Attaching to %s\n"),
5813 target_pid_to_str (pid_to_ptid (pid)));
5814
5815 gdb_flush (gdb_stdout);
5816 }
5817
bba74b36 5818 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5819 putpkt (rs->buf);
5820 getpkt (&rs->buf, &rs->buf_size, 0);
5821
4082afcc
PA
5822 switch (packet_ok (rs->buf,
5823 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5824 {
4082afcc 5825 case PACKET_OK:
6efcd9a8 5826 if (!target_is_non_stop_p ())
74531fed
PA
5827 {
5828 /* Save the reply for later. */
224c3ddb 5829 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5830 strcpy (wait_status, rs->buf);
5831 }
5832 else if (strcmp (rs->buf, "OK") != 0)
5833 error (_("Attaching to %s failed with: %s"),
5834 target_pid_to_str (pid_to_ptid (pid)),
5835 rs->buf);
4082afcc
PA
5836 break;
5837 case PACKET_UNKNOWN:
5838 error (_("This target does not support attaching to a process"));
5839 default:
5840 error (_("Attaching to %s failed"),
5841 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5842 }
2d717e4f 5843
1b6e6f5c 5844 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5845
2d717e4f 5846 inferior_ptid = pid_to_ptid (pid);
79d7f229 5847
6efcd9a8 5848 if (target_is_non_stop_p ())
bad34192
PA
5849 {
5850 struct thread_info *thread;
79d7f229 5851
bad34192 5852 /* Get list of threads. */
f6ac5f3d 5853 update_thread_list ();
82f73884 5854
bad34192
PA
5855 thread = first_thread_of_process (pid);
5856 if (thread)
5857 inferior_ptid = thread->ptid;
5858 else
5859 inferior_ptid = pid_to_ptid (pid);
5860
5861 /* Invalidate our notion of the remote current thread. */
47f8a51d 5862 record_currthread (rs, minus_one_ptid);
bad34192 5863 }
74531fed 5864 else
bad34192
PA
5865 {
5866 /* Now, if we have thread information, update inferior_ptid. */
5867 inferior_ptid = remote_current_thread (inferior_ptid);
5868
5869 /* Add the main thread to the thread list. */
00aecdcf
PA
5870 thread_info *thr = add_thread_silent (inferior_ptid);
5871 /* Don't consider the thread stopped until we've processed the
5872 saved stop reply. */
5873 set_executing (thr->ptid, true);
bad34192 5874 }
c0a2216e 5875
96ef3384
UW
5876 /* Next, if the target can specify a description, read it. We do
5877 this before anything involving memory or registers. */
5878 target_find_description ();
5879
6efcd9a8 5880 if (!target_is_non_stop_p ())
74531fed
PA
5881 {
5882 /* Use the previously fetched status. */
5883 gdb_assert (wait_status != NULL);
5884
5885 if (target_can_async_p ())
5886 {
722247f1 5887 struct notif_event *reply
6b8edb51 5888 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 5889
722247f1 5890 push_stop_reply ((struct stop_reply *) reply);
74531fed 5891
6a3753b3 5892 target_async (1);
74531fed
PA
5893 }
5894 else
5895 {
5896 gdb_assert (wait_status != NULL);
5897 strcpy (rs->buf, wait_status);
5898 rs->cached_wait_status = 1;
5899 }
5900 }
5901 else
5902 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5903}
5904
b9c1d481
AS
5905/* Implementation of the to_post_attach method. */
5906
f6ac5f3d
PA
5907void
5908extended_remote_target::post_attach (int pid)
b9c1d481 5909{
6efcd9a8
PA
5910 /* Get text, data & bss offsets. */
5911 get_offsets ();
5912
b9c1d481
AS
5913 /* In certain cases GDB might not have had the chance to start
5914 symbol lookup up until now. This could happen if the debugged
5915 binary is not using shared libraries, the vsyscall page is not
5916 present (on Linux) and the binary itself hadn't changed since the
5917 debugging process was started. */
5918 if (symfile_objfile != NULL)
5919 remote_check_symbols();
5920}
5921
c906108c 5922\f
506fb367
DJ
5923/* Check for the availability of vCont. This function should also check
5924 the response. */
c906108c 5925
6b8edb51
PA
5926void
5927remote_target::remote_vcont_probe ()
c906108c 5928{
6b8edb51 5929 remote_state *rs = get_remote_state ();
2e9f7625 5930 char *buf;
6d820c5c 5931
2e9f7625
DJ
5932 strcpy (rs->buf, "vCont?");
5933 putpkt (rs->buf);
6d820c5c 5934 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5935 buf = rs->buf;
c906108c 5936
506fb367 5937 /* Make sure that the features we assume are supported. */
61012eef 5938 if (startswith (buf, "vCont"))
506fb367
DJ
5939 {
5940 char *p = &buf[5];
750ce8d1 5941 int support_c, support_C;
506fb367 5942
750ce8d1
YQ
5943 rs->supports_vCont.s = 0;
5944 rs->supports_vCont.S = 0;
506fb367
DJ
5945 support_c = 0;
5946 support_C = 0;
d458bd84 5947 rs->supports_vCont.t = 0;
c1e36e3e 5948 rs->supports_vCont.r = 0;
506fb367
DJ
5949 while (p && *p == ';')
5950 {
5951 p++;
5952 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5953 rs->supports_vCont.s = 1;
506fb367 5954 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5955 rs->supports_vCont.S = 1;
506fb367
DJ
5956 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5957 support_c = 1;
5958 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5959 support_C = 1;
74531fed 5960 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5961 rs->supports_vCont.t = 1;
c1e36e3e
PA
5962 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5963 rs->supports_vCont.r = 1;
506fb367
DJ
5964
5965 p = strchr (p, ';');
5966 }
c906108c 5967
750ce8d1
YQ
5968 /* If c, and C are not all supported, we can't use vCont. Clearing
5969 BUF will make packet_ok disable the packet. */
5970 if (!support_c || !support_C)
506fb367
DJ
5971 buf[0] = 0;
5972 }
c906108c 5973
444abaca 5974 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5975}
c906108c 5976
0d8f58ca
PA
5977/* Helper function for building "vCont" resumptions. Write a
5978 resumption to P. ENDP points to one-passed-the-end of the buffer
5979 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5980 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5981 resumed thread should be single-stepped and/or signalled. If PTID
5982 equals minus_one_ptid, then all threads are resumed; if PTID
5983 represents a process, then all threads of the process are resumed;
5984 the thread to be stepped and/or signalled is given in the global
5985 INFERIOR_PTID. */
5986
6b8edb51
PA
5987char *
5988remote_target::append_resumption (char *p, char *endp,
5989 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
5990{
5991 struct remote_state *rs = get_remote_state ();
5992
a493e3e2 5993 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5994 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5995 else if (step
5996 /* GDB is willing to range step. */
5997 && use_range_stepping
5998 /* Target supports range stepping. */
5999 && rs->supports_vCont.r
6000 /* We don't currently support range stepping multiple
6001 threads with a wildcard (though the protocol allows it,
6002 so stubs shouldn't make an active effort to forbid
6003 it). */
6004 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6005 {
6006 struct thread_info *tp;
6007
6008 if (ptid_equal (ptid, minus_one_ptid))
6009 {
6010 /* If we don't know about the target thread's tid, then
6011 we're resuming magic_null_ptid (see caller). */
6012 tp = find_thread_ptid (magic_null_ptid);
6013 }
6014 else
6015 tp = find_thread_ptid (ptid);
6016 gdb_assert (tp != NULL);
6017
6018 if (tp->control.may_range_step)
6019 {
6020 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6021
6022 p += xsnprintf (p, endp - p, ";r%s,%s",
6023 phex_nz (tp->control.step_range_start,
6024 addr_size),
6025 phex_nz (tp->control.step_range_end,
6026 addr_size));
6027 }
6028 else
6029 p += xsnprintf (p, endp - p, ";s");
6030 }
0d8f58ca
PA
6031 else if (step)
6032 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6033 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6034 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6035 else
6036 p += xsnprintf (p, endp - p, ";c");
6037
6038 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
6039 {
6040 ptid_t nptid;
6041
6042 /* All (-1) threads of process. */
ba348170 6043 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
6044
6045 p += xsnprintf (p, endp - p, ":");
6046 p = write_ptid (p, endp, nptid);
6047 }
6048 else if (!ptid_equal (ptid, minus_one_ptid))
6049 {
6050 p += xsnprintf (p, endp - p, ":");
6051 p = write_ptid (p, endp, ptid);
6052 }
6053
6054 return p;
6055}
6056
799a2abe
PA
6057/* Clear the thread's private info on resume. */
6058
6059static void
6060resume_clear_thread_private_info (struct thread_info *thread)
6061{
6062 if (thread->priv != NULL)
6063 {
7aabaf9d
SM
6064 remote_thread_info *priv = get_remote_thread_info (thread);
6065
6066 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6067 priv->watch_data_address = 0;
799a2abe
PA
6068 }
6069}
6070
e5ef252a
PA
6071/* Append a vCont continue-with-signal action for threads that have a
6072 non-zero stop signal. */
6073
6b8edb51
PA
6074char *
6075remote_target::append_pending_thread_resumptions (char *p, char *endp,
6076 ptid_t ptid)
e5ef252a
PA
6077{
6078 struct thread_info *thread;
6079
034f788c 6080 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
6081 if (ptid_match (thread->ptid, ptid)
6082 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 6083 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
6084 {
6085 p = append_resumption (p, endp, thread->ptid,
6086 0, thread->suspend.stop_signal);
6087 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 6088 resume_clear_thread_private_info (thread);
e5ef252a
PA
6089 }
6090
6091 return p;
6092}
6093
7b68ffbb
PA
6094/* Set the target running, using the packets that use Hc
6095 (c/s/C/S). */
6096
6b8edb51
PA
6097void
6098remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6099 gdb_signal siggnal)
7b68ffbb
PA
6100{
6101 struct remote_state *rs = get_remote_state ();
6102 struct thread_info *thread;
6103 char *buf;
6104
6105 rs->last_sent_signal = siggnal;
6106 rs->last_sent_step = step;
6107
6108 /* The c/s/C/S resume packets use Hc, so set the continue
6109 thread. */
6110 if (ptid_equal (ptid, minus_one_ptid))
6111 set_continue_thread (any_thread_ptid);
6112 else
6113 set_continue_thread (ptid);
6114
6115 ALL_NON_EXITED_THREADS (thread)
6116 resume_clear_thread_private_info (thread);
6117
6118 buf = rs->buf;
6b8edb51 6119 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6120 {
6121 /* We don't pass signals to the target in reverse exec mode. */
6122 if (info_verbose && siggnal != GDB_SIGNAL_0)
6123 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6124 siggnal);
6125
6126 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6127 error (_("Remote reverse-step not supported."));
6128 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6129 error (_("Remote reverse-continue not supported."));
6130
6131 strcpy (buf, step ? "bs" : "bc");
6132 }
6133 else if (siggnal != GDB_SIGNAL_0)
6134 {
6135 buf[0] = step ? 'S' : 'C';
6136 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6137 buf[2] = tohex (((int) siggnal) & 0xf);
6138 buf[3] = '\0';
6139 }
6140 else
6141 strcpy (buf, step ? "s" : "c");
6142
6143 putpkt (buf);
6144}
6145
506fb367
DJ
6146/* Resume the remote inferior by using a "vCont" packet. The thread
6147 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
6148 resumed thread should be single-stepped and/or signalled. If PTID
6149 equals minus_one_ptid, then all threads are resumed; the thread to
6150 be stepped and/or signalled is given in the global INFERIOR_PTID.
6151 This function returns non-zero iff it resumes the inferior.
44eaed12 6152
7b68ffbb
PA
6153 This function issues a strict subset of all possible vCont commands
6154 at the moment. */
44eaed12 6155
6b8edb51
PA
6156int
6157remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6158 enum gdb_signal siggnal)
506fb367
DJ
6159{
6160 struct remote_state *rs = get_remote_state ();
82f73884
PA
6161 char *p;
6162 char *endp;
44eaed12 6163
7b68ffbb 6164 /* No reverse execution actions defined for vCont. */
6b8edb51 6165 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6166 return 0;
6167
4082afcc 6168 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6169 remote_vcont_probe ();
44eaed12 6170
4082afcc 6171 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6172 return 0;
44eaed12 6173
82f73884
PA
6174 p = rs->buf;
6175 endp = rs->buf + get_remote_packet_size ();
6176
506fb367
DJ
6177 /* If we could generate a wider range of packets, we'd have to worry
6178 about overflowing BUF. Should there be a generic
6179 "multi-part-packet" packet? */
6180
0d8f58ca
PA
6181 p += xsnprintf (p, endp - p, "vCont");
6182
79d7f229 6183 if (ptid_equal (ptid, magic_null_ptid))
c906108c 6184 {
79d7f229
PA
6185 /* MAGIC_NULL_PTID means that we don't have any active threads,
6186 so we don't have any TID numbers the inferior will
6187 understand. Make sure to only send forms that do not specify
6188 a TID. */
a9cbf802 6189 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6190 }
0d8f58ca 6191 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 6192 {
0d8f58ca
PA
6193 /* Resume all threads (of all processes, or of a single
6194 process), with preference for INFERIOR_PTID. This assumes
6195 inferior_ptid belongs to the set of all threads we are about
6196 to resume. */
a493e3e2 6197 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6198 {
0d8f58ca
PA
6199 /* Step inferior_ptid, with or without signal. */
6200 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6201 }
0d8f58ca 6202
e5ef252a
PA
6203 /* Also pass down any pending signaled resumption for other
6204 threads not the current. */
6205 p = append_pending_thread_resumptions (p, endp, ptid);
6206
0d8f58ca 6207 /* And continue others without a signal. */
a493e3e2 6208 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6209 }
6210 else
506fb367
DJ
6211 {
6212 /* Scheduler locking; resume only PTID. */
a9cbf802 6213 append_resumption (p, endp, ptid, step, siggnal);
506fb367 6214 }
c906108c 6215
82f73884
PA
6216 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6217 putpkt (rs->buf);
506fb367 6218
6efcd9a8 6219 if (target_is_non_stop_p ())
74531fed
PA
6220 {
6221 /* In non-stop, the stub replies to vCont with "OK". The stop
6222 reply will be reported asynchronously by means of a `%Stop'
6223 notification. */
6224 getpkt (&rs->buf, &rs->buf_size, 0);
6225 if (strcmp (rs->buf, "OK") != 0)
6226 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6227 }
6228
506fb367 6229 return 1;
c906108c 6230}
43ff13b4 6231
506fb367
DJ
6232/* Tell the remote machine to resume. */
6233
f6ac5f3d
PA
6234void
6235remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 6236{
d01949b6 6237 struct remote_state *rs = get_remote_state ();
43ff13b4 6238
85ad3aaf
PA
6239 /* When connected in non-stop mode, the core resumes threads
6240 individually. Resuming remote threads directly in target_resume
6241 would thus result in sending one packet per thread. Instead, to
6242 minimize roundtrip latency, here we just store the resume
6243 request; the actual remote resumption will be done in
6244 target_commit_resume / remote_commit_resume, where we'll be able
6245 to do vCont action coalescing. */
f6ac5f3d 6246 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6247 {
7aabaf9d 6248 remote_thread_info *remote_thr;
85ad3aaf
PA
6249
6250 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
7aabaf9d 6251 remote_thr = get_remote_thread_info (inferior_ptid);
85ad3aaf 6252 else
7aabaf9d
SM
6253 remote_thr = get_remote_thread_info (ptid);
6254
85ad3aaf
PA
6255 remote_thr->last_resume_step = step;
6256 remote_thr->last_resume_sig = siggnal;
6257 return;
6258 }
6259
722247f1
YQ
6260 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6261 (explained in remote-notif.c:handle_notification) so
6262 remote_notif_process is not called. We need find a place where
6263 it is safe to start a 'vNotif' sequence. It is good to do it
6264 before resuming inferior, because inferior was stopped and no RSP
6265 traffic at that moment. */
6efcd9a8 6266 if (!target_is_non_stop_p ())
5965e028 6267 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6268
f6ac5f3d 6269 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6270
7b68ffbb
PA
6271 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6272 if (!remote_resume_with_vcont (ptid, step, siggnal))
6b8edb51 6273 remote_resume_with_hc (ptid, step, siggnal);
43ff13b4 6274
2acceee2 6275 /* We are about to start executing the inferior, let's register it
0df8b418
MS
6276 with the event loop. NOTE: this is the one place where all the
6277 execution commands end up. We could alternatively do this in each
23860348 6278 of the execution commands in infcmd.c. */
2acceee2
JM
6279 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6280 into infcmd.c in order to allow inferior function calls to work
23860348 6281 NOT asynchronously. */
362646f5 6282 if (target_can_async_p ())
6a3753b3 6283 target_async (1);
e24a49d8
PA
6284
6285 /* We've just told the target to resume. The remote server will
6286 wait for the inferior to stop, and then send a stop reply. In
6287 the mean time, we can't start another command/query ourselves
74531fed
PA
6288 because the stub wouldn't be ready to process it. This applies
6289 only to the base all-stop protocol, however. In non-stop (which
6290 only supports vCont), the stub replies with an "OK", and is
6291 immediate able to process further serial input. */
6efcd9a8 6292 if (!target_is_non_stop_p ())
74531fed 6293 rs->waiting_for_stop_reply = 1;
43ff13b4 6294}
85ad3aaf 6295
85ad3aaf
PA
6296static int is_pending_fork_parent_thread (struct thread_info *thread);
6297
6298/* Private per-inferior info for target remote processes. */
6299
089354bb 6300struct remote_inferior : public private_inferior
85ad3aaf
PA
6301{
6302 /* Whether we can send a wildcard vCont for this process. */
089354bb 6303 bool may_wildcard_vcont = true;
85ad3aaf
PA
6304};
6305
089354bb
SM
6306/* Get the remote private inferior data associated to INF. */
6307
6308static remote_inferior *
6309get_remote_inferior (inferior *inf)
6310{
6311 if (inf->priv == NULL)
6312 inf->priv.reset (new remote_inferior);
6313
6314 return static_cast<remote_inferior *> (inf->priv.get ());
6315}
6316
f5db4863 6317/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6318 outgoing packet buffer. This is used to send multiple vCont
6319 packets if we have more actions than would fit a single packet. */
6320
f5db4863 6321class vcont_builder
85ad3aaf 6322{
f5db4863 6323public:
6b8edb51
PA
6324 explicit vcont_builder (remote_target *remote)
6325 : m_remote (remote)
f5db4863
PA
6326 {
6327 restart ();
6328 }
6329
6330 void flush ();
6331 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6332
6333private:
6334 void restart ();
6335
6b8edb51
PA
6336 /* The remote target. */
6337 remote_target *m_remote;
6338
85ad3aaf
PA
6339 /* Pointer to the first action. P points here if no action has been
6340 appended yet. */
f5db4863 6341 char *m_first_action;
85ad3aaf
PA
6342
6343 /* Where the next action will be appended. */
f5db4863 6344 char *m_p;
85ad3aaf
PA
6345
6346 /* The end of the buffer. Must never write past this. */
f5db4863 6347 char *m_endp;
85ad3aaf
PA
6348};
6349
6350/* Prepare the outgoing buffer for a new vCont packet. */
6351
f5db4863
PA
6352void
6353vcont_builder::restart ()
85ad3aaf 6354{
6b8edb51 6355 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6356
f5db4863 6357 m_p = rs->buf;
6b8edb51 6358 m_endp = rs->buf + m_remote->get_remote_packet_size ();
f5db4863
PA
6359 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6360 m_first_action = m_p;
85ad3aaf
PA
6361}
6362
6363/* If the vCont packet being built has any action, send it to the
6364 remote end. */
6365
f5db4863
PA
6366void
6367vcont_builder::flush ()
85ad3aaf
PA
6368{
6369 struct remote_state *rs;
6370
f5db4863 6371 if (m_p == m_first_action)
85ad3aaf
PA
6372 return;
6373
6b8edb51
PA
6374 rs = m_remote->get_remote_state ();
6375 m_remote->putpkt (rs->buf);
6376 m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
85ad3aaf
PA
6377 if (strcmp (rs->buf, "OK") != 0)
6378 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6379}
6380
6381/* The largest action is range-stepping, with its two addresses. This
6382 is more than sufficient. If a new, bigger action is created, it'll
6383 quickly trigger a failed assertion in append_resumption (and we'll
6384 just bump this). */
6385#define MAX_ACTION_SIZE 200
6386
6387/* Append a new vCont action in the outgoing packet being built. If
6388 the action doesn't fit the packet along with previous actions, push
6389 what we've got so far to the remote end and start over a new vCont
6390 packet (with the new action). */
6391
f5db4863
PA
6392void
6393vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6394{
6395 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6396
6b8edb51
PA
6397 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6398 ptid, step, siggnal);
85ad3aaf
PA
6399
6400 /* Check whether this new action would fit in the vCont packet along
6401 with previous actions. If not, send what we've got so far and
6402 start a new vCont packet. */
f5db4863
PA
6403 size_t rsize = endp - buf;
6404 if (rsize > m_endp - m_p)
85ad3aaf 6405 {
f5db4863
PA
6406 flush ();
6407 restart ();
85ad3aaf
PA
6408
6409 /* Should now fit. */
f5db4863 6410 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6411 }
6412
f5db4863
PA
6413 memcpy (m_p, buf, rsize);
6414 m_p += rsize;
6415 *m_p = '\0';
85ad3aaf
PA
6416}
6417
6418/* to_commit_resume implementation. */
6419
f6ac5f3d
PA
6420void
6421remote_target::commit_resume ()
85ad3aaf 6422{
85ad3aaf
PA
6423 struct inferior *inf;
6424 struct thread_info *tp;
6425 int any_process_wildcard;
6426 int may_global_wildcard_vcont;
85ad3aaf
PA
6427
6428 /* If connected in all-stop mode, we'd send the remote resume
6429 request directly from remote_resume. Likewise if
6430 reverse-debugging, as there are no defined vCont actions for
6431 reverse execution. */
f6ac5f3d 6432 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6433 return;
6434
6435 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6436 instead of resuming all threads of each process individually.
6437 However, if any thread of a process must remain halted, we can't
6438 send wildcard resumes and must send one action per thread.
6439
6440 Care must be taken to not resume threads/processes the server
6441 side already told us are stopped, but the core doesn't know about
6442 yet, because the events are still in the vStopped notification
6443 queue. For example:
6444
6445 #1 => vCont s:p1.1;c
6446 #2 <= OK
6447 #3 <= %Stopped T05 p1.1
6448 #4 => vStopped
6449 #5 <= T05 p1.2
6450 #6 => vStopped
6451 #7 <= OK
6452 #8 (infrun handles the stop for p1.1 and continues stepping)
6453 #9 => vCont s:p1.1;c
6454
6455 The last vCont above would resume thread p1.2 by mistake, because
6456 the server has no idea that the event for p1.2 had not been
6457 handled yet.
6458
6459 The server side must similarly ignore resume actions for the
6460 thread that has a pending %Stopped notification (and any other
6461 threads with events pending), until GDB acks the notification
6462 with vStopped. Otherwise, e.g., the following case is
6463 mishandled:
6464
6465 #1 => g (or any other packet)
6466 #2 <= [registers]
6467 #3 <= %Stopped T05 p1.2
6468 #4 => vCont s:p1.1;c
6469 #5 <= OK
6470
6471 Above, the server must not resume thread p1.2. GDB can't know
6472 that p1.2 stopped until it acks the %Stopped notification, and
6473 since from GDB's perspective all threads should be running, it
6474 sends a "c" action.
6475
6476 Finally, special care must also be given to handling fork/vfork
6477 events. A (v)fork event actually tells us that two processes
6478 stopped -- the parent and the child. Until we follow the fork,
6479 we must not resume the child. Therefore, if we have a pending
6480 fork follow, we must not send a global wildcard resume action
6481 (vCont;c). We can still send process-wide wildcards though. */
6482
6483 /* Start by assuming a global wildcard (vCont;c) is possible. */
6484 may_global_wildcard_vcont = 1;
6485
6486 /* And assume every process is individually wildcard-able too. */
6487 ALL_NON_EXITED_INFERIORS (inf)
6488 {
089354bb
SM
6489 remote_inferior *priv = get_remote_inferior (inf);
6490
6491 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6492 }
6493
6494 /* Check for any pending events (not reported or processed yet) and
6495 disable process and global wildcard resumes appropriately. */
6496 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6497
6498 ALL_NON_EXITED_THREADS (tp)
6499 {
6500 /* If a thread of a process is not meant to be resumed, then we
6501 can't wildcard that process. */
6502 if (!tp->executing)
6503 {
089354bb 6504 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6505
6506 /* And if we can't wildcard a process, we can't wildcard
6507 everything either. */
6508 may_global_wildcard_vcont = 0;
6509 continue;
6510 }
6511
6512 /* If a thread is the parent of an unfollowed fork, then we
6513 can't do a global wildcard, as that would resume the fork
6514 child. */
6515 if (is_pending_fork_parent_thread (tp))
6516 may_global_wildcard_vcont = 0;
6517 }
6518
6519 /* Now let's build the vCont packet(s). Actions must be appended
6520 from narrower to wider scopes (thread -> process -> global). If
6521 we end up with too many actions for a single packet vcont_builder
6522 flushes the current vCont packet to the remote side and starts a
6523 new one. */
6b8edb51 6524 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
6525
6526 /* Threads first. */
6527 ALL_NON_EXITED_THREADS (tp)
6528 {
7aabaf9d 6529 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf
PA
6530
6531 if (!tp->executing || remote_thr->vcont_resumed)
6532 continue;
6533
6534 gdb_assert (!thread_is_in_step_over_chain (tp));
6535
6536 if (!remote_thr->last_resume_step
6537 && remote_thr->last_resume_sig == GDB_SIGNAL_0
089354bb 6538 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
85ad3aaf
PA
6539 {
6540 /* We'll send a wildcard resume instead. */
6541 remote_thr->vcont_resumed = 1;
6542 continue;
6543 }
6544
f5db4863 6545 vcont_builder.push_action (tp->ptid,
85ad3aaf
PA
6546 remote_thr->last_resume_step,
6547 remote_thr->last_resume_sig);
6548 remote_thr->vcont_resumed = 1;
6549 }
6550
6551 /* Now check whether we can send any process-wide wildcard. This is
6552 to avoid sending a global wildcard in the case nothing is
6553 supposed to be resumed. */
6554 any_process_wildcard = 0;
6555
6556 ALL_NON_EXITED_INFERIORS (inf)
6557 {
089354bb 6558 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf
PA
6559 {
6560 any_process_wildcard = 1;
6561 break;
6562 }
6563 }
6564
6565 if (any_process_wildcard)
6566 {
6567 /* If all processes are wildcard-able, then send a single "c"
6568 action, otherwise, send an "all (-1) threads of process"
6569 continue action for each running process, if any. */
6570 if (may_global_wildcard_vcont)
6571 {
f5db4863
PA
6572 vcont_builder.push_action (minus_one_ptid,
6573 false, GDB_SIGNAL_0);
85ad3aaf
PA
6574 }
6575 else
6576 {
6577 ALL_NON_EXITED_INFERIORS (inf)
6578 {
089354bb 6579 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6580 {
f5db4863
PA
6581 vcont_builder.push_action (pid_to_ptid (inf->pid),
6582 false, GDB_SIGNAL_0);
85ad3aaf
PA
6583 }
6584 }
6585 }
6586 }
6587
f5db4863 6588 vcont_builder.flush ();
85ad3aaf
PA
6589}
6590
c906108c 6591\f
43ff13b4 6592
74531fed
PA
6593/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6594 thread, all threads of a remote process, or all threads of all
6595 processes. */
6596
6b8edb51
PA
6597void
6598remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
6599{
6600 struct remote_state *rs = get_remote_state ();
6601 char *p = rs->buf;
6602 char *endp = rs->buf + get_remote_packet_size ();
74531fed 6603
4082afcc 6604 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6605 remote_vcont_probe ();
74531fed 6606
d458bd84 6607 if (!rs->supports_vCont.t)
74531fed
PA
6608 error (_("Remote server does not support stopping threads"));
6609
f91d3df5
PA
6610 if (ptid_equal (ptid, minus_one_ptid)
6611 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
6612 p += xsnprintf (p, endp - p, "vCont;t");
6613 else
6614 {
6615 ptid_t nptid;
6616
74531fed
PA
6617 p += xsnprintf (p, endp - p, "vCont;t:");
6618
6619 if (ptid_is_pid (ptid))
6620 /* All (-1) threads of process. */
ba348170 6621 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
6622 else
6623 {
6624 /* Small optimization: if we already have a stop reply for
6625 this thread, no use in telling the stub we want this
6626 stopped. */
6627 if (peek_stop_reply (ptid))
6628 return;
6629
6630 nptid = ptid;
6631 }
6632
a9cbf802 6633 write_ptid (p, endp, nptid);
74531fed
PA
6634 }
6635
6636 /* In non-stop, we get an immediate OK reply. The stop reply will
6637 come in asynchronously by notification. */
6638 putpkt (rs->buf);
6639 getpkt (&rs->buf, &rs->buf_size, 0);
6640 if (strcmp (rs->buf, "OK") != 0)
6641 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6642}
6643
bfedc46a
PA
6644/* All-stop version of target_interrupt. Sends a break or a ^C to
6645 interrupt the remote target. It is undefined which thread of which
6646 process reports the interrupt. */
74531fed 6647
6b8edb51
PA
6648void
6649remote_target::remote_interrupt_as ()
74531fed
PA
6650{
6651 struct remote_state *rs = get_remote_state ();
6652
3a29589a
DJ
6653 rs->ctrlc_pending_p = 1;
6654
74531fed
PA
6655 /* If the inferior is stopped already, but the core didn't know
6656 about it yet, just ignore the request. The cached wait status
6657 will be collected in remote_wait. */
6658 if (rs->cached_wait_status)
6659 return;
6660
9a7071a8
JB
6661 /* Send interrupt_sequence to remote target. */
6662 send_interrupt_sequence ();
74531fed
PA
6663}
6664
de979965
PA
6665/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6666 the remote target. It is undefined which thread of which process
e42de8c7
PA
6667 reports the interrupt. Throws an error if the packet is not
6668 supported by the server. */
de979965 6669
6b8edb51
PA
6670void
6671remote_target::remote_interrupt_ns ()
de979965
PA
6672{
6673 struct remote_state *rs = get_remote_state ();
6674 char *p = rs->buf;
6675 char *endp = rs->buf + get_remote_packet_size ();
6676
6677 xsnprintf (p, endp - p, "vCtrlC");
6678
6679 /* In non-stop, we get an immediate OK reply. The stop reply will
6680 come in asynchronously by notification. */
6681 putpkt (rs->buf);
6682 getpkt (&rs->buf, &rs->buf_size, 0);
6683
6684 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6685 {
6686 case PACKET_OK:
6687 break;
6688 case PACKET_UNKNOWN:
e42de8c7 6689 error (_("No support for interrupting the remote target."));
de979965
PA
6690 case PACKET_ERROR:
6691 error (_("Interrupting target failed: %s"), rs->buf);
6692 }
de979965
PA
6693}
6694
bfedc46a 6695/* Implement the to_stop function for the remote targets. */
74531fed 6696
f6ac5f3d
PA
6697void
6698remote_target::stop (ptid_t ptid)
c906108c 6699{
7a292a7a 6700 if (remote_debug)
0f71a2f6 6701 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6702
6efcd9a8 6703 if (target_is_non_stop_p ())
74531fed 6704 remote_stop_ns (ptid);
c906108c 6705 else
bfedc46a
PA
6706 {
6707 /* We don't currently have a way to transparently pause the
6708 remote target in all-stop mode. Interrupt it instead. */
de979965 6709 remote_interrupt_as ();
bfedc46a
PA
6710 }
6711}
6712
6713/* Implement the to_interrupt function for the remote targets. */
6714
f6ac5f3d
PA
6715void
6716remote_target::interrupt ()
bfedc46a
PA
6717{
6718 if (remote_debug)
6719 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6720
e42de8c7
PA
6721 if (target_is_non_stop_p ())
6722 remote_interrupt_ns ();
bfedc46a 6723 else
e42de8c7 6724 remote_interrupt_as ();
c906108c
SS
6725}
6726
93692b58
PA
6727/* Implement the to_pass_ctrlc function for the remote targets. */
6728
f6ac5f3d
PA
6729void
6730remote_target::pass_ctrlc ()
93692b58
PA
6731{
6732 struct remote_state *rs = get_remote_state ();
6733
6734 if (remote_debug)
6735 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6736
6737 /* If we're starting up, we're not fully synced yet. Quit
6738 immediately. */
6739 if (rs->starting_up)
6740 quit ();
6741 /* If ^C has already been sent once, offer to disconnect. */
6742 else if (rs->ctrlc_pending_p)
6743 interrupt_query ();
6744 else
e671cd59 6745 target_interrupt ();
93692b58
PA
6746}
6747
c906108c
SS
6748/* Ask the user what to do when an interrupt is received. */
6749
6b8edb51
PA
6750void
6751remote_target::interrupt_query ()
c906108c 6752{
abc56d60 6753 struct remote_state *rs = get_remote_state ();
c906108c 6754
abc56d60 6755 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6756 {
abc56d60
PA
6757 if (query (_("The target is not responding to interrupt requests.\n"
6758 "Stop debugging it? ")))
74531fed 6759 {
78a095c3 6760 remote_unpush_target ();
abc56d60 6761 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6762 }
6763 }
abc56d60
PA
6764 else
6765 {
6766 if (query (_("Interrupted while waiting for the program.\n"
6767 "Give up waiting? ")))
6768 quit ();
6769 }
c906108c
SS
6770}
6771
6426a772
JM
6772/* Enable/disable target terminal ownership. Most targets can use
6773 terminal groups to control terminal ownership. Remote targets are
6774 different in that explicit transfer of ownership to/from GDB/target
23860348 6775 is required. */
6426a772 6776
f6ac5f3d
PA
6777void
6778remote_target::terminal_inferior ()
6426a772 6779{
6426a772
JM
6780 /* NOTE: At this point we could also register our selves as the
6781 recipient of all input. Any characters typed could then be
23860348 6782 passed on down to the target. */
6426a772
JM
6783}
6784
f6ac5f3d
PA
6785void
6786remote_target::terminal_ours ()
6426a772 6787{
6426a772
JM
6788}
6789
176a6961 6790static void
917317f4 6791remote_console_output (char *msg)
c906108c
SS
6792{
6793 char *p;
6794
c5aa993b 6795 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6796 {
6797 char tb[2];
6798 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6799
c906108c
SS
6800 tb[0] = c;
6801 tb[1] = 0;
43ff13b4 6802 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6803 }
00db5b94
PA
6804 gdb_flush (gdb_stdtarg);
6805}
74531fed 6806
74531fed
PA
6807DEF_VEC_O(cached_reg_t);
6808
722247f1 6809typedef struct stop_reply
74531fed 6810{
722247f1 6811 struct notif_event base;
74531fed 6812
722247f1 6813 /* The identifier of the thread about this event */
74531fed
PA
6814 ptid_t ptid;
6815
340e3c99 6816 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6817 connection, represented by a remote_state object, is closed,
6818 all the associated stop_reply events should be released. */
6819 struct remote_state *rs;
6820
74531fed
PA
6821 struct target_waitstatus ws;
6822
5cd63fda
PA
6823 /* The architecture associated with the expedited registers. */
6824 gdbarch *arch;
6825
15148d6a
PA
6826 /* Expedited registers. This makes remote debugging a bit more
6827 efficient for those targets that provide critical registers as
6828 part of their normal status mechanism (as another roundtrip to
6829 fetch them is avoided). */
74531fed
PA
6830 VEC(cached_reg_t) *regcache;
6831
f7e6eed5
PA
6832 enum target_stop_reason stop_reason;
6833
74531fed
PA
6834 CORE_ADDR watch_data_address;
6835
dc146f7c 6836 int core;
722247f1 6837} *stop_reply_p;
a744cf53 6838
74531fed
PA
6839static void
6840stop_reply_xfree (struct stop_reply *r)
6841{
f48ff2a7 6842 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6843}
6844
221e1a37
PA
6845/* Return the length of the stop reply queue. */
6846
6b8edb51
PA
6847int
6848remote_target::stop_reply_queue_length ()
221e1a37 6849{
6b8edb51
PA
6850 remote_state *rs = get_remote_state ();
6851 return QUEUE_length (stop_reply_p, rs->stop_reply_queue);
221e1a37
PA
6852}
6853
6b8edb51
PA
6854void
6855remote_notif_stop_parse (remote_target *remote,
6856 struct notif_client *self, char *buf,
722247f1
YQ
6857 struct notif_event *event)
6858{
6b8edb51 6859 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
6860}
6861
6862static void
6b8edb51
PA
6863remote_notif_stop_ack (remote_target *remote,
6864 struct notif_client *self, char *buf,
722247f1
YQ
6865 struct notif_event *event)
6866{
6867 struct stop_reply *stop_reply = (struct stop_reply *) event;
6868
6869 /* acknowledge */
6b8edb51 6870 putpkt (remote, self->ack_command);
722247f1
YQ
6871
6872 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6b8edb51 6873 {
722247f1
YQ
6874 /* We got an unknown stop reply. */
6875 error (_("Unknown stop reply"));
6b8edb51 6876 }
722247f1 6877
6b8edb51 6878 remote->push_stop_reply (stop_reply);
722247f1
YQ
6879}
6880
6881static int
6b8edb51
PA
6882remote_notif_stop_can_get_pending_events (remote_target *remote,
6883 struct notif_client *self)
722247f1
YQ
6884{
6885 /* We can't get pending events in remote_notif_process for
6886 notification stop, and we have to do this in remote_wait_ns
6887 instead. If we fetch all queued events from stub, remote stub
6888 may exit and we have no chance to process them back in
6889 remote_wait_ns. */
6b8edb51
PA
6890 remote_state *rs = remote->get_remote_state ();
6891 mark_async_event_handler (rs->remote_async_inferior_event_token);
722247f1
YQ
6892 return 0;
6893}
6894
6895static void
6896stop_reply_dtr (struct notif_event *event)
6897{
6898 struct stop_reply *r = (struct stop_reply *) event;
d1dff226
AH
6899 cached_reg_t *reg;
6900 int ix;
6901
6902 for (ix = 0;
6903 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6904 ix++)
6905 xfree (reg->data);
722247f1
YQ
6906
6907 VEC_free (cached_reg_t, r->regcache);
6908}
6909
6910static struct notif_event *
6911remote_notif_stop_alloc_reply (void)
6912{
8d749320
SM
6913 /* We cast to a pointer to the "base class". */
6914 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6915
6916 r->dtr = stop_reply_dtr;
6917
6918 return r;
6919}
6920
6921/* A client of notification Stop. */
6922
6923struct notif_client notif_client_stop =
6924{
6925 "Stop",
6926 "vStopped",
6927 remote_notif_stop_parse,
6928 remote_notif_stop_ack,
6929 remote_notif_stop_can_get_pending_events,
6930 remote_notif_stop_alloc_reply,
f48ff2a7 6931 REMOTE_NOTIF_STOP,
722247f1
YQ
6932};
6933
6934/* A parameter to pass data in and out. */
6935
6936struct queue_iter_param
6937{
6b8edb51 6938 remote_target *remote;
722247f1
YQ
6939 void *input;
6940 struct stop_reply *output;
6941};
6942
85ad3aaf 6943/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6944 the pid of the process that owns the threads we want to check, or
6945 -1 if we want to check all threads. */
6946
6947static int
6948is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6949 ptid_t thread_ptid)
6950{
6951 if (ws->kind == TARGET_WAITKIND_FORKED
6952 || ws->kind == TARGET_WAITKIND_VFORKED)
6953 {
6954 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6955 return 1;
6956 }
6957
6958 return 0;
6959}
6960
85ad3aaf
PA
6961/* Return the thread's pending status used to determine whether the
6962 thread is a fork parent stopped at a fork event. */
6963
6964static struct target_waitstatus *
6965thread_pending_fork_status (struct thread_info *thread)
6966{
6967 if (thread->suspend.waitstatus_pending_p)
6968 return &thread->suspend.waitstatus;
6969 else
6970 return &thread->pending_follow;
6971}
6972
6973/* Determine if THREAD is a pending fork parent thread. */
6974
6975static int
6976is_pending_fork_parent_thread (struct thread_info *thread)
6977{
6978 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6979 int pid = -1;
6980
6981 return is_pending_fork_parent (ws, pid, thread->ptid);
6982}
6983
cbb8991c
DB
6984/* Check whether EVENT is a fork event, and if it is, remove the
6985 fork child from the context list passed in DATA. */
6986
6987static int
6988remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6989 QUEUE_ITER (stop_reply_p) *iter,
6990 stop_reply_p event,
6991 void *data)
6992{
19ba03f4
SM
6993 struct queue_iter_param *param = (struct queue_iter_param *) data;
6994 struct threads_listing_context *context
6995 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6996
6997 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6998 || event->ws.kind == TARGET_WAITKIND_VFORKED
6999 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
21fe1c75 7000 context->remove_thread (event->ws.value.related_pid);
cbb8991c
DB
7001
7002 return 1;
7003}
7004
7005/* If CONTEXT contains any fork child threads that have not been
7006 reported yet, remove them from the CONTEXT list. If such a
7007 thread exists it is because we are stopped at a fork catchpoint
7008 and have not yet called follow_fork, which will set up the
7009 host-side data structures for the new process. */
7010
6b8edb51
PA
7011void
7012remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c
DB
7013{
7014 struct thread_info * thread;
7015 int pid = -1;
7016 struct notif_client *notif = &notif_client_stop;
7017 struct queue_iter_param param;
7018
7019 /* For any threads stopped at a fork event, remove the corresponding
7020 fork child threads from the CONTEXT list. */
7021 ALL_NON_EXITED_THREADS (thread)
7022 {
85ad3aaf 7023 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
7024
7025 if (is_pending_fork_parent (ws, pid, thread->ptid))
21fe1c75 7026 context->remove_thread (ws->value.related_pid);
cbb8991c
DB
7027 }
7028
7029 /* Check for any pending fork events (not reported or processed yet)
7030 in process PID and remove those fork child threads from the
7031 CONTEXT list as well. */
7032 remote_notif_get_pending_events (notif);
6b8edb51 7033 param.remote = this;
cbb8991c
DB
7034 param.input = context;
7035 param.output = NULL;
6b8edb51 7036 QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
cbb8991c
DB
7037 remove_child_of_pending_fork, &param);
7038}
7039
6b8edb51
PA
7040/* Callback data for
7041 check_pending_event_prevents_wildcard_vcont_callback. */
7042struct check_pending_event_prevents_wildcard_vcont_callback_data
7043{
7044 /* The remote target. */
7045 remote_target *remote;
7046
7047 /* Whether we can do a global wildcard (vCont;c) */
7048 int *may_global_wildcard_vcont;
7049};
7050
85ad3aaf
PA
7051/* Check whether EVENT would prevent a global or process wildcard
7052 vCont action. */
7053
7054static int
7055check_pending_event_prevents_wildcard_vcont_callback
7056 (QUEUE (stop_reply_p) *q,
7057 QUEUE_ITER (stop_reply_p) *iter,
7058 stop_reply_p event,
7059 void *data)
7060{
7061 struct inferior *inf;
6b8edb51 7062 auto *cb_data = (check_pending_event_prevents_wildcard_vcont_callback_data *) data;
85ad3aaf
PA
7063
7064 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7065 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7066 return 1;
7067
7068 if (event->ws.kind == TARGET_WAITKIND_FORKED
7069 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6b8edb51 7070 *cb_data->may_global_wildcard_vcont = 0;
85ad3aaf
PA
7071
7072 inf = find_inferior_ptid (event->ptid);
7073
7074 /* This may be the first time we heard about this process.
7075 Regardless, we must not do a global wildcard resume, otherwise
7076 we'd resume this process too. */
6b8edb51 7077 *cb_data->may_global_wildcard_vcont = 0;
85ad3aaf 7078 if (inf != NULL)
089354bb 7079 get_remote_inferior (inf)->may_wildcard_vcont = false;
85ad3aaf
PA
7080
7081 return 1;
7082}
7083
7084/* Check whether any event pending in the vStopped queue would prevent
7085 a global or process wildcard vCont action. Clear
7086 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7087 and clear the event inferior's may_wildcard_vcont flag if we can't
7088 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7089
6b8edb51
PA
7090void
7091remote_target::check_pending_events_prevent_wildcard_vcont
7092 (int *may_global_wildcard)
85ad3aaf
PA
7093{
7094 struct notif_client *notif = &notif_client_stop;
6b8edb51
PA
7095 check_pending_event_prevents_wildcard_vcont_callback_data cb_data
7096 {this, may_global_wildcard};
85ad3aaf
PA
7097
7098 remote_notif_get_pending_events (notif);
6b8edb51 7099 QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
85ad3aaf 7100 check_pending_event_prevents_wildcard_vcont_callback,
6b8edb51 7101 &cb_data);
85ad3aaf
PA
7102}
7103
f48ff2a7
YQ
7104/* Remove stop replies in the queue if its pid is equal to the given
7105 inferior's pid. */
722247f1
YQ
7106
7107static int
f48ff2a7
YQ
7108remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
7109 QUEUE_ITER (stop_reply_p) *iter,
7110 stop_reply_p event,
7111 void *data)
722247f1 7112{
19ba03f4
SM
7113 struct queue_iter_param *param = (struct queue_iter_param *) data;
7114 struct inferior *inf = (struct inferior *) param->input;
722247f1 7115
f48ff2a7 7116 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
7117 {
7118 stop_reply_xfree (event);
7119 QUEUE_remove_elem (stop_reply_p, q, iter);
7120 }
7121
7122 return 1;
7123}
7124
f48ff2a7 7125/* Discard all pending stop replies of inferior INF. */
c906108c 7126
6b8edb51
PA
7127void
7128remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7129{
722247f1 7130 struct queue_iter_param param;
f48ff2a7
YQ
7131 struct stop_reply *reply;
7132 struct remote_state *rs = get_remote_state ();
7133 struct remote_notif_state *rns = rs->notif_state;
7134
7135 /* This function can be notified when an inferior exists. When the
7136 target is not remote, the notification state is NULL. */
7137 if (rs->remote_desc == NULL)
7138 return;
7139
7140 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7141
74531fed 7142 /* Discard the in-flight notification. */
f48ff2a7 7143 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 7144 {
722247f1 7145 stop_reply_xfree (reply);
f48ff2a7 7146 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 7147 }
c906108c 7148
6b8edb51 7149 param.remote = this;
722247f1
YQ
7150 param.input = inf;
7151 param.output = NULL;
74531fed
PA
7152 /* Discard the stop replies we have already pulled with
7153 vStopped. */
6b8edb51 7154 QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
f48ff2a7
YQ
7155 remove_stop_reply_for_inferior, &param);
7156}
7157
bcc75809
YQ
7158/* If its remote state is equal to the given remote state,
7159 remove EVENT from the stop reply queue. */
7160
7161static int
7162remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
7163 QUEUE_ITER (stop_reply_p) *iter,
7164 stop_reply_p event,
7165 void *data)
7166{
19ba03f4
SM
7167 struct queue_iter_param *param = (struct queue_iter_param *) data;
7168 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
7169
7170 if (event->rs == rs)
7171 {
7172 stop_reply_xfree (event);
7173 QUEUE_remove_elem (stop_reply_p, q, iter);
7174 }
7175
7176 return 1;
7177}
7178
7179/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7180
6b8edb51
PA
7181void
7182remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7183{
6b8edb51 7184 remote_state *rs = get_remote_state ();
f48ff2a7
YQ
7185 struct queue_iter_param param;
7186
6b8edb51 7187 param.remote = this;
bcc75809 7188 param.input = rs;
f48ff2a7
YQ
7189 param.output = NULL;
7190 /* Discard the stop replies we have already pulled with
7191 vStopped. */
6b8edb51 7192 QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
bcc75809 7193 remove_stop_reply_of_remote_state, &param);
722247f1 7194}
74531fed 7195
722247f1
YQ
7196/* A parameter to pass data in and out. */
7197
7198static int
7199remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
7200 QUEUE_ITER (stop_reply_p) *iter,
7201 stop_reply_p event,
7202 void *data)
7203{
19ba03f4
SM
7204 struct queue_iter_param *param = (struct queue_iter_param *) data;
7205 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
7206
7207 if (ptid_match (event->ptid, *ptid))
7208 {
7209 param->output = event;
7210 QUEUE_remove_elem (stop_reply_p, q, iter);
7211 return 0;
c8e38a49 7212 }
722247f1
YQ
7213
7214 return 1;
74531fed 7215}
43ff13b4 7216
722247f1
YQ
7217/* Remove the first reply in 'stop_reply_queue' which matches
7218 PTID. */
2e9f7625 7219
6b8edb51
PA
7220struct stop_reply *
7221remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7222{
722247f1
YQ
7223 struct queue_iter_param param;
7224
6b8edb51 7225 param.remote = this;
722247f1
YQ
7226 param.input = &ptid;
7227 param.output = NULL;
7228
6b8edb51 7229 QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
722247f1
YQ
7230 remote_notif_remove_once_on_match, &param);
7231 if (notif_debug)
7232 fprintf_unfiltered (gdb_stdlog,
7233 "notif: discard queued event: 'Stop' in %s\n",
7234 target_pid_to_str (ptid));
a744cf53 7235
722247f1 7236 return param.output;
74531fed 7237}
75c99385 7238
74531fed
PA
7239/* Look for a queued stop reply belonging to PTID. If one is found,
7240 remove it from the queue, and return it. Returns NULL if none is
7241 found. If there are still queued events left to process, tell the
7242 event loop to get back to target_wait soon. */
e24a49d8 7243
6b8edb51
PA
7244struct stop_reply *
7245remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7246{
722247f1 7247 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7248
6b8edb51
PA
7249 if (!QUEUE_is_empty (stop_reply_p, get_remote_state ()->stop_reply_queue))
7250 {
7251 remote_state *rs = get_remote_state ();
7252 /* There's still at least an event left. */
7253 mark_async_event_handler (rs->remote_async_inferior_event_token);
7254 }
74531fed 7255
722247f1 7256 return r;
74531fed
PA
7257}
7258
7259/* Push a fully parsed stop reply in the stop reply queue. Since we
7260 know that we now have at least one queued event left to pass to the
7261 core side, tell the event loop to get back to target_wait soon. */
7262
6b8edb51
PA
7263void
7264remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7265{
6b8edb51
PA
7266 remote_state *rs = get_remote_state ();
7267 QUEUE_enque (stop_reply_p, rs->stop_reply_queue, new_event);
74531fed 7268
722247f1
YQ
7269 if (notif_debug)
7270 fprintf_unfiltered (gdb_stdlog,
7271 "notif: push 'Stop' %s to queue %d\n",
7272 target_pid_to_str (new_event->ptid),
7273 QUEUE_length (stop_reply_p,
6b8edb51 7274 rs->stop_reply_queue));
74531fed 7275
6b8edb51 7276 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
7277}
7278
722247f1
YQ
7279static int
7280stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
7281 QUEUE_ITER (stop_reply_p) *iter,
7282 struct stop_reply *event,
7283 void *data)
7284{
19ba03f4 7285 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
7286
7287 return !(ptid_equal (*ptid, event->ptid)
7288 && event->ws.kind == TARGET_WAITKIND_STOPPED);
7289}
7290
74531fed
PA
7291/* Returns true if we have a stop reply for PTID. */
7292
6b8edb51
PA
7293int
7294remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7295{
6b8edb51
PA
7296 remote_state *rs = get_remote_state ();
7297 return !QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
722247f1 7298 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
7299}
7300
26d56a93
SL
7301/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7302 starting with P and ending with PEND matches PREFIX. */
7303
7304static int
7305strprefix (const char *p, const char *pend, const char *prefix)
7306{
7307 for ( ; p < pend; p++, prefix++)
7308 if (*p != *prefix)
7309 return 0;
7310 return *prefix == '\0';
7311}
7312
74531fed
PA
7313/* Parse the stop reply in BUF. Either the function succeeds, and the
7314 result is stored in EVENT, or throws an error. */
7315
6b8edb51
PA
7316void
7317remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
74531fed 7318{
5cd63fda 7319 remote_arch_state *rsa = NULL;
74531fed 7320 ULONGEST addr;
256642e8 7321 const char *p;
94585166 7322 int skipregs = 0;
74531fed
PA
7323
7324 event->ptid = null_ptid;
bcc75809 7325 event->rs = get_remote_state ();
74531fed
PA
7326 event->ws.kind = TARGET_WAITKIND_IGNORE;
7327 event->ws.value.integer = 0;
f7e6eed5 7328 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 7329 event->regcache = NULL;
dc146f7c 7330 event->core = -1;
74531fed
PA
7331
7332 switch (buf[0])
7333 {
7334 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7335 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7336 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7337 ss = signal number
7338 n... = register number
7339 r... = register contents
7340 */
7341
7342 p = &buf[3]; /* after Txx */
7343 while (*p)
7344 {
256642e8 7345 const char *p1;
cea39f65 7346 int fieldsize;
43ff13b4 7347
1f10ba14
PA
7348 p1 = strchr (p, ':');
7349 if (p1 == NULL)
7350 error (_("Malformed packet(a) (missing colon): %s\n\
7351Packet: '%s'\n"),
7352 p, buf);
7353 if (p == p1)
7354 error (_("Malformed packet(a) (missing register number): %s\n\
7355Packet: '%s'\n"),
7356 p, buf);
3c3bea1c 7357
1f10ba14
PA
7358 /* Some "registers" are actually extended stop information.
7359 Note if you're adding a new entry here: GDB 7.9 and
7360 earlier assume that all register "numbers" that start
7361 with an hex digit are real register numbers. Make sure
7362 the server only sends such a packet if it knows the
7363 client understands it. */
c8e38a49 7364
26d56a93 7365 if (strprefix (p, p1, "thread"))
1f10ba14 7366 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7367 else if (strprefix (p, p1, "syscall_entry"))
7368 {
7369 ULONGEST sysno;
7370
7371 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7372 p = unpack_varlen_hex (++p1, &sysno);
7373 event->ws.value.syscall_number = (int) sysno;
7374 }
7375 else if (strprefix (p, p1, "syscall_return"))
7376 {
7377 ULONGEST sysno;
7378
7379 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7380 p = unpack_varlen_hex (++p1, &sysno);
7381 event->ws.value.syscall_number = (int) sysno;
7382 }
26d56a93
SL
7383 else if (strprefix (p, p1, "watch")
7384 || strprefix (p, p1, "rwatch")
7385 || strprefix (p, p1, "awatch"))
cea39f65 7386 {
f7e6eed5 7387 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7388 p = unpack_varlen_hex (++p1, &addr);
7389 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7390 }
26d56a93 7391 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7392 {
7393 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7394
7395 /* Make sure the stub doesn't forget to indicate support
7396 with qSupported. */
7397 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7398 error (_("Unexpected swbreak stop reason"));
7399
7400 /* The value part is documented as "must be empty",
7401 though we ignore it, in case we ever decide to make
7402 use of it in a backward compatible way. */
8424cc97 7403 p = strchrnul (p1 + 1, ';');
f7e6eed5 7404 }
26d56a93 7405 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7406 {
7407 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7408
7409 /* Make sure the stub doesn't forget to indicate support
7410 with qSupported. */
7411 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7412 error (_("Unexpected hwbreak stop reason"));
7413
7414 /* See above. */
8424cc97 7415 p = strchrnul (p1 + 1, ';');
f7e6eed5 7416 }
26d56a93 7417 else if (strprefix (p, p1, "library"))
cea39f65 7418 {
1f10ba14 7419 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 7420 p = strchrnul (p1 + 1, ';');
1f10ba14 7421 }
26d56a93 7422 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
7423 {
7424 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7425 /* p1 will indicate "begin" or "end", but it makes
7426 no difference for now, so ignore it. */
8424cc97 7427 p = strchrnul (p1 + 1, ';');
1f10ba14 7428 }
26d56a93 7429 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7430 {
7431 ULONGEST c;
a744cf53 7432
1f10ba14
PA
7433 p = unpack_varlen_hex (++p1, &c);
7434 event->core = c;
cea39f65 7435 }
26d56a93 7436 else if (strprefix (p, p1, "fork"))
de0d863e
DB
7437 {
7438 event->ws.value.related_pid = read_ptid (++p1, &p);
7439 event->ws.kind = TARGET_WAITKIND_FORKED;
7440 }
26d56a93 7441 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
7442 {
7443 event->ws.value.related_pid = read_ptid (++p1, &p);
7444 event->ws.kind = TARGET_WAITKIND_VFORKED;
7445 }
26d56a93 7446 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
7447 {
7448 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 7449 p = strchrnul (p1 + 1, ';');
c269dbdb 7450 }
6ab24463 7451 else if (strprefix (p, p1, "exec"))
94585166
DB
7452 {
7453 ULONGEST ignored;
7454 char pathname[PATH_MAX];
7455 int pathlen;
7456
7457 /* Determine the length of the execd pathname. */
7458 p = unpack_varlen_hex (++p1, &ignored);
7459 pathlen = (p - p1) / 2;
7460
7461 /* Save the pathname for event reporting and for
7462 the next run command. */
7463 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7464 pathname[pathlen] = '\0';
7465
7466 /* This is freed during event handling. */
7467 event->ws.value.execd_pathname = xstrdup (pathname);
7468 event->ws.kind = TARGET_WAITKIND_EXECD;
7469
7470 /* Skip the registers included in this packet, since
7471 they may be for an architecture different from the
7472 one used by the original program. */
7473 skipregs = 1;
7474 }
65706a29
PA
7475 else if (strprefix (p, p1, "create"))
7476 {
7477 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 7478 p = strchrnul (p1 + 1, ';');
65706a29 7479 }
cea39f65
MS
7480 else
7481 {
1f10ba14 7482 ULONGEST pnum;
256642e8 7483 const char *p_temp;
1f10ba14 7484
94585166
DB
7485 if (skipregs)
7486 {
8424cc97 7487 p = strchrnul (p1 + 1, ';');
94585166
DB
7488 p++;
7489 continue;
7490 }
7491
1f10ba14
PA
7492 /* Maybe a real ``P'' register number. */
7493 p_temp = unpack_varlen_hex (p, &pnum);
7494 /* If the first invalid character is the colon, we got a
7495 register number. Otherwise, it's an unknown stop
7496 reason. */
7497 if (p_temp == p1)
7498 {
5cd63fda
PA
7499 /* If we haven't parsed the event's thread yet, find
7500 it now, in order to find the architecture of the
7501 reported expedited registers. */
7502 if (event->ptid == null_ptid)
7503 {
7504 const char *thr = strstr (p1 + 1, ";thread:");
7505 if (thr != NULL)
7506 event->ptid = read_ptid (thr + strlen (";thread:"),
7507 NULL);
7508 else
3cada740
PA
7509 {
7510 /* Either the current thread hasn't changed,
7511 or the inferior is not multi-threaded.
7512 The event must be for the thread we last
7513 set as (or learned as being) current. */
7514 event->ptid = event->rs->general_thread;
7515 }
5cd63fda
PA
7516 }
7517
7518 if (rsa == NULL)
7519 {
7520 inferior *inf = (event->ptid == null_ptid
7521 ? NULL
7522 : find_inferior_ptid (event->ptid));
7523 /* If this is the first time we learn anything
7524 about this process, skip the registers
7525 included in this packet, since we don't yet
7526 know which architecture to use to parse them.
7527 We'll determine the architecture later when
7528 we process the stop reply and retrieve the
7529 target description, via
7530 remote_notice_new_inferior ->
7531 post_create_inferior. */
7532 if (inf == NULL)
7533 {
7534 p = strchrnul (p1 + 1, ';');
7535 p++;
7536 continue;
7537 }
7538
7539 event->arch = inf->gdbarch;
9d6eea31 7540 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7541 }
7542
7543 packet_reg *reg
7544 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7545 cached_reg_t cached_reg;
43ff13b4 7546
1f10ba14
PA
7547 if (reg == NULL)
7548 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7549Packet: '%s'\n"),
1f10ba14 7550 hex_string (pnum), p, buf);
c8e38a49 7551
1f10ba14 7552 cached_reg.num = reg->regnum;
d1dff226 7553 cached_reg.data = (gdb_byte *)
5cd63fda 7554 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7555
1f10ba14
PA
7556 p = p1 + 1;
7557 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7558 register_size (event->arch, reg->regnum));
1f10ba14 7559 p += 2 * fieldsize;
5cd63fda 7560 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7561 warning (_("Remote reply is too short: %s"), buf);
74531fed 7562
1f10ba14
PA
7563 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7564 }
7565 else
7566 {
7567 /* Not a number. Silently skip unknown optional
7568 info. */
8424cc97 7569 p = strchrnul (p1 + 1, ';');
1f10ba14 7570 }
cea39f65 7571 }
c8e38a49 7572
cea39f65
MS
7573 if (*p != ';')
7574 error (_("Remote register badly formatted: %s\nhere: %s"),
7575 buf, p);
7576 ++p;
7577 }
5b5596ff
PA
7578
7579 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7580 break;
7581
c8e38a49
PA
7582 /* fall through */
7583 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7584 {
7585 int sig;
7586
7587 event->ws.kind = TARGET_WAITKIND_STOPPED;
7588 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7589 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7590 event->ws.value.sig = (enum gdb_signal) sig;
7591 else
7592 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7593 }
c8e38a49 7594 break;
65706a29
PA
7595 case 'w': /* Thread exited. */
7596 {
256642e8 7597 const char *p;
65706a29
PA
7598 ULONGEST value;
7599
7600 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7601 p = unpack_varlen_hex (&buf[1], &value);
7602 event->ws.value.integer = value;
7603 if (*p != ';')
7604 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7605 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7606 break;
7607 }
c8e38a49
PA
7608 case 'W': /* Target exited. */
7609 case 'X':
7610 {
256642e8 7611 const char *p;
c8e38a49
PA
7612 int pid;
7613 ULONGEST value;
82f73884 7614
c8e38a49
PA
7615 /* GDB used to accept only 2 hex chars here. Stubs should
7616 only send more if they detect GDB supports multi-process
7617 support. */
7618 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7619
c8e38a49
PA
7620 if (buf[0] == 'W')
7621 {
7622 /* The remote process exited. */
74531fed
PA
7623 event->ws.kind = TARGET_WAITKIND_EXITED;
7624 event->ws.value.integer = value;
c8e38a49
PA
7625 }
7626 else
7627 {
7628 /* The remote process exited with a signal. */
74531fed 7629 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7630 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7631 event->ws.value.sig = (enum gdb_signal) value;
7632 else
7633 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7634 }
82f73884 7635
c8e38a49
PA
7636 /* If no process is specified, assume inferior_ptid. */
7637 pid = ptid_get_pid (inferior_ptid);
7638 if (*p == '\0')
7639 ;
7640 else if (*p == ';')
7641 {
7642 p++;
7643
0b24eb2d 7644 if (*p == '\0')
82f73884 7645 ;
61012eef 7646 else if (startswith (p, "process:"))
82f73884 7647 {
c8e38a49 7648 ULONGEST upid;
a744cf53 7649
c8e38a49
PA
7650 p += sizeof ("process:") - 1;
7651 unpack_varlen_hex (p, &upid);
7652 pid = upid;
82f73884
PA
7653 }
7654 else
7655 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7656 }
c8e38a49
PA
7657 else
7658 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
7659 event->ptid = pid_to_ptid (pid);
7660 }
7661 break;
f2faf941
PA
7662 case 'N':
7663 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7664 event->ptid = minus_one_ptid;
7665 break;
74531fed
PA
7666 }
7667
6efcd9a8 7668 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
7669 error (_("No process or thread specified in stop reply: %s"), buf);
7670}
7671
722247f1
YQ
7672/* When the stub wants to tell GDB about a new notification reply, it
7673 sends a notification (%Stop, for example). Those can come it at
7674 any time, hence, we have to make sure that any pending
7675 putpkt/getpkt sequence we're making is finished, before querying
7676 the stub for more events with the corresponding ack command
7677 (vStopped, for example). E.g., if we started a vStopped sequence
7678 immediately upon receiving the notification, something like this
7679 could happen:
74531fed
PA
7680
7681 1.1) --> Hg 1
7682 1.2) <-- OK
7683 1.3) --> g
7684 1.4) <-- %Stop
7685 1.5) --> vStopped
7686 1.6) <-- (registers reply to step #1.3)
7687
7688 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7689 query.
7690
796cb314 7691 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7692 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7693 doing whatever we were doing:
7694
7695 2.1) --> Hg 1
7696 2.2) <-- OK
7697 2.3) --> g
7698 2.4) <-- %Stop
7699 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7700 2.5) <-- (registers reply to step #2.3)
7701
7702 Eventualy after step #2.5, we return to the event loop, which
7703 notices there's an event on the
7704 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7705 associated callback --- the function below. At this point, we're
7706 always safe to start a vStopped sequence. :
7707
7708 2.6) --> vStopped
7709 2.7) <-- T05 thread:2
7710 2.8) --> vStopped
7711 2.9) --> OK
7712*/
7713
722247f1 7714void
6b8edb51 7715remote_target::remote_notif_get_pending_events (notif_client *nc)
74531fed
PA
7716{
7717 struct remote_state *rs = get_remote_state ();
74531fed 7718
f48ff2a7 7719 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7720 {
722247f1
YQ
7721 if (notif_debug)
7722 fprintf_unfiltered (gdb_stdlog,
7723 "notif: process: '%s' ack pending event\n",
7724 nc->name);
74531fed 7725
722247f1 7726 /* acknowledge */
6b8edb51 7727 nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
f48ff2a7 7728 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7729
7730 while (1)
7731 {
7732 getpkt (&rs->buf, &rs->buf_size, 0);
7733 if (strcmp (rs->buf, "OK") == 0)
7734 break;
7735 else
6b8edb51 7736 remote_notif_ack (this, nc, rs->buf);
74531fed
PA
7737 }
7738 }
722247f1
YQ
7739 else
7740 {
7741 if (notif_debug)
7742 fprintf_unfiltered (gdb_stdlog,
7743 "notif: process: '%s' no pending reply\n",
7744 nc->name);
7745 }
74531fed
PA
7746}
7747
6b8edb51
PA
7748/* Wrapper around remote_target::remote_notif_get_pending_events to
7749 avoid having to export the whole remote_target class. */
7750
7751void
7752remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7753{
7754 remote->remote_notif_get_pending_events (nc);
7755}
7756
74531fed
PA
7757/* Called when it is decided that STOP_REPLY holds the info of the
7758 event that is to be returned to the core. This function always
7759 destroys STOP_REPLY. */
7760
6b8edb51
PA
7761ptid_t
7762remote_target::process_stop_reply (struct stop_reply *stop_reply,
7763 struct target_waitstatus *status)
74531fed
PA
7764{
7765 ptid_t ptid;
7766
7767 *status = stop_reply->ws;
7768 ptid = stop_reply->ptid;
7769
7770 /* If no thread/process was reported by the stub, assume the current
7771 inferior. */
7772 if (ptid_equal (ptid, null_ptid))
7773 ptid = inferior_ptid;
7774
5f3563ea 7775 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7776 && status->kind != TARGET_WAITKIND_SIGNALLED
7777 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7778 {
5f3563ea
PA
7779 /* Expedited registers. */
7780 if (stop_reply->regcache)
7781 {
217f1f79 7782 struct regcache *regcache
5cd63fda 7783 = get_thread_arch_regcache (ptid, stop_reply->arch);
5f3563ea
PA
7784 cached_reg_t *reg;
7785 int ix;
7786
7787 for (ix = 0;
d1dff226 7788 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
5f3563ea 7789 ix++)
d1dff226 7790 {
217f1f79 7791 regcache_raw_supply (regcache, reg->num, reg->data);
d1dff226
AH
7792 xfree (reg->data);
7793 }
7794
5f3563ea
PA
7795 VEC_free (cached_reg_t, stop_reply->regcache);
7796 }
74531fed 7797
1941c569 7798 remote_notice_new_inferior (ptid, 0);
7aabaf9d 7799 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
799a2abe
PA
7800 remote_thr->core = stop_reply->core;
7801 remote_thr->stop_reason = stop_reply->stop_reason;
7802 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7803 remote_thr->vcont_resumed = 0;
74531fed
PA
7804 }
7805
74531fed
PA
7806 stop_reply_xfree (stop_reply);
7807 return ptid;
7808}
7809
7810/* The non-stop mode version of target_wait. */
7811
6b8edb51
PA
7812ptid_t
7813remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7814{
7815 struct remote_state *rs = get_remote_state ();
74531fed
PA
7816 struct stop_reply *stop_reply;
7817 int ret;
fee9eda9 7818 int is_notif = 0;
74531fed
PA
7819
7820 /* If in non-stop mode, get out of getpkt even if a
7821 notification is received. */
7822
7823 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7824 0 /* forever */, &is_notif);
74531fed
PA
7825 while (1)
7826 {
fee9eda9 7827 if (ret != -1 && !is_notif)
74531fed
PA
7828 switch (rs->buf[0])
7829 {
7830 case 'E': /* Error of some sort. */
7831 /* We're out of sync with the target now. Did it continue
7832 or not? We can't tell which thread it was in non-stop,
7833 so just ignore this. */
7834 warning (_("Remote failure reply: %s"), rs->buf);
7835 break;
7836 case 'O': /* Console output. */
7837 remote_console_output (rs->buf + 1);
7838 break;
7839 default:
7840 warning (_("Invalid remote reply: %s"), rs->buf);
7841 break;
7842 }
7843
7844 /* Acknowledge a pending stop reply that may have arrived in the
7845 mean time. */
f48ff2a7 7846 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7847 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7848
7849 /* If indeed we noticed a stop reply, we're done. */
7850 stop_reply = queued_stop_reply (ptid);
7851 if (stop_reply != NULL)
7852 return process_stop_reply (stop_reply, status);
7853
47608cb1 7854 /* Still no event. If we're just polling for an event, then
74531fed 7855 return to the event loop. */
47608cb1 7856 if (options & TARGET_WNOHANG)
74531fed
PA
7857 {
7858 status->kind = TARGET_WAITKIND_IGNORE;
7859 return minus_one_ptid;
7860 }
7861
47608cb1 7862 /* Otherwise do a blocking wait. */
74531fed 7863 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7864 1 /* forever */, &is_notif);
74531fed
PA
7865 }
7866}
7867
7868/* Wait until the remote machine stops, then return, storing status in
7869 STATUS just as `wait' would. */
7870
6b8edb51
PA
7871ptid_t
7872remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
74531fed
PA
7873{
7874 struct remote_state *rs = get_remote_state ();
74531fed 7875 ptid_t event_ptid = null_ptid;
cea39f65 7876 char *buf;
74531fed
PA
7877 struct stop_reply *stop_reply;
7878
47608cb1
PA
7879 again:
7880
74531fed
PA
7881 status->kind = TARGET_WAITKIND_IGNORE;
7882 status->value.integer = 0;
7883
7884 stop_reply = queued_stop_reply (ptid);
7885 if (stop_reply != NULL)
7886 return process_stop_reply (stop_reply, status);
7887
7888 if (rs->cached_wait_status)
7889 /* Use the cached wait status, but only once. */
7890 rs->cached_wait_status = 0;
7891 else
7892 {
7893 int ret;
722247f1 7894 int is_notif;
567420d1 7895 int forever = ((options & TARGET_WNOHANG) == 0
6b8edb51 7896 && rs->wait_forever_enabled_p);
567420d1
PA
7897
7898 if (!rs->waiting_for_stop_reply)
7899 {
7900 status->kind = TARGET_WAITKIND_NO_RESUMED;
7901 return minus_one_ptid;
7902 }
74531fed 7903
74531fed
PA
7904 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7905 _never_ wait for ever -> test on target_is_async_p().
7906 However, before we do that we need to ensure that the caller
7907 knows how to take the target into/out of async mode. */
722247f1 7908 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 7909 forever, &is_notif);
722247f1
YQ
7910
7911 /* GDB gets a notification. Return to core as this event is
7912 not interesting. */
7913 if (ret != -1 && is_notif)
7914 return minus_one_ptid;
567420d1
PA
7915
7916 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7917 return minus_one_ptid;
74531fed
PA
7918 }
7919
7920 buf = rs->buf;
7921
3a29589a
DJ
7922 /* Assume that the target has acknowledged Ctrl-C unless we receive
7923 an 'F' or 'O' packet. */
7924 if (buf[0] != 'F' && buf[0] != 'O')
7925 rs->ctrlc_pending_p = 0;
7926
74531fed
PA
7927 switch (buf[0])
7928 {
7929 case 'E': /* Error of some sort. */
7930 /* We're out of sync with the target now. Did it continue or
7931 not? Not is more likely, so report a stop. */
29090fb6
LM
7932 rs->waiting_for_stop_reply = 0;
7933
74531fed
PA
7934 warning (_("Remote failure reply: %s"), buf);
7935 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7936 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7937 break;
7938 case 'F': /* File-I/O request. */
e42e5352
YQ
7939 /* GDB may access the inferior memory while handling the File-I/O
7940 request, but we don't want GDB accessing memory while waiting
7941 for a stop reply. See the comments in putpkt_binary. Set
7942 waiting_for_stop_reply to 0 temporarily. */
7943 rs->waiting_for_stop_reply = 0;
6b8edb51 7944 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
3a29589a 7945 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7946 /* GDB handled the File-I/O request, and the target is running
7947 again. Keep waiting for events. */
7948 rs->waiting_for_stop_reply = 1;
74531fed 7949 break;
f2faf941 7950 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7951 {
29090fb6
LM
7952 struct stop_reply *stop_reply;
7953
7954 /* There is a stop reply to handle. */
7955 rs->waiting_for_stop_reply = 0;
7956
7957 stop_reply
6b8edb51
PA
7958 = (struct stop_reply *) remote_notif_parse (this,
7959 &notif_client_stop,
722247f1 7960 rs->buf);
74531fed 7961
74531fed 7962 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7963 break;
7964 }
7965 case 'O': /* Console output. */
7966 remote_console_output (buf + 1);
c8e38a49
PA
7967 break;
7968 case '\0':
b73be471 7969 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7970 {
7971 /* Zero length reply means that we tried 'S' or 'C' and the
7972 remote system doesn't support it. */
223ffa71 7973 target_terminal::ours_for_output ();
c8e38a49
PA
7974 printf_filtered
7975 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7976 gdb_signal_to_name (rs->last_sent_signal));
7977 rs->last_sent_signal = GDB_SIGNAL_0;
223ffa71 7978 target_terminal::inferior ();
c8e38a49 7979
f5c4fcd9
TT
7980 strcpy (buf, rs->last_sent_step ? "s" : "c");
7981 putpkt (buf);
c8e38a49 7982 break;
43ff13b4 7983 }
86a73007 7984 /* fallthrough */
c8e38a49
PA
7985 default:
7986 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7987 break;
43ff13b4 7988 }
c8e38a49 7989
f2faf941
PA
7990 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7991 return minus_one_ptid;
7992 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7993 {
7994 /* Nothing interesting happened. If we're doing a non-blocking
7995 poll, we're done. Otherwise, go back to waiting. */
7996 if (options & TARGET_WNOHANG)
7997 return minus_one_ptid;
7998 else
7999 goto again;
8000 }
74531fed
PA
8001 else if (status->kind != TARGET_WAITKIND_EXITED
8002 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
8003 {
8004 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 8005 record_currthread (rs, event_ptid);
82f73884
PA
8006 else
8007 event_ptid = inferior_ptid;
43ff13b4 8008 }
74531fed
PA
8009 else
8010 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 8011 record_currthread (rs, minus_one_ptid);
79d7f229 8012
82f73884 8013 return event_ptid;
43ff13b4
JM
8014}
8015
74531fed
PA
8016/* Wait until the remote machine stops, then return, storing status in
8017 STATUS just as `wait' would. */
8018
f6ac5f3d
PA
8019ptid_t
8020remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
8021{
8022 ptid_t event_ptid;
8023
6efcd9a8 8024 if (target_is_non_stop_p ())
6b8edb51 8025 event_ptid = wait_ns (ptid, status, options);
74531fed 8026 else
6b8edb51 8027 event_ptid = wait_as (ptid, status, options);
c8e38a49 8028
d9d41e78 8029 if (target_is_async_p ())
c8e38a49 8030 {
6b8edb51
PA
8031 remote_state *rs = get_remote_state ();
8032
74531fed
PA
8033 /* If there are are events left in the queue tell the event loop
8034 to return here. */
6b8edb51
PA
8035 if (!QUEUE_is_empty (stop_reply_p, rs->stop_reply_queue))
8036 mark_async_event_handler (rs->remote_async_inferior_event_token);
c8e38a49 8037 }
c8e38a49
PA
8038
8039 return event_ptid;
8040}
8041
74ca34ce 8042/* Fetch a single register using a 'p' packet. */
c906108c 8043
6b8edb51
PA
8044int
8045remote_target::fetch_register_using_p (struct regcache *regcache,
8046 packet_reg *reg)
b96ec7ac 8047{
ac7936df 8048 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 8049 struct remote_state *rs = get_remote_state ();
2e9f7625 8050 char *buf, *p;
9890e433 8051 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
8052 int i;
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
2e9f7625 8060 p = rs->buf;
fcad0fa4 8061 *p++ = 'p';
74ca34ce 8062 p += hexnumstr (p, reg->pnum);
fcad0fa4 8063 *p++ = '\0';
1f4437a4
MS
8064 putpkt (rs->buf);
8065 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 8066
2e9f7625
DJ
8067 buf = rs->buf;
8068
74ca34ce
DJ
8069 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
8070 {
8071 case PACKET_OK:
8072 break;
8073 case PACKET_UNKNOWN:
8074 return 0;
8075 case PACKET_ERROR:
27a9c0bf 8076 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 8077 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
8078 reg->regnum),
8079 buf);
74ca34ce 8080 }
3f9a994c
JB
8081
8082 /* If this register is unfetchable, tell the regcache. */
8083 if (buf[0] == 'x')
8480adf2 8084 {
56be3814 8085 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 8086 return 1;
b96ec7ac 8087 }
b96ec7ac 8088
3f9a994c
JB
8089 /* Otherwise, parse and supply the value. */
8090 p = buf;
8091 i = 0;
8092 while (p[0] != 0)
8093 {
8094 if (p[1] == 0)
74ca34ce 8095 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
8096
8097 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8098 p += 2;
8099 }
56be3814 8100 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 8101 return 1;
b96ec7ac
AC
8102}
8103
74ca34ce
DJ
8104/* Fetch the registers included in the target's 'g' packet. */
8105
6b8edb51
PA
8106int
8107remote_target::send_g_packet ()
c906108c 8108{
d01949b6 8109 struct remote_state *rs = get_remote_state ();
cea39f65 8110 int buf_len;
c906108c 8111
bba74b36 8112 xsnprintf (rs->buf, get_remote_packet_size (), "g");
b75abf5b
AK
8113 putpkt (rs->buf);
8114 getpkt (&rs->buf, &rs->buf_size, 0);
8115 if (packet_check_result (rs->buf) == PACKET_ERROR)
8116 error (_("Could not read registers; remote failure reply '%s'"),
8117 rs->buf);
c906108c 8118
29709017
DJ
8119 /* We can get out of synch in various cases. If the first character
8120 in the buffer is not a hex character, assume that has happened
8121 and try to fetch another packet to read. */
8122 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8123 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8124 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8125 && rs->buf[0] != 'x') /* New: unavailable register value. */
8126 {
8127 if (remote_debug)
8128 fprintf_unfiltered (gdb_stdlog,
8129 "Bad register packet; fetching a new packet\n");
8130 getpkt (&rs->buf, &rs->buf_size, 0);
8131 }
8132
74ca34ce
DJ
8133 buf_len = strlen (rs->buf);
8134
8135 /* Sanity check the received packet. */
8136 if (buf_len % 2 != 0)
8137 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
8138
8139 return buf_len / 2;
8140}
8141
6b8edb51
PA
8142void
8143remote_target::process_g_packet (struct regcache *regcache)
29709017 8144{
ac7936df 8145 struct gdbarch *gdbarch = regcache->arch ();
29709017 8146 struct remote_state *rs = get_remote_state ();
9d6eea31 8147 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8148 int i, buf_len;
8149 char *p;
8150 char *regs;
8151
8152 buf_len = strlen (rs->buf);
8153
8154 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8155 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827
SM
8156 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8157 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
74ca34ce
DJ
8158
8159 /* Save the size of the packet sent to us by the target. It is used
8160 as a heuristic when determining the max size of packets that the
8161 target can safely receive. */
8162 if (rsa->actual_register_packet_size == 0)
8163 rsa->actual_register_packet_size = buf_len;
8164
8165 /* If this is smaller than we guessed the 'g' packet would be,
8166 update our records. A 'g' reply that doesn't include a register's
8167 value implies either that the register is not available, or that
8168 the 'p' packet must be used. */
8169 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8170 {
9dc193c3 8171 long sizeof_g_packet = buf_len / 2;
74ca34ce 8172
4a22f64d 8173 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8174 {
9dc193c3
LF
8175 long offset = rsa->regs[i].offset;
8176 long reg_size = register_size (gdbarch, i);
8177
74ca34ce
DJ
8178 if (rsa->regs[i].pnum == -1)
8179 continue;
8180
9dc193c3 8181 if (offset >= sizeof_g_packet)
74ca34ce 8182 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8183 else if (offset + reg_size > sizeof_g_packet)
8184 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8185 else
74ca34ce 8186 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8187 }
9dc193c3
LF
8188
8189 /* Looks valid enough, we can assume this is the correct length
8190 for a 'g' packet. It's important not to adjust
8191 rsa->sizeof_g_packet if we have truncated registers otherwise
8192 this "if" won't be run the next time the method is called
8193 with a packet of the same size and one of the internal errors
8194 below will trigger instead. */
8195 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8196 }
b323314b 8197
224c3ddb 8198 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8199
8200 /* Unimplemented registers read as all bits zero. */
ea9c271d 8201 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8202
c906108c
SS
8203 /* Reply describes registers byte by byte, each byte encoded as two
8204 hex characters. Suck them all up, then supply them to the
8205 register cacheing/storage mechanism. */
8206
74ca34ce 8207 p = rs->buf;
ea9c271d 8208 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8209 {
74ca34ce
DJ
8210 if (p[0] == 0 || p[1] == 0)
8211 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8212 internal_error (__FILE__, __LINE__,
9b20d036 8213 _("unexpected end of 'g' packet reply"));
74ca34ce 8214
c906108c 8215 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8216 regs[i] = 0; /* 'x' */
c906108c
SS
8217 else
8218 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8219 p += 2;
8220 }
8221
a744cf53
MS
8222 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8223 {
8224 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8225 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8226
8227 if (r->in_g_packet)
8228 {
9dc193c3 8229 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
a744cf53
MS
8230 /* This shouldn't happen - we adjusted in_g_packet above. */
8231 internal_error (__FILE__, __LINE__,
9b20d036 8232 _("unexpected end of 'g' packet reply"));
a744cf53
MS
8233 else if (rs->buf[r->offset * 2] == 'x')
8234 {
8235 gdb_assert (r->offset * 2 < strlen (rs->buf));
8236 /* The register isn't available, mark it as such (at
8237 the same time setting the value to zero). */
8238 regcache_raw_supply (regcache, r->regnum, NULL);
8239 }
8240 else
8241 regcache_raw_supply (regcache, r->regnum,
8242 regs + r->offset);
8243 }
8244 }
c906108c
SS
8245}
8246
6b8edb51
PA
8247void
8248remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8249{
8250 send_g_packet ();
56be3814 8251 process_g_packet (regcache);
29709017
DJ
8252}
8253
e6e4e701
PA
8254/* Make the remote selected traceframe match GDB's selected
8255 traceframe. */
8256
6b8edb51
PA
8257void
8258remote_target::set_remote_traceframe ()
e6e4e701
PA
8259{
8260 int newnum;
262e1174 8261 struct remote_state *rs = get_remote_state ();
e6e4e701 8262
262e1174 8263 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8264 return;
8265
8266 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8267 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8268
8269 newnum = target_trace_find (tfind_number,
8270 get_traceframe_number (), 0, 0, NULL);
8271
8272 /* Should not happen. If it does, all bets are off. */
8273 if (newnum != get_traceframe_number ())
8274 warning (_("could not set remote traceframe"));
8275}
8276
f6ac5f3d
PA
8277void
8278remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8279{
ac7936df 8280 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8281 struct remote_state *rs = get_remote_state ();
8282 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8283 int i;
8284
e6e4e701 8285 set_remote_traceframe ();
bcc0c096 8286 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
8287
8288 if (regnum >= 0)
8289 {
5cd63fda 8290 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8291
74ca34ce
DJ
8292 gdb_assert (reg != NULL);
8293
8294 /* If this register might be in the 'g' packet, try that first -
8295 we are likely to read more than one register. If this is the
8296 first 'g' packet, we might be overly optimistic about its
8297 contents, so fall back to 'p'. */
8298 if (reg->in_g_packet)
8299 {
56be3814 8300 fetch_registers_using_g (regcache);
74ca34ce
DJ
8301 if (reg->in_g_packet)
8302 return;
8303 }
8304
56be3814 8305 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8306 return;
8307
8308 /* This register is not available. */
56be3814 8309 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
8310
8311 return;
8312 }
8313
56be3814 8314 fetch_registers_using_g (regcache);
74ca34ce 8315
5cd63fda 8316 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8317 if (!rsa->regs[i].in_g_packet)
56be3814 8318 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8319 {
8320 /* This register is not available. */
56be3814 8321 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
8322 }
8323}
8324
c906108c
SS
8325/* Prepare to store registers. Since we may send them all (using a
8326 'G' request), we have to read out the ones we don't want to change
8327 first. */
8328
f6ac5f3d
PA
8329void
8330remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8331{
9d6eea31
PA
8332 struct remote_state *rs = get_remote_state ();
8333 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8334 int i;
cf0e1e0d 8335
c906108c 8336 /* Make sure the entire registers array is valid. */
4082afcc 8337 switch (packet_support (PACKET_P))
5a2468f5
JM
8338 {
8339 case PACKET_DISABLE:
8340 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8341 /* Make sure all the necessary registers are cached. */
ac7936df 8342 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8343 if (rsa->regs[i].in_g_packet)
8e368124 8344 regcache_raw_update (regcache, rsa->regs[i].regnum);
5a2468f5
JM
8345 break;
8346 case PACKET_ENABLE:
8347 break;
8348 }
8349}
8350
ad10f812 8351/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8352 packet was not recognized. */
5a2468f5 8353
6b8edb51
PA
8354int
8355remote_target::store_register_using_P (const struct regcache *regcache,
8356 packet_reg *reg)
5a2468f5 8357{
ac7936df 8358 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8359 struct remote_state *rs = get_remote_state ();
5a2468f5 8360 /* Try storing a single register. */
6d820c5c 8361 char *buf = rs->buf;
9890e433 8362 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8363 char *p;
5a2468f5 8364
4082afcc 8365 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8366 return 0;
8367
8368 if (reg->pnum == -1)
8369 return 0;
8370
ea9c271d 8371 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8372 p = buf + strlen (buf);
56be3814 8373 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 8374 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
8375 putpkt (rs->buf);
8376 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 8377
74ca34ce
DJ
8378 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8379 {
8380 case PACKET_OK:
8381 return 1;
8382 case PACKET_ERROR:
27a9c0bf
MS
8383 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8384 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
8385 case PACKET_UNKNOWN:
8386 return 0;
8387 default:
8388 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8389 }
c906108c
SS
8390}
8391
23860348
MS
8392/* Store register REGNUM, or all registers if REGNUM == -1, from the
8393 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8394
6b8edb51
PA
8395void
8396remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8397{
d01949b6 8398 struct remote_state *rs = get_remote_state ();
9d6eea31 8399 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8400 gdb_byte *regs;
c906108c
SS
8401 char *p;
8402
193cb69f
AC
8403 /* Extract all the registers in the regcache copying them into a
8404 local buffer. */
8405 {
b323314b 8406 int i;
a744cf53 8407
224c3ddb 8408 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8409 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8410 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8411 {
ea9c271d 8412 struct packet_reg *r = &rsa->regs[i];
a744cf53 8413
b323314b 8414 if (r->in_g_packet)
56be3814 8415 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
8416 }
8417 }
c906108c
SS
8418
8419 /* Command describes registers byte by byte,
8420 each byte encoded as two hex characters. */
6d820c5c 8421 p = rs->buf;
193cb69f 8422 *p++ = 'G';
74ca34ce 8423 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
8424 putpkt (rs->buf);
8425 getpkt (&rs->buf, &rs->buf_size, 0);
8426 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
8427 error (_("Could not write registers; remote failure reply '%s'"),
8428 rs->buf);
c906108c 8429}
74ca34ce
DJ
8430
8431/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8432 of the register cache buffer. FIXME: ignores errors. */
8433
f6ac5f3d
PA
8434void
8435remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8436{
5cd63fda 8437 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8438 struct remote_state *rs = get_remote_state ();
8439 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8440 int i;
8441
e6e4e701 8442 set_remote_traceframe ();
bcc0c096 8443 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
8444
8445 if (regnum >= 0)
8446 {
5cd63fda 8447 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8448
74ca34ce
DJ
8449 gdb_assert (reg != NULL);
8450
8451 /* Always prefer to store registers using the 'P' packet if
8452 possible; we often change only a small number of registers.
8453 Sometimes we change a larger number; we'd need help from a
8454 higher layer to know to use 'G'. */
56be3814 8455 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8456 return;
8457
8458 /* For now, don't complain if we have no way to write the
8459 register. GDB loses track of unavailable registers too
8460 easily. Some day, this may be an error. We don't have
0df8b418 8461 any way to read the register, either... */
74ca34ce
DJ
8462 if (!reg->in_g_packet)
8463 return;
8464
56be3814 8465 store_registers_using_G (regcache);
74ca34ce
DJ
8466 return;
8467 }
8468
56be3814 8469 store_registers_using_G (regcache);
74ca34ce 8470
5cd63fda 8471 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8472 if (!rsa->regs[i].in_g_packet)
56be3814 8473 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8474 /* See above for why we do not issue an error here. */
8475 continue;
8476}
c906108c
SS
8477\f
8478
8479/* Return the number of hex digits in num. */
8480
8481static int
fba45db2 8482hexnumlen (ULONGEST num)
c906108c
SS
8483{
8484 int i;
8485
8486 for (i = 0; num != 0; i++)
8487 num >>= 4;
8488
325fac50 8489 return std::max (i, 1);
c906108c
SS
8490}
8491
2df3850c 8492/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8493
8494static int
fba45db2 8495hexnumstr (char *buf, ULONGEST num)
c906108c 8496{
c906108c 8497 int len = hexnumlen (num);
a744cf53 8498
2df3850c
JM
8499 return hexnumnstr (buf, num, len);
8500}
8501
c906108c 8502
2df3850c 8503/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8504
2df3850c 8505static int
fba45db2 8506hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8507{
8508 int i;
8509
8510 buf[width] = '\0';
8511
8512 for (i = width - 1; i >= 0; i--)
c906108c 8513 {
c5aa993b 8514 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8515 num >>= 4;
8516 }
8517
2df3850c 8518 return width;
c906108c
SS
8519}
8520
23860348 8521/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8522
8523static CORE_ADDR
fba45db2 8524remote_address_masked (CORE_ADDR addr)
c906108c 8525{
883b9c6c 8526 unsigned int address_size = remote_address_size;
a744cf53 8527
911c95a5
UW
8528 /* If "remoteaddresssize" was not set, default to target address size. */
8529 if (!address_size)
f5656ead 8530 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8531
8532 if (address_size > 0
8533 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8534 {
8535 /* Only create a mask when that mask can safely be constructed
23860348 8536 in a ULONGEST variable. */
c906108c 8537 ULONGEST mask = 1;
a744cf53 8538
911c95a5 8539 mask = (mask << address_size) - 1;
c906108c
SS
8540 addr &= mask;
8541 }
8542 return addr;
8543}
8544
8545/* Determine whether the remote target supports binary downloading.
8546 This is accomplished by sending a no-op memory write of zero length
8547 to the target at the specified address. It does not suffice to send
23860348
MS
8548 the whole packet, since many stubs strip the eighth bit and
8549 subsequently compute a wrong checksum, which causes real havoc with
8550 remote_write_bytes.
7a292a7a 8551
96baa820 8552 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8553 clean. In cases like this, the user should clear "remote
23860348 8554 X-packet". */
96baa820 8555
6b8edb51
PA
8556void
8557remote_target::check_binary_download (CORE_ADDR addr)
c906108c 8558{
d01949b6 8559 struct remote_state *rs = get_remote_state ();
24b06219 8560
4082afcc 8561 switch (packet_support (PACKET_X))
c906108c 8562 {
96baa820
JM
8563 case PACKET_DISABLE:
8564 break;
8565 case PACKET_ENABLE:
8566 break;
8567 case PACKET_SUPPORT_UNKNOWN:
8568 {
96baa820 8569 char *p;
802188a7 8570
2e9f7625 8571 p = rs->buf;
96baa820
JM
8572 *p++ = 'X';
8573 p += hexnumstr (p, (ULONGEST) addr);
8574 *p++ = ',';
8575 p += hexnumstr (p, (ULONGEST) 0);
8576 *p++ = ':';
8577 *p = '\0';
802188a7 8578
2e9f7625 8579 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8580 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8581
2e9f7625 8582 if (rs->buf[0] == '\0')
96baa820
JM
8583 {
8584 if (remote_debug)
8585 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8586 "binary downloading NOT "
8587 "supported by target\n");
444abaca 8588 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8589 }
8590 else
8591 {
8592 if (remote_debug)
8593 fprintf_unfiltered (gdb_stdlog,
64b9b334 8594 "binary downloading supported by target\n");
444abaca 8595 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8596 }
8597 break;
8598 }
c906108c
SS
8599 }
8600}
8601
124e13d9
SM
8602/* Helper function to resize the payload in order to try to get a good
8603 alignment. We try to write an amount of data such that the next write will
8604 start on an address aligned on REMOTE_ALIGN_WRITES. */
8605
8606static int
8607align_for_efficient_write (int todo, CORE_ADDR memaddr)
8608{
8609 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8610}
8611
c906108c
SS
8612/* Write memory data directly to the remote machine.
8613 This does not inform the data cache; the data cache uses this.
a76d924d 8614 HEADER is the starting part of the packet.
c906108c
SS
8615 MEMADDR is the address in the remote memory space.
8616 MYADDR is the address of the buffer in our space.
124e13d9
SM
8617 LEN_UNITS is the number of addressable units to write.
8618 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8619 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8620 should send data as binary ('X'), or hex-encoded ('M').
8621
8622 The function creates packet of the form
8623 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8624
124e13d9 8625 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8626
8627 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8628 are omitted.
8629
9b409511 8630 Return the transferred status, error or OK (an
124e13d9
SM
8631 'enum target_xfer_status' value). Save the number of addressable units
8632 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8633
8634 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8635 exchange between gdb and the stub could look like (?? in place of the
8636 checksum):
8637
8638 -> $m1000,4#??
8639 <- aaaabbbbccccdddd
8640
8641 -> $M1000,3:eeeeffffeeee#??
8642 <- OK
8643
8644 -> $m1000,4#??
8645 <- eeeeffffeeeedddd */
c906108c 8646
6b8edb51
PA
8647target_xfer_status
8648remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8649 const gdb_byte *myaddr,
8650 ULONGEST len_units,
8651 int unit_size,
8652 ULONGEST *xfered_len_units,
8653 char packet_format, int use_length)
c906108c 8654{
6d820c5c 8655 struct remote_state *rs = get_remote_state ();
cfd77fa1 8656 char *p;
a76d924d
DJ
8657 char *plen = NULL;
8658 int plenlen = 0;
124e13d9
SM
8659 int todo_units;
8660 int units_written;
8661 int payload_capacity_bytes;
8662 int payload_length_bytes;
a76d924d
DJ
8663
8664 if (packet_format != 'X' && packet_format != 'M')
8665 internal_error (__FILE__, __LINE__,
9b20d036 8666 _("remote_write_bytes_aux: bad packet format"));
c906108c 8667
124e13d9 8668 if (len_units == 0)
9b409511 8669 return TARGET_XFER_EOF;
b2182ed2 8670
124e13d9 8671 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8672
6d820c5c
DJ
8673 /* The packet buffer will be large enough for the payload;
8674 get_memory_packet_size ensures this. */
a76d924d 8675 rs->buf[0] = '\0';
c906108c 8676
a257b5bb 8677 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8678 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8679
124e13d9 8680 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8681 if (!use_length)
0df8b418 8682 /* The comma won't be used. */
124e13d9
SM
8683 payload_capacity_bytes += 1;
8684 payload_capacity_bytes -= strlen (header);
8685 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8686
a76d924d 8687 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8688
a76d924d
DJ
8689 strcat (rs->buf, header);
8690 p = rs->buf + strlen (header);
8691
8692 /* Compute a best guess of the number of bytes actually transfered. */
8693 if (packet_format == 'X')
c906108c 8694 {
23860348 8695 /* Best guess at number of bytes that will fit. */
325fac50
PA
8696 todo_units = std::min (len_units,
8697 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8698 if (use_length)
124e13d9 8699 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8700 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8701 }
8702 else
8703 {
124e13d9 8704 /* Number of bytes that will fit. */
325fac50
PA
8705 todo_units
8706 = std::min (len_units,
8707 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8708 if (use_length)
124e13d9 8709 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8710 todo_units = std::min (todo_units,
8711 (payload_capacity_bytes / unit_size) / 2);
917317f4 8712 }
a76d924d 8713
124e13d9 8714 if (todo_units <= 0)
3de11b2e 8715 internal_error (__FILE__, __LINE__,
405f8e94 8716 _("minimum packet size too small to write data"));
802188a7 8717
6765f3e5
DJ
8718 /* If we already need another packet, then try to align the end
8719 of this packet to a useful boundary. */
124e13d9
SM
8720 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8721 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8722
a257b5bb 8723 /* Append "<memaddr>". */
917317f4
JM
8724 memaddr = remote_address_masked (memaddr);
8725 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8726
a76d924d
DJ
8727 if (use_length)
8728 {
8729 /* Append ",". */
8730 *p++ = ',';
802188a7 8731
124e13d9
SM
8732 /* Append the length and retain its location and size. It may need to be
8733 adjusted once the packet body has been created. */
a76d924d 8734 plen = p;
124e13d9 8735 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8736 p += plenlen;
8737 }
a257b5bb
AC
8738
8739 /* Append ":". */
917317f4
JM
8740 *p++ = ':';
8741 *p = '\0';
802188a7 8742
a257b5bb 8743 /* Append the packet body. */
a76d924d 8744 if (packet_format == 'X')
917317f4 8745 {
917317f4
JM
8746 /* Binary mode. Send target system values byte by byte, in
8747 increasing byte addresses. Only escape certain critical
8748 characters. */
124e13d9
SM
8749 payload_length_bytes =
8750 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8751 &units_written, payload_capacity_bytes);
6765f3e5 8752
124e13d9 8753 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8754 a second try to keep the end of the packet aligned. Don't do
8755 this if the packet is tiny. */
124e13d9 8756 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8757 {
124e13d9
SM
8758 int new_todo_units;
8759
8760 new_todo_units = align_for_efficient_write (units_written, memaddr);
8761
8762 if (new_todo_units != units_written)
8763 payload_length_bytes =
8764 remote_escape_output (myaddr, new_todo_units, unit_size,
8765 (gdb_byte *) p, &units_written,
8766 payload_capacity_bytes);
6765f3e5
DJ
8767 }
8768
124e13d9
SM
8769 p += payload_length_bytes;
8770 if (use_length && units_written < todo_units)
c906108c 8771 {
802188a7 8772 /* Escape chars have filled up the buffer prematurely,
124e13d9 8773 and we have actually sent fewer units than planned.
917317f4
JM
8774 Fix-up the length field of the packet. Use the same
8775 number of characters as before. */
124e13d9
SM
8776 plen += hexnumnstr (plen, (ULONGEST) units_written,
8777 plenlen);
917317f4 8778 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8779 }
a76d924d
DJ
8780 }
8781 else
8782 {
917317f4
JM
8783 /* Normal mode: Send target system values byte by byte, in
8784 increasing byte addresses. Each byte is encoded as a two hex
8785 value. */
124e13d9
SM
8786 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8787 units_written = todo_units;
c906108c 8788 }
802188a7 8789
2e9f7625 8790 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8791 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8792
2e9f7625 8793 if (rs->buf[0] == 'E')
00d84524 8794 return TARGET_XFER_E_IO;
802188a7 8795
124e13d9
SM
8796 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8797 send fewer units than we'd planned. */
8798 *xfered_len_units = (ULONGEST) units_written;
92ffd475 8799 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
8800}
8801
a76d924d
DJ
8802/* Write memory data directly to the remote machine.
8803 This does not inform the data cache; the data cache uses this.
8804 MEMADDR is the address in the remote memory space.
8805 MYADDR is the address of the buffer in our space.
8806 LEN is the number of bytes.
8807
9b409511
YQ
8808 Return the transferred status, error or OK (an
8809 'enum target_xfer_status' value). Save the number of bytes
8810 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8811
6b8edb51
PA
8812target_xfer_status
8813remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8814 ULONGEST len, int unit_size,
8815 ULONGEST *xfered_len)
a76d924d 8816{
a121b7c1 8817 const char *packet_format = NULL;
a76d924d
DJ
8818
8819 /* Check whether the target supports binary download. */
8820 check_binary_download (memaddr);
8821
4082afcc 8822 switch (packet_support (PACKET_X))
a76d924d
DJ
8823 {
8824 case PACKET_ENABLE:
8825 packet_format = "X";
8826 break;
8827 case PACKET_DISABLE:
8828 packet_format = "M";
8829 break;
8830 case PACKET_SUPPORT_UNKNOWN:
8831 internal_error (__FILE__, __LINE__,
8832 _("remote_write_bytes: bad internal state"));
8833 default:
8834 internal_error (__FILE__, __LINE__, _("bad switch"));
8835 }
8836
8837 return remote_write_bytes_aux (packet_format,
124e13d9 8838 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8839 packet_format[0], 1);
a76d924d
DJ
8840}
8841
9217e74e
YQ
8842/* Read memory data directly from the remote machine.
8843 This does not use the data cache; the data cache uses this.
8844 MEMADDR is the address in the remote memory space.
8845 MYADDR is the address of the buffer in our space.
124e13d9
SM
8846 LEN_UNITS is the number of addressable memory units to read..
8847 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8848
8849 Return the transferred status, error or OK (an
8850 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8851 transferred in *XFERED_LEN_UNITS.
8852
8853 See the comment of remote_write_bytes_aux for an example of
8854 memory read/write exchange between gdb and the stub. */
9217e74e 8855
6b8edb51
PA
8856target_xfer_status
8857remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8858 ULONGEST len_units,
8859 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8860{
8861 struct remote_state *rs = get_remote_state ();
124e13d9 8862 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8863 char *p;
124e13d9
SM
8864 int todo_units;
8865 int decoded_bytes;
9217e74e 8866
124e13d9 8867 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8868 /* The packet buffer will be large enough for the payload;
8869 get_memory_packet_size ensures this. */
8870
124e13d9 8871 /* Number of units that will fit. */
325fac50
PA
8872 todo_units = std::min (len_units,
8873 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8874
8875 /* Construct "m"<memaddr>","<len>". */
8876 memaddr = remote_address_masked (memaddr);
8877 p = rs->buf;
8878 *p++ = 'm';
8879 p += hexnumstr (p, (ULONGEST) memaddr);
8880 *p++ = ',';
124e13d9 8881 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8882 *p = '\0';
8883 putpkt (rs->buf);
8884 getpkt (&rs->buf, &rs->buf_size, 0);
8885 if (rs->buf[0] == 'E'
8886 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8887 && rs->buf[3] == '\0')
8888 return TARGET_XFER_E_IO;
8889 /* Reply describes memory byte by byte, each byte encoded as two hex
8890 characters. */
8891 p = rs->buf;
124e13d9 8892 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8893 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8894 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 8895 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
8896}
8897
b55fbac4
YQ
8898/* Using the set of read-only target sections of remote, read live
8899 read-only memory.
8acf9577
YQ
8900
8901 For interface/parameters/return description see target.h,
8902 to_xfer_partial. */
8903
6b8edb51
PA
8904target_xfer_status
8905remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8906 ULONGEST memaddr,
8907 ULONGEST len,
8908 int unit_size,
8909 ULONGEST *xfered_len)
8acf9577
YQ
8910{
8911 struct target_section *secp;
8912 struct target_section_table *table;
8913
6b8edb51 8914 secp = target_section_by_addr (this, memaddr);
8acf9577
YQ
8915 if (secp != NULL
8916 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8917 secp->the_bfd_section)
8918 & SEC_READONLY))
8919 {
8920 struct target_section *p;
8921 ULONGEST memend = memaddr + len;
8922
6b8edb51 8923 table = target_get_section_table (this);
8acf9577
YQ
8924
8925 for (p = table->sections; p < table->sections_end; p++)
8926 {
8927 if (memaddr >= p->addr)
8928 {
8929 if (memend <= p->endaddr)
8930 {
8931 /* Entire transfer is within this section. */
124e13d9 8932 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8933 xfered_len);
8acf9577
YQ
8934 }
8935 else if (memaddr >= p->endaddr)
8936 {
8937 /* This section ends before the transfer starts. */
8938 continue;
8939 }
8940 else
8941 {
8942 /* This section overlaps the transfer. Just do half. */
8943 len = p->endaddr - memaddr;
124e13d9 8944 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8945 xfered_len);
8acf9577
YQ
8946 }
8947 }
8948 }
8949 }
8950
8951 return TARGET_XFER_EOF;
8952}
8953
9217e74e
YQ
8954/* Similar to remote_read_bytes_1, but it reads from the remote stub
8955 first if the requested memory is unavailable in traceframe.
8956 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8957
6b8edb51
PA
8958target_xfer_status
8959remote_target::remote_read_bytes (CORE_ADDR memaddr,
8960 gdb_byte *myaddr, ULONGEST len, int unit_size,
8961 ULONGEST *xfered_len)
c906108c 8962{
6b6aa828 8963 if (len == 0)
96c4f946 8964 return TARGET_XFER_EOF;
b2182ed2 8965
8acf9577
YQ
8966 if (get_traceframe_number () != -1)
8967 {
a79b1bc6 8968 std::vector<mem_range> available;
8acf9577
YQ
8969
8970 /* If we fail to get the set of available memory, then the
8971 target does not support querying traceframe info, and so we
8972 attempt reading from the traceframe anyway (assuming the
8973 target implements the old QTro packet then). */
8974 if (traceframe_available_memory (&available, memaddr, len))
8975 {
a79b1bc6 8976 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
8977 {
8978 enum target_xfer_status res;
8979
8980 /* Don't read into the traceframe's available
8981 memory. */
a79b1bc6 8982 if (!available.empty ())
8acf9577
YQ
8983 {
8984 LONGEST oldlen = len;
8985
a79b1bc6 8986 len = available[0].start - memaddr;
8acf9577
YQ
8987 gdb_assert (len <= oldlen);
8988 }
8989
8acf9577 8990 /* This goes through the topmost target again. */
6b8edb51 8991 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 8992 len, unit_size, xfered_len);
8acf9577
YQ
8993 if (res == TARGET_XFER_OK)
8994 return TARGET_XFER_OK;
8995 else
8996 {
8997 /* No use trying further, we know some memory starting
8998 at MEMADDR isn't available. */
8999 *xfered_len = len;
92ffd475
PC
9000 return (*xfered_len != 0) ?
9001 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
9002 }
9003 }
9004
9005 /* Don't try to read more than how much is available, in
9006 case the target implements the deprecated QTro packet to
9007 cater for older GDBs (the target's knowledge of read-only
9008 sections may be outdated by now). */
a79b1bc6 9009 len = available[0].length;
8acf9577
YQ
9010 }
9011 }
9012
124e13d9 9013 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 9014}
74531fed 9015
c906108c 9016\f
c906108c 9017
a76d924d
DJ
9018/* Sends a packet with content determined by the printf format string
9019 FORMAT and the remaining arguments, then gets the reply. Returns
9020 whether the packet was a success, a failure, or unknown. */
9021
6b8edb51
PA
9022packet_result
9023remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
9024{
9025 struct remote_state *rs = get_remote_state ();
9026 int max_size = get_remote_packet_size ();
a76d924d 9027 va_list ap;
a744cf53 9028
a76d924d
DJ
9029 va_start (ap, format);
9030
9031 rs->buf[0] = '\0';
9032 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 9033 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
9034
9035 if (putpkt (rs->buf) < 0)
9036 error (_("Communication problem with target."));
9037
9038 rs->buf[0] = '\0';
9039 getpkt (&rs->buf, &rs->buf_size, 0);
9040
9041 return packet_check_result (rs->buf);
9042}
9043
a76d924d
DJ
9044/* Flash writing can take quite some time. We'll set
9045 effectively infinite timeout for flash operations.
9046 In future, we'll need to decide on a better approach. */
9047static const int remote_flash_timeout = 1000;
9048
f6ac5f3d
PA
9049void
9050remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 9051{
f5656ead 9052 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 9053 enum packet_result ret;
2ec845e7
TT
9054 scoped_restore restore_timeout
9055 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
9056
9057 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 9058 phex (address, addr_size),
a76d924d
DJ
9059 phex (length, 4));
9060 switch (ret)
9061 {
9062 case PACKET_UNKNOWN:
9063 error (_("Remote target does not support flash erase"));
9064 case PACKET_ERROR:
9065 error (_("Error erasing flash with vFlashErase packet"));
9066 default:
9067 break;
9068 }
a76d924d
DJ
9069}
9070
6b8edb51
PA
9071target_xfer_status
9072remote_target::remote_flash_write (ULONGEST address,
9073 ULONGEST length, ULONGEST *xfered_len,
9074 const gdb_byte *data)
a76d924d 9075{
2ec845e7
TT
9076 scoped_restore restore_timeout
9077 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9078 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9079 xfered_len,'X', 0);
a76d924d
DJ
9080}
9081
f6ac5f3d
PA
9082void
9083remote_target::flash_done ()
a76d924d 9084{
a76d924d 9085 int ret;
a76d924d 9086
2ec845e7
TT
9087 scoped_restore restore_timeout
9088 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9089
a76d924d 9090 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
9091
9092 switch (ret)
9093 {
9094 case PACKET_UNKNOWN:
9095 error (_("Remote target does not support vFlashDone"));
9096 case PACKET_ERROR:
9097 error (_("Error finishing flash operation"));
9098 default:
9099 break;
9100 }
9101}
9102
f6ac5f3d
PA
9103void
9104remote_target::files_info ()
c906108c
SS
9105{
9106 puts_filtered ("Debugging a target over a serial line.\n");
9107}
9108\f
9109/* Stuff for dealing with the packets which are part of this protocol.
9110 See comment at top of file for details. */
9111
1927e618
PA
9112/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9113 error to higher layers. Called when a serial error is detected.
9114 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
9115 the system error message for errno at function entry and final dot
9116 for output compatibility with throw_perror_with_name. */
1927e618
PA
9117
9118static void
9119unpush_and_perror (const char *string)
9120{
d6cb50a2 9121 int saved_errno = errno;
1927e618
PA
9122
9123 remote_unpush_target ();
d6cb50a2
JK
9124 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9125 safe_strerror (saved_errno));
1927e618
PA
9126}
9127
048094ac
PA
9128/* Read a single character from the remote end. The current quit
9129 handler is overridden to avoid quitting in the middle of packet
9130 sequence, as that would break communication with the remote server.
9131 See remote_serial_quit_handler for more detail. */
c906108c 9132
6b8edb51
PA
9133int
9134remote_target::readchar (int timeout)
c906108c
SS
9135{
9136 int ch;
5d93a237 9137 struct remote_state *rs = get_remote_state ();
048094ac 9138
2ec845e7 9139 {
6b8edb51
PA
9140 scoped_restore restore_quit_target
9141 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9142 scoped_restore restore_quit
6b8edb51 9143 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9144
2ec845e7 9145 rs->got_ctrlc_during_io = 0;
c906108c 9146
2ec845e7 9147 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9148
2ec845e7
TT
9149 if (rs->got_ctrlc_during_io)
9150 set_quit_flag ();
9151 }
048094ac 9152
2acceee2 9153 if (ch >= 0)
0876f84a 9154 return ch;
2acceee2
JM
9155
9156 switch ((enum serial_rc) ch)
c906108c
SS
9157 {
9158 case SERIAL_EOF:
78a095c3 9159 remote_unpush_target ();
598d3636 9160 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9161 /* no return */
c906108c 9162 case SERIAL_ERROR:
1927e618
PA
9163 unpush_and_perror (_("Remote communication error. "
9164 "Target disconnected."));
2acceee2 9165 /* no return */
c906108c 9166 case SERIAL_TIMEOUT:
2acceee2 9167 break;
c906108c 9168 }
2acceee2 9169 return ch;
c906108c
SS
9170}
9171
c33e31fd 9172/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9173 writing fails. The current quit handler is overridden to avoid
9174 quitting in the middle of packet sequence, as that would break
9175 communication with the remote server. See
9176 remote_serial_quit_handler for more detail. */
c33e31fd 9177
6b8edb51
PA
9178void
9179remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9180{
5d93a237 9181 struct remote_state *rs = get_remote_state ();
048094ac 9182
6b8edb51
PA
9183 scoped_restore restore_quit_target
9184 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9185 scoped_restore restore_quit
6b8edb51 9186 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9187
9188 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9189
9190 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9191 {
1927e618
PA
9192 unpush_and_perror (_("Remote communication error. "
9193 "Target disconnected."));
c33e31fd 9194 }
048094ac
PA
9195
9196 if (rs->got_ctrlc_during_io)
9197 set_quit_flag ();
c33e31fd
PA
9198}
9199
b3ced9ba
PA
9200/* Return a string representing an escaped version of BUF, of len N.
9201 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9202
b3ced9ba 9203static std::string
6e5abd65
PA
9204escape_buffer (const char *buf, int n)
9205{
d7e74731 9206 string_file stb;
6e5abd65 9207
d7e74731
PA
9208 stb.putstrn (buf, n, '\\');
9209 return std::move (stb.string ());
6e5abd65
PA
9210}
9211
c906108c
SS
9212/* Display a null-terminated packet on stdout, for debugging, using C
9213 string notation. */
9214
9215static void
baa336ce 9216print_packet (const char *buf)
c906108c
SS
9217{
9218 puts_filtered ("\"");
43e526b9 9219 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
9220 puts_filtered ("\"");
9221}
9222
9223int
6b8edb51 9224remote_target::putpkt (const char *buf)
c906108c
SS
9225{
9226 return putpkt_binary (buf, strlen (buf));
9227}
9228
6b8edb51
PA
9229/* Wrapper around remote_target::putpkt to avoid exporting
9230 remote_target. */
9231
9232int
9233putpkt (remote_target *remote, const char *buf)
9234{
9235 return remote->putpkt (buf);
9236}
9237
c906108c 9238/* Send a packet to the remote machine, with error checking. The data
23860348 9239 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9240 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9241 and for a possible /0 if we are debugging (remote_debug) and want
9242 to print the sent packet as a string. */
c906108c 9243
6b8edb51
PA
9244int
9245remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9246{
2d717e4f 9247 struct remote_state *rs = get_remote_state ();
c906108c
SS
9248 int i;
9249 unsigned char csum = 0;
b80406ac
TT
9250 gdb::def_vector<char> data (cnt + 6);
9251 char *buf2 = data.data ();
085dd6e6 9252
c906108c
SS
9253 int ch;
9254 int tcount = 0;
9255 char *p;
9256
e24a49d8
PA
9257 /* Catch cases like trying to read memory or listing threads while
9258 we're waiting for a stop reply. The remote server wouldn't be
9259 ready to handle this request, so we'd hang and timeout. We don't
9260 have to worry about this in synchronous mode, because in that
9261 case it's not possible to issue a command while the target is
74531fed
PA
9262 running. This is not a problem in non-stop mode, because in that
9263 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9264 if (!target_is_non_stop_p ()
9265 && target_is_async_p ()
9266 && rs->waiting_for_stop_reply)
9597b22a
DE
9267 {
9268 error (_("Cannot execute this command while the target is running.\n"
9269 "Use the \"interrupt\" command to stop the target\n"
9270 "and then try again."));
9271 }
e24a49d8 9272
2d717e4f
DJ
9273 /* We're sending out a new packet. Make sure we don't look at a
9274 stale cached response. */
9275 rs->cached_wait_status = 0;
9276
c906108c
SS
9277 /* Copy the packet into buffer BUF2, encapsulating it
9278 and giving it a checksum. */
9279
c906108c
SS
9280 p = buf2;
9281 *p++ = '$';
9282
9283 for (i = 0; i < cnt; i++)
9284 {
9285 csum += buf[i];
9286 *p++ = buf[i];
9287 }
9288 *p++ = '#';
9289 *p++ = tohex ((csum >> 4) & 0xf);
9290 *p++ = tohex (csum & 0xf);
9291
9292 /* Send it over and over until we get a positive ack. */
9293
9294 while (1)
9295 {
9296 int started_error_output = 0;
9297
9298 if (remote_debug)
9299 {
9300 *p = '\0';
b3ced9ba 9301
6f8976bf
YQ
9302 int len = (int) (p - buf2);
9303
9304 std::string str
9305 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9306
9307 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9308
567a3e54
SM
9309 if (len > REMOTE_DEBUG_MAX_CHAR)
9310 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9311 len - REMOTE_DEBUG_MAX_CHAR);
6f8976bf
YQ
9312
9313 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 9314
0f71a2f6 9315 gdb_flush (gdb_stdlog);
c906108c 9316 }
c33e31fd 9317 remote_serial_write (buf2, p - buf2);
c906108c 9318
a6f3e723
SL
9319 /* If this is a no acks version of the remote protocol, send the
9320 packet and move on. */
9321 if (rs->noack_mode)
9322 break;
9323
74531fed
PA
9324 /* Read until either a timeout occurs (-2) or '+' is read.
9325 Handle any notification that arrives in the mean time. */
c906108c
SS
9326 while (1)
9327 {
9328 ch = readchar (remote_timeout);
9329
c5aa993b 9330 if (remote_debug)
c906108c
SS
9331 {
9332 switch (ch)
9333 {
9334 case '+':
1216fa2c 9335 case '-':
c906108c
SS
9336 case SERIAL_TIMEOUT:
9337 case '$':
74531fed 9338 case '%':
c906108c
SS
9339 if (started_error_output)
9340 {
9341 putchar_unfiltered ('\n');
9342 started_error_output = 0;
9343 }
9344 }
9345 }
9346
9347 switch (ch)
9348 {
9349 case '+':
9350 if (remote_debug)
0f71a2f6 9351 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 9352 return 1;
1216fa2c
AC
9353 case '-':
9354 if (remote_debug)
9355 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 9356 /* FALLTHROUGH */
c906108c 9357 case SERIAL_TIMEOUT:
c5aa993b 9358 tcount++;
c906108c 9359 if (tcount > 3)
b80406ac 9360 return 0;
23860348 9361 break; /* Retransmit buffer. */
c906108c
SS
9362 case '$':
9363 {
40e3f985 9364 if (remote_debug)
2bc416ba 9365 fprintf_unfiltered (gdb_stdlog,
23860348 9366 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
9367 /* It's probably an old response sent because an ACK
9368 was lost. Gobble up the packet and ack it so it
9369 doesn't get retransmitted when we resend this
9370 packet. */
6d820c5c 9371 skip_frame ();
c33e31fd 9372 remote_serial_write ("+", 1);
23860348 9373 continue; /* Now, go look for +. */
c906108c 9374 }
74531fed
PA
9375
9376 case '%':
9377 {
9378 int val;
9379
9380 /* If we got a notification, handle it, and go back to looking
9381 for an ack. */
9382 /* We've found the start of a notification. Now
9383 collect the data. */
9384 val = read_frame (&rs->buf, &rs->buf_size);
9385 if (val >= 0)
9386 {
9387 if (remote_debug)
9388 {
b3ced9ba 9389 std::string str = escape_buffer (rs->buf, val);
6e5abd65 9390
6e5abd65
PA
9391 fprintf_unfiltered (gdb_stdlog,
9392 " Notification received: %s\n",
b3ced9ba 9393 str.c_str ());
74531fed 9394 }
5965e028 9395 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
9396 /* We're in sync now, rewait for the ack. */
9397 tcount = 0;
9398 }
9399 else
9400 {
9401 if (remote_debug)
9402 {
9403 if (!started_error_output)
9404 {
9405 started_error_output = 1;
9406 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9407 }
9408 fputc_unfiltered (ch & 0177, gdb_stdlog);
9409 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9410 }
9411 }
9412 continue;
9413 }
9414 /* fall-through */
c906108c
SS
9415 default:
9416 if (remote_debug)
9417 {
9418 if (!started_error_output)
9419 {
9420 started_error_output = 1;
0f71a2f6 9421 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 9422 }
0f71a2f6 9423 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
9424 }
9425 continue;
9426 }
23860348 9427 break; /* Here to retransmit. */
c906108c
SS
9428 }
9429
9430#if 0
9431 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
9432 able to get out next time we call QUIT, without anything as
9433 violent as interrupt_query. If we want to provide a way out of
9434 here without getting to the next QUIT, it should be based on
9435 hitting ^C twice as in remote_wait. */
c906108c
SS
9436 if (quit_flag)
9437 {
9438 quit_flag = 0;
9439 interrupt_query ();
9440 }
9441#endif
9442 }
a5c0808e 9443
a6f3e723 9444 return 0;
c906108c
SS
9445}
9446
6d820c5c
DJ
9447/* Come here after finding the start of a frame when we expected an
9448 ack. Do our best to discard the rest of this packet. */
9449
6b8edb51
PA
9450void
9451remote_target::skip_frame ()
6d820c5c
DJ
9452{
9453 int c;
9454
9455 while (1)
9456 {
9457 c = readchar (remote_timeout);
9458 switch (c)
9459 {
9460 case SERIAL_TIMEOUT:
9461 /* Nothing we can do. */
9462 return;
9463 case '#':
9464 /* Discard the two bytes of checksum and stop. */
9465 c = readchar (remote_timeout);
9466 if (c >= 0)
9467 c = readchar (remote_timeout);
9468
9469 return;
9470 case '*': /* Run length encoding. */
9471 /* Discard the repeat count. */
9472 c = readchar (remote_timeout);
9473 if (c < 0)
9474 return;
9475 break;
9476 default:
9477 /* A regular character. */
9478 break;
9479 }
9480 }
9481}
9482
c906108c 9483/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9484 into *BUF, verifying the checksum, length, and handling run-length
9485 compression. NUL terminate the buffer. If there is not enough room,
9486 expand *BUF using xrealloc.
c906108c 9487
c2d11a7d
JM
9488 Returns -1 on error, number of characters in buffer (ignoring the
9489 trailing NULL) on success. (could be extended to return one of the
23860348 9490 SERIAL status indications). */
c2d11a7d 9491
6b8edb51
PA
9492long
9493remote_target::read_frame (char **buf_p, long *sizeof_buf)
c906108c
SS
9494{
9495 unsigned char csum;
c2d11a7d 9496 long bc;
c906108c 9497 int c;
6d820c5c 9498 char *buf = *buf_p;
a6f3e723 9499 struct remote_state *rs = get_remote_state ();
c906108c
SS
9500
9501 csum = 0;
c2d11a7d 9502 bc = 0;
c906108c
SS
9503
9504 while (1)
9505 {
9506 c = readchar (remote_timeout);
c906108c
SS
9507 switch (c)
9508 {
9509 case SERIAL_TIMEOUT:
9510 if (remote_debug)
0f71a2f6 9511 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 9512 return -1;
c906108c
SS
9513 case '$':
9514 if (remote_debug)
0f71a2f6
JM
9515 fputs_filtered ("Saw new packet start in middle of old one\n",
9516 gdb_stdlog);
23860348 9517 return -1; /* Start a new packet, count retries. */
c906108c
SS
9518 case '#':
9519 {
9520 unsigned char pktcsum;
e1b09194
AC
9521 int check_0 = 0;
9522 int check_1 = 0;
c906108c 9523
c2d11a7d 9524 buf[bc] = '\0';
c906108c 9525
e1b09194
AC
9526 check_0 = readchar (remote_timeout);
9527 if (check_0 >= 0)
9528 check_1 = readchar (remote_timeout);
802188a7 9529
e1b09194
AC
9530 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9531 {
9532 if (remote_debug)
2bc416ba 9533 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 9534 gdb_stdlog);
e1b09194
AC
9535 return -1;
9536 }
9537 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
9538 {
9539 if (remote_debug)
2bc416ba 9540 fputs_filtered ("Communication error in checksum\n",
23860348 9541 gdb_stdlog);
40e3f985
FN
9542 return -1;
9543 }
c906108c 9544
a6f3e723
SL
9545 /* Don't recompute the checksum; with no ack packets we
9546 don't have any way to indicate a packet retransmission
9547 is necessary. */
9548 if (rs->noack_mode)
9549 return bc;
9550
e1b09194 9551 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9552 if (csum == pktcsum)
c2d11a7d 9553 return bc;
c906108c 9554
c5aa993b 9555 if (remote_debug)
c906108c 9556 {
b3ced9ba 9557 std::string str = escape_buffer (buf, bc);
6e5abd65 9558
6e5abd65 9559 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9560 "Bad checksum, sentsum=0x%x, "
9561 "csum=0x%x, buf=%s\n",
b3ced9ba 9562 pktcsum, csum, str.c_str ());
c906108c 9563 }
c2d11a7d 9564 /* Number of characters in buffer ignoring trailing
23860348 9565 NULL. */
c2d11a7d 9566 return -1;
c906108c 9567 }
23860348 9568 case '*': /* Run length encoding. */
c2c6d25f
JM
9569 {
9570 int repeat;
c906108c 9571
a744cf53 9572 csum += c;
b4501125
AC
9573 c = readchar (remote_timeout);
9574 csum += c;
23860348 9575 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9576
23860348 9577 /* The character before ``*'' is repeated. */
c2d11a7d 9578
6d820c5c 9579 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9580 {
6d820c5c
DJ
9581 if (bc + repeat - 1 >= *sizeof_buf - 1)
9582 {
9583 /* Make some more room in the buffer. */
9584 *sizeof_buf += repeat;
224c3ddb 9585 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
9586 buf = *buf_p;
9587 }
9588
c2d11a7d
JM
9589 memset (&buf[bc], buf[bc - 1], repeat);
9590 bc += repeat;
c2c6d25f
JM
9591 continue;
9592 }
9593
c2d11a7d 9594 buf[bc] = '\0';
6d820c5c 9595 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9596 return -1;
c2c6d25f 9597 }
c906108c 9598 default:
6d820c5c 9599 if (bc >= *sizeof_buf - 1)
c906108c 9600 {
6d820c5c
DJ
9601 /* Make some more room in the buffer. */
9602 *sizeof_buf *= 2;
224c3ddb 9603 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 9604 buf = *buf_p;
c906108c
SS
9605 }
9606
6d820c5c
DJ
9607 buf[bc++] = c;
9608 csum += c;
9609 continue;
c906108c
SS
9610 }
9611 }
9612}
9613
9614/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9615 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9616 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9617 rather than timing out; this is used (in synchronous mode) to wait
9618 for a target that is is executing user code to stop. */
d9fcf2fb
JM
9619/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9620 don't have to change all the calls to getpkt to deal with the
9621 return value, because at the moment I don't know what the right
23860348 9622 thing to do it for those. */
6b8edb51 9623
c906108c 9624void
6b8edb51 9625remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
d9fcf2fb 9626{
54887903 9627 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
9628}
9629
9630
9631/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9632 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9633 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9634 rather than timing out; this is used (in synchronous mode) to wait
9635 for a target that is is executing user code to stop. If FOREVER ==
9636 0, this function is allowed to time out gracefully and return an
74531fed
PA
9637 indication of this to the caller. Otherwise return the number of
9638 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
9639 enough reason to return to the caller. *IS_NOTIF is an output
9640 boolean that indicates whether *BUF holds a notification or not
9641 (a regular packet). */
74531fed 9642
6b8edb51
PA
9643int
9644remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9645 int forever, int expecting_notif,
9646 int *is_notif)
c906108c 9647{
2d717e4f 9648 struct remote_state *rs = get_remote_state ();
c906108c
SS
9649 int c;
9650 int tries;
9651 int timeout;
df4b58fe 9652 int val = -1;
c906108c 9653
2d717e4f
DJ
9654 /* We're reading a new response. Make sure we don't look at a
9655 previously cached response. */
9656 rs->cached_wait_status = 0;
9657
6d820c5c 9658 strcpy (*buf, "timeout");
c906108c
SS
9659
9660 if (forever)
74531fed
PA
9661 timeout = watchdog > 0 ? watchdog : -1;
9662 else if (expecting_notif)
9663 timeout = 0; /* There should already be a char in the buffer. If
9664 not, bail out. */
c906108c
SS
9665 else
9666 timeout = remote_timeout;
9667
9668#define MAX_TRIES 3
9669
74531fed
PA
9670 /* Process any number of notifications, and then return when
9671 we get a packet. */
9672 for (;;)
c906108c 9673 {
d9c43928 9674 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9675 times. */
9676 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9677 {
74531fed
PA
9678 /* This can loop forever if the remote side sends us
9679 characters continuously, but if it pauses, we'll get
9680 SERIAL_TIMEOUT from readchar because of timeout. Then
9681 we'll count that as a retry.
9682
9683 Note that even when forever is set, we will only wait
9684 forever prior to the start of a packet. After that, we
9685 expect characters to arrive at a brisk pace. They should
9686 show up within remote_timeout intervals. */
9687 do
9688 c = readchar (timeout);
9689 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9690
9691 if (c == SERIAL_TIMEOUT)
9692 {
74531fed
PA
9693 if (expecting_notif)
9694 return -1; /* Don't complain, it's normal to not get
9695 anything in this case. */
9696
23860348 9697 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9698 {
78a095c3 9699 remote_unpush_target ();
598d3636
JK
9700 throw_error (TARGET_CLOSE_ERROR,
9701 _("Watchdog timeout has expired. "
9702 "Target detached."));
c906108c 9703 }
c906108c 9704 if (remote_debug)
0f71a2f6 9705 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9706 }
74531fed
PA
9707 else
9708 {
9709 /* We've found the start of a packet or notification.
9710 Now collect the data. */
9711 val = read_frame (buf, sizeof_buf);
9712 if (val >= 0)
9713 break;
9714 }
9715
c33e31fd 9716 remote_serial_write ("-", 1);
c906108c 9717 }
c906108c 9718
74531fed
PA
9719 if (tries > MAX_TRIES)
9720 {
9721 /* We have tried hard enough, and just can't receive the
9722 packet/notification. Give up. */
9723 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9724
74531fed
PA
9725 /* Skip the ack char if we're in no-ack mode. */
9726 if (!rs->noack_mode)
c33e31fd 9727 remote_serial_write ("+", 1);
74531fed
PA
9728 return -1;
9729 }
c906108c 9730
74531fed
PA
9731 /* If we got an ordinary packet, return that to our caller. */
9732 if (c == '$')
c906108c
SS
9733 {
9734 if (remote_debug)
43e526b9 9735 {
6f8976bf
YQ
9736 std::string str
9737 = escape_buffer (*buf,
9738 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9739
9740 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9741 str.c_str ());
9742
567a3e54
SM
9743 if (val > REMOTE_DEBUG_MAX_CHAR)
9744 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9745 val - REMOTE_DEBUG_MAX_CHAR);
6e5abd65 9746
6f8976bf 9747 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9748 }
a6f3e723
SL
9749
9750 /* Skip the ack char if we're in no-ack mode. */
9751 if (!rs->noack_mode)
c33e31fd 9752 remote_serial_write ("+", 1);
fee9eda9
YQ
9753 if (is_notif != NULL)
9754 *is_notif = 0;
0876f84a 9755 return val;
c906108c
SS
9756 }
9757
74531fed
PA
9758 /* If we got a notification, handle it, and go back to looking
9759 for a packet. */
9760 else
9761 {
9762 gdb_assert (c == '%');
9763
9764 if (remote_debug)
9765 {
b3ced9ba 9766 std::string str = escape_buffer (*buf, val);
6e5abd65 9767
6e5abd65
PA
9768 fprintf_unfiltered (gdb_stdlog,
9769 " Notification received: %s\n",
b3ced9ba 9770 str.c_str ());
74531fed 9771 }
fee9eda9
YQ
9772 if (is_notif != NULL)
9773 *is_notif = 1;
c906108c 9774
5965e028 9775 handle_notification (rs->notif_state, *buf);
c906108c 9776
74531fed 9777 /* Notifications require no acknowledgement. */
a6f3e723 9778
74531fed 9779 if (expecting_notif)
fee9eda9 9780 return val;
74531fed
PA
9781 }
9782 }
9783}
9784
6b8edb51
PA
9785int
9786remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
74531fed 9787{
fee9eda9 9788 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
9789}
9790
6b8edb51
PA
9791int
9792remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9793 int *is_notif)
74531fed 9794{
fee9eda9
YQ
9795 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9796 is_notif);
c906108c 9797}
74531fed 9798
cbb8991c
DB
9799/* Check whether EVENT is a fork event for the process specified
9800 by the pid passed in DATA, and if it is, kill the fork child. */
9801
6b8edb51
PA
9802int
9803remote_kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9804 QUEUE_ITER (stop_reply_p) *iter,
9805 stop_reply_p event,
9806 void *data)
cbb8991c 9807{
19ba03f4 9808 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
9809 int parent_pid = *(int *) param->input;
9810
9811 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9812 {
6b8edb51 9813 remote_target *remote = param->remote;
cbb8991c
DB
9814 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9815 int res;
9816
6b8edb51 9817 res = remote->remote_vkill (child_pid);
cbb8991c
DB
9818 if (res != 0)
9819 error (_("Can't kill fork child process %d"), child_pid);
9820 }
9821
9822 return 1;
9823}
9824
9825/* Kill any new fork children of process PID that haven't been
9826 processed by follow_fork. */
9827
6b8edb51
PA
9828void
9829remote_target::kill_new_fork_children (int pid)
cbb8991c 9830{
6b8edb51 9831 remote_state *rs = get_remote_state ();
cbb8991c
DB
9832 struct thread_info *thread;
9833 struct notif_client *notif = &notif_client_stop;
9834 struct queue_iter_param param;
9835
9836 /* Kill the fork child threads of any threads in process PID
9837 that are stopped at a fork event. */
9838 ALL_NON_EXITED_THREADS (thread)
9839 {
9840 struct target_waitstatus *ws = &thread->pending_follow;
9841
9842 if (is_pending_fork_parent (ws, pid, thread->ptid))
9843 {
cbb8991c
DB
9844 int child_pid = ptid_get_pid (ws->value.related_pid);
9845 int res;
9846
6b8edb51 9847 res = remote_vkill (child_pid);
cbb8991c
DB
9848 if (res != 0)
9849 error (_("Can't kill fork child process %d"), child_pid);
9850 }
9851 }
9852
9853 /* Check for any pending fork events (not reported or processed yet)
9854 in process PID and kill those fork child threads as well. */
9855 remote_notif_get_pending_events (notif);
6b8edb51 9856 param.remote = this;
cbb8991c
DB
9857 param.input = &pid;
9858 param.output = NULL;
6b8edb51
PA
9859 QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
9860 remote_kill_child_of_pending_fork, &param);
cbb8991c
DB
9861}
9862
c906108c 9863\f
8020350c
DB
9864/* Target hook to kill the current inferior. */
9865
f6ac5f3d
PA
9866void
9867remote_target::kill ()
43ff13b4 9868{
8020350c
DB
9869 int res = -1;
9870 int pid = ptid_get_pid (inferior_ptid);
9871 struct remote_state *rs = get_remote_state ();
0fdf84ca 9872
8020350c 9873 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9874 {
8020350c
DB
9875 /* If we're stopped while forking and we haven't followed yet,
9876 kill the child task. We need to do this before killing the
9877 parent task because if this is a vfork then the parent will
9878 be sleeping. */
6b8edb51 9879 kill_new_fork_children (pid);
8020350c 9880
6b8edb51 9881 res = remote_vkill (pid);
8020350c 9882 if (res == 0)
0fdf84ca 9883 {
bc1e6c81 9884 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9885 return;
9886 }
8020350c 9887 }
0fdf84ca 9888
8020350c
DB
9889 /* If we are in 'target remote' mode and we are killing the only
9890 inferior, then we will tell gdbserver to exit and unpush the
9891 target. */
9892 if (res == -1 && !remote_multi_process_p (rs)
9893 && number_of_live_inferiors () == 1)
9894 {
9895 remote_kill_k ();
9896
9897 /* We've killed the remote end, we get to mourn it. If we are
9898 not in extended mode, mourning the inferior also unpushes
9899 remote_ops from the target stack, which closes the remote
9900 connection. */
bc1e6c81 9901 target_mourn_inferior (inferior_ptid);
8020350c
DB
9902
9903 return;
0fdf84ca 9904 }
43ff13b4 9905
8020350c 9906 error (_("Can't kill process"));
43ff13b4
JM
9907}
9908
8020350c
DB
9909/* Send a kill request to the target using the 'vKill' packet. */
9910
6b8edb51
PA
9911int
9912remote_target::remote_vkill (int pid)
82f73884 9913{
4082afcc 9914 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9915 return -1;
9916
6b8edb51
PA
9917 remote_state *rs = get_remote_state ();
9918
82f73884 9919 /* Tell the remote target to detach. */
bba74b36 9920 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
9921 putpkt (rs->buf);
9922 getpkt (&rs->buf, &rs->buf_size, 0);
9923
4082afcc
PA
9924 switch (packet_ok (rs->buf,
9925 &remote_protocol_packets[PACKET_vKill]))
9926 {
9927 case PACKET_OK:
9928 return 0;
9929 case PACKET_ERROR:
9930 return 1;
9931 case PACKET_UNKNOWN:
9932 return -1;
9933 default:
9934 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9935 }
82f73884
PA
9936}
9937
8020350c
DB
9938/* Send a kill request to the target using the 'k' packet. */
9939
6b8edb51
PA
9940void
9941remote_target::remote_kill_k ()
82f73884 9942{
8020350c
DB
9943 /* Catch errors so the user can quit from gdb even when we
9944 aren't on speaking terms with the remote system. */
9945 TRY
82f73884 9946 {
82f73884 9947 putpkt ("k");
82f73884 9948 }
8020350c
DB
9949 CATCH (ex, RETURN_MASK_ERROR)
9950 {
9951 if (ex.error == TARGET_CLOSE_ERROR)
9952 {
9953 /* If we got an (EOF) error that caused the target
9954 to go away, then we're done, that's what we wanted.
9955 "k" is susceptible to cause a premature EOF, given
9956 that the remote server isn't actually required to
9957 reply to "k", and it can happen that it doesn't
9958 even get to reply ACK to the "k". */
9959 return;
9960 }
82f73884 9961
8020350c
DB
9962 /* Otherwise, something went wrong. We didn't actually kill
9963 the target. Just propagate the exception, and let the
9964 user or higher layers decide what to do. */
9965 throw_exception (ex);
9966 }
9967 END_CATCH
82f73884
PA
9968}
9969
f6ac5f3d
PA
9970void
9971remote_target::mourn_inferior ()
c906108c 9972{
8020350c 9973 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9974
9607784a
PA
9975 /* We're no longer interested in notification events of an inferior
9976 that exited or was killed/detached. */
9977 discard_pending_stop_replies (current_inferior ());
9978
8020350c
DB
9979 /* In 'target remote' mode with one inferior, we close the connection. */
9980 if (!rs->extended && number_of_live_inferiors () <= 1)
9981 {
f6ac5f3d 9982 unpush_target (this);
c906108c 9983
8020350c
DB
9984 /* remote_close takes care of doing most of the clean up. */
9985 generic_mourn_inferior ();
9986 return;
9987 }
c906108c 9988
e24a49d8
PA
9989 /* In case we got here due to an error, but we're going to stay
9990 connected. */
9991 rs->waiting_for_stop_reply = 0;
9992
dc1981d7
PA
9993 /* If the current general thread belonged to the process we just
9994 detached from or has exited, the remote side current general
9995 thread becomes undefined. Considering a case like this:
9996
9997 - We just got here due to a detach.
9998 - The process that we're detaching from happens to immediately
9999 report a global breakpoint being hit in non-stop mode, in the
10000 same thread we had selected before.
10001 - GDB attaches to this process again.
10002 - This event happens to be the next event we handle.
10003
10004 GDB would consider that the current general thread didn't need to
10005 be set on the stub side (with Hg), since for all it knew,
10006 GENERAL_THREAD hadn't changed.
10007
10008 Notice that although in all-stop mode, the remote server always
10009 sets the current thread to the thread reporting the stop event,
10010 that doesn't happen in non-stop mode; in non-stop, the stub *must
10011 not* change the current thread when reporting a breakpoint hit,
10012 due to the decoupling of event reporting and event handling.
10013
10014 To keep things simple, we always invalidate our notion of the
10015 current thread. */
47f8a51d 10016 record_currthread (rs, minus_one_ptid);
dc1981d7 10017
8020350c 10018 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
10019 generic_mourn_inferior ();
10020
d729566a 10021 if (!have_inferiors ())
2d717e4f 10022 {
82f73884
PA
10023 if (!remote_multi_process_p (rs))
10024 {
10025 /* Check whether the target is running now - some remote stubs
10026 automatically restart after kill. */
10027 putpkt ("?");
10028 getpkt (&rs->buf, &rs->buf_size, 0);
10029
10030 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
10031 {
3e43a32a
MS
10032 /* Assume that the target has been restarted. Set
10033 inferior_ptid so that bits of core GDB realizes
10034 there's something here, e.g., so that the user can
10035 say "kill" again. */
82f73884
PA
10036 inferior_ptid = magic_null_ptid;
10037 }
82f73884 10038 }
2d717e4f
DJ
10039 }
10040}
c906108c 10041
57810aa7 10042bool
f6ac5f3d 10043extended_remote_target::supports_disable_randomization ()
03583c20 10044{
4082afcc 10045 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
10046}
10047
6b8edb51
PA
10048void
10049remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
10050{
10051 struct remote_state *rs = get_remote_state ();
10052 char *reply;
10053
bba74b36
YQ
10054 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
10055 val);
03583c20 10056 putpkt (rs->buf);
b6bb3468 10057 reply = remote_get_noisy_reply ();
03583c20
UW
10058 if (*reply == '\0')
10059 error (_("Target does not support QDisableRandomization."));
10060 if (strcmp (reply, "OK") != 0)
10061 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10062}
10063
6b8edb51
PA
10064int
10065remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
10066{
10067 struct remote_state *rs = get_remote_state ();
2d717e4f 10068 int len;
94585166 10069 const char *remote_exec_file = get_remote_exec_file ();
c906108c 10070
2d717e4f
DJ
10071 /* If the user has disabled vRun support, or we have detected that
10072 support is not available, do not try it. */
4082afcc 10073 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 10074 return -1;
424163ea 10075
2d717e4f
DJ
10076 strcpy (rs->buf, "vRun;");
10077 len = strlen (rs->buf);
c906108c 10078
2d717e4f
DJ
10079 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10080 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
10081 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
10082 strlen (remote_exec_file));
2d717e4f 10083
7c5ded6a 10084 if (!args.empty ())
2d717e4f 10085 {
2d717e4f 10086 int i;
2d717e4f 10087
773a1edc 10088 gdb_argv argv (args.c_str ());
2d717e4f
DJ
10089 for (i = 0; argv[i] != NULL; i++)
10090 {
10091 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10092 error (_("Argument list too long for run packet"));
10093 rs->buf[len++] = ';';
9f1b45b0
TT
10094 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
10095 strlen (argv[i]));
2d717e4f 10096 }
2d717e4f
DJ
10097 }
10098
10099 rs->buf[len++] = '\0';
10100
10101 putpkt (rs->buf);
10102 getpkt (&rs->buf, &rs->buf_size, 0);
10103
4082afcc 10104 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 10105 {
4082afcc 10106 case PACKET_OK:
3405876a 10107 /* We have a wait response. All is well. */
2d717e4f 10108 return 0;
4082afcc
PA
10109 case PACKET_UNKNOWN:
10110 return -1;
10111 case PACKET_ERROR:
2d717e4f
DJ
10112 if (remote_exec_file[0] == '\0')
10113 error (_("Running the default executable on the remote target failed; "
10114 "try \"set remote exec-file\"?"));
10115 else
10116 error (_("Running \"%s\" on the remote target failed"),
10117 remote_exec_file);
4082afcc
PA
10118 default:
10119 gdb_assert_not_reached (_("bad switch"));
2d717e4f 10120 }
c906108c
SS
10121}
10122
0a2dde4a
SDJ
10123/* Helper function to send set/unset environment packets. ACTION is
10124 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10125 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10126 sent. */
10127
6b8edb51
PA
10128void
10129remote_target::send_environment_packet (const char *action,
10130 const char *packet,
10131 const char *value)
0a2dde4a 10132{
6b8edb51
PA
10133 remote_state *rs = get_remote_state ();
10134
0a2dde4a
SDJ
10135 /* Convert the environment variable to an hex string, which
10136 is the best format to be transmitted over the wire. */
10137 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10138 strlen (value));
10139
10140 xsnprintf (rs->buf, get_remote_packet_size (),
10141 "%s:%s", packet, encoded_value.c_str ());
10142
10143 putpkt (rs->buf);
10144 getpkt (&rs->buf, &rs->buf_size, 0);
10145 if (strcmp (rs->buf, "OK") != 0)
10146 warning (_("Unable to %s environment variable '%s' on remote."),
10147 action, value);
10148}
10149
10150/* Helper function to handle the QEnvironment* packets. */
10151
6b8edb51
PA
10152void
10153remote_target::extended_remote_environment_support ()
0a2dde4a 10154{
6b8edb51
PA
10155 remote_state *rs = get_remote_state ();
10156
0a2dde4a
SDJ
10157 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10158 {
10159 putpkt ("QEnvironmentReset");
10160 getpkt (&rs->buf, &rs->buf_size, 0);
10161 if (strcmp (rs->buf, "OK") != 0)
10162 warning (_("Unable to reset environment on remote."));
10163 }
10164
10165 gdb_environ *e = &current_inferior ()->environment;
10166
10167 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10168 for (const std::string &el : e->user_set_env ())
6b8edb51 10169 send_environment_packet ("set", "QEnvironmentHexEncoded",
0a2dde4a
SDJ
10170 el.c_str ());
10171
10172 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10173 for (const std::string &el : e->user_unset_env ())
6b8edb51 10174 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10175}
10176
bc3b087d
SDJ
10177/* Helper function to set the current working directory for the
10178 inferior in the remote target. */
10179
6b8edb51
PA
10180void
10181remote_target::extended_remote_set_inferior_cwd ()
bc3b087d
SDJ
10182{
10183 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10184 {
10185 const char *inferior_cwd = get_inferior_cwd ();
6b8edb51 10186 remote_state *rs = get_remote_state ();
bc3b087d
SDJ
10187
10188 if (inferior_cwd != NULL)
10189 {
10190 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10191 strlen (inferior_cwd));
10192
10193 xsnprintf (rs->buf, get_remote_packet_size (),
10194 "QSetWorkingDir:%s", hexpath.c_str ());
10195 }
10196 else
10197 {
10198 /* An empty inferior_cwd means that the user wants us to
10199 reset the remote server's inferior's cwd. */
10200 xsnprintf (rs->buf, get_remote_packet_size (),
10201 "QSetWorkingDir:");
10202 }
10203
10204 putpkt (rs->buf);
10205 getpkt (&rs->buf, &rs->buf_size, 0);
10206 if (packet_ok (rs->buf,
10207 &remote_protocol_packets[PACKET_QSetWorkingDir])
10208 != PACKET_OK)
10209 error (_("\
10210Remote replied unexpectedly while setting the inferior's working\n\
10211directory: %s"),
10212 rs->buf);
10213
10214 }
10215}
10216
2d717e4f
DJ
10217/* In the extended protocol we want to be able to do things like
10218 "run" and have them basically work as expected. So we need
10219 a special create_inferior function. We support changing the
10220 executable file and the command line arguments, but not the
10221 environment. */
10222
f6ac5f3d
PA
10223void
10224extended_remote_target::create_inferior (const char *exec_file,
10225 const std::string &args,
10226 char **env, int from_tty)
43ff13b4 10227{
3405876a
PA
10228 int run_worked;
10229 char *stop_reply;
10230 struct remote_state *rs = get_remote_state ();
94585166 10231 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10232
43ff13b4 10233 /* If running asynchronously, register the target file descriptor
23860348 10234 with the event loop. */
75c99385 10235 if (target_can_async_p ())
6a3753b3 10236 target_async (1);
43ff13b4 10237
03583c20 10238 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10239 if (supports_disable_randomization ())
03583c20
UW
10240 extended_remote_disable_randomization (disable_randomization);
10241
aefd8b33
SDJ
10242 /* If startup-with-shell is on, we inform gdbserver to start the
10243 remote inferior using a shell. */
10244 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10245 {
10246 xsnprintf (rs->buf, get_remote_packet_size (),
10247 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10248 putpkt (rs->buf);
10249 getpkt (&rs->buf, &rs->buf_size, 0);
10250 if (strcmp (rs->buf, "OK") != 0)
10251 error (_("\
10252Remote replied unexpectedly while setting startup-with-shell: %s"),
10253 rs->buf);
10254 }
10255
6b8edb51 10256 extended_remote_environment_support ();
0a2dde4a 10257
6b8edb51 10258 extended_remote_set_inferior_cwd ();
bc3b087d 10259
43ff13b4 10260 /* Now restart the remote server. */
3405876a
PA
10261 run_worked = extended_remote_run (args) != -1;
10262 if (!run_worked)
2d717e4f
DJ
10263 {
10264 /* vRun was not supported. Fail if we need it to do what the
10265 user requested. */
10266 if (remote_exec_file[0])
10267 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10268 if (!args.empty ())
2d717e4f 10269 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 10270
2d717e4f
DJ
10271 /* Fall back to "R". */
10272 extended_remote_restart ();
10273 }
424163ea 10274
6c95b8df
PA
10275 if (!have_inferiors ())
10276 {
10277 /* Clean up from the last time we ran, before we mark the target
10278 running again. This will mark breakpoints uninserted, and
10279 get_offsets may insert breakpoints. */
10280 init_thread_list ();
10281 init_wait_for_inferior ();
10282 }
45280a52 10283
3405876a
PA
10284 /* vRun's success return is a stop reply. */
10285 stop_reply = run_worked ? rs->buf : NULL;
10286 add_current_inferior_and_thread (stop_reply);
c0a2216e 10287
2d717e4f
DJ
10288 /* Get updated offsets, if the stub uses qOffsets. */
10289 get_offsets ();
2d717e4f 10290}
c906108c 10291\f
c5aa993b 10292
b775012e
LM
10293/* Given a location's target info BP_TGT and the packet buffer BUF, output
10294 the list of conditions (in agent expression bytecode format), if any, the
10295 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10296 started from BUF and ended at BUF_END. */
b775012e
LM
10297
10298static int
10299remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10300 struct bp_target_info *bp_tgt, char *buf,
10301 char *buf_end)
b775012e 10302{
3cde5c42 10303 if (bp_tgt->conditions.empty ())
b775012e
LM
10304 return 0;
10305
10306 buf += strlen (buf);
bba74b36 10307 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10308 buf++;
10309
83621223 10310 /* Send conditions to the target. */
d538e36d 10311 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10312 {
bba74b36 10313 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 10314 buf += strlen (buf);
3cde5c42 10315 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
10316 buf = pack_hex_byte (buf, aexpr->buf[i]);
10317 *buf = '\0';
10318 }
b775012e
LM
10319 return 0;
10320}
10321
d3ce09f5
SS
10322static void
10323remote_add_target_side_commands (struct gdbarch *gdbarch,
10324 struct bp_target_info *bp_tgt, char *buf)
10325{
3cde5c42 10326 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10327 return;
10328
10329 buf += strlen (buf);
10330
10331 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10332 buf += strlen (buf);
10333
10334 /* Concatenate all the agent expressions that are commands into the
10335 cmds parameter. */
df97be55 10336 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
10337 {
10338 sprintf (buf, "X%x,", aexpr->len);
10339 buf += strlen (buf);
3cde5c42 10340 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
10341 buf = pack_hex_byte (buf, aexpr->buf[i]);
10342 *buf = '\0';
10343 }
d3ce09f5
SS
10344}
10345
8181d85f
DJ
10346/* Insert a breakpoint. On targets that have software breakpoint
10347 support, we ask the remote target to do the work; on targets
10348 which don't, we insert a traditional memory breakpoint. */
c906108c 10349
f6ac5f3d
PA
10350int
10351remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10352 struct bp_target_info *bp_tgt)
c906108c 10353{
d471ea57
AC
10354 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10355 If it succeeds, then set the support to PACKET_ENABLE. If it
10356 fails, and the user has explicitly requested the Z support then
23860348 10357 report an error, otherwise, mark it disabled and go on. */
802188a7 10358
4082afcc 10359 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10360 {
0d5ed153 10361 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10362 struct remote_state *rs;
bba74b36 10363 char *p, *endbuf;
4fff2411 10364
28439a30
PA
10365 /* Make sure the remote is pointing at the right process, if
10366 necessary. */
10367 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10368 set_general_process ();
10369
4fff2411
JZ
10370 rs = get_remote_state ();
10371 p = rs->buf;
bba74b36 10372 endbuf = rs->buf + get_remote_packet_size ();
802188a7 10373
96baa820
JM
10374 *(p++) = 'Z';
10375 *(p++) = '0';
10376 *(p++) = ',';
7c0f6dcc 10377 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10378 p += hexnumstr (p, addr);
579c6ad9 10379 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10380
f6ac5f3d 10381 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10382 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10383
f6ac5f3d 10384 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10385 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10386
6d820c5c
DJ
10387 putpkt (rs->buf);
10388 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10389
6d820c5c 10390 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 10391 {
d471ea57
AC
10392 case PACKET_ERROR:
10393 return -1;
10394 case PACKET_OK:
10395 return 0;
10396 case PACKET_UNKNOWN:
10397 break;
96baa820
JM
10398 }
10399 }
c906108c 10400
0000e5cc
PA
10401 /* If this breakpoint has target-side commands but this stub doesn't
10402 support Z0 packets, throw error. */
3cde5c42 10403 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10404 throw_error (NOT_SUPPORTED_ERROR, _("\
10405Target doesn't support breakpoints that have target side commands."));
10406
f6ac5f3d 10407 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10408}
10409
f6ac5f3d
PA
10410int
10411remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10412 struct bp_target_info *bp_tgt,
10413 enum remove_bp_reason reason)
c906108c 10414{
8181d85f 10415 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10416 struct remote_state *rs = get_remote_state ();
96baa820 10417
4082afcc 10418 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10419 {
6d820c5c 10420 char *p = rs->buf;
bba74b36 10421 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 10422
28439a30
PA
10423 /* Make sure the remote is pointing at the right process, if
10424 necessary. */
10425 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10426 set_general_process ();
10427
96baa820
JM
10428 *(p++) = 'z';
10429 *(p++) = '0';
10430 *(p++) = ',';
10431
8181d85f
DJ
10432 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10433 p += hexnumstr (p, addr);
579c6ad9 10434 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10435
6d820c5c
DJ
10436 putpkt (rs->buf);
10437 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10438
6d820c5c 10439 return (rs->buf[0] == 'E');
96baa820
JM
10440 }
10441
f6ac5f3d 10442 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10443}
10444
f486487f 10445static enum Z_packet_type
d471ea57
AC
10446watchpoint_to_Z_packet (int type)
10447{
10448 switch (type)
10449 {
10450 case hw_write:
bb858e6a 10451 return Z_PACKET_WRITE_WP;
d471ea57
AC
10452 break;
10453 case hw_read:
bb858e6a 10454 return Z_PACKET_READ_WP;
d471ea57
AC
10455 break;
10456 case hw_access:
bb858e6a 10457 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10458 break;
10459 default:
8e65ff28 10460 internal_error (__FILE__, __LINE__,
e2e0b3e5 10461 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10462 }
10463}
10464
f6ac5f3d
PA
10465int
10466remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10467 enum target_hw_bp_type type, struct expression *cond)
96baa820 10468{
d01949b6 10469 struct remote_state *rs = get_remote_state ();
bba74b36 10470 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10471 char *p;
d471ea57 10472 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10473
4082afcc 10474 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10475 return 1;
802188a7 10476
28439a30
PA
10477 /* Make sure the remote is pointing at the right process, if
10478 necessary. */
10479 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10480 set_general_process ();
10481
bba74b36 10482 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 10483 p = strchr (rs->buf, '\0');
96baa820
JM
10484 addr = remote_address_masked (addr);
10485 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10486 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10487
6d820c5c
DJ
10488 putpkt (rs->buf);
10489 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10490
6d820c5c 10491 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10492 {
10493 case PACKET_ERROR:
d471ea57 10494 return -1;
85d721b8
PA
10495 case PACKET_UNKNOWN:
10496 return 1;
d471ea57
AC
10497 case PACKET_OK:
10498 return 0;
10499 }
8e65ff28 10500 internal_error (__FILE__, __LINE__,
e2e0b3e5 10501 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10502}
10503
57810aa7 10504bool
f6ac5f3d
PA
10505remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10506 CORE_ADDR start, int length)
283002cf
MR
10507{
10508 CORE_ADDR diff = remote_address_masked (addr - start);
10509
10510 return diff < length;
10511}
10512
d471ea57 10513
f6ac5f3d
PA
10514int
10515remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10516 enum target_hw_bp_type type, struct expression *cond)
96baa820 10517{
d01949b6 10518 struct remote_state *rs = get_remote_state ();
bba74b36 10519 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10520 char *p;
d471ea57
AC
10521 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10522
4082afcc 10523 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10524 return -1;
802188a7 10525
28439a30
PA
10526 /* Make sure the remote is pointing at the right process, if
10527 necessary. */
10528 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10529 set_general_process ();
10530
bba74b36 10531 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 10532 p = strchr (rs->buf, '\0');
96baa820
JM
10533 addr = remote_address_masked (addr);
10534 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10535 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
10536 putpkt (rs->buf);
10537 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10538
6d820c5c 10539 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10540 {
10541 case PACKET_ERROR:
10542 case PACKET_UNKNOWN:
10543 return -1;
10544 case PACKET_OK:
10545 return 0;
10546 }
8e65ff28 10547 internal_error (__FILE__, __LINE__,
e2e0b3e5 10548 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10549}
10550
3c3bea1c 10551
501eef12 10552int remote_hw_watchpoint_limit = -1;
480a3f21 10553int remote_hw_watchpoint_length_limit = -1;
501eef12 10554int remote_hw_breakpoint_limit = -1;
d471ea57 10555
f6ac5f3d
PA
10556int
10557remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10558{
10559 if (remote_hw_watchpoint_length_limit == 0)
10560 return 0;
10561 else if (remote_hw_watchpoint_length_limit < 0)
10562 return 1;
10563 else if (len <= remote_hw_watchpoint_length_limit)
10564 return 1;
10565 else
10566 return 0;
10567}
10568
f6ac5f3d
PA
10569int
10570remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10571{
3c3bea1c
GS
10572 if (type == bp_hardware_breakpoint)
10573 {
10574 if (remote_hw_breakpoint_limit == 0)
10575 return 0;
501eef12
AC
10576 else if (remote_hw_breakpoint_limit < 0)
10577 return 1;
3c3bea1c
GS
10578 else if (cnt <= remote_hw_breakpoint_limit)
10579 return 1;
10580 }
10581 else
10582 {
10583 if (remote_hw_watchpoint_limit == 0)
10584 return 0;
501eef12
AC
10585 else if (remote_hw_watchpoint_limit < 0)
10586 return 1;
3c3bea1c
GS
10587 else if (ot)
10588 return -1;
10589 else if (cnt <= remote_hw_watchpoint_limit)
10590 return 1;
10591 }
10592 return -1;
10593}
10594
f7e6eed5
PA
10595/* The to_stopped_by_sw_breakpoint method of target remote. */
10596
57810aa7 10597bool
f6ac5f3d 10598remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10599{
799a2abe 10600 struct thread_info *thread = inferior_thread ();
f7e6eed5 10601
799a2abe 10602 return (thread->priv != NULL
7aabaf9d
SM
10603 && (get_remote_thread_info (thread)->stop_reason
10604 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10605}
10606
10607/* The to_supports_stopped_by_sw_breakpoint method of target
10608 remote. */
10609
57810aa7 10610bool
f6ac5f3d 10611remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10612{
f7e6eed5
PA
10613 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10614}
10615
10616/* The to_stopped_by_hw_breakpoint method of target remote. */
10617
57810aa7 10618bool
f6ac5f3d 10619remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10620{
799a2abe 10621 struct thread_info *thread = inferior_thread ();
f7e6eed5 10622
799a2abe 10623 return (thread->priv != NULL
7aabaf9d
SM
10624 && (get_remote_thread_info (thread)->stop_reason
10625 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10626}
10627
10628/* The to_supports_stopped_by_hw_breakpoint method of target
10629 remote. */
10630
57810aa7 10631bool
f6ac5f3d 10632remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10633{
f7e6eed5
PA
10634 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10635}
10636
57810aa7 10637bool
f6ac5f3d 10638remote_target::stopped_by_watchpoint ()
3c3bea1c 10639{
799a2abe 10640 struct thread_info *thread = inferior_thread ();
ee154bee 10641
799a2abe 10642 return (thread->priv != NULL
7aabaf9d
SM
10643 && (get_remote_thread_info (thread)->stop_reason
10644 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10645}
10646
57810aa7 10647bool
f6ac5f3d 10648remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10649{
799a2abe 10650 struct thread_info *thread = inferior_thread ();
a744cf53 10651
799a2abe 10652 if (thread->priv != NULL
7aabaf9d
SM
10653 && (get_remote_thread_info (thread)->stop_reason
10654 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10655 {
7aabaf9d 10656 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 10657 return true;
4aa7a7f5
JJ
10658 }
10659
57810aa7 10660 return false;
3c3bea1c
GS
10661}
10662
10663
f6ac5f3d
PA
10664int
10665remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10666 struct bp_target_info *bp_tgt)
3c3bea1c 10667{
0d5ed153 10668 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10669 struct remote_state *rs;
bba74b36 10670 char *p, *endbuf;
dd61ec5c 10671 char *message;
3c3bea1c 10672
4082afcc 10673 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10674 return -1;
2bc416ba 10675
28439a30
PA
10676 /* Make sure the remote is pointing at the right process, if
10677 necessary. */
10678 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10679 set_general_process ();
10680
4fff2411
JZ
10681 rs = get_remote_state ();
10682 p = rs->buf;
bba74b36 10683 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 10684
96baa820
JM
10685 *(p++) = 'Z';
10686 *(p++) = '1';
10687 *(p++) = ',';
802188a7 10688
0d5ed153 10689 addr = remote_address_masked (addr);
96baa820 10690 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10691 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10692
f6ac5f3d 10693 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10694 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10695
f6ac5f3d 10696 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10697 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10698
6d820c5c
DJ
10699 putpkt (rs->buf);
10700 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10701
6d820c5c 10702 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10703 {
10704 case PACKET_ERROR:
dd61ec5c
MW
10705 if (rs->buf[1] == '.')
10706 {
10707 message = strchr (rs->buf + 2, '.');
10708 if (message)
0316657e 10709 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10710 }
10711 return -1;
d471ea57
AC
10712 case PACKET_UNKNOWN:
10713 return -1;
10714 case PACKET_OK:
10715 return 0;
10716 }
8e65ff28 10717 internal_error (__FILE__, __LINE__,
e2e0b3e5 10718 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10719}
10720
d471ea57 10721
f6ac5f3d
PA
10722int
10723remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10724 struct bp_target_info *bp_tgt)
96baa820 10725{
8181d85f 10726 CORE_ADDR addr;
d01949b6 10727 struct remote_state *rs = get_remote_state ();
6d820c5c 10728 char *p = rs->buf;
bba74b36 10729 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 10730
4082afcc 10731 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10732 return -1;
802188a7 10733
28439a30
PA
10734 /* Make sure the remote is pointing at the right process, if
10735 necessary. */
10736 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10737 set_general_process ();
10738
96baa820
JM
10739 *(p++) = 'z';
10740 *(p++) = '1';
10741 *(p++) = ',';
802188a7 10742
8181d85f 10743 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10744 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10745 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10746
6d820c5c
DJ
10747 putpkt (rs->buf);
10748 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 10749
6d820c5c 10750 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10751 {
10752 case PACKET_ERROR:
10753 case PACKET_UNKNOWN:
10754 return -1;
10755 case PACKET_OK:
10756 return 0;
10757 }
8e65ff28 10758 internal_error (__FILE__, __LINE__,
e2e0b3e5 10759 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10760}
96baa820 10761
4a5e7a5b
PA
10762/* Verify memory using the "qCRC:" request. */
10763
f6ac5f3d
PA
10764int
10765remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
10766{
10767 struct remote_state *rs = get_remote_state ();
10768 unsigned long host_crc, target_crc;
10769 char *tmp;
10770
936d2992
PA
10771 /* It doesn't make sense to use qCRC if the remote target is
10772 connected but not running. */
10773 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10774 {
10775 enum packet_result result;
28439a30 10776
936d2992
PA
10777 /* Make sure the remote is pointing at the right process. */
10778 set_general_process ();
4a5e7a5b 10779
936d2992
PA
10780 /* FIXME: assumes lma can fit into long. */
10781 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10782 (long) lma, (long) size);
10783 putpkt (rs->buf);
4a5e7a5b 10784
936d2992
PA
10785 /* Be clever; compute the host_crc before waiting for target
10786 reply. */
10787 host_crc = xcrc32 (data, size, 0xffffffff);
10788
10789 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 10790
936d2992
PA
10791 result = packet_ok (rs->buf,
10792 &remote_protocol_packets[PACKET_qCRC]);
10793 if (result == PACKET_ERROR)
10794 return -1;
10795 else if (result == PACKET_OK)
10796 {
10797 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10798 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10799
936d2992
PA
10800 return (host_crc == target_crc);
10801 }
10802 }
4a5e7a5b 10803
f6ac5f3d 10804 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
10805}
10806
c906108c
SS
10807/* compare-sections command
10808
10809 With no arguments, compares each loadable section in the exec bfd
10810 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10811 Useful for verifying the image on the target against the exec file. */
e514a9d6 10812
c906108c 10813static void
ac88e2de 10814compare_sections_command (const char *args, int from_tty)
c906108c
SS
10815{
10816 asection *s;
ce359b09 10817 const char *sectname;
c906108c
SS
10818 bfd_size_type size;
10819 bfd_vma lma;
10820 int matched = 0;
10821 int mismatched = 0;
4a5e7a5b 10822 int res;
95cf3b38 10823 int read_only = 0;
c906108c
SS
10824
10825 if (!exec_bfd)
8a3fe4f8 10826 error (_("command cannot be used without an exec file"));
c906108c 10827
95cf3b38
DT
10828 if (args != NULL && strcmp (args, "-r") == 0)
10829 {
10830 read_only = 1;
10831 args = NULL;
10832 }
10833
c5aa993b 10834 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10835 {
10836 if (!(s->flags & SEC_LOAD))
0df8b418 10837 continue; /* Skip non-loadable section. */
c906108c 10838
95cf3b38
DT
10839 if (read_only && (s->flags & SEC_READONLY) == 0)
10840 continue; /* Skip writeable sections */
10841
2c500098 10842 size = bfd_get_section_size (s);
c906108c 10843 if (size == 0)
0df8b418 10844 continue; /* Skip zero-length section. */
c906108c 10845
ce359b09 10846 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10847 if (args && strcmp (args, sectname) != 0)
0df8b418 10848 continue; /* Not the section selected by user. */
c906108c 10849
0df8b418 10850 matched = 1; /* Do this section. */
c906108c 10851 lma = s->lma;
c906108c 10852
b80406ac
TT
10853 gdb::byte_vector sectdata (size);
10854 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
c906108c 10855
b80406ac 10856 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
10857
10858 if (res == -1)
5af949e3 10859 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10860 paddress (target_gdbarch (), lma),
10861 paddress (target_gdbarch (), lma + size));
c906108c 10862
5af949e3 10863 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10864 paddress (target_gdbarch (), lma),
10865 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10866 if (res)
c906108c
SS
10867 printf_filtered ("matched.\n");
10868 else
c5aa993b
JM
10869 {
10870 printf_filtered ("MIS-MATCHED!\n");
10871 mismatched++;
10872 }
c906108c
SS
10873 }
10874 if (mismatched > 0)
936d2992 10875 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10876the loaded file\n"));
c906108c 10877 if (args && !matched)
a3f17187 10878 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10879}
10880
0e7f50da
UW
10881/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10882 into remote target. The number of bytes written to the remote
10883 target is returned, or -1 for error. */
10884
6b8edb51
PA
10885target_xfer_status
10886remote_target::remote_write_qxfer (const char *object_name,
10887 const char *annex, const gdb_byte *writebuf,
10888 ULONGEST offset, LONGEST len,
10889 ULONGEST *xfered_len,
10890 struct packet_config *packet)
0e7f50da
UW
10891{
10892 int i, buf_len;
10893 ULONGEST n;
0e7f50da
UW
10894 struct remote_state *rs = get_remote_state ();
10895 int max_size = get_memory_write_packet_size ();
10896
7cc244de 10897 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10898 return TARGET_XFER_E_IO;
0e7f50da
UW
10899
10900 /* Insert header. */
10901 i = snprintf (rs->buf, max_size,
10902 "qXfer:%s:write:%s:%s:",
10903 object_name, annex ? annex : "",
10904 phex_nz (offset, sizeof offset));
10905 max_size -= (i + 1);
10906
10907 /* Escape as much data as fits into rs->buf. */
10908 buf_len = remote_escape_output
124e13d9 10909 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
10910
10911 if (putpkt_binary (rs->buf, i + buf_len) < 0
10912 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10913 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10914 return TARGET_XFER_E_IO;
0e7f50da
UW
10915
10916 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
10917
10918 *xfered_len = n;
92ffd475 10919 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
10920}
10921
0876f84a
DJ
10922/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10923 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10924 number of bytes read is returned, or 0 for EOF, or -1 for error.
10925 The number of bytes read may be less than LEN without indicating an
10926 EOF. PACKET is checked and updated to indicate whether the remote
10927 target supports this object. */
10928
6b8edb51
PA
10929target_xfer_status
10930remote_target::remote_read_qxfer (const char *object_name,
10931 const char *annex,
10932 gdb_byte *readbuf, ULONGEST offset,
10933 LONGEST len,
10934 ULONGEST *xfered_len,
10935 struct packet_config *packet)
0876f84a 10936{
0876f84a 10937 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10938 LONGEST i, n, packet_len;
10939
7cc244de 10940 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10941 return TARGET_XFER_E_IO;
0876f84a
DJ
10942
10943 /* Check whether we've cached an end-of-object packet that matches
10944 this request. */
8e88304f 10945 if (rs->finished_object)
0876f84a 10946 {
8e88304f
TT
10947 if (strcmp (object_name, rs->finished_object) == 0
10948 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10949 && offset == rs->finished_offset)
9b409511
YQ
10950 return TARGET_XFER_EOF;
10951
0876f84a
DJ
10952
10953 /* Otherwise, we're now reading something different. Discard
10954 the cache. */
8e88304f
TT
10955 xfree (rs->finished_object);
10956 xfree (rs->finished_annex);
10957 rs->finished_object = NULL;
10958 rs->finished_annex = NULL;
0876f84a
DJ
10959 }
10960
10961 /* Request only enough to fit in a single packet. The actual data
10962 may not, since we don't know how much of it will need to be escaped;
10963 the target is free to respond with slightly less data. We subtract
10964 five to account for the response type and the protocol frame. */
768adc05 10965 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
0876f84a
DJ
10966 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10967 object_name, annex ? annex : "",
10968 phex_nz (offset, sizeof offset),
10969 phex_nz (n, sizeof n));
10970 i = putpkt (rs->buf);
10971 if (i < 0)
2ed4b548 10972 return TARGET_XFER_E_IO;
0876f84a
DJ
10973
10974 rs->buf[0] = '\0';
10975 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10976 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10977 return TARGET_XFER_E_IO;
0876f84a
DJ
10978
10979 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10980 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10981
10982 /* 'm' means there is (or at least might be) more data after this
10983 batch. That does not make sense unless there's at least one byte
10984 of data in this reply. */
10985 if (rs->buf[0] == 'm' && packet_len == 1)
10986 error (_("Remote qXfer reply contained no data."));
10987
10988 /* Got some data. */
bc20a4af
PA
10989 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10990 packet_len - 1, readbuf, n);
0876f84a
DJ
10991
10992 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10993 or possibly empty. If we have the final block of a non-empty
10994 object, record this fact to bypass a subsequent partial read. */
10995 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10996 {
8e88304f
TT
10997 rs->finished_object = xstrdup (object_name);
10998 rs->finished_annex = xstrdup (annex ? annex : "");
10999 rs->finished_offset = offset + i;
0876f84a
DJ
11000 }
11001
9b409511
YQ
11002 if (i == 0)
11003 return TARGET_XFER_EOF;
11004 else
11005 {
11006 *xfered_len = i;
11007 return TARGET_XFER_OK;
11008 }
0876f84a
DJ
11009}
11010
f6ac5f3d
PA
11011enum target_xfer_status
11012remote_target::xfer_partial (enum target_object object,
11013 const char *annex, gdb_byte *readbuf,
11014 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11015 ULONGEST *xfered_len)
c906108c 11016{
82f73884 11017 struct remote_state *rs;
c906108c 11018 int i;
6d820c5c 11019 char *p2;
1e3ff5ad 11020 char query_type;
124e13d9 11021 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 11022
e6e4e701 11023 set_remote_traceframe ();
82f73884
PA
11024 set_general_thread (inferior_ptid);
11025
11026 rs = get_remote_state ();
11027
b2182ed2 11028 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
11029 if (object == TARGET_OBJECT_MEMORY)
11030 {
2d717e4f
DJ
11031 /* If the remote target is connected but not running, we should
11032 pass this request down to a lower stratum (e.g. the executable
11033 file). */
11034 if (!target_has_execution)
9b409511 11035 return TARGET_XFER_EOF;
2d717e4f 11036
21e3b9b9 11037 if (writebuf != NULL)
124e13d9
SM
11038 return remote_write_bytes (offset, writebuf, len, unit_size,
11039 xfered_len);
21e3b9b9 11040 else
6b8edb51 11041 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 11042 xfered_len);
21e3b9b9
DJ
11043 }
11044
0df8b418 11045 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
11046 if (object == TARGET_OBJECT_SPU)
11047 {
11048 if (readbuf)
f6ac5f3d 11049 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
9b409511
YQ
11050 xfered_len, &remote_protocol_packets
11051 [PACKET_qXfer_spu_read]);
0e7f50da 11052 else
f6ac5f3d 11053 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
9b409511
YQ
11054 xfered_len, &remote_protocol_packets
11055 [PACKET_qXfer_spu_write]);
0e7f50da
UW
11056 }
11057
4aa995e1
PA
11058 /* Handle extra signal info using qxfer packets. */
11059 if (object == TARGET_OBJECT_SIGNAL_INFO)
11060 {
11061 if (readbuf)
f6ac5f3d 11062 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
9b409511 11063 xfered_len, &remote_protocol_packets
4aa995e1
PA
11064 [PACKET_qXfer_siginfo_read]);
11065 else
f6ac5f3d 11066 return remote_write_qxfer ("siginfo", annex,
9b409511 11067 writebuf, offset, len, xfered_len,
4aa995e1
PA
11068 &remote_protocol_packets
11069 [PACKET_qXfer_siginfo_write]);
11070 }
11071
0fb4aa4b
PA
11072 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11073 {
11074 if (readbuf)
f6ac5f3d 11075 return remote_read_qxfer ("statictrace", annex,
9b409511 11076 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
11077 &remote_protocol_packets
11078 [PACKET_qXfer_statictrace_read]);
11079 else
2ed4b548 11080 return TARGET_XFER_E_IO;
0fb4aa4b
PA
11081 }
11082
a76d924d
DJ
11083 /* Only handle flash writes. */
11084 if (writebuf != NULL)
11085 {
a76d924d
DJ
11086 switch (object)
11087 {
11088 case TARGET_OBJECT_FLASH:
6b8edb51 11089 return remote_flash_write (offset, len, xfered_len,
9b409511 11090 writebuf);
a76d924d
DJ
11091
11092 default:
2ed4b548 11093 return TARGET_XFER_E_IO;
a76d924d
DJ
11094 }
11095 }
4b8a223f 11096
1e3ff5ad
AC
11097 /* Map pre-existing objects onto letters. DO NOT do this for new
11098 objects!!! Instead specify new query packets. */
11099 switch (object)
c906108c 11100 {
1e3ff5ad
AC
11101 case TARGET_OBJECT_AVR:
11102 query_type = 'R';
11103 break;
802188a7
RM
11104
11105 case TARGET_OBJECT_AUXV:
0876f84a 11106 gdb_assert (annex == NULL);
f6ac5f3d 11107 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
9b409511 11108 xfered_len,
0876f84a 11109 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 11110
23181151
DJ
11111 case TARGET_OBJECT_AVAILABLE_FEATURES:
11112 return remote_read_qxfer
f6ac5f3d 11113 ("features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
11114 &remote_protocol_packets[PACKET_qXfer_features]);
11115
cfa9d6d9
DJ
11116 case TARGET_OBJECT_LIBRARIES:
11117 return remote_read_qxfer
f6ac5f3d 11118 ("libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
11119 &remote_protocol_packets[PACKET_qXfer_libraries]);
11120
2268b414
JK
11121 case TARGET_OBJECT_LIBRARIES_SVR4:
11122 return remote_read_qxfer
f6ac5f3d 11123 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
11124 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11125
fd79ecee
DJ
11126 case TARGET_OBJECT_MEMORY_MAP:
11127 gdb_assert (annex == NULL);
f6ac5f3d 11128 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
9b409511 11129 xfered_len,
fd79ecee
DJ
11130 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11131
07e059b5
VP
11132 case TARGET_OBJECT_OSDATA:
11133 /* Should only get here if we're connected. */
5d93a237 11134 gdb_assert (rs->remote_desc);
07e059b5 11135 return remote_read_qxfer
f6ac5f3d 11136 ("osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
11137 &remote_protocol_packets[PACKET_qXfer_osdata]);
11138
dc146f7c
VP
11139 case TARGET_OBJECT_THREADS:
11140 gdb_assert (annex == NULL);
f6ac5f3d 11141 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
9b409511 11142 xfered_len,
dc146f7c
VP
11143 &remote_protocol_packets[PACKET_qXfer_threads]);
11144
b3b9301e
PA
11145 case TARGET_OBJECT_TRACEFRAME_INFO:
11146 gdb_assert (annex == NULL);
11147 return remote_read_qxfer
f6ac5f3d 11148 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 11149 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
11150
11151 case TARGET_OBJECT_FDPIC:
f6ac5f3d 11152 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
9b409511 11153 xfered_len,
78d85199 11154 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
11155
11156 case TARGET_OBJECT_OPENVMS_UIB:
f6ac5f3d 11157 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
9b409511 11158 xfered_len,
169081d0
TG
11159 &remote_protocol_packets[PACKET_qXfer_uib]);
11160
9accd112 11161 case TARGET_OBJECT_BTRACE:
f6ac5f3d 11162 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
9b409511 11163 xfered_len,
9accd112
MM
11164 &remote_protocol_packets[PACKET_qXfer_btrace]);
11165
f4abbc16 11166 case TARGET_OBJECT_BTRACE_CONF:
f6ac5f3d 11167 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
f4abbc16
MM
11168 len, xfered_len,
11169 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11170
c78fa86a 11171 case TARGET_OBJECT_EXEC_FILE:
f6ac5f3d 11172 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
c78fa86a
GB
11173 len, xfered_len,
11174 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11175
1e3ff5ad 11176 default:
2ed4b548 11177 return TARGET_XFER_E_IO;
c906108c
SS
11178 }
11179
0df8b418 11180 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11181 large enough let the caller deal with it. */
ea9c271d 11182 if (len < get_remote_packet_size ())
2ed4b548 11183 return TARGET_XFER_E_IO;
ea9c271d 11184 len = get_remote_packet_size ();
1e3ff5ad 11185
23860348 11186 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11187 if (!rs->remote_desc)
8a3fe4f8 11188 error (_("remote query is only available after target open"));
c906108c 11189
1e3ff5ad 11190 gdb_assert (annex != NULL);
4b8a223f 11191 gdb_assert (readbuf != NULL);
c906108c 11192
6d820c5c 11193 p2 = rs->buf;
c906108c
SS
11194 *p2++ = 'q';
11195 *p2++ = query_type;
11196
23860348
MS
11197 /* We used one buffer char for the remote protocol q command and
11198 another for the query type. As the remote protocol encapsulation
11199 uses 4 chars plus one extra in case we are debugging
11200 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11201 string. */
c906108c 11202 i = 0;
ea9c271d 11203 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11204 {
1e3ff5ad
AC
11205 /* Bad caller may have sent forbidden characters. */
11206 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11207 *p2++ = annex[i];
c906108c
SS
11208 i++;
11209 }
1e3ff5ad
AC
11210 *p2 = '\0';
11211 gdb_assert (annex[i] == '\0');
c906108c 11212
6d820c5c 11213 i = putpkt (rs->buf);
c5aa993b 11214 if (i < 0)
2ed4b548 11215 return TARGET_XFER_E_IO;
c906108c 11216
6d820c5c
DJ
11217 getpkt (&rs->buf, &rs->buf_size, 0);
11218 strcpy ((char *) readbuf, rs->buf);
c906108c 11219
9b409511 11220 *xfered_len = strlen ((char *) readbuf);
92ffd475 11221 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11222}
11223
09c98b44
DB
11224/* Implementation of to_get_memory_xfer_limit. */
11225
f6ac5f3d
PA
11226ULONGEST
11227remote_target::get_memory_xfer_limit ()
09c98b44
DB
11228{
11229 return get_memory_write_packet_size ();
11230}
11231
f6ac5f3d
PA
11232int
11233remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11234 const gdb_byte *pattern, ULONGEST pattern_len,
11235 CORE_ADDR *found_addrp)
08388c79 11236{
f5656ead 11237 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
11238 struct remote_state *rs = get_remote_state ();
11239 int max_size = get_memory_write_packet_size ();
11240 struct packet_config *packet =
11241 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
11242 /* Number of packet bytes used to encode the pattern;
11243 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11244 int escaped_pattern_len;
0df8b418 11245 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11246 int used_pattern_len;
11247 int i;
11248 int found;
11249 ULONGEST found_addr;
11250
7cc244de
PA
11251 /* Don't go to the target if we don't have to. This is done before
11252 checking packet_config_support to avoid the possibility that a
11253 success for this edge case means the facility works in
11254 general. */
08388c79
DE
11255 if (pattern_len > search_space_len)
11256 return 0;
11257 if (pattern_len == 0)
11258 {
11259 *found_addrp = start_addr;
11260 return 1;
11261 }
11262
11263 /* If we already know the packet isn't supported, fall back to the simple
11264 way of searching memory. */
11265
4082afcc 11266 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
11267 {
11268 /* Target doesn't provided special support, fall back and use the
11269 standard support (copy memory and do the search here). */
f6ac5f3d 11270 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11271 pattern, pattern_len, found_addrp);
11272 }
11273
28439a30
PA
11274 /* Make sure the remote is pointing at the right process. */
11275 set_general_process ();
11276
08388c79
DE
11277 /* Insert header. */
11278 i = snprintf (rs->buf, max_size,
11279 "qSearch:memory:%s;%s;",
5af949e3 11280 phex_nz (start_addr, addr_size),
08388c79
DE
11281 phex_nz (search_space_len, sizeof (search_space_len)));
11282 max_size -= (i + 1);
11283
11284 /* Escape as much data as fits into rs->buf. */
11285 escaped_pattern_len =
124e13d9 11286 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
11287 &used_pattern_len, max_size);
11288
11289 /* Bail if the pattern is too large. */
11290 if (used_pattern_len != pattern_len)
9b20d036 11291 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
11292
11293 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11294 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11295 || packet_ok (rs->buf, packet) != PACKET_OK)
11296 {
11297 /* The request may not have worked because the command is not
11298 supported. If so, fall back to the simple way. */
7cc244de 11299 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79 11300 {
f6ac5f3d 11301 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11302 pattern, pattern_len, found_addrp);
11303 }
11304 return -1;
11305 }
11306
11307 if (rs->buf[0] == '0')
11308 found = 0;
11309 else if (rs->buf[0] == '1')
11310 {
11311 found = 1;
11312 if (rs->buf[1] != ',')
10e0fa18 11313 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
11314 unpack_varlen_hex (rs->buf + 2, &found_addr);
11315 *found_addrp = found_addr;
11316 }
11317 else
10e0fa18 11318 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
11319
11320 return found;
11321}
11322
f6ac5f3d
PA
11323void
11324remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11325{
d01949b6 11326 struct remote_state *rs = get_remote_state ();
2e9f7625 11327 char *p = rs->buf;
96baa820 11328
5d93a237 11329 if (!rs->remote_desc)
8a3fe4f8 11330 error (_("remote rcmd is only available after target open"));
96baa820 11331
23860348 11332 /* Send a NULL command across as an empty command. */
7be570e7
JM
11333 if (command == NULL)
11334 command = "";
11335
23860348 11336 /* The query prefix. */
2e9f7625
DJ
11337 strcpy (rs->buf, "qRcmd,");
11338 p = strchr (rs->buf, '\0');
96baa820 11339
3e43a32a
MS
11340 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11341 > get_remote_packet_size ())
8a3fe4f8 11342 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11343
23860348 11344 /* Encode the actual command. */
a30bf1f1 11345 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11346
6d820c5c 11347 if (putpkt (rs->buf) < 0)
8a3fe4f8 11348 error (_("Communication problem with target."));
96baa820
JM
11349
11350 /* get/display the response */
11351 while (1)
11352 {
2e9f7625
DJ
11353 char *buf;
11354
00bf0b85 11355 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11356 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11357 rs->buf[0] = '\0';
5b37825d
PW
11358 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11359 {
11360 /* Timeout. Continue to (try to) read responses.
11361 This is better than stopping with an error, assuming the stub
11362 is still executing the (long) monitor command.
11363 If needed, the user can interrupt gdb using C-c, obtaining
11364 an effect similar to stop on timeout. */
11365 continue;
11366 }
2e9f7625 11367 buf = rs->buf;
96baa820 11368 if (buf[0] == '\0')
8a3fe4f8 11369 error (_("Target does not support this command."));
96baa820
JM
11370 if (buf[0] == 'O' && buf[1] != 'K')
11371 {
23860348 11372 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11373 continue;
11374 }
11375 if (strcmp (buf, "OK") == 0)
11376 break;
7be570e7
JM
11377 if (strlen (buf) == 3 && buf[0] == 'E'
11378 && isdigit (buf[1]) && isdigit (buf[2]))
11379 {
8a3fe4f8 11380 error (_("Protocol error with Rcmd"));
7be570e7 11381 }
96baa820
JM
11382 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11383 {
11384 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11385
96baa820
JM
11386 fputc_unfiltered (c, outbuf);
11387 }
11388 break;
11389 }
11390}
11391
f6ac5f3d
PA
11392std::vector<mem_region>
11393remote_target::memory_map ()
fd79ecee 11394{
a664f67e 11395 std::vector<mem_region> result;
9018be22 11396 gdb::optional<gdb::char_vector> text
f6ac5f3d 11397 = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11398
11399 if (text)
9018be22 11400 result = parse_memory_map (text->data ());
fd79ecee
DJ
11401
11402 return result;
11403}
11404
c906108c 11405static void
ac88e2de 11406packet_command (const char *args, int from_tty)
c906108c 11407{
6b8edb51 11408 remote_target *remote = get_current_remote_target ();
c906108c 11409
6b8edb51 11410 if (remote == nullptr)
8a3fe4f8 11411 error (_("command can only be used with remote target"));
c906108c 11412
6b8edb51
PA
11413 remote->packet_command (args, from_tty);
11414}
11415
11416void
11417remote_target::packet_command (const char *args, int from_tty)
11418{
c5aa993b 11419 if (!args)
8a3fe4f8 11420 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
11421
11422 puts_filtered ("sending: ");
11423 print_packet (args);
11424 puts_filtered ("\n");
11425 putpkt (args);
11426
6b8edb51
PA
11427 remote_state *rs = get_remote_state ();
11428
6d820c5c 11429 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 11430 puts_filtered ("received: ");
6d820c5c 11431 print_packet (rs->buf);
c906108c
SS
11432 puts_filtered ("\n");
11433}
11434
11435#if 0
23860348 11436/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11437
a14ed312 11438static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11439
a14ed312 11440static void threadset_test_cmd (char *cmd, int tty);
c906108c 11441
a14ed312 11442static void threadalive_test (char *cmd, int tty);
c906108c 11443
a14ed312 11444static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11445
23860348 11446int get_and_display_threadinfo (threadref *ref);
c906108c 11447
a14ed312 11448static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11449
23860348 11450static int thread_display_step (threadref *ref, void *context);
c906108c 11451
a14ed312 11452static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11453
a14ed312 11454static void init_remote_threadtests (void);
c906108c 11455
23860348 11456#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11457
11458static void
0b39b52e 11459threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11460{
11461 int sample_thread = SAMPLE_THREAD;
11462
a3f17187 11463 printf_filtered (_("Remote threadset test\n"));
79d7f229 11464 set_general_thread (sample_thread);
c906108c
SS
11465}
11466
11467
11468static void
0b39b52e 11469threadalive_test (const char *cmd, int tty)
c906108c
SS
11470{
11471 int sample_thread = SAMPLE_THREAD;
79d7f229 11472 int pid = ptid_get_pid (inferior_ptid);
ba348170 11473 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 11474
79d7f229 11475 if (remote_thread_alive (ptid))
c906108c
SS
11476 printf_filtered ("PASS: Thread alive test\n");
11477 else
11478 printf_filtered ("FAIL: Thread alive test\n");
11479}
11480
23860348 11481void output_threadid (char *title, threadref *ref);
c906108c
SS
11482
11483void
fba45db2 11484output_threadid (char *title, threadref *ref)
c906108c
SS
11485{
11486 char hexid[20];
11487
23860348 11488 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
11489 hexid[16] = 0;
11490 printf_filtered ("%s %s\n", title, (&hexid[0]));
11491}
11492
11493static void
0b39b52e 11494threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11495{
11496 int startflag = 1;
11497 threadref nextthread;
11498 int done, result_count;
11499 threadref threadlist[3];
11500
11501 printf_filtered ("Remote Threadlist test\n");
11502 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11503 &result_count, &threadlist[0]))
11504 printf_filtered ("FAIL: threadlist test\n");
11505 else
11506 {
11507 threadref *scan = threadlist;
11508 threadref *limit = scan + result_count;
11509
11510 while (scan < limit)
11511 output_threadid (" thread ", scan++);
11512 }
11513}
11514
11515void
fba45db2 11516display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11517{
11518 output_threadid ("Threadid: ", &info->threadid);
11519 printf_filtered ("Name: %s\n ", info->shortname);
11520 printf_filtered ("State: %s\n", info->display);
11521 printf_filtered ("other: %s\n\n", info->more_display);
11522}
11523
11524int
fba45db2 11525get_and_display_threadinfo (threadref *ref)
c906108c
SS
11526{
11527 int result;
11528 int set;
11529 struct gdb_ext_thread_info threadinfo;
11530
11531 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11532 | TAG_MOREDISPLAY | TAG_DISPLAY;
11533 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11534 display_thread_info (&threadinfo);
11535 return result;
11536}
11537
11538static void
0b39b52e 11539threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11540{
11541 int athread = SAMPLE_THREAD;
11542 threadref thread;
11543 int set;
11544
11545 int_to_threadref (&thread, athread);
11546 printf_filtered ("Remote Threadinfo test\n");
11547 if (!get_and_display_threadinfo (&thread))
11548 printf_filtered ("FAIL cannot get thread info\n");
11549}
11550
11551static int
fba45db2 11552thread_display_step (threadref *ref, void *context)
c906108c
SS
11553{
11554 /* output_threadid(" threadstep ",ref); *//* simple test */
11555 return get_and_display_threadinfo (ref);
11556}
11557
11558static void
0b39b52e 11559threadlist_update_test_cmd (const char *cmd, int tty)
c906108c
SS
11560{
11561 printf_filtered ("Remote Threadlist update test\n");
11562 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11563}
11564
11565static void
11566init_remote_threadtests (void)
11567{
3e43a32a
MS
11568 add_com ("tlist", class_obscure, threadlist_test_cmd,
11569 _("Fetch and print the remote list of "
11570 "thread identifiers, one pkt only"));
c906108c 11571 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 11572 _("Fetch and display info about one thread"));
c906108c 11573 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 11574 _("Test setting to a different thread"));
c906108c 11575 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 11576 _("Iterate through updating all remote thread info"));
c906108c 11577 add_com ("talive", class_obscure, threadalive_test,
1bedd215 11578 _(" Remote thread alive test "));
c906108c
SS
11579}
11580
11581#endif /* 0 */
11582
f3fb8c85
MS
11583/* Convert a thread ID to a string. Returns the string in a static
11584 buffer. */
11585
f6ac5f3d
PA
11586const char *
11587remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11588{
79d7f229 11589 static char buf[64];
82f73884 11590 struct remote_state *rs = get_remote_state ();
f3fb8c85 11591
7cee1e54
PA
11592 if (ptid_equal (ptid, null_ptid))
11593 return normal_pid_to_str (ptid);
11594 else if (ptid_is_pid (ptid))
ecd0ada5
PA
11595 {
11596 /* Printing an inferior target id. */
11597
11598 /* When multi-process extensions are off, there's no way in the
11599 remote protocol to know the remote process id, if there's any
11600 at all. There's one exception --- when we're connected with
11601 target extended-remote, and we manually attached to a process
11602 with "attach PID". We don't record anywhere a flag that
11603 allows us to distinguish that case from the case of
11604 connecting with extended-remote and the stub already being
11605 attached to a process, and reporting yes to qAttached, hence
11606 no smart special casing here. */
11607 if (!remote_multi_process_p (rs))
11608 {
11609 xsnprintf (buf, sizeof buf, "Remote target");
11610 return buf;
11611 }
11612
11613 return normal_pid_to_str (ptid);
82f73884 11614 }
ecd0ada5 11615 else
79d7f229 11616 {
ecd0ada5
PA
11617 if (ptid_equal (magic_null_ptid, ptid))
11618 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 11619 else if (remote_multi_process_p (rs))
de0d863e
DB
11620 if (ptid_get_lwp (ptid) == 0)
11621 return normal_pid_to_str (ptid);
11622 else
11623 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11624 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
11625 else
11626 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 11627 ptid_get_lwp (ptid));
79d7f229
PA
11628 return buf;
11629 }
f3fb8c85
MS
11630}
11631
38691318
KB
11632/* Get the address of the thread local variable in OBJFILE which is
11633 stored at OFFSET within the thread local storage for thread PTID. */
11634
f6ac5f3d
PA
11635CORE_ADDR
11636remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11637 CORE_ADDR offset)
38691318 11638{
4082afcc 11639 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11640 {
11641 struct remote_state *rs = get_remote_state ();
6d820c5c 11642 char *p = rs->buf;
82f73884 11643 char *endp = rs->buf + get_remote_packet_size ();
571dd617 11644 enum packet_result result;
38691318
KB
11645
11646 strcpy (p, "qGetTLSAddr:");
11647 p += strlen (p);
82f73884 11648 p = write_ptid (p, endp, ptid);
38691318
KB
11649 *p++ = ',';
11650 p += hexnumstr (p, offset);
11651 *p++ = ',';
11652 p += hexnumstr (p, lm);
11653 *p++ = '\0';
11654
6d820c5c
DJ
11655 putpkt (rs->buf);
11656 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
11657 result = packet_ok (rs->buf,
11658 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11659 if (result == PACKET_OK)
38691318
KB
11660 {
11661 ULONGEST result;
11662
6d820c5c 11663 unpack_varlen_hex (rs->buf, &result);
38691318
KB
11664 return result;
11665 }
571dd617 11666 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11667 throw_error (TLS_GENERIC_ERROR,
11668 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11669 else
109c3e39
AC
11670 throw_error (TLS_GENERIC_ERROR,
11671 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11672 }
11673 else
109c3e39
AC
11674 throw_error (TLS_GENERIC_ERROR,
11675 _("TLS not supported or disabled on this target"));
38691318
KB
11676 /* Not reached. */
11677 return 0;
11678}
11679
711e434b
PM
11680/* Provide thread local base, i.e. Thread Information Block address.
11681 Returns 1 if ptid is found and thread_local_base is non zero. */
11682
57810aa7 11683bool
f6ac5f3d 11684remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 11685{
4082afcc 11686 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11687 {
11688 struct remote_state *rs = get_remote_state ();
11689 char *p = rs->buf;
11690 char *endp = rs->buf + get_remote_packet_size ();
11691 enum packet_result result;
11692
11693 strcpy (p, "qGetTIBAddr:");
11694 p += strlen (p);
11695 p = write_ptid (p, endp, ptid);
11696 *p++ = '\0';
11697
11698 putpkt (rs->buf);
11699 getpkt (&rs->buf, &rs->buf_size, 0);
11700 result = packet_ok (rs->buf,
11701 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11702 if (result == PACKET_OK)
11703 {
11704 ULONGEST result;
11705
11706 unpack_varlen_hex (rs->buf, &result);
11707 if (addr)
11708 *addr = (CORE_ADDR) result;
57810aa7 11709 return true;
711e434b
PM
11710 }
11711 else if (result == PACKET_UNKNOWN)
11712 error (_("Remote target doesn't support qGetTIBAddr packet"));
11713 else
11714 error (_("Remote target failed to process qGetTIBAddr request"));
11715 }
11716 else
11717 error (_("qGetTIBAddr not supported or disabled on this target"));
11718 /* Not reached. */
57810aa7 11719 return false;
711e434b
PM
11720}
11721
29709017
DJ
11722/* Support for inferring a target description based on the current
11723 architecture and the size of a 'g' packet. While the 'g' packet
11724 can have any size (since optional registers can be left off the
11725 end), some sizes are easily recognizable given knowledge of the
11726 approximate architecture. */
11727
11728struct remote_g_packet_guess
11729{
11730 int bytes;
11731 const struct target_desc *tdesc;
11732};
11733typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11734DEF_VEC_O(remote_g_packet_guess_s);
11735
11736struct remote_g_packet_data
11737{
11738 VEC(remote_g_packet_guess_s) *guesses;
11739};
11740
11741static struct gdbarch_data *remote_g_packet_data_handle;
11742
11743static void *
11744remote_g_packet_data_init (struct obstack *obstack)
11745{
11746 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11747}
11748
11749void
11750register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11751 const struct target_desc *tdesc)
11752{
11753 struct remote_g_packet_data *data
19ba03f4
SM
11754 = ((struct remote_g_packet_data *)
11755 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11756 struct remote_g_packet_guess new_guess, *guess;
11757 int ix;
11758
11759 gdb_assert (tdesc != NULL);
11760
11761 for (ix = 0;
11762 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11763 ix++)
11764 if (guess->bytes == bytes)
11765 internal_error (__FILE__, __LINE__,
9b20d036 11766 _("Duplicate g packet description added for size %d"),
29709017
DJ
11767 bytes);
11768
11769 new_guess.bytes = bytes;
11770 new_guess.tdesc = tdesc;
11771 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11772}
11773
d962ef82
DJ
11774/* Return 1 if remote_read_description would do anything on this target
11775 and architecture, 0 otherwise. */
11776
11777static int
11778remote_read_description_p (struct target_ops *target)
11779{
11780 struct remote_g_packet_data *data
19ba03f4
SM
11781 = ((struct remote_g_packet_data *)
11782 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
11783
11784 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11785 return 1;
11786
11787 return 0;
11788}
11789
f6ac5f3d
PA
11790const struct target_desc *
11791remote_target::read_description ()
29709017
DJ
11792{
11793 struct remote_g_packet_data *data
19ba03f4
SM
11794 = ((struct remote_g_packet_data *)
11795 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11796
d962ef82
DJ
11797 /* Do not try this during initial connection, when we do not know
11798 whether there is a running but stopped thread. */
11799 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
f6ac5f3d 11800 return beneath->read_description ();
d962ef82 11801
29709017
DJ
11802 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11803 {
11804 struct remote_g_packet_guess *guess;
11805 int ix;
11806 int bytes = send_g_packet ();
11807
11808 for (ix = 0;
11809 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11810 ix++)
11811 if (guess->bytes == bytes)
11812 return guess->tdesc;
11813
11814 /* We discard the g packet. A minor optimization would be to
11815 hold on to it, and fill the register cache once we have selected
11816 an architecture, but it's too tricky to do safely. */
11817 }
11818
f6ac5f3d 11819 return beneath->read_description ();
29709017
DJ
11820}
11821
a6b151f1
DJ
11822/* Remote file transfer support. This is host-initiated I/O, not
11823 target-initiated; for target-initiated, see remote-fileio.c. */
11824
11825/* If *LEFT is at least the length of STRING, copy STRING to
11826 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11827 decrease *LEFT. Otherwise raise an error. */
11828
11829static void
a121b7c1 11830remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11831{
11832 int len = strlen (string);
11833
11834 if (len > *left)
11835 error (_("Packet too long for target."));
11836
11837 memcpy (*buffer, string, len);
11838 *buffer += len;
11839 *left -= len;
11840
11841 /* NUL-terminate the buffer as a convenience, if there is
11842 room. */
11843 if (*left)
11844 **buffer = '\0';
11845}
11846
11847/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11848 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11849 decrease *LEFT. Otherwise raise an error. */
11850
11851static void
11852remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11853 int len)
11854{
11855 if (2 * len > *left)
11856 error (_("Packet too long for target."));
11857
11858 bin2hex (bytes, *buffer, len);
11859 *buffer += 2 * len;
11860 *left -= 2 * len;
11861
11862 /* NUL-terminate the buffer as a convenience, if there is
11863 room. */
11864 if (*left)
11865 **buffer = '\0';
11866}
11867
11868/* If *LEFT is large enough, convert VALUE to hex and add it to
11869 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11870 decrease *LEFT. Otherwise raise an error. */
11871
11872static void
11873remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11874{
11875 int len = hexnumlen (value);
11876
11877 if (len > *left)
11878 error (_("Packet too long for target."));
11879
11880 hexnumstr (*buffer, value);
11881 *buffer += len;
11882 *left -= len;
11883
11884 /* NUL-terminate the buffer as a convenience, if there is
11885 room. */
11886 if (*left)
11887 **buffer = '\0';
11888}
11889
11890/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11891 value, *REMOTE_ERRNO to the remote error number or zero if none
11892 was included, and *ATTACHMENT to point to the start of the annex
11893 if any. The length of the packet isn't needed here; there may
11894 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11895
11896 Return 0 if the packet could be parsed, -1 if it could not. If
11897 -1 is returned, the other variables may not be initialized. */
11898
11899static int
11900remote_hostio_parse_result (char *buffer, int *retcode,
11901 int *remote_errno, char **attachment)
11902{
11903 char *p, *p2;
11904
11905 *remote_errno = 0;
11906 *attachment = NULL;
11907
11908 if (buffer[0] != 'F')
11909 return -1;
11910
11911 errno = 0;
11912 *retcode = strtol (&buffer[1], &p, 16);
11913 if (errno != 0 || p == &buffer[1])
11914 return -1;
11915
11916 /* Check for ",errno". */
11917 if (*p == ',')
11918 {
11919 errno = 0;
11920 *remote_errno = strtol (p + 1, &p2, 16);
11921 if (errno != 0 || p + 1 == p2)
11922 return -1;
11923 p = p2;
11924 }
11925
11926 /* Check for ";attachment". If there is no attachment, the
11927 packet should end here. */
11928 if (*p == ';')
11929 {
11930 *attachment = p + 1;
11931 return 0;
11932 }
11933 else if (*p == '\0')
11934 return 0;
11935 else
11936 return -1;
11937}
11938
11939/* Send a prepared I/O packet to the target and read its response.
11940 The prepared packet is in the global RS->BUF before this function
11941 is called, and the answer is there when we return.
11942
11943 COMMAND_BYTES is the length of the request to send, which may include
11944 binary data. WHICH_PACKET is the packet configuration to check
11945 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11946 is set to the error number and -1 is returned. Otherwise the value
11947 returned by the function is returned.
11948
11949 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11950 attachment is expected; an error will be reported if there's a
11951 mismatch. If one is found, *ATTACHMENT will be set to point into
11952 the packet buffer and *ATTACHMENT_LEN will be set to the
11953 attachment's length. */
11954
6b8edb51
PA
11955int
11956remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11957 int *remote_errno, char **attachment,
11958 int *attachment_len)
a6b151f1
DJ
11959{
11960 struct remote_state *rs = get_remote_state ();
11961 int ret, bytes_read;
11962 char *attachment_tmp;
11963
20db9c52 11964 if (packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11965 {
11966 *remote_errno = FILEIO_ENOSYS;
11967 return -1;
11968 }
11969
11970 putpkt_binary (rs->buf, command_bytes);
11971 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11972
11973 /* If it timed out, something is wrong. Don't try to parse the
11974 buffer. */
11975 if (bytes_read < 0)
11976 {
11977 *remote_errno = FILEIO_EINVAL;
11978 return -1;
11979 }
11980
11981 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11982 {
11983 case PACKET_ERROR:
11984 *remote_errno = FILEIO_EINVAL;
11985 return -1;
11986 case PACKET_UNKNOWN:
11987 *remote_errno = FILEIO_ENOSYS;
11988 return -1;
11989 case PACKET_OK:
11990 break;
11991 }
11992
11993 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11994 &attachment_tmp))
11995 {
11996 *remote_errno = FILEIO_EINVAL;
11997 return -1;
11998 }
11999
12000 /* Make sure we saw an attachment if and only if we expected one. */
12001 if ((attachment_tmp == NULL && attachment != NULL)
12002 || (attachment_tmp != NULL && attachment == NULL))
12003 {
12004 *remote_errno = FILEIO_EINVAL;
12005 return -1;
12006 }
12007
12008 /* If an attachment was found, it must point into the packet buffer;
12009 work out how many bytes there were. */
12010 if (attachment_tmp != NULL)
12011 {
12012 *attachment = attachment_tmp;
12013 *attachment_len = bytes_read - (*attachment - rs->buf);
12014 }
12015
12016 return ret;
12017}
12018
dd194f6b 12019/* See declaration.h. */
80152258 12020
dd194f6b
PA
12021void
12022readahead_cache::invalidate ()
80152258 12023{
dd194f6b 12024 this->fd = -1;
80152258
PA
12025}
12026
dd194f6b 12027/* See declaration.h. */
80152258 12028
dd194f6b
PA
12029void
12030readahead_cache::invalidate_fd (int fd)
80152258 12031{
dd194f6b
PA
12032 if (this->fd == fd)
12033 this->fd = -1;
80152258
PA
12034}
12035
15a201c8
GB
12036/* Set the filesystem remote_hostio functions that take FILENAME
12037 arguments will use. Return 0 on success, or -1 if an error
12038 occurs (and set *REMOTE_ERRNO). */
12039
6b8edb51
PA
12040int
12041remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12042 int *remote_errno)
15a201c8
GB
12043{
12044 struct remote_state *rs = get_remote_state ();
12045 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12046 char *p = rs->buf;
12047 int left = get_remote_packet_size () - 1;
12048 char arg[9];
12049 int ret;
12050
12051 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12052 return 0;
12053
12054 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12055 return 0;
12056
12057 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12058
12059 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12060 remote_buffer_add_string (&p, &left, arg);
12061
12062 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
12063 remote_errno, NULL, NULL);
12064
12065 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12066 return 0;
12067
12068 if (ret == 0)
12069 rs->fs_pid = required_pid;
12070
12071 return ret;
12072}
12073
12e2a5fd 12074/* Implementation of to_fileio_open. */
a6b151f1 12075
6b8edb51
PA
12076int
12077remote_target::remote_hostio_open (inferior *inf, const char *filename,
12078 int flags, int mode, int warn_if_slow,
12079 int *remote_errno)
a6b151f1
DJ
12080{
12081 struct remote_state *rs = get_remote_state ();
12082 char *p = rs->buf;
12083 int left = get_remote_packet_size () - 1;
12084
4313b8c0
GB
12085 if (warn_if_slow)
12086 {
12087 static int warning_issued = 0;
12088
12089 printf_unfiltered (_("Reading %s from remote target...\n"),
12090 filename);
12091
12092 if (!warning_issued)
12093 {
12094 warning (_("File transfers from remote targets can be slow."
12095 " Use \"set sysroot\" to access files locally"
12096 " instead."));
12097 warning_issued = 1;
12098 }
12099 }
12100
15a201c8
GB
12101 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12102 return -1;
12103
a6b151f1
DJ
12104 remote_buffer_add_string (&p, &left, "vFile:open:");
12105
12106 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12107 strlen (filename));
12108 remote_buffer_add_string (&p, &left, ",");
12109
12110 remote_buffer_add_int (&p, &left, flags);
12111 remote_buffer_add_string (&p, &left, ",");
12112
12113 remote_buffer_add_int (&p, &left, mode);
12114
12115 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
12116 remote_errno, NULL, NULL);
12117}
12118
f6ac5f3d
PA
12119int
12120remote_target::fileio_open (struct inferior *inf, const char *filename,
12121 int flags, int mode, int warn_if_slow,
12122 int *remote_errno)
12123{
6b8edb51 12124 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
12125 remote_errno);
12126}
12127
12e2a5fd 12128/* Implementation of to_fileio_pwrite. */
a6b151f1 12129
6b8edb51
PA
12130int
12131remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12132 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12133{
12134 struct remote_state *rs = get_remote_state ();
12135 char *p = rs->buf;
12136 int left = get_remote_packet_size ();
12137 int out_len;
12138
dd194f6b 12139 rs->readahead_cache.invalidate_fd (fd);
80152258 12140
a6b151f1
DJ
12141 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12142
12143 remote_buffer_add_int (&p, &left, fd);
12144 remote_buffer_add_string (&p, &left, ",");
12145
12146 remote_buffer_add_int (&p, &left, offset);
12147 remote_buffer_add_string (&p, &left, ",");
12148
124e13d9 12149 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
12150 get_remote_packet_size () - (p - rs->buf));
12151
12152 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12153 remote_errno, NULL, NULL);
12154}
12155
f6ac5f3d
PA
12156int
12157remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12158 ULONGEST offset, int *remote_errno)
12159{
6b8edb51 12160 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12161}
12162
80152258
PA
12163/* Helper for the implementation of to_fileio_pread. Read the file
12164 from the remote side with vFile:pread. */
a6b151f1 12165
6b8edb51
PA
12166int
12167remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12168 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12169{
12170 struct remote_state *rs = get_remote_state ();
12171 char *p = rs->buf;
12172 char *attachment;
12173 int left = get_remote_packet_size ();
12174 int ret, attachment_len;
12175 int read_len;
12176
12177 remote_buffer_add_string (&p, &left, "vFile:pread:");
12178
12179 remote_buffer_add_int (&p, &left, fd);
12180 remote_buffer_add_string (&p, &left, ",");
12181
12182 remote_buffer_add_int (&p, &left, len);
12183 remote_buffer_add_string (&p, &left, ",");
12184
12185 remote_buffer_add_int (&p, &left, offset);
12186
12187 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12188 remote_errno, &attachment,
12189 &attachment_len);
12190
12191 if (ret < 0)
12192 return ret;
12193
bc20a4af 12194 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12195 read_buf, len);
12196 if (read_len != ret)
12197 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12198
12199 return ret;
12200}
12201
dd194f6b 12202/* See declaration.h. */
80152258 12203
dd194f6b
PA
12204int
12205readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12206 ULONGEST offset)
80152258 12207{
dd194f6b
PA
12208 if (this->fd == fd
12209 && this->offset <= offset
12210 && offset < this->offset + this->bufsize)
80152258 12211 {
dd194f6b 12212 ULONGEST max = this->offset + this->bufsize;
80152258
PA
12213
12214 if (offset + len > max)
12215 len = max - offset;
12216
dd194f6b 12217 memcpy (read_buf, this->buf + offset - this->offset, len);
80152258
PA
12218 return len;
12219 }
12220
12221 return 0;
12222}
12223
12224/* Implementation of to_fileio_pread. */
12225
6b8edb51
PA
12226int
12227remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12228 ULONGEST offset, int *remote_errno)
80152258
PA
12229{
12230 int ret;
12231 struct remote_state *rs = get_remote_state ();
dd194f6b 12232 readahead_cache *cache = &rs->readahead_cache;
80152258 12233
dd194f6b 12234 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12235 if (ret > 0)
12236 {
12237 cache->hit_count++;
12238
12239 if (remote_debug)
12240 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12241 pulongest (cache->hit_count));
12242 return ret;
12243 }
12244
12245 cache->miss_count++;
12246 if (remote_debug)
12247 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12248 pulongest (cache->miss_count));
12249
12250 cache->fd = fd;
12251 cache->offset = offset;
12252 cache->bufsize = get_remote_packet_size ();
224c3ddb 12253 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258 12254
6b8edb51 12255 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
80152258
PA
12256 cache->offset, remote_errno);
12257 if (ret <= 0)
12258 {
dd194f6b 12259 cache->invalidate_fd (fd);
80152258
PA
12260 return ret;
12261 }
12262
12263 cache->bufsize = ret;
dd194f6b 12264 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12265}
12266
f6ac5f3d
PA
12267int
12268remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12269 ULONGEST offset, int *remote_errno)
12270{
6b8edb51 12271 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12272}
12273
12e2a5fd 12274/* Implementation of to_fileio_close. */
a6b151f1 12275
6b8edb51
PA
12276int
12277remote_target::remote_hostio_close (int fd, int *remote_errno)
a6b151f1
DJ
12278{
12279 struct remote_state *rs = get_remote_state ();
12280 char *p = rs->buf;
12281 int left = get_remote_packet_size () - 1;
12282
dd194f6b 12283 rs->readahead_cache.invalidate_fd (fd);
80152258 12284
a6b151f1
DJ
12285 remote_buffer_add_string (&p, &left, "vFile:close:");
12286
12287 remote_buffer_add_int (&p, &left, fd);
12288
12289 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12290 remote_errno, NULL, NULL);
12291}
12292
f6ac5f3d
PA
12293int
12294remote_target::fileio_close (int fd, int *remote_errno)
12295{
6b8edb51 12296 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12297}
12298
12e2a5fd 12299/* Implementation of to_fileio_unlink. */
a6b151f1 12300
6b8edb51
PA
12301int
12302remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12303 int *remote_errno)
a6b151f1
DJ
12304{
12305 struct remote_state *rs = get_remote_state ();
12306 char *p = rs->buf;
12307 int left = get_remote_packet_size () - 1;
12308
15a201c8
GB
12309 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12310 return -1;
12311
a6b151f1
DJ
12312 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12313
12314 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12315 strlen (filename));
12316
12317 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12318 remote_errno, NULL, NULL);
12319}
12320
f6ac5f3d
PA
12321int
12322remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12323 int *remote_errno)
12324{
6b8edb51 12325 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12326}
12327
12e2a5fd 12328/* Implementation of to_fileio_readlink. */
b9e7b9c3 12329
f6ac5f3d
PA
12330gdb::optional<std::string>
12331remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12332 int *remote_errno)
b9e7b9c3
UW
12333{
12334 struct remote_state *rs = get_remote_state ();
12335 char *p = rs->buf;
12336 char *attachment;
12337 int left = get_remote_packet_size ();
12338 int len, attachment_len;
12339 int read_len;
b9e7b9c3 12340
15a201c8 12341 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12342 return {};
15a201c8 12343
b9e7b9c3
UW
12344 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12345
12346 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12347 strlen (filename));
12348
12349 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12350 remote_errno, &attachment,
12351 &attachment_len);
12352
12353 if (len < 0)
e0d3522b 12354 return {};
b9e7b9c3 12355
e0d3522b 12356 std::string ret (len, '\0');
b9e7b9c3 12357
bc20a4af 12358 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12359 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12360 if (read_len != len)
12361 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12362
b9e7b9c3
UW
12363 return ret;
12364}
12365
12e2a5fd 12366/* Implementation of to_fileio_fstat. */
0a93529c 12367
f6ac5f3d
PA
12368int
12369remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
0a93529c
GB
12370{
12371 struct remote_state *rs = get_remote_state ();
12372 char *p = rs->buf;
12373 int left = get_remote_packet_size ();
12374 int attachment_len, ret;
12375 char *attachment;
12376 struct fio_stat fst;
12377 int read_len;
12378
464b0089
GB
12379 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12380
12381 remote_buffer_add_int (&p, &left, fd);
12382
12383 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12384 remote_errno, &attachment,
12385 &attachment_len);
12386 if (ret < 0)
0a93529c 12387 {
464b0089
GB
12388 if (*remote_errno != FILEIO_ENOSYS)
12389 return ret;
12390
0a93529c
GB
12391 /* Strictly we should return -1, ENOSYS here, but when
12392 "set sysroot remote:" was implemented in August 2008
12393 BFD's need for a stat function was sidestepped with
12394 this hack. This was not remedied until March 2015
12395 so we retain the previous behavior to avoid breaking
12396 compatibility.
12397
12398 Note that the memset is a March 2015 addition; older
12399 GDBs set st_size *and nothing else* so the structure
12400 would have garbage in all other fields. This might
12401 break something but retaining the previous behavior
12402 here would be just too wrong. */
12403
12404 memset (st, 0, sizeof (struct stat));
12405 st->st_size = INT_MAX;
12406 return 0;
12407 }
12408
0a93529c
GB
12409 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12410 (gdb_byte *) &fst, sizeof (fst));
12411
12412 if (read_len != ret)
12413 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12414
12415 if (read_len != sizeof (fst))
12416 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12417 read_len, (int) sizeof (fst));
12418
12419 remote_fileio_to_host_stat (&fst, st);
12420
12421 return 0;
12422}
12423
12e2a5fd 12424/* Implementation of to_filesystem_is_local. */
e3dd7556 12425
57810aa7 12426bool
f6ac5f3d 12427remote_target::filesystem_is_local ()
e3dd7556
GB
12428{
12429 /* Valgrind GDB presents itself as a remote target but works
12430 on the local filesystem: it does not implement remote get
12431 and users are not expected to set a sysroot. To handle
12432 this case we treat the remote filesystem as local if the
12433 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12434 does not support vFile:open. */
a3be80c3 12435 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
12436 {
12437 enum packet_support ps = packet_support (PACKET_vFile_open);
12438
12439 if (ps == PACKET_SUPPORT_UNKNOWN)
12440 {
12441 int fd, remote_errno;
12442
12443 /* Try opening a file to probe support. The supplied
12444 filename is irrelevant, we only care about whether
12445 the stub recognizes the packet or not. */
6b8edb51 12446 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12447 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12448 &remote_errno);
12449
12450 if (fd >= 0)
6b8edb51 12451 remote_hostio_close (fd, &remote_errno);
e3dd7556
GB
12452
12453 ps = packet_support (PACKET_vFile_open);
12454 }
12455
12456 if (ps == PACKET_DISABLE)
12457 {
12458 static int warning_issued = 0;
12459
12460 if (!warning_issued)
12461 {
12462 warning (_("remote target does not support file"
12463 " transfer, attempting to access files"
12464 " from local filesystem."));
12465 warning_issued = 1;
12466 }
12467
57810aa7 12468 return true;
e3dd7556
GB
12469 }
12470 }
12471
57810aa7 12472 return false;
e3dd7556
GB
12473}
12474
a6b151f1
DJ
12475static int
12476remote_fileio_errno_to_host (int errnum)
12477{
12478 switch (errnum)
12479 {
12480 case FILEIO_EPERM:
12481 return EPERM;
12482 case FILEIO_ENOENT:
12483 return ENOENT;
12484 case FILEIO_EINTR:
12485 return EINTR;
12486 case FILEIO_EIO:
12487 return EIO;
12488 case FILEIO_EBADF:
12489 return EBADF;
12490 case FILEIO_EACCES:
12491 return EACCES;
12492 case FILEIO_EFAULT:
12493 return EFAULT;
12494 case FILEIO_EBUSY:
12495 return EBUSY;
12496 case FILEIO_EEXIST:
12497 return EEXIST;
12498 case FILEIO_ENODEV:
12499 return ENODEV;
12500 case FILEIO_ENOTDIR:
12501 return ENOTDIR;
12502 case FILEIO_EISDIR:
12503 return EISDIR;
12504 case FILEIO_EINVAL:
12505 return EINVAL;
12506 case FILEIO_ENFILE:
12507 return ENFILE;
12508 case FILEIO_EMFILE:
12509 return EMFILE;
12510 case FILEIO_EFBIG:
12511 return EFBIG;
12512 case FILEIO_ENOSPC:
12513 return ENOSPC;
12514 case FILEIO_ESPIPE:
12515 return ESPIPE;
12516 case FILEIO_EROFS:
12517 return EROFS;
12518 case FILEIO_ENOSYS:
12519 return ENOSYS;
12520 case FILEIO_ENAMETOOLONG:
12521 return ENAMETOOLONG;
12522 }
12523 return -1;
12524}
12525
12526static char *
12527remote_hostio_error (int errnum)
12528{
12529 int host_error = remote_fileio_errno_to_host (errnum);
12530
12531 if (host_error == -1)
12532 error (_("Unknown remote I/O error %d"), errnum);
12533 else
12534 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12535}
12536
440b7aec
PA
12537/* A RAII wrapper around a remote file descriptor. */
12538
12539class scoped_remote_fd
a6b151f1 12540{
440b7aec 12541public:
6b8edb51
PA
12542 scoped_remote_fd (remote_target *remote, int fd)
12543 : m_remote (remote), m_fd (fd)
440b7aec
PA
12544 {
12545 }
a6b151f1 12546
440b7aec
PA
12547 ~scoped_remote_fd ()
12548 {
12549 if (m_fd != -1)
12550 {
12551 try
12552 {
12553 int remote_errno;
6b8edb51 12554 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12555 }
12556 catch (...)
12557 {
12558 /* Swallow exception before it escapes the dtor. If
12559 something goes wrong, likely the connection is gone,
12560 and there's nothing else that can be done. */
12561 }
12562 }
12563 }
12564
12565 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12566
12567 /* Release ownership of the file descriptor, and return it. */
12568 int release () noexcept
12569 {
12570 int fd = m_fd;
12571 m_fd = -1;
12572 return fd;
12573 }
12574
12575 /* Return the owned file descriptor. */
12576 int get () const noexcept
12577 {
12578 return m_fd;
12579 }
12580
12581private:
6b8edb51
PA
12582 /* The remote target. */
12583 remote_target *m_remote;
12584
440b7aec
PA
12585 /* The owned remote I/O file descriptor. */
12586 int m_fd;
12587};
a6b151f1
DJ
12588
12589void
12590remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12591{
12592 remote_target *remote = get_current_remote_target ();
12593
12594 if (remote == nullptr)
12595 error (_("command can only be used with remote target"));
12596
12597 remote->remote_file_put (local_file, remote_file, from_tty);
12598}
12599
12600void
12601remote_target::remote_file_put (const char *local_file, const char *remote_file,
12602 int from_tty)
a6b151f1 12603{
440b7aec
PA
12604 struct cleanup *back_to;
12605 int retcode, remote_errno, bytes, io_size;
a6b151f1
DJ
12606 gdb_byte *buffer;
12607 int bytes_in_buffer;
12608 int saw_eof;
12609 ULONGEST offset;
a6b151f1 12610
d419f42d 12611 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12612 if (file == NULL)
12613 perror_with_name (local_file);
a6b151f1 12614
440b7aec 12615 scoped_remote_fd fd
6b8edb51
PA
12616 (this, remote_hostio_open (NULL,
12617 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12618 | FILEIO_O_TRUNC),
12619 0700, 0, &remote_errno));
440b7aec 12620 if (fd.get () == -1)
a6b151f1
DJ
12621 remote_hostio_error (remote_errno);
12622
12623 /* Send up to this many bytes at once. They won't all fit in the
12624 remote packet limit, so we'll transfer slightly fewer. */
12625 io_size = get_remote_packet_size ();
224c3ddb 12626 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 12627 back_to = make_cleanup (xfree, buffer);
a6b151f1 12628
a6b151f1
DJ
12629 bytes_in_buffer = 0;
12630 saw_eof = 0;
12631 offset = 0;
12632 while (bytes_in_buffer || !saw_eof)
12633 {
12634 if (!saw_eof)
12635 {
3e43a32a
MS
12636 bytes = fread (buffer + bytes_in_buffer, 1,
12637 io_size - bytes_in_buffer,
d419f42d 12638 file.get ());
a6b151f1
DJ
12639 if (bytes == 0)
12640 {
d419f42d 12641 if (ferror (file.get ()))
a6b151f1
DJ
12642 error (_("Error reading %s."), local_file);
12643 else
12644 {
12645 /* EOF. Unless there is something still in the
12646 buffer from the last iteration, we are done. */
12647 saw_eof = 1;
12648 if (bytes_in_buffer == 0)
12649 break;
12650 }
12651 }
12652 }
12653 else
12654 bytes = 0;
12655
12656 bytes += bytes_in_buffer;
12657 bytes_in_buffer = 0;
12658
6b8edb51 12659 retcode = remote_hostio_pwrite (fd.get (), buffer, bytes,
3e43a32a 12660 offset, &remote_errno);
a6b151f1
DJ
12661
12662 if (retcode < 0)
12663 remote_hostio_error (remote_errno);
12664 else if (retcode == 0)
12665 error (_("Remote write of %d bytes returned 0!"), bytes);
12666 else if (retcode < bytes)
12667 {
12668 /* Short write. Save the rest of the read data for the next
12669 write. */
12670 bytes_in_buffer = bytes - retcode;
12671 memmove (buffer, buffer + retcode, bytes_in_buffer);
12672 }
12673
12674 offset += retcode;
12675 }
12676
6b8edb51 12677 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12678 remote_hostio_error (remote_errno);
12679
12680 if (from_tty)
12681 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12682 do_cleanups (back_to);
12683}
12684
12685void
12686remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
12687{
12688 remote_target *remote = get_current_remote_target ();
12689
12690 if (remote == nullptr)
12691 error (_("command can only be used with remote target"));
12692
12693 remote->remote_file_get (remote_file, local_file, from_tty);
12694}
12695
12696void
12697remote_target::remote_file_get (const char *remote_file, const char *local_file,
12698 int from_tty)
a6b151f1 12699{
440b7aec
PA
12700 struct cleanup *back_to;
12701 int remote_errno, bytes, io_size;
a6b151f1
DJ
12702 gdb_byte *buffer;
12703 ULONGEST offset;
a6b151f1 12704
440b7aec 12705 scoped_remote_fd fd
6b8edb51
PA
12706 (this, remote_hostio_open (NULL,
12707 remote_file, FILEIO_O_RDONLY, 0, 0,
12708 &remote_errno));
440b7aec 12709 if (fd.get () == -1)
a6b151f1
DJ
12710 remote_hostio_error (remote_errno);
12711
d419f42d 12712 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12713 if (file == NULL)
12714 perror_with_name (local_file);
a6b151f1
DJ
12715
12716 /* Send up to this many bytes at once. They won't all fit in the
12717 remote packet limit, so we'll transfer slightly fewer. */
12718 io_size = get_remote_packet_size ();
224c3ddb 12719 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 12720 back_to = make_cleanup (xfree, buffer);
a6b151f1 12721
a6b151f1
DJ
12722 offset = 0;
12723 while (1)
12724 {
6b8edb51 12725 bytes = remote_hostio_pread (fd.get (), buffer, io_size, offset,
440b7aec 12726 &remote_errno);
a6b151f1
DJ
12727 if (bytes == 0)
12728 /* Success, but no bytes, means end-of-file. */
12729 break;
12730 if (bytes == -1)
12731 remote_hostio_error (remote_errno);
12732
12733 offset += bytes;
12734
d419f42d 12735 bytes = fwrite (buffer, 1, bytes, file.get ());
a6b151f1
DJ
12736 if (bytes == 0)
12737 perror_with_name (local_file);
12738 }
12739
6b8edb51 12740 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12741 remote_hostio_error (remote_errno);
12742
12743 if (from_tty)
12744 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12745 do_cleanups (back_to);
12746}
12747
12748void
12749remote_file_delete (const char *remote_file, int from_tty)
12750{
6b8edb51 12751 remote_target *remote = get_current_remote_target ();
a6b151f1 12752
6b8edb51 12753 if (remote == nullptr)
a6b151f1
DJ
12754 error (_("command can only be used with remote target"));
12755
6b8edb51
PA
12756 remote->remote_file_delete (remote_file, from_tty);
12757}
12758
12759void
12760remote_target::remote_file_delete (const char *remote_file, int from_tty)
12761{
12762 int retcode, remote_errno;
12763
12764 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
12765 if (retcode == -1)
12766 remote_hostio_error (remote_errno);
12767
12768 if (from_tty)
12769 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12770}
12771
12772static void
ac88e2de 12773remote_put_command (const char *args, int from_tty)
a6b151f1 12774{
d1a41061
PP
12775 if (args == NULL)
12776 error_no_arg (_("file to put"));
12777
773a1edc 12778 gdb_argv argv (args);
a6b151f1
DJ
12779 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12780 error (_("Invalid parameters to remote put"));
12781
12782 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12783}
12784
12785static void
ac88e2de 12786remote_get_command (const char *args, int from_tty)
a6b151f1 12787{
d1a41061
PP
12788 if (args == NULL)
12789 error_no_arg (_("file to get"));
12790
773a1edc 12791 gdb_argv argv (args);
a6b151f1
DJ
12792 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12793 error (_("Invalid parameters to remote get"));
12794
12795 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12796}
12797
12798static void
ac88e2de 12799remote_delete_command (const char *args, int from_tty)
a6b151f1 12800{
d1a41061
PP
12801 if (args == NULL)
12802 error_no_arg (_("file to delete"));
12803
773a1edc 12804 gdb_argv argv (args);
a6b151f1
DJ
12805 if (argv[0] == NULL || argv[1] != NULL)
12806 error (_("Invalid parameters to remote delete"));
12807
12808 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12809}
12810
12811static void
981a3fb3 12812remote_command (const char *args, int from_tty)
a6b151f1 12813{
635c7e8a 12814 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12815}
12816
57810aa7 12817bool
f6ac5f3d 12818remote_target::can_execute_reverse ()
b2175913 12819{
4082afcc
PA
12820 if (packet_support (PACKET_bs) == PACKET_ENABLE
12821 || packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 12822 return true;
40ab02ce 12823 else
57810aa7 12824 return false;
b2175913
MS
12825}
12826
57810aa7 12827bool
f6ac5f3d 12828remote_target::supports_non_stop ()
74531fed 12829{
57810aa7 12830 return true;
74531fed
PA
12831}
12832
57810aa7 12833bool
f6ac5f3d 12834remote_target::supports_disable_randomization ()
03583c20
UW
12835{
12836 /* Only supported in extended mode. */
57810aa7 12837 return false;
03583c20
UW
12838}
12839
57810aa7 12840bool
f6ac5f3d 12841remote_target::supports_multi_process ()
8a305172
PA
12842{
12843 struct remote_state *rs = get_remote_state ();
a744cf53 12844
8020350c 12845 return remote_multi_process_p (rs);
8a305172
PA
12846}
12847
70221824 12848static int
f6ac5f3d 12849remote_supports_cond_tracepoints ()
782b2b07 12850{
4082afcc 12851 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12852}
12853
57810aa7 12854bool
f6ac5f3d 12855remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 12856{
4082afcc 12857 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12858}
12859
70221824 12860static int
f6ac5f3d 12861remote_supports_fast_tracepoints ()
7a697b8d 12862{
4082afcc 12863 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12864}
12865
0fb4aa4b 12866static int
f6ac5f3d 12867remote_supports_static_tracepoints ()
0fb4aa4b 12868{
4082afcc 12869 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12870}
12871
1e4d1764 12872static int
f6ac5f3d 12873remote_supports_install_in_trace ()
1e4d1764 12874{
4082afcc 12875 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12876}
12877
57810aa7 12878bool
f6ac5f3d 12879remote_target::supports_enable_disable_tracepoint ()
d248b706 12880{
4082afcc
PA
12881 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12882 == PACKET_ENABLE);
d248b706
KY
12883}
12884
57810aa7 12885bool
f6ac5f3d 12886remote_target::supports_string_tracing ()
3065dfb6 12887{
4082afcc 12888 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12889}
12890
57810aa7 12891bool
f6ac5f3d 12892remote_target::can_run_breakpoint_commands ()
d3ce09f5 12893{
4082afcc 12894 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12895}
12896
f6ac5f3d
PA
12897void
12898remote_target::trace_init ()
35b1e5cc 12899{
b6bb3468
PA
12900 struct remote_state *rs = get_remote_state ();
12901
35b1e5cc 12902 putpkt ("QTinit");
b6bb3468
PA
12903 remote_get_noisy_reply ();
12904 if (strcmp (rs->buf, "OK") != 0)
35b1e5cc
SS
12905 error (_("Target does not support this command."));
12906}
12907
409873ef
SS
12908/* Recursive routine to walk through command list including loops, and
12909 download packets for each command. */
12910
6b8edb51
PA
12911void
12912remote_target::remote_download_command_source (int num, ULONGEST addr,
12913 struct command_line *cmds)
409873ef
SS
12914{
12915 struct remote_state *rs = get_remote_state ();
12916 struct command_line *cmd;
12917
12918 for (cmd = cmds; cmd; cmd = cmd->next)
12919 {
0df8b418 12920 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12921 strcpy (rs->buf, "QTDPsrc:");
12922 encode_source_string (num, addr, "cmd", cmd->line,
12923 rs->buf + strlen (rs->buf),
12924 rs->buf_size - strlen (rs->buf));
12925 putpkt (rs->buf);
b6bb3468
PA
12926 remote_get_noisy_reply ();
12927 if (strcmp (rs->buf, "OK"))
409873ef
SS
12928 warning (_("Target does not support source download."));
12929
12930 if (cmd->control_type == while_control
12931 || cmd->control_type == while_stepping_control)
12932 {
12973681 12933 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 12934
0df8b418 12935 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12936 strcpy (rs->buf, "QTDPsrc:");
12937 encode_source_string (num, addr, "cmd", "end",
12938 rs->buf + strlen (rs->buf),
12939 rs->buf_size - strlen (rs->buf));
12940 putpkt (rs->buf);
b6bb3468
PA
12941 remote_get_noisy_reply ();
12942 if (strcmp (rs->buf, "OK"))
409873ef
SS
12943 warning (_("Target does not support source download."));
12944 }
12945 }
12946}
12947
f6ac5f3d
PA
12948void
12949remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc 12950{
bba74b36 12951#define BUF_SIZE 2048
e8ba3115 12952
35b1e5cc 12953 CORE_ADDR tpaddr;
409873ef 12954 char addrbuf[40];
bba74b36 12955 char buf[BUF_SIZE];
b44ec619
SM
12956 std::vector<std::string> tdp_actions;
12957 std::vector<std::string> stepping_actions;
35b1e5cc 12958 char *pkt;
e8ba3115 12959 struct breakpoint *b = loc->owner;
d9b3f62e 12960 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 12961 struct remote_state *rs = get_remote_state ();
35b1e5cc 12962
dc673c81 12963 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12964
12965 tpaddr = loc->address;
12966 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
12967 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12968 addrbuf, /* address */
12969 (b->enable_state == bp_enabled ? 'E' : 'D'),
12970 t->step_count, t->pass_count);
e8ba3115
YQ
12971 /* Fast tracepoints are mostly handled by the target, but we can
12972 tell the target how big of an instruction block should be moved
12973 around. */
12974 if (b->type == bp_fast_tracepoint)
12975 {
12976 /* Only test for support at download time; we may not know
12977 target capabilities at definition time. */
12978 if (remote_supports_fast_tracepoints ())
35b1e5cc 12979 {
6b940e6a
PL
12980 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12981 NULL))
bba74b36 12982 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 12983 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 12984 else
e8ba3115
YQ
12985 /* If it passed validation at definition but fails now,
12986 something is very wrong. */
12987 internal_error (__FILE__, __LINE__,
12988 _("Fast tracepoint not "
12989 "valid during download"));
35b1e5cc 12990 }
e8ba3115
YQ
12991 else
12992 /* Fast tracepoints are functionally identical to regular
12993 tracepoints, so don't take lack of support as a reason to
12994 give up on the trace run. */
12995 warning (_("Target does not support fast tracepoints, "
12996 "downloading %d as regular tracepoint"), b->number);
12997 }
12998 else if (b->type == bp_static_tracepoint)
12999 {
13000 /* Only test for support at download time; we may not know
13001 target capabilities at definition time. */
13002 if (remote_supports_static_tracepoints ())
0fb4aa4b 13003 {
e8ba3115 13004 struct static_tracepoint_marker marker;
0fb4aa4b 13005
e8ba3115
YQ
13006 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13007 strcat (buf, ":S");
0fb4aa4b 13008 else
e8ba3115 13009 error (_("Static tracepoint not valid during download"));
0fb4aa4b 13010 }
e8ba3115
YQ
13011 else
13012 /* Fast tracepoints are functionally identical to regular
13013 tracepoints, so don't take lack of support as a reason
13014 to give up on the trace run. */
13015 error (_("Target does not support static tracepoints"));
13016 }
13017 /* If the tracepoint has a conditional, make it into an agent
13018 expression and append to the definition. */
13019 if (loc->cond)
13020 {
13021 /* Only test support at download time, we may not know target
13022 capabilities at definition time. */
13023 if (remote_supports_cond_tracepoints ())
35b1e5cc 13024 {
833177a4 13025 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
bba74b36
YQ
13026 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
13027 aexpr->len);
e8ba3115 13028 pkt = buf + strlen (buf);
b44ec619 13029 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
13030 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13031 *pkt = '\0';
35b1e5cc 13032 }
e8ba3115
YQ
13033 else
13034 warning (_("Target does not support conditional tracepoints, "
13035 "ignoring tp %d cond"), b->number);
13036 }
35b1e5cc 13037
d9b3f62e 13038 if (b->commands || *default_collect)
e8ba3115
YQ
13039 strcat (buf, "-");
13040 putpkt (buf);
b6bb3468
PA
13041 remote_get_noisy_reply ();
13042 if (strcmp (rs->buf, "OK"))
e8ba3115 13043 error (_("Target does not support tracepoints."));
35b1e5cc 13044
e8ba3115 13045 /* do_single_steps (t); */
b44ec619
SM
13046 for (auto action_it = tdp_actions.begin ();
13047 action_it != tdp_actions.end (); action_it++)
e8ba3115 13048 {
b44ec619
SM
13049 QUIT; /* Allow user to bail out with ^C. */
13050
13051 bool has_more = (action_it != tdp_actions.end ()
13052 || !stepping_actions.empty ());
13053
13054 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
13055 b->number, addrbuf, /* address */
13056 action_it->c_str (),
13057 has_more ? '-' : 0);
13058 putpkt (buf);
13059 remote_get_noisy_reply ();
13060 if (strcmp (rs->buf, "OK"))
13061 error (_("Error on target while setting tracepoints."));
e8ba3115 13062 }
409873ef 13063
b44ec619
SM
13064 for (auto action_it = stepping_actions.begin ();
13065 action_it != stepping_actions.end (); action_it++)
13066 {
13067 QUIT; /* Allow user to bail out with ^C. */
13068
13069 bool is_first = action_it == stepping_actions.begin ();
13070 bool has_more = action_it != stepping_actions.end ();
13071
13072 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
13073 b->number, addrbuf, /* address */
13074 is_first ? "S" : "",
13075 action_it->c_str (),
13076 has_more ? "-" : "");
13077 putpkt (buf);
13078 remote_get_noisy_reply ();
13079 if (strcmp (rs->buf, "OK"))
13080 error (_("Error on target while setting tracepoints."));
13081 }
13082
4082afcc 13083 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 13084 {
f00aae0f 13085 if (b->location != NULL)
409873ef 13086 {
e8ba3115 13087 strcpy (buf, "QTDPsrc:");
f00aae0f 13088 encode_source_string (b->number, loc->address, "at",
d28cd78a 13089 event_location_to_string (b->location.get ()),
f00aae0f 13090 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115 13091 putpkt (buf);
b6bb3468
PA
13092 remote_get_noisy_reply ();
13093 if (strcmp (rs->buf, "OK"))
e8ba3115 13094 warning (_("Target does not support source download."));
409873ef 13095 }
e8ba3115
YQ
13096 if (b->cond_string)
13097 {
13098 strcpy (buf, "QTDPsrc:");
13099 encode_source_string (b->number, loc->address,
13100 "cond", b->cond_string, buf + strlen (buf),
13101 2048 - strlen (buf));
13102 putpkt (buf);
b6bb3468
PA
13103 remote_get_noisy_reply ();
13104 if (strcmp (rs->buf, "OK"))
e8ba3115
YQ
13105 warning (_("Target does not support source download."));
13106 }
13107 remote_download_command_source (b->number, loc->address,
13108 breakpoint_commands (b));
35b1e5cc 13109 }
35b1e5cc
SS
13110}
13111
57810aa7 13112bool
f6ac5f3d 13113remote_target::can_download_tracepoint ()
1e4d1764 13114{
1e51243a
PA
13115 struct remote_state *rs = get_remote_state ();
13116 struct trace_status *ts;
13117 int status;
13118
13119 /* Don't try to install tracepoints until we've relocated our
13120 symbols, and fetched and merged the target's tracepoint list with
13121 ours. */
13122 if (rs->starting_up)
57810aa7 13123 return false;
1e51243a
PA
13124
13125 ts = current_trace_status ();
f6ac5f3d 13126 status = get_trace_status (ts);
1e4d1764
YQ
13127
13128 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13129 return false;
1e4d1764
YQ
13130
13131 /* If we are in a tracing experiment, but remote stub doesn't support
13132 installing tracepoint in trace, we have to return. */
13133 if (!remote_supports_install_in_trace ())
57810aa7 13134 return false;
1e4d1764 13135
57810aa7 13136 return true;
1e4d1764
YQ
13137}
13138
13139
f6ac5f3d
PA
13140void
13141remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
13142{
13143 struct remote_state *rs = get_remote_state ();
00bf0b85 13144 char *p;
35b1e5cc 13145
bba74b36 13146 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
13147 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13148 tsv.builtin);
00bf0b85 13149 p = rs->buf + strlen (rs->buf);
c252925c 13150 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
00bf0b85 13151 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 13152 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 13153 *p++ = '\0';
35b1e5cc 13154 putpkt (rs->buf);
b6bb3468
PA
13155 remote_get_noisy_reply ();
13156 if (*rs->buf == '\0')
ad91cd99 13157 error (_("Target does not support this command."));
b6bb3468 13158 if (strcmp (rs->buf, "OK") != 0)
ad91cd99 13159 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13160}
13161
f6ac5f3d
PA
13162void
13163remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13164{
13165 struct remote_state *rs = get_remote_state ();
13166 char addr_buf[40];
13167
13168 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
13169 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13170 location->owner->number, addr_buf);
d248b706 13171 putpkt (rs->buf);
b6bb3468 13172 remote_get_noisy_reply ();
d248b706
KY
13173 if (*rs->buf == '\0')
13174 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13175 if (strcmp (rs->buf, "OK") != 0)
13176 error (_("Error on target while enabling tracepoint."));
13177}
13178
f6ac5f3d
PA
13179void
13180remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13181{
13182 struct remote_state *rs = get_remote_state ();
13183 char addr_buf[40];
13184
13185 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
13186 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13187 location->owner->number, addr_buf);
d248b706 13188 putpkt (rs->buf);
b6bb3468 13189 remote_get_noisy_reply ();
d248b706
KY
13190 if (*rs->buf == '\0')
13191 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13192 if (strcmp (rs->buf, "OK") != 0)
13193 error (_("Error on target while disabling tracepoint."));
13194}
13195
f6ac5f3d
PA
13196void
13197remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13198{
13199 asection *s;
81b9b86e 13200 bfd *abfd = NULL;
35b1e5cc 13201 bfd_size_type size;
608bcef2 13202 bfd_vma vma;
35b1e5cc 13203 int anysecs = 0;
c2fa21f1 13204 int offset = 0;
35b1e5cc
SS
13205
13206 if (!exec_bfd)
13207 return; /* No information to give. */
13208
b6bb3468
PA
13209 struct remote_state *rs = get_remote_state ();
13210
13211 strcpy (rs->buf, "QTro");
13212 offset = strlen (rs->buf);
35b1e5cc
SS
13213 for (s = exec_bfd->sections; s; s = s->next)
13214 {
13215 char tmp1[40], tmp2[40];
c2fa21f1 13216 int sec_length;
35b1e5cc
SS
13217
13218 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 13219 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
13220 (s->flags & SEC_READONLY) == 0)
13221 continue;
13222
13223 anysecs = 1;
81b9b86e 13224 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 13225 size = bfd_get_section_size (s);
608bcef2
HZ
13226 sprintf_vma (tmp1, vma);
13227 sprintf_vma (tmp2, vma + size);
c2fa21f1 13228 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
b6bb3468 13229 if (offset + sec_length + 1 > rs->buf_size)
c2fa21f1 13230 {
4082afcc 13231 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 13232 warning (_("\
c2fa21f1
HZ
13233Too many sections for read-only sections definition packet."));
13234 break;
13235 }
b6bb3468 13236 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
bba74b36 13237 tmp1, tmp2);
c2fa21f1 13238 offset += sec_length;
35b1e5cc
SS
13239 }
13240 if (anysecs)
13241 {
b6bb3468
PA
13242 putpkt (rs->buf);
13243 getpkt (&rs->buf, &rs->buf_size, 0);
35b1e5cc
SS
13244 }
13245}
13246
f6ac5f3d
PA
13247void
13248remote_target::trace_start ()
35b1e5cc 13249{
b6bb3468
PA
13250 struct remote_state *rs = get_remote_state ();
13251
35b1e5cc 13252 putpkt ("QTStart");
b6bb3468
PA
13253 remote_get_noisy_reply ();
13254 if (*rs->buf == '\0')
ad91cd99 13255 error (_("Target does not support this command."));
b6bb3468
PA
13256 if (strcmp (rs->buf, "OK") != 0)
13257 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
13258}
13259
f6ac5f3d
PA
13260int
13261remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13262{
953b98d1 13263 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13264 char *p = NULL;
0df8b418 13265 /* FIXME we need to get register block size some other way. */
00bf0b85 13266 extern int trace_regblock_size;
bd3eecc3 13267 enum packet_result result;
b6bb3468 13268 struct remote_state *rs = get_remote_state ();
bd3eecc3 13269
4082afcc 13270 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13271 return -1;
a744cf53 13272
5cd63fda 13273 trace_regblock_size
9d6eea31 13274 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 13275
049dc89b
JK
13276 putpkt ("qTStatus");
13277
492d29ea 13278 TRY
67f41397 13279 {
b6bb3468 13280 p = remote_get_noisy_reply ();
67f41397 13281 }
492d29ea 13282 CATCH (ex, RETURN_MASK_ERROR)
67f41397 13283 {
598d3636
JK
13284 if (ex.error != TARGET_CLOSE_ERROR)
13285 {
13286 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13287 return -1;
13288 }
13289 throw_exception (ex);
67f41397 13290 }
492d29ea 13291 END_CATCH
00bf0b85 13292
bd3eecc3
PA
13293 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13294
00bf0b85 13295 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13296 if (result == PACKET_UNKNOWN)
00bf0b85 13297 return -1;
35b1e5cc 13298
00bf0b85 13299 /* We're working with a live target. */
f5911ea1 13300 ts->filename = NULL;
00bf0b85 13301
00bf0b85 13302 if (*p++ != 'T')
b6bb3468 13303 error (_("Bogus trace status reply from target: %s"), rs->buf);
35b1e5cc 13304
84cebc4a
YQ
13305 /* Function 'parse_trace_status' sets default value of each field of
13306 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13307 parse_trace_status (p, ts);
13308
13309 return ts->running;
35b1e5cc
SS
13310}
13311
f6ac5f3d
PA
13312void
13313remote_target::get_tracepoint_status (struct breakpoint *bp,
13314 struct uploaded_tp *utp)
f196051f
SS
13315{
13316 struct remote_state *rs = get_remote_state ();
f196051f
SS
13317 char *reply;
13318 struct bp_location *loc;
13319 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 13320 size_t size = get_remote_packet_size ();
f196051f
SS
13321
13322 if (tp)
13323 {
c1fc2657 13324 tp->hit_count = 0;
f196051f 13325 tp->traceframe_usage = 0;
c1fc2657 13326 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
13327 {
13328 /* If the tracepoint was never downloaded, don't go asking for
13329 any status. */
13330 if (tp->number_on_target == 0)
13331 continue;
bba74b36
YQ
13332 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13333 phex_nz (loc->address, 0));
f196051f 13334 putpkt (rs->buf);
b6bb3468 13335 reply = remote_get_noisy_reply ();
f196051f
SS
13336 if (reply && *reply)
13337 {
13338 if (*reply == 'V')
13339 parse_tracepoint_status (reply + 1, bp, utp);
13340 }
13341 }
13342 }
13343 else if (utp)
13344 {
13345 utp->hit_count = 0;
13346 utp->traceframe_usage = 0;
bba74b36
YQ
13347 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13348 phex_nz (utp->addr, 0));
f196051f 13349 putpkt (rs->buf);
b6bb3468 13350 reply = remote_get_noisy_reply ();
f196051f
SS
13351 if (reply && *reply)
13352 {
13353 if (*reply == 'V')
13354 parse_tracepoint_status (reply + 1, bp, utp);
13355 }
13356 }
13357}
13358
f6ac5f3d
PA
13359void
13360remote_target::trace_stop ()
35b1e5cc 13361{
b6bb3468
PA
13362 struct remote_state *rs = get_remote_state ();
13363
35b1e5cc 13364 putpkt ("QTStop");
b6bb3468
PA
13365 remote_get_noisy_reply ();
13366 if (*rs->buf == '\0')
ad91cd99 13367 error (_("Target does not support this command."));
b6bb3468
PA
13368 if (strcmp (rs->buf, "OK") != 0)
13369 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
13370}
13371
f6ac5f3d
PA
13372int
13373remote_target::trace_find (enum trace_find_type type, int num,
13374 CORE_ADDR addr1, CORE_ADDR addr2,
13375 int *tpp)
35b1e5cc
SS
13376{
13377 struct remote_state *rs = get_remote_state ();
bba74b36 13378 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
13379 char *p, *reply;
13380 int target_frameno = -1, target_tracept = -1;
13381
e6e4e701
PA
13382 /* Lookups other than by absolute frame number depend on the current
13383 trace selected, so make sure it is correct on the remote end
13384 first. */
13385 if (type != tfind_number)
13386 set_remote_traceframe ();
13387
35b1e5cc
SS
13388 p = rs->buf;
13389 strcpy (p, "QTFrame:");
13390 p = strchr (p, '\0');
13391 switch (type)
13392 {
13393 case tfind_number:
bba74b36 13394 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13395 break;
13396 case tfind_pc:
bba74b36 13397 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13398 break;
13399 case tfind_tp:
bba74b36 13400 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13401 break;
13402 case tfind_range:
bba74b36
YQ
13403 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13404 phex_nz (addr2, 0));
35b1e5cc
SS
13405 break;
13406 case tfind_outside:
bba74b36
YQ
13407 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13408 phex_nz (addr2, 0));
35b1e5cc
SS
13409 break;
13410 default:
9b20d036 13411 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13412 }
13413
13414 putpkt (rs->buf);
b6bb3468 13415 reply = remote_get_noisy_reply ();
ad91cd99
PA
13416 if (*reply == '\0')
13417 error (_("Target does not support this command."));
35b1e5cc
SS
13418
13419 while (reply && *reply)
13420 switch (*reply)
13421 {
13422 case 'F':
f197e0f1
VP
13423 p = ++reply;
13424 target_frameno = (int) strtol (p, &reply, 16);
13425 if (reply == p)
13426 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13427 /* Don't update our remote traceframe number cache on failure
13428 to select a remote traceframe. */
f197e0f1
VP
13429 if (target_frameno == -1)
13430 return -1;
35b1e5cc
SS
13431 break;
13432 case 'T':
f197e0f1
VP
13433 p = ++reply;
13434 target_tracept = (int) strtol (p, &reply, 16);
13435 if (reply == p)
13436 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13437 break;
13438 case 'O': /* "OK"? */
13439 if (reply[1] == 'K' && reply[2] == '\0')
13440 reply += 2;
13441 else
13442 error (_("Bogus reply from target: %s"), reply);
13443 break;
13444 default:
13445 error (_("Bogus reply from target: %s"), reply);
13446 }
13447 if (tpp)
13448 *tpp = target_tracept;
e6e4e701 13449
262e1174 13450 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13451 return target_frameno;
13452}
13453
57810aa7 13454bool
f6ac5f3d 13455remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13456{
13457 struct remote_state *rs = get_remote_state ();
13458 char *reply;
13459 ULONGEST uval;
13460
e6e4e701
PA
13461 set_remote_traceframe ();
13462
bba74b36 13463 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13464 putpkt (rs->buf);
b6bb3468 13465 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13466 if (reply && *reply)
13467 {
13468 if (*reply == 'V')
13469 {
13470 unpack_varlen_hex (reply + 1, &uval);
13471 *val = (LONGEST) uval;
57810aa7 13472 return true;
35b1e5cc
SS
13473 }
13474 }
57810aa7 13475 return false;
35b1e5cc
SS
13476}
13477
f6ac5f3d
PA
13478int
13479remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13480{
13481 struct remote_state *rs = get_remote_state ();
13482 char *p, *reply;
13483
13484 p = rs->buf;
13485 strcpy (p, "QTSave:");
13486 p += strlen (p);
13487 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13488 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13489 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13490 *p++ = '\0';
13491 putpkt (rs->buf);
b6bb3468 13492 reply = remote_get_noisy_reply ();
d6c5869f 13493 if (*reply == '\0')
ad91cd99
PA
13494 error (_("Target does not support this command."));
13495 if (strcmp (reply, "OK") != 0)
13496 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13497 return 0;
13498}
13499
13500/* This is basically a memory transfer, but needs to be its own packet
13501 because we don't know how the target actually organizes its trace
13502 memory, plus we want to be able to ask for as much as possible, but
13503 not be unhappy if we don't get as much as we ask for. */
13504
f6ac5f3d
PA
13505LONGEST
13506remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13507{
13508 struct remote_state *rs = get_remote_state ();
13509 char *reply;
13510 char *p;
13511 int rslt;
13512
13513 p = rs->buf;
13514 strcpy (p, "qTBuffer:");
13515 p += strlen (p);
13516 p += hexnumstr (p, offset);
13517 *p++ = ',';
13518 p += hexnumstr (p, len);
13519 *p++ = '\0';
13520
13521 putpkt (rs->buf);
b6bb3468 13522 reply = remote_get_noisy_reply ();
00bf0b85
SS
13523 if (reply && *reply)
13524 {
13525 /* 'l' by itself means we're at the end of the buffer and
13526 there is nothing more to get. */
13527 if (*reply == 'l')
13528 return 0;
13529
13530 /* Convert the reply into binary. Limit the number of bytes to
13531 convert according to our passed-in buffer size, rather than
13532 what was returned in the packet; if the target is
13533 unexpectedly generous and gives us a bigger reply than we
13534 asked for, we don't want to crash. */
b6bb3468 13535 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13536 return rslt;
13537 }
13538
13539 /* Something went wrong, flag as an error. */
13540 return -1;
13541}
13542
f6ac5f3d
PA
13543void
13544remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13545{
13546 struct remote_state *rs = get_remote_state ();
13547
4082afcc 13548 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 13549 {
ad91cd99
PA
13550 char *reply;
13551
bba74b36 13552 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 13553 putpkt (rs->buf);
b6bb3468 13554 reply = remote_get_noisy_reply ();
ad91cd99 13555 if (*reply == '\0')
33da3f1c 13556 error (_("Target does not support this command."));
ad91cd99
PA
13557 if (strcmp (reply, "OK") != 0)
13558 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13559 }
13560 else if (val)
13561 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13562}
13563
f6ac5f3d
PA
13564int
13565remote_target::core_of_thread (ptid_t ptid)
dc146f7c
VP
13566{
13567 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 13568
7aabaf9d
SM
13569 if (info != NULL && info->priv != NULL)
13570 return get_remote_thread_info (info)->core;
13571
dc146f7c
VP
13572 return -1;
13573}
13574
f6ac5f3d
PA
13575void
13576remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13577{
13578 struct remote_state *rs = get_remote_state ();
ad91cd99 13579 char *reply;
4daf5ac0 13580
bba74b36 13581 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 13582 putpkt (rs->buf);
b6bb3468 13583 reply = remote_get_noisy_reply ();
ad91cd99 13584 if (*reply == '\0')
4daf5ac0 13585 error (_("Target does not support this command."));
ad91cd99
PA
13586 if (strcmp (reply, "OK") != 0)
13587 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13588}
13589
f6ac5f3d
PA
13590traceframe_info_up
13591remote_target::traceframe_info ()
b3b9301e 13592{
9018be22 13593 gdb::optional<gdb::char_vector> text
f6ac5f3d 13594 = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13595 NULL);
9018be22
SM
13596 if (text)
13597 return parse_traceframe_info (text->data ());
b3b9301e
PA
13598
13599 return NULL;
13600}
13601
405f8e94
SS
13602/* Handle the qTMinFTPILen packet. Returns the minimum length of
13603 instruction on which a fast tracepoint may be placed. Returns -1
13604 if the packet is not supported, and 0 if the minimum instruction
13605 length is unknown. */
13606
f6ac5f3d
PA
13607int
13608remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13609{
13610 struct remote_state *rs = get_remote_state ();
13611 char *reply;
13612
e886a173
PA
13613 /* If we're not debugging a process yet, the IPA can't be
13614 loaded. */
13615 if (!target_has_execution)
13616 return 0;
13617
13618 /* Make sure the remote is pointing at the right process. */
13619 set_general_process ();
13620
bba74b36 13621 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13622 putpkt (rs->buf);
b6bb3468 13623 reply = remote_get_noisy_reply ();
405f8e94
SS
13624 if (*reply == '\0')
13625 return -1;
13626 else
13627 {
13628 ULONGEST min_insn_len;
13629
13630 unpack_varlen_hex (reply, &min_insn_len);
13631
13632 return (int) min_insn_len;
13633 }
13634}
13635
f6ac5f3d
PA
13636void
13637remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13638{
4082afcc 13639 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13640 {
13641 struct remote_state *rs = get_remote_state ();
13642 char *buf = rs->buf;
13643 char *endbuf = rs->buf + get_remote_packet_size ();
13644 enum packet_result result;
13645
13646 gdb_assert (val >= 0 || val == -1);
13647 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13648 /* Send -1 as literal "-1" to avoid host size dependency. */
13649 if (val < 0)
13650 {
13651 *buf++ = '-';
13652 buf += hexnumstr (buf, (ULONGEST) -val);
13653 }
13654 else
13655 buf += hexnumstr (buf, (ULONGEST) val);
13656
13657 putpkt (rs->buf);
b6bb3468 13658 remote_get_noisy_reply ();
f6f899bf
HAQ
13659 result = packet_ok (rs->buf,
13660 &remote_protocol_packets[PACKET_QTBuffer_size]);
13661
13662 if (result != PACKET_OK)
13663 warning (_("Bogus reply from target: %s"), rs->buf);
13664 }
13665}
13666
57810aa7 13667bool
f6ac5f3d
PA
13668remote_target::set_trace_notes (const char *user, const char *notes,
13669 const char *stop_notes)
f196051f
SS
13670{
13671 struct remote_state *rs = get_remote_state ();
13672 char *reply;
13673 char *buf = rs->buf;
13674 char *endbuf = rs->buf + get_remote_packet_size ();
13675 int nbytes;
13676
13677 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13678 if (user)
13679 {
13680 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13681 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13682 buf += 2 * nbytes;
13683 *buf++ = ';';
13684 }
13685 if (notes)
13686 {
13687 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13688 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13689 buf += 2 * nbytes;
13690 *buf++ = ';';
13691 }
13692 if (stop_notes)
13693 {
13694 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13695 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13696 buf += 2 * nbytes;
13697 *buf++ = ';';
13698 }
13699 /* Ensure the buffer is terminated. */
13700 *buf = '\0';
13701
13702 putpkt (rs->buf);
b6bb3468 13703 reply = remote_get_noisy_reply ();
f196051f 13704 if (*reply == '\0')
57810aa7 13705 return false;
f196051f
SS
13706
13707 if (strcmp (reply, "OK") != 0)
13708 error (_("Bogus reply from target: %s"), reply);
13709
57810aa7 13710 return true;
f196051f
SS
13711}
13712
57810aa7
PA
13713bool
13714remote_target::use_agent (bool use)
d1feda86 13715{
4082afcc 13716 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13717 {
13718 struct remote_state *rs = get_remote_state ();
13719
13720 /* If the stub supports QAgent. */
bba74b36 13721 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
13722 putpkt (rs->buf);
13723 getpkt (&rs->buf, &rs->buf_size, 0);
13724
13725 if (strcmp (rs->buf, "OK") == 0)
13726 {
f6ac5f3d 13727 ::use_agent = use;
57810aa7 13728 return true;
d1feda86
YQ
13729 }
13730 }
13731
57810aa7 13732 return false;
d1feda86
YQ
13733}
13734
57810aa7 13735bool
f6ac5f3d 13736remote_target::can_use_agent ()
d1feda86 13737{
4082afcc 13738 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13739}
13740
9accd112
MM
13741struct btrace_target_info
13742{
13743 /* The ptid of the traced thread. */
13744 ptid_t ptid;
f4abbc16
MM
13745
13746 /* The obtained branch trace configuration. */
13747 struct btrace_config conf;
9accd112
MM
13748};
13749
f4abbc16
MM
13750/* Reset our idea of our target's btrace configuration. */
13751
13752static void
6b8edb51 13753remote_btrace_reset (remote_state *rs)
f4abbc16 13754{
f4abbc16
MM
13755 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13756}
13757
f4abbc16
MM
13758/* Synchronize the configuration with the target. */
13759
6b8edb51
PA
13760void
13761remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 13762{
d33501a5
MM
13763 struct packet_config *packet;
13764 struct remote_state *rs;
13765 char *buf, *pos, *endbuf;
13766
13767 rs = get_remote_state ();
13768 buf = rs->buf;
13769 endbuf = buf + get_remote_packet_size ();
13770
13771 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13772 if (packet_config_support (packet) == PACKET_ENABLE
13773 && conf->bts.size != rs->btrace_config.bts.size)
13774 {
13775 pos = buf;
13776 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13777 conf->bts.size);
13778
13779 putpkt (buf);
13780 getpkt (&buf, &rs->buf_size, 0);
13781
13782 if (packet_ok (buf, packet) == PACKET_ERROR)
13783 {
13784 if (buf[0] == 'E' && buf[1] == '.')
13785 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13786 else
13787 error (_("Failed to configure the BTS buffer size."));
13788 }
13789
13790 rs->btrace_config.bts.size = conf->bts.size;
13791 }
b20a6524
MM
13792
13793 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13794 if (packet_config_support (packet) == PACKET_ENABLE
13795 && conf->pt.size != rs->btrace_config.pt.size)
13796 {
13797 pos = buf;
13798 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13799 conf->pt.size);
13800
13801 putpkt (buf);
13802 getpkt (&buf, &rs->buf_size, 0);
13803
13804 if (packet_ok (buf, packet) == PACKET_ERROR)
13805 {
13806 if (buf[0] == 'E' && buf[1] == '.')
13807 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13808 else
13809 error (_("Failed to configure the trace buffer size."));
13810 }
13811
13812 rs->btrace_config.pt.size = conf->pt.size;
13813 }
f4abbc16
MM
13814}
13815
13816/* Read the current thread's btrace configuration from the target and
13817 store it into CONF. */
13818
13819static void
13820btrace_read_config (struct btrace_config *conf)
13821{
9018be22 13822 gdb::optional<gdb::char_vector> xml
f6ac5f3d 13823 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
13824 if (xml)
13825 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
13826}
13827
c0272db5
TW
13828/* Maybe reopen target btrace. */
13829
6b8edb51
PA
13830void
13831remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
13832{
13833 struct remote_state *rs = get_remote_state ();
c0272db5
TW
13834 struct thread_info *tp;
13835 int btrace_target_pushed = 0;
13836 int warned = 0;
13837
5ed8105e
PA
13838 scoped_restore_current_thread restore_thread;
13839
c0272db5
TW
13840 ALL_NON_EXITED_THREADS (tp)
13841 {
13842 set_general_thread (tp->ptid);
13843
13844 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13845 btrace_read_config (&rs->btrace_config);
13846
13847 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13848 continue;
13849
13850#if !defined (HAVE_LIBIPT)
13851 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13852 {
13853 if (!warned)
13854 {
13855 warned = 1;
c4e12631
MM
13856 warning (_("Target is recording using Intel Processor Trace "
13857 "but support was disabled at compile time."));
c0272db5
TW
13858 }
13859
13860 continue;
13861 }
13862#endif /* !defined (HAVE_LIBIPT) */
13863
13864 /* Push target, once, but before anything else happens. This way our
13865 changes to the threads will be cleaned up by unpushing the target
13866 in case btrace_read_config () throws. */
13867 if (!btrace_target_pushed)
13868 {
13869 btrace_target_pushed = 1;
13870 record_btrace_push_target ();
13871 printf_filtered (_("Target is recording using %s.\n"),
13872 btrace_format_string (rs->btrace_config.format));
13873 }
13874
13875 tp->btrace.target = XCNEW (struct btrace_target_info);
13876 tp->btrace.target->ptid = tp->ptid;
13877 tp->btrace.target->conf = rs->btrace_config;
13878 }
c0272db5
TW
13879}
13880
9accd112
MM
13881/* Enable branch tracing. */
13882
f6ac5f3d
PA
13883struct btrace_target_info *
13884remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
9accd112
MM
13885{
13886 struct btrace_target_info *tinfo = NULL;
b20a6524 13887 struct packet_config *packet = NULL;
9accd112
MM
13888 struct remote_state *rs = get_remote_state ();
13889 char *buf = rs->buf;
13890 char *endbuf = rs->buf + get_remote_packet_size ();
13891
b20a6524
MM
13892 switch (conf->format)
13893 {
13894 case BTRACE_FORMAT_BTS:
13895 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13896 break;
13897
13898 case BTRACE_FORMAT_PT:
13899 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13900 break;
13901 }
13902
13903 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13904 error (_("Target does not support branch tracing."));
13905
f4abbc16
MM
13906 btrace_sync_conf (conf);
13907
9accd112
MM
13908 set_general_thread (ptid);
13909
13910 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13911 putpkt (rs->buf);
13912 getpkt (&rs->buf, &rs->buf_size, 0);
13913
13914 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13915 {
13916 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13917 error (_("Could not enable branch tracing for %s: %s"),
13918 target_pid_to_str (ptid), rs->buf + 2);
13919 else
13920 error (_("Could not enable branch tracing for %s."),
13921 target_pid_to_str (ptid));
13922 }
13923
8d749320 13924 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13925 tinfo->ptid = ptid;
13926
f4abbc16
MM
13927 /* If we fail to read the configuration, we lose some information, but the
13928 tracing itself is not impacted. */
492d29ea
PA
13929 TRY
13930 {
13931 btrace_read_config (&tinfo->conf);
13932 }
13933 CATCH (err, RETURN_MASK_ERROR)
13934 {
13935 if (err.message != NULL)
13936 warning ("%s", err.message);
13937 }
13938 END_CATCH
f4abbc16 13939
9accd112
MM
13940 return tinfo;
13941}
13942
13943/* Disable branch tracing. */
13944
f6ac5f3d
PA
13945void
13946remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13947{
13948 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13949 struct remote_state *rs = get_remote_state ();
13950 char *buf = rs->buf;
13951 char *endbuf = rs->buf + get_remote_packet_size ();
13952
4082afcc 13953 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13954 error (_("Target does not support branch tracing."));
13955
13956 set_general_thread (tinfo->ptid);
13957
13958 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13959 putpkt (rs->buf);
13960 getpkt (&rs->buf, &rs->buf_size, 0);
13961
13962 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13963 {
13964 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13965 error (_("Could not disable branch tracing for %s: %s"),
13966 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13967 else
13968 error (_("Could not disable branch tracing for %s."),
13969 target_pid_to_str (tinfo->ptid));
13970 }
13971
13972 xfree (tinfo);
13973}
13974
13975/* Teardown branch tracing. */
13976
f6ac5f3d
PA
13977void
13978remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13979{
13980 /* We must not talk to the target during teardown. */
13981 xfree (tinfo);
13982}
13983
13984/* Read the branch trace. */
13985
f6ac5f3d
PA
13986enum btrace_error
13987remote_target::read_btrace (struct btrace_data *btrace,
13988 struct btrace_target_info *tinfo,
13989 enum btrace_read_type type)
9accd112
MM
13990{
13991 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 13992 const char *annex;
9accd112 13993
4082afcc 13994 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13995 error (_("Target does not support branch tracing."));
13996
13997#if !defined(HAVE_LIBEXPAT)
13998 error (_("Cannot process branch tracing result. XML parsing not supported."));
13999#endif
14000
14001 switch (type)
14002 {
864089d2 14003 case BTRACE_READ_ALL:
9accd112
MM
14004 annex = "all";
14005 break;
864089d2 14006 case BTRACE_READ_NEW:
9accd112
MM
14007 annex = "new";
14008 break;
969c39fb
MM
14009 case BTRACE_READ_DELTA:
14010 annex = "delta";
14011 break;
9accd112
MM
14012 default:
14013 internal_error (__FILE__, __LINE__,
14014 _("Bad branch tracing read type: %u."),
14015 (unsigned int) type);
14016 }
14017
9018be22 14018 gdb::optional<gdb::char_vector> xml
f6ac5f3d 14019 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
9018be22 14020 if (!xml)
969c39fb 14021 return BTRACE_ERR_UNKNOWN;
9accd112 14022
9018be22 14023 parse_xml_btrace (btrace, xml->data ());
9accd112 14024
969c39fb 14025 return BTRACE_ERR_NONE;
9accd112
MM
14026}
14027
f6ac5f3d
PA
14028const struct btrace_config *
14029remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
14030{
14031 return &tinfo->conf;
14032}
14033
57810aa7 14034bool
f6ac5f3d 14035remote_target::augmented_libraries_svr4_read ()
ced63ec0 14036{
4082afcc
PA
14037 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14038 == PACKET_ENABLE);
ced63ec0
GB
14039}
14040
9dd130a0
TT
14041/* Implementation of to_load. */
14042
f6ac5f3d
PA
14043void
14044remote_target::load (const char *name, int from_tty)
9dd130a0
TT
14045{
14046 generic_load (name, from_tty);
14047}
14048
c78fa86a
GB
14049/* Accepts an integer PID; returns a string representing a file that
14050 can be opened on the remote side to get the symbols for the child
14051 process. Returns NULL if the operation is not supported. */
14052
f6ac5f3d
PA
14053char *
14054remote_target::pid_to_exec_file (int pid)
c78fa86a 14055{
9018be22 14056 static gdb::optional<gdb::char_vector> filename;
835205d0
GB
14057 struct inferior *inf;
14058 char *annex = NULL;
c78fa86a
GB
14059
14060 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14061 return NULL;
14062
835205d0
GB
14063 inf = find_inferior_pid (pid);
14064 if (inf == NULL)
14065 internal_error (__FILE__, __LINE__,
14066 _("not currently attached to process %d"), pid);
14067
14068 if (!inf->fake_pid_p)
14069 {
14070 const int annex_size = 9;
14071
224c3ddb 14072 annex = (char *) alloca (annex_size);
835205d0
GB
14073 xsnprintf (annex, annex_size, "%x", pid);
14074 }
14075
f6ac5f3d 14076 filename = target_read_stralloc (target_stack,
c78fa86a
GB
14077 TARGET_OBJECT_EXEC_FILE, annex);
14078
9018be22 14079 return filename ? filename->data () : nullptr;
c78fa86a
GB
14080}
14081
750ce8d1
YQ
14082/* Implement the to_can_do_single_step target_ops method. */
14083
f6ac5f3d
PA
14084int
14085remote_target::can_do_single_step ()
750ce8d1
YQ
14086{
14087 /* We can only tell whether target supports single step or not by
14088 supported s and S vCont actions if the stub supports vContSupported
14089 feature. If the stub doesn't support vContSupported feature,
14090 we have conservatively to think target doesn't supports single
14091 step. */
14092 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14093 {
14094 struct remote_state *rs = get_remote_state ();
14095
14096 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 14097 remote_vcont_probe ();
750ce8d1
YQ
14098
14099 return rs->supports_vCont.s && rs->supports_vCont.S;
14100 }
14101 else
14102 return 0;
14103}
14104
3a00c802
PA
14105/* Implementation of the to_execution_direction method for the remote
14106 target. */
14107
f6ac5f3d
PA
14108enum exec_direction_kind
14109remote_target::execution_direction ()
3a00c802
PA
14110{
14111 struct remote_state *rs = get_remote_state ();
14112
14113 return rs->last_resume_exec_dir;
14114}
14115
f6327dcb
KB
14116/* Return pointer to the thread_info struct which corresponds to
14117 THREAD_HANDLE (having length HANDLE_LEN). */
14118
f6ac5f3d
PA
14119thread_info *
14120remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14121 int handle_len,
14122 inferior *inf)
f6327dcb
KB
14123{
14124 struct thread_info *tp;
14125
14126 ALL_NON_EXITED_THREADS (tp)
14127 {
7aabaf9d 14128 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
14129
14130 if (tp->inf == inf && priv != NULL)
14131 {
7aabaf9d 14132 if (handle_len != priv->thread_handle.size ())
f6327dcb 14133 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
7aabaf9d
SM
14134 handle_len, priv->thread_handle.size ());
14135 if (memcmp (thread_handle, priv->thread_handle.data (),
f6327dcb
KB
14136 handle_len) == 0)
14137 return tp;
14138 }
14139 }
14140
14141 return NULL;
14142}
14143
57810aa7 14144bool
f6ac5f3d 14145remote_target::can_async_p ()
6426a772 14146{
5d93a237
TT
14147 struct remote_state *rs = get_remote_state ();
14148
3015c064
SM
14149 /* We don't go async if the user has explicitly prevented it with the
14150 "maint set target-async" command. */
c6ebd6cf 14151 if (!target_async_permitted)
57810aa7 14152 return false;
75c99385 14153
23860348 14154 /* We're async whenever the serial device is. */
5d93a237 14155 return serial_can_async_p (rs->remote_desc);
6426a772
JM
14156}
14157
57810aa7 14158bool
f6ac5f3d 14159remote_target::is_async_p ()
6426a772 14160{
5d93a237
TT
14161 struct remote_state *rs = get_remote_state ();
14162
c6ebd6cf 14163 if (!target_async_permitted)
75c99385 14164 /* We only enable async when the user specifically asks for it. */
57810aa7 14165 return false;
75c99385 14166
23860348 14167 /* We're async whenever the serial device is. */
5d93a237 14168 return serial_is_async_p (rs->remote_desc);
6426a772
JM
14169}
14170
2acceee2
JM
14171/* Pass the SERIAL event on and up to the client. One day this code
14172 will be able to delay notifying the client of an event until the
23860348 14173 point where an entire packet has been received. */
2acceee2 14174
2acceee2
JM
14175static serial_event_ftype remote_async_serial_handler;
14176
6426a772 14177static void
819cc324 14178remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14179{
2acceee2
JM
14180 /* Don't propogate error information up to the client. Instead let
14181 the client find out about the error by querying the target. */
6a3753b3 14182 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
14183}
14184
74531fed
PA
14185static void
14186remote_async_inferior_event_handler (gdb_client_data data)
14187{
6b8edb51 14188 inferior_event_handler (INF_REG_EVENT, data);
74531fed
PA
14189}
14190
f6ac5f3d
PA
14191void
14192remote_target::async (int enable)
2acceee2 14193{
5d93a237
TT
14194 struct remote_state *rs = get_remote_state ();
14195
6a3753b3 14196 if (enable)
2acceee2 14197 {
88b496c3 14198 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14199
14200 /* If there are pending events in the stop reply queue tell the
14201 event loop to process them. */
6b8edb51
PA
14202 if (!QUEUE_is_empty (stop_reply_p, rs->stop_reply_queue))
14203 mark_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14204 /* For simplicity, below we clear the pending events token
14205 without remembering whether it is marked, so here we always
14206 mark it. If there's actually no pending notification to
14207 process, this ends up being a no-op (other than a spurious
14208 event-loop wakeup). */
14209 if (target_is_non_stop_p ())
14210 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14211 }
14212 else
b7d2e916
PA
14213 {
14214 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14215 /* If the core is disabling async, it doesn't want to be
14216 disturbed with target events. Clear all async event sources
14217 too. */
6b8edb51 14218 clear_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14219 if (target_is_non_stop_p ())
14220 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14221 }
6426a772
JM
14222}
14223
65706a29
PA
14224/* Implementation of the to_thread_events method. */
14225
f6ac5f3d
PA
14226void
14227remote_target::thread_events (int enable)
65706a29
PA
14228{
14229 struct remote_state *rs = get_remote_state ();
14230 size_t size = get_remote_packet_size ();
65706a29
PA
14231
14232 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14233 return;
14234
14235 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14236 putpkt (rs->buf);
14237 getpkt (&rs->buf, &rs->buf_size, 0);
14238
14239 switch (packet_ok (rs->buf,
14240 &remote_protocol_packets[PACKET_QThreadEvents]))
14241 {
14242 case PACKET_OK:
14243 if (strcmp (rs->buf, "OK") != 0)
14244 error (_("Remote refused setting thread events: %s"), rs->buf);
14245 break;
14246 case PACKET_ERROR:
14247 warning (_("Remote failure reply: %s"), rs->buf);
14248 break;
14249 case PACKET_UNKNOWN:
14250 break;
14251 }
14252}
14253
5a2468f5 14254static void
981a3fb3 14255set_remote_cmd (const char *args, int from_tty)
5a2468f5 14256{
635c7e8a 14257 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
14258}
14259
d471ea57 14260static void
981a3fb3 14261show_remote_cmd (const char *args, int from_tty)
d471ea57 14262{
37a105a1 14263 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14264 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14265 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14266 struct ui_out *uiout = current_uiout;
37a105a1 14267
2e783024 14268 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14269 for (; list != NULL; list = list->next)
14270 if (strcmp (list->name, "Z-packet") == 0)
14271 continue;
427c3a89
DJ
14272 else if (list->type == not_set_cmd)
14273 /* Alias commands are exactly like the original, except they
14274 don't have the normal type. */
14275 continue;
14276 else
37a105a1 14277 {
2e783024 14278 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14279
112e8700
SM
14280 uiout->field_string ("name", list->name);
14281 uiout->text (": ");
427c3a89 14282 if (list->type == show_cmd)
f5c4fcd9 14283 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14284 else
14285 cmd_func (list, NULL, from_tty);
37a105a1 14286 }
d471ea57 14287}
5a2468f5 14288
0f71a2f6 14289
23860348 14290/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
14291static void
14292remote_new_objfile (struct objfile *objfile)
14293{
6b8edb51 14294 remote_target *remote = get_current_remote_target ();
5d93a237 14295
6b8edb51
PA
14296 if (remote != NULL) /* Have a remote connection. */
14297 remote->remote_check_symbols ();
dc8acb97
MS
14298}
14299
00bf0b85
SS
14300/* Pull all the tracepoints defined on the target and create local
14301 data structures representing them. We don't want to create real
14302 tracepoints yet, we don't want to mess up the user's existing
14303 collection. */
14304
f6ac5f3d
PA
14305int
14306remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 14307{
00bf0b85
SS
14308 struct remote_state *rs = get_remote_state ();
14309 char *p;
d5551862 14310
00bf0b85
SS
14311 /* Ask for a first packet of tracepoint definition. */
14312 putpkt ("qTfP");
14313 getpkt (&rs->buf, &rs->buf_size, 0);
14314 p = rs->buf;
14315 while (*p && *p != 'l')
d5551862 14316 {
00bf0b85
SS
14317 parse_tracepoint_definition (p, utpp);
14318 /* Ask for another packet of tracepoint definition. */
14319 putpkt ("qTsP");
14320 getpkt (&rs->buf, &rs->buf_size, 0);
14321 p = rs->buf;
d5551862 14322 }
00bf0b85 14323 return 0;
d5551862
SS
14324}
14325
f6ac5f3d
PA
14326int
14327remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 14328{
00bf0b85 14329 struct remote_state *rs = get_remote_state ();
d5551862 14330 char *p;
d5551862 14331
00bf0b85
SS
14332 /* Ask for a first packet of variable definition. */
14333 putpkt ("qTfV");
d5551862
SS
14334 getpkt (&rs->buf, &rs->buf_size, 0);
14335 p = rs->buf;
00bf0b85 14336 while (*p && *p != 'l')
d5551862 14337 {
00bf0b85
SS
14338 parse_tsv_definition (p, utsvp);
14339 /* Ask for another packet of variable definition. */
14340 putpkt ("qTsV");
d5551862
SS
14341 getpkt (&rs->buf, &rs->buf_size, 0);
14342 p = rs->buf;
14343 }
00bf0b85 14344 return 0;
d5551862
SS
14345}
14346
c1e36e3e
PA
14347/* The "set/show range-stepping" show hook. */
14348
14349static void
14350show_range_stepping (struct ui_file *file, int from_tty,
14351 struct cmd_list_element *c,
14352 const char *value)
14353{
14354 fprintf_filtered (file,
14355 _("Debugger's willingness to use range stepping "
14356 "is %s.\n"), value);
14357}
14358
6b8edb51
PA
14359/* Return true if the vCont;r action is supported by the remote
14360 stub. */
14361
14362bool
14363remote_target::vcont_r_supported ()
14364{
14365 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14366 remote_vcont_probe ();
14367
14368 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14369 && get_remote_state ()->supports_vCont.r);
14370}
14371
c1e36e3e
PA
14372/* The "set/show range-stepping" set hook. */
14373
14374static void
eb4c3f4a 14375set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
14376 struct cmd_list_element *c)
14377{
6b8edb51
PA
14378 /* When enabling, check whether range stepping is actually supported
14379 by the target, and warn if not. */
c1e36e3e
PA
14380 if (use_range_stepping)
14381 {
6b8edb51
PA
14382 remote_target *remote = get_current_remote_target ();
14383 if (remote == NULL
14384 || !remote->vcont_r_supported ())
14385 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
14386 }
14387}
14388
c906108c 14389void
fba45db2 14390_initialize_remote (void)
c906108c 14391{
9a7071a8 14392 struct cmd_list_element *cmd;
6f937416 14393 const char *cmd_name;
ea9c271d 14394
0f71a2f6 14395 /* architecture specific data */
29709017
DJ
14396 remote_g_packet_data_handle =
14397 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14398
94585166
DB
14399 remote_pspace_data
14400 = register_program_space_data_with_cleanup (NULL,
14401 remote_pspace_data_cleanup);
14402
d9f719f1
PA
14403 add_target (remote_target_info, remote_target::open);
14404 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 14405
dc8acb97 14406 /* Hook into new objfile notification. */
76727919 14407 gdb::observers::new_objfile.attach (remote_new_objfile);
dc8acb97 14408
c906108c
SS
14409#if 0
14410 init_remote_threadtests ();
14411#endif
14412
23860348 14413 /* set/show remote ... */
d471ea57 14414
1bedd215 14415 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
14416Remote protocol specific variables\n\
14417Configure various remote-protocol specific variables such as\n\
1bedd215 14418the packets being used"),
cff3e48b 14419 &remote_set_cmdlist, "set remote ",
23860348 14420 0 /* allow-unknown */, &setlist);
1bedd215 14421 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
14422Remote protocol specific variables\n\
14423Configure various remote-protocol specific variables such as\n\
1bedd215 14424the packets being used"),
cff3e48b 14425 &remote_show_cmdlist, "show remote ",
23860348 14426 0 /* allow-unknown */, &showlist);
5a2468f5 14427
1a966eab
AC
14428 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14429Compare section data on target to the exec file.\n\
95cf3b38
DT
14430Argument is a single section name (default: all loaded sections).\n\
14431To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14432 &cmdlist);
14433
1a966eab
AC
14434 add_cmd ("packet", class_maintenance, packet_command, _("\
14435Send an arbitrary packet to a remote target.\n\
c906108c
SS
14436 maintenance packet TEXT\n\
14437If GDB is talking to an inferior via the GDB serial protocol, then\n\
14438this command sends the string TEXT to the inferior, and displays the\n\
14439response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14440terminating `#' character and checksum."),
c906108c
SS
14441 &maintenancelist);
14442
7915a72c
AC
14443 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14444Set whether to send break if interrupted."), _("\
14445Show whether to send break if interrupted."), _("\
14446If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14447 set_remotebreak, show_remotebreak,
e707bbc2 14448 &setlist, &showlist);
9a7071a8
JB
14449 cmd_name = "remotebreak";
14450 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14451 deprecate_cmd (cmd, "set remote interrupt-sequence");
14452 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14453 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14454 deprecate_cmd (cmd, "show remote interrupt-sequence");
14455
14456 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14457 interrupt_sequence_modes, &interrupt_sequence_mode,
14458 _("\
9a7071a8
JB
14459Set interrupt sequence to remote target."), _("\
14460Show interrupt sequence to remote target."), _("\
14461Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14462 NULL, show_interrupt_sequence,
14463 &remote_set_cmdlist,
14464 &remote_show_cmdlist);
14465
14466 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14467 &interrupt_on_connect, _("\
14468Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14469Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14470If set, interrupt sequence is sent to remote target."),
14471 NULL, NULL,
14472 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14473
23860348 14474 /* Install commands for configuring memory read/write packets. */
11cf8741 14475
1a966eab
AC
14476 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14477Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14478 &setlist);
1a966eab
AC
14479 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14480Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14481 &showlist);
14482 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14483 set_memory_write_packet_size, _("\
14484Set the maximum number of bytes per memory-write packet.\n\
14485Specify the number of bytes in a packet or 0 (zero) for the\n\
14486default packet size. The actual limit is further reduced\n\
14487dependent on the target. Specify ``fixed'' to disable the\n\
14488further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14489 &remote_set_cmdlist);
14490 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14491 set_memory_read_packet_size, _("\
14492Set the maximum number of bytes per memory-read packet.\n\
14493Specify the number of bytes in a packet or 0 (zero) for the\n\
14494default packet size. The actual limit is further reduced\n\
14495dependent on the target. Specify ``fixed'' to disable the\n\
14496further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14497 &remote_set_cmdlist);
14498 add_cmd ("memory-write-packet-size", no_class,
14499 show_memory_write_packet_size,
1a966eab 14500 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14501 &remote_show_cmdlist);
14502 add_cmd ("memory-read-packet-size", no_class,
14503 show_memory_read_packet_size,
1a966eab 14504 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14505 &remote_show_cmdlist);
c906108c 14506
b3f42336 14507 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14508 &remote_hw_watchpoint_limit, _("\
14509Set the maximum number of target hardware watchpoints."), _("\
14510Show the maximum number of target hardware watchpoints."), _("\
14511Specify a negative limit for unlimited."),
3e43a32a
MS
14512 NULL, NULL, /* FIXME: i18n: The maximum
14513 number of target hardware
14514 watchpoints is %s. */
b3f42336 14515 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
14516 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14517 &remote_hw_watchpoint_length_limit, _("\
14518Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14519Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14520Specify a negative limit for unlimited."),
14521 NULL, NULL, /* FIXME: i18n: The maximum
14522 length (in bytes) of a target
14523 hardware watchpoint is %s. */
14524 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 14525 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14526 &remote_hw_breakpoint_limit, _("\
14527Set the maximum number of target hardware breakpoints."), _("\
14528Show the maximum number of target hardware breakpoints."), _("\
14529Specify a negative limit for unlimited."),
3e43a32a
MS
14530 NULL, NULL, /* FIXME: i18n: The maximum
14531 number of target hardware
14532 breakpoints is %s. */
b3f42336 14533 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14534
1b493192
PA
14535 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14536 &remote_address_size, _("\
4d28ad1e
AC
14537Set the maximum size of the address (in bits) in a memory packet."), _("\
14538Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14539 NULL,
14540 NULL, /* FIXME: i18n: */
14541 &setlist, &showlist);
c906108c 14542
ca4f7f8b
PA
14543 init_all_packet_configs ();
14544
444abaca 14545 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14546 "X", "binary-download", 1);
0f71a2f6 14547
444abaca 14548 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14549 "vCont", "verbose-resume", 0);
506fb367 14550
89be2091
DJ
14551 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14552 "QPassSignals", "pass-signals", 0);
14553
82075af2
JS
14554 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14555 "QCatchSyscalls", "catch-syscalls", 0);
14556
9b224c5e
PA
14557 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14558 "QProgramSignals", "program-signals", 0);
14559
bc3b087d
SDJ
14560 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14561 "QSetWorkingDir", "set-working-dir", 0);
14562
aefd8b33
SDJ
14563 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14564 "QStartupWithShell", "startup-with-shell", 0);
14565
0a2dde4a
SDJ
14566 add_packet_config_cmd (&remote_protocol_packets
14567 [PACKET_QEnvironmentHexEncoded],
14568 "QEnvironmentHexEncoded", "environment-hex-encoded",
14569 0);
14570
14571 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14572 "QEnvironmentReset", "environment-reset",
14573 0);
14574
14575 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14576 "QEnvironmentUnset", "environment-unset",
14577 0);
14578
444abaca 14579 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14580 "qSymbol", "symbol-lookup", 0);
dc8acb97 14581
444abaca 14582 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14583 "P", "set-register", 1);
d471ea57 14584
444abaca 14585 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14586 "p", "fetch-register", 1);
b96ec7ac 14587
444abaca 14588 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14589 "Z0", "software-breakpoint", 0);
d471ea57 14590
444abaca 14591 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14592 "Z1", "hardware-breakpoint", 0);
d471ea57 14593
444abaca 14594 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14595 "Z2", "write-watchpoint", 0);
d471ea57 14596
444abaca 14597 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14598 "Z3", "read-watchpoint", 0);
d471ea57 14599
444abaca 14600 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14601 "Z4", "access-watchpoint", 0);
d471ea57 14602
0876f84a
DJ
14603 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14604 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14605
c78fa86a
GB
14606 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14607 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14608
23181151
DJ
14609 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14610 "qXfer:features:read", "target-features", 0);
14611
cfa9d6d9
DJ
14612 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14613 "qXfer:libraries:read", "library-info", 0);
14614
2268b414
JK
14615 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14616 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14617
fd79ecee
DJ
14618 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14619 "qXfer:memory-map:read", "memory-map", 0);
14620
0e7f50da
UW
14621 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14622 "qXfer:spu:read", "read-spu-object", 0);
14623
14624 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14625 "qXfer:spu:write", "write-spu-object", 0);
14626
07e059b5
VP
14627 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14628 "qXfer:osdata:read", "osdata", 0);
14629
dc146f7c
VP
14630 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14631 "qXfer:threads:read", "threads", 0);
14632
4aa995e1
PA
14633 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14634 "qXfer:siginfo:read", "read-siginfo-object", 0);
14635
14636 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14637 "qXfer:siginfo:write", "write-siginfo-object", 0);
14638
b3b9301e
PA
14639 add_packet_config_cmd
14640 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14641 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14642
169081d0
TG
14643 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14644 "qXfer:uib:read", "unwind-info-block", 0);
14645
444abaca 14646 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14647 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14648 0);
14649
711e434b
PM
14650 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14651 "qGetTIBAddr", "get-thread-information-block-address",
14652 0);
14653
40ab02ce
MS
14654 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14655 "bc", "reverse-continue", 0);
14656
14657 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14658 "bs", "reverse-step", 0);
14659
be2a5f71
DJ
14660 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14661 "qSupported", "supported-packets", 0);
14662
08388c79
DE
14663 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14664 "qSearch:memory", "search-memory", 0);
14665
bd3eecc3
PA
14666 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14667 "qTStatus", "trace-status", 0);
14668
15a201c8
GB
14669 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14670 "vFile:setfs", "hostio-setfs", 0);
14671
a6b151f1
DJ
14672 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14673 "vFile:open", "hostio-open", 0);
14674
14675 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14676 "vFile:pread", "hostio-pread", 0);
14677
14678 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14679 "vFile:pwrite", "hostio-pwrite", 0);
14680
14681 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14682 "vFile:close", "hostio-close", 0);
14683
14684 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14685 "vFile:unlink", "hostio-unlink", 0);
14686
b9e7b9c3
UW
14687 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14688 "vFile:readlink", "hostio-readlink", 0);
14689
0a93529c
GB
14690 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14691 "vFile:fstat", "hostio-fstat", 0);
14692
2d717e4f
DJ
14693 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14694 "vAttach", "attach", 0);
14695
14696 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14697 "vRun", "run", 0);
14698
a6f3e723
SL
14699 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14700 "QStartNoAckMode", "noack", 0);
14701
82f73884
PA
14702 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14703 "vKill", "kill", 0);
14704
0b16c5cf
PA
14705 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14706 "qAttached", "query-attached", 0);
14707
782b2b07 14708 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14709 "ConditionalTracepoints",
14710 "conditional-tracepoints", 0);
3788aec7
LM
14711
14712 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14713 "ConditionalBreakpoints",
14714 "conditional-breakpoints", 0);
14715
d3ce09f5
SS
14716 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14717 "BreakpointCommands",
14718 "breakpoint-commands", 0);
14719
7a697b8d
SS
14720 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14721 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14722
409873ef
SS
14723 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14724 "TracepointSource", "TracepointSource", 0);
14725
d914c394
SS
14726 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14727 "QAllow", "allow", 0);
14728
0fb4aa4b
PA
14729 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14730 "StaticTracepoints", "static-tracepoints", 0);
14731
1e4d1764
YQ
14732 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14733 "InstallInTrace", "install-in-trace", 0);
14734
0fb4aa4b
PA
14735 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14736 "qXfer:statictrace:read", "read-sdata-object", 0);
14737
78d85199
YQ
14738 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14739 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14740
03583c20
UW
14741 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14742 "QDisableRandomization", "disable-randomization", 0);
14743
d1feda86
YQ
14744 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14745 "QAgent", "agent", 0);
14746
f6f899bf
HAQ
14747 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14748 "QTBuffer:size", "trace-buffer-size", 0);
14749
9accd112
MM
14750 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14751 "Qbtrace:off", "disable-btrace", 0);
14752
14753 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14754 "Qbtrace:bts", "enable-btrace-bts", 0);
14755
14756 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14757 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14758
14759 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14760 "qXfer:btrace", "read-btrace", 0);
14761
f4abbc16
MM
14762 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14763 "qXfer:btrace-conf", "read-btrace-conf", 0);
14764
d33501a5
MM
14765 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14766 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14767
73b8c1fd
PA
14768 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14769 "multiprocess-feature", "multiprocess-feature", 0);
14770
f7e6eed5
PA
14771 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14772 "swbreak-feature", "swbreak-feature", 0);
14773
14774 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14775 "hwbreak-feature", "hwbreak-feature", 0);
14776
89245bc0
DB
14777 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14778 "fork-event-feature", "fork-event-feature", 0);
14779
14780 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14781 "vfork-event-feature", "vfork-event-feature", 0);
14782
b20a6524
MM
14783 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14784 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14785
750ce8d1
YQ
14786 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14787 "vContSupported", "verbose-resume-supported", 0);
14788
94585166
DB
14789 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14790 "exec-event-feature", "exec-event-feature", 0);
14791
de979965
PA
14792 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14793 "vCtrlC", "ctrl-c", 0);
14794
65706a29
PA
14795 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14796 "QThreadEvents", "thread-events", 0);
14797
f2faf941
PA
14798 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14799 "N stop reply", "no-resumed-stop-reply", 0);
14800
0b736949
DB
14801 /* Assert that we've registered "set remote foo-packet" commands
14802 for all packet configs. */
ca4f7f8b
PA
14803 {
14804 int i;
14805
14806 for (i = 0; i < PACKET_MAX; i++)
14807 {
14808 /* Ideally all configs would have a command associated. Some
14809 still don't though. */
14810 int excepted;
14811
14812 switch (i)
14813 {
14814 case PACKET_QNonStop:
ca4f7f8b
PA
14815 case PACKET_EnableDisableTracepoints_feature:
14816 case PACKET_tracenz_feature:
14817 case PACKET_DisconnectedTracing_feature:
14818 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14819 case PACKET_qCRC:
14820 /* Additions to this list need to be well justified:
14821 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14822 excepted = 1;
14823 break;
14824 default:
14825 excepted = 0;
14826 break;
14827 }
14828
14829 /* This catches both forgetting to add a config command, and
14830 forgetting to remove a packet from the exception list. */
14831 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14832 }
14833 }
14834
37a105a1
DJ
14835 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14836 Z sub-packet has its own set and show commands, but users may
14837 have sets to this variable in their .gdbinit files (or in their
14838 documentation). */
e9e68a56 14839 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14840 &remote_Z_packet_detect, _("\
14841Set use of remote protocol `Z' packets"), _("\
14842Show use of remote protocol `Z' packets "), _("\
3b64bf98 14843When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14844packets."),
e9e68a56 14845 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14846 show_remote_protocol_Z_packet_cmd,
14847 /* FIXME: i18n: Use of remote protocol
14848 `Z' packets is %s. */
e9e68a56 14849 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14850
a6b151f1
DJ
14851 add_prefix_cmd ("remote", class_files, remote_command, _("\
14852Manipulate files on the remote system\n\
14853Transfer files to and from the remote target system."),
14854 &remote_cmdlist, "remote ",
14855 0 /* allow-unknown */, &cmdlist);
14856
14857 add_cmd ("put", class_files, remote_put_command,
14858 _("Copy a local file to the remote system."),
14859 &remote_cmdlist);
14860
14861 add_cmd ("get", class_files, remote_get_command,
14862 _("Copy a remote file to the local system."),
14863 &remote_cmdlist);
14864
14865 add_cmd ("delete", class_files, remote_delete_command,
14866 _("Delete a remote file."),
14867 &remote_cmdlist);
14868
2d717e4f 14869 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14870 &remote_exec_file_var, _("\
2d717e4f 14871Set the remote pathname for \"run\""), _("\
94585166
DB
14872Show the remote pathname for \"run\""), NULL,
14873 set_remote_exec_file,
14874 show_remote_exec_file,
14875 &remote_set_cmdlist,
14876 &remote_show_cmdlist);
2d717e4f 14877
c1e36e3e
PA
14878 add_setshow_boolean_cmd ("range-stepping", class_run,
14879 &use_range_stepping, _("\
14880Enable or disable range stepping."), _("\
14881Show whether target-assisted range stepping is enabled."), _("\
14882If on, and the target supports it, when stepping a source line, GDB\n\
14883tells the target to step the corresponding range of addresses itself instead\n\
14884of issuing multiple single-steps. This speeds up source level\n\
14885stepping. If off, GDB always issues single-steps, even if range\n\
14886stepping is supported by the target. The default is on."),
14887 set_range_stepping,
14888 show_range_stepping,
14889 &setlist,
14890 &showlist);
14891
449092f6
CV
14892 /* Eventually initialize fileio. See fileio.c */
14893 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14894
ba348170 14895 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14896 special ptids with it set to != 0. */
ba348170
PA
14897 magic_null_ptid = ptid_build (42000, -1, 1);
14898 not_sent_ptid = ptid_build (42000, -2, 1);
14899 any_thread_ptid = ptid_build (42000, 0, 1);
c906108c 14900}