remote: one struct remote_state per struct remote_target
[deliverable/binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2018 Free Software Foundation, Inc.
4
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
9 the Free Software Foundation; either version 3 of the License, or
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
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* See the GDB User Guide for details of the GDB remote protocol. */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 /*#include "terminal.h" */
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observable.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "filestuff.h"
46 #include "rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdb_sys_time.h"
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "common/scoped_restore.h"
76 #include "environ.h"
77 #include "common/byte-vector.h"
78 #include <unordered_map>
79
80 /* The remote target. */
81
82 static const char remote_doc[] = N_("\
83 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
84 Specify the serial device it is connected to\n\
85 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
86
87 #define OPAQUETHREADBYTES 8
88
89 /* a 64 bit opaque identifier */
90 typedef unsigned char threadref[OPAQUETHREADBYTES];
91
92 struct gdb_ext_thread_info;
93 struct threads_listing_context;
94 typedef int (*rmt_thread_action) (threadref *ref, void *context);
95 struct protocol_feature;
96 struct packet_reg;
97
98 struct stop_reply;
99 typedef struct stop_reply *stop_reply_p;
100
101 DECLARE_QUEUE_P (stop_reply_p);
102 DEFINE_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
108 enum 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
118 enum packet_result
119 {
120 PACKET_ERROR,
121 PACKET_OK,
122 PACKET_UNKNOWN
123 };
124
125 struct threads_listing_context;
126 struct remote_state;
127
128 static const target_info remote_target_info = {
129 "remote",
130 N_("Remote serial target in gdb-specific protocol"),
131 remote_doc
132 };
133
134 class remote_target : public target_ops
135 {
136 public:
137 remote_target ()
138 {
139 to_stratum = process_stratum;
140 }
141 ~remote_target () override;
142
143 const target_info &info () const override
144 { return remote_target_info; }
145
146 thread_control_capabilities get_thread_control_capabilities () override
147 { return tc_schedlock; }
148
149 /* Open a remote connection. */
150 static void open (const char *, int);
151
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
173 bool stopped_by_sw_breakpoint () override;
174 bool supports_stopped_by_sw_breakpoint () override;
175
176 bool stopped_by_hw_breakpoint () override;
177
178 bool supports_stopped_by_hw_breakpoint () override;
179
180 bool stopped_by_watchpoint () override;
181
182 bool stopped_data_address (CORE_ADDR *) override;
183
184 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
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
213 bool thread_alive (ptid_t ptid) override;
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
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); }
262
263 bool can_execute_reverse () override;
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
277 bool can_async_p () override;
278
279 bool is_async_p () override;
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
291 bool supports_non_stop () override;
292
293 bool supports_multi_process () override;
294
295 bool supports_disable_randomization () override;
296
297 bool filesystem_is_local () override;
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
323 bool supports_enable_disable_tracepoint () override;
324
325 bool supports_string_tracing () override;
326
327 bool supports_evaluation_of_breakpoint_conditions () override;
328
329 bool can_run_breakpoint_commands () override;
330
331 void trace_init () override;
332
333 void download_tracepoint (struct bp_location *location) override;
334
335 bool can_download_tracepoint () override;
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
357 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
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
375 bool set_trace_notes (const char *user, const char *notes,
376 const char *stopnotes) override;
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
384 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
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
397 bool use_agent (bool use) override;
398 bool can_use_agent () override;
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;
412 bool augmented_libraries_svr4_read () override;
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
423 public: /* 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);
465 static void open_1 (const char *name, int from_tty, int extended_p);
466 void start_remote (int from_tty, int extended_p);
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
672 private: /* data fields */
673
674 std::unique_ptr<struct remote_state> m_remote_state;
675 };
676
677 static 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
683 /* Set up the extended remote target by extending the standard remote
684 target and adding to it. */
685
686 class extended_remote_target final : public remote_target
687 {
688 public:
689 const target_info &info () const override
690 { return extended_remote_target_info; }
691
692 /* Open an extended-remote connection. */
693 static void open (const char *, int);
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;
705 bool supports_disable_randomization () override;
706 };
707
708 /* Per-program-space data key. */
709 static 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. */
715 static char *remote_exec_file_var;
716
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. */
727 enum { REMOTE_ALIGN_WRITES = 16 };
728
729 /* Prototypes for local functions. */
730
731 static int hexnumlen (ULONGEST num);
732
733 static int stubhex (int ch);
734
735 static int hexnumstr (char *, ULONGEST);
736
737 static int hexnumnstr (char *, ULONGEST, int);
738
739 static CORE_ADDR remote_address_masked (CORE_ADDR);
740
741 static void print_packet (const char *);
742
743 static int stub_unpack_int (char *buff, int fieldlength);
744
745 struct packet_config;
746
747 static void show_packet_config_cmd (struct packet_config *config);
748
749 static 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
754 static ptid_t read_ptid (const char *buf, const char **obuf);
755
756 struct stop_reply;
757 static void stop_reply_xfree (struct stop_reply *);
758
759 static void remote_async_inferior_event_handler (gdb_client_data);
760
761 static int remote_read_description_p (struct target_ops *target);
762
763 static void remote_console_output (char *msg);
764
765 static void remote_btrace_reset (remote_state *rs);
766
767 static void remote_unpush_and_throw (void);
768
769 /* For "remote". */
770
771 static struct cmd_list_element *remote_cmdlist;
772
773 /* For "set remote" and "show remote". */
774
775 static struct cmd_list_element *remote_set_cmdlist;
776 static struct cmd_list_element *remote_show_cmdlist;
777
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
783 struct vCont_action_support
784 {
785 /* vCont;t */
786 bool t = false;
787
788 /* vCont;r */
789 bool r = false;
790
791 /* vCont;s */
792 bool s = false;
793
794 /* vCont;S */
795 bool S = false;
796 };
797
798 /* Controls whether GDB is willing to use range stepping. */
799
800 static int use_range_stepping = 1;
801
802 /* About this many threadisds fit in a packet. */
803
804 #define MAXTHREADLISTRESULTS 32
805
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
811 /* Data for the vFile:pread readahead cache. */
812
813 struct readahead_cache
814 {
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
825 /* The file descriptor for the file that is being cached. -1 if the
826 cache is invalid. */
827 int fd = -1;
828
829 /* The offset into the file that the cache buffer corresponds
830 to. */
831 ULONGEST offset = 0;
832
833 /* The buffer holding the cache contents. */
834 gdb_byte *buf = nullptr;
835 /* The buffer's size. We try to read as much as fits into a packet
836 at a time. */
837 size_t bufsize = 0;
838
839 /* Cache hit and miss counters. */
840 ULONGEST hit_count = 0;
841 ULONGEST miss_count = 0;
842 };
843
844 /* Description of the remote protocol for a given architecture. */
845
846 struct 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
858 struct 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
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
886 class remote_state
887 {
888 public:
889
890 remote_state ();
891 ~remote_state ();
892
893 /* Get the remote arch state for GDBARCH. */
894 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
895
896 public: /* data */
897
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;
906
907 /* True if we're going through initial connection setup (finding out
908 about the remote side's threads, relocating symbols, etc.). */
909 bool starting_up = false;
910
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. */
915 long explicit_packet_size = 0;
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. */
924 int cached_wait_status = 0;
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. */
929 bool noack_mode = false;
930
931 /* True if we're connected in extended remote mode. */
932 bool extended = false;
933
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. */
940 bool waiting_for_stop_reply = false;
941
942 /* The status of the stub support for the various vCont actions. */
943 vCont_action_support supports_vCont;
944
945 /* True if the user has pressed Ctrl-C, but the target hasn't
946 responded to that. */
947 bool ctrlc_pending_p = false;
948
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. */
955 bool got_ctrlc_during_io = false;
956
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. */
960 struct serial *remote_desc = nullptr;
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. */
964 ptid_t general_thread = null_ptid;
965 ptid_t continue_thread = null_ptid;
966
967 /* This is the traceframe which we last selected on the remote system.
968 It will be -1 if no traceframe is selected. */
969 int remote_traceframe_number = -1;
970
971 char *last_pass_packet = nullptr;
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. */
977 char *last_program_signals_packet = nullptr;
978
979 gdb_signal last_sent_signal = GDB_SIGNAL_0;
980
981 bool last_sent_step = false;
982
983 /* The execution direction of the last resume we got. */
984 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
985
986 char *finished_object = nullptr;
987 char *finished_annex = nullptr;
988 ULONGEST finished_offset = 0;
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). */
997 bool use_threadinfo_query = false;
998 bool use_threadextra_query = false;
999
1000 threadref echo_nextthread {};
1001 threadref nextthread {};
1002 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
1003
1004 /* The state of remote notification. */
1005 struct remote_notif_state *notif_state = nullptr;
1006
1007 /* The branch trace configuration. */
1008 struct btrace_config btrace_config {};
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. */
1014 int fs_pid = -1;
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;
1023
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
1046 private:
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. */
1050 std::unordered_map<struct gdbarch *, remote_arch_state>
1051 m_arch_states;
1052 };
1053
1054 /* Private data that we'll store in (struct thread_info)->priv. */
1055 struct remote_thread_info : public private_thread_info
1056 {
1057 std::string extra;
1058 std::string name;
1059 int core = -1;
1060
1061 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1062 sequence of bytes. */
1063 gdb::byte_vector thread_handle;
1064
1065 /* Whether the target stopped for a breakpoint/watchpoint. */
1066 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1067
1068 /* This is set to the data address of the access causing the target
1069 to stop for a watchpoint. */
1070 CORE_ADDR watch_data_address = 0;
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. */
1080 int last_resume_step = 0;
1081
1082 /* The signal specified in the last target_resume call for this
1083 thread. */
1084 gdb_signal last_resume_sig = GDB_SIGNAL_0;
1085
1086 /* Whether this thread was already vCont-resumed on the remote
1087 side. */
1088 int vcont_resumed = 0;
1089 };
1090
1091 remote_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);
1097
1098 this->stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
1099 }
1100
1101 remote_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);
1108 QUEUE_free (stop_reply_p, this->stop_reply_queue);
1109 }
1110
1111 /* Utility: generate error from an incoming stub packet. */
1112 static void
1113 trace_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));
1125 default:
1126 error (_("Target returns error code '%s'."), buf);
1127 }
1128 }
1129
1130 /* Utility: wait for reply from stub, while accepting "O" packets. */
1131
1132 char *
1133 remote_target::remote_get_noisy_reply ()
1134 {
1135 struct remote_state *rs = get_remote_state ();
1136
1137 do /* Loop on reply from remote stub. */
1138 {
1139 char *buf;
1140
1141 QUIT; /* Allow user to bail out with ^C. */
1142 getpkt (&rs->buf, &rs->buf_size, 0);
1143 buf = rs->buf;
1144 if (buf[0] == 'E')
1145 trace_error (buf);
1146 else if (startswith (buf, "qRelocInsn:"))
1147 {
1148 ULONGEST ul;
1149 CORE_ADDR from, to, org_to;
1150 const char *p, *pp;
1151 int adjusted_size = 0;
1152 int relocated = 0;
1153
1154 p = buf + strlen ("qRelocInsn:");
1155 pp = unpack_varlen_hex (p, &ul);
1156 if (*pp != ';')
1157 error (_("invalid qRelocInsn packet: %s"), buf);
1158 from = ul;
1159
1160 p = pp + 1;
1161 unpack_varlen_hex (p, &ul);
1162 to = ul;
1163
1164 org_to = to;
1165
1166 TRY
1167 {
1168 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1169 relocated = 1;
1170 }
1171 CATCH (ex, RETURN_MASK_ALL)
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 }
1190 END_CATCH
1191
1192 if (relocated)
1193 {
1194 adjusted_size = to - org_to;
1195
1196 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
1197 putpkt (buf);
1198 }
1199 }
1200 else if (buf[0] == 'O' && buf[1] != 'K')
1201 remote_console_output (buf + 1); /* 'O' message from stub */
1202 else
1203 return buf; /* Here's the actual reply. */
1204 }
1205 while (1);
1206 }
1207
1208 struct remote_arch_state *
1209 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1210 {
1211 remote_arch_state *rsa;
1212
1213 auto it = this->m_arch_states.find (gdbarch);
1214 if (it == this->m_arch_states.end ())
1215 {
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;
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 }
1229 else
1230 rsa = &it->second;
1231
1232 return rsa;
1233 }
1234
1235 /* Fetch the global remote target state. */
1236
1237 remote_state *
1238 remote_target::get_remote_state ()
1239 {
1240 if (m_remote_state == nullptr)
1241 m_remote_state.reset (new remote_state ());
1242
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. */
1248 m_remote_state->get_remote_arch_state (target_gdbarch ());
1249
1250 return m_remote_state.get ();
1251 }
1252
1253 /* Cleanup routine for the remote module's pspace data. */
1254
1255 static void
1256 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1257 {
1258 char *remote_exec_file = (char *) arg;
1259
1260 xfree (remote_exec_file);
1261 }
1262
1263 /* Fetch the remote exec-file from the current program space. */
1264
1265 static const char *
1266 get_remote_exec_file (void)
1267 {
1268 char *remote_exec_file;
1269
1270 remote_exec_file
1271 = (char *) program_space_data (current_program_space,
1272 remote_pspace_data);
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
1281 static void
1282 set_pspace_remote_exec_file (struct program_space *pspace,
1283 char *remote_exec_file)
1284 {
1285 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
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
1294 static void
1295 set_remote_exec_file (const char *ignored, int from_tty,
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
1304 static void
1305 show_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
1311 static int
1312 compare_pnums (const void *lhs_, const void *rhs_)
1313 {
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_;
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
1327 static int
1328 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1329 {
1330 int regnum, num_remote_regs, offset;
1331 struct packet_reg **remote_regs;
1332
1333 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1334 {
1335 struct packet_reg *r = &regs[regnum];
1336
1337 if (register_size (gdbarch, regnum) == 0)
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
1343 r->regnum = regnum;
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
1350 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1351 for (num_remote_regs = 0, regnum = 0;
1352 regnum < gdbarch_num_regs (gdbarch);
1353 regnum++)
1354 if (regs[regnum].pnum != -1)
1355 remote_regs[num_remote_regs++] = &regs[regnum];
1356
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;
1364 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1365 }
1366
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
1376 int
1377 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1378 int *pnum, int *poffset)
1379 {
1380 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1381
1382 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1383
1384 map_regcache_remote_table (gdbarch, regs.data ());
1385
1386 *pnum = regs[regnum].pnum;
1387 *poffset = regs[regnum].offset;
1388
1389 return *pnum != -1;
1390 }
1391
1392 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1393 {
1394 /* Use the architecture to build a regnum<->pnum table, which will be
1395 1:1 unless a feature set specifies otherwise. */
1396 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1397
1398 /* Record the maximum possible size of the g packet - it may turn out
1399 to be smaller. */
1400 this->sizeof_g_packet
1401 = map_regcache_remote_table (gdbarch, this->regs.get ());
1402
1403 /* Default maximum number of characters in a packet body. Many
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
1409 already a full buffer (As of 1999-12-04 that was most stubs). */
1410 this->remote_packet_size = 400 - 1;
1411
1412 /* This one is filled in when a ``g'' packet is received. */
1413 this->actual_register_packet_size = 0;
1414
1415 /* Should rsa->sizeof_g_packet needs more space than the
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
1419 (``$NN:G...#NN'') is a better guess, the below has been padded a
1420 little. */
1421 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1422 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1423 }
1424
1425 /* Get a pointer to the current remote target. If not connected to a
1426 remote target, return NULL. */
1427
1428 static remote_target *
1429 get_current_remote_target ()
1430 {
1431 target_ops *proc_target = find_target_at (process_stratum);
1432 return dynamic_cast<remote_target *> (proc_target);
1433 }
1434
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. */
1438 long
1439 remote_target::get_remote_packet_size ()
1440 {
1441 struct remote_state *rs = get_remote_state ();
1442 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1443
1444 if (rs->explicit_packet_size)
1445 return rs->explicit_packet_size;
1446
1447 return rsa->remote_packet_size;
1448 }
1449
1450 static struct packet_reg *
1451 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1452 long regnum)
1453 {
1454 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1455 return NULL;
1456 else
1457 {
1458 struct packet_reg *r = &rsa->regs[regnum];
1459
1460 gdb_assert (r->regnum == regnum);
1461 return r;
1462 }
1463 }
1464
1465 static struct packet_reg *
1466 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1467 LONGEST pnum)
1468 {
1469 int i;
1470
1471 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1472 {
1473 struct packet_reg *r = &rsa->regs[i];
1474
1475 if (r->pnum == pnum)
1476 return r;
1477 }
1478 return NULL;
1479 }
1480
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. */
1487 const char interrupt_sequence_control_c[] = "Ctrl-C";
1488 const char interrupt_sequence_break[] = "BREAK";
1489 const char interrupt_sequence_break_g[] = "BREAK-g";
1490 static const char *const interrupt_sequence_modes[] =
1491 {
1492 interrupt_sequence_control_c,
1493 interrupt_sequence_break,
1494 interrupt_sequence_break_g,
1495 NULL
1496 };
1497 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1498
1499 static void
1500 show_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 }
1523
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. */
1528 static int interrupt_on_connect = 0;
1529
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. */
1533 static int remote_break;
1534
1535 static void
1536 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1537 {
1538 if (remote_break)
1539 interrupt_sequence_mode = interrupt_sequence_break;
1540 else
1541 interrupt_sequence_mode = interrupt_sequence_control_c;
1542 }
1543
1544 static void
1545 show_remotebreak (struct ui_file *file, int from_tty,
1546 struct cmd_list_element *c,
1547 const char *value)
1548 {
1549 }
1550
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
1553 leading zeros, the entire address would be sent. This variable
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
1560 facilitate backward compatibility. */
1561
1562 static unsigned int remote_address_size;
1563
1564 \f
1565 /* User configurable variables for the number of characters in a
1566 memory read/write packet. MIN (rsa->remote_packet_size,
1567 rsa->sizeof_g_packet) is the default. Some targets need smaller
1568 values (fifo overruns, et.al.) and some users need larger values
1569 (speed up transfers). The variables ``preferred_*'' (the user
1570 request), ``current_*'' (what was actually set) and ``forced_*''
1571 (Positive - a soft limit, negative - a hard limit). */
1572
1573 struct memory_packet_config
1574 {
1575 const char *name;
1576 long size;
1577 int fixed_p;
1578 };
1579
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
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
1590 /* Get the memory packet size, assuming it is fixed. */
1591
1592 static long
1593 get_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
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
1606 long
1607 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1608 {
1609 struct remote_state *rs = get_remote_state ();
1610 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1611
1612 long what_they_get;
1613 if (config->fixed_p)
1614 what_they_get = get_fixed_memory_packet_size (config);
1615 else
1616 {
1617 what_they_get = get_remote_packet_size ();
1618 /* Limit the packet to the size specified by the user. */
1619 if (config->size > 0
1620 && what_they_get > config->size)
1621 what_they_get = config->size;
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;
1629 }
1630 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1631 what_they_get = MIN_MEMORY_PACKET_SIZE;
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;
1638 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1639 }
1640
1641 return what_they_get;
1642 }
1643
1644 /* Update the size of a read/write packet. If they user wants
1645 something really big then do a sanity check. */
1646
1647 static void
1648 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1649 {
1650 int fixed_p = config->fixed_p;
1651 long size = config->size;
1652
1653 if (args == NULL)
1654 error (_("Argument required (integer, `fixed' or `limited')."));
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;
1664
1665 size = strtoul (args, &end, 0);
1666 if (args == end)
1667 error (_("Invalid %s (bad syntax)."), config->name);
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. */
1672 }
1673
1674 /* Extra checks? */
1675 if (fixed_p && !config->fixed_p)
1676 {
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
1682 if (! query (_("The target may not be able to correctly handle a %s\n"
1683 "of %ld bytes. Change the packet size? "),
1684 config->name, query_size))
1685 error (_("Packet size not changed."));
1686 }
1687 /* Update the config. */
1688 config->fixed_p = fixed_p;
1689 config->size = size;
1690 }
1691
1692 static void
1693 show_memory_packet_size (struct memory_packet_config *config)
1694 {
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);
1699 if (config->fixed_p)
1700 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1701 get_fixed_memory_packet_size (config));
1702 else
1703 {
1704 remote_target *remote = get_current_remote_target ();
1705
1706 if (remote != NULL)
1707 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1708 remote->get_memory_packet_size (config));
1709 else
1710 puts_filtered ("The actual limit will be further reduced "
1711 "dependent on the target.\n");
1712 }
1713 }
1714
1715 static struct memory_packet_config memory_write_packet_config =
1716 {
1717 "memory-write-packet-size",
1718 };
1719
1720 static void
1721 set_memory_write_packet_size (const char *args, int from_tty)
1722 {
1723 set_memory_packet_size (args, &memory_write_packet_config);
1724 }
1725
1726 static void
1727 show_memory_write_packet_size (const char *args, int from_tty)
1728 {
1729 show_memory_packet_size (&memory_write_packet_config);
1730 }
1731
1732 long
1733 remote_target::get_memory_write_packet_size ()
1734 {
1735 return get_memory_packet_size (&memory_write_packet_config);
1736 }
1737
1738 static struct memory_packet_config memory_read_packet_config =
1739 {
1740 "memory-read-packet-size",
1741 };
1742
1743 static void
1744 set_memory_read_packet_size (const char *args, int from_tty)
1745 {
1746 set_memory_packet_size (args, &memory_read_packet_config);
1747 }
1748
1749 static void
1750 show_memory_read_packet_size (const char *args, int from_tty)
1751 {
1752 show_memory_packet_size (&memory_read_packet_config);
1753 }
1754
1755 long
1756 remote_target::get_memory_read_packet_size ()
1757 {
1758 long size = get_memory_packet_size (&memory_read_packet_config);
1759
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
1762 increased beyond this. */
1763 if (size > get_remote_packet_size ())
1764 size = get_remote_packet_size ();
1765 return size;
1766 }
1767
1768 \f
1769
1770 struct packet_config
1771 {
1772 const char *name;
1773 const char *title;
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
1778 packet. If false, the packet is disabled. Configs that don't
1779 have an associated command always have this set to auto. */
1780 enum auto_boolean detect;
1781
1782 /* Does the target support this packet? */
1783 enum packet_support support;
1784 };
1785
1786 static enum packet_support packet_config_support (struct packet_config *config);
1787 static enum packet_support packet_support (int packet);
1788
1789 static void
1790 show_packet_config_cmd (struct packet_config *config)
1791 {
1792 const char *support = "internal-error";
1793
1794 switch (packet_config_support (config))
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 {
1808 case AUTO_BOOLEAN_AUTO:
1809 printf_filtered (_("Support for the `%s' packet "
1810 "is auto-detected, currently %s.\n"),
1811 config->name, support);
1812 break;
1813 case AUTO_BOOLEAN_TRUE:
1814 case AUTO_BOOLEAN_FALSE:
1815 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1816 config->name, support);
1817 break;
1818 }
1819 }
1820
1821 static void
1822 add_packet_config_cmd (struct packet_config *config, const char *name,
1823 const char *title, int legacy)
1824 {
1825 char *set_doc;
1826 char *show_doc;
1827 char *cmd_name;
1828
1829 config->name = name;
1830 config->title = title;
1831 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1832 name, title);
1833 show_doc = xstrprintf ("Show current use of remote "
1834 "protocol `%s' (%s) packet",
1835 name, title);
1836 /* set/show TITLE-packet {auto,on,off} */
1837 cmd_name = xstrprintf ("%s-packet", title);
1838 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1839 &config->detect, set_doc,
1840 show_doc, NULL, /* help_doc */
1841 NULL,
1842 show_remote_protocol_packet_cmd,
1843 &remote_set_cmdlist, &remote_show_cmdlist);
1844 /* The command code copies the documentation strings. */
1845 xfree (set_doc);
1846 xfree (show_doc);
1847 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1848 if (legacy)
1849 {
1850 char *legacy_name;
1851
1852 legacy_name = xstrprintf ("%s-packet", name);
1853 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1854 &remote_set_cmdlist);
1855 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1856 &remote_show_cmdlist);
1857 }
1858 }
1859
1860 static enum packet_result
1861 packet_check_result (const char *buf)
1862 {
1863 if (buf[0] != '\0')
1864 {
1865 /* The stub recognized the packet request. Check that the
1866 operation succeeded. */
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
1886 static enum packet_result
1887 packet_ok (const char *buf, struct packet_config *config)
1888 {
1889 enum packet_result result;
1890
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
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. */
1902 if (config->support == PACKET_SUPPORT_UNKNOWN)
1903 {
1904 if (remote_debug)
1905 fprintf_unfiltered (gdb_stdlog,
1906 "Packet %s (%s) is supported\n",
1907 config->name, config->title);
1908 config->support = PACKET_ENABLE;
1909 }
1910 break;
1911 case PACKET_UNKNOWN:
1912 /* The stub does not support the packet. */
1913 if (config->detect == AUTO_BOOLEAN_AUTO
1914 && config->support == PACKET_ENABLE)
1915 {
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);
1926 }
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;
1933 break;
1934 }
1935
1936 return result;
1937 }
1938
1939 enum {
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,
1950 PACKET_vFile_setfs,
1951 PACKET_vFile_open,
1952 PACKET_vFile_pread,
1953 PACKET_vFile_pwrite,
1954 PACKET_vFile_close,
1955 PACKET_vFile_unlink,
1956 PACKET_vFile_readlink,
1957 PACKET_vFile_fstat,
1958 PACKET_qXfer_auxv,
1959 PACKET_qXfer_features,
1960 PACKET_qXfer_exec_file,
1961 PACKET_qXfer_libraries,
1962 PACKET_qXfer_libraries_svr4,
1963 PACKET_qXfer_memory_map,
1964 PACKET_qXfer_spu_read,
1965 PACKET_qXfer_spu_write,
1966 PACKET_qXfer_osdata,
1967 PACKET_qXfer_threads,
1968 PACKET_qXfer_statictrace_read,
1969 PACKET_qXfer_traceframe_info,
1970 PACKET_qXfer_uib,
1971 PACKET_qGetTIBAddr,
1972 PACKET_qGetTLSAddr,
1973 PACKET_qSupported,
1974 PACKET_qTStatus,
1975 PACKET_QPassSignals,
1976 PACKET_QCatchSyscalls,
1977 PACKET_QProgramSignals,
1978 PACKET_QSetWorkingDir,
1979 PACKET_QStartupWithShell,
1980 PACKET_QEnvironmentHexEncoded,
1981 PACKET_QEnvironmentReset,
1982 PACKET_QEnvironmentUnset,
1983 PACKET_qCRC,
1984 PACKET_qSearch_memory,
1985 PACKET_vAttach,
1986 PACKET_vRun,
1987 PACKET_QStartNoAckMode,
1988 PACKET_vKill,
1989 PACKET_qXfer_siginfo_read,
1990 PACKET_qXfer_siginfo_write,
1991 PACKET_qAttached,
1992
1993 /* Support for conditional tracepoints. */
1994 PACKET_ConditionalTracepoints,
1995
1996 /* Support for target-side breakpoint conditions. */
1997 PACKET_ConditionalBreakpoints,
1998
1999 /* Support for target-side breakpoint commands. */
2000 PACKET_BreakpointCommands,
2001
2002 /* Support for fast tracepoints. */
2003 PACKET_FastTracepoints,
2004
2005 /* Support for static tracepoints. */
2006 PACKET_StaticTracepoints,
2007
2008 /* Support for installing tracepoints while a trace experiment is
2009 running. */
2010 PACKET_InstallInTrace,
2011
2012 PACKET_bc,
2013 PACKET_bs,
2014 PACKET_TracepointSource,
2015 PACKET_QAllow,
2016 PACKET_qXfer_fdpic,
2017 PACKET_QDisableRandomization,
2018 PACKET_QAgent,
2019 PACKET_QTBuffer_size,
2020 PACKET_Qbtrace_off,
2021 PACKET_Qbtrace_bts,
2022 PACKET_Qbtrace_pt,
2023 PACKET_qXfer_btrace,
2024
2025 /* Support for the QNonStop packet. */
2026 PACKET_QNonStop,
2027
2028 /* Support for the QThreadEvents packet. */
2029 PACKET_QThreadEvents,
2030
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
2048 /* Support for the qXfer:btrace-conf:read packet. */
2049 PACKET_qXfer_btrace_conf,
2050
2051 /* Support for the Qbtrace-conf:bts:size packet. */
2052 PACKET_Qbtrace_conf_bts_size,
2053
2054 /* Support for swbreak+ feature. */
2055 PACKET_swbreak_feature,
2056
2057 /* Support for hwbreak+ feature. */
2058 PACKET_hwbreak_feature,
2059
2060 /* Support for fork events. */
2061 PACKET_fork_event_feature,
2062
2063 /* Support for vfork events. */
2064 PACKET_vfork_event_feature,
2065
2066 /* Support for the Qbtrace-conf:pt:size packet. */
2067 PACKET_Qbtrace_conf_pt_size,
2068
2069 /* Support for exec events. */
2070 PACKET_exec_event_feature,
2071
2072 /* Support for query supported vCont actions. */
2073 PACKET_vContSupported,
2074
2075 /* Support remote CTRL-C. */
2076 PACKET_vCtrlC,
2077
2078 /* Support TARGET_WAITKIND_NO_RESUMED. */
2079 PACKET_no_resumed,
2080
2081 PACKET_MAX
2082 };
2083
2084 static struct packet_config remote_protocol_packets[PACKET_MAX];
2085
2086 /* Returns the packet's corresponding "set remote foo-packet" command
2087 state. See struct packet_config for more details. */
2088
2089 static enum auto_boolean
2090 packet_set_cmd_state (int packet)
2091 {
2092 return remote_protocol_packets[packet].detect;
2093 }
2094
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. */
2098
2099 static enum packet_support
2100 packet_config_support (struct packet_config *config)
2101 {
2102 switch (config->detect)
2103 {
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"));
2112 }
2113 }
2114
2115 /* Same as packet_config_support, but takes the packet's enum value as
2116 argument. */
2117
2118 static enum packet_support
2119 packet_support (int packet)
2120 {
2121 struct packet_config *config = &remote_protocol_packets[packet];
2122
2123 return packet_config_support (config);
2124 }
2125
2126 static void
2127 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2128 struct cmd_list_element *c,
2129 const char *value)
2130 {
2131 struct packet_config *packet;
2132
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 }
2143 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2144 c->name);
2145 }
2146
2147 /* Should we try one of the 'Z' requests? */
2148
2149 enum 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 };
2158
2159 /* For compatibility with older distributions. Provide a ``set remote
2160 Z-packet ...'' command that updates all the Z packet types. */
2161
2162 static enum auto_boolean remote_Z_packet_detect;
2163
2164 static void
2165 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2166 struct cmd_list_element *c)
2167 {
2168 int i;
2169
2170 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2171 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2172 }
2173
2174 static void
2175 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2176 struct cmd_list_element *c,
2177 const char *value)
2178 {
2179 int i;
2180
2181 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2182 {
2183 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2184 }
2185 }
2186
2187 /* Returns true if the multi-process extensions are in effect. */
2188
2189 static int
2190 remote_multi_process_p (struct remote_state *rs)
2191 {
2192 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2193 }
2194
2195 /* Returns true if fork events are supported. */
2196
2197 static int
2198 remote_fork_event_p (struct remote_state *rs)
2199 {
2200 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2201 }
2202
2203 /* Returns true if vfork events are supported. */
2204
2205 static int
2206 remote_vfork_event_p (struct remote_state *rs)
2207 {
2208 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2209 }
2210
2211 /* Returns true if exec events are supported. */
2212
2213 static int
2214 remote_exec_event_p (struct remote_state *rs)
2215 {
2216 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2217 }
2218
2219 /* Insert fork catchpoint target routine. If fork events are enabled
2220 then return success, nothing more to do. */
2221
2222 int
2223 remote_target::insert_fork_catchpoint (int pid)
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
2233 int
2234 remote_target::remove_fork_catchpoint (int pid)
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
2242 int
2243 remote_target::insert_vfork_catchpoint (int pid)
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
2253 int
2254 remote_target::remove_vfork_catchpoint (int pid)
2255 {
2256 return 0;
2257 }
2258
2259 /* Insert exec catchpoint target routine. If exec events are
2260 enabled, just return success. */
2261
2262 int
2263 remote_target::insert_exec_catchpoint (int pid)
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
2273 int
2274 remote_target::remove_exec_catchpoint (int pid)
2275 {
2276 return 0;
2277 }
2278
2279 \f
2280
2281 static ptid_t magic_null_ptid;
2282 static ptid_t not_sent_ptid;
2283 static ptid_t any_thread_ptid;
2284
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
2288 int
2289 remote_target::remote_query_attached (int pid)
2290 {
2291 struct remote_state *rs = get_remote_state ();
2292 size_t size = get_remote_packet_size ();
2293
2294 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2295 return 0;
2296
2297 if (remote_multi_process_p (rs))
2298 xsnprintf (rs->buf, size, "qAttached:%x", pid);
2299 else
2300 xsnprintf (rs->buf, size, "qAttached");
2301
2302 putpkt (rs->buf);
2303 getpkt (&rs->buf, &rs->buf_size, 0);
2304
2305 switch (packet_ok (rs->buf,
2306 &remote_protocol_packets[PACKET_qAttached]))
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
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
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. */
2332
2333 inferior *
2334 remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2335 int try_open_exec)
2336 {
2337 struct inferior *inf;
2338
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
2345 if (gdbarch_has_global_solist (target_gdbarch ()))
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 }
2365
2366 inf->attach_flag = attached;
2367 inf->fake_pid_p = fake_pid_p;
2368
2369 /* If no main executable is currently open then attempt to
2370 open the file that was executed to create this inferior. */
2371 if (try_open_exec && get_exec_file (0) == NULL)
2372 exec_file_locate_attach (pid, 0, 1);
2373
2374 return inf;
2375 }
2376
2377 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2378
2379 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2380 according to RUNNING. */
2381
2382 void
2383 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2384 {
2385 struct remote_state *rs = get_remote_state ();
2386 struct thread_info *thread;
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)
2395 thread = add_thread_silent (ptid);
2396 else
2397 thread = add_thread (ptid);
2398
2399 get_remote_thread_info (thread)->vcont_resumed = executing;
2400 set_executing (ptid, executing);
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
2408 GDB's inferior list as well. EXECUTING indicates whether the
2409 thread is (internally) executing or stopped. */
2410
2411 void
2412 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2413 {
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
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. */
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. */
2426 remote_add_thread (currthread, running, executing);
2427 return;
2428 }
2429
2430 if (!in_thread_list (currthread))
2431 {
2432 struct inferior *inf = NULL;
2433 int pid = ptid_get_pid (currthread);
2434
2435 if (ptid_is_pid (inferior_ptid)
2436 && pid == ptid_get_pid (inferior_ptid))
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. */
2443 if (in_thread_list (pid_to_ptid (pid)))
2444 thread_change_ptid (inferior_ptid, currthread);
2445 else
2446 {
2447 remote_add_thread (currthread, running, executing);
2448 inferior_ptid = currthread;
2449 }
2450 return;
2451 }
2452
2453 if (ptid_equal (magic_null_ptid, inferior_ptid))
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. */
2460 thread_change_ptid (inferior_ptid, currthread);
2461 return;
2462 }
2463
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)))
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,
2474 ptid_get_pid (currthread), -1, 1);
2475 }
2476
2477 /* This is really a new thread. Add it. */
2478 remote_add_thread (currthread, running, executing);
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
2482 breakpoints), unless we're just setting up an all-stop
2483 connection. */
2484 if (inf != NULL)
2485 {
2486 struct remote_state *rs = get_remote_state ();
2487
2488 if (!rs->starting_up)
2489 notice_new_inferior (currthread, executing, 0);
2490 }
2491 }
2492 }
2493
2494 /* Return THREAD's private thread data, creating it if necessary. */
2495
2496 static remote_thread_info *
2497 get_remote_thread_info (thread_info *thread)
2498 {
2499 gdb_assert (thread != NULL);
2500
2501 if (thread->priv == NULL)
2502 thread->priv.reset (new remote_thread_info);
2503
2504 return static_cast<remote_thread_info *> (thread->priv.get ());
2505 }
2506
2507 /* Return PTID's private thread data, creating it if necessary. */
2508
2509 static remote_thread_info *
2510 get_remote_thread_info (ptid_t ptid)
2511 {
2512 struct thread_info *info = find_thread_ptid (ptid);
2513
2514 return get_remote_thread_info (info);
2515 }
2516
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
2520 3) Successful execution of set thread */
2521
2522 static void
2523 record_currthread (struct remote_state *rs, ptid_t currthread)
2524 {
2525 rs->general_thread = currthread;
2526 }
2527
2528 /* If 'QPassSignals' is supported, tell the remote stub what signals
2529 it can simply pass through to the inferior without reporting. */
2530
2531 void
2532 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2533 {
2534 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2535 {
2536 char *pass_packet, *p;
2537 int count = 0, i;
2538 struct remote_state *rs = get_remote_state ();
2539
2540 gdb_assert (numsigs < 256);
2541 for (i = 0; i < numsigs; i++)
2542 {
2543 if (pass_signals[i])
2544 count++;
2545 }
2546 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2547 strcpy (pass_packet, "QPassSignals:");
2548 p = pass_packet + strlen (pass_packet);
2549 for (i = 0; i < numsigs; i++)
2550 {
2551 if (pass_signals[i])
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;
2564 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2565 {
2566 putpkt (pass_packet);
2567 getpkt (&rs->buf, &rs->buf_size, 0);
2568 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2569 if (rs->last_pass_packet)
2570 xfree (rs->last_pass_packet);
2571 rs->last_pass_packet = pass_packet;
2572 }
2573 else
2574 xfree (pass_packet);
2575 }
2576 }
2577
2578 /* If 'QCatchSyscalls' is supported, tell the remote stub
2579 to report syscalls to GDB. */
2580
2581 int
2582 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2583 gdb::array_view<const int> syscall_counts)
2584 {
2585 const char *catch_packet;
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
2595 if (needed && any_count == 0)
2596 {
2597 /* Count how many syscalls are to be caught. */
2598 for (size_t i = 0; i < syscall_counts.size (); i++)
2599 {
2600 if (syscall_counts[i] != 0)
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
2613 std::string built_packet;
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;
2620 built_packet.reserve (maxpktsz);
2621 built_packet = "QCatchSyscalls:1";
2622 if (any_count == 0)
2623 {
2624 /* Add in each syscall to be caught. */
2625 for (size_t i = 0; i < syscall_counts.size (); i++)
2626 {
2627 if (syscall_counts[i] != 0)
2628 string_appendf (built_packet, ";%zx", i);
2629 }
2630 }
2631 if (built_packet.size () > get_remote_packet_size ())
2632 {
2633 /* catch_packet too big. Fallback to less efficient
2634 non selective mode, with GDB doing the filtering. */
2635 catch_packet = "QCatchSyscalls:1";
2636 }
2637 else
2638 catch_packet = built_packet.c_str ();
2639 }
2640 else
2641 catch_packet = "QCatchSyscalls:0";
2642
2643 struct remote_state *rs = get_remote_state ();
2644
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;
2652 }
2653
2654 /* If 'QProgramSignals' is supported, tell the remote stub what
2655 signals it should pass through to the inferior when detaching. */
2656
2657 void
2658 remote_target::program_signals (int numsigs, unsigned char *signals)
2659 {
2660 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2661 {
2662 char *packet, *p;
2663 int count = 0, i;
2664 struct remote_state *rs = get_remote_state ();
2665
2666 gdb_assert (numsigs < 256);
2667 for (i = 0; i < numsigs; i++)
2668 {
2669 if (signals[i])
2670 count++;
2671 }
2672 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
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;
2690 if (!rs->last_program_signals_packet
2691 || strcmp (rs->last_program_signals_packet, packet) != 0)
2692 {
2693 putpkt (packet);
2694 getpkt (&rs->buf, &rs->buf_size, 0);
2695 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2696 xfree (rs->last_program_signals_packet);
2697 rs->last_program_signals_packet = packet;
2698 }
2699 else
2700 xfree (packet);
2701 }
2702 }
2703
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. */
2708 void
2709 remote_target::set_thread (ptid_t ptid, int gen)
2710 {
2711 struct remote_state *rs = get_remote_state ();
2712 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2713 char *buf = rs->buf;
2714 char *endbuf = rs->buf + get_remote_packet_size ();
2715
2716 if (ptid_equal (state, ptid))
2717 return;
2718
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
2728 write_ptid (buf, endbuf, ptid);
2729 putpkt (rs->buf);
2730 getpkt (&rs->buf, &rs->buf_size, 0);
2731 if (gen)
2732 rs->general_thread = ptid;
2733 else
2734 rs->continue_thread = ptid;
2735 }
2736
2737 void
2738 remote_target::set_general_thread (ptid_t ptid)
2739 {
2740 set_thread (ptid, 1);
2741 }
2742
2743 void
2744 remote_target::set_continue_thread (ptid_t ptid)
2745 {
2746 set_thread (ptid, 0);
2747 }
2748
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
2758 void
2759 remote_target::set_general_process ()
2760 {
2761 struct remote_state *rs = get_remote_state ();
2762
2763 /* If the remote can't handle multiple processes, don't bother. */
2764 if (!remote_multi_process_p (rs))
2765 return;
2766
2767 /* We only need to change the remote current thread if it's pointing
2768 at some other process. */
2769 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2770 set_general_thread (inferior_ptid);
2771 }
2772
2773 \f
2774 /* Return nonzero if this is the main thread that we made up ourselves
2775 to model non-threaded targets as single-threaded. */
2776
2777 static int
2778 remote_thread_always_alive (ptid_t ptid)
2779 {
2780 if (ptid_equal (ptid, magic_null_ptid))
2781 /* The main thread is always alive. */
2782 return 1;
2783
2784 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
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
2790 return 0;
2791 }
2792
2793 /* Return nonzero if the thread PTID is still alive on the remote
2794 system. */
2795
2796 bool
2797 remote_target::thread_alive (ptid_t ptid)
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. */
2804 if (remote_thread_always_alive (ptid))
2805 return 1;
2806
2807 p = rs->buf;
2808 endp = rs->buf + get_remote_packet_size ();
2809
2810 *p++ = 'T';
2811 write_ptid (p, endp, ptid);
2812
2813 putpkt (rs->buf);
2814 getpkt (&rs->buf, &rs->buf_size, 0);
2815 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2816 }
2817
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
2821 const char *
2822 remote_target::thread_name (struct thread_info *info)
2823 {
2824 if (info->priv != NULL)
2825 {
2826 const std::string &name = get_remote_thread_info (info)->name;
2827 return !name.empty () ? name.c_str () : NULL;
2828 }
2829
2830 return NULL;
2831 }
2832
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
2839 /* WARNING: This threadref data structure comes from the remote O.S.,
2840 libstub protocol encoding, and remote.c. It is not particularly
2841 changable. */
2842
2843 /* Right now, the internal structure is int. We want it to be bigger.
2844 Plan to fix this. */
2845
2846 typedef int gdb_threadref; /* Internal GDB thread reference. */
2847
2848 /* gdb_ext_thread_info is an internal GDB data structure which is
2849 equivalent to the reply of the remote threadinfo packet. */
2850
2851 struct gdb_ext_thread_info
2852 {
2853 threadref threadid; /* External form of thread reference. */
2854 int active; /* Has state interesting to GDB?
2855 regs, stack. */
2856 char display[256]; /* Brief state display, name,
2857 blocked/suspended. */
2858 char shortname[32]; /* To be used to name threads. */
2859 char more_display[256]; /* Long info, statistics, queue depth,
2860 whatever. */
2861 };
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
2866 get_thread_info. FIXME: Make these TAG names more thread specific. */
2867
2868 #define TAG_THREADID 1
2869 #define TAG_EXISTS 2
2870 #define TAG_DISPLAY 4
2871 #define TAG_THREADNAME 8
2872 #define TAG_MOREDISPLAY 16
2873
2874 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2875
2876 static char *unpack_nibble (char *buf, int *val);
2877
2878 static char *unpack_byte (char *buf, int *value);
2879
2880 static char *pack_int (char *buf, int value);
2881
2882 static char *unpack_int (char *buf, int *value);
2883
2884 static char *unpack_string (char *src, char *dest, int length);
2885
2886 static char *pack_threadid (char *pkt, threadref *id);
2887
2888 static char *unpack_threadid (char *inbuf, threadref *id);
2889
2890 void int_to_threadref (threadref *id, int value);
2891
2892 static int threadref_to_int (threadref *ref);
2893
2894 static void copy_threadref (threadref *dest, threadref *src);
2895
2896 static int threadmatch (threadref *dest, threadref *src);
2897
2898 static char *pack_threadinfo_request (char *pkt, int mode,
2899 threadref *id);
2900
2901 static char *pack_threadlist_request (char *pkt, int startflag,
2902 int threadcount,
2903 threadref *nextthread);
2904
2905 static int remote_newthread_step (threadref *ref, void *context);
2906
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
2912 char *
2913 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
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 }
2926 tid = ptid_get_lwp (ptid);
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
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. */
2938
2939 static ptid_t
2940 read_ptid (const char *buf, const char **obuf)
2941 {
2942 const char *p = buf;
2943 const char *pp;
2944 ULONGEST pid = 0, tid = 0;
2945
2946 if (*p == 'p')
2947 {
2948 /* Multi-process ptid. */
2949 pp = unpack_varlen_hex (p + 1, &pid);
2950 if (*pp != '.')
2951 error (_("invalid remote ptid: %s"), p);
2952
2953 p = pp;
2954 pp = unpack_varlen_hex (p + 1, &tid);
2955 if (obuf)
2956 *obuf = pp;
2957 return ptid_build (pid, tid, 0);
2958 }
2959
2960 /* No multi-process. Just a tid. */
2961 pp = unpack_varlen_hex (p, &tid);
2962
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
2971 /* Since the stub is not sending a process id, then default to
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);
2979
2980 if (obuf)
2981 *obuf = pp;
2982 return ptid_build (pid, tid, 0);
2983 }
2984
2985 static int
2986 stubhex (int ch)
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
2997 static int
2998 stub_unpack_int (char *buff, int fieldlength)
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
3014 static char *
3015 unpack_nibble (char *buf, int *val)
3016 {
3017 *val = fromhex (*buf++);
3018 return buf;
3019 }
3020
3021 static char *
3022 unpack_byte (char *buf, int *value)
3023 {
3024 *value = stub_unpack_int (buf, 2);
3025 return buf + 2;
3026 }
3027
3028 static char *
3029 pack_int (char *buf, int value)
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
3038 static char *
3039 unpack_int (char *buf, int *value)
3040 {
3041 *value = stub_unpack_int (buf, 8);
3042 return buf + 8;
3043 }
3044
3045 #if 0 /* Currently unused, uncomment when needed. */
3046 static char *pack_string (char *pkt, char *string);
3047
3048 static char *
3049 pack_string (char *pkt, char *string)
3050 {
3051 char ch;
3052 int len;
3053
3054 len = strlen (string);
3055 if (len > 200)
3056 len = 200; /* Bigger than most GDB packets, junk??? */
3057 pkt = pack_hex_byte (pkt, len);
3058 while (len-- > 0)
3059 {
3060 ch = *string++;
3061 if ((ch == '\0') || (ch == '#'))
3062 ch = '*'; /* Protect encapsulation. */
3063 *pkt++ = ch;
3064 }
3065 return pkt;
3066 }
3067 #endif /* 0 (unused) */
3068
3069 static char *
3070 unpack_string (char *src, char *dest, int length)
3071 {
3072 while (length--)
3073 *dest++ = *src++;
3074 *dest = '\0';
3075 return src;
3076 }
3077
3078 static char *
3079 pack_threadid (char *pkt, threadref *id)
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
3092 static char *
3093 unpack_threadid (char *inbuf, threadref *id)
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
3111 ints. This is due to a mismatch of specifications. We would like
3112 to use 64bit thread references internally. This is an adapter
3113 function. */
3114
3115 void
3116 int_to_threadref (threadref *id, int value)
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
3132 static int
3133 threadref_to_int (threadref *ref)
3134 {
3135 int i, value = 0;
3136 unsigned char *scan;
3137
3138 scan = *ref;
3139 scan += 4;
3140 i = 4;
3141 while (i-- > 0)
3142 value = (value << 8) | ((*scan++) & 0xff);
3143 return value;
3144 }
3145
3146 static void
3147 copy_threadref (threadref *dest, threadref *src)
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
3159 static int
3160 threadmatch (threadref *dest, threadref *src)
3161 {
3162 /* Things are broken right now, so just assume we got a match. */
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 /*
3178 threadid:1, # always request threadid
3179 context_exists:2,
3180 display:4,
3181 unique_name:8,
3182 more_display:16
3183 */
3184
3185 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3186
3187 static char *
3188 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3189 {
3190 *pkt++ = 'q'; /* Info Query */
3191 *pkt++ = 'P'; /* process or thread info */
3192 pkt = pack_int (pkt, mode); /* mode */
3193 pkt = pack_threadid (pkt, id); /* threadid */
3194 *pkt = '\0'; /* terminate */
3195 return pkt;
3196 }
3197
3198 /* These values tag the fields in a thread info response packet. */
3199 /* Tagging the fields allows us to request specific fields and to
3200 add more fields as time goes by. */
3201
3202 #define TAG_THREADID 1 /* Echo the thread identifier. */
3203 #define TAG_EXISTS 2 /* Is this process defined enough to
3204 fetch registers and its stack? */
3205 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3206 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3207 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3208 the process. */
3209
3210 int
3211 remote_target::remote_unpack_thread_info_response (char *pkt,
3212 threadref *expectedref,
3213 gdb_ext_thread_info *info)
3214 {
3215 struct remote_state *rs = get_remote_state ();
3216 int mask, length;
3217 int tag;
3218 threadref ref;
3219 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
3220 int retval = 1;
3221
3222 /* info->threadid = 0; FIXME: implement zero_threadref. */
3223 info->active = 0;
3224 info->display[0] = '\0';
3225 info->shortname[0] = '\0';
3226 info->more_display[0] = '\0';
3227
3228 /* Assume the characters indicating the packet type have been
3229 stripped. */
3230 pkt = unpack_int (pkt, &mask); /* arg mask */
3231 pkt = unpack_threadid (pkt, &ref);
3232
3233 if (mask == 0)
3234 warning (_("Incomplete response to threadinfo request."));
3235 if (!threadmatch (&ref, expectedref))
3236 { /* This is an answer to a different request. */
3237 warning (_("ERROR RMT Thread info mismatch."));
3238 return 0;
3239 }
3240 copy_threadref (&info->threadid, &ref);
3241
3242 /* Loop on tagged fields , try to bail if somthing goes wrong. */
3243
3244 /* Packets are terminated with nulls. */
3245 while ((pkt < limit) && mask && *pkt)
3246 {
3247 pkt = unpack_int (pkt, &tag); /* tag */
3248 pkt = unpack_byte (pkt, &length); /* length */
3249 if (!(tag & mask)) /* Tags out of synch with mask. */
3250 {
3251 warning (_("ERROR RMT: threadinfo tag mismatch."));
3252 retval = 0;
3253 break;
3254 }
3255 if (tag == TAG_THREADID)
3256 {
3257 if (length != 16)
3258 {
3259 warning (_("ERROR RMT: length of threadid is not 16."));
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 {
3274 warning (_("ERROR RMT: 'exists' length too long."));
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 }
3298 warning (_("ERROR RMT: unknown thread info tag."));
3299 break; /* Not a tag we know about. */
3300 }
3301 return retval;
3302 }
3303
3304 int
3305 remote_target::remote_get_threadinfo (threadref *threadid,
3306 int fieldset,
3307 gdb_ext_thread_info *info)
3308 {
3309 struct remote_state *rs = get_remote_state ();
3310 int result;
3311
3312 pack_threadinfo_request (rs->buf, fieldset, threadid);
3313 putpkt (rs->buf);
3314 getpkt (&rs->buf, &rs->buf_size, 0);
3315
3316 if (rs->buf[0] == '\0')
3317 return 0;
3318
3319 result = remote_unpack_thread_info_response (rs->buf + 2,
3320 threadid, info);
3321 return result;
3322 }
3323
3324 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3325
3326 static char *
3327 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3328 threadref *nextthread)
3329 {
3330 *pkt++ = 'q'; /* info query packet */
3331 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3332 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
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
3341 int
3342 remote_target::parse_threadlist_response (char *pkt, int result_limit,
3343 threadref *original_echo,
3344 threadref *resultlist,
3345 int *doneflag)
3346 {
3347 struct remote_state *rs = get_remote_state ();
3348 char *limit;
3349 int count, resultcount, done;
3350
3351 resultcount = 0;
3352 /* Assume the 'q' and 'M chars have been stripped. */
3353 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3354 /* done parse past here */
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
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
3373 int
3374 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3375 int result_limit, int *done, int *result_count,
3376 threadref *threadlist)
3377 {
3378 struct remote_state *rs = get_remote_state ();
3379 int result = 1;
3380
3381 /* Trancate result limit to be smaller than the packet size. */
3382 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3383 >= get_remote_packet_size ())
3384 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3385
3386 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3387 putpkt (rs->buf);
3388 getpkt (&rs->buf, &rs->buf_size, 0);
3389 if (*rs->buf == '\0')
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);
3398
3399 if (!threadmatch (&rs->echo_nextthread, nextthread))
3400 {
3401 /* FIXME: This is a good reason to drop the packet. */
3402 /* Possably, there is a duplicate response. */
3403 /* Possabilities :
3404 retransmit immediatly - race conditions
3405 retransmit after timeout - yes
3406 exit
3407 wait for packet, then exit
3408 */
3409 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3410 return 0; /* I choose simply exiting. */
3411 }
3412 if (*result_count <= 0)
3413 {
3414 if (*done != 1)
3415 {
3416 warning (_("RMT ERROR : failed to get remote thread list."));
3417 result = 0;
3418 }
3419 return result; /* break; */
3420 }
3421 if (*result_count > result_limit)
3422 {
3423 *result_count = 0;
3424 warning (_("RMT ERROR: threadlist response longer than requested."));
3425 return 0;
3426 }
3427 return result;
3428 }
3429
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. */
3435
3436 int
3437 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3438 void *context, int looplimit)
3439 {
3440 struct remote_state *rs = get_remote_state ();
3441 int done, i, result_count;
3442 int startflag = 1;
3443 int result = 1;
3444 int loopcount = 0;
3445
3446 done = 0;
3447 while (!done)
3448 {
3449 if (loopcount++ > looplimit)
3450 {
3451 result = 0;
3452 warning (_("Remote fetch threadlist -infinite loop-."));
3453 break;
3454 }
3455 result = remote_get_threadlist (startflag, &rs->nextthread,
3456 MAXTHREADLISTRESULTS,
3457 &done, &result_count,
3458 rs->resultthreadlist);
3459 if (result <= 0)
3460 break;
3461 /* Clear for later iterations. */
3462 startflag = 0;
3463 /* Setup to resume next batch of thread references, set nextthread. */
3464 if (result_count >= 1)
3465 copy_threadref (&rs->nextthread,
3466 &rs->resultthreadlist[result_count - 1]);
3467 i = 0;
3468 while (result_count--)
3469 {
3470 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3471 {
3472 result = 0;
3473 break;
3474 }
3475 }
3476 }
3477 return result;
3478 }
3479
3480 /* A thread found on the remote target. */
3481
3482 struct thread_item
3483 {
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
3493 /* The thread's PTID. */
3494 ptid_t ptid;
3495
3496 /* The thread's extra info. */
3497 std::string extra;
3498
3499 /* The thread's name. */
3500 std::string name;
3501
3502 /* The core the thread was running on. -1 if not known. */
3503 int core = -1;
3504
3505 /* The thread handle associated with the thread. */
3506 gdb::byte_vector thread_handle;
3507 };
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
3513 struct threads_listing_context
3514 {
3515 /* Return true if this object contains an entry for a thread with ptid
3516 PTID. */
3517
3518 bool contains_thread (ptid_t ptid) const
3519 {
3520 auto match_ptid = [&] (const thread_item &item)
3521 {
3522 return item.ptid == ptid;
3523 };
3524
3525 auto it = std::find_if (this->items.begin (),
3526 this->items.end (),
3527 match_ptid);
3528
3529 return it != this->items.end ();
3530 }
3531
3532 /* Remove the thread with ptid PTID. */
3533
3534 void remove_thread (ptid_t ptid)
3535 {
3536 auto match_ptid = [&] (const thread_item &item)
3537 {
3538 return item.ptid == ptid;
3539 };
3540
3541 auto it = std::remove_if (this->items.begin (),
3542 this->items.end (),
3543 match_ptid);
3544
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 };
3552
3553 static int
3554 remote_newthread_step (threadref *ref, void *data)
3555 {
3556 struct threads_listing_context *context
3557 = (struct threads_listing_context *) data;
3558 int pid = inferior_ptid.pid ();
3559 int lwp = threadref_to_int (ref);
3560 ptid_t ptid (pid, lwp);
3561
3562 context->items.emplace_back (ptid);
3563
3564 return 1; /* continue iterator */
3565 }
3566
3567 #define CRAZY_MAX_THREADS 1000
3568
3569 ptid_t
3570 remote_target::remote_current_thread (ptid_t oldpid)
3571 {
3572 struct remote_state *rs = get_remote_state ();
3573
3574 putpkt ("qC");
3575 getpkt (&rs->buf, &rs->buf_size, 0);
3576 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3577 {
3578 const char *obuf;
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 }
3588 else
3589 return oldpid;
3590 }
3591
3592 /* List remote threads using the deprecated qL packet. */
3593
3594 int
3595 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3596 {
3597 if (remote_threadlist_iterator (remote_newthread_step, context,
3598 CRAZY_MAX_THREADS) >= 0)
3599 return 1;
3600
3601 return 0;
3602 }
3603
3604 #if defined(HAVE_LIBEXPAT)
3605
3606 static void
3607 start_thread (struct gdb_xml_parser *parser,
3608 const struct gdb_xml_element *element,
3609 void *user_data,
3610 std::vector<gdb_xml_value> &attributes)
3611 {
3612 struct threads_listing_context *data
3613 = (struct threads_listing_context *) user_data;
3614 struct gdb_xml_value *attr;
3615
3616 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3617 ptid_t ptid = read_ptid (id, NULL);
3618
3619 data->items.emplace_back (ptid);
3620 thread_item &item = data->items.back ();
3621
3622 attr = xml_find_attribute (attributes, "core");
3623 if (attr != NULL)
3624 item.core = *(ULONGEST *) attr->value.get ();
3625
3626 attr = xml_find_attribute (attributes, "name");
3627 if (attr != NULL)
3628 item.name = (const char *) attr->value.get ();
3629
3630 attr = xml_find_attribute (attributes, "handle");
3631 if (attr != NULL)
3632 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3633 }
3634
3635 static void
3636 end_thread (struct gdb_xml_parser *parser,
3637 const struct gdb_xml_element *element,
3638 void *user_data, const char *body_text)
3639 {
3640 struct threads_listing_context *data
3641 = (struct threads_listing_context *) user_data;
3642
3643 if (body_text != NULL && *body_text != '\0')
3644 data->items.back ().extra = body_text;
3645 }
3646
3647 const 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 },
3650 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3651 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3652 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3653 };
3654
3655 const struct gdb_xml_element thread_children[] = {
3656 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3657 };
3658
3659 const 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
3666 const 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
3674 /* List remote threads using qXfer:threads:read. */
3675
3676 int
3677 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3678 {
3679 #if defined(HAVE_LIBEXPAT)
3680 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3681 {
3682 gdb::optional<gdb::char_vector> xml
3683 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3684
3685 if (xml && (*xml)[0] != '\0')
3686 {
3687 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3688 threads_elements, xml->data (), context);
3689 }
3690
3691 return 1;
3692 }
3693 #endif
3694
3695 return 0;
3696 }
3697
3698 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3699
3700 int
3701 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3702 {
3703 struct remote_state *rs = get_remote_state ();
3704
3705 if (rs->use_threadinfo_query)
3706 {
3707 const char *bufp;
3708
3709 putpkt ("qfThreadInfo");
3710 getpkt (&rs->buf, &rs->buf_size, 0);
3711 bufp = rs->buf;
3712 if (bufp[0] != '\0') /* q packet recognized */
3713 {
3714 while (*bufp++ == 'm') /* reply contains one or more TID */
3715 {
3716 do
3717 {
3718 ptid_t ptid = read_ptid (bufp, &bufp);
3719 context->items.emplace_back (ptid);
3720 }
3721 while (*bufp++ == ','); /* comma-separated list */
3722 putpkt ("qsThreadInfo");
3723 getpkt (&rs->buf, &rs->buf_size, 0);
3724 bufp = rs->buf;
3725 }
3726 return 1;
3727 }
3728 else
3729 {
3730 /* Packet not recognized. */
3731 rs->use_threadinfo_query = 0;
3732 }
3733 }
3734
3735 return 0;
3736 }
3737
3738 /* Implement the to_update_thread_list function for the remote
3739 targets. */
3740
3741 void
3742 remote_target::update_thread_list ()
3743 {
3744 struct threads_listing_context context;
3745 int got_list = 0;
3746
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. */
3750 if (remote_get_threads_with_qxfer (&context)
3751 || remote_get_threads_with_qthreadinfo (&context)
3752 || remote_get_threads_with_ql (&context))
3753 {
3754 struct thread_info *tp, *tmp;
3755
3756 got_list = 1;
3757
3758 if (context.items.empty ()
3759 && remote_thread_always_alive (inferior_ptid))
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. */
3766 return;
3767 }
3768
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. */
3772 ALL_THREADS_SAFE (tp, tmp)
3773 {
3774 if (!context.contains_thread (tp->ptid))
3775 {
3776 /* Not found. */
3777 delete_thread (tp->ptid);
3778 }
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);
3785
3786 /* And now add threads we don't know about yet to our list. */
3787 for (thread_item &item : context.items)
3788 {
3789 if (item.ptid != null_ptid)
3790 {
3791 /* In non-stop mode, we assume new found threads are
3792 executing until proven otherwise with a stop reply.
3793 In all-stop, we can only get here if all threads are
3794 stopped. */
3795 int executing = target_is_non_stop_p () ? 1 : 0;
3796
3797 remote_notice_new_inferior (item.ptid, executing);
3798
3799 remote_thread_info *info = get_remote_thread_info (item.ptid);
3800 info->core = item.core;
3801 info->extra = std::move (item.extra);
3802 info->name = std::move (item.name);
3803 info->thread_handle = std::move (item.thread_handle);
3804 }
3805 }
3806 }
3807
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 }
3816 }
3817
3818 /*
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.
3823 *
3824 * Optional: targets are not required to implement this function.
3825 */
3826
3827 const char *
3828 remote_target::extra_thread_info (thread_info *tp)
3829 {
3830 struct remote_state *rs = get_remote_state ();
3831 int result;
3832 int set;
3833 threadref id;
3834 struct gdb_ext_thread_info threadinfo;
3835 static char display_buf[100]; /* arbitrary... */
3836 int n = 0; /* position in display_buf */
3837
3838 if (rs->remote_desc == 0) /* paranoia */
3839 internal_error (__FILE__, __LINE__,
3840 _("remote_threads_extra_info"));
3841
3842 if (ptid_equal (tp->ptid, magic_null_ptid)
3843 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3844 /* This is the main thread which was added by GDB. The remote
3845 server doesn't know about it. */
3846 return NULL;
3847
3848 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3849 {
3850 struct thread_info *info = find_thread_ptid (tp->ptid);
3851
3852 if (info != NULL && info->priv != NULL)
3853 {
3854 const std::string &extra = get_remote_thread_info (info)->extra;
3855 return !extra.empty () ? extra.c_str () : NULL;
3856 }
3857 else
3858 return NULL;
3859 }
3860
3861 if (rs->use_threadextra_query)
3862 {
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
3870 putpkt (rs->buf);
3871 getpkt (&rs->buf, &rs->buf_size, 0);
3872 if (rs->buf[0] != 0)
3873 {
3874 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3875 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3876 display_buf [result] = '\0';
3877 return display_buf;
3878 }
3879 }
3880
3881 /* If the above query fails, fall back to the old method. */
3882 rs->use_threadextra_query = 0;
3883 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3884 | TAG_MOREDISPLAY | TAG_DISPLAY;
3885 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3886 if (remote_get_threadinfo (&id, set, &threadinfo))
3887 if (threadinfo.active)
3888 {
3889 if (*threadinfo.shortname)
3890 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3891 " Name: %s,", threadinfo.shortname);
3892 if (*threadinfo.display)
3893 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3894 " State: %s,", threadinfo.display);
3895 if (*threadinfo.more_display)
3896 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3897 " Priority: %s", threadinfo.more_display);
3898
3899 if (n > 0)
3900 {
3901 /* For purely cosmetic reasons, clear up trailing commas. */
3902 if (',' == display_buf[n-1])
3903 display_buf[n-1] = ' ';
3904 return display_buf;
3905 }
3906 }
3907 return NULL;
3908 }
3909 \f
3910
3911 bool
3912 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3913 struct static_tracepoint_marker *marker)
3914 {
3915 struct remote_state *rs = get_remote_state ();
3916 char *p = rs->buf;
3917
3918 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
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 {
3930 parse_static_tracepoint_marker_definition (p, NULL, marker);
3931 return true;
3932 }
3933
3934 return false;
3935 }
3936
3937 std::vector<static_tracepoint_marker>
3938 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3939 {
3940 struct remote_state *rs = get_remote_state ();
3941 std::vector<static_tracepoint_marker> markers;
3942 const char *p;
3943 static_tracepoint_marker marker;
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
3953 while (*p++ == 'm')
3954 {
3955 do
3956 {
3957 parse_static_tracepoint_marker_definition (p, &p, &marker);
3958
3959 if (strid == NULL || marker.str_id == strid)
3960 markers.push_back (std::move (marker));
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
3969 return markers;
3970 }
3971
3972 \f
3973 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3974
3975 ptid_t
3976 remote_target::get_ada_task_ptid (long lwp, long thread)
3977 {
3978 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3979 }
3980 \f
3981
3982 /* Restart the remote side; this is an extended protocol operation. */
3983
3984 void
3985 remote_target::extended_remote_restart ()
3986 {
3987 struct remote_state *rs = get_remote_state ();
3988
3989 /* Send the restart command; for reasons I don't understand the
3990 remote side really expects a number after the "R". */
3991 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3992 putpkt (rs->buf);
3993
3994 remote_fileio_reset ();
3995 }
3996 \f
3997 /* Clean up connection to a remote debugger. */
3998
3999 void
4000 remote_target::close ()
4001 {
4002 /* Make sure we leave stdin registered in the event loop. */
4003 terminal_ours ();
4004
4005 /* We don't have a connection to the remote stub anymore. Get rid
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). */
4009 inferior_ptid = null_ptid;
4010 discard_all_inferiors ();
4011
4012 trace_reset_local_state ();
4013
4014 delete this;
4015 }
4016
4017 remote_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
4029 everything of this target. */
4030 discard_pending_stop_replies_in_queue ();
4031
4032 if (rs->remote_async_inferior_event_token)
4033 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4034
4035 remote_notif_state_xfree (rs->notif_state);
4036 }
4037
4038 /* Query the remote side for the text, data and bss offsets. */
4039
4040 void
4041 remote_target::get_offsets ()
4042 {
4043 struct remote_state *rs = get_remote_state ();
4044 char *buf;
4045 char *ptr;
4046 int lose, num_segments = 0, do_sections, do_segments;
4047 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4048 struct section_offsets *offs;
4049 struct symfile_segment_data *data;
4050
4051 if (symfile_objfile == NULL)
4052 return;
4053
4054 putpkt ("qOffsets");
4055 getpkt (&rs->buf, &rs->buf_size, 0);
4056 buf = rs->buf;
4057
4058 if (buf[0] == '\000')
4059 return; /* Return silently. Stub doesn't support
4060 this command. */
4061 if (buf[0] == 'E')
4062 {
4063 warning (_("Remote failure reply: %s"), buf);
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
4075 if (startswith (ptr, "Text="))
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++);
4081
4082 if (startswith (ptr, ";Data="))
4083 {
4084 ptr += 6;
4085 while (*ptr && *ptr != ';')
4086 data_addr = (data_addr << 4) + fromhex (*ptr++);
4087 }
4088 else
4089 lose = 1;
4090
4091 if (!lose && startswith (ptr, ";Bss="))
4092 {
4093 ptr += 5;
4094 while (*ptr && *ptr != ';')
4095 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4096
4097 if (bss_addr != data_addr)
4098 warning (_("Target reported unsupported offsets: %s"), buf);
4099 }
4100 else
4101 lose = 1;
4102 }
4103 else if (startswith (ptr, "TextSeg="))
4104 {
4105 ptr += 8;
4106 /* Don't use strtol, could lose on big values. */
4107 while (*ptr && *ptr != ';')
4108 text_addr = (text_addr << 4) + fromhex (*ptr++);
4109 num_segments = 1;
4110
4111 if (startswith (ptr, ";DataSeg="))
4112 {
4113 ptr += 9;
4114 while (*ptr && *ptr != ';')
4115 data_addr = (data_addr << 4) + fromhex (*ptr++);
4116 num_segments++;
4117 }
4118 }
4119 else
4120 lose = 1;
4121
4122 if (lose)
4123 error (_("Malformed response to offset query, %s"), buf);
4124 else if (*ptr != '\0')
4125 warning (_("Target reported unsupported offsets: %s"), buf);
4126
4127 offs = ((struct section_offsets *)
4128 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
4129 memcpy (offs, symfile_objfile->section_offsets,
4130 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
4131
4132 data = get_symfile_segment_data (symfile_objfile->obfd);
4133 do_segments = (data != NULL);
4134 do_sections = num_segments == 0;
4135
4136 if (num_segments > 0)
4137 {
4138 segments[0] = text_addr;
4139 segments[1] = data_addr;
4140 }
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 }
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 }
4161 /* There's no way to relocate by segment. */
4162 else
4163 do_segments = 0;
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)
4171 error (_("Can not handle qOffsets TextSeg "
4172 "response with this symbol file"));
4173
4174 if (ret > 0)
4175 do_sections = 0;
4176 }
4177
4178 if (data)
4179 free_symfile_segment_data (data);
4180
4181 if (do_sections)
4182 {
4183 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4184
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. */
4189
4190 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4191 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4192 }
4193
4194 objfile_relocate (symfile_objfile, offs);
4195 }
4196
4197 /* Send interrupt_sequence to remote target. */
4198
4199 void
4200 remote_target::send_interrupt_sequence ()
4201 {
4202 struct remote_state *rs = get_remote_state ();
4203
4204 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4205 remote_serial_write ("\x03", 1);
4206 else if (interrupt_sequence_mode == interrupt_sequence_break)
4207 serial_send_break (rs->remote_desc);
4208 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4209 {
4210 serial_send_break (rs->remote_desc);
4211 remote_serial_write ("g", 1);
4212 }
4213 else
4214 internal_error (__FILE__, __LINE__,
4215 _("Invalid value for interrupt_sequence_mode: %s."),
4216 interrupt_sequence_mode);
4217 }
4218
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
4223 static ptid_t
4224 stop_reply_extract_thread (char *stop_reply)
4225 {
4226 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4227 {
4228 const char *p;
4229
4230 /* Txx r:val ; r:val (...) */
4231 p = &stop_reply[3];
4232
4233 /* Look for "register" named "thread". */
4234 while (*p != '\0')
4235 {
4236 const char *p1;
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
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
4263 ptid_t
4264 remote_target::get_current_thread (char *wait_status)
4265 {
4266 ptid_t ptid = null_ptid;
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
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
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. */
4289
4290 void
4291 remote_target::add_current_inferior_and_thread (char *wait_status)
4292 {
4293 struct remote_state *rs = get_remote_state ();
4294 int fake_pid_p = 0;
4295
4296 inferior_ptid = null_ptid;
4297
4298 /* Now, if we have thread information, update inferior_ptid. */
4299 ptid_t curr_ptid = get_current_thread (wait_status);
4300
4301 if (curr_ptid != null_ptid)
4302 {
4303 if (!remote_multi_process_p (rs))
4304 fake_pid_p = 1;
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. */
4312 curr_ptid = magic_null_ptid;
4313 fake_pid_p = 1;
4314 }
4315
4316 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
4317
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);
4323 }
4324
4325 /* Print info about a thread that was found already stopped on
4326 connection. */
4327
4328 static void
4329 print_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))
4344 gdb::observers::signal_received.notify (sig);
4345 }
4346 gdb::observers::normal_stop.notify (NULL, 1);
4347 }
4348
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
4354 void
4355 remote_target::process_initial_stop_replies (int from_tty)
4356 {
4357 int pending_stop_replies = stop_reply_queue_length ();
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;
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;
4371 struct thread_info *thread;
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
4400 thread = find_thread_ptid (event_ptid);
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;
4410 thread->suspend.stop_signal = sig;
4411 ws.value.sig = sig;
4412 }
4413
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);
4422 get_remote_thread_info (thread)->vcont_resumed = 0;
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;
4456
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 }
4464 }
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 {
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
4479 if (selected == NULL
4480 && thread->suspend.waitstatus_pending_p)
4481 selected = thread;
4482
4483 if (lowest_stopped == NULL
4484 || thread->inf->num < lowest_stopped->inf->num
4485 || thread->per_inf_num < lowest_stopped->per_inf_num)
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);
4509 }
4510
4511 /* Start the remote connection and sync state. */
4512
4513 void
4514 remote_target::start_remote (int from_tty, int extended_p)
4515 {
4516 struct remote_state *rs = get_remote_state ();
4517 struct packet_config *noack_config;
4518 char *wait_status = NULL;
4519
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
4528 QUIT;
4529
4530 if (interrupt_on_connect)
4531 send_interrupt_sequence ();
4532
4533 /* Ack any packet which the remote side has already sent. */
4534 remote_serial_write ("+", 1);
4535
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
4541 /* If the stub wants to get a QAllow, compose one and send it. */
4542 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4543 set_permissions ();
4544
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
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];
4578 if (packet_config_support (noack_config) != PACKET_DISABLE)
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
4586 if (extended_p)
4587 {
4588 /* Tell the remote that we are using the extended protocol. */
4589 putpkt ("!");
4590 getpkt (&rs->buf, &rs->buf_size, 0);
4591 }
4592
4593 /* Let the target know which signals it is allowed to pass down to
4594 the program. */
4595 update_signals_program_target ();
4596
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
4601 /* Next, now that we know something about the target, update the
4602 address spaces in the program spaces. */
4603 update_address_spaces ();
4604
4605 /* On OSs where the list of libraries is global to all
4606 processes, we fetch them early. */
4607 if (gdbarch_has_global_solist (target_gdbarch ()))
4608 solib_add (NULL, from_tty, auto_solib_add);
4609
4610 if (target_is_non_stop_p ())
4611 {
4612 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4613 error (_("Non-stop mode requested, but remote "
4614 "does not support non-stop"));
4615
4616 putpkt ("QNonStop:1");
4617 getpkt (&rs->buf, &rs->buf_size, 0);
4618
4619 if (strcmp (rs->buf, "OK") != 0)
4620 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
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. */
4626 this->update_thread_list ();
4627 }
4628 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4629 {
4630 /* Don't assume that the stub can operate in all-stop mode.
4631 Request it explicitly. */
4632 putpkt ("QNonStop:0");
4633 getpkt (&rs->buf, &rs->buf_size, 0);
4634
4635 if (strcmp (rs->buf, "OK") != 0)
4636 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4637 }
4638
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. */
4642 if (get_trace_status (current_trace_status ()) != -1)
4643 {
4644 struct uploaded_tsv *uploaded_tsvs = NULL;
4645
4646 upload_trace_state_variables (&uploaded_tsvs);
4647 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4648 }
4649
4650 /* Check whether the target is running now. */
4651 putpkt ("?");
4652 getpkt (&rs->buf, &rs->buf_size, 0);
4653
4654 if (!target_is_non_stop_p ())
4655 {
4656 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4657 {
4658 if (!extended_p)
4659 error (_("The target is not running (try extended-remote?)"));
4660
4661 /* We're connected, but not running. Drop out before we
4662 call start_remote. */
4663 rs->starting_up = 0;
4664 return;
4665 }
4666 else
4667 {
4668 /* Save the reply for later. */
4669 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4670 strcpy (wait_status, rs->buf);
4671 }
4672
4673 /* Fetch thread list. */
4674 target_update_thread_list ();
4675
4676 /* Let the stub know that we want it to return the thread. */
4677 set_continue_thread (minus_one_ptid);
4678
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. */
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
4705 inferior_ptid = thread_list->ptid;
4706 }
4707 }
4708
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
4720 get_offsets (); /* Get text, data & bss offsets. */
4721
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. */
4726 if (remote_read_description_p (this)
4727 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4728 {
4729 target_clear_description ();
4730 target_find_description ();
4731 }
4732
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
4738 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4739 }
4740 else
4741 {
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
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 {
4756 struct notif_client *notif = &notif_client_stop;
4757
4758 /* remote_notif_get_pending_replies acks this one, and gets
4759 the rest out. */
4760 rs->notif_state->pending_event[notif_client_stop.id]
4761 = remote_notif_parse (this, notif, rs->buf);
4762 remote_notif_get_pending_events (notif);
4763 }
4764
4765 if (thread_count () == 0)
4766 {
4767 if (!extended_p)
4768 error (_("The target is not running (try extended-remote?)"));
4769
4770 /* We're connected, but not running. Drop out before we
4771 call start_remote. */
4772 rs->starting_up = 0;
4773 return;
4774 }
4775
4776 /* In non-stop mode, any cached wait status will be stored in
4777 the stop reply queue. */
4778 gdb_assert (wait_status == NULL);
4779
4780 /* Report all signals during attach/startup. */
4781 pass_signals (0, NULL);
4782
4783 /* If there are already stopped threads, mark them stopped and
4784 report their stops before giving the prompt to the user. */
4785 process_initial_stop_replies (from_tty);
4786
4787 if (target_can_async_p ())
4788 target_async (1);
4789 }
4790
4791 /* If we connected to a live target, do some additional setup. */
4792 if (target_has_execution)
4793 {
4794 if (symfile_objfile) /* No use without a symbol-file. */
4795 remote_check_symbols ();
4796 }
4797
4798 /* Possibly the target has been engaged in a trace run started
4799 previously; find out where things are at. */
4800 if (get_trace_status (current_trace_status ()) != -1)
4801 {
4802 struct uploaded_tp *uploaded_tps = NULL;
4803
4804 if (current_trace_status ()->running)
4805 printf_filtered (_("Trace is already running on the target.\n"));
4806
4807 upload_tracepoints (&uploaded_tps);
4808
4809 merge_uploaded_tracepoints (&uploaded_tps);
4810 }
4811
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
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
4822 /* Maybe breakpoints are global and need to be inserted now. */
4823 if (breakpoints_should_be_inserted_now ())
4824 insert_breakpoints ();
4825 }
4826
4827 /* Open a connection to a remote debugger.
4828 NAME is the filename used for communication. */
4829
4830 void
4831 remote_target::open (const char *name, int from_tty)
4832 {
4833 open_1 (name, from_tty, 0);
4834 }
4835
4836 /* Open a connection to a remote debugger using the extended
4837 remote gdb protocol. NAME is the filename used for communication. */
4838
4839 void
4840 extended_remote_target::open (const char *name, int from_tty)
4841 {
4842 open_1 (name, from_tty, 1 /*extended_p */);
4843 }
4844
4845 /* Reset all packets back to "unknown support". Called when opening a
4846 new connection to a remote target. */
4847
4848 static void
4849 reset_all_packet_configs_support (void)
4850 {
4851 int i;
4852
4853 for (i = 0; i < PACKET_MAX; i++)
4854 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4855 }
4856
4857 /* Initialize all packet configs. */
4858
4859 static void
4860 init_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
4871 /* Symbol look-up. */
4872
4873 void
4874 remote_target::remote_check_symbols ()
4875 {
4876 char *msg, *reply, *tmp;
4877 int end;
4878 long reply_size;
4879 struct cleanup *old_chain;
4880
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
4889 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4890 return;
4891
4892 /* Make sure the remote is pointing at the right process. Note
4893 there's no way to select "no process". */
4894 set_general_process ();
4895
4896 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4897 because we need both at the same time. */
4898 msg = (char *) xmalloc (get_remote_packet_size ());
4899 old_chain = make_cleanup (xfree, msg);
4900 reply = (char *) xmalloc (get_remote_packet_size ());
4901 make_cleanup (free_current_contents, &reply);
4902 reply_size = get_remote_packet_size ();
4903
4904 /* Invite target to request symbol lookups. */
4905
4906 putpkt ("qSymbol::");
4907 getpkt (&reply, &reply_size, 0);
4908 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4909
4910 while (startswith (reply, "qSymbol:"))
4911 {
4912 struct bound_minimal_symbol sym;
4913
4914 tmp = &reply[8];
4915 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4916 msg[end] = '\0';
4917 sym = lookup_minimal_symbol (msg, NULL, NULL);
4918 if (sym.minsym == NULL)
4919 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4920 else
4921 {
4922 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4923 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4924
4925 /* If this is a function address, return the start of code
4926 instead of any data function descriptor. */
4927 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4928 sym_addr,
4929 target_stack);
4930
4931 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4932 phex_nz (sym_addr, addr_size), &reply[8]);
4933 }
4934
4935 putpkt (msg);
4936 getpkt (&reply, &reply_size, 0);
4937 }
4938
4939 do_cleanups (old_chain);
4940 }
4941
4942 static struct serial *
4943 remote_serial_open (const char *name)
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. */
4951 if (!udp_warning && startswith (name, "udp:"))
4952 {
4953 warning (_("The remote protocol may be unreliable over UDP.\n"
4954 "Some events may be lost, rendering further debugging "
4955 "impossible."));
4956 udp_warning = 1;
4957 }
4958
4959 return serial_open (name);
4960 }
4961
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
4971 void
4972 remote_target::set_permissions ()
4973 {
4974 struct remote_state *rs = get_remote_state ();
4975
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);
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)
4989 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4990 }
4991
4992 /* This type describes each known response to the qSupported
4993 packet. */
4994 struct 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. */
5011 void (*func) (remote_target *remote, const struct protocol_feature *,
5012 enum packet_support, const char *);
5013
5014 /* The corresponding packet for this feature. Only used if
5015 FUNC is remote_supported_packet. */
5016 int packet;
5017 };
5018
5019 static void
5020 remote_supported_packet (remote_target *remote,
5021 const struct protocol_feature *feature,
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
5032 remote_protocol_packets[feature->packet].support = support;
5033 }
5034
5035 void
5036 remote_target::remote_packet_size (const protocol_feature *feature,
5037 enum packet_support support, const char *value)
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
5063 /* Record the new maximum packet size. */
5064 rs->explicit_packet_size = packet_size;
5065 }
5066
5067 void
5068 remote_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
5074 static const struct protocol_feature remote_protocol_features[] = {
5075 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5076 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5077 PACKET_qXfer_auxv },
5078 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5079 PACKET_qXfer_exec_file },
5080 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5081 PACKET_qXfer_features },
5082 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5083 PACKET_qXfer_libraries },
5084 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5085 PACKET_qXfer_libraries_svr4 },
5086 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5087 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5088 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5089 PACKET_qXfer_memory_map },
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 },
5094 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5095 PACKET_qXfer_osdata },
5096 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5097 PACKET_qXfer_threads },
5098 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5099 PACKET_qXfer_traceframe_info },
5100 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5101 PACKET_QPassSignals },
5102 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5103 PACKET_QCatchSyscalls },
5104 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5105 PACKET_QProgramSignals },
5106 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5107 PACKET_QSetWorkingDir },
5108 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5109 PACKET_QStartupWithShell },
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 },
5116 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5117 PACKET_QStartNoAckMode },
5118 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5119 PACKET_multiprocess_feature },
5120 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
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 },
5125 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5126 PACKET_ConditionalTracepoints },
5127 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5128 PACKET_ConditionalBreakpoints },
5129 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5130 PACKET_BreakpointCommands },
5131 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5132 PACKET_FastTracepoints },
5133 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5134 PACKET_StaticTracepoints },
5135 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5136 PACKET_InstallInTrace},
5137 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5138 PACKET_DisconnectedTracing_feature },
5139 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5140 PACKET_bc },
5141 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5142 PACKET_bs },
5143 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5144 PACKET_TracepointSource },
5145 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5146 PACKET_QAllow },
5147 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5148 PACKET_EnableDisableTracepoints_feature },
5149 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5150 PACKET_qXfer_fdpic },
5151 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5152 PACKET_qXfer_uib },
5153 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5154 PACKET_QDisableRandomization },
5155 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5156 { "QTBuffer:size", PACKET_DISABLE,
5157 remote_supported_packet, PACKET_QTBuffer_size},
5158 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5159 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5160 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5161 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5162 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5163 PACKET_qXfer_btrace },
5164 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5165 PACKET_qXfer_btrace_conf },
5166 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5167 PACKET_Qbtrace_conf_bts_size },
5168 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5169 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
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 },
5174 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5175 PACKET_exec_event_feature },
5176 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5177 PACKET_Qbtrace_conf_pt_size },
5178 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5179 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5180 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5181 };
5182
5183 static char *remote_support_xml;
5184
5185 /* Register string appended to "xmlRegisters=" in qSupported query. */
5186
5187 void
5188 register_remote_support_xml (const char *xml)
5189 {
5190 #if defined(HAVE_LIBEXPAT)
5191 if (remote_support_xml == NULL)
5192 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
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
5210 remote_support_xml = reconcat (remote_support_xml,
5211 remote_support_xml, ",", xml,
5212 (char *) NULL);
5213 }
5214 #endif
5215 }
5216
5217 static void
5218 remote_query_supported_append (std::string *msg, const char *append)
5219 {
5220 if (!msg->empty ())
5221 msg->append (";");
5222 msg->append (append);
5223 }
5224
5225 void
5226 remote_target::remote_query_supported ()
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;
5241 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5242 {
5243 std::string q;
5244
5245 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5246 remote_query_supported_append (&q, "multiprocess+");
5247
5248 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5249 remote_query_supported_append (&q, "swbreak+");
5250 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5251 remote_query_supported_append (&q, "hwbreak+");
5252
5253 remote_query_supported_append (&q, "qRelocInsn+");
5254
5255 if (packet_set_cmd_state (PACKET_fork_event_feature)
5256 != AUTO_BOOLEAN_FALSE)
5257 remote_query_supported_append (&q, "fork-events+");
5258 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5259 != AUTO_BOOLEAN_FALSE)
5260 remote_query_supported_append (&q, "vfork-events+");
5261 if (packet_set_cmd_state (PACKET_exec_event_feature)
5262 != AUTO_BOOLEAN_FALSE)
5263 remote_query_supported_append (&q, "exec-events+");
5264
5265 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5266 remote_query_supported_append (&q, "vContSupported+");
5267
5268 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5269 remote_query_supported_append (&q, "QThreadEvents+");
5270
5271 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5272 remote_query_supported_append (&q, "no-resumed+");
5273
5274 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5275 the qSupported:xmlRegisters=i386 handling. */
5276 if (remote_support_xml != NULL
5277 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5278 remote_query_supported_append (&q, remote_support_xml);
5279
5280 q = "qSupported:" + q;
5281 putpkt (q.c_str ());
5282
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 {
5315 *end = '\0';
5316 next = end + 1;
5317
5318 if (end == p)
5319 {
5320 warning (_("empty item in \"qSupported\" response"));
5321 continue;
5322 }
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:
5351 warning (_("unrecognized item \"%s\" "
5352 "in \"qSupported\" response"), p);
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];
5365 feature->func (this, feature, is_supported, value);
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;
5377 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
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];
5387 feature->func (this, feature, feature->default_support, NULL);
5388 }
5389 }
5390
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
5401 (target_terminal::is_ours is false) with a synchronous resume
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
5414 void
5415 remote_target::remote_serial_quit_handler ()
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. */
5432 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5433 interrupt_query ();
5434 /* All-stop protocol, and blocked waiting for stop reply. Send
5435 an interrupt request. */
5436 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5437 target_interrupt ();
5438 else
5439 rs->got_ctrlc_during_io = 1;
5440 }
5441 }
5442
5443 /* The remote_target that is current while the quit handler is
5444 overridden with remote_serial_quit_handler. */
5445 static remote_target *curr_quit_handler_target;
5446
5447 static void
5448 remote_serial_quit_handler ()
5449 {
5450 curr_quit_handler_target->remote_serial_quit_handler ();
5451 }
5452
5453 /* Remove any of the remote.c targets from target stack. Upper targets depend
5454 on it so remove them first. */
5455
5456 static void
5457 remote_unpush_target (void)
5458 {
5459 pop_all_targets_at_and_above (process_stratum);
5460 }
5461
5462 static void
5463 remote_unpush_and_throw (void)
5464 {
5465 remote_unpush_target ();
5466 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5467 }
5468
5469 void
5470 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5471 {
5472 remote_target *curr_remote = get_current_remote_target ();
5473
5474 if (name == 0)
5475 error (_("To open a remote debug connection, you need to specify what\n"
5476 "serial device is attached to the remote system\n"
5477 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5478
5479 /* If we're connected to a running target, target_preopen will kill it.
5480 Ask this question first, before target_preopen has a chance to kill
5481 anything. */
5482 if (curr_remote != NULL && !have_inferiors ())
5483 {
5484 if (from_tty
5485 && !query (_("Already connected to a remote target. Disconnect? ")))
5486 error (_("Still connected."));
5487 }
5488
5489 /* Here the possibly existing remote target gets unpushed. */
5490 target_preopen (from_tty);
5491
5492 remote_fileio_reset ();
5493 reopen_exec_file ();
5494 reread_symbols ();
5495
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
5506 rs->remote_desc = remote_serial_open (name);
5507 if (!rs->remote_desc)
5508 perror_with_name (name);
5509
5510 if (baud_rate != -1)
5511 {
5512 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5513 {
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. */
5518 serial_close (rs->remote_desc);
5519 rs->remote_desc = NULL;
5520 perror_with_name (name);
5521 }
5522 }
5523
5524 serial_setparity (rs->remote_desc, serial_parity);
5525 serial_raw (rs->remote_desc);
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. */
5529 serial_flush_input (rs->remote_desc);
5530
5531 if (from_tty)
5532 {
5533 puts_filtered ("Remote debugging using ");
5534 puts_filtered (name);
5535 puts_filtered ("\n");
5536 }
5537
5538 /* Switch to using the remote target now. */
5539 push_target (remote);
5540 /* The target stack owns the target now. */
5541 target_holder.release ();
5542
5543 /* Register extra event sources in the event loop. */
5544 rs->remote_async_inferior_event_token
5545 = create_async_event_handler (remote_async_inferior_event_handler,
5546 remote);
5547 rs->notif_state = remote_notif_state_allocate (remote);
5548
5549 /* Reset the target state; these things will be queried either by
5550 remote_query_supported or as they are needed. */
5551 reset_all_packet_configs_support ();
5552 rs->cached_wait_status = 0;
5553 rs->explicit_packet_size = 0;
5554 rs->noack_mode = 0;
5555 rs->extended = extended_p;
5556 rs->waiting_for_stop_reply = 0;
5557 rs->ctrlc_pending_p = 0;
5558 rs->got_ctrlc_during_io = 0;
5559
5560 rs->general_thread = not_sent_ptid;
5561 rs->continue_thread = not_sent_ptid;
5562 rs->remote_traceframe_number = -1;
5563
5564 rs->last_resume_exec_dir = EXEC_FORWARD;
5565
5566 /* Probe for ability to use "ThreadInfo" query, as required. */
5567 rs->use_threadinfo_query = 1;
5568 rs->use_threadextra_query = 1;
5569
5570 rs->readahead_cache.invalidate ();
5571
5572 if (target_async_permitted)
5573 {
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
5576 requests. Unfortunately remote_start_remote() eventually calls
5577 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5578 around this. Eventually a mechanism that allows
5579 wait_for_inferior() to expect/get timeouts will be
5580 implemented. */
5581 rs->wait_forever_enabled_p = 0;
5582 }
5583
5584 /* First delete any symbols previously loaded from shared libraries. */
5585 no_shared_libraries (NULL, 0);
5586
5587 /* Start afresh. */
5588 init_thread_list ();
5589
5590 /* Start the remote connection. If error() or QUIT, discard this
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.
5596
5597 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5598 this function should return an error indication letting the
5599 caller restore the previous state. Unfortunately the command
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. */
5605 {
5606
5607 TRY
5608 {
5609 remote->start_remote (from_tty, extended_p);
5610 }
5611 CATCH (ex, RETURN_MASK_ALL)
5612 {
5613 /* Pop the partially set up target - unless something else did
5614 already before throwing the exception. */
5615 if (ex.error != TARGET_CLOSE_ERROR)
5616 remote_unpush_target ();
5617 throw_exception (ex);
5618 }
5619 END_CATCH
5620 }
5621
5622 remote_btrace_reset (rs);
5623
5624 if (target_async_permitted)
5625 rs->wait_forever_enabled_p = 1;
5626 }
5627
5628 /* Detach the specified process. */
5629
5630 void
5631 remote_target::remote_detach_pid (int pid)
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. */
5656
5657 void
5658 remote_target::remote_detach_1 (int from_tty, inferior *inf)
5659 {
5660 int pid = ptid_get_pid (inferior_ptid);
5661 struct remote_state *rs = get_remote_state ();
5662 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5663 int is_fork_parent;
5664
5665 if (!target_has_execution)
5666 error (_("No process to detach from."));
5667
5668 target_announce_detach (from_tty);
5669
5670 /* Tell the remote target to detach. */
5671 remote_detach_pid (pid);
5672
5673 /* Exit only if this is the only active inferior. */
5674 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5675 puts_filtered (_("Ending remote debugging.\n"));
5676
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)
5685 {
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));
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 }
5695 else
5696 {
5697 inferior_ptid = null_ptid;
5698 detach_inferior (pid);
5699 }
5700 }
5701
5702 void
5703 remote_target::detach (inferior *inf, int from_tty)
5704 {
5705 remote_detach_1 (from_tty, inf);
5706 }
5707
5708 void
5709 extended_remote_target::detach (inferior *inf, int from_tty)
5710 {
5711 remote_detach_1 (from_tty, inf);
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
5721 int
5722 remote_target::follow_fork (int follow_child, int detach_fork)
5723 {
5724 struct remote_state *rs = get_remote_state ();
5725 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5726
5727 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5728 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
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);
5746 }
5747 }
5748 return 0;
5749 }
5750
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
5757 void
5758 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
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
5768 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5769
5770 void
5771 remote_target::disconnect (const char *args, int from_tty)
5772 {
5773 if (args)
5774 error (_("Argument given to \"disconnect\" when remotely debugging."));
5775
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. */
5779 unpush_target (this);
5780 generic_mourn_inferior ();
5781
5782 if (from_tty)
5783 puts_filtered ("Ending remote debugging.\n");
5784 }
5785
5786 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5787 be chatty about it. */
5788
5789 void
5790 extended_remote_target::attach (const char *args, int from_tty)
5791 {
5792 struct remote_state *rs = get_remote_state ();
5793 int pid;
5794 char *wait_status = NULL;
5795
5796 pid = parse_pid_to_attach (args);
5797
5798 /* Remote PID can be freely equal to getpid, do not check it here the same
5799 way as in other targets. */
5800
5801 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5802 error (_("This target does not support attaching to a process"));
5803
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
5818 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5819 putpkt (rs->buf);
5820 getpkt (&rs->buf, &rs->buf_size, 0);
5821
5822 switch (packet_ok (rs->buf,
5823 &remote_protocol_packets[PACKET_vAttach]))
5824 {
5825 case PACKET_OK:
5826 if (!target_is_non_stop_p ())
5827 {
5828 /* Save the reply for later. */
5829 wait_status = (char *) alloca (strlen (rs->buf) + 1);
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);
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)));
5842 }
5843
5844 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5845
5846 inferior_ptid = pid_to_ptid (pid);
5847
5848 if (target_is_non_stop_p ())
5849 {
5850 struct thread_info *thread;
5851
5852 /* Get list of threads. */
5853 update_thread_list ();
5854
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. */
5862 record_currthread (rs, minus_one_ptid);
5863 }
5864 else
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. */
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);
5874 }
5875
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
5880 if (!target_is_non_stop_p ())
5881 {
5882 /* Use the previously fetched status. */
5883 gdb_assert (wait_status != NULL);
5884
5885 if (target_can_async_p ())
5886 {
5887 struct notif_event *reply
5888 = remote_notif_parse (this, &notif_client_stop, wait_status);
5889
5890 push_stop_reply ((struct stop_reply *) reply);
5891
5892 target_async (1);
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);
5903 }
5904
5905 /* Implementation of the to_post_attach method. */
5906
5907 void
5908 extended_remote_target::post_attach (int pid)
5909 {
5910 /* Get text, data & bss offsets. */
5911 get_offsets ();
5912
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
5922 \f
5923 /* Check for the availability of vCont. This function should also check
5924 the response. */
5925
5926 void
5927 remote_target::remote_vcont_probe ()
5928 {
5929 remote_state *rs = get_remote_state ();
5930 char *buf;
5931
5932 strcpy (rs->buf, "vCont?");
5933 putpkt (rs->buf);
5934 getpkt (&rs->buf, &rs->buf_size, 0);
5935 buf = rs->buf;
5936
5937 /* Make sure that the features we assume are supported. */
5938 if (startswith (buf, "vCont"))
5939 {
5940 char *p = &buf[5];
5941 int support_c, support_C;
5942
5943 rs->supports_vCont.s = 0;
5944 rs->supports_vCont.S = 0;
5945 support_c = 0;
5946 support_C = 0;
5947 rs->supports_vCont.t = 0;
5948 rs->supports_vCont.r = 0;
5949 while (p && *p == ';')
5950 {
5951 p++;
5952 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5953 rs->supports_vCont.s = 1;
5954 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5955 rs->supports_vCont.S = 1;
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;
5960 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5961 rs->supports_vCont.t = 1;
5962 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5963 rs->supports_vCont.r = 1;
5964
5965 p = strchr (p, ';');
5966 }
5967
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)
5971 buf[0] = 0;
5972 }
5973
5974 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5975 }
5976
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
5987 char *
5988 remote_target::append_resumption (char *p, char *endp,
5989 ptid_t ptid, int step, gdb_signal siggnal)
5990 {
5991 struct remote_state *rs = get_remote_state ();
5992
5993 if (step && siggnal != GDB_SIGNAL_0)
5994 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
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 }
6031 else if (step)
6032 p += xsnprintf (p, endp - p, ";s");
6033 else if (siggnal != GDB_SIGNAL_0)
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. */
6043 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
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
6057 /* Clear the thread's private info on resume. */
6058
6059 static void
6060 resume_clear_thread_private_info (struct thread_info *thread)
6061 {
6062 if (thread->priv != NULL)
6063 {
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;
6068 }
6069 }
6070
6071 /* Append a vCont continue-with-signal action for threads that have a
6072 non-zero stop signal. */
6073
6074 char *
6075 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6076 ptid_t ptid)
6077 {
6078 struct thread_info *thread;
6079
6080 ALL_NON_EXITED_THREADS (thread)
6081 if (ptid_match (thread->ptid, ptid)
6082 && !ptid_equal (inferior_ptid, thread->ptid)
6083 && thread->suspend.stop_signal != GDB_SIGNAL_0)
6084 {
6085 p = append_resumption (p, endp, thread->ptid,
6086 0, thread->suspend.stop_signal);
6087 thread->suspend.stop_signal = GDB_SIGNAL_0;
6088 resume_clear_thread_private_info (thread);
6089 }
6090
6091 return p;
6092 }
6093
6094 /* Set the target running, using the packets that use Hc
6095 (c/s/C/S). */
6096
6097 void
6098 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6099 gdb_signal siggnal)
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;
6119 if (::execution_direction == EXEC_REVERSE)
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
6146 /* Resume the remote inferior by using a "vCont" packet. The thread
6147 to be resumed is PTID; STEP and SIGGNAL indicate whether the
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.
6152
6153 This function issues a strict subset of all possible vCont commands
6154 at the moment. */
6155
6156 int
6157 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6158 enum gdb_signal siggnal)
6159 {
6160 struct remote_state *rs = get_remote_state ();
6161 char *p;
6162 char *endp;
6163
6164 /* No reverse execution actions defined for vCont. */
6165 if (::execution_direction == EXEC_REVERSE)
6166 return 0;
6167
6168 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6169 remote_vcont_probe ();
6170
6171 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6172 return 0;
6173
6174 p = rs->buf;
6175 endp = rs->buf + get_remote_packet_size ();
6176
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
6181 p += xsnprintf (p, endp - p, "vCont");
6182
6183 if (ptid_equal (ptid, magic_null_ptid))
6184 {
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. */
6189 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6190 }
6191 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
6192 {
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. */
6197 if (step || siggnal != GDB_SIGNAL_0)
6198 {
6199 /* Step inferior_ptid, with or without signal. */
6200 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6201 }
6202
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
6207 /* And continue others without a signal. */
6208 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6209 }
6210 else
6211 {
6212 /* Scheduler locking; resume only PTID. */
6213 append_resumption (p, endp, ptid, step, siggnal);
6214 }
6215
6216 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6217 putpkt (rs->buf);
6218
6219 if (target_is_non_stop_p ())
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
6229 return 1;
6230 }
6231
6232 /* Tell the remote machine to resume. */
6233
6234 void
6235 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6236 {
6237 struct remote_state *rs = get_remote_state ();
6238
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. */
6246 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6247 {
6248 remote_thread_info *remote_thr;
6249
6250 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
6251 remote_thr = get_remote_thread_info (inferior_ptid);
6252 else
6253 remote_thr = get_remote_thread_info (ptid);
6254
6255 remote_thr->last_resume_step = step;
6256 remote_thr->last_resume_sig = siggnal;
6257 return;
6258 }
6259
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. */
6266 if (!target_is_non_stop_p ())
6267 remote_notif_process (rs->notif_state, &notif_client_stop);
6268
6269 rs->last_resume_exec_dir = ::execution_direction;
6270
6271 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6272 if (!remote_resume_with_vcont (ptid, step, siggnal))
6273 remote_resume_with_hc (ptid, step, siggnal);
6274
6275 /* We are about to start executing the inferior, let's register it
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
6278 of the execution commands in infcmd.c. */
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
6281 NOT asynchronously. */
6282 if (target_can_async_p ())
6283 target_async (1);
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
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. */
6292 if (!target_is_non_stop_p ())
6293 rs->waiting_for_stop_reply = 1;
6294 }
6295
6296 static int is_pending_fork_parent_thread (struct thread_info *thread);
6297
6298 /* Private per-inferior info for target remote processes. */
6299
6300 struct remote_inferior : public private_inferior
6301 {
6302 /* Whether we can send a wildcard vCont for this process. */
6303 bool may_wildcard_vcont = true;
6304 };
6305
6306 /* Get the remote private inferior data associated to INF. */
6307
6308 static remote_inferior *
6309 get_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
6317 /* Class used to track the construction of a vCont packet in the
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
6321 class vcont_builder
6322 {
6323 public:
6324 explicit vcont_builder (remote_target *remote)
6325 : m_remote (remote)
6326 {
6327 restart ();
6328 }
6329
6330 void flush ();
6331 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6332
6333 private:
6334 void restart ();
6335
6336 /* The remote target. */
6337 remote_target *m_remote;
6338
6339 /* Pointer to the first action. P points here if no action has been
6340 appended yet. */
6341 char *m_first_action;
6342
6343 /* Where the next action will be appended. */
6344 char *m_p;
6345
6346 /* The end of the buffer. Must never write past this. */
6347 char *m_endp;
6348 };
6349
6350 /* Prepare the outgoing buffer for a new vCont packet. */
6351
6352 void
6353 vcont_builder::restart ()
6354 {
6355 struct remote_state *rs = m_remote->get_remote_state ();
6356
6357 m_p = rs->buf;
6358 m_endp = rs->buf + m_remote->get_remote_packet_size ();
6359 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6360 m_first_action = m_p;
6361 }
6362
6363 /* If the vCont packet being built has any action, send it to the
6364 remote end. */
6365
6366 void
6367 vcont_builder::flush ()
6368 {
6369 struct remote_state *rs;
6370
6371 if (m_p == m_first_action)
6372 return;
6373
6374 rs = m_remote->get_remote_state ();
6375 m_remote->putpkt (rs->buf);
6376 m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
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
6392 void
6393 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6394 {
6395 char buf[MAX_ACTION_SIZE + 1];
6396
6397 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6398 ptid, step, siggnal);
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. */
6403 size_t rsize = endp - buf;
6404 if (rsize > m_endp - m_p)
6405 {
6406 flush ();
6407 restart ();
6408
6409 /* Should now fit. */
6410 gdb_assert (rsize <= m_endp - m_p);
6411 }
6412
6413 memcpy (m_p, buf, rsize);
6414 m_p += rsize;
6415 *m_p = '\0';
6416 }
6417
6418 /* to_commit_resume implementation. */
6419
6420 void
6421 remote_target::commit_resume ()
6422 {
6423 struct inferior *inf;
6424 struct thread_info *tp;
6425 int any_process_wildcard;
6426 int may_global_wildcard_vcont;
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. */
6432 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
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 {
6489 remote_inferior *priv = get_remote_inferior (inf);
6490
6491 priv->may_wildcard_vcont = true;
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 {
6504 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
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. */
6524 struct vcont_builder vcont_builder (this);
6525
6526 /* Threads first. */
6527 ALL_NON_EXITED_THREADS (tp)
6528 {
6529 remote_thread_info *remote_thr = get_remote_thread_info (tp);
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
6538 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6539 {
6540 /* We'll send a wildcard resume instead. */
6541 remote_thr->vcont_resumed = 1;
6542 continue;
6543 }
6544
6545 vcont_builder.push_action (tp->ptid,
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 {
6558 if (get_remote_inferior (inf)->may_wildcard_vcont)
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 {
6572 vcont_builder.push_action (minus_one_ptid,
6573 false, GDB_SIGNAL_0);
6574 }
6575 else
6576 {
6577 ALL_NON_EXITED_INFERIORS (inf)
6578 {
6579 if (get_remote_inferior (inf)->may_wildcard_vcont)
6580 {
6581 vcont_builder.push_action (pid_to_ptid (inf->pid),
6582 false, GDB_SIGNAL_0);
6583 }
6584 }
6585 }
6586 }
6587
6588 vcont_builder.flush ();
6589 }
6590
6591 \f
6592
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
6597 void
6598 remote_target::remote_stop_ns (ptid_t ptid)
6599 {
6600 struct remote_state *rs = get_remote_state ();
6601 char *p = rs->buf;
6602 char *endp = rs->buf + get_remote_packet_size ();
6603
6604 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6605 remote_vcont_probe ();
6606
6607 if (!rs->supports_vCont.t)
6608 error (_("Remote server does not support stopping threads"));
6609
6610 if (ptid_equal (ptid, minus_one_ptid)
6611 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6612 p += xsnprintf (p, endp - p, "vCont;t");
6613 else
6614 {
6615 ptid_t nptid;
6616
6617 p += xsnprintf (p, endp - p, "vCont;t:");
6618
6619 if (ptid_is_pid (ptid))
6620 /* All (-1) threads of process. */
6621 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
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
6633 write_ptid (p, endp, nptid);
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
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. */
6647
6648 void
6649 remote_target::remote_interrupt_as ()
6650 {
6651 struct remote_state *rs = get_remote_state ();
6652
6653 rs->ctrlc_pending_p = 1;
6654
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
6661 /* Send interrupt_sequence to remote target. */
6662 send_interrupt_sequence ();
6663 }
6664
6665 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6666 the remote target. It is undefined which thread of which process
6667 reports the interrupt. Throws an error if the packet is not
6668 supported by the server. */
6669
6670 void
6671 remote_target::remote_interrupt_ns ()
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:
6689 error (_("No support for interrupting the remote target."));
6690 case PACKET_ERROR:
6691 error (_("Interrupting target failed: %s"), rs->buf);
6692 }
6693 }
6694
6695 /* Implement the to_stop function for the remote targets. */
6696
6697 void
6698 remote_target::stop (ptid_t ptid)
6699 {
6700 if (remote_debug)
6701 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6702
6703 if (target_is_non_stop_p ())
6704 remote_stop_ns (ptid);
6705 else
6706 {
6707 /* We don't currently have a way to transparently pause the
6708 remote target in all-stop mode. Interrupt it instead. */
6709 remote_interrupt_as ();
6710 }
6711 }
6712
6713 /* Implement the to_interrupt function for the remote targets. */
6714
6715 void
6716 remote_target::interrupt ()
6717 {
6718 if (remote_debug)
6719 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6720
6721 if (target_is_non_stop_p ())
6722 remote_interrupt_ns ();
6723 else
6724 remote_interrupt_as ();
6725 }
6726
6727 /* Implement the to_pass_ctrlc function for the remote targets. */
6728
6729 void
6730 remote_target::pass_ctrlc ()
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
6745 target_interrupt ();
6746 }
6747
6748 /* Ask the user what to do when an interrupt is received. */
6749
6750 void
6751 remote_target::interrupt_query ()
6752 {
6753 struct remote_state *rs = get_remote_state ();
6754
6755 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6756 {
6757 if (query (_("The target is not responding to interrupt requests.\n"
6758 "Stop debugging it? ")))
6759 {
6760 remote_unpush_target ();
6761 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6762 }
6763 }
6764 else
6765 {
6766 if (query (_("Interrupted while waiting for the program.\n"
6767 "Give up waiting? ")))
6768 quit ();
6769 }
6770 }
6771
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
6775 is required. */
6776
6777 void
6778 remote_target::terminal_inferior ()
6779 {
6780 /* NOTE: At this point we could also register our selves as the
6781 recipient of all input. Any characters typed could then be
6782 passed on down to the target. */
6783 }
6784
6785 void
6786 remote_target::terminal_ours ()
6787 {
6788 }
6789
6790 static void
6791 remote_console_output (char *msg)
6792 {
6793 char *p;
6794
6795 for (p = msg; p[0] && p[1]; p += 2)
6796 {
6797 char tb[2];
6798 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6799
6800 tb[0] = c;
6801 tb[1] = 0;
6802 fputs_unfiltered (tb, gdb_stdtarg);
6803 }
6804 gdb_flush (gdb_stdtarg);
6805 }
6806
6807 DEF_VEC_O(cached_reg_t);
6808
6809 typedef struct stop_reply
6810 {
6811 struct notif_event base;
6812
6813 /* The identifier of the thread about this event */
6814 ptid_t ptid;
6815
6816 /* The remote state this event is associated with. When the remote
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
6821 struct target_waitstatus ws;
6822
6823 /* The architecture associated with the expedited registers. */
6824 gdbarch *arch;
6825
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). */
6830 VEC(cached_reg_t) *regcache;
6831
6832 enum target_stop_reason stop_reason;
6833
6834 CORE_ADDR watch_data_address;
6835
6836 int core;
6837 } *stop_reply_p;
6838
6839 static void
6840 stop_reply_xfree (struct stop_reply *r)
6841 {
6842 notif_event_xfree ((struct notif_event *) r);
6843 }
6844
6845 /* Return the length of the stop reply queue. */
6846
6847 int
6848 remote_target::stop_reply_queue_length ()
6849 {
6850 remote_state *rs = get_remote_state ();
6851 return QUEUE_length (stop_reply_p, rs->stop_reply_queue);
6852 }
6853
6854 void
6855 remote_notif_stop_parse (remote_target *remote,
6856 struct notif_client *self, char *buf,
6857 struct notif_event *event)
6858 {
6859 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
6860 }
6861
6862 static void
6863 remote_notif_stop_ack (remote_target *remote,
6864 struct notif_client *self, char *buf,
6865 struct notif_event *event)
6866 {
6867 struct stop_reply *stop_reply = (struct stop_reply *) event;
6868
6869 /* acknowledge */
6870 putpkt (remote, self->ack_command);
6871
6872 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6873 {
6874 /* We got an unknown stop reply. */
6875 error (_("Unknown stop reply"));
6876 }
6877
6878 remote->push_stop_reply (stop_reply);
6879 }
6880
6881 static int
6882 remote_notif_stop_can_get_pending_events (remote_target *remote,
6883 struct notif_client *self)
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. */
6890 remote_state *rs = remote->get_remote_state ();
6891 mark_async_event_handler (rs->remote_async_inferior_event_token);
6892 return 0;
6893 }
6894
6895 static void
6896 stop_reply_dtr (struct notif_event *event)
6897 {
6898 struct stop_reply *r = (struct stop_reply *) event;
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);
6906
6907 VEC_free (cached_reg_t, r->regcache);
6908 }
6909
6910 static struct notif_event *
6911 remote_notif_stop_alloc_reply (void)
6912 {
6913 /* We cast to a pointer to the "base class". */
6914 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6915
6916 r->dtr = stop_reply_dtr;
6917
6918 return r;
6919 }
6920
6921 /* A client of notification Stop. */
6922
6923 struct 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,
6931 REMOTE_NOTIF_STOP,
6932 };
6933
6934 /* A parameter to pass data in and out. */
6935
6936 struct queue_iter_param
6937 {
6938 remote_target *remote;
6939 void *input;
6940 struct stop_reply *output;
6941 };
6942
6943 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
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
6947 static int
6948 is_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
6961 /* Return the thread's pending status used to determine whether the
6962 thread is a fork parent stopped at a fork event. */
6963
6964 static struct target_waitstatus *
6965 thread_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
6975 static int
6976 is_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
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
6987 static int
6988 remove_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 {
6993 struct queue_iter_param *param = (struct queue_iter_param *) data;
6994 struct threads_listing_context *context
6995 = (struct threads_listing_context *) param->input;
6996
6997 if (event->ws.kind == TARGET_WAITKIND_FORKED
6998 || event->ws.kind == TARGET_WAITKIND_VFORKED
6999 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7000 context->remove_thread (event->ws.value.related_pid);
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
7011 void
7012 remote_target::remove_new_fork_children (threads_listing_context *context)
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 {
7023 struct target_waitstatus *ws = thread_pending_fork_status (thread);
7024
7025 if (is_pending_fork_parent (ws, pid, thread->ptid))
7026 context->remove_thread (ws->value.related_pid);
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);
7033 param.remote = this;
7034 param.input = context;
7035 param.output = NULL;
7036 QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
7037 remove_child_of_pending_fork, &param);
7038 }
7039
7040 /* Callback data for
7041 check_pending_event_prevents_wildcard_vcont_callback. */
7042 struct 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
7051 /* Check whether EVENT would prevent a global or process wildcard
7052 vCont action. */
7053
7054 static int
7055 check_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;
7062 auto *cb_data = (check_pending_event_prevents_wildcard_vcont_callback_data *) data;
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)
7070 *cb_data->may_global_wildcard_vcont = 0;
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. */
7077 *cb_data->may_global_wildcard_vcont = 0;
7078 if (inf != NULL)
7079 get_remote_inferior (inf)->may_wildcard_vcont = false;
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
7090 void
7091 remote_target::check_pending_events_prevent_wildcard_vcont
7092 (int *may_global_wildcard)
7093 {
7094 struct notif_client *notif = &notif_client_stop;
7095 check_pending_event_prevents_wildcard_vcont_callback_data cb_data
7096 {this, may_global_wildcard};
7097
7098 remote_notif_get_pending_events (notif);
7099 QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
7100 check_pending_event_prevents_wildcard_vcont_callback,
7101 &cb_data);
7102 }
7103
7104 /* Remove stop replies in the queue if its pid is equal to the given
7105 inferior's pid. */
7106
7107 static int
7108 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
7109 QUEUE_ITER (stop_reply_p) *iter,
7110 stop_reply_p event,
7111 void *data)
7112 {
7113 struct queue_iter_param *param = (struct queue_iter_param *) data;
7114 struct inferior *inf = (struct inferior *) param->input;
7115
7116 if (ptid_get_pid (event->ptid) == inf->pid)
7117 {
7118 stop_reply_xfree (event);
7119 QUEUE_remove_elem (stop_reply_p, q, iter);
7120 }
7121
7122 return 1;
7123 }
7124
7125 /* Discard all pending stop replies of inferior INF. */
7126
7127 void
7128 remote_target::discard_pending_stop_replies (struct inferior *inf)
7129 {
7130 struct queue_iter_param param;
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];
7141
7142 /* Discard the in-flight notification. */
7143 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
7144 {
7145 stop_reply_xfree (reply);
7146 rns->pending_event[notif_client_stop.id] = NULL;
7147 }
7148
7149 param.remote = this;
7150 param.input = inf;
7151 param.output = NULL;
7152 /* Discard the stop replies we have already pulled with
7153 vStopped. */
7154 QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
7155 remove_stop_reply_for_inferior, &param);
7156 }
7157
7158 /* If its remote state is equal to the given remote state,
7159 remove EVENT from the stop reply queue. */
7160
7161 static int
7162 remove_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 {
7167 struct queue_iter_param *param = (struct queue_iter_param *) data;
7168 struct remote_state *rs = (struct remote_state *) param->input;
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. */
7180
7181 void
7182 remote_target::discard_pending_stop_replies_in_queue ()
7183 {
7184 remote_state *rs = get_remote_state ();
7185 struct queue_iter_param param;
7186
7187 param.remote = this;
7188 param.input = rs;
7189 param.output = NULL;
7190 /* Discard the stop replies we have already pulled with
7191 vStopped. */
7192 QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
7193 remove_stop_reply_of_remote_state, &param);
7194 }
7195
7196 /* A parameter to pass data in and out. */
7197
7198 static int
7199 remote_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 {
7204 struct queue_iter_param *param = (struct queue_iter_param *) data;
7205 ptid_t *ptid = (ptid_t *) param->input;
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;
7212 }
7213
7214 return 1;
7215 }
7216
7217 /* Remove the first reply in 'stop_reply_queue' which matches
7218 PTID. */
7219
7220 struct stop_reply *
7221 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7222 {
7223 struct queue_iter_param param;
7224
7225 param.remote = this;
7226 param.input = &ptid;
7227 param.output = NULL;
7228
7229 QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
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));
7235
7236 return param.output;
7237 }
7238
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. */
7243
7244 struct stop_reply *
7245 remote_target::queued_stop_reply (ptid_t ptid)
7246 {
7247 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7248
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 }
7255
7256 return r;
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
7263 void
7264 remote_target::push_stop_reply (struct stop_reply *new_event)
7265 {
7266 remote_state *rs = get_remote_state ();
7267 QUEUE_enque (stop_reply_p, rs->stop_reply_queue, new_event);
7268
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,
7274 rs->stop_reply_queue));
7275
7276 mark_async_event_handler (rs->remote_async_inferior_event_token);
7277 }
7278
7279 static int
7280 stop_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 {
7285 ptid_t *ptid = (ptid_t *) data;
7286
7287 return !(ptid_equal (*ptid, event->ptid)
7288 && event->ws.kind == TARGET_WAITKIND_STOPPED);
7289 }
7290
7291 /* Returns true if we have a stop reply for PTID. */
7292
7293 int
7294 remote_target::peek_stop_reply (ptid_t ptid)
7295 {
7296 remote_state *rs = get_remote_state ();
7297 return !QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
7298 stop_reply_match_ptid_and_ws, &ptid);
7299 }
7300
7301 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7302 starting with P and ending with PEND matches PREFIX. */
7303
7304 static int
7305 strprefix (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
7313 /* Parse the stop reply in BUF. Either the function succeeds, and the
7314 result is stored in EVENT, or throws an error. */
7315
7316 void
7317 remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
7318 {
7319 remote_arch_state *rsa = NULL;
7320 ULONGEST addr;
7321 const char *p;
7322 int skipregs = 0;
7323
7324 event->ptid = null_ptid;
7325 event->rs = get_remote_state ();
7326 event->ws.kind = TARGET_WAITKIND_IGNORE;
7327 event->ws.value.integer = 0;
7328 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7329 event->regcache = NULL;
7330 event->core = -1;
7331
7332 switch (buf[0])
7333 {
7334 case 'T': /* Status with PC, SP, FP, ... */
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 {
7345 const char *p1;
7346 int fieldsize;
7347
7348 p1 = strchr (p, ':');
7349 if (p1 == NULL)
7350 error (_("Malformed packet(a) (missing colon): %s\n\
7351 Packet: '%s'\n"),
7352 p, buf);
7353 if (p == p1)
7354 error (_("Malformed packet(a) (missing register number): %s\n\
7355 Packet: '%s'\n"),
7356 p, buf);
7357
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. */
7364
7365 if (strprefix (p, p1, "thread"))
7366 event->ptid = read_ptid (++p1, &p);
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 }
7383 else if (strprefix (p, p1, "watch")
7384 || strprefix (p, p1, "rwatch")
7385 || strprefix (p, p1, "awatch"))
7386 {
7387 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7388 p = unpack_varlen_hex (++p1, &addr);
7389 event->watch_data_address = (CORE_ADDR) addr;
7390 }
7391 else if (strprefix (p, p1, "swbreak"))
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. */
7403 p = strchrnul (p1 + 1, ';');
7404 }
7405 else if (strprefix (p, p1, "hwbreak"))
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. */
7415 p = strchrnul (p1 + 1, ';');
7416 }
7417 else if (strprefix (p, p1, "library"))
7418 {
7419 event->ws.kind = TARGET_WAITKIND_LOADED;
7420 p = strchrnul (p1 + 1, ';');
7421 }
7422 else if (strprefix (p, p1, "replaylog"))
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. */
7427 p = strchrnul (p1 + 1, ';');
7428 }
7429 else if (strprefix (p, p1, "core"))
7430 {
7431 ULONGEST c;
7432
7433 p = unpack_varlen_hex (++p1, &c);
7434 event->core = c;
7435 }
7436 else if (strprefix (p, p1, "fork"))
7437 {
7438 event->ws.value.related_pid = read_ptid (++p1, &p);
7439 event->ws.kind = TARGET_WAITKIND_FORKED;
7440 }
7441 else if (strprefix (p, p1, "vfork"))
7442 {
7443 event->ws.value.related_pid = read_ptid (++p1, &p);
7444 event->ws.kind = TARGET_WAITKIND_VFORKED;
7445 }
7446 else if (strprefix (p, p1, "vforkdone"))
7447 {
7448 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7449 p = strchrnul (p1 + 1, ';');
7450 }
7451 else if (strprefix (p, p1, "exec"))
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 }
7475 else if (strprefix (p, p1, "create"))
7476 {
7477 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7478 p = strchrnul (p1 + 1, ';');
7479 }
7480 else
7481 {
7482 ULONGEST pnum;
7483 const char *p_temp;
7484
7485 if (skipregs)
7486 {
7487 p = strchrnul (p1 + 1, ';');
7488 p++;
7489 continue;
7490 }
7491
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 {
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
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 }
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;
7540 rsa = event->rs->get_remote_arch_state (event->arch);
7541 }
7542
7543 packet_reg *reg
7544 = packet_reg_from_pnum (event->arch, rsa, pnum);
7545 cached_reg_t cached_reg;
7546
7547 if (reg == NULL)
7548 error (_("Remote sent bad register number %s: %s\n\
7549 Packet: '%s'\n"),
7550 hex_string (pnum), p, buf);
7551
7552 cached_reg.num = reg->regnum;
7553 cached_reg.data = (gdb_byte *)
7554 xmalloc (register_size (event->arch, reg->regnum));
7555
7556 p = p1 + 1;
7557 fieldsize = hex2bin (p, cached_reg.data,
7558 register_size (event->arch, reg->regnum));
7559 p += 2 * fieldsize;
7560 if (fieldsize < register_size (event->arch, reg->regnum))
7561 warning (_("Remote reply is too short: %s"), buf);
7562
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. */
7569 p = strchrnul (p1 + 1, ';');
7570 }
7571 }
7572
7573 if (*p != ';')
7574 error (_("Remote register badly formatted: %s\nhere: %s"),
7575 buf, p);
7576 ++p;
7577 }
7578
7579 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7580 break;
7581
7582 /* fall through */
7583 case 'S': /* Old style status, just signal only. */
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 }
7594 break;
7595 case 'w': /* Thread exited. */
7596 {
7597 const char *p;
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);
7605 event->ptid = read_ptid (++p, NULL);
7606 break;
7607 }
7608 case 'W': /* Target exited. */
7609 case 'X':
7610 {
7611 const char *p;
7612 int pid;
7613 ULONGEST value;
7614
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);
7619
7620 if (buf[0] == 'W')
7621 {
7622 /* The remote process exited. */
7623 event->ws.kind = TARGET_WAITKIND_EXITED;
7624 event->ws.value.integer = value;
7625 }
7626 else
7627 {
7628 /* The remote process exited with a signal. */
7629 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
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;
7634 }
7635
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
7644 if (*p == '\0')
7645 ;
7646 else if (startswith (p, "process:"))
7647 {
7648 ULONGEST upid;
7649
7650 p += sizeof ("process:") - 1;
7651 unpack_varlen_hex (p, &upid);
7652 pid = upid;
7653 }
7654 else
7655 error (_("unknown stop reply packet: %s"), buf);
7656 }
7657 else
7658 error (_("unknown stop reply packet: %s"), buf);
7659 event->ptid = pid_to_ptid (pid);
7660 }
7661 break;
7662 case 'N':
7663 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7664 event->ptid = minus_one_ptid;
7665 break;
7666 }
7667
7668 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7669 error (_("No process or thread specified in stop reply: %s"), buf);
7670 }
7671
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:
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
7691 To solve this, whenever we parse a %Stop notification successfully,
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
7714 void
7715 remote_target::remote_notif_get_pending_events (notif_client *nc)
7716 {
7717 struct remote_state *rs = get_remote_state ();
7718
7719 if (rs->notif_state->pending_event[nc->id] != NULL)
7720 {
7721 if (notif_debug)
7722 fprintf_unfiltered (gdb_stdlog,
7723 "notif: process: '%s' ack pending event\n",
7724 nc->name);
7725
7726 /* acknowledge */
7727 nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7728 rs->notif_state->pending_event[nc->id] = NULL;
7729
7730 while (1)
7731 {
7732 getpkt (&rs->buf, &rs->buf_size, 0);
7733 if (strcmp (rs->buf, "OK") == 0)
7734 break;
7735 else
7736 remote_notif_ack (this, nc, rs->buf);
7737 }
7738 }
7739 else
7740 {
7741 if (notif_debug)
7742 fprintf_unfiltered (gdb_stdlog,
7743 "notif: process: '%s' no pending reply\n",
7744 nc->name);
7745 }
7746 }
7747
7748 /* Wrapper around remote_target::remote_notif_get_pending_events to
7749 avoid having to export the whole remote_target class. */
7750
7751 void
7752 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7753 {
7754 remote->remote_notif_get_pending_events (nc);
7755 }
7756
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
7761 ptid_t
7762 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7763 struct target_waitstatus *status)
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
7775 if (status->kind != TARGET_WAITKIND_EXITED
7776 && status->kind != TARGET_WAITKIND_SIGNALLED
7777 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7778 {
7779 /* Expedited registers. */
7780 if (stop_reply->regcache)
7781 {
7782 struct regcache *regcache
7783 = get_thread_arch_regcache (ptid, stop_reply->arch);
7784 cached_reg_t *reg;
7785 int ix;
7786
7787 for (ix = 0;
7788 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7789 ix++)
7790 {
7791 regcache_raw_supply (regcache, reg->num, reg->data);
7792 xfree (reg->data);
7793 }
7794
7795 VEC_free (cached_reg_t, stop_reply->regcache);
7796 }
7797
7798 remote_notice_new_inferior (ptid, 0);
7799 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
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;
7803 remote_thr->vcont_resumed = 0;
7804 }
7805
7806 stop_reply_xfree (stop_reply);
7807 return ptid;
7808 }
7809
7810 /* The non-stop mode version of target_wait. */
7811
7812 ptid_t
7813 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7814 {
7815 struct remote_state *rs = get_remote_state ();
7816 struct stop_reply *stop_reply;
7817 int ret;
7818 int is_notif = 0;
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,
7824 0 /* forever */, &is_notif);
7825 while (1)
7826 {
7827 if (ret != -1 && !is_notif)
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. */
7846 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7847 remote_notif_get_pending_events (&notif_client_stop);
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
7854 /* Still no event. If we're just polling for an event, then
7855 return to the event loop. */
7856 if (options & TARGET_WNOHANG)
7857 {
7858 status->kind = TARGET_WAITKIND_IGNORE;
7859 return minus_one_ptid;
7860 }
7861
7862 /* Otherwise do a blocking wait. */
7863 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7864 1 /* forever */, &is_notif);
7865 }
7866 }
7867
7868 /* Wait until the remote machine stops, then return, storing status in
7869 STATUS just as `wait' would. */
7870
7871 ptid_t
7872 remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
7873 {
7874 struct remote_state *rs = get_remote_state ();
7875 ptid_t event_ptid = null_ptid;
7876 char *buf;
7877 struct stop_reply *stop_reply;
7878
7879 again:
7880
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;
7894 int is_notif;
7895 int forever = ((options & TARGET_WNOHANG) == 0
7896 && rs->wait_forever_enabled_p);
7897
7898 if (!rs->waiting_for_stop_reply)
7899 {
7900 status->kind = TARGET_WAITKIND_NO_RESUMED;
7901 return minus_one_ptid;
7902 }
7903
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. */
7908 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7909 forever, &is_notif);
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;
7915
7916 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7917 return minus_one_ptid;
7918 }
7919
7920 buf = rs->buf;
7921
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
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. */
7932 rs->waiting_for_stop_reply = 0;
7933
7934 warning (_("Remote failure reply: %s"), buf);
7935 status->kind = TARGET_WAITKIND_STOPPED;
7936 status->value.sig = GDB_SIGNAL_0;
7937 break;
7938 case 'F': /* File-I/O request. */
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;
7944 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
7945 rs->ctrlc_pending_p = 0;
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;
7949 break;
7950 case 'N': case 'T': case 'S': case 'X': case 'W':
7951 {
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
7958 = (struct stop_reply *) remote_notif_parse (this,
7959 &notif_client_stop,
7960 rs->buf);
7961
7962 event_ptid = process_stop_reply (stop_reply, status);
7963 break;
7964 }
7965 case 'O': /* Console output. */
7966 remote_console_output (buf + 1);
7967 break;
7968 case '\0':
7969 if (rs->last_sent_signal != GDB_SIGNAL_0)
7970 {
7971 /* Zero length reply means that we tried 'S' or 'C' and the
7972 remote system doesn't support it. */
7973 target_terminal::ours_for_output ();
7974 printf_filtered
7975 ("Can't send signals to this remote system. %s not sent.\n",
7976 gdb_signal_to_name (rs->last_sent_signal));
7977 rs->last_sent_signal = GDB_SIGNAL_0;
7978 target_terminal::inferior ();
7979
7980 strcpy (buf, rs->last_sent_step ? "s" : "c");
7981 putpkt (buf);
7982 break;
7983 }
7984 /* fallthrough */
7985 default:
7986 warning (_("Invalid remote reply: %s"), buf);
7987 break;
7988 }
7989
7990 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7991 return minus_one_ptid;
7992 else if (status->kind == TARGET_WAITKIND_IGNORE)
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 }
8001 else if (status->kind != TARGET_WAITKIND_EXITED
8002 && status->kind != TARGET_WAITKIND_SIGNALLED)
8003 {
8004 if (!ptid_equal (event_ptid, null_ptid))
8005 record_currthread (rs, event_ptid);
8006 else
8007 event_ptid = inferior_ptid;
8008 }
8009 else
8010 /* A process exit. Invalidate our notion of current thread. */
8011 record_currthread (rs, minus_one_ptid);
8012
8013 return event_ptid;
8014 }
8015
8016 /* Wait until the remote machine stops, then return, storing status in
8017 STATUS just as `wait' would. */
8018
8019 ptid_t
8020 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
8021 {
8022 ptid_t event_ptid;
8023
8024 if (target_is_non_stop_p ())
8025 event_ptid = wait_ns (ptid, status, options);
8026 else
8027 event_ptid = wait_as (ptid, status, options);
8028
8029 if (target_is_async_p ())
8030 {
8031 remote_state *rs = get_remote_state ();
8032
8033 /* If there are are events left in the queue tell the event loop
8034 to return here. */
8035 if (!QUEUE_is_empty (stop_reply_p, rs->stop_reply_queue))
8036 mark_async_event_handler (rs->remote_async_inferior_event_token);
8037 }
8038
8039 return event_ptid;
8040 }
8041
8042 /* Fetch a single register using a 'p' packet. */
8043
8044 int
8045 remote_target::fetch_register_using_p (struct regcache *regcache,
8046 packet_reg *reg)
8047 {
8048 struct gdbarch *gdbarch = regcache->arch ();
8049 struct remote_state *rs = get_remote_state ();
8050 char *buf, *p;
8051 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8052 int i;
8053
8054 if (packet_support (PACKET_p) == PACKET_DISABLE)
8055 return 0;
8056
8057 if (reg->pnum == -1)
8058 return 0;
8059
8060 p = rs->buf;
8061 *p++ = 'p';
8062 p += hexnumstr (p, reg->pnum);
8063 *p++ = '\0';
8064 putpkt (rs->buf);
8065 getpkt (&rs->buf, &rs->buf_size, 0);
8066
8067 buf = rs->buf;
8068
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:
8076 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8077 gdbarch_register_name (regcache->arch (),
8078 reg->regnum),
8079 buf);
8080 }
8081
8082 /* If this register is unfetchable, tell the regcache. */
8083 if (buf[0] == 'x')
8084 {
8085 regcache_raw_supply (regcache, reg->regnum, NULL);
8086 return 1;
8087 }
8088
8089 /* Otherwise, parse and supply the value. */
8090 p = buf;
8091 i = 0;
8092 while (p[0] != 0)
8093 {
8094 if (p[1] == 0)
8095 error (_("fetch_register_using_p: early buf termination"));
8096
8097 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8098 p += 2;
8099 }
8100 regcache_raw_supply (regcache, reg->regnum, regp);
8101 return 1;
8102 }
8103
8104 /* Fetch the registers included in the target's 'g' packet. */
8105
8106 int
8107 remote_target::send_g_packet ()
8108 {
8109 struct remote_state *rs = get_remote_state ();
8110 int buf_len;
8111
8112 xsnprintf (rs->buf, get_remote_packet_size (), "g");
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);
8118
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
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);
8138
8139 return buf_len / 2;
8140 }
8141
8142 void
8143 remote_target::process_g_packet (struct regcache *regcache)
8144 {
8145 struct gdbarch *gdbarch = regcache->arch ();
8146 struct remote_state *rs = get_remote_state ();
8147 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
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. */
8155 if (buf_len > 2 * rsa->sizeof_g_packet)
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);
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)
8170 {
8171 long sizeof_g_packet = buf_len / 2;
8172
8173 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8174 {
8175 long offset = rsa->regs[i].offset;
8176 long reg_size = register_size (gdbarch, i);
8177
8178 if (rsa->regs[i].pnum == -1)
8179 continue;
8180
8181 if (offset >= sizeof_g_packet)
8182 rsa->regs[i].in_g_packet = 0;
8183 else if (offset + reg_size > sizeof_g_packet)
8184 error (_("Truncated register %d in remote 'g' packet"), i);
8185 else
8186 rsa->regs[i].in_g_packet = 1;
8187 }
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;
8196 }
8197
8198 regs = (char *) alloca (rsa->sizeof_g_packet);
8199
8200 /* Unimplemented registers read as all bits zero. */
8201 memset (regs, 0, rsa->sizeof_g_packet);
8202
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
8207 p = rs->buf;
8208 for (i = 0; i < rsa->sizeof_g_packet; i++)
8209 {
8210 if (p[0] == 0 || p[1] == 0)
8211 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8212 internal_error (__FILE__, __LINE__,
8213 _("unexpected end of 'g' packet reply"));
8214
8215 if (p[0] == 'x' && p[1] == 'x')
8216 regs[i] = 0; /* 'x' */
8217 else
8218 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8219 p += 2;
8220 }
8221
8222 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8223 {
8224 struct packet_reg *r = &rsa->regs[i];
8225 long reg_size = register_size (gdbarch, i);
8226
8227 if (r->in_g_packet)
8228 {
8229 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
8230 /* This shouldn't happen - we adjusted in_g_packet above. */
8231 internal_error (__FILE__, __LINE__,
8232 _("unexpected end of 'g' packet reply"));
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 }
8245 }
8246
8247 void
8248 remote_target::fetch_registers_using_g (struct regcache *regcache)
8249 {
8250 send_g_packet ();
8251 process_g_packet (regcache);
8252 }
8253
8254 /* Make the remote selected traceframe match GDB's selected
8255 traceframe. */
8256
8257 void
8258 remote_target::set_remote_traceframe ()
8259 {
8260 int newnum;
8261 struct remote_state *rs = get_remote_state ();
8262
8263 if (rs->remote_traceframe_number == get_traceframe_number ())
8264 return;
8265
8266 /* Avoid recursion, remote_trace_find calls us again. */
8267 rs->remote_traceframe_number = get_traceframe_number ();
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
8277 void
8278 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8279 {
8280 struct gdbarch *gdbarch = regcache->arch ();
8281 struct remote_state *rs = get_remote_state ();
8282 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8283 int i;
8284
8285 set_remote_traceframe ();
8286 set_general_thread (regcache_get_ptid (regcache));
8287
8288 if (regnum >= 0)
8289 {
8290 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8291
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 {
8300 fetch_registers_using_g (regcache);
8301 if (reg->in_g_packet)
8302 return;
8303 }
8304
8305 if (fetch_register_using_p (regcache, reg))
8306 return;
8307
8308 /* This register is not available. */
8309 regcache_raw_supply (regcache, reg->regnum, NULL);
8310
8311 return;
8312 }
8313
8314 fetch_registers_using_g (regcache);
8315
8316 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8317 if (!rsa->regs[i].in_g_packet)
8318 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8319 {
8320 /* This register is not available. */
8321 regcache_raw_supply (regcache, i, NULL);
8322 }
8323 }
8324
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
8329 void
8330 remote_target::prepare_to_store (struct regcache *regcache)
8331 {
8332 struct remote_state *rs = get_remote_state ();
8333 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8334 int i;
8335
8336 /* Make sure the entire registers array is valid. */
8337 switch (packet_support (PACKET_P))
8338 {
8339 case PACKET_DISABLE:
8340 case PACKET_SUPPORT_UNKNOWN:
8341 /* Make sure all the necessary registers are cached. */
8342 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8343 if (rsa->regs[i].in_g_packet)
8344 regcache_raw_update (regcache, rsa->regs[i].regnum);
8345 break;
8346 case PACKET_ENABLE:
8347 break;
8348 }
8349 }
8350
8351 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8352 packet was not recognized. */
8353
8354 int
8355 remote_target::store_register_using_P (const struct regcache *regcache,
8356 packet_reg *reg)
8357 {
8358 struct gdbarch *gdbarch = regcache->arch ();
8359 struct remote_state *rs = get_remote_state ();
8360 /* Try storing a single register. */
8361 char *buf = rs->buf;
8362 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8363 char *p;
8364
8365 if (packet_support (PACKET_P) == PACKET_DISABLE)
8366 return 0;
8367
8368 if (reg->pnum == -1)
8369 return 0;
8370
8371 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8372 p = buf + strlen (buf);
8373 regcache_raw_collect (regcache, reg->regnum, regp);
8374 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8375 putpkt (rs->buf);
8376 getpkt (&rs->buf, &rs->buf_size, 0);
8377
8378 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8379 {
8380 case PACKET_OK:
8381 return 1;
8382 case PACKET_ERROR:
8383 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8384 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8385 case PACKET_UNKNOWN:
8386 return 0;
8387 default:
8388 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8389 }
8390 }
8391
8392 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8393 contents of the register cache buffer. FIXME: ignores errors. */
8394
8395 void
8396 remote_target::store_registers_using_G (const struct regcache *regcache)
8397 {
8398 struct remote_state *rs = get_remote_state ();
8399 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8400 gdb_byte *regs;
8401 char *p;
8402
8403 /* Extract all the registers in the regcache copying them into a
8404 local buffer. */
8405 {
8406 int i;
8407
8408 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8409 memset (regs, 0, rsa->sizeof_g_packet);
8410 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8411 {
8412 struct packet_reg *r = &rsa->regs[i];
8413
8414 if (r->in_g_packet)
8415 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
8416 }
8417 }
8418
8419 /* Command describes registers byte by byte,
8420 each byte encoded as two hex characters. */
8421 p = rs->buf;
8422 *p++ = 'G';
8423 bin2hex (regs, p, rsa->sizeof_g_packet);
8424 putpkt (rs->buf);
8425 getpkt (&rs->buf, &rs->buf_size, 0);
8426 if (packet_check_result (rs->buf) == PACKET_ERROR)
8427 error (_("Could not write registers; remote failure reply '%s'"),
8428 rs->buf);
8429 }
8430
8431 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8432 of the register cache buffer. FIXME: ignores errors. */
8433
8434 void
8435 remote_target::store_registers (struct regcache *regcache, int regnum)
8436 {
8437 struct gdbarch *gdbarch = regcache->arch ();
8438 struct remote_state *rs = get_remote_state ();
8439 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8440 int i;
8441
8442 set_remote_traceframe ();
8443 set_general_thread (regcache_get_ptid (regcache));
8444
8445 if (regnum >= 0)
8446 {
8447 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8448
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'. */
8455 if (store_register_using_P (regcache, reg))
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
8461 any way to read the register, either... */
8462 if (!reg->in_g_packet)
8463 return;
8464
8465 store_registers_using_G (regcache);
8466 return;
8467 }
8468
8469 store_registers_using_G (regcache);
8470
8471 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8472 if (!rsa->regs[i].in_g_packet)
8473 if (!store_register_using_P (regcache, &rsa->regs[i]))
8474 /* See above for why we do not issue an error here. */
8475 continue;
8476 }
8477 \f
8478
8479 /* Return the number of hex digits in num. */
8480
8481 static int
8482 hexnumlen (ULONGEST num)
8483 {
8484 int i;
8485
8486 for (i = 0; num != 0; i++)
8487 num >>= 4;
8488
8489 return std::max (i, 1);
8490 }
8491
8492 /* Set BUF to the minimum number of hex digits representing NUM. */
8493
8494 static int
8495 hexnumstr (char *buf, ULONGEST num)
8496 {
8497 int len = hexnumlen (num);
8498
8499 return hexnumnstr (buf, num, len);
8500 }
8501
8502
8503 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8504
8505 static int
8506 hexnumnstr (char *buf, ULONGEST num, int width)
8507 {
8508 int i;
8509
8510 buf[width] = '\0';
8511
8512 for (i = width - 1; i >= 0; i--)
8513 {
8514 buf[i] = "0123456789abcdef"[(num & 0xf)];
8515 num >>= 4;
8516 }
8517
8518 return width;
8519 }
8520
8521 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8522
8523 static CORE_ADDR
8524 remote_address_masked (CORE_ADDR addr)
8525 {
8526 unsigned int address_size = remote_address_size;
8527
8528 /* If "remoteaddresssize" was not set, default to target address size. */
8529 if (!address_size)
8530 address_size = gdbarch_addr_bit (target_gdbarch ());
8531
8532 if (address_size > 0
8533 && address_size < (sizeof (ULONGEST) * 8))
8534 {
8535 /* Only create a mask when that mask can safely be constructed
8536 in a ULONGEST variable. */
8537 ULONGEST mask = 1;
8538
8539 mask = (mask << address_size) - 1;
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
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.
8551
8552 NOTE: This can still lose if the serial line is not eight-bit
8553 clean. In cases like this, the user should clear "remote
8554 X-packet". */
8555
8556 void
8557 remote_target::check_binary_download (CORE_ADDR addr)
8558 {
8559 struct remote_state *rs = get_remote_state ();
8560
8561 switch (packet_support (PACKET_X))
8562 {
8563 case PACKET_DISABLE:
8564 break;
8565 case PACKET_ENABLE:
8566 break;
8567 case PACKET_SUPPORT_UNKNOWN:
8568 {
8569 char *p;
8570
8571 p = rs->buf;
8572 *p++ = 'X';
8573 p += hexnumstr (p, (ULONGEST) addr);
8574 *p++ = ',';
8575 p += hexnumstr (p, (ULONGEST) 0);
8576 *p++ = ':';
8577 *p = '\0';
8578
8579 putpkt_binary (rs->buf, (int) (p - rs->buf));
8580 getpkt (&rs->buf, &rs->buf_size, 0);
8581
8582 if (rs->buf[0] == '\0')
8583 {
8584 if (remote_debug)
8585 fprintf_unfiltered (gdb_stdlog,
8586 "binary downloading NOT "
8587 "supported by target\n");
8588 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8589 }
8590 else
8591 {
8592 if (remote_debug)
8593 fprintf_unfiltered (gdb_stdlog,
8594 "binary downloading supported by target\n");
8595 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8596 }
8597 break;
8598 }
8599 }
8600 }
8601
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
8606 static int
8607 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8608 {
8609 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8610 }
8611
8612 /* Write memory data directly to the remote machine.
8613 This does not inform the data cache; the data cache uses this.
8614 HEADER is the starting part of the packet.
8615 MEMADDR is the address in the remote memory space.
8616 MYADDR is the address of the buffer in our space.
8617 LEN_UNITS is the number of addressable units to write.
8618 UNIT_SIZE is the length in bytes of an addressable unit.
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
8625 where encoding of <DATA> is terminated by PACKET_FORMAT.
8626
8627 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8628 are omitted.
8629
8630 Return the transferred status, error or OK (an
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 */
8646
8647 target_xfer_status
8648 remote_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)
8654 {
8655 struct remote_state *rs = get_remote_state ();
8656 char *p;
8657 char *plen = NULL;
8658 int plenlen = 0;
8659 int todo_units;
8660 int units_written;
8661 int payload_capacity_bytes;
8662 int payload_length_bytes;
8663
8664 if (packet_format != 'X' && packet_format != 'M')
8665 internal_error (__FILE__, __LINE__,
8666 _("remote_write_bytes_aux: bad packet format"));
8667
8668 if (len_units == 0)
8669 return TARGET_XFER_EOF;
8670
8671 payload_capacity_bytes = get_memory_write_packet_size ();
8672
8673 /* The packet buffer will be large enough for the payload;
8674 get_memory_packet_size ensures this. */
8675 rs->buf[0] = '\0';
8676
8677 /* Compute the size of the actual payload by subtracting out the
8678 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8679
8680 payload_capacity_bytes -= strlen ("$,:#NN");
8681 if (!use_length)
8682 /* The comma won't be used. */
8683 payload_capacity_bytes += 1;
8684 payload_capacity_bytes -= strlen (header);
8685 payload_capacity_bytes -= hexnumlen (memaddr);
8686
8687 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8688
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')
8694 {
8695 /* Best guess at number of bytes that will fit. */
8696 todo_units = std::min (len_units,
8697 (ULONGEST) payload_capacity_bytes / unit_size);
8698 if (use_length)
8699 payload_capacity_bytes -= hexnumlen (todo_units);
8700 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8701 }
8702 else
8703 {
8704 /* Number of bytes that will fit. */
8705 todo_units
8706 = std::min (len_units,
8707 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8708 if (use_length)
8709 payload_capacity_bytes -= hexnumlen (todo_units);
8710 todo_units = std::min (todo_units,
8711 (payload_capacity_bytes / unit_size) / 2);
8712 }
8713
8714 if (todo_units <= 0)
8715 internal_error (__FILE__, __LINE__,
8716 _("minimum packet size too small to write data"));
8717
8718 /* If we already need another packet, then try to align the end
8719 of this packet to a useful boundary. */
8720 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8721 todo_units = align_for_efficient_write (todo_units, memaddr);
8722
8723 /* Append "<memaddr>". */
8724 memaddr = remote_address_masked (memaddr);
8725 p += hexnumstr (p, (ULONGEST) memaddr);
8726
8727 if (use_length)
8728 {
8729 /* Append ",". */
8730 *p++ = ',';
8731
8732 /* Append the length and retain its location and size. It may need to be
8733 adjusted once the packet body has been created. */
8734 plen = p;
8735 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8736 p += plenlen;
8737 }
8738
8739 /* Append ":". */
8740 *p++ = ':';
8741 *p = '\0';
8742
8743 /* Append the packet body. */
8744 if (packet_format == 'X')
8745 {
8746 /* Binary mode. Send target system values byte by byte, in
8747 increasing byte addresses. Only escape certain critical
8748 characters. */
8749 payload_length_bytes =
8750 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8751 &units_written, payload_capacity_bytes);
8752
8753 /* If not all TODO units fit, then we'll need another packet. Make
8754 a second try to keep the end of the packet aligned. Don't do
8755 this if the packet is tiny. */
8756 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8757 {
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);
8767 }
8768
8769 p += payload_length_bytes;
8770 if (use_length && units_written < todo_units)
8771 {
8772 /* Escape chars have filled up the buffer prematurely,
8773 and we have actually sent fewer units than planned.
8774 Fix-up the length field of the packet. Use the same
8775 number of characters as before. */
8776 plen += hexnumnstr (plen, (ULONGEST) units_written,
8777 plenlen);
8778 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8779 }
8780 }
8781 else
8782 {
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. */
8786 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8787 units_written = todo_units;
8788 }
8789
8790 putpkt_binary (rs->buf, (int) (p - rs->buf));
8791 getpkt (&rs->buf, &rs->buf_size, 0);
8792
8793 if (rs->buf[0] == 'E')
8794 return TARGET_XFER_E_IO;
8795
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;
8799 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8800 }
8801
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
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. */
8811
8812 target_xfer_status
8813 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8814 ULONGEST len, int unit_size,
8815 ULONGEST *xfered_len)
8816 {
8817 const char *packet_format = NULL;
8818
8819 /* Check whether the target supports binary download. */
8820 check_binary_download (memaddr);
8821
8822 switch (packet_support (PACKET_X))
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,
8838 memaddr, myaddr, len, unit_size, xfered_len,
8839 packet_format[0], 1);
8840 }
8841
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.
8846 LEN_UNITS is the number of addressable memory units to read..
8847 UNIT_SIZE is the length in bytes of an addressable unit.
8848
8849 Return the transferred status, error or OK (an
8850 'enum target_xfer_status' value). Save the number of bytes
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. */
8855
8856 target_xfer_status
8857 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8858 ULONGEST len_units,
8859 int unit_size, ULONGEST *xfered_len_units)
8860 {
8861 struct remote_state *rs = get_remote_state ();
8862 int buf_size_bytes; /* Max size of packet output buffer. */
8863 char *p;
8864 int todo_units;
8865 int decoded_bytes;
8866
8867 buf_size_bytes = get_memory_read_packet_size ();
8868 /* The packet buffer will be large enough for the payload;
8869 get_memory_packet_size ensures this. */
8870
8871 /* Number of units that will fit. */
8872 todo_units = std::min (len_units,
8873 (ULONGEST) (buf_size_bytes / unit_size) / 2);
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++ = ',';
8881 p += hexnumstr (p, (ULONGEST) todo_units);
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;
8892 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8893 /* Return what we have. Let higher layers handle partial reads. */
8894 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8895 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8896 }
8897
8898 /* Using the set of read-only target sections of remote, read live
8899 read-only memory.
8900
8901 For interface/parameters/return description see target.h,
8902 to_xfer_partial. */
8903
8904 target_xfer_status
8905 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8906 ULONGEST memaddr,
8907 ULONGEST len,
8908 int unit_size,
8909 ULONGEST *xfered_len)
8910 {
8911 struct target_section *secp;
8912 struct target_section_table *table;
8913
8914 secp = target_section_by_addr (this, memaddr);
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
8923 table = target_get_section_table (this);
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. */
8932 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8933 xfered_len);
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;
8944 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8945 xfered_len);
8946 }
8947 }
8948 }
8949 }
8950
8951 return TARGET_XFER_EOF;
8952 }
8953
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. */
8957
8958 target_xfer_status
8959 remote_target::remote_read_bytes (CORE_ADDR memaddr,
8960 gdb_byte *myaddr, ULONGEST len, int unit_size,
8961 ULONGEST *xfered_len)
8962 {
8963 if (len == 0)
8964 return TARGET_XFER_EOF;
8965
8966 if (get_traceframe_number () != -1)
8967 {
8968 std::vector<mem_range> available;
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 {
8976 if (available.empty () || available[0].start != memaddr)
8977 {
8978 enum target_xfer_status res;
8979
8980 /* Don't read into the traceframe's available
8981 memory. */
8982 if (!available.empty ())
8983 {
8984 LONGEST oldlen = len;
8985
8986 len = available[0].start - memaddr;
8987 gdb_assert (len <= oldlen);
8988 }
8989
8990 /* This goes through the topmost target again. */
8991 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
8992 len, unit_size, xfered_len);
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;
9000 return (*xfered_len != 0) ?
9001 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
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). */
9009 len = available[0].length;
9010 }
9011 }
9012
9013 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9014 }
9015
9016 \f
9017
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
9022 packet_result
9023 remote_target::remote_send_printf (const char *format, ...)
9024 {
9025 struct remote_state *rs = get_remote_state ();
9026 int max_size = get_remote_packet_size ();
9027 va_list ap;
9028
9029 va_start (ap, format);
9030
9031 rs->buf[0] = '\0';
9032 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9033 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
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
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. */
9047 static const int remote_flash_timeout = 1000;
9048
9049 void
9050 remote_target::flash_erase (ULONGEST address, LONGEST length)
9051 {
9052 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9053 enum packet_result ret;
9054 scoped_restore restore_timeout
9055 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9056
9057 ret = remote_send_printf ("vFlashErase:%s,%s",
9058 phex (address, addr_size),
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 }
9069 }
9070
9071 target_xfer_status
9072 remote_target::remote_flash_write (ULONGEST address,
9073 ULONGEST length, ULONGEST *xfered_len,
9074 const gdb_byte *data)
9075 {
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);
9080 }
9081
9082 void
9083 remote_target::flash_done ()
9084 {
9085 int ret;
9086
9087 scoped_restore restore_timeout
9088 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9089
9090 ret = remote_send_printf ("vFlashDone");
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
9103 void
9104 remote_target::files_info ()
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
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,
9115 the system error message for errno at function entry and final dot
9116 for output compatibility with throw_perror_with_name. */
9117
9118 static void
9119 unpush_and_perror (const char *string)
9120 {
9121 int saved_errno = errno;
9122
9123 remote_unpush_target ();
9124 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9125 safe_strerror (saved_errno));
9126 }
9127
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. */
9132
9133 int
9134 remote_target::readchar (int timeout)
9135 {
9136 int ch;
9137 struct remote_state *rs = get_remote_state ();
9138
9139 {
9140 scoped_restore restore_quit_target
9141 = make_scoped_restore (&curr_quit_handler_target, this);
9142 scoped_restore restore_quit
9143 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9144
9145 rs->got_ctrlc_during_io = 0;
9146
9147 ch = serial_readchar (rs->remote_desc, timeout);
9148
9149 if (rs->got_ctrlc_during_io)
9150 set_quit_flag ();
9151 }
9152
9153 if (ch >= 0)
9154 return ch;
9155
9156 switch ((enum serial_rc) ch)
9157 {
9158 case SERIAL_EOF:
9159 remote_unpush_target ();
9160 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9161 /* no return */
9162 case SERIAL_ERROR:
9163 unpush_and_perror (_("Remote communication error. "
9164 "Target disconnected."));
9165 /* no return */
9166 case SERIAL_TIMEOUT:
9167 break;
9168 }
9169 return ch;
9170 }
9171
9172 /* Wrapper for serial_write that closes the target and throws if
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. */
9177
9178 void
9179 remote_target::remote_serial_write (const char *str, int len)
9180 {
9181 struct remote_state *rs = get_remote_state ();
9182
9183 scoped_restore restore_quit_target
9184 = make_scoped_restore (&curr_quit_handler_target, this);
9185 scoped_restore restore_quit
9186 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9187
9188 rs->got_ctrlc_during_io = 0;
9189
9190 if (serial_write (rs->remote_desc, str, len))
9191 {
9192 unpush_and_perror (_("Remote communication error. "
9193 "Target disconnected."));
9194 }
9195
9196 if (rs->got_ctrlc_during_io)
9197 set_quit_flag ();
9198 }
9199
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. */
9202
9203 static std::string
9204 escape_buffer (const char *buf, int n)
9205 {
9206 string_file stb;
9207
9208 stb.putstrn (buf, n, '\\');
9209 return std::move (stb.string ());
9210 }
9211
9212 /* Display a null-terminated packet on stdout, for debugging, using C
9213 string notation. */
9214
9215 static void
9216 print_packet (const char *buf)
9217 {
9218 puts_filtered ("\"");
9219 fputstr_filtered (buf, '"', gdb_stdout);
9220 puts_filtered ("\"");
9221 }
9222
9223 int
9224 remote_target::putpkt (const char *buf)
9225 {
9226 return putpkt_binary (buf, strlen (buf));
9227 }
9228
9229 /* Wrapper around remote_target::putpkt to avoid exporting
9230 remote_target. */
9231
9232 int
9233 putpkt (remote_target *remote, const char *buf)
9234 {
9235 return remote->putpkt (buf);
9236 }
9237
9238 /* Send a packet to the remote machine, with error checking. The data
9239 of the packet is in BUF. The string in BUF can be at most
9240 get_remote_packet_size () - 5 to account for the $, # and checksum,
9241 and for a possible /0 if we are debugging (remote_debug) and want
9242 to print the sent packet as a string. */
9243
9244 int
9245 remote_target::putpkt_binary (const char *buf, int cnt)
9246 {
9247 struct remote_state *rs = get_remote_state ();
9248 int i;
9249 unsigned char csum = 0;
9250 gdb::def_vector<char> data (cnt + 6);
9251 char *buf2 = data.data ();
9252
9253 int ch;
9254 int tcount = 0;
9255 char *p;
9256
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
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. */
9264 if (!target_is_non_stop_p ()
9265 && target_is_async_p ()
9266 && rs->waiting_for_stop_reply)
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 }
9272
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
9277 /* Copy the packet into buffer BUF2, encapsulating it
9278 and giving it a checksum. */
9279
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';
9301
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
9309 if (len > REMOTE_DEBUG_MAX_CHAR)
9310 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9311 len - REMOTE_DEBUG_MAX_CHAR);
9312
9313 fprintf_unfiltered (gdb_stdlog, "...");
9314
9315 gdb_flush (gdb_stdlog);
9316 }
9317 remote_serial_write (buf2, p - buf2);
9318
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
9324 /* Read until either a timeout occurs (-2) or '+' is read.
9325 Handle any notification that arrives in the mean time. */
9326 while (1)
9327 {
9328 ch = readchar (remote_timeout);
9329
9330 if (remote_debug)
9331 {
9332 switch (ch)
9333 {
9334 case '+':
9335 case '-':
9336 case SERIAL_TIMEOUT:
9337 case '$':
9338 case '%':
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)
9351 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9352 return 1;
9353 case '-':
9354 if (remote_debug)
9355 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9356 /* FALLTHROUGH */
9357 case SERIAL_TIMEOUT:
9358 tcount++;
9359 if (tcount > 3)
9360 return 0;
9361 break; /* Retransmit buffer. */
9362 case '$':
9363 {
9364 if (remote_debug)
9365 fprintf_unfiltered (gdb_stdlog,
9366 "Packet instead of Ack, ignoring it\n");
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. */
9371 skip_frame ();
9372 remote_serial_write ("+", 1);
9373 continue; /* Now, go look for +. */
9374 }
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 {
9389 std::string str = escape_buffer (rs->buf, val);
9390
9391 fprintf_unfiltered (gdb_stdlog,
9392 " Notification received: %s\n",
9393 str.c_str ());
9394 }
9395 handle_notification (rs->notif_state, rs->buf);
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 */
9415 default:
9416 if (remote_debug)
9417 {
9418 if (!started_error_output)
9419 {
9420 started_error_output = 1;
9421 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9422 }
9423 fputc_unfiltered (ch & 0177, gdb_stdlog);
9424 }
9425 continue;
9426 }
9427 break; /* Here to retransmit. */
9428 }
9429
9430 #if 0
9431 /* This is wrong. If doing a long backtrace, the user should be
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. */
9436 if (quit_flag)
9437 {
9438 quit_flag = 0;
9439 interrupt_query ();
9440 }
9441 #endif
9442 }
9443
9444 return 0;
9445 }
9446
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
9450 void
9451 remote_target::skip_frame ()
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
9483 /* Come here after finding the start of the frame. Collect the rest
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.
9487
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
9490 SERIAL status indications). */
9491
9492 long
9493 remote_target::read_frame (char **buf_p, long *sizeof_buf)
9494 {
9495 unsigned char csum;
9496 long bc;
9497 int c;
9498 char *buf = *buf_p;
9499 struct remote_state *rs = get_remote_state ();
9500
9501 csum = 0;
9502 bc = 0;
9503
9504 while (1)
9505 {
9506 c = readchar (remote_timeout);
9507 switch (c)
9508 {
9509 case SERIAL_TIMEOUT:
9510 if (remote_debug)
9511 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9512 return -1;
9513 case '$':
9514 if (remote_debug)
9515 fputs_filtered ("Saw new packet start in middle of old one\n",
9516 gdb_stdlog);
9517 return -1; /* Start a new packet, count retries. */
9518 case '#':
9519 {
9520 unsigned char pktcsum;
9521 int check_0 = 0;
9522 int check_1 = 0;
9523
9524 buf[bc] = '\0';
9525
9526 check_0 = readchar (remote_timeout);
9527 if (check_0 >= 0)
9528 check_1 = readchar (remote_timeout);
9529
9530 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9531 {
9532 if (remote_debug)
9533 fputs_filtered ("Timeout in checksum, retrying\n",
9534 gdb_stdlog);
9535 return -1;
9536 }
9537 else if (check_0 < 0 || check_1 < 0)
9538 {
9539 if (remote_debug)
9540 fputs_filtered ("Communication error in checksum\n",
9541 gdb_stdlog);
9542 return -1;
9543 }
9544
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
9551 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9552 if (csum == pktcsum)
9553 return bc;
9554
9555 if (remote_debug)
9556 {
9557 std::string str = escape_buffer (buf, bc);
9558
9559 fprintf_unfiltered (gdb_stdlog,
9560 "Bad checksum, sentsum=0x%x, "
9561 "csum=0x%x, buf=%s\n",
9562 pktcsum, csum, str.c_str ());
9563 }
9564 /* Number of characters in buffer ignoring trailing
9565 NULL. */
9566 return -1;
9567 }
9568 case '*': /* Run length encoding. */
9569 {
9570 int repeat;
9571
9572 csum += c;
9573 c = readchar (remote_timeout);
9574 csum += c;
9575 repeat = c - ' ' + 3; /* Compute repeat count. */
9576
9577 /* The character before ``*'' is repeated. */
9578
9579 if (repeat > 0 && repeat <= 255 && bc > 0)
9580 {
9581 if (bc + repeat - 1 >= *sizeof_buf - 1)
9582 {
9583 /* Make some more room in the buffer. */
9584 *sizeof_buf += repeat;
9585 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9586 buf = *buf_p;
9587 }
9588
9589 memset (&buf[bc], buf[bc - 1], repeat);
9590 bc += repeat;
9591 continue;
9592 }
9593
9594 buf[bc] = '\0';
9595 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9596 return -1;
9597 }
9598 default:
9599 if (bc >= *sizeof_buf - 1)
9600 {
9601 /* Make some more room in the buffer. */
9602 *sizeof_buf *= 2;
9603 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9604 buf = *buf_p;
9605 }
9606
9607 buf[bc++] = c;
9608 csum += c;
9609 continue;
9610 }
9611 }
9612 }
9613
9614 /* Read a packet from the remote machine, with error checking, and
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. */
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
9622 thing to do it for those. */
9623
9624 void
9625 remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
9626 {
9627 getpkt_sane (buf, sizeof_buf, forever);
9628 }
9629
9630
9631 /* Read a packet from the remote machine, with error checking, and
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
9637 indication of this to the caller. Otherwise return the number of
9638 bytes read. If EXPECTING_NOTIF, consider receiving a notification
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). */
9642
9643 int
9644 remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9645 int forever, int expecting_notif,
9646 int *is_notif)
9647 {
9648 struct remote_state *rs = get_remote_state ();
9649 int c;
9650 int tries;
9651 int timeout;
9652 int val = -1;
9653
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
9658 strcpy (*buf, "timeout");
9659
9660 if (forever)
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. */
9665 else
9666 timeout = remote_timeout;
9667
9668 #define MAX_TRIES 3
9669
9670 /* Process any number of notifications, and then return when
9671 we get a packet. */
9672 for (;;)
9673 {
9674 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9675 times. */
9676 for (tries = 1; tries <= MAX_TRIES; tries++)
9677 {
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 != '%');
9690
9691 if (c == SERIAL_TIMEOUT)
9692 {
9693 if (expecting_notif)
9694 return -1; /* Don't complain, it's normal to not get
9695 anything in this case. */
9696
9697 if (forever) /* Watchdog went off? Kill the target. */
9698 {
9699 remote_unpush_target ();
9700 throw_error (TARGET_CLOSE_ERROR,
9701 _("Watchdog timeout has expired. "
9702 "Target detached."));
9703 }
9704 if (remote_debug)
9705 fputs_filtered ("Timed out.\n", gdb_stdlog);
9706 }
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
9716 remote_serial_write ("-", 1);
9717 }
9718
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"));
9724
9725 /* Skip the ack char if we're in no-ack mode. */
9726 if (!rs->noack_mode)
9727 remote_serial_write ("+", 1);
9728 return -1;
9729 }
9730
9731 /* If we got an ordinary packet, return that to our caller. */
9732 if (c == '$')
9733 {
9734 if (remote_debug)
9735 {
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
9743 if (val > REMOTE_DEBUG_MAX_CHAR)
9744 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9745 val - REMOTE_DEBUG_MAX_CHAR);
9746
9747 fprintf_unfiltered (gdb_stdlog, "\n");
9748 }
9749
9750 /* Skip the ack char if we're in no-ack mode. */
9751 if (!rs->noack_mode)
9752 remote_serial_write ("+", 1);
9753 if (is_notif != NULL)
9754 *is_notif = 0;
9755 return val;
9756 }
9757
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 {
9766 std::string str = escape_buffer (*buf, val);
9767
9768 fprintf_unfiltered (gdb_stdlog,
9769 " Notification received: %s\n",
9770 str.c_str ());
9771 }
9772 if (is_notif != NULL)
9773 *is_notif = 1;
9774
9775 handle_notification (rs->notif_state, *buf);
9776
9777 /* Notifications require no acknowledgement. */
9778
9779 if (expecting_notif)
9780 return val;
9781 }
9782 }
9783 }
9784
9785 int
9786 remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
9787 {
9788 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9789 }
9790
9791 int
9792 remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9793 int *is_notif)
9794 {
9795 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9796 is_notif);
9797 }
9798
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
9802 int
9803 remote_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)
9807 {
9808 struct queue_iter_param *param = (struct queue_iter_param *) data;
9809 int parent_pid = *(int *) param->input;
9810
9811 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9812 {
9813 remote_target *remote = param->remote;
9814 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9815 int res;
9816
9817 res = remote->remote_vkill (child_pid);
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
9828 void
9829 remote_target::kill_new_fork_children (int pid)
9830 {
9831 remote_state *rs = get_remote_state ();
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 {
9844 int child_pid = ptid_get_pid (ws->value.related_pid);
9845 int res;
9846
9847 res = remote_vkill (child_pid);
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);
9856 param.remote = this;
9857 param.input = &pid;
9858 param.output = NULL;
9859 QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
9860 remote_kill_child_of_pending_fork, &param);
9861 }
9862
9863 \f
9864 /* Target hook to kill the current inferior. */
9865
9866 void
9867 remote_target::kill ()
9868 {
9869 int res = -1;
9870 int pid = ptid_get_pid (inferior_ptid);
9871 struct remote_state *rs = get_remote_state ();
9872
9873 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9874 {
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. */
9879 kill_new_fork_children (pid);
9880
9881 res = remote_vkill (pid);
9882 if (res == 0)
9883 {
9884 target_mourn_inferior (inferior_ptid);
9885 return;
9886 }
9887 }
9888
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. */
9901 target_mourn_inferior (inferior_ptid);
9902
9903 return;
9904 }
9905
9906 error (_("Can't kill process"));
9907 }
9908
9909 /* Send a kill request to the target using the 'vKill' packet. */
9910
9911 int
9912 remote_target::remote_vkill (int pid)
9913 {
9914 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9915 return -1;
9916
9917 remote_state *rs = get_remote_state ();
9918
9919 /* Tell the remote target to detach. */
9920 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9921 putpkt (rs->buf);
9922 getpkt (&rs->buf, &rs->buf_size, 0);
9923
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 }
9936 }
9937
9938 /* Send a kill request to the target using the 'k' packet. */
9939
9940 void
9941 remote_target::remote_kill_k ()
9942 {
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
9946 {
9947 putpkt ("k");
9948 }
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 }
9961
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
9968 }
9969
9970 void
9971 remote_target::mourn_inferior ()
9972 {
9973 struct remote_state *rs = get_remote_state ();
9974
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
9979 /* In 'target remote' mode with one inferior, we close the connection. */
9980 if (!rs->extended && number_of_live_inferiors () <= 1)
9981 {
9982 unpush_target (this);
9983
9984 /* remote_close takes care of doing most of the clean up. */
9985 generic_mourn_inferior ();
9986 return;
9987 }
9988
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
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. */
10016 record_currthread (rs, minus_one_ptid);
10017
10018 /* Call common code to mark the inferior as not running. */
10019 generic_mourn_inferior ();
10020
10021 if (!have_inferiors ())
10022 {
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 {
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. */
10036 inferior_ptid = magic_null_ptid;
10037 }
10038 }
10039 }
10040 }
10041
10042 bool
10043 extended_remote_target::supports_disable_randomization ()
10044 {
10045 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10046 }
10047
10048 void
10049 remote_target::extended_remote_disable_randomization (int val)
10050 {
10051 struct remote_state *rs = get_remote_state ();
10052 char *reply;
10053
10054 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
10055 val);
10056 putpkt (rs->buf);
10057 reply = remote_get_noisy_reply ();
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
10064 int
10065 remote_target::extended_remote_run (const std::string &args)
10066 {
10067 struct remote_state *rs = get_remote_state ();
10068 int len;
10069 const char *remote_exec_file = get_remote_exec_file ();
10070
10071 /* If the user has disabled vRun support, or we have detected that
10072 support is not available, do not try it. */
10073 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10074 return -1;
10075
10076 strcpy (rs->buf, "vRun;");
10077 len = strlen (rs->buf);
10078
10079 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10080 error (_("Remote file name too long for run packet"));
10081 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
10082 strlen (remote_exec_file));
10083
10084 if (!args.empty ())
10085 {
10086 int i;
10087
10088 gdb_argv argv (args.c_str ());
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++] = ';';
10094 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
10095 strlen (argv[i]));
10096 }
10097 }
10098
10099 rs->buf[len++] = '\0';
10100
10101 putpkt (rs->buf);
10102 getpkt (&rs->buf, &rs->buf_size, 0);
10103
10104 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10105 {
10106 case PACKET_OK:
10107 /* We have a wait response. All is well. */
10108 return 0;
10109 case PACKET_UNKNOWN:
10110 return -1;
10111 case PACKET_ERROR:
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);
10118 default:
10119 gdb_assert_not_reached (_("bad switch"));
10120 }
10121 }
10122
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
10128 void
10129 remote_target::send_environment_packet (const char *action,
10130 const char *packet,
10131 const char *value)
10132 {
10133 remote_state *rs = get_remote_state ();
10134
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
10152 void
10153 remote_target::extended_remote_environment_support ()
10154 {
10155 remote_state *rs = get_remote_state ();
10156
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 ())
10169 send_environment_packet ("set", "QEnvironmentHexEncoded",
10170 el.c_str ());
10171
10172 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10173 for (const std::string &el : e->user_unset_env ())
10174 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10175 }
10176
10177 /* Helper function to set the current working directory for the
10178 inferior in the remote target. */
10179
10180 void
10181 remote_target::extended_remote_set_inferior_cwd ()
10182 {
10183 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10184 {
10185 const char *inferior_cwd = get_inferior_cwd ();
10186 remote_state *rs = get_remote_state ();
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 (_("\
10210 Remote replied unexpectedly while setting the inferior's working\n\
10211 directory: %s"),
10212 rs->buf);
10213
10214 }
10215 }
10216
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
10223 void
10224 extended_remote_target::create_inferior (const char *exec_file,
10225 const std::string &args,
10226 char **env, int from_tty)
10227 {
10228 int run_worked;
10229 char *stop_reply;
10230 struct remote_state *rs = get_remote_state ();
10231 const char *remote_exec_file = get_remote_exec_file ();
10232
10233 /* If running asynchronously, register the target file descriptor
10234 with the event loop. */
10235 if (target_can_async_p ())
10236 target_async (1);
10237
10238 /* Disable address space randomization if requested (and supported). */
10239 if (supports_disable_randomization ())
10240 extended_remote_disable_randomization (disable_randomization);
10241
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 (_("\
10252 Remote replied unexpectedly while setting startup-with-shell: %s"),
10253 rs->buf);
10254 }
10255
10256 extended_remote_environment_support ();
10257
10258 extended_remote_set_inferior_cwd ();
10259
10260 /* Now restart the remote server. */
10261 run_worked = extended_remote_run (args) != -1;
10262 if (!run_worked)
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\""));
10268 if (!args.empty ())
10269 error (_("Remote target does not support \"set args\" or run <ARGS>"));
10270
10271 /* Fall back to "R". */
10272 extended_remote_restart ();
10273 }
10274
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 }
10283
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);
10287
10288 /* Get updated offsets, if the stub uses qOffsets. */
10289 get_offsets ();
10290 }
10291 \f
10292
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
10296 started from BUF and ended at BUF_END. */
10297
10298 static int
10299 remote_add_target_side_condition (struct gdbarch *gdbarch,
10300 struct bp_target_info *bp_tgt, char *buf,
10301 char *buf_end)
10302 {
10303 if (bp_tgt->conditions.empty ())
10304 return 0;
10305
10306 buf += strlen (buf);
10307 xsnprintf (buf, buf_end - buf, "%s", ";");
10308 buf++;
10309
10310 /* Send conditions to the target. */
10311 for (agent_expr *aexpr : bp_tgt->conditions)
10312 {
10313 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10314 buf += strlen (buf);
10315 for (int i = 0; i < aexpr->len; ++i)
10316 buf = pack_hex_byte (buf, aexpr->buf[i]);
10317 *buf = '\0';
10318 }
10319 return 0;
10320 }
10321
10322 static void
10323 remote_add_target_side_commands (struct gdbarch *gdbarch,
10324 struct bp_target_info *bp_tgt, char *buf)
10325 {
10326 if (bp_tgt->tcommands.empty ())
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. */
10336 for (agent_expr *aexpr : bp_tgt->tcommands)
10337 {
10338 sprintf (buf, "X%x,", aexpr->len);
10339 buf += strlen (buf);
10340 for (int i = 0; i < aexpr->len; ++i)
10341 buf = pack_hex_byte (buf, aexpr->buf[i]);
10342 *buf = '\0';
10343 }
10344 }
10345
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. */
10349
10350 int
10351 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10352 struct bp_target_info *bp_tgt)
10353 {
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
10357 report an error, otherwise, mark it disabled and go on. */
10358
10359 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10360 {
10361 CORE_ADDR addr = bp_tgt->reqstd_address;
10362 struct remote_state *rs;
10363 char *p, *endbuf;
10364
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
10370 rs = get_remote_state ();
10371 p = rs->buf;
10372 endbuf = rs->buf + get_remote_packet_size ();
10373
10374 *(p++) = 'Z';
10375 *(p++) = '0';
10376 *(p++) = ',';
10377 addr = (ULONGEST) remote_address_masked (addr);
10378 p += hexnumstr (p, addr);
10379 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10380
10381 if (supports_evaluation_of_breakpoint_conditions ())
10382 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10383
10384 if (can_run_breakpoint_commands ())
10385 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10386
10387 putpkt (rs->buf);
10388 getpkt (&rs->buf, &rs->buf_size, 0);
10389
10390 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10391 {
10392 case PACKET_ERROR:
10393 return -1;
10394 case PACKET_OK:
10395 return 0;
10396 case PACKET_UNKNOWN:
10397 break;
10398 }
10399 }
10400
10401 /* If this breakpoint has target-side commands but this stub doesn't
10402 support Z0 packets, throw error. */
10403 if (!bp_tgt->tcommands.empty ())
10404 throw_error (NOT_SUPPORTED_ERROR, _("\
10405 Target doesn't support breakpoints that have target side commands."));
10406
10407 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10408 }
10409
10410 int
10411 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10412 struct bp_target_info *bp_tgt,
10413 enum remove_bp_reason reason)
10414 {
10415 CORE_ADDR addr = bp_tgt->placed_address;
10416 struct remote_state *rs = get_remote_state ();
10417
10418 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10419 {
10420 char *p = rs->buf;
10421 char *endbuf = rs->buf + get_remote_packet_size ();
10422
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
10428 *(p++) = 'z';
10429 *(p++) = '0';
10430 *(p++) = ',';
10431
10432 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10433 p += hexnumstr (p, addr);
10434 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10435
10436 putpkt (rs->buf);
10437 getpkt (&rs->buf, &rs->buf_size, 0);
10438
10439 return (rs->buf[0] == 'E');
10440 }
10441
10442 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10443 }
10444
10445 static enum Z_packet_type
10446 watchpoint_to_Z_packet (int type)
10447 {
10448 switch (type)
10449 {
10450 case hw_write:
10451 return Z_PACKET_WRITE_WP;
10452 break;
10453 case hw_read:
10454 return Z_PACKET_READ_WP;
10455 break;
10456 case hw_access:
10457 return Z_PACKET_ACCESS_WP;
10458 break;
10459 default:
10460 internal_error (__FILE__, __LINE__,
10461 _("hw_bp_to_z: bad watchpoint type %d"), type);
10462 }
10463 }
10464
10465 int
10466 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10467 enum target_hw_bp_type type, struct expression *cond)
10468 {
10469 struct remote_state *rs = get_remote_state ();
10470 char *endbuf = rs->buf + get_remote_packet_size ();
10471 char *p;
10472 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10473
10474 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10475 return 1;
10476
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
10482 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10483 p = strchr (rs->buf, '\0');
10484 addr = remote_address_masked (addr);
10485 p += hexnumstr (p, (ULONGEST) addr);
10486 xsnprintf (p, endbuf - p, ",%x", len);
10487
10488 putpkt (rs->buf);
10489 getpkt (&rs->buf, &rs->buf_size, 0);
10490
10491 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10492 {
10493 case PACKET_ERROR:
10494 return -1;
10495 case PACKET_UNKNOWN:
10496 return 1;
10497 case PACKET_OK:
10498 return 0;
10499 }
10500 internal_error (__FILE__, __LINE__,
10501 _("remote_insert_watchpoint: reached end of function"));
10502 }
10503
10504 bool
10505 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10506 CORE_ADDR start, int length)
10507 {
10508 CORE_ADDR diff = remote_address_masked (addr - start);
10509
10510 return diff < length;
10511 }
10512
10513
10514 int
10515 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10516 enum target_hw_bp_type type, struct expression *cond)
10517 {
10518 struct remote_state *rs = get_remote_state ();
10519 char *endbuf = rs->buf + get_remote_packet_size ();
10520 char *p;
10521 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10522
10523 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10524 return -1;
10525
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
10531 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10532 p = strchr (rs->buf, '\0');
10533 addr = remote_address_masked (addr);
10534 p += hexnumstr (p, (ULONGEST) addr);
10535 xsnprintf (p, endbuf - p, ",%x", len);
10536 putpkt (rs->buf);
10537 getpkt (&rs->buf, &rs->buf_size, 0);
10538
10539 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10540 {
10541 case PACKET_ERROR:
10542 case PACKET_UNKNOWN:
10543 return -1;
10544 case PACKET_OK:
10545 return 0;
10546 }
10547 internal_error (__FILE__, __LINE__,
10548 _("remote_remove_watchpoint: reached end of function"));
10549 }
10550
10551
10552 int remote_hw_watchpoint_limit = -1;
10553 int remote_hw_watchpoint_length_limit = -1;
10554 int remote_hw_breakpoint_limit = -1;
10555
10556 int
10557 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
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
10569 int
10570 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10571 {
10572 if (type == bp_hardware_breakpoint)
10573 {
10574 if (remote_hw_breakpoint_limit == 0)
10575 return 0;
10576 else if (remote_hw_breakpoint_limit < 0)
10577 return 1;
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;
10585 else if (remote_hw_watchpoint_limit < 0)
10586 return 1;
10587 else if (ot)
10588 return -1;
10589 else if (cnt <= remote_hw_watchpoint_limit)
10590 return 1;
10591 }
10592 return -1;
10593 }
10594
10595 /* The to_stopped_by_sw_breakpoint method of target remote. */
10596
10597 bool
10598 remote_target::stopped_by_sw_breakpoint ()
10599 {
10600 struct thread_info *thread = inferior_thread ();
10601
10602 return (thread->priv != NULL
10603 && (get_remote_thread_info (thread)->stop_reason
10604 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10605 }
10606
10607 /* The to_supports_stopped_by_sw_breakpoint method of target
10608 remote. */
10609
10610 bool
10611 remote_target::supports_stopped_by_sw_breakpoint ()
10612 {
10613 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10614 }
10615
10616 /* The to_stopped_by_hw_breakpoint method of target remote. */
10617
10618 bool
10619 remote_target::stopped_by_hw_breakpoint ()
10620 {
10621 struct thread_info *thread = inferior_thread ();
10622
10623 return (thread->priv != NULL
10624 && (get_remote_thread_info (thread)->stop_reason
10625 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10626 }
10627
10628 /* The to_supports_stopped_by_hw_breakpoint method of target
10629 remote. */
10630
10631 bool
10632 remote_target::supports_stopped_by_hw_breakpoint ()
10633 {
10634 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10635 }
10636
10637 bool
10638 remote_target::stopped_by_watchpoint ()
10639 {
10640 struct thread_info *thread = inferior_thread ();
10641
10642 return (thread->priv != NULL
10643 && (get_remote_thread_info (thread)->stop_reason
10644 == TARGET_STOPPED_BY_WATCHPOINT));
10645 }
10646
10647 bool
10648 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10649 {
10650 struct thread_info *thread = inferior_thread ();
10651
10652 if (thread->priv != NULL
10653 && (get_remote_thread_info (thread)->stop_reason
10654 == TARGET_STOPPED_BY_WATCHPOINT))
10655 {
10656 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10657 return true;
10658 }
10659
10660 return false;
10661 }
10662
10663
10664 int
10665 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10666 struct bp_target_info *bp_tgt)
10667 {
10668 CORE_ADDR addr = bp_tgt->reqstd_address;
10669 struct remote_state *rs;
10670 char *p, *endbuf;
10671 char *message;
10672
10673 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10674 return -1;
10675
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
10681 rs = get_remote_state ();
10682 p = rs->buf;
10683 endbuf = rs->buf + get_remote_packet_size ();
10684
10685 *(p++) = 'Z';
10686 *(p++) = '1';
10687 *(p++) = ',';
10688
10689 addr = remote_address_masked (addr);
10690 p += hexnumstr (p, (ULONGEST) addr);
10691 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10692
10693 if (supports_evaluation_of_breakpoint_conditions ())
10694 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10695
10696 if (can_run_breakpoint_commands ())
10697 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10698
10699 putpkt (rs->buf);
10700 getpkt (&rs->buf, &rs->buf_size, 0);
10701
10702 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10703 {
10704 case PACKET_ERROR:
10705 if (rs->buf[1] == '.')
10706 {
10707 message = strchr (rs->buf + 2, '.');
10708 if (message)
10709 error (_("Remote failure reply: %s"), message + 1);
10710 }
10711 return -1;
10712 case PACKET_UNKNOWN:
10713 return -1;
10714 case PACKET_OK:
10715 return 0;
10716 }
10717 internal_error (__FILE__, __LINE__,
10718 _("remote_insert_hw_breakpoint: reached end of function"));
10719 }
10720
10721
10722 int
10723 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10724 struct bp_target_info *bp_tgt)
10725 {
10726 CORE_ADDR addr;
10727 struct remote_state *rs = get_remote_state ();
10728 char *p = rs->buf;
10729 char *endbuf = rs->buf + get_remote_packet_size ();
10730
10731 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10732 return -1;
10733
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
10739 *(p++) = 'z';
10740 *(p++) = '1';
10741 *(p++) = ',';
10742
10743 addr = remote_address_masked (bp_tgt->placed_address);
10744 p += hexnumstr (p, (ULONGEST) addr);
10745 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10746
10747 putpkt (rs->buf);
10748 getpkt (&rs->buf, &rs->buf_size, 0);
10749
10750 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10751 {
10752 case PACKET_ERROR:
10753 case PACKET_UNKNOWN:
10754 return -1;
10755 case PACKET_OK:
10756 return 0;
10757 }
10758 internal_error (__FILE__, __LINE__,
10759 _("remote_remove_hw_breakpoint: reached end of function"));
10760 }
10761
10762 /* Verify memory using the "qCRC:" request. */
10763
10764 int
10765 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10766 {
10767 struct remote_state *rs = get_remote_state ();
10768 unsigned long host_crc, target_crc;
10769 char *tmp;
10770
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;
10776
10777 /* Make sure the remote is pointing at the right process. */
10778 set_general_process ();
10779
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);
10784
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);
10790
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);
10799
10800 return (host_crc == target_crc);
10801 }
10802 }
10803
10804 return simple_verify_memory (this, data, lma, size);
10805 }
10806
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.
10811 Useful for verifying the image on the target against the exec file. */
10812
10813 static void
10814 compare_sections_command (const char *args, int from_tty)
10815 {
10816 asection *s;
10817 const char *sectname;
10818 bfd_size_type size;
10819 bfd_vma lma;
10820 int matched = 0;
10821 int mismatched = 0;
10822 int res;
10823 int read_only = 0;
10824
10825 if (!exec_bfd)
10826 error (_("command cannot be used without an exec file"));
10827
10828 if (args != NULL && strcmp (args, "-r") == 0)
10829 {
10830 read_only = 1;
10831 args = NULL;
10832 }
10833
10834 for (s = exec_bfd->sections; s; s = s->next)
10835 {
10836 if (!(s->flags & SEC_LOAD))
10837 continue; /* Skip non-loadable section. */
10838
10839 if (read_only && (s->flags & SEC_READONLY) == 0)
10840 continue; /* Skip writeable sections */
10841
10842 size = bfd_get_section_size (s);
10843 if (size == 0)
10844 continue; /* Skip zero-length section. */
10845
10846 sectname = bfd_get_section_name (exec_bfd, s);
10847 if (args && strcmp (args, sectname) != 0)
10848 continue; /* Not the section selected by user. */
10849
10850 matched = 1; /* Do this section. */
10851 lma = s->lma;
10852
10853 gdb::byte_vector sectdata (size);
10854 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10855
10856 res = target_verify_memory (sectdata.data (), lma, size);
10857
10858 if (res == -1)
10859 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10860 paddress (target_gdbarch (), lma),
10861 paddress (target_gdbarch (), lma + size));
10862
10863 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10864 paddress (target_gdbarch (), lma),
10865 paddress (target_gdbarch (), lma + size));
10866 if (res)
10867 printf_filtered ("matched.\n");
10868 else
10869 {
10870 printf_filtered ("MIS-MATCHED!\n");
10871 mismatched++;
10872 }
10873 }
10874 if (mismatched > 0)
10875 warning (_("One or more sections of the target image does not match\n\
10876 the loaded file\n"));
10877 if (args && !matched)
10878 printf_filtered (_("No loaded section named '%s'.\n"), args);
10879 }
10880
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
10885 target_xfer_status
10886 remote_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)
10891 {
10892 int i, buf_len;
10893 ULONGEST n;
10894 struct remote_state *rs = get_remote_state ();
10895 int max_size = get_memory_write_packet_size ();
10896
10897 if (packet_config_support (packet) == PACKET_DISABLE)
10898 return TARGET_XFER_E_IO;
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
10909 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
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)
10914 return TARGET_XFER_E_IO;
10915
10916 unpack_varlen_hex (rs->buf, &n);
10917
10918 *xfered_len = n;
10919 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10920 }
10921
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
10929 target_xfer_status
10930 remote_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)
10936 {
10937 struct remote_state *rs = get_remote_state ();
10938 LONGEST i, n, packet_len;
10939
10940 if (packet_config_support (packet) == PACKET_DISABLE)
10941 return TARGET_XFER_E_IO;
10942
10943 /* Check whether we've cached an end-of-object packet that matches
10944 this request. */
10945 if (rs->finished_object)
10946 {
10947 if (strcmp (object_name, rs->finished_object) == 0
10948 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10949 && offset == rs->finished_offset)
10950 return TARGET_XFER_EOF;
10951
10952
10953 /* Otherwise, we're now reading something different. Discard
10954 the cache. */
10955 xfree (rs->finished_object);
10956 xfree (rs->finished_annex);
10957 rs->finished_object = NULL;
10958 rs->finished_annex = NULL;
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. */
10965 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
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)
10972 return TARGET_XFER_E_IO;
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)
10977 return TARGET_XFER_E_IO;
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. */
10989 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10990 packet_len - 1, readbuf, n);
10991
10992 /* 'l' is an EOF marker, possibly including a final block of data,
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)
10996 {
10997 rs->finished_object = xstrdup (object_name);
10998 rs->finished_annex = xstrdup (annex ? annex : "");
10999 rs->finished_offset = offset + i;
11000 }
11001
11002 if (i == 0)
11003 return TARGET_XFER_EOF;
11004 else
11005 {
11006 *xfered_len = i;
11007 return TARGET_XFER_OK;
11008 }
11009 }
11010
11011 enum target_xfer_status
11012 remote_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)
11016 {
11017 struct remote_state *rs;
11018 int i;
11019 char *p2;
11020 char query_type;
11021 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11022
11023 set_remote_traceframe ();
11024 set_general_thread (inferior_ptid);
11025
11026 rs = get_remote_state ();
11027
11028 /* Handle memory using the standard memory routines. */
11029 if (object == TARGET_OBJECT_MEMORY)
11030 {
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)
11035 return TARGET_XFER_EOF;
11036
11037 if (writebuf != NULL)
11038 return remote_write_bytes (offset, writebuf, len, unit_size,
11039 xfered_len);
11040 else
11041 return remote_read_bytes (offset, readbuf, len, unit_size,
11042 xfered_len);
11043 }
11044
11045 /* Handle SPU memory using qxfer packets. */
11046 if (object == TARGET_OBJECT_SPU)
11047 {
11048 if (readbuf)
11049 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
11050 xfered_len, &remote_protocol_packets
11051 [PACKET_qXfer_spu_read]);
11052 else
11053 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
11054 xfered_len, &remote_protocol_packets
11055 [PACKET_qXfer_spu_write]);
11056 }
11057
11058 /* Handle extra signal info using qxfer packets. */
11059 if (object == TARGET_OBJECT_SIGNAL_INFO)
11060 {
11061 if (readbuf)
11062 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11063 xfered_len, &remote_protocol_packets
11064 [PACKET_qXfer_siginfo_read]);
11065 else
11066 return remote_write_qxfer ("siginfo", annex,
11067 writebuf, offset, len, xfered_len,
11068 &remote_protocol_packets
11069 [PACKET_qXfer_siginfo_write]);
11070 }
11071
11072 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11073 {
11074 if (readbuf)
11075 return remote_read_qxfer ("statictrace", annex,
11076 readbuf, offset, len, xfered_len,
11077 &remote_protocol_packets
11078 [PACKET_qXfer_statictrace_read]);
11079 else
11080 return TARGET_XFER_E_IO;
11081 }
11082
11083 /* Only handle flash writes. */
11084 if (writebuf != NULL)
11085 {
11086 switch (object)
11087 {
11088 case TARGET_OBJECT_FLASH:
11089 return remote_flash_write (offset, len, xfered_len,
11090 writebuf);
11091
11092 default:
11093 return TARGET_XFER_E_IO;
11094 }
11095 }
11096
11097 /* Map pre-existing objects onto letters. DO NOT do this for new
11098 objects!!! Instead specify new query packets. */
11099 switch (object)
11100 {
11101 case TARGET_OBJECT_AVR:
11102 query_type = 'R';
11103 break;
11104
11105 case TARGET_OBJECT_AUXV:
11106 gdb_assert (annex == NULL);
11107 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11108 xfered_len,
11109 &remote_protocol_packets[PACKET_qXfer_auxv]);
11110
11111 case TARGET_OBJECT_AVAILABLE_FEATURES:
11112 return remote_read_qxfer
11113 ("features", annex, readbuf, offset, len, xfered_len,
11114 &remote_protocol_packets[PACKET_qXfer_features]);
11115
11116 case TARGET_OBJECT_LIBRARIES:
11117 return remote_read_qxfer
11118 ("libraries", annex, readbuf, offset, len, xfered_len,
11119 &remote_protocol_packets[PACKET_qXfer_libraries]);
11120
11121 case TARGET_OBJECT_LIBRARIES_SVR4:
11122 return remote_read_qxfer
11123 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11124 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11125
11126 case TARGET_OBJECT_MEMORY_MAP:
11127 gdb_assert (annex == NULL);
11128 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11129 xfered_len,
11130 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11131
11132 case TARGET_OBJECT_OSDATA:
11133 /* Should only get here if we're connected. */
11134 gdb_assert (rs->remote_desc);
11135 return remote_read_qxfer
11136 ("osdata", annex, readbuf, offset, len, xfered_len,
11137 &remote_protocol_packets[PACKET_qXfer_osdata]);
11138
11139 case TARGET_OBJECT_THREADS:
11140 gdb_assert (annex == NULL);
11141 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11142 xfered_len,
11143 &remote_protocol_packets[PACKET_qXfer_threads]);
11144
11145 case TARGET_OBJECT_TRACEFRAME_INFO:
11146 gdb_assert (annex == NULL);
11147 return remote_read_qxfer
11148 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11149 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11150
11151 case TARGET_OBJECT_FDPIC:
11152 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11153 xfered_len,
11154 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11155
11156 case TARGET_OBJECT_OPENVMS_UIB:
11157 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11158 xfered_len,
11159 &remote_protocol_packets[PACKET_qXfer_uib]);
11160
11161 case TARGET_OBJECT_BTRACE:
11162 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11163 xfered_len,
11164 &remote_protocol_packets[PACKET_qXfer_btrace]);
11165
11166 case TARGET_OBJECT_BTRACE_CONF:
11167 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11168 len, xfered_len,
11169 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11170
11171 case TARGET_OBJECT_EXEC_FILE:
11172 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11173 len, xfered_len,
11174 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11175
11176 default:
11177 return TARGET_XFER_E_IO;
11178 }
11179
11180 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11181 large enough let the caller deal with it. */
11182 if (len < get_remote_packet_size ())
11183 return TARGET_XFER_E_IO;
11184 len = get_remote_packet_size ();
11185
11186 /* Except for querying the minimum buffer size, target must be open. */
11187 if (!rs->remote_desc)
11188 error (_("remote query is only available after target open"));
11189
11190 gdb_assert (annex != NULL);
11191 gdb_assert (readbuf != NULL);
11192
11193 p2 = rs->buf;
11194 *p2++ = 'q';
11195 *p2++ = query_type;
11196
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. */
11202 i = 0;
11203 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11204 {
11205 /* Bad caller may have sent forbidden characters. */
11206 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11207 *p2++ = annex[i];
11208 i++;
11209 }
11210 *p2 = '\0';
11211 gdb_assert (annex[i] == '\0');
11212
11213 i = putpkt (rs->buf);
11214 if (i < 0)
11215 return TARGET_XFER_E_IO;
11216
11217 getpkt (&rs->buf, &rs->buf_size, 0);
11218 strcpy ((char *) readbuf, rs->buf);
11219
11220 *xfered_len = strlen ((char *) readbuf);
11221 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11222 }
11223
11224 /* Implementation of to_get_memory_xfer_limit. */
11225
11226 ULONGEST
11227 remote_target::get_memory_xfer_limit ()
11228 {
11229 return get_memory_write_packet_size ();
11230 }
11231
11232 int
11233 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11234 const gdb_byte *pattern, ULONGEST pattern_len,
11235 CORE_ADDR *found_addrp)
11236 {
11237 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
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];
11242 /* Number of packet bytes used to encode the pattern;
11243 this could be more than PATTERN_LEN due to escape characters. */
11244 int escaped_pattern_len;
11245 /* Amount of pattern that was encodable in the packet. */
11246 int used_pattern_len;
11247 int i;
11248 int found;
11249 ULONGEST found_addr;
11250
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. */
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
11266 if (packet_config_support (packet) == PACKET_DISABLE)
11267 {
11268 /* Target doesn't provided special support, fall back and use the
11269 standard support (copy memory and do the search here). */
11270 return simple_search_memory (this, start_addr, search_space_len,
11271 pattern, pattern_len, found_addrp);
11272 }
11273
11274 /* Make sure the remote is pointing at the right process. */
11275 set_general_process ();
11276
11277 /* Insert header. */
11278 i = snprintf (rs->buf, max_size,
11279 "qSearch:memory:%s;%s;",
11280 phex_nz (start_addr, addr_size),
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 =
11286 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
11287 &used_pattern_len, max_size);
11288
11289 /* Bail if the pattern is too large. */
11290 if (used_pattern_len != pattern_len)
11291 error (_("Pattern is too large to transmit to remote target."));
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. */
11299 if (packet_config_support (packet) == PACKET_DISABLE)
11300 {
11301 return simple_search_memory (this, start_addr, search_space_len,
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] != ',')
11313 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11314 unpack_varlen_hex (rs->buf + 2, &found_addr);
11315 *found_addrp = found_addr;
11316 }
11317 else
11318 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11319
11320 return found;
11321 }
11322
11323 void
11324 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11325 {
11326 struct remote_state *rs = get_remote_state ();
11327 char *p = rs->buf;
11328
11329 if (!rs->remote_desc)
11330 error (_("remote rcmd is only available after target open"));
11331
11332 /* Send a NULL command across as an empty command. */
11333 if (command == NULL)
11334 command = "";
11335
11336 /* The query prefix. */
11337 strcpy (rs->buf, "qRcmd,");
11338 p = strchr (rs->buf, '\0');
11339
11340 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11341 > get_remote_packet_size ())
11342 error (_("\"monitor\" command ``%s'' is too long."), command);
11343
11344 /* Encode the actual command. */
11345 bin2hex ((const gdb_byte *) command, p, strlen (command));
11346
11347 if (putpkt (rs->buf) < 0)
11348 error (_("Communication problem with target."));
11349
11350 /* get/display the response */
11351 while (1)
11352 {
11353 char *buf;
11354
11355 /* XXX - see also remote_get_noisy_reply(). */
11356 QUIT; /* Allow user to bail out with ^C. */
11357 rs->buf[0] = '\0';
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 }
11367 buf = rs->buf;
11368 if (buf[0] == '\0')
11369 error (_("Target does not support this command."));
11370 if (buf[0] == 'O' && buf[1] != 'K')
11371 {
11372 remote_console_output (buf + 1); /* 'O' message from stub. */
11373 continue;
11374 }
11375 if (strcmp (buf, "OK") == 0)
11376 break;
11377 if (strlen (buf) == 3 && buf[0] == 'E'
11378 && isdigit (buf[1]) && isdigit (buf[2]))
11379 {
11380 error (_("Protocol error with Rcmd"));
11381 }
11382 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11383 {
11384 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11385
11386 fputc_unfiltered (c, outbuf);
11387 }
11388 break;
11389 }
11390 }
11391
11392 std::vector<mem_region>
11393 remote_target::memory_map ()
11394 {
11395 std::vector<mem_region> result;
11396 gdb::optional<gdb::char_vector> text
11397 = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
11398
11399 if (text)
11400 result = parse_memory_map (text->data ());
11401
11402 return result;
11403 }
11404
11405 static void
11406 packet_command (const char *args, int from_tty)
11407 {
11408 remote_target *remote = get_current_remote_target ();
11409
11410 if (remote == nullptr)
11411 error (_("command can only be used with remote target"));
11412
11413 remote->packet_command (args, from_tty);
11414 }
11415
11416 void
11417 remote_target::packet_command (const char *args, int from_tty)
11418 {
11419 if (!args)
11420 error (_("remote-packet command requires packet text as argument"));
11421
11422 puts_filtered ("sending: ");
11423 print_packet (args);
11424 puts_filtered ("\n");
11425 putpkt (args);
11426
11427 remote_state *rs = get_remote_state ();
11428
11429 getpkt (&rs->buf, &rs->buf_size, 0);
11430 puts_filtered ("received: ");
11431 print_packet (rs->buf);
11432 puts_filtered ("\n");
11433 }
11434
11435 #if 0
11436 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11437
11438 static void display_thread_info (struct gdb_ext_thread_info *info);
11439
11440 static void threadset_test_cmd (char *cmd, int tty);
11441
11442 static void threadalive_test (char *cmd, int tty);
11443
11444 static void threadlist_test_cmd (char *cmd, int tty);
11445
11446 int get_and_display_threadinfo (threadref *ref);
11447
11448 static void threadinfo_test_cmd (char *cmd, int tty);
11449
11450 static int thread_display_step (threadref *ref, void *context);
11451
11452 static void threadlist_update_test_cmd (char *cmd, int tty);
11453
11454 static void init_remote_threadtests (void);
11455
11456 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11457
11458 static void
11459 threadset_test_cmd (const char *cmd, int tty)
11460 {
11461 int sample_thread = SAMPLE_THREAD;
11462
11463 printf_filtered (_("Remote threadset test\n"));
11464 set_general_thread (sample_thread);
11465 }
11466
11467
11468 static void
11469 threadalive_test (const char *cmd, int tty)
11470 {
11471 int sample_thread = SAMPLE_THREAD;
11472 int pid = ptid_get_pid (inferior_ptid);
11473 ptid_t ptid = ptid_build (pid, sample_thread, 0);
11474
11475 if (remote_thread_alive (ptid))
11476 printf_filtered ("PASS: Thread alive test\n");
11477 else
11478 printf_filtered ("FAIL: Thread alive test\n");
11479 }
11480
11481 void output_threadid (char *title, threadref *ref);
11482
11483 void
11484 output_threadid (char *title, threadref *ref)
11485 {
11486 char hexid[20];
11487
11488 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
11489 hexid[16] = 0;
11490 printf_filtered ("%s %s\n", title, (&hexid[0]));
11491 }
11492
11493 static void
11494 threadlist_test_cmd (const char *cmd, int tty)
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
11515 void
11516 display_thread_info (struct gdb_ext_thread_info *info)
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
11524 int
11525 get_and_display_threadinfo (threadref *ref)
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
11538 static void
11539 threadinfo_test_cmd (const char *cmd, int tty)
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
11551 static int
11552 thread_display_step (threadref *ref, void *context)
11553 {
11554 /* output_threadid(" threadstep ",ref); *//* simple test */
11555 return get_and_display_threadinfo (ref);
11556 }
11557
11558 static void
11559 threadlist_update_test_cmd (const char *cmd, int tty)
11560 {
11561 printf_filtered ("Remote Threadlist update test\n");
11562 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11563 }
11564
11565 static void
11566 init_remote_threadtests (void)
11567 {
11568 add_com ("tlist", class_obscure, threadlist_test_cmd,
11569 _("Fetch and print the remote list of "
11570 "thread identifiers, one pkt only"));
11571 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11572 _("Fetch and display info about one thread"));
11573 add_com ("tset", class_obscure, threadset_test_cmd,
11574 _("Test setting to a different thread"));
11575 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11576 _("Iterate through updating all remote thread info"));
11577 add_com ("talive", class_obscure, threadalive_test,
11578 _(" Remote thread alive test "));
11579 }
11580
11581 #endif /* 0 */
11582
11583 /* Convert a thread ID to a string. Returns the string in a static
11584 buffer. */
11585
11586 const char *
11587 remote_target::pid_to_str (ptid_t ptid)
11588 {
11589 static char buf[64];
11590 struct remote_state *rs = get_remote_state ();
11591
11592 if (ptid_equal (ptid, null_ptid))
11593 return normal_pid_to_str (ptid);
11594 else if (ptid_is_pid (ptid))
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);
11614 }
11615 else
11616 {
11617 if (ptid_equal (magic_null_ptid, ptid))
11618 xsnprintf (buf, sizeof buf, "Thread <main>");
11619 else if (remote_multi_process_p (rs))
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));
11625 else
11626 xsnprintf (buf, sizeof buf, "Thread %ld",
11627 ptid_get_lwp (ptid));
11628 return buf;
11629 }
11630 }
11631
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
11635 CORE_ADDR
11636 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11637 CORE_ADDR offset)
11638 {
11639 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11640 {
11641 struct remote_state *rs = get_remote_state ();
11642 char *p = rs->buf;
11643 char *endp = rs->buf + get_remote_packet_size ();
11644 enum packet_result result;
11645
11646 strcpy (p, "qGetTLSAddr:");
11647 p += strlen (p);
11648 p = write_ptid (p, endp, ptid);
11649 *p++ = ',';
11650 p += hexnumstr (p, offset);
11651 *p++ = ',';
11652 p += hexnumstr (p, lm);
11653 *p++ = '\0';
11654
11655 putpkt (rs->buf);
11656 getpkt (&rs->buf, &rs->buf_size, 0);
11657 result = packet_ok (rs->buf,
11658 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11659 if (result == PACKET_OK)
11660 {
11661 ULONGEST result;
11662
11663 unpack_varlen_hex (rs->buf, &result);
11664 return result;
11665 }
11666 else if (result == PACKET_UNKNOWN)
11667 throw_error (TLS_GENERIC_ERROR,
11668 _("Remote target doesn't support qGetTLSAddr packet"));
11669 else
11670 throw_error (TLS_GENERIC_ERROR,
11671 _("Remote target failed to process qGetTLSAddr request"));
11672 }
11673 else
11674 throw_error (TLS_GENERIC_ERROR,
11675 _("TLS not supported or disabled on this target"));
11676 /* Not reached. */
11677 return 0;
11678 }
11679
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
11683 bool
11684 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11685 {
11686 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
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;
11709 return true;
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. */
11719 return false;
11720 }
11721
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
11728 struct remote_g_packet_guess
11729 {
11730 int bytes;
11731 const struct target_desc *tdesc;
11732 };
11733 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11734 DEF_VEC_O(remote_g_packet_guess_s);
11735
11736 struct remote_g_packet_data
11737 {
11738 VEC(remote_g_packet_guess_s) *guesses;
11739 };
11740
11741 static struct gdbarch_data *remote_g_packet_data_handle;
11742
11743 static void *
11744 remote_g_packet_data_init (struct obstack *obstack)
11745 {
11746 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11747 }
11748
11749 void
11750 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11751 const struct target_desc *tdesc)
11752 {
11753 struct remote_g_packet_data *data
11754 = ((struct remote_g_packet_data *)
11755 gdbarch_data (gdbarch, remote_g_packet_data_handle));
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__,
11766 _("Duplicate g packet description added for size %d"),
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
11774 /* Return 1 if remote_read_description would do anything on this target
11775 and architecture, 0 otherwise. */
11776
11777 static int
11778 remote_read_description_p (struct target_ops *target)
11779 {
11780 struct remote_g_packet_data *data
11781 = ((struct remote_g_packet_data *)
11782 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11783
11784 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11785 return 1;
11786
11787 return 0;
11788 }
11789
11790 const struct target_desc *
11791 remote_target::read_description ()
11792 {
11793 struct remote_g_packet_data *data
11794 = ((struct remote_g_packet_data *)
11795 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11796
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))
11800 return beneath->read_description ();
11801
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
11819 return beneath->read_description ();
11820 }
11821
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
11829 static void
11830 remote_buffer_add_string (char **buffer, int *left, const char *string)
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
11851 static void
11852 remote_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
11872 static void
11873 remote_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
11899 static int
11900 remote_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
11955 int
11956 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11957 int *remote_errno, char **attachment,
11958 int *attachment_len)
11959 {
11960 struct remote_state *rs = get_remote_state ();
11961 int ret, bytes_read;
11962 char *attachment_tmp;
11963
11964 if (packet_support (which_packet) == PACKET_DISABLE)
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
12019 /* See declaration.h. */
12020
12021 void
12022 readahead_cache::invalidate ()
12023 {
12024 this->fd = -1;
12025 }
12026
12027 /* See declaration.h. */
12028
12029 void
12030 readahead_cache::invalidate_fd (int fd)
12031 {
12032 if (this->fd == fd)
12033 this->fd = -1;
12034 }
12035
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
12040 int
12041 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12042 int *remote_errno)
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
12074 /* Implementation of to_fileio_open. */
12075
12076 int
12077 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12078 int flags, int mode, int warn_if_slow,
12079 int *remote_errno)
12080 {
12081 struct remote_state *rs = get_remote_state ();
12082 char *p = rs->buf;
12083 int left = get_remote_packet_size () - 1;
12084
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
12101 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12102 return -1;
12103
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
12119 int
12120 remote_target::fileio_open (struct inferior *inf, const char *filename,
12121 int flags, int mode, int warn_if_slow,
12122 int *remote_errno)
12123 {
12124 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12125 remote_errno);
12126 }
12127
12128 /* Implementation of to_fileio_pwrite. */
12129
12130 int
12131 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12132 ULONGEST offset, int *remote_errno)
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
12139 rs->readahead_cache.invalidate_fd (fd);
12140
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
12149 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
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
12156 int
12157 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12158 ULONGEST offset, int *remote_errno)
12159 {
12160 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12161 }
12162
12163 /* Helper for the implementation of to_fileio_pread. Read the file
12164 from the remote side with vFile:pread. */
12165
12166 int
12167 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12168 ULONGEST offset, int *remote_errno)
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
12194 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
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
12202 /* See declaration.h. */
12203
12204 int
12205 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12206 ULONGEST offset)
12207 {
12208 if (this->fd == fd
12209 && this->offset <= offset
12210 && offset < this->offset + this->bufsize)
12211 {
12212 ULONGEST max = this->offset + this->bufsize;
12213
12214 if (offset + len > max)
12215 len = max - offset;
12216
12217 memcpy (read_buf, this->buf + offset - this->offset, len);
12218 return len;
12219 }
12220
12221 return 0;
12222 }
12223
12224 /* Implementation of to_fileio_pread. */
12225
12226 int
12227 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12228 ULONGEST offset, int *remote_errno)
12229 {
12230 int ret;
12231 struct remote_state *rs = get_remote_state ();
12232 readahead_cache *cache = &rs->readahead_cache;
12233
12234 ret = cache->pread (fd, read_buf, len, offset);
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 ();
12253 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12254
12255 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12256 cache->offset, remote_errno);
12257 if (ret <= 0)
12258 {
12259 cache->invalidate_fd (fd);
12260 return ret;
12261 }
12262
12263 cache->bufsize = ret;
12264 return cache->pread (fd, read_buf, len, offset);
12265 }
12266
12267 int
12268 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12269 ULONGEST offset, int *remote_errno)
12270 {
12271 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12272 }
12273
12274 /* Implementation of to_fileio_close. */
12275
12276 int
12277 remote_target::remote_hostio_close (int fd, int *remote_errno)
12278 {
12279 struct remote_state *rs = get_remote_state ();
12280 char *p = rs->buf;
12281 int left = get_remote_packet_size () - 1;
12282
12283 rs->readahead_cache.invalidate_fd (fd);
12284
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
12293 int
12294 remote_target::fileio_close (int fd, int *remote_errno)
12295 {
12296 return remote_hostio_close (fd, remote_errno);
12297 }
12298
12299 /* Implementation of to_fileio_unlink. */
12300
12301 int
12302 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12303 int *remote_errno)
12304 {
12305 struct remote_state *rs = get_remote_state ();
12306 char *p = rs->buf;
12307 int left = get_remote_packet_size () - 1;
12308
12309 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12310 return -1;
12311
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
12321 int
12322 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12323 int *remote_errno)
12324 {
12325 return remote_hostio_unlink (inf, filename, remote_errno);
12326 }
12327
12328 /* Implementation of to_fileio_readlink. */
12329
12330 gdb::optional<std::string>
12331 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12332 int *remote_errno)
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;
12340
12341 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12342 return {};
12343
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)
12354 return {};
12355
12356 std::string ret (len, '\0');
12357
12358 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12359 (gdb_byte *) &ret[0], len);
12360 if (read_len != len)
12361 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12362
12363 return ret;
12364 }
12365
12366 /* Implementation of to_fileio_fstat. */
12367
12368 int
12369 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
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
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)
12387 {
12388 if (*remote_errno != FILEIO_ENOSYS)
12389 return ret;
12390
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
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
12424 /* Implementation of to_filesystem_is_local. */
12425
12426 bool
12427 remote_target::filesystem_is_local ()
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. */
12435 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
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. */
12446 fd = remote_hostio_open (NULL, "just probing",
12447 FILEIO_O_RDONLY, 0700, 0,
12448 &remote_errno);
12449
12450 if (fd >= 0)
12451 remote_hostio_close (fd, &remote_errno);
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
12468 return true;
12469 }
12470 }
12471
12472 return false;
12473 }
12474
12475 static int
12476 remote_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
12526 static char *
12527 remote_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
12537 /* A RAII wrapper around a remote file descriptor. */
12538
12539 class scoped_remote_fd
12540 {
12541 public:
12542 scoped_remote_fd (remote_target *remote, int fd)
12543 : m_remote (remote), m_fd (fd)
12544 {
12545 }
12546
12547 ~scoped_remote_fd ()
12548 {
12549 if (m_fd != -1)
12550 {
12551 try
12552 {
12553 int remote_errno;
12554 m_remote->remote_hostio_close (m_fd, &remote_errno);
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
12581 private:
12582 /* The remote target. */
12583 remote_target *m_remote;
12584
12585 /* The owned remote I/O file descriptor. */
12586 int m_fd;
12587 };
12588
12589 void
12590 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
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
12600 void
12601 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12602 int from_tty)
12603 {
12604 struct cleanup *back_to;
12605 int retcode, remote_errno, bytes, io_size;
12606 gdb_byte *buffer;
12607 int bytes_in_buffer;
12608 int saw_eof;
12609 ULONGEST offset;
12610
12611 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12612 if (file == NULL)
12613 perror_with_name (local_file);
12614
12615 scoped_remote_fd fd
12616 (this, remote_hostio_open (NULL,
12617 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12618 | FILEIO_O_TRUNC),
12619 0700, 0, &remote_errno));
12620 if (fd.get () == -1)
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 ();
12626 buffer = (gdb_byte *) xmalloc (io_size);
12627 back_to = make_cleanup (xfree, buffer);
12628
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 {
12636 bytes = fread (buffer + bytes_in_buffer, 1,
12637 io_size - bytes_in_buffer,
12638 file.get ());
12639 if (bytes == 0)
12640 {
12641 if (ferror (file.get ()))
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
12659 retcode = remote_hostio_pwrite (fd.get (), buffer, bytes,
12660 offset, &remote_errno);
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
12677 if (remote_hostio_close (fd.release (), &remote_errno))
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
12685 void
12686 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
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
12696 void
12697 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12698 int from_tty)
12699 {
12700 struct cleanup *back_to;
12701 int remote_errno, bytes, io_size;
12702 gdb_byte *buffer;
12703 ULONGEST offset;
12704
12705 scoped_remote_fd fd
12706 (this, remote_hostio_open (NULL,
12707 remote_file, FILEIO_O_RDONLY, 0, 0,
12708 &remote_errno));
12709 if (fd.get () == -1)
12710 remote_hostio_error (remote_errno);
12711
12712 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12713 if (file == NULL)
12714 perror_with_name (local_file);
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 ();
12719 buffer = (gdb_byte *) xmalloc (io_size);
12720 back_to = make_cleanup (xfree, buffer);
12721
12722 offset = 0;
12723 while (1)
12724 {
12725 bytes = remote_hostio_pread (fd.get (), buffer, io_size, offset,
12726 &remote_errno);
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
12735 bytes = fwrite (buffer, 1, bytes, file.get ());
12736 if (bytes == 0)
12737 perror_with_name (local_file);
12738 }
12739
12740 if (remote_hostio_close (fd.release (), &remote_errno))
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
12748 void
12749 remote_file_delete (const char *remote_file, int from_tty)
12750 {
12751 remote_target *remote = get_current_remote_target ();
12752
12753 if (remote == nullptr)
12754 error (_("command can only be used with remote target"));
12755
12756 remote->remote_file_delete (remote_file, from_tty);
12757 }
12758
12759 void
12760 remote_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);
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
12772 static void
12773 remote_put_command (const char *args, int from_tty)
12774 {
12775 if (args == NULL)
12776 error_no_arg (_("file to put"));
12777
12778 gdb_argv argv (args);
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);
12783 }
12784
12785 static void
12786 remote_get_command (const char *args, int from_tty)
12787 {
12788 if (args == NULL)
12789 error_no_arg (_("file to get"));
12790
12791 gdb_argv argv (args);
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);
12796 }
12797
12798 static void
12799 remote_delete_command (const char *args, int from_tty)
12800 {
12801 if (args == NULL)
12802 error_no_arg (_("file to delete"));
12803
12804 gdb_argv argv (args);
12805 if (argv[0] == NULL || argv[1] != NULL)
12806 error (_("Invalid parameters to remote delete"));
12807
12808 remote_file_delete (argv[0], from_tty);
12809 }
12810
12811 static void
12812 remote_command (const char *args, int from_tty)
12813 {
12814 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12815 }
12816
12817 bool
12818 remote_target::can_execute_reverse ()
12819 {
12820 if (packet_support (PACKET_bs) == PACKET_ENABLE
12821 || packet_support (PACKET_bc) == PACKET_ENABLE)
12822 return true;
12823 else
12824 return false;
12825 }
12826
12827 bool
12828 remote_target::supports_non_stop ()
12829 {
12830 return true;
12831 }
12832
12833 bool
12834 remote_target::supports_disable_randomization ()
12835 {
12836 /* Only supported in extended mode. */
12837 return false;
12838 }
12839
12840 bool
12841 remote_target::supports_multi_process ()
12842 {
12843 struct remote_state *rs = get_remote_state ();
12844
12845 return remote_multi_process_p (rs);
12846 }
12847
12848 static int
12849 remote_supports_cond_tracepoints ()
12850 {
12851 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12852 }
12853
12854 bool
12855 remote_target::supports_evaluation_of_breakpoint_conditions ()
12856 {
12857 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12858 }
12859
12860 static int
12861 remote_supports_fast_tracepoints ()
12862 {
12863 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12864 }
12865
12866 static int
12867 remote_supports_static_tracepoints ()
12868 {
12869 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12870 }
12871
12872 static int
12873 remote_supports_install_in_trace ()
12874 {
12875 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12876 }
12877
12878 bool
12879 remote_target::supports_enable_disable_tracepoint ()
12880 {
12881 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12882 == PACKET_ENABLE);
12883 }
12884
12885 bool
12886 remote_target::supports_string_tracing ()
12887 {
12888 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12889 }
12890
12891 bool
12892 remote_target::can_run_breakpoint_commands ()
12893 {
12894 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12895 }
12896
12897 void
12898 remote_target::trace_init ()
12899 {
12900 struct remote_state *rs = get_remote_state ();
12901
12902 putpkt ("QTinit");
12903 remote_get_noisy_reply ();
12904 if (strcmp (rs->buf, "OK") != 0)
12905 error (_("Target does not support this command."));
12906 }
12907
12908 /* Recursive routine to walk through command list including loops, and
12909 download packets for each command. */
12910
12911 void
12912 remote_target::remote_download_command_source (int num, ULONGEST addr,
12913 struct command_line *cmds)
12914 {
12915 struct remote_state *rs = get_remote_state ();
12916 struct command_line *cmd;
12917
12918 for (cmd = cmds; cmd; cmd = cmd->next)
12919 {
12920 QUIT; /* Allow user to bail out with ^C. */
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);
12926 remote_get_noisy_reply ();
12927 if (strcmp (rs->buf, "OK"))
12928 warning (_("Target does not support source download."));
12929
12930 if (cmd->control_type == while_control
12931 || cmd->control_type == while_stepping_control)
12932 {
12933 remote_download_command_source (num, addr, cmd->body_list_0.get ());
12934
12935 QUIT; /* Allow user to bail out with ^C. */
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);
12941 remote_get_noisy_reply ();
12942 if (strcmp (rs->buf, "OK"))
12943 warning (_("Target does not support source download."));
12944 }
12945 }
12946 }
12947
12948 void
12949 remote_target::download_tracepoint (struct bp_location *loc)
12950 {
12951 #define BUF_SIZE 2048
12952
12953 CORE_ADDR tpaddr;
12954 char addrbuf[40];
12955 char buf[BUF_SIZE];
12956 std::vector<std::string> tdp_actions;
12957 std::vector<std::string> stepping_actions;
12958 char *pkt;
12959 struct breakpoint *b = loc->owner;
12960 struct tracepoint *t = (struct tracepoint *) b;
12961 struct remote_state *rs = get_remote_state ();
12962
12963 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12964
12965 tpaddr = loc->address;
12966 sprintf_vma (addrbuf, tpaddr);
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);
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 ())
12979 {
12980 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12981 NULL))
12982 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12983 gdb_insn_length (loc->gdbarch, tpaddr));
12984 else
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"));
12990 }
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 ())
13003 {
13004 struct static_tracepoint_marker marker;
13005
13006 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13007 strcat (buf, ":S");
13008 else
13009 error (_("Static tracepoint not valid during download"));
13010 }
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 ())
13024 {
13025 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
13026 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
13027 aexpr->len);
13028 pkt = buf + strlen (buf);
13029 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13030 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13031 *pkt = '\0';
13032 }
13033 else
13034 warning (_("Target does not support conditional tracepoints, "
13035 "ignoring tp %d cond"), b->number);
13036 }
13037
13038 if (b->commands || *default_collect)
13039 strcat (buf, "-");
13040 putpkt (buf);
13041 remote_get_noisy_reply ();
13042 if (strcmp (rs->buf, "OK"))
13043 error (_("Target does not support tracepoints."));
13044
13045 /* do_single_steps (t); */
13046 for (auto action_it = tdp_actions.begin ();
13047 action_it != tdp_actions.end (); action_it++)
13048 {
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."));
13062 }
13063
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
13083 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13084 {
13085 if (b->location != NULL)
13086 {
13087 strcpy (buf, "QTDPsrc:");
13088 encode_source_string (b->number, loc->address, "at",
13089 event_location_to_string (b->location.get ()),
13090 buf + strlen (buf), 2048 - strlen (buf));
13091 putpkt (buf);
13092 remote_get_noisy_reply ();
13093 if (strcmp (rs->buf, "OK"))
13094 warning (_("Target does not support source download."));
13095 }
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);
13103 remote_get_noisy_reply ();
13104 if (strcmp (rs->buf, "OK"))
13105 warning (_("Target does not support source download."));
13106 }
13107 remote_download_command_source (b->number, loc->address,
13108 breakpoint_commands (b));
13109 }
13110 }
13111
13112 bool
13113 remote_target::can_download_tracepoint ()
13114 {
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)
13123 return false;
13124
13125 ts = current_trace_status ();
13126 status = get_trace_status (ts);
13127
13128 if (status == -1 || !ts->running_known || !ts->running)
13129 return false;
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 ())
13134 return false;
13135
13136 return true;
13137 }
13138
13139
13140 void
13141 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13142 {
13143 struct remote_state *rs = get_remote_state ();
13144 char *p;
13145
13146 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
13147 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13148 tsv.builtin);
13149 p = rs->buf + strlen (rs->buf);
13150 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
13151 error (_("Trace state variable name too long for tsv definition packet"));
13152 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13153 *p++ = '\0';
13154 putpkt (rs->buf);
13155 remote_get_noisy_reply ();
13156 if (*rs->buf == '\0')
13157 error (_("Target does not support this command."));
13158 if (strcmp (rs->buf, "OK") != 0)
13159 error (_("Error on target while downloading trace state variable."));
13160 }
13161
13162 void
13163 remote_target::enable_tracepoint (struct bp_location *location)
13164 {
13165 struct remote_state *rs = get_remote_state ();
13166 char addr_buf[40];
13167
13168 sprintf_vma (addr_buf, location->address);
13169 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13170 location->owner->number, addr_buf);
13171 putpkt (rs->buf);
13172 remote_get_noisy_reply ();
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
13179 void
13180 remote_target::disable_tracepoint (struct bp_location *location)
13181 {
13182 struct remote_state *rs = get_remote_state ();
13183 char addr_buf[40];
13184
13185 sprintf_vma (addr_buf, location->address);
13186 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13187 location->owner->number, addr_buf);
13188 putpkt (rs->buf);
13189 remote_get_noisy_reply ();
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
13196 void
13197 remote_target::trace_set_readonly_regions ()
13198 {
13199 asection *s;
13200 bfd *abfd = NULL;
13201 bfd_size_type size;
13202 bfd_vma vma;
13203 int anysecs = 0;
13204 int offset = 0;
13205
13206 if (!exec_bfd)
13207 return; /* No information to give. */
13208
13209 struct remote_state *rs = get_remote_state ();
13210
13211 strcpy (rs->buf, "QTro");
13212 offset = strlen (rs->buf);
13213 for (s = exec_bfd->sections; s; s = s->next)
13214 {
13215 char tmp1[40], tmp2[40];
13216 int sec_length;
13217
13218 if ((s->flags & SEC_LOAD) == 0 ||
13219 /* (s->flags & SEC_CODE) == 0 || */
13220 (s->flags & SEC_READONLY) == 0)
13221 continue;
13222
13223 anysecs = 1;
13224 vma = bfd_get_section_vma (abfd, s);
13225 size = bfd_get_section_size (s);
13226 sprintf_vma (tmp1, vma);
13227 sprintf_vma (tmp2, vma + size);
13228 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13229 if (offset + sec_length + 1 > rs->buf_size)
13230 {
13231 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13232 warning (_("\
13233 Too many sections for read-only sections definition packet."));
13234 break;
13235 }
13236 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
13237 tmp1, tmp2);
13238 offset += sec_length;
13239 }
13240 if (anysecs)
13241 {
13242 putpkt (rs->buf);
13243 getpkt (&rs->buf, &rs->buf_size, 0);
13244 }
13245 }
13246
13247 void
13248 remote_target::trace_start ()
13249 {
13250 struct remote_state *rs = get_remote_state ();
13251
13252 putpkt ("QTStart");
13253 remote_get_noisy_reply ();
13254 if (*rs->buf == '\0')
13255 error (_("Target does not support this command."));
13256 if (strcmp (rs->buf, "OK") != 0)
13257 error (_("Bogus reply from target: %s"), rs->buf);
13258 }
13259
13260 int
13261 remote_target::get_trace_status (struct trace_status *ts)
13262 {
13263 /* Initialize it just to avoid a GCC false warning. */
13264 char *p = NULL;
13265 /* FIXME we need to get register block size some other way. */
13266 extern int trace_regblock_size;
13267 enum packet_result result;
13268 struct remote_state *rs = get_remote_state ();
13269
13270 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13271 return -1;
13272
13273 trace_regblock_size
13274 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13275
13276 putpkt ("qTStatus");
13277
13278 TRY
13279 {
13280 p = remote_get_noisy_reply ();
13281 }
13282 CATCH (ex, RETURN_MASK_ERROR)
13283 {
13284 if (ex.error != TARGET_CLOSE_ERROR)
13285 {
13286 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13287 return -1;
13288 }
13289 throw_exception (ex);
13290 }
13291 END_CATCH
13292
13293 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13294
13295 /* If the remote target doesn't do tracing, flag it. */
13296 if (result == PACKET_UNKNOWN)
13297 return -1;
13298
13299 /* We're working with a live target. */
13300 ts->filename = NULL;
13301
13302 if (*p++ != 'T')
13303 error (_("Bogus trace status reply from target: %s"), rs->buf);
13304
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. */
13307 parse_trace_status (p, ts);
13308
13309 return ts->running;
13310 }
13311
13312 void
13313 remote_target::get_tracepoint_status (struct breakpoint *bp,
13314 struct uploaded_tp *utp)
13315 {
13316 struct remote_state *rs = get_remote_state ();
13317 char *reply;
13318 struct bp_location *loc;
13319 struct tracepoint *tp = (struct tracepoint *) bp;
13320 size_t size = get_remote_packet_size ();
13321
13322 if (tp)
13323 {
13324 tp->hit_count = 0;
13325 tp->traceframe_usage = 0;
13326 for (loc = tp->loc; loc; loc = loc->next)
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;
13332 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13333 phex_nz (loc->address, 0));
13334 putpkt (rs->buf);
13335 reply = remote_get_noisy_reply ();
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;
13347 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13348 phex_nz (utp->addr, 0));
13349 putpkt (rs->buf);
13350 reply = remote_get_noisy_reply ();
13351 if (reply && *reply)
13352 {
13353 if (*reply == 'V')
13354 parse_tracepoint_status (reply + 1, bp, utp);
13355 }
13356 }
13357 }
13358
13359 void
13360 remote_target::trace_stop ()
13361 {
13362 struct remote_state *rs = get_remote_state ();
13363
13364 putpkt ("QTStop");
13365 remote_get_noisy_reply ();
13366 if (*rs->buf == '\0')
13367 error (_("Target does not support this command."));
13368 if (strcmp (rs->buf, "OK") != 0)
13369 error (_("Bogus reply from target: %s"), rs->buf);
13370 }
13371
13372 int
13373 remote_target::trace_find (enum trace_find_type type, int num,
13374 CORE_ADDR addr1, CORE_ADDR addr2,
13375 int *tpp)
13376 {
13377 struct remote_state *rs = get_remote_state ();
13378 char *endbuf = rs->buf + get_remote_packet_size ();
13379 char *p, *reply;
13380 int target_frameno = -1, target_tracept = -1;
13381
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
13388 p = rs->buf;
13389 strcpy (p, "QTFrame:");
13390 p = strchr (p, '\0');
13391 switch (type)
13392 {
13393 case tfind_number:
13394 xsnprintf (p, endbuf - p, "%x", num);
13395 break;
13396 case tfind_pc:
13397 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13398 break;
13399 case tfind_tp:
13400 xsnprintf (p, endbuf - p, "tdp:%x", num);
13401 break;
13402 case tfind_range:
13403 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13404 phex_nz (addr2, 0));
13405 break;
13406 case tfind_outside:
13407 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13408 phex_nz (addr2, 0));
13409 break;
13410 default:
13411 error (_("Unknown trace find type %d"), type);
13412 }
13413
13414 putpkt (rs->buf);
13415 reply = remote_get_noisy_reply ();
13416 if (*reply == '\0')
13417 error (_("Target does not support this command."));
13418
13419 while (reply && *reply)
13420 switch (*reply)
13421 {
13422 case 'F':
13423 p = ++reply;
13424 target_frameno = (int) strtol (p, &reply, 16);
13425 if (reply == p)
13426 error (_("Unable to parse trace frame number"));
13427 /* Don't update our remote traceframe number cache on failure
13428 to select a remote traceframe. */
13429 if (target_frameno == -1)
13430 return -1;
13431 break;
13432 case 'T':
13433 p = ++reply;
13434 target_tracept = (int) strtol (p, &reply, 16);
13435 if (reply == p)
13436 error (_("Unable to parse tracepoint number"));
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;
13449
13450 rs->remote_traceframe_number = target_frameno;
13451 return target_frameno;
13452 }
13453
13454 bool
13455 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13456 {
13457 struct remote_state *rs = get_remote_state ();
13458 char *reply;
13459 ULONGEST uval;
13460
13461 set_remote_traceframe ();
13462
13463 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13464 putpkt (rs->buf);
13465 reply = remote_get_noisy_reply ();
13466 if (reply && *reply)
13467 {
13468 if (*reply == 'V')
13469 {
13470 unpack_varlen_hex (reply + 1, &uval);
13471 *val = (LONGEST) uval;
13472 return true;
13473 }
13474 }
13475 return false;
13476 }
13477
13478 int
13479 remote_target::save_trace_data (const char *filename)
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"));
13489 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13490 *p++ = '\0';
13491 putpkt (rs->buf);
13492 reply = remote_get_noisy_reply ();
13493 if (*reply == '\0')
13494 error (_("Target does not support this command."));
13495 if (strcmp (reply, "OK") != 0)
13496 error (_("Bogus reply from target: %s"), reply);
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
13505 LONGEST
13506 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
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);
13522 reply = remote_get_noisy_reply ();
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. */
13535 rslt = hex2bin (reply, buf, len);
13536 return rslt;
13537 }
13538
13539 /* Something went wrong, flag as an error. */
13540 return -1;
13541 }
13542
13543 void
13544 remote_target::set_disconnected_tracing (int val)
13545 {
13546 struct remote_state *rs = get_remote_state ();
13547
13548 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13549 {
13550 char *reply;
13551
13552 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13553 putpkt (rs->buf);
13554 reply = remote_get_noisy_reply ();
13555 if (*reply == '\0')
13556 error (_("Target does not support this command."));
13557 if (strcmp (reply, "OK") != 0)
13558 error (_("Bogus reply from target: %s"), reply);
13559 }
13560 else if (val)
13561 warning (_("Target does not support disconnected tracing."));
13562 }
13563
13564 int
13565 remote_target::core_of_thread (ptid_t ptid)
13566 {
13567 struct thread_info *info = find_thread_ptid (ptid);
13568
13569 if (info != NULL && info->priv != NULL)
13570 return get_remote_thread_info (info)->core;
13571
13572 return -1;
13573 }
13574
13575 void
13576 remote_target::set_circular_trace_buffer (int val)
13577 {
13578 struct remote_state *rs = get_remote_state ();
13579 char *reply;
13580
13581 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13582 putpkt (rs->buf);
13583 reply = remote_get_noisy_reply ();
13584 if (*reply == '\0')
13585 error (_("Target does not support this command."));
13586 if (strcmp (reply, "OK") != 0)
13587 error (_("Bogus reply from target: %s"), reply);
13588 }
13589
13590 traceframe_info_up
13591 remote_target::traceframe_info ()
13592 {
13593 gdb::optional<gdb::char_vector> text
13594 = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
13595 NULL);
13596 if (text)
13597 return parse_traceframe_info (text->data ());
13598
13599 return NULL;
13600 }
13601
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
13607 int
13608 remote_target::get_min_fast_tracepoint_insn_len ()
13609 {
13610 struct remote_state *rs = get_remote_state ();
13611 char *reply;
13612
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
13621 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13622 putpkt (rs->buf);
13623 reply = remote_get_noisy_reply ();
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
13636 void
13637 remote_target::set_trace_buffer_size (LONGEST val)
13638 {
13639 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
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);
13658 remote_get_noisy_reply ();
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
13667 bool
13668 remote_target::set_trace_notes (const char *user, const char *notes,
13669 const char *stop_notes)
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:");
13681 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13682 buf += 2 * nbytes;
13683 *buf++ = ';';
13684 }
13685 if (notes)
13686 {
13687 buf += xsnprintf (buf, endbuf - buf, "notes:");
13688 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13689 buf += 2 * nbytes;
13690 *buf++ = ';';
13691 }
13692 if (stop_notes)
13693 {
13694 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13695 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13696 buf += 2 * nbytes;
13697 *buf++ = ';';
13698 }
13699 /* Ensure the buffer is terminated. */
13700 *buf = '\0';
13701
13702 putpkt (rs->buf);
13703 reply = remote_get_noisy_reply ();
13704 if (*reply == '\0')
13705 return false;
13706
13707 if (strcmp (reply, "OK") != 0)
13708 error (_("Bogus reply from target: %s"), reply);
13709
13710 return true;
13711 }
13712
13713 bool
13714 remote_target::use_agent (bool use)
13715 {
13716 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13717 {
13718 struct remote_state *rs = get_remote_state ();
13719
13720 /* If the stub supports QAgent. */
13721 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13722 putpkt (rs->buf);
13723 getpkt (&rs->buf, &rs->buf_size, 0);
13724
13725 if (strcmp (rs->buf, "OK") == 0)
13726 {
13727 ::use_agent = use;
13728 return true;
13729 }
13730 }
13731
13732 return false;
13733 }
13734
13735 bool
13736 remote_target::can_use_agent ()
13737 {
13738 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13739 }
13740
13741 struct btrace_target_info
13742 {
13743 /* The ptid of the traced thread. */
13744 ptid_t ptid;
13745
13746 /* The obtained branch trace configuration. */
13747 struct btrace_config conf;
13748 };
13749
13750 /* Reset our idea of our target's btrace configuration. */
13751
13752 static void
13753 remote_btrace_reset (remote_state *rs)
13754 {
13755 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13756 }
13757
13758 /* Synchronize the configuration with the target. */
13759
13760 void
13761 remote_target::btrace_sync_conf (const btrace_config *conf)
13762 {
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 }
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 }
13814 }
13815
13816 /* Read the current thread's btrace configuration from the target and
13817 store it into CONF. */
13818
13819 static void
13820 btrace_read_config (struct btrace_config *conf)
13821 {
13822 gdb::optional<gdb::char_vector> xml
13823 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
13824 if (xml)
13825 parse_xml_btrace_conf (conf, xml->data ());
13826 }
13827
13828 /* Maybe reopen target btrace. */
13829
13830 void
13831 remote_target::remote_btrace_maybe_reopen ()
13832 {
13833 struct remote_state *rs = get_remote_state ();
13834 struct thread_info *tp;
13835 int btrace_target_pushed = 0;
13836 int warned = 0;
13837
13838 scoped_restore_current_thread restore_thread;
13839
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;
13856 warning (_("Target is recording using Intel Processor Trace "
13857 "but support was disabled at compile time."));
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 }
13879 }
13880
13881 /* Enable branch tracing. */
13882
13883 struct btrace_target_info *
13884 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13885 {
13886 struct btrace_target_info *tinfo = NULL;
13887 struct packet_config *packet = NULL;
13888 struct remote_state *rs = get_remote_state ();
13889 char *buf = rs->buf;
13890 char *endbuf = rs->buf + get_remote_packet_size ();
13891
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)
13904 error (_("Target does not support branch tracing."));
13905
13906 btrace_sync_conf (conf);
13907
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
13924 tinfo = XCNEW (struct btrace_target_info);
13925 tinfo->ptid = ptid;
13926
13927 /* If we fail to read the configuration, we lose some information, but the
13928 tracing itself is not impacted. */
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
13939
13940 return tinfo;
13941 }
13942
13943 /* Disable branch tracing. */
13944
13945 void
13946 remote_target::disable_btrace (struct btrace_target_info *tinfo)
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
13953 if (packet_config_support (packet) != PACKET_ENABLE)
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
13977 void
13978 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13979 {
13980 /* We must not talk to the target during teardown. */
13981 xfree (tinfo);
13982 }
13983
13984 /* Read the branch trace. */
13985
13986 enum btrace_error
13987 remote_target::read_btrace (struct btrace_data *btrace,
13988 struct btrace_target_info *tinfo,
13989 enum btrace_read_type type)
13990 {
13991 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13992 const char *annex;
13993
13994 if (packet_config_support (packet) != PACKET_ENABLE)
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 {
14003 case BTRACE_READ_ALL:
14004 annex = "all";
14005 break;
14006 case BTRACE_READ_NEW:
14007 annex = "new";
14008 break;
14009 case BTRACE_READ_DELTA:
14010 annex = "delta";
14011 break;
14012 default:
14013 internal_error (__FILE__, __LINE__,
14014 _("Bad branch tracing read type: %u."),
14015 (unsigned int) type);
14016 }
14017
14018 gdb::optional<gdb::char_vector> xml
14019 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
14020 if (!xml)
14021 return BTRACE_ERR_UNKNOWN;
14022
14023 parse_xml_btrace (btrace, xml->data ());
14024
14025 return BTRACE_ERR_NONE;
14026 }
14027
14028 const struct btrace_config *
14029 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14030 {
14031 return &tinfo->conf;
14032 }
14033
14034 bool
14035 remote_target::augmented_libraries_svr4_read ()
14036 {
14037 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14038 == PACKET_ENABLE);
14039 }
14040
14041 /* Implementation of to_load. */
14042
14043 void
14044 remote_target::load (const char *name, int from_tty)
14045 {
14046 generic_load (name, from_tty);
14047 }
14048
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
14053 char *
14054 remote_target::pid_to_exec_file (int pid)
14055 {
14056 static gdb::optional<gdb::char_vector> filename;
14057 struct inferior *inf;
14058 char *annex = NULL;
14059
14060 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14061 return NULL;
14062
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
14072 annex = (char *) alloca (annex_size);
14073 xsnprintf (annex, annex_size, "%x", pid);
14074 }
14075
14076 filename = target_read_stralloc (target_stack,
14077 TARGET_OBJECT_EXEC_FILE, annex);
14078
14079 return filename ? filename->data () : nullptr;
14080 }
14081
14082 /* Implement the to_can_do_single_step target_ops method. */
14083
14084 int
14085 remote_target::can_do_single_step ()
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)
14097 remote_vcont_probe ();
14098
14099 return rs->supports_vCont.s && rs->supports_vCont.S;
14100 }
14101 else
14102 return 0;
14103 }
14104
14105 /* Implementation of the to_execution_direction method for the remote
14106 target. */
14107
14108 enum exec_direction_kind
14109 remote_target::execution_direction ()
14110 {
14111 struct remote_state *rs = get_remote_state ();
14112
14113 return rs->last_resume_exec_dir;
14114 }
14115
14116 /* Return pointer to the thread_info struct which corresponds to
14117 THREAD_HANDLE (having length HANDLE_LEN). */
14118
14119 thread_info *
14120 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14121 int handle_len,
14122 inferior *inf)
14123 {
14124 struct thread_info *tp;
14125
14126 ALL_NON_EXITED_THREADS (tp)
14127 {
14128 remote_thread_info *priv = get_remote_thread_info (tp);
14129
14130 if (tp->inf == inf && priv != NULL)
14131 {
14132 if (handle_len != priv->thread_handle.size ())
14133 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14134 handle_len, priv->thread_handle.size ());
14135 if (memcmp (thread_handle, priv->thread_handle.data (),
14136 handle_len) == 0)
14137 return tp;
14138 }
14139 }
14140
14141 return NULL;
14142 }
14143
14144 bool
14145 remote_target::can_async_p ()
14146 {
14147 struct remote_state *rs = get_remote_state ();
14148
14149 /* We don't go async if the user has explicitly prevented it with the
14150 "maint set target-async" command. */
14151 if (!target_async_permitted)
14152 return false;
14153
14154 /* We're async whenever the serial device is. */
14155 return serial_can_async_p (rs->remote_desc);
14156 }
14157
14158 bool
14159 remote_target::is_async_p ()
14160 {
14161 struct remote_state *rs = get_remote_state ();
14162
14163 if (!target_async_permitted)
14164 /* We only enable async when the user specifically asks for it. */
14165 return false;
14166
14167 /* We're async whenever the serial device is. */
14168 return serial_is_async_p (rs->remote_desc);
14169 }
14170
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
14173 point where an entire packet has been received. */
14174
14175 static serial_event_ftype remote_async_serial_handler;
14176
14177 static void
14178 remote_async_serial_handler (struct serial *scb, void *context)
14179 {
14180 /* Don't propogate error information up to the client. Instead let
14181 the client find out about the error by querying the target. */
14182 inferior_event_handler (INF_REG_EVENT, NULL);
14183 }
14184
14185 static void
14186 remote_async_inferior_event_handler (gdb_client_data data)
14187 {
14188 inferior_event_handler (INF_REG_EVENT, data);
14189 }
14190
14191 void
14192 remote_target::async (int enable)
14193 {
14194 struct remote_state *rs = get_remote_state ();
14195
14196 if (enable)
14197 {
14198 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14199
14200 /* If there are pending events in the stop reply queue tell the
14201 event loop to process them. */
14202 if (!QUEUE_is_empty (stop_reply_p, rs->stop_reply_queue))
14203 mark_async_event_handler (rs->remote_async_inferior_event_token);
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);
14211 }
14212 else
14213 {
14214 serial_async (rs->remote_desc, NULL, NULL);
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. */
14218 clear_async_event_handler (rs->remote_async_inferior_event_token);
14219 if (target_is_non_stop_p ())
14220 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14221 }
14222 }
14223
14224 /* Implementation of the to_thread_events method. */
14225
14226 void
14227 remote_target::thread_events (int enable)
14228 {
14229 struct remote_state *rs = get_remote_state ();
14230 size_t size = get_remote_packet_size ();
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
14254 static void
14255 set_remote_cmd (const char *args, int from_tty)
14256 {
14257 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
14258 }
14259
14260 static void
14261 show_remote_cmd (const char *args, int from_tty)
14262 {
14263 /* We can't just use cmd_show_list here, because we want to skip
14264 the redundant "show remote Z-packet" and the legacy aliases. */
14265 struct cmd_list_element *list = remote_show_cmdlist;
14266 struct ui_out *uiout = current_uiout;
14267
14268 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14269 for (; list != NULL; list = list->next)
14270 if (strcmp (list->name, "Z-packet") == 0)
14271 continue;
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
14277 {
14278 ui_out_emit_tuple option_emitter (uiout, "option");
14279
14280 uiout->field_string ("name", list->name);
14281 uiout->text (": ");
14282 if (list->type == show_cmd)
14283 do_show_command (NULL, from_tty, list);
14284 else
14285 cmd_func (list, NULL, from_tty);
14286 }
14287 }
14288
14289
14290 /* Function to be called whenever a new objfile (shlib) is detected. */
14291 static void
14292 remote_new_objfile (struct objfile *objfile)
14293 {
14294 remote_target *remote = get_current_remote_target ();
14295
14296 if (remote != NULL) /* Have a remote connection. */
14297 remote->remote_check_symbols ();
14298 }
14299
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
14305 int
14306 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14307 {
14308 struct remote_state *rs = get_remote_state ();
14309 char *p;
14310
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')
14316 {
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;
14322 }
14323 return 0;
14324 }
14325
14326 int
14327 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14328 {
14329 struct remote_state *rs = get_remote_state ();
14330 char *p;
14331
14332 /* Ask for a first packet of variable definition. */
14333 putpkt ("qTfV");
14334 getpkt (&rs->buf, &rs->buf_size, 0);
14335 p = rs->buf;
14336 while (*p && *p != 'l')
14337 {
14338 parse_tsv_definition (p, utsvp);
14339 /* Ask for another packet of variable definition. */
14340 putpkt ("qTsV");
14341 getpkt (&rs->buf, &rs->buf_size, 0);
14342 p = rs->buf;
14343 }
14344 return 0;
14345 }
14346
14347 /* The "set/show range-stepping" show hook. */
14348
14349 static void
14350 show_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
14359 /* Return true if the vCont;r action is supported by the remote
14360 stub. */
14361
14362 bool
14363 remote_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
14372 /* The "set/show range-stepping" set hook. */
14373
14374 static void
14375 set_range_stepping (const char *ignore_args, int from_tty,
14376 struct cmd_list_element *c)
14377 {
14378 /* When enabling, check whether range stepping is actually supported
14379 by the target, and warn if not. */
14380 if (use_range_stepping)
14381 {
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"));
14386 }
14387 }
14388
14389 void
14390 _initialize_remote (void)
14391 {
14392 struct cmd_list_element *cmd;
14393 const char *cmd_name;
14394
14395 /* architecture specific data */
14396 remote_g_packet_data_handle =
14397 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14398
14399 remote_pspace_data
14400 = register_program_space_data_with_cleanup (NULL,
14401 remote_pspace_data_cleanup);
14402
14403 add_target (remote_target_info, remote_target::open);
14404 add_target (extended_remote_target_info, extended_remote_target::open);
14405
14406 /* Hook into new objfile notification. */
14407 gdb::observers::new_objfile.attach (remote_new_objfile);
14408
14409 #if 0
14410 init_remote_threadtests ();
14411 #endif
14412
14413 /* set/show remote ... */
14414
14415 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14416 Remote protocol specific variables\n\
14417 Configure various remote-protocol specific variables such as\n\
14418 the packets being used"),
14419 &remote_set_cmdlist, "set remote ",
14420 0 /* allow-unknown */, &setlist);
14421 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14422 Remote protocol specific variables\n\
14423 Configure various remote-protocol specific variables such as\n\
14424 the packets being used"),
14425 &remote_show_cmdlist, "show remote ",
14426 0 /* allow-unknown */, &showlist);
14427
14428 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14429 Compare section data on target to the exec file.\n\
14430 Argument is a single section name (default: all loaded sections).\n\
14431 To compare only read-only loaded sections, specify the -r option."),
14432 &cmdlist);
14433
14434 add_cmd ("packet", class_maintenance, packet_command, _("\
14435 Send an arbitrary packet to a remote target.\n\
14436 maintenance packet TEXT\n\
14437 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14438 this command sends the string TEXT to the inferior, and displays the\n\
14439 response packet. GDB supplies the initial `$' character, and the\n\
14440 terminating `#' character and checksum."),
14441 &maintenancelist);
14442
14443 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14444 Set whether to send break if interrupted."), _("\
14445 Show whether to send break if interrupted."), _("\
14446 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14447 set_remotebreak, show_remotebreak,
14448 &setlist, &showlist);
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,
14457 interrupt_sequence_modes, &interrupt_sequence_mode,
14458 _("\
14459 Set interrupt sequence to remote target."), _("\
14460 Show interrupt sequence to remote target."), _("\
14461 Valid 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, _("\
14468 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14469 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14470 If set, interrupt sequence is sent to remote target."),
14471 NULL, NULL,
14472 &remote_set_cmdlist, &remote_show_cmdlist);
14473
14474 /* Install commands for configuring memory read/write packets. */
14475
14476 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14477 Set the maximum number of bytes per memory write packet (deprecated)."),
14478 &setlist);
14479 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14480 Show the maximum number of bytes per memory write packet (deprecated)."),
14481 &showlist);
14482 add_cmd ("memory-write-packet-size", no_class,
14483 set_memory_write_packet_size, _("\
14484 Set the maximum number of bytes per memory-write packet.\n\
14485 Specify the number of bytes in a packet or 0 (zero) for the\n\
14486 default packet size. The actual limit is further reduced\n\
14487 dependent on the target. Specify ``fixed'' to disable the\n\
14488 further restriction and ``limit'' to enable that restriction."),
14489 &remote_set_cmdlist);
14490 add_cmd ("memory-read-packet-size", no_class,
14491 set_memory_read_packet_size, _("\
14492 Set the maximum number of bytes per memory-read packet.\n\
14493 Specify the number of bytes in a packet or 0 (zero) for the\n\
14494 default packet size. The actual limit is further reduced\n\
14495 dependent on the target. Specify ``fixed'' to disable the\n\
14496 further restriction and ``limit'' to enable that restriction."),
14497 &remote_set_cmdlist);
14498 add_cmd ("memory-write-packet-size", no_class,
14499 show_memory_write_packet_size,
14500 _("Show the maximum number of bytes per memory-write packet."),
14501 &remote_show_cmdlist);
14502 add_cmd ("memory-read-packet-size", no_class,
14503 show_memory_read_packet_size,
14504 _("Show the maximum number of bytes per memory-read packet."),
14505 &remote_show_cmdlist);
14506
14507 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14508 &remote_hw_watchpoint_limit, _("\
14509 Set the maximum number of target hardware watchpoints."), _("\
14510 Show the maximum number of target hardware watchpoints."), _("\
14511 Specify a negative limit for unlimited."),
14512 NULL, NULL, /* FIXME: i18n: The maximum
14513 number of target hardware
14514 watchpoints is %s. */
14515 &remote_set_cmdlist, &remote_show_cmdlist);
14516 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14517 &remote_hw_watchpoint_length_limit, _("\
14518 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14519 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14520 Specify 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);
14525 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14526 &remote_hw_breakpoint_limit, _("\
14527 Set the maximum number of target hardware breakpoints."), _("\
14528 Show the maximum number of target hardware breakpoints."), _("\
14529 Specify a negative limit for unlimited."),
14530 NULL, NULL, /* FIXME: i18n: The maximum
14531 number of target hardware
14532 breakpoints is %s. */
14533 &remote_set_cmdlist, &remote_show_cmdlist);
14534
14535 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14536 &remote_address_size, _("\
14537 Set the maximum size of the address (in bits) in a memory packet."), _("\
14538 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14539 NULL,
14540 NULL, /* FIXME: i18n: */
14541 &setlist, &showlist);
14542
14543 init_all_packet_configs ();
14544
14545 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14546 "X", "binary-download", 1);
14547
14548 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14549 "vCont", "verbose-resume", 0);
14550
14551 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14552 "QPassSignals", "pass-signals", 0);
14553
14554 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14555 "QCatchSyscalls", "catch-syscalls", 0);
14556
14557 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14558 "QProgramSignals", "program-signals", 0);
14559
14560 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14561 "QSetWorkingDir", "set-working-dir", 0);
14562
14563 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14564 "QStartupWithShell", "startup-with-shell", 0);
14565
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
14579 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14580 "qSymbol", "symbol-lookup", 0);
14581
14582 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14583 "P", "set-register", 1);
14584
14585 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14586 "p", "fetch-register", 1);
14587
14588 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14589 "Z0", "software-breakpoint", 0);
14590
14591 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14592 "Z1", "hardware-breakpoint", 0);
14593
14594 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14595 "Z2", "write-watchpoint", 0);
14596
14597 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14598 "Z3", "read-watchpoint", 0);
14599
14600 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14601 "Z4", "access-watchpoint", 0);
14602
14603 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14604 "qXfer:auxv:read", "read-aux-vector", 0);
14605
14606 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14607 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14608
14609 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14610 "qXfer:features:read", "target-features", 0);
14611
14612 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14613 "qXfer:libraries:read", "library-info", 0);
14614
14615 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14616 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14617
14618 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14619 "qXfer:memory-map:read", "memory-map", 0);
14620
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
14627 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14628 "qXfer:osdata:read", "osdata", 0);
14629
14630 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14631 "qXfer:threads:read", "threads", 0);
14632
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
14639 add_packet_config_cmd
14640 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14641 "qXfer:traceframe-info:read", "traceframe-info", 0);
14642
14643 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14644 "qXfer:uib:read", "unwind-info-block", 0);
14645
14646 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14647 "qGetTLSAddr", "get-thread-local-storage-address",
14648 0);
14649
14650 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14651 "qGetTIBAddr", "get-thread-information-block-address",
14652 0);
14653
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
14660 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14661 "qSupported", "supported-packets", 0);
14662
14663 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14664 "qSearch:memory", "search-memory", 0);
14665
14666 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14667 "qTStatus", "trace-status", 0);
14668
14669 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14670 "vFile:setfs", "hostio-setfs", 0);
14671
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
14687 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14688 "vFile:readlink", "hostio-readlink", 0);
14689
14690 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14691 "vFile:fstat", "hostio-fstat", 0);
14692
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
14699 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14700 "QStartNoAckMode", "noack", 0);
14701
14702 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14703 "vKill", "kill", 0);
14704
14705 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14706 "qAttached", "query-attached", 0);
14707
14708 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14709 "ConditionalTracepoints",
14710 "conditional-tracepoints", 0);
14711
14712 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14713 "ConditionalBreakpoints",
14714 "conditional-breakpoints", 0);
14715
14716 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14717 "BreakpointCommands",
14718 "breakpoint-commands", 0);
14719
14720 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14721 "FastTracepoints", "fast-tracepoints", 0);
14722
14723 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14724 "TracepointSource", "TracepointSource", 0);
14725
14726 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14727 "QAllow", "allow", 0);
14728
14729 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14730 "StaticTracepoints", "static-tracepoints", 0);
14731
14732 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14733 "InstallInTrace", "install-in-trace", 0);
14734
14735 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14736 "qXfer:statictrace:read", "read-sdata-object", 0);
14737
14738 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14739 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14740
14741 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14742 "QDisableRandomization", "disable-randomization", 0);
14743
14744 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14745 "QAgent", "agent", 0);
14746
14747 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14748 "QTBuffer:size", "trace-buffer-size", 0);
14749
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],
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);
14758
14759 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14760 "qXfer:btrace", "read-btrace", 0);
14761
14762 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14763 "qXfer:btrace-conf", "read-btrace-conf", 0);
14764
14765 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14766 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14767
14768 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14769 "multiprocess-feature", "multiprocess-feature", 0);
14770
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
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
14783 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14784 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14785
14786 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14787 "vContSupported", "verbose-resume-supported", 0);
14788
14789 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14790 "exec-event-feature", "exec-event-feature", 0);
14791
14792 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14793 "vCtrlC", "ctrl-c", 0);
14794
14795 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14796 "QThreadEvents", "thread-events", 0);
14797
14798 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14799 "N stop reply", "no-resumed-stop-reply", 0);
14800
14801 /* Assert that we've registered "set remote foo-packet" commands
14802 for all packet configs. */
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:
14815 case PACKET_EnableDisableTracepoints_feature:
14816 case PACKET_tracenz_feature:
14817 case PACKET_DisconnectedTracing_feature:
14818 case PACKET_augmented_libraries_svr4_read_feature:
14819 case PACKET_qCRC:
14820 /* Additions to this list need to be well justified:
14821 pre-existing packets are OK; new packets are not. */
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
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). */
14839 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14840 &remote_Z_packet_detect, _("\
14841 Set use of remote protocol `Z' packets"), _("\
14842 Show use of remote protocol `Z' packets "), _("\
14843 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14844 packets."),
14845 set_remote_protocol_Z_packet_cmd,
14846 show_remote_protocol_Z_packet_cmd,
14847 /* FIXME: i18n: Use of remote protocol
14848 `Z' packets is %s. */
14849 &remote_set_cmdlist, &remote_show_cmdlist);
14850
14851 add_prefix_cmd ("remote", class_files, remote_command, _("\
14852 Manipulate files on the remote system\n\
14853 Transfer 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
14869 add_setshow_string_noescape_cmd ("exec-file", class_files,
14870 &remote_exec_file_var, _("\
14871 Set the remote pathname for \"run\""), _("\
14872 Show the remote pathname for \"run\""), NULL,
14873 set_remote_exec_file,
14874 show_remote_exec_file,
14875 &remote_set_cmdlist,
14876 &remote_show_cmdlist);
14877
14878 add_setshow_boolean_cmd ("range-stepping", class_run,
14879 &use_range_stepping, _("\
14880 Enable or disable range stepping."), _("\
14881 Show whether target-assisted range stepping is enabled."), _("\
14882 If on, and the target supports it, when stepping a source line, GDB\n\
14883 tells the target to step the corresponding range of addresses itself instead\n\
14884 of issuing multiple single-steps. This speeds up source level\n\
14885 stepping. If off, GDB always issues single-steps, even if range\n\
14886 stepping is supported by the target. The default is on."),
14887 set_range_stepping,
14888 show_range_stepping,
14889 &setlist,
14890 &showlist);
14891
14892 /* Eventually initialize fileio. See fileio.c */
14893 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14894
14895 /* Take advantage of the fact that the TID field is not used, to tag
14896 special ptids with it set to != 0. */
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);
14900 }
This page took 0.355716 seconds and 4 git commands to generate.