remote: multiple remote_arch_state instances per arch
[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 static const target_info remote_target_info = {
88 "remote",
89 N_("Remote serial target in gdb-specific protocol"),
90 remote_doc
91 };
92
93 class remote_target : public target_ops
94 {
95 public:
96 remote_target ()
97 {
98 to_stratum = process_stratum;
99 }
100
101 const target_info &info () const override
102 { return remote_target_info; }
103
104 thread_control_capabilities get_thread_control_capabilities () override
105 { return tc_schedlock; }
106
107 /* Open a remote connection. */
108 static void open (const char *, int);
109
110 void close () override;
111
112 void detach (inferior *, int) override;
113 void disconnect (const char *, int) override;
114
115 void commit_resume () override;
116 void resume (ptid_t, int, enum gdb_signal) override;
117 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
118
119 void fetch_registers (struct regcache *, int) override;
120 void store_registers (struct regcache *, int) override;
121 void prepare_to_store (struct regcache *) override;
122
123 void files_info () override;
124
125 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
126
127 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
128 enum remove_bp_reason) override;
129
130
131 bool stopped_by_sw_breakpoint () override;
132 bool supports_stopped_by_sw_breakpoint () override;
133
134 bool stopped_by_hw_breakpoint () override;
135
136 bool supports_stopped_by_hw_breakpoint () override;
137
138 bool stopped_by_watchpoint () override;
139
140 bool stopped_data_address (CORE_ADDR *) override;
141
142 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
143
144 int can_use_hw_breakpoint (enum bptype, int, int) override;
145
146 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
147
148 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
149
150 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
151
152 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
153 struct expression *) override;
154
155 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
156 struct expression *) override;
157
158 void kill () override;
159
160 void load (const char *, int) override;
161
162 void mourn_inferior () override;
163
164 void pass_signals (int, unsigned char *) override;
165
166 int set_syscall_catchpoint (int, bool, int,
167 gdb::array_view<const int>) override;
168
169 void program_signals (int, unsigned char *) override;
170
171 bool thread_alive (ptid_t ptid) override;
172
173 const char *thread_name (struct thread_info *) override;
174
175 void update_thread_list () override;
176
177 const char *pid_to_str (ptid_t) override;
178
179 const char *extra_thread_info (struct thread_info *) override;
180
181 ptid_t get_ada_task_ptid (long lwp, long thread) override;
182
183 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
184 int handle_len,
185 inferior *inf) override;
186
187 void stop (ptid_t) override;
188
189 void interrupt () override;
190
191 void pass_ctrlc () override;
192
193 enum target_xfer_status xfer_partial (enum target_object object,
194 const char *annex,
195 gdb_byte *readbuf,
196 const gdb_byte *writebuf,
197 ULONGEST offset, ULONGEST len,
198 ULONGEST *xfered_len) override;
199
200 ULONGEST get_memory_xfer_limit () override;
201
202 void rcmd (const char *command, struct ui_file *output) override;
203
204 char *pid_to_exec_file (int pid) override;
205
206 void log_command (const char *cmd) override
207 {
208 serial_log_command (this, cmd);
209 }
210
211 CORE_ADDR get_thread_local_address (ptid_t ptid,
212 CORE_ADDR load_module_addr,
213 CORE_ADDR offset) override;
214
215 bool has_all_memory () override { return default_child_has_all_memory (); }
216 bool has_memory () override { return default_child_has_memory (); }
217 bool has_stack () override { return default_child_has_stack (); }
218 bool has_registers () override { return default_child_has_registers (); }
219 bool has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
220
221 bool can_execute_reverse () override;
222
223 std::vector<mem_region> memory_map () override;
224
225 void flash_erase (ULONGEST address, LONGEST length) override;
226
227 void flash_done () override;
228
229 const struct target_desc *read_description () override;
230
231 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
232 const gdb_byte *pattern, ULONGEST pattern_len,
233 CORE_ADDR *found_addrp) override;
234
235 bool can_async_p () override;
236
237 bool is_async_p () override;
238
239 void async (int) override;
240
241 void thread_events (int) override;
242
243 int can_do_single_step () override;
244
245 void terminal_inferior () override;
246
247 void terminal_ours () override;
248
249 bool supports_non_stop () override;
250
251 bool supports_multi_process () override;
252
253 bool supports_disable_randomization () override;
254
255 bool filesystem_is_local () override;
256
257
258 int fileio_open (struct inferior *inf, const char *filename,
259 int flags, int mode, int warn_if_slow,
260 int *target_errno) override;
261
262 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
263 ULONGEST offset, int *target_errno) override;
264
265 int fileio_pread (int fd, gdb_byte *read_buf, int len,
266 ULONGEST offset, int *target_errno) override;
267
268 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
269
270 int fileio_close (int fd, int *target_errno) override;
271
272 int fileio_unlink (struct inferior *inf,
273 const char *filename,
274 int *target_errno) override;
275
276 gdb::optional<std::string>
277 fileio_readlink (struct inferior *inf,
278 const char *filename,
279 int *target_errno) override;
280
281 bool supports_enable_disable_tracepoint () override;
282
283 bool supports_string_tracing () override;
284
285 bool supports_evaluation_of_breakpoint_conditions () override;
286
287 bool can_run_breakpoint_commands () override;
288
289 void trace_init () override;
290
291 void download_tracepoint (struct bp_location *location) override;
292
293 bool can_download_tracepoint () override;
294
295 void download_trace_state_variable (const trace_state_variable &tsv) override;
296
297 void enable_tracepoint (struct bp_location *location) override;
298
299 void disable_tracepoint (struct bp_location *location) override;
300
301 void trace_set_readonly_regions () override;
302
303 void trace_start () override;
304
305 int get_trace_status (struct trace_status *ts) override;
306
307 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
308 override;
309
310 void trace_stop () override;
311
312 int trace_find (enum trace_find_type type, int num,
313 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
314
315 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
316
317 int save_trace_data (const char *filename) override;
318
319 int upload_tracepoints (struct uploaded_tp **utpp) override;
320
321 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
322
323 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
324
325 int get_min_fast_tracepoint_insn_len () override;
326
327 void set_disconnected_tracing (int val) override;
328
329 void set_circular_trace_buffer (int val) override;
330
331 void set_trace_buffer_size (LONGEST val) override;
332
333 bool set_trace_notes (const char *user, const char *notes,
334 const char *stopnotes) override;
335
336 int core_of_thread (ptid_t ptid) override;
337
338 int verify_memory (const gdb_byte *data,
339 CORE_ADDR memaddr, ULONGEST size) override;
340
341
342 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
343
344 void set_permissions () override;
345
346 bool static_tracepoint_marker_at (CORE_ADDR,
347 struct static_tracepoint_marker *marker)
348 override;
349
350 std::vector<static_tracepoint_marker>
351 static_tracepoint_markers_by_strid (const char *id) override;
352
353 traceframe_info_up traceframe_info () override;
354
355 bool use_agent (bool use) override;
356 bool can_use_agent () override;
357
358 struct btrace_target_info *enable_btrace (ptid_t ptid,
359 const struct btrace_config *conf) override;
360
361 void disable_btrace (struct btrace_target_info *tinfo) override;
362
363 void teardown_btrace (struct btrace_target_info *tinfo) override;
364
365 enum btrace_error read_btrace (struct btrace_data *data,
366 struct btrace_target_info *btinfo,
367 enum btrace_read_type type) override;
368
369 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
370 bool augmented_libraries_svr4_read () override;
371 int follow_fork (int, int) override;
372 void follow_exec (struct inferior *, char *) override;
373 int insert_fork_catchpoint (int) override;
374 int remove_fork_catchpoint (int) override;
375 int insert_vfork_catchpoint (int) override;
376 int remove_vfork_catchpoint (int) override;
377 int insert_exec_catchpoint (int) override;
378 int remove_exec_catchpoint (int) override;
379 enum exec_direction_kind execution_direction () override;
380
381 protected:
382 static void open_1 (const char *name, int from_tty, int extended_p);
383 void start_remote (int from_tty, int extended_p);
384 };
385
386 static const target_info extended_remote_target_info = {
387 "extended-remote",
388 N_("Extended remote serial target in gdb-specific protocol"),
389 remote_doc
390 };
391
392 /* Set up the extended remote target by extending the standard remote
393 target and adding to it. */
394
395 class extended_remote_target final : public remote_target
396 {
397 public:
398 const target_info &info () const override
399 { return extended_remote_target_info; }
400
401 /* Open an extended-remote connection. */
402 static void open (const char *, int);
403
404 bool can_create_inferior () override { return true; }
405 void create_inferior (const char *, const std::string &,
406 char **, int) override;
407
408 void detach (inferior *, int) override;
409
410 bool can_attach () override { return true; }
411 void attach (const char *, int) override;
412
413 void post_attach (int) override;
414 bool supports_disable_randomization () override;
415 };
416
417 /* Per-program-space data key. */
418 static const struct program_space_data *remote_pspace_data;
419
420 /* The variable registered as the control variable used by the
421 remote exec-file commands. While the remote exec-file setting is
422 per-program-space, the set/show machinery uses this as the
423 location of the remote exec-file value. */
424 static char *remote_exec_file_var;
425
426 /* The size to align memory write packets, when practical. The protocol
427 does not guarantee any alignment, and gdb will generate short
428 writes and unaligned writes, but even as a best-effort attempt this
429 can improve bulk transfers. For instance, if a write is misaligned
430 relative to the target's data bus, the stub may need to make an extra
431 round trip fetching data from the target. This doesn't make a
432 huge difference, but it's easy to do, so we try to be helpful.
433
434 The alignment chosen is arbitrary; usually data bus width is
435 important here, not the possibly larger cache line size. */
436 enum { REMOTE_ALIGN_WRITES = 16 };
437
438 /* Prototypes for local functions. */
439 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
440 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
441 int forever, int *is_notif);
442
443 struct remote_state;
444
445 static int remote_vkill (int pid, struct remote_state *rs);
446
447 static void remote_kill_k (void);
448
449 static int readchar (int timeout);
450
451 static void remote_serial_write (const char *str, int len);
452
453 static void interrupt_query (void);
454
455 static void set_general_thread (ptid_t ptid);
456 static void set_continue_thread (ptid_t ptid);
457
458 static void get_offsets (void);
459
460 static void skip_frame (void);
461
462 static long read_frame (char **buf_p, long *sizeof_buf);
463
464 static int hexnumlen (ULONGEST num);
465
466 static int stubhex (int ch);
467
468 static int hexnumstr (char *, ULONGEST);
469
470 static int hexnumnstr (char *, ULONGEST, int);
471
472 static CORE_ADDR remote_address_masked (CORE_ADDR);
473
474 static void print_packet (const char *);
475
476 static int stub_unpack_int (char *buff, int fieldlength);
477
478 static ptid_t remote_current_thread (ptid_t oldptid);
479
480 static int putpkt_binary (const char *buf, int cnt);
481
482 static void check_binary_download (CORE_ADDR addr);
483
484 struct packet_config;
485
486 static void show_packet_config_cmd (struct packet_config *config);
487
488 static void show_remote_protocol_packet_cmd (struct ui_file *file,
489 int from_tty,
490 struct cmd_list_element *c,
491 const char *value);
492
493 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
494 static ptid_t read_ptid (const char *buf, const char **obuf);
495
496 static void remote_query_supported (void);
497
498 static void remote_check_symbols (void);
499
500 struct stop_reply;
501 static void stop_reply_xfree (struct stop_reply *);
502 static void remote_parse_stop_reply (char *, struct stop_reply *);
503 static void push_stop_reply (struct stop_reply *);
504 static void discard_pending_stop_replies_in_queue (struct remote_state *);
505 static int peek_stop_reply (ptid_t ptid);
506
507 struct threads_listing_context;
508 static void remove_new_fork_children (struct threads_listing_context *);
509
510 static void remote_async_inferior_event_handler (gdb_client_data);
511
512 static int remote_read_description_p (struct target_ops *target);
513
514 static void remote_console_output (char *msg);
515
516 static void remote_btrace_reset (void);
517
518 static void remote_btrace_maybe_reopen (void);
519
520 static int stop_reply_queue_length (void);
521
522 static void remote_unpush_and_throw (void);
523
524 static struct remote_state *get_remote_state (void);
525
526 /* For "remote". */
527
528 static struct cmd_list_element *remote_cmdlist;
529
530 /* For "set remote" and "show remote". */
531
532 static struct cmd_list_element *remote_set_cmdlist;
533 static struct cmd_list_element *remote_show_cmdlist;
534
535 /* Stub vCont actions support.
536
537 Each field is a boolean flag indicating whether the stub reports
538 support for the corresponding action. */
539
540 struct vCont_action_support
541 {
542 /* vCont;t */
543 bool t = false;
544
545 /* vCont;r */
546 bool r = false;
547
548 /* vCont;s */
549 bool s = false;
550
551 /* vCont;S */
552 bool S = false;
553 };
554
555 /* Controls whether GDB is willing to use range stepping. */
556
557 static int use_range_stepping = 1;
558
559 #define OPAQUETHREADBYTES 8
560
561 /* a 64 bit opaque identifier */
562 typedef unsigned char threadref[OPAQUETHREADBYTES];
563
564 /* About this many threadisds fit in a packet. */
565
566 #define MAXTHREADLISTRESULTS 32
567
568 /* The max number of chars in debug output. The rest of chars are
569 omitted. */
570
571 #define REMOTE_DEBUG_MAX_CHAR 512
572
573 /* Data for the vFile:pread readahead cache. */
574
575 struct readahead_cache
576 {
577 /* Invalidate the readahead cache. */
578 void invalidate ();
579
580 /* Invalidate the readahead cache if it is holding data for FD. */
581 void invalidate_fd (int fd);
582
583 /* Serve pread from the readahead cache. Returns number of bytes
584 read, or 0 if the request can't be served from the cache. */
585 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
586
587 /* The file descriptor for the file that is being cached. -1 if the
588 cache is invalid. */
589 int fd = -1;
590
591 /* The offset into the file that the cache buffer corresponds
592 to. */
593 ULONGEST offset = 0;
594
595 /* The buffer holding the cache contents. */
596 gdb_byte *buf = nullptr;
597 /* The buffer's size. We try to read as much as fits into a packet
598 at a time. */
599 size_t bufsize = 0;
600
601 /* Cache hit and miss counters. */
602 ULONGEST hit_count = 0;
603 ULONGEST miss_count = 0;
604 };
605
606 /* Description of the remote protocol state for the currently
607 connected target. This is per-target state, and independent of the
608 selected architecture. */
609
610 class remote_state
611 {
612 public:
613
614 remote_state ();
615 ~remote_state ();
616
617 /* Get the remote arch state for GDBARCH. */
618 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
619
620 public: /* data */
621
622 /* A buffer to use for incoming packets, and its current size. The
623 buffer is grown dynamically for larger incoming packets.
624 Outgoing packets may also be constructed in this buffer.
625 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
626 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
627 packets. */
628 char *buf;
629 long buf_size;
630
631 /* True if we're going through initial connection setup (finding out
632 about the remote side's threads, relocating symbols, etc.). */
633 bool starting_up = false;
634
635 /* If we negotiated packet size explicitly (and thus can bypass
636 heuristics for the largest packet size that will not overflow
637 a buffer in the stub), this will be set to that packet size.
638 Otherwise zero, meaning to use the guessed size. */
639 long explicit_packet_size = 0;
640
641 /* remote_wait is normally called when the target is running and
642 waits for a stop reply packet. But sometimes we need to call it
643 when the target is already stopped. We can send a "?" packet
644 and have remote_wait read the response. Or, if we already have
645 the response, we can stash it in BUF and tell remote_wait to
646 skip calling getpkt. This flag is set when BUF contains a
647 stop reply packet and the target is not waiting. */
648 int cached_wait_status = 0;
649
650 /* True, if in no ack mode. That is, neither GDB nor the stub will
651 expect acks from each other. The connection is assumed to be
652 reliable. */
653 bool noack_mode = false;
654
655 /* True if we're connected in extended remote mode. */
656 bool extended = false;
657
658 /* True if we resumed the target and we're waiting for the target to
659 stop. In the mean time, we can't start another command/query.
660 The remote server wouldn't be ready to process it, so we'd
661 timeout waiting for a reply that would never come and eventually
662 we'd close the connection. This can happen in asynchronous mode
663 because we allow GDB commands while the target is running. */
664 bool waiting_for_stop_reply = false;
665
666 /* The status of the stub support for the various vCont actions. */
667 vCont_action_support supports_vCont;
668
669 /* True if the user has pressed Ctrl-C, but the target hasn't
670 responded to that. */
671 bool ctrlc_pending_p = false;
672
673 /* True if we saw a Ctrl-C while reading or writing from/to the
674 remote descriptor. At that point it is not safe to send a remote
675 interrupt packet, so we instead remember we saw the Ctrl-C and
676 process it once we're done with sending/receiving the current
677 packet, which should be shortly. If however that takes too long,
678 and the user presses Ctrl-C again, we offer to disconnect. */
679 bool got_ctrlc_during_io = false;
680
681 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
682 remote_open knows that we don't have a file open when the program
683 starts. */
684 struct serial *remote_desc = nullptr;
685
686 /* These are the threads which we last sent to the remote system. The
687 TID member will be -1 for all or -2 for not sent yet. */
688 ptid_t general_thread = null_ptid;
689 ptid_t continue_thread = null_ptid;
690
691 /* This is the traceframe which we last selected on the remote system.
692 It will be -1 if no traceframe is selected. */
693 int remote_traceframe_number = -1;
694
695 char *last_pass_packet = nullptr;
696
697 /* The last QProgramSignals packet sent to the target. We bypass
698 sending a new program signals list down to the target if the new
699 packet is exactly the same as the last we sent. IOW, we only let
700 the target know about program signals list changes. */
701 char *last_program_signals_packet = nullptr;
702
703 gdb_signal last_sent_signal = GDB_SIGNAL_0;
704
705 bool last_sent_step = false;
706
707 /* The execution direction of the last resume we got. */
708 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
709
710 char *finished_object = nullptr;
711 char *finished_annex = nullptr;
712 ULONGEST finished_offset = 0;
713
714 /* Should we try the 'ThreadInfo' query packet?
715
716 This variable (NOT available to the user: auto-detect only!)
717 determines whether GDB will use the new, simpler "ThreadInfo"
718 query or the older, more complex syntax for thread queries.
719 This is an auto-detect variable (set to true at each connect,
720 and set to false when the target fails to recognize it). */
721 bool use_threadinfo_query = false;
722 bool use_threadextra_query = false;
723
724 threadref echo_nextthread {};
725 threadref nextthread {};
726 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
727
728 /* The state of remote notification. */
729 struct remote_notif_state *notif_state = nullptr;
730
731 /* The branch trace configuration. */
732 struct btrace_config btrace_config {};
733
734 /* The argument to the last "vFile:setfs:" packet we sent, used
735 to avoid sending repeated unnecessary "vFile:setfs:" packets.
736 Initialized to -1 to indicate that no "vFile:setfs:" packet
737 has yet been sent. */
738 int fs_pid = -1;
739
740 /* A readahead cache for vFile:pread. Often, reading a binary
741 involves a sequence of small reads. E.g., when parsing an ELF
742 file. A readahead cache helps mostly the case of remote
743 debugging on a connection with higher latency, due to the
744 request/reply nature of the RSP. We only cache data for a single
745 file descriptor at a time. */
746 struct readahead_cache readahead_cache;
747
748 private:
749 /* Mapping of remote protocol data for each gdbarch. Usually there
750 is only one entry here, though we may see more with stubs that
751 support multi-process. */
752 std::unordered_map<struct gdbarch *,
753 std::unique_ptr<struct remote_arch_state>>
754 m_arch_states;
755 };
756
757 /* Private data that we'll store in (struct thread_info)->priv. */
758 struct remote_thread_info : public private_thread_info
759 {
760 std::string extra;
761 std::string name;
762 int core = -1;
763
764 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
765 sequence of bytes. */
766 gdb::byte_vector thread_handle;
767
768 /* Whether the target stopped for a breakpoint/watchpoint. */
769 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
770
771 /* This is set to the data address of the access causing the target
772 to stop for a watchpoint. */
773 CORE_ADDR watch_data_address = 0;
774
775 /* Fields used by the vCont action coalescing implemented in
776 remote_resume / remote_commit_resume. remote_resume stores each
777 thread's last resume request in these fields, so that a later
778 remote_commit_resume knows which is the proper action for this
779 thread to include in the vCont packet. */
780
781 /* True if the last target_resume call for this thread was a step
782 request, false if a continue request. */
783 int last_resume_step = 0;
784
785 /* The signal specified in the last target_resume call for this
786 thread. */
787 gdb_signal last_resume_sig = GDB_SIGNAL_0;
788
789 /* Whether this thread was already vCont-resumed on the remote
790 side. */
791 int vcont_resumed = 0;
792 };
793
794 remote_state::remote_state ()
795 {
796 /* The default buffer size is unimportant; it will be expanded
797 whenever a larger buffer is needed. */
798 this->buf_size = 400;
799 this->buf = (char *) xmalloc (this->buf_size);
800 }
801
802 remote_state::~remote_state ()
803 {
804 xfree (this->last_pass_packet);
805 xfree (this->last_program_signals_packet);
806 xfree (this->buf);
807 xfree (this->finished_object);
808 xfree (this->finished_annex);
809 }
810
811 /* This data could be associated with a target, but we do not always
812 have access to the current target when we need it, so for now it is
813 static. This will be fine for as long as only one target is in use
814 at a time. */
815 static struct remote_state *remote_state;
816
817 static struct remote_state *
818 get_remote_state_raw (void)
819 {
820 return remote_state;
821 }
822
823 /* Description of the remote protocol for a given architecture. */
824
825 struct packet_reg
826 {
827 long offset; /* Offset into G packet. */
828 long regnum; /* GDB's internal register number. */
829 LONGEST pnum; /* Remote protocol register number. */
830 int in_g_packet; /* Always part of G packet. */
831 /* long size in bytes; == register_size (target_gdbarch (), regnum);
832 at present. */
833 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
834 at present. */
835 };
836
837 struct remote_arch_state
838 {
839 explicit remote_arch_state (struct gdbarch *gdbarch);
840
841 /* Description of the remote protocol registers. */
842 long sizeof_g_packet;
843
844 /* Description of the remote protocol registers indexed by REGNUM
845 (making an array gdbarch_num_regs in size). */
846 std::unique_ptr<packet_reg[]> regs;
847
848 /* This is the size (in chars) of the first response to the ``g''
849 packet. It is used as a heuristic when determining the maximum
850 size of memory-read and memory-write packets. A target will
851 typically only reserve a buffer large enough to hold the ``g''
852 packet. The size does not include packet overhead (headers and
853 trailers). */
854 long actual_register_packet_size;
855
856 /* This is the maximum size (in chars) of a non read/write packet.
857 It is also used as a cap on the size of read/write packets. */
858 long remote_packet_size;
859 };
860
861 /* Utility: generate error from an incoming stub packet. */
862 static void
863 trace_error (char *buf)
864 {
865 if (*buf++ != 'E')
866 return; /* not an error msg */
867 switch (*buf)
868 {
869 case '1': /* malformed packet error */
870 if (*++buf == '0') /* general case: */
871 error (_("remote.c: error in outgoing packet."));
872 else
873 error (_("remote.c: error in outgoing packet at field #%ld."),
874 strtol (buf, NULL, 16));
875 default:
876 error (_("Target returns error code '%s'."), buf);
877 }
878 }
879
880 /* Utility: wait for reply from stub, while accepting "O" packets. */
881
882 static char *
883 remote_get_noisy_reply ()
884 {
885 struct remote_state *rs = get_remote_state ();
886
887 do /* Loop on reply from remote stub. */
888 {
889 char *buf;
890
891 QUIT; /* Allow user to bail out with ^C. */
892 getpkt (&rs->buf, &rs->buf_size, 0);
893 buf = rs->buf;
894 if (buf[0] == 'E')
895 trace_error (buf);
896 else if (startswith (buf, "qRelocInsn:"))
897 {
898 ULONGEST ul;
899 CORE_ADDR from, to, org_to;
900 const char *p, *pp;
901 int adjusted_size = 0;
902 int relocated = 0;
903
904 p = buf + strlen ("qRelocInsn:");
905 pp = unpack_varlen_hex (p, &ul);
906 if (*pp != ';')
907 error (_("invalid qRelocInsn packet: %s"), buf);
908 from = ul;
909
910 p = pp + 1;
911 unpack_varlen_hex (p, &ul);
912 to = ul;
913
914 org_to = to;
915
916 TRY
917 {
918 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
919 relocated = 1;
920 }
921 CATCH (ex, RETURN_MASK_ALL)
922 {
923 if (ex.error == MEMORY_ERROR)
924 {
925 /* Propagate memory errors silently back to the
926 target. The stub may have limited the range of
927 addresses we can write to, for example. */
928 }
929 else
930 {
931 /* Something unexpectedly bad happened. Be verbose
932 so we can tell what, and propagate the error back
933 to the stub, so it doesn't get stuck waiting for
934 a response. */
935 exception_fprintf (gdb_stderr, ex,
936 _("warning: relocating instruction: "));
937 }
938 putpkt ("E01");
939 }
940 END_CATCH
941
942 if (relocated)
943 {
944 adjusted_size = to - org_to;
945
946 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
947 putpkt (buf);
948 }
949 }
950 else if (buf[0] == 'O' && buf[1] != 'K')
951 remote_console_output (buf + 1); /* 'O' message from stub */
952 else
953 return buf; /* Here's the actual reply. */
954 }
955 while (1);
956 }
957
958 struct remote_arch_state *
959 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
960 {
961 auto &rsa = this->m_arch_states[gdbarch];
962 if (rsa == nullptr)
963 {
964 rsa.reset (new remote_arch_state (gdbarch));
965
966 /* Make sure that the packet buffer is plenty big enough for
967 this architecture. */
968 if (this->buf_size < rsa->remote_packet_size)
969 {
970 this->buf_size = 2 * rsa->remote_packet_size;
971 this->buf = (char *) xrealloc (this->buf, this->buf_size);
972 }
973 }
974 return rsa.get ();
975 }
976
977 /* Fetch the global remote target state. */
978
979 static struct remote_state *
980 get_remote_state (void)
981 {
982 struct remote_state *rs = get_remote_state_raw ();
983
984 /* Make sure that the remote architecture state has been
985 initialized, because doing so might reallocate rs->buf. Any
986 function which calls getpkt also needs to be mindful of changes
987 to rs->buf, but this call limits the number of places which run
988 into trouble. */
989 rs->get_remote_arch_state (target_gdbarch ());
990
991 return rs;
992 }
993
994 /* Cleanup routine for the remote module's pspace data. */
995
996 static void
997 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
998 {
999 char *remote_exec_file = (char *) arg;
1000
1001 xfree (remote_exec_file);
1002 }
1003
1004 /* Fetch the remote exec-file from the current program space. */
1005
1006 static const char *
1007 get_remote_exec_file (void)
1008 {
1009 char *remote_exec_file;
1010
1011 remote_exec_file
1012 = (char *) program_space_data (current_program_space,
1013 remote_pspace_data);
1014 if (remote_exec_file == NULL)
1015 return "";
1016
1017 return remote_exec_file;
1018 }
1019
1020 /* Set the remote exec file for PSPACE. */
1021
1022 static void
1023 set_pspace_remote_exec_file (struct program_space *pspace,
1024 char *remote_exec_file)
1025 {
1026 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
1027
1028 xfree (old_file);
1029 set_program_space_data (pspace, remote_pspace_data,
1030 xstrdup (remote_exec_file));
1031 }
1032
1033 /* The "set/show remote exec-file" set command hook. */
1034
1035 static void
1036 set_remote_exec_file (const char *ignored, int from_tty,
1037 struct cmd_list_element *c)
1038 {
1039 gdb_assert (remote_exec_file_var != NULL);
1040 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1041 }
1042
1043 /* The "set/show remote exec-file" show command hook. */
1044
1045 static void
1046 show_remote_exec_file (struct ui_file *file, int from_tty,
1047 struct cmd_list_element *cmd, const char *value)
1048 {
1049 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1050 }
1051
1052 static int
1053 compare_pnums (const void *lhs_, const void *rhs_)
1054 {
1055 const struct packet_reg * const *lhs
1056 = (const struct packet_reg * const *) lhs_;
1057 const struct packet_reg * const *rhs
1058 = (const struct packet_reg * const *) rhs_;
1059
1060 if ((*lhs)->pnum < (*rhs)->pnum)
1061 return -1;
1062 else if ((*lhs)->pnum == (*rhs)->pnum)
1063 return 0;
1064 else
1065 return 1;
1066 }
1067
1068 static int
1069 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1070 {
1071 int regnum, num_remote_regs, offset;
1072 struct packet_reg **remote_regs;
1073
1074 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1075 {
1076 struct packet_reg *r = &regs[regnum];
1077
1078 if (register_size (gdbarch, regnum) == 0)
1079 /* Do not try to fetch zero-sized (placeholder) registers. */
1080 r->pnum = -1;
1081 else
1082 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1083
1084 r->regnum = regnum;
1085 }
1086
1087 /* Define the g/G packet format as the contents of each register
1088 with a remote protocol number, in order of ascending protocol
1089 number. */
1090
1091 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1092 for (num_remote_regs = 0, regnum = 0;
1093 regnum < gdbarch_num_regs (gdbarch);
1094 regnum++)
1095 if (regs[regnum].pnum != -1)
1096 remote_regs[num_remote_regs++] = &regs[regnum];
1097
1098 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1099 compare_pnums);
1100
1101 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1102 {
1103 remote_regs[regnum]->in_g_packet = 1;
1104 remote_regs[regnum]->offset = offset;
1105 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1106 }
1107
1108 return offset;
1109 }
1110
1111 /* Given the architecture described by GDBARCH, return the remote
1112 protocol register's number and the register's offset in the g/G
1113 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1114 If the target does not have a mapping for REGNUM, return false,
1115 otherwise, return true. */
1116
1117 int
1118 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1119 int *pnum, int *poffset)
1120 {
1121 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1122
1123 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1124
1125 map_regcache_remote_table (gdbarch, regs.data ());
1126
1127 *pnum = regs[regnum].pnum;
1128 *poffset = regs[regnum].offset;
1129
1130 return *pnum != -1;
1131 }
1132
1133 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1134 {
1135 /* Use the architecture to build a regnum<->pnum table, which will be
1136 1:1 unless a feature set specifies otherwise. */
1137 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1138
1139 /* Record the maximum possible size of the g packet - it may turn out
1140 to be smaller. */
1141 this->sizeof_g_packet
1142 = map_regcache_remote_table (gdbarch, this->regs.get ());
1143
1144 /* Default maximum number of characters in a packet body. Many
1145 remote stubs have a hardwired buffer size of 400 bytes
1146 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1147 as the maximum packet-size to ensure that the packet and an extra
1148 NUL character can always fit in the buffer. This stops GDB
1149 trashing stubs that try to squeeze an extra NUL into what is
1150 already a full buffer (As of 1999-12-04 that was most stubs). */
1151 this->remote_packet_size = 400 - 1;
1152
1153 /* This one is filled in when a ``g'' packet is received. */
1154 this->actual_register_packet_size = 0;
1155
1156 /* Should rsa->sizeof_g_packet needs more space than the
1157 default, adjust the size accordingly. Remember that each byte is
1158 encoded as two characters. 32 is the overhead for the packet
1159 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1160 (``$NN:G...#NN'') is a better guess, the below has been padded a
1161 little. */
1162 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1163 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1164 }
1165
1166 /* Return the current allowed size of a remote packet. This is
1167 inferred from the current architecture, and should be used to
1168 limit the length of outgoing packets. */
1169 static long
1170 get_remote_packet_size (void)
1171 {
1172 struct remote_state *rs = get_remote_state ();
1173 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1174
1175 if (rs->explicit_packet_size)
1176 return rs->explicit_packet_size;
1177
1178 return rsa->remote_packet_size;
1179 }
1180
1181 static struct packet_reg *
1182 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1183 long regnum)
1184 {
1185 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1186 return NULL;
1187 else
1188 {
1189 struct packet_reg *r = &rsa->regs[regnum];
1190
1191 gdb_assert (r->regnum == regnum);
1192 return r;
1193 }
1194 }
1195
1196 static struct packet_reg *
1197 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1198 LONGEST pnum)
1199 {
1200 int i;
1201
1202 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1203 {
1204 struct packet_reg *r = &rsa->regs[i];
1205
1206 if (r->pnum == pnum)
1207 return r;
1208 }
1209 return NULL;
1210 }
1211
1212 static remote_target remote_ops;
1213
1214 static extended_remote_target extended_remote_ops;
1215
1216 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
1217 ``forever'' still use the normal timeout mechanism. This is
1218 currently used by the ASYNC code to guarentee that target reads
1219 during the initial connect always time-out. Once getpkt has been
1220 modified to return a timeout indication and, in turn
1221 remote_wait()/wait_for_inferior() have gained a timeout parameter
1222 this can go away. */
1223 static int wait_forever_enabled_p = 1;
1224
1225 /* Allow the user to specify what sequence to send to the remote
1226 when he requests a program interruption: Although ^C is usually
1227 what remote systems expect (this is the default, here), it is
1228 sometimes preferable to send a break. On other systems such
1229 as the Linux kernel, a break followed by g, which is Magic SysRq g
1230 is required in order to interrupt the execution. */
1231 const char interrupt_sequence_control_c[] = "Ctrl-C";
1232 const char interrupt_sequence_break[] = "BREAK";
1233 const char interrupt_sequence_break_g[] = "BREAK-g";
1234 static const char *const interrupt_sequence_modes[] =
1235 {
1236 interrupt_sequence_control_c,
1237 interrupt_sequence_break,
1238 interrupt_sequence_break_g,
1239 NULL
1240 };
1241 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1242
1243 static void
1244 show_interrupt_sequence (struct ui_file *file, int from_tty,
1245 struct cmd_list_element *c,
1246 const char *value)
1247 {
1248 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1249 fprintf_filtered (file,
1250 _("Send the ASCII ETX character (Ctrl-c) "
1251 "to the remote target to interrupt the "
1252 "execution of the program.\n"));
1253 else if (interrupt_sequence_mode == interrupt_sequence_break)
1254 fprintf_filtered (file,
1255 _("send a break signal to the remote target "
1256 "to interrupt the execution of the program.\n"));
1257 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1258 fprintf_filtered (file,
1259 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1260 "the remote target to interrupt the execution "
1261 "of Linux kernel.\n"));
1262 else
1263 internal_error (__FILE__, __LINE__,
1264 _("Invalid value for interrupt_sequence_mode: %s."),
1265 interrupt_sequence_mode);
1266 }
1267
1268 /* This boolean variable specifies whether interrupt_sequence is sent
1269 to the remote target when gdb connects to it.
1270 This is mostly needed when you debug the Linux kernel: The Linux kernel
1271 expects BREAK g which is Magic SysRq g for connecting gdb. */
1272 static int interrupt_on_connect = 0;
1273
1274 /* This variable is used to implement the "set/show remotebreak" commands.
1275 Since these commands are now deprecated in favor of "set/show remote
1276 interrupt-sequence", it no longer has any effect on the code. */
1277 static int remote_break;
1278
1279 static void
1280 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1281 {
1282 if (remote_break)
1283 interrupt_sequence_mode = interrupt_sequence_break;
1284 else
1285 interrupt_sequence_mode = interrupt_sequence_control_c;
1286 }
1287
1288 static void
1289 show_remotebreak (struct ui_file *file, int from_tty,
1290 struct cmd_list_element *c,
1291 const char *value)
1292 {
1293 }
1294
1295 /* This variable sets the number of bits in an address that are to be
1296 sent in a memory ("M" or "m") packet. Normally, after stripping
1297 leading zeros, the entire address would be sent. This variable
1298 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1299 initial implementation of remote.c restricted the address sent in
1300 memory packets to ``host::sizeof long'' bytes - (typically 32
1301 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1302 address was never sent. Since fixing this bug may cause a break in
1303 some remote targets this variable is principly provided to
1304 facilitate backward compatibility. */
1305
1306 static unsigned int remote_address_size;
1307
1308 \f
1309 /* User configurable variables for the number of characters in a
1310 memory read/write packet. MIN (rsa->remote_packet_size,
1311 rsa->sizeof_g_packet) is the default. Some targets need smaller
1312 values (fifo overruns, et.al.) and some users need larger values
1313 (speed up transfers). The variables ``preferred_*'' (the user
1314 request), ``current_*'' (what was actually set) and ``forced_*''
1315 (Positive - a soft limit, negative - a hard limit). */
1316
1317 struct memory_packet_config
1318 {
1319 const char *name;
1320 long size;
1321 int fixed_p;
1322 };
1323
1324 /* The default max memory-write-packet-size. The 16k is historical.
1325 (It came from older GDB's using alloca for buffers and the
1326 knowledge (folklore?) that some hosts don't cope very well with
1327 large alloca calls.) */
1328 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1329
1330 /* The minimum remote packet size for memory transfers. Ensures we
1331 can write at least one byte. */
1332 #define MIN_MEMORY_PACKET_SIZE 20
1333
1334 /* Compute the current size of a read/write packet. Since this makes
1335 use of ``actual_register_packet_size'' the computation is dynamic. */
1336
1337 static long
1338 get_memory_packet_size (struct memory_packet_config *config)
1339 {
1340 struct remote_state *rs = get_remote_state ();
1341 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1342
1343 long what_they_get;
1344 if (config->fixed_p)
1345 {
1346 if (config->size <= 0)
1347 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1348 else
1349 what_they_get = config->size;
1350 }
1351 else
1352 {
1353 what_they_get = get_remote_packet_size ();
1354 /* Limit the packet to the size specified by the user. */
1355 if (config->size > 0
1356 && what_they_get > config->size)
1357 what_they_get = config->size;
1358
1359 /* Limit it to the size of the targets ``g'' response unless we have
1360 permission from the stub to use a larger packet size. */
1361 if (rs->explicit_packet_size == 0
1362 && rsa->actual_register_packet_size > 0
1363 && what_they_get > rsa->actual_register_packet_size)
1364 what_they_get = rsa->actual_register_packet_size;
1365 }
1366 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1367 what_they_get = MIN_MEMORY_PACKET_SIZE;
1368
1369 /* Make sure there is room in the global buffer for this packet
1370 (including its trailing NUL byte). */
1371 if (rs->buf_size < what_they_get + 1)
1372 {
1373 rs->buf_size = 2 * what_they_get;
1374 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1375 }
1376
1377 return what_they_get;
1378 }
1379
1380 /* Update the size of a read/write packet. If they user wants
1381 something really big then do a sanity check. */
1382
1383 static void
1384 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1385 {
1386 int fixed_p = config->fixed_p;
1387 long size = config->size;
1388
1389 if (args == NULL)
1390 error (_("Argument required (integer, `fixed' or `limited')."));
1391 else if (strcmp (args, "hard") == 0
1392 || strcmp (args, "fixed") == 0)
1393 fixed_p = 1;
1394 else if (strcmp (args, "soft") == 0
1395 || strcmp (args, "limit") == 0)
1396 fixed_p = 0;
1397 else
1398 {
1399 char *end;
1400
1401 size = strtoul (args, &end, 0);
1402 if (args == end)
1403 error (_("Invalid %s (bad syntax)."), config->name);
1404
1405 /* Instead of explicitly capping the size of a packet to or
1406 disallowing it, the user is allowed to set the size to
1407 something arbitrarily large. */
1408 }
1409
1410 /* So that the query shows the correct value. */
1411 if (size <= 0)
1412 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1413
1414 /* Extra checks? */
1415 if (fixed_p && !config->fixed_p)
1416 {
1417 if (! query (_("The target may not be able to correctly handle a %s\n"
1418 "of %ld bytes. Change the packet size? "),
1419 config->name, size))
1420 error (_("Packet size not changed."));
1421 }
1422 /* Update the config. */
1423 config->fixed_p = fixed_p;
1424 config->size = size;
1425 }
1426
1427 static void
1428 show_memory_packet_size (struct memory_packet_config *config)
1429 {
1430 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1431 if (config->fixed_p)
1432 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1433 get_memory_packet_size (config));
1434 else
1435 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1436 get_memory_packet_size (config));
1437 }
1438
1439 static struct memory_packet_config memory_write_packet_config =
1440 {
1441 "memory-write-packet-size",
1442 };
1443
1444 static void
1445 set_memory_write_packet_size (const char *args, int from_tty)
1446 {
1447 set_memory_packet_size (args, &memory_write_packet_config);
1448 }
1449
1450 static void
1451 show_memory_write_packet_size (const char *args, int from_tty)
1452 {
1453 show_memory_packet_size (&memory_write_packet_config);
1454 }
1455
1456 static long
1457 get_memory_write_packet_size (void)
1458 {
1459 return get_memory_packet_size (&memory_write_packet_config);
1460 }
1461
1462 static struct memory_packet_config memory_read_packet_config =
1463 {
1464 "memory-read-packet-size",
1465 };
1466
1467 static void
1468 set_memory_read_packet_size (const char *args, int from_tty)
1469 {
1470 set_memory_packet_size (args, &memory_read_packet_config);
1471 }
1472
1473 static void
1474 show_memory_read_packet_size (const char *args, int from_tty)
1475 {
1476 show_memory_packet_size (&memory_read_packet_config);
1477 }
1478
1479 static long
1480 get_memory_read_packet_size (void)
1481 {
1482 long size = get_memory_packet_size (&memory_read_packet_config);
1483
1484 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1485 extra buffer size argument before the memory read size can be
1486 increased beyond this. */
1487 if (size > get_remote_packet_size ())
1488 size = get_remote_packet_size ();
1489 return size;
1490 }
1491
1492 \f
1493 /* Generic configuration support for packets the stub optionally
1494 supports. Allows the user to specify the use of the packet as well
1495 as allowing GDB to auto-detect support in the remote stub. */
1496
1497 enum packet_support
1498 {
1499 PACKET_SUPPORT_UNKNOWN = 0,
1500 PACKET_ENABLE,
1501 PACKET_DISABLE
1502 };
1503
1504 struct packet_config
1505 {
1506 const char *name;
1507 const char *title;
1508
1509 /* If auto, GDB auto-detects support for this packet or feature,
1510 either through qSupported, or by trying the packet and looking
1511 at the response. If true, GDB assumes the target supports this
1512 packet. If false, the packet is disabled. Configs that don't
1513 have an associated command always have this set to auto. */
1514 enum auto_boolean detect;
1515
1516 /* Does the target support this packet? */
1517 enum packet_support support;
1518 };
1519
1520 /* Analyze a packet's return value and update the packet config
1521 accordingly. */
1522
1523 enum packet_result
1524 {
1525 PACKET_ERROR,
1526 PACKET_OK,
1527 PACKET_UNKNOWN
1528 };
1529
1530 static enum packet_support packet_config_support (struct packet_config *config);
1531 static enum packet_support packet_support (int packet);
1532
1533 static void
1534 show_packet_config_cmd (struct packet_config *config)
1535 {
1536 const char *support = "internal-error";
1537
1538 switch (packet_config_support (config))
1539 {
1540 case PACKET_ENABLE:
1541 support = "enabled";
1542 break;
1543 case PACKET_DISABLE:
1544 support = "disabled";
1545 break;
1546 case PACKET_SUPPORT_UNKNOWN:
1547 support = "unknown";
1548 break;
1549 }
1550 switch (config->detect)
1551 {
1552 case AUTO_BOOLEAN_AUTO:
1553 printf_filtered (_("Support for the `%s' packet "
1554 "is auto-detected, currently %s.\n"),
1555 config->name, support);
1556 break;
1557 case AUTO_BOOLEAN_TRUE:
1558 case AUTO_BOOLEAN_FALSE:
1559 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1560 config->name, support);
1561 break;
1562 }
1563 }
1564
1565 static void
1566 add_packet_config_cmd (struct packet_config *config, const char *name,
1567 const char *title, int legacy)
1568 {
1569 char *set_doc;
1570 char *show_doc;
1571 char *cmd_name;
1572
1573 config->name = name;
1574 config->title = title;
1575 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1576 name, title);
1577 show_doc = xstrprintf ("Show current use of remote "
1578 "protocol `%s' (%s) packet",
1579 name, title);
1580 /* set/show TITLE-packet {auto,on,off} */
1581 cmd_name = xstrprintf ("%s-packet", title);
1582 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1583 &config->detect, set_doc,
1584 show_doc, NULL, /* help_doc */
1585 NULL,
1586 show_remote_protocol_packet_cmd,
1587 &remote_set_cmdlist, &remote_show_cmdlist);
1588 /* The command code copies the documentation strings. */
1589 xfree (set_doc);
1590 xfree (show_doc);
1591 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1592 if (legacy)
1593 {
1594 char *legacy_name;
1595
1596 legacy_name = xstrprintf ("%s-packet", name);
1597 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1598 &remote_set_cmdlist);
1599 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1600 &remote_show_cmdlist);
1601 }
1602 }
1603
1604 static enum packet_result
1605 packet_check_result (const char *buf)
1606 {
1607 if (buf[0] != '\0')
1608 {
1609 /* The stub recognized the packet request. Check that the
1610 operation succeeded. */
1611 if (buf[0] == 'E'
1612 && isxdigit (buf[1]) && isxdigit (buf[2])
1613 && buf[3] == '\0')
1614 /* "Enn" - definitly an error. */
1615 return PACKET_ERROR;
1616
1617 /* Always treat "E." as an error. This will be used for
1618 more verbose error messages, such as E.memtypes. */
1619 if (buf[0] == 'E' && buf[1] == '.')
1620 return PACKET_ERROR;
1621
1622 /* The packet may or may not be OK. Just assume it is. */
1623 return PACKET_OK;
1624 }
1625 else
1626 /* The stub does not support the packet. */
1627 return PACKET_UNKNOWN;
1628 }
1629
1630 static enum packet_result
1631 packet_ok (const char *buf, struct packet_config *config)
1632 {
1633 enum packet_result result;
1634
1635 if (config->detect != AUTO_BOOLEAN_TRUE
1636 && config->support == PACKET_DISABLE)
1637 internal_error (__FILE__, __LINE__,
1638 _("packet_ok: attempt to use a disabled packet"));
1639
1640 result = packet_check_result (buf);
1641 switch (result)
1642 {
1643 case PACKET_OK:
1644 case PACKET_ERROR:
1645 /* The stub recognized the packet request. */
1646 if (config->support == PACKET_SUPPORT_UNKNOWN)
1647 {
1648 if (remote_debug)
1649 fprintf_unfiltered (gdb_stdlog,
1650 "Packet %s (%s) is supported\n",
1651 config->name, config->title);
1652 config->support = PACKET_ENABLE;
1653 }
1654 break;
1655 case PACKET_UNKNOWN:
1656 /* The stub does not support the packet. */
1657 if (config->detect == AUTO_BOOLEAN_AUTO
1658 && config->support == PACKET_ENABLE)
1659 {
1660 /* If the stub previously indicated that the packet was
1661 supported then there is a protocol error. */
1662 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1663 config->name, config->title);
1664 }
1665 else if (config->detect == AUTO_BOOLEAN_TRUE)
1666 {
1667 /* The user set it wrong. */
1668 error (_("Enabled packet %s (%s) not recognized by stub"),
1669 config->name, config->title);
1670 }
1671
1672 if (remote_debug)
1673 fprintf_unfiltered (gdb_stdlog,
1674 "Packet %s (%s) is NOT supported\n",
1675 config->name, config->title);
1676 config->support = PACKET_DISABLE;
1677 break;
1678 }
1679
1680 return result;
1681 }
1682
1683 enum {
1684 PACKET_vCont = 0,
1685 PACKET_X,
1686 PACKET_qSymbol,
1687 PACKET_P,
1688 PACKET_p,
1689 PACKET_Z0,
1690 PACKET_Z1,
1691 PACKET_Z2,
1692 PACKET_Z3,
1693 PACKET_Z4,
1694 PACKET_vFile_setfs,
1695 PACKET_vFile_open,
1696 PACKET_vFile_pread,
1697 PACKET_vFile_pwrite,
1698 PACKET_vFile_close,
1699 PACKET_vFile_unlink,
1700 PACKET_vFile_readlink,
1701 PACKET_vFile_fstat,
1702 PACKET_qXfer_auxv,
1703 PACKET_qXfer_features,
1704 PACKET_qXfer_exec_file,
1705 PACKET_qXfer_libraries,
1706 PACKET_qXfer_libraries_svr4,
1707 PACKET_qXfer_memory_map,
1708 PACKET_qXfer_spu_read,
1709 PACKET_qXfer_spu_write,
1710 PACKET_qXfer_osdata,
1711 PACKET_qXfer_threads,
1712 PACKET_qXfer_statictrace_read,
1713 PACKET_qXfer_traceframe_info,
1714 PACKET_qXfer_uib,
1715 PACKET_qGetTIBAddr,
1716 PACKET_qGetTLSAddr,
1717 PACKET_qSupported,
1718 PACKET_qTStatus,
1719 PACKET_QPassSignals,
1720 PACKET_QCatchSyscalls,
1721 PACKET_QProgramSignals,
1722 PACKET_QSetWorkingDir,
1723 PACKET_QStartupWithShell,
1724 PACKET_QEnvironmentHexEncoded,
1725 PACKET_QEnvironmentReset,
1726 PACKET_QEnvironmentUnset,
1727 PACKET_qCRC,
1728 PACKET_qSearch_memory,
1729 PACKET_vAttach,
1730 PACKET_vRun,
1731 PACKET_QStartNoAckMode,
1732 PACKET_vKill,
1733 PACKET_qXfer_siginfo_read,
1734 PACKET_qXfer_siginfo_write,
1735 PACKET_qAttached,
1736
1737 /* Support for conditional tracepoints. */
1738 PACKET_ConditionalTracepoints,
1739
1740 /* Support for target-side breakpoint conditions. */
1741 PACKET_ConditionalBreakpoints,
1742
1743 /* Support for target-side breakpoint commands. */
1744 PACKET_BreakpointCommands,
1745
1746 /* Support for fast tracepoints. */
1747 PACKET_FastTracepoints,
1748
1749 /* Support for static tracepoints. */
1750 PACKET_StaticTracepoints,
1751
1752 /* Support for installing tracepoints while a trace experiment is
1753 running. */
1754 PACKET_InstallInTrace,
1755
1756 PACKET_bc,
1757 PACKET_bs,
1758 PACKET_TracepointSource,
1759 PACKET_QAllow,
1760 PACKET_qXfer_fdpic,
1761 PACKET_QDisableRandomization,
1762 PACKET_QAgent,
1763 PACKET_QTBuffer_size,
1764 PACKET_Qbtrace_off,
1765 PACKET_Qbtrace_bts,
1766 PACKET_Qbtrace_pt,
1767 PACKET_qXfer_btrace,
1768
1769 /* Support for the QNonStop packet. */
1770 PACKET_QNonStop,
1771
1772 /* Support for the QThreadEvents packet. */
1773 PACKET_QThreadEvents,
1774
1775 /* Support for multi-process extensions. */
1776 PACKET_multiprocess_feature,
1777
1778 /* Support for enabling and disabling tracepoints while a trace
1779 experiment is running. */
1780 PACKET_EnableDisableTracepoints_feature,
1781
1782 /* Support for collecting strings using the tracenz bytecode. */
1783 PACKET_tracenz_feature,
1784
1785 /* Support for continuing to run a trace experiment while GDB is
1786 disconnected. */
1787 PACKET_DisconnectedTracing_feature,
1788
1789 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1790 PACKET_augmented_libraries_svr4_read_feature,
1791
1792 /* Support for the qXfer:btrace-conf:read packet. */
1793 PACKET_qXfer_btrace_conf,
1794
1795 /* Support for the Qbtrace-conf:bts:size packet. */
1796 PACKET_Qbtrace_conf_bts_size,
1797
1798 /* Support for swbreak+ feature. */
1799 PACKET_swbreak_feature,
1800
1801 /* Support for hwbreak+ feature. */
1802 PACKET_hwbreak_feature,
1803
1804 /* Support for fork events. */
1805 PACKET_fork_event_feature,
1806
1807 /* Support for vfork events. */
1808 PACKET_vfork_event_feature,
1809
1810 /* Support for the Qbtrace-conf:pt:size packet. */
1811 PACKET_Qbtrace_conf_pt_size,
1812
1813 /* Support for exec events. */
1814 PACKET_exec_event_feature,
1815
1816 /* Support for query supported vCont actions. */
1817 PACKET_vContSupported,
1818
1819 /* Support remote CTRL-C. */
1820 PACKET_vCtrlC,
1821
1822 /* Support TARGET_WAITKIND_NO_RESUMED. */
1823 PACKET_no_resumed,
1824
1825 PACKET_MAX
1826 };
1827
1828 static struct packet_config remote_protocol_packets[PACKET_MAX];
1829
1830 /* Returns the packet's corresponding "set remote foo-packet" command
1831 state. See struct packet_config for more details. */
1832
1833 static enum auto_boolean
1834 packet_set_cmd_state (int packet)
1835 {
1836 return remote_protocol_packets[packet].detect;
1837 }
1838
1839 /* Returns whether a given packet or feature is supported. This takes
1840 into account the state of the corresponding "set remote foo-packet"
1841 command, which may be used to bypass auto-detection. */
1842
1843 static enum packet_support
1844 packet_config_support (struct packet_config *config)
1845 {
1846 switch (config->detect)
1847 {
1848 case AUTO_BOOLEAN_TRUE:
1849 return PACKET_ENABLE;
1850 case AUTO_BOOLEAN_FALSE:
1851 return PACKET_DISABLE;
1852 case AUTO_BOOLEAN_AUTO:
1853 return config->support;
1854 default:
1855 gdb_assert_not_reached (_("bad switch"));
1856 }
1857 }
1858
1859 /* Same as packet_config_support, but takes the packet's enum value as
1860 argument. */
1861
1862 static enum packet_support
1863 packet_support (int packet)
1864 {
1865 struct packet_config *config = &remote_protocol_packets[packet];
1866
1867 return packet_config_support (config);
1868 }
1869
1870 static void
1871 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1872 struct cmd_list_element *c,
1873 const char *value)
1874 {
1875 struct packet_config *packet;
1876
1877 for (packet = remote_protocol_packets;
1878 packet < &remote_protocol_packets[PACKET_MAX];
1879 packet++)
1880 {
1881 if (&packet->detect == c->var)
1882 {
1883 show_packet_config_cmd (packet);
1884 return;
1885 }
1886 }
1887 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1888 c->name);
1889 }
1890
1891 /* Should we try one of the 'Z' requests? */
1892
1893 enum Z_packet_type
1894 {
1895 Z_PACKET_SOFTWARE_BP,
1896 Z_PACKET_HARDWARE_BP,
1897 Z_PACKET_WRITE_WP,
1898 Z_PACKET_READ_WP,
1899 Z_PACKET_ACCESS_WP,
1900 NR_Z_PACKET_TYPES
1901 };
1902
1903 /* For compatibility with older distributions. Provide a ``set remote
1904 Z-packet ...'' command that updates all the Z packet types. */
1905
1906 static enum auto_boolean remote_Z_packet_detect;
1907
1908 static void
1909 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
1910 struct cmd_list_element *c)
1911 {
1912 int i;
1913
1914 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1915 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1916 }
1917
1918 static void
1919 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1920 struct cmd_list_element *c,
1921 const char *value)
1922 {
1923 int i;
1924
1925 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1926 {
1927 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1928 }
1929 }
1930
1931 /* Returns true if the multi-process extensions are in effect. */
1932
1933 static int
1934 remote_multi_process_p (struct remote_state *rs)
1935 {
1936 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1937 }
1938
1939 /* Returns true if fork events are supported. */
1940
1941 static int
1942 remote_fork_event_p (struct remote_state *rs)
1943 {
1944 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1945 }
1946
1947 /* Returns true if vfork events are supported. */
1948
1949 static int
1950 remote_vfork_event_p (struct remote_state *rs)
1951 {
1952 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1953 }
1954
1955 /* Returns true if exec events are supported. */
1956
1957 static int
1958 remote_exec_event_p (struct remote_state *rs)
1959 {
1960 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1961 }
1962
1963 /* Insert fork catchpoint target routine. If fork events are enabled
1964 then return success, nothing more to do. */
1965
1966 int
1967 remote_target::insert_fork_catchpoint (int pid)
1968 {
1969 struct remote_state *rs = get_remote_state ();
1970
1971 return !remote_fork_event_p (rs);
1972 }
1973
1974 /* Remove fork catchpoint target routine. Nothing to do, just
1975 return success. */
1976
1977 int
1978 remote_target::remove_fork_catchpoint (int pid)
1979 {
1980 return 0;
1981 }
1982
1983 /* Insert vfork catchpoint target routine. If vfork events are enabled
1984 then return success, nothing more to do. */
1985
1986 int
1987 remote_target::insert_vfork_catchpoint (int pid)
1988 {
1989 struct remote_state *rs = get_remote_state ();
1990
1991 return !remote_vfork_event_p (rs);
1992 }
1993
1994 /* Remove vfork catchpoint target routine. Nothing to do, just
1995 return success. */
1996
1997 int
1998 remote_target::remove_vfork_catchpoint (int pid)
1999 {
2000 return 0;
2001 }
2002
2003 /* Insert exec catchpoint target routine. If exec events are
2004 enabled, just return success. */
2005
2006 int
2007 remote_target::insert_exec_catchpoint (int pid)
2008 {
2009 struct remote_state *rs = get_remote_state ();
2010
2011 return !remote_exec_event_p (rs);
2012 }
2013
2014 /* Remove exec catchpoint target routine. Nothing to do, just
2015 return success. */
2016
2017 int
2018 remote_target::remove_exec_catchpoint (int pid)
2019 {
2020 return 0;
2021 }
2022
2023 \f
2024 /* Asynchronous signal handle registered as event loop source for
2025 when we have pending events ready to be passed to the core. */
2026
2027 static struct async_event_handler *remote_async_inferior_event_token;
2028
2029 \f
2030
2031 static ptid_t magic_null_ptid;
2032 static ptid_t not_sent_ptid;
2033 static ptid_t any_thread_ptid;
2034
2035 /* Find out if the stub attached to PID (and hence GDB should offer to
2036 detach instead of killing it when bailing out). */
2037
2038 static int
2039 remote_query_attached (int pid)
2040 {
2041 struct remote_state *rs = get_remote_state ();
2042 size_t size = get_remote_packet_size ();
2043
2044 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2045 return 0;
2046
2047 if (remote_multi_process_p (rs))
2048 xsnprintf (rs->buf, size, "qAttached:%x", pid);
2049 else
2050 xsnprintf (rs->buf, size, "qAttached");
2051
2052 putpkt (rs->buf);
2053 getpkt (&rs->buf, &rs->buf_size, 0);
2054
2055 switch (packet_ok (rs->buf,
2056 &remote_protocol_packets[PACKET_qAttached]))
2057 {
2058 case PACKET_OK:
2059 if (strcmp (rs->buf, "1") == 0)
2060 return 1;
2061 break;
2062 case PACKET_ERROR:
2063 warning (_("Remote failure reply: %s"), rs->buf);
2064 break;
2065 case PACKET_UNKNOWN:
2066 break;
2067 }
2068
2069 return 0;
2070 }
2071
2072 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2073 has been invented by GDB, instead of reported by the target. Since
2074 we can be connected to a remote system before before knowing about
2075 any inferior, mark the target with execution when we find the first
2076 inferior. If ATTACHED is 1, then we had just attached to this
2077 inferior. If it is 0, then we just created this inferior. If it
2078 is -1, then try querying the remote stub to find out if it had
2079 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2080 attempt to open this inferior's executable as the main executable
2081 if no main executable is open already. */
2082
2083 static struct inferior *
2084 remote_add_inferior (int fake_pid_p, int pid, int attached,
2085 int try_open_exec)
2086 {
2087 struct inferior *inf;
2088
2089 /* Check whether this process we're learning about is to be
2090 considered attached, or if is to be considered to have been
2091 spawned by the stub. */
2092 if (attached == -1)
2093 attached = remote_query_attached (pid);
2094
2095 if (gdbarch_has_global_solist (target_gdbarch ()))
2096 {
2097 /* If the target shares code across all inferiors, then every
2098 attach adds a new inferior. */
2099 inf = add_inferior (pid);
2100
2101 /* ... and every inferior is bound to the same program space.
2102 However, each inferior may still have its own address
2103 space. */
2104 inf->aspace = maybe_new_address_space ();
2105 inf->pspace = current_program_space;
2106 }
2107 else
2108 {
2109 /* In the traditional debugging scenario, there's a 1-1 match
2110 between program/address spaces. We simply bind the inferior
2111 to the program space's address space. */
2112 inf = current_inferior ();
2113 inferior_appeared (inf, pid);
2114 }
2115
2116 inf->attach_flag = attached;
2117 inf->fake_pid_p = fake_pid_p;
2118
2119 /* If no main executable is currently open then attempt to
2120 open the file that was executed to create this inferior. */
2121 if (try_open_exec && get_exec_file (0) == NULL)
2122 exec_file_locate_attach (pid, 0, 1);
2123
2124 return inf;
2125 }
2126
2127 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2128
2129 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2130 according to RUNNING. */
2131
2132 static void
2133 remote_add_thread (ptid_t ptid, int running, int executing)
2134 {
2135 struct remote_state *rs = get_remote_state ();
2136 struct thread_info *thread;
2137
2138 /* GDB historically didn't pull threads in the initial connection
2139 setup. If the remote target doesn't even have a concept of
2140 threads (e.g., a bare-metal target), even if internally we
2141 consider that a single-threaded target, mentioning a new thread
2142 might be confusing to the user. Be silent then, preserving the
2143 age old behavior. */
2144 if (rs->starting_up)
2145 thread = add_thread_silent (ptid);
2146 else
2147 thread = add_thread (ptid);
2148
2149 get_remote_thread_info (thread)->vcont_resumed = executing;
2150 set_executing (ptid, executing);
2151 set_running (ptid, running);
2152 }
2153
2154 /* Come here when we learn about a thread id from the remote target.
2155 It may be the first time we hear about such thread, so take the
2156 opportunity to add it to GDB's thread list. In case this is the
2157 first time we're noticing its corresponding inferior, add it to
2158 GDB's inferior list as well. EXECUTING indicates whether the
2159 thread is (internally) executing or stopped. */
2160
2161 static void
2162 remote_notice_new_inferior (ptid_t currthread, int executing)
2163 {
2164 /* In non-stop mode, we assume new found threads are (externally)
2165 running until proven otherwise with a stop reply. In all-stop,
2166 we can only get here if all threads are stopped. */
2167 int running = target_is_non_stop_p () ? 1 : 0;
2168
2169 /* If this is a new thread, add it to GDB's thread list.
2170 If we leave it up to WFI to do this, bad things will happen. */
2171
2172 if (in_thread_list (currthread) && is_exited (currthread))
2173 {
2174 /* We're seeing an event on a thread id we knew had exited.
2175 This has to be a new thread reusing the old id. Add it. */
2176 remote_add_thread (currthread, running, executing);
2177 return;
2178 }
2179
2180 if (!in_thread_list (currthread))
2181 {
2182 struct inferior *inf = NULL;
2183 int pid = ptid_get_pid (currthread);
2184
2185 if (ptid_is_pid (inferior_ptid)
2186 && pid == ptid_get_pid (inferior_ptid))
2187 {
2188 /* inferior_ptid has no thread member yet. This can happen
2189 with the vAttach -> remote_wait,"TAAthread:" path if the
2190 stub doesn't support qC. This is the first stop reported
2191 after an attach, so this is the main thread. Update the
2192 ptid in the thread list. */
2193 if (in_thread_list (pid_to_ptid (pid)))
2194 thread_change_ptid (inferior_ptid, currthread);
2195 else
2196 {
2197 remote_add_thread (currthread, running, executing);
2198 inferior_ptid = currthread;
2199 }
2200 return;
2201 }
2202
2203 if (ptid_equal (magic_null_ptid, inferior_ptid))
2204 {
2205 /* inferior_ptid is not set yet. This can happen with the
2206 vRun -> remote_wait,"TAAthread:" path if the stub
2207 doesn't support qC. This is the first stop reported
2208 after an attach, so this is the main thread. Update the
2209 ptid in the thread list. */
2210 thread_change_ptid (inferior_ptid, currthread);
2211 return;
2212 }
2213
2214 /* When connecting to a target remote, or to a target
2215 extended-remote which already was debugging an inferior, we
2216 may not know about it yet. Add it before adding its child
2217 thread, so notifications are emitted in a sensible order. */
2218 if (!in_inferior_list (ptid_get_pid (currthread)))
2219 {
2220 struct remote_state *rs = get_remote_state ();
2221 int fake_pid_p = !remote_multi_process_p (rs);
2222
2223 inf = remote_add_inferior (fake_pid_p,
2224 ptid_get_pid (currthread), -1, 1);
2225 }
2226
2227 /* This is really a new thread. Add it. */
2228 remote_add_thread (currthread, running, executing);
2229
2230 /* If we found a new inferior, let the common code do whatever
2231 it needs to with it (e.g., read shared libraries, insert
2232 breakpoints), unless we're just setting up an all-stop
2233 connection. */
2234 if (inf != NULL)
2235 {
2236 struct remote_state *rs = get_remote_state ();
2237
2238 if (!rs->starting_up)
2239 notice_new_inferior (currthread, executing, 0);
2240 }
2241 }
2242 }
2243
2244 /* Return THREAD's private thread data, creating it if necessary. */
2245
2246 static remote_thread_info *
2247 get_remote_thread_info (thread_info *thread)
2248 {
2249 gdb_assert (thread != NULL);
2250
2251 if (thread->priv == NULL)
2252 thread->priv.reset (new remote_thread_info);
2253
2254 return static_cast<remote_thread_info *> (thread->priv.get ());
2255 }
2256
2257 /* Return PTID's private thread data, creating it if necessary. */
2258
2259 static remote_thread_info *
2260 get_remote_thread_info (ptid_t ptid)
2261 {
2262 struct thread_info *info = find_thread_ptid (ptid);
2263
2264 return get_remote_thread_info (info);
2265 }
2266
2267 /* Call this function as a result of
2268 1) A halt indication (T packet) containing a thread id
2269 2) A direct query of currthread
2270 3) Successful execution of set thread */
2271
2272 static void
2273 record_currthread (struct remote_state *rs, ptid_t currthread)
2274 {
2275 rs->general_thread = currthread;
2276 }
2277
2278 /* If 'QPassSignals' is supported, tell the remote stub what signals
2279 it can simply pass through to the inferior without reporting. */
2280
2281 void
2282 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2283 {
2284 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2285 {
2286 char *pass_packet, *p;
2287 int count = 0, i;
2288 struct remote_state *rs = get_remote_state ();
2289
2290 gdb_assert (numsigs < 256);
2291 for (i = 0; i < numsigs; i++)
2292 {
2293 if (pass_signals[i])
2294 count++;
2295 }
2296 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2297 strcpy (pass_packet, "QPassSignals:");
2298 p = pass_packet + strlen (pass_packet);
2299 for (i = 0; i < numsigs; i++)
2300 {
2301 if (pass_signals[i])
2302 {
2303 if (i >= 16)
2304 *p++ = tohex (i >> 4);
2305 *p++ = tohex (i & 15);
2306 if (count)
2307 *p++ = ';';
2308 else
2309 break;
2310 count--;
2311 }
2312 }
2313 *p = 0;
2314 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2315 {
2316 putpkt (pass_packet);
2317 getpkt (&rs->buf, &rs->buf_size, 0);
2318 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2319 if (rs->last_pass_packet)
2320 xfree (rs->last_pass_packet);
2321 rs->last_pass_packet = pass_packet;
2322 }
2323 else
2324 xfree (pass_packet);
2325 }
2326 }
2327
2328 /* If 'QCatchSyscalls' is supported, tell the remote stub
2329 to report syscalls to GDB. */
2330
2331 int
2332 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2333 gdb::array_view<const int> syscall_counts)
2334 {
2335 const char *catch_packet;
2336 enum packet_result result;
2337 int n_sysno = 0;
2338
2339 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2340 {
2341 /* Not supported. */
2342 return 1;
2343 }
2344
2345 if (needed && any_count == 0)
2346 {
2347 /* Count how many syscalls are to be caught. */
2348 for (size_t i = 0; i < syscall_counts.size (); i++)
2349 {
2350 if (syscall_counts[i] != 0)
2351 n_sysno++;
2352 }
2353 }
2354
2355 if (remote_debug)
2356 {
2357 fprintf_unfiltered (gdb_stdlog,
2358 "remote_set_syscall_catchpoint "
2359 "pid %d needed %d any_count %d n_sysno %d\n",
2360 pid, needed, any_count, n_sysno);
2361 }
2362
2363 std::string built_packet;
2364 if (needed)
2365 {
2366 /* Prepare a packet with the sysno list, assuming max 8+1
2367 characters for a sysno. If the resulting packet size is too
2368 big, fallback on the non-selective packet. */
2369 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2370 built_packet.reserve (maxpktsz);
2371 built_packet = "QCatchSyscalls:1";
2372 if (any_count == 0)
2373 {
2374 /* Add in each syscall to be caught. */
2375 for (size_t i = 0; i < syscall_counts.size (); i++)
2376 {
2377 if (syscall_counts[i] != 0)
2378 string_appendf (built_packet, ";%zx", i);
2379 }
2380 }
2381 if (built_packet.size () > get_remote_packet_size ())
2382 {
2383 /* catch_packet too big. Fallback to less efficient
2384 non selective mode, with GDB doing the filtering. */
2385 catch_packet = "QCatchSyscalls:1";
2386 }
2387 else
2388 catch_packet = built_packet.c_str ();
2389 }
2390 else
2391 catch_packet = "QCatchSyscalls:0";
2392
2393 struct remote_state *rs = get_remote_state ();
2394
2395 putpkt (catch_packet);
2396 getpkt (&rs->buf, &rs->buf_size, 0);
2397 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2398 if (result == PACKET_OK)
2399 return 0;
2400 else
2401 return -1;
2402 }
2403
2404 /* If 'QProgramSignals' is supported, tell the remote stub what
2405 signals it should pass through to the inferior when detaching. */
2406
2407 void
2408 remote_target::program_signals (int numsigs, unsigned char *signals)
2409 {
2410 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2411 {
2412 char *packet, *p;
2413 int count = 0, i;
2414 struct remote_state *rs = get_remote_state ();
2415
2416 gdb_assert (numsigs < 256);
2417 for (i = 0; i < numsigs; i++)
2418 {
2419 if (signals[i])
2420 count++;
2421 }
2422 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2423 strcpy (packet, "QProgramSignals:");
2424 p = packet + strlen (packet);
2425 for (i = 0; i < numsigs; i++)
2426 {
2427 if (signal_pass_state (i))
2428 {
2429 if (i >= 16)
2430 *p++ = tohex (i >> 4);
2431 *p++ = tohex (i & 15);
2432 if (count)
2433 *p++ = ';';
2434 else
2435 break;
2436 count--;
2437 }
2438 }
2439 *p = 0;
2440 if (!rs->last_program_signals_packet
2441 || strcmp (rs->last_program_signals_packet, packet) != 0)
2442 {
2443 putpkt (packet);
2444 getpkt (&rs->buf, &rs->buf_size, 0);
2445 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2446 xfree (rs->last_program_signals_packet);
2447 rs->last_program_signals_packet = packet;
2448 }
2449 else
2450 xfree (packet);
2451 }
2452 }
2453
2454 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2455 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2456 thread. If GEN is set, set the general thread, if not, then set
2457 the step/continue thread. */
2458 static void
2459 set_thread (ptid_t ptid, int gen)
2460 {
2461 struct remote_state *rs = get_remote_state ();
2462 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2463 char *buf = rs->buf;
2464 char *endbuf = rs->buf + get_remote_packet_size ();
2465
2466 if (ptid_equal (state, ptid))
2467 return;
2468
2469 *buf++ = 'H';
2470 *buf++ = gen ? 'g' : 'c';
2471 if (ptid_equal (ptid, magic_null_ptid))
2472 xsnprintf (buf, endbuf - buf, "0");
2473 else if (ptid_equal (ptid, any_thread_ptid))
2474 xsnprintf (buf, endbuf - buf, "0");
2475 else if (ptid_equal (ptid, minus_one_ptid))
2476 xsnprintf (buf, endbuf - buf, "-1");
2477 else
2478 write_ptid (buf, endbuf, ptid);
2479 putpkt (rs->buf);
2480 getpkt (&rs->buf, &rs->buf_size, 0);
2481 if (gen)
2482 rs->general_thread = ptid;
2483 else
2484 rs->continue_thread = ptid;
2485 }
2486
2487 static void
2488 set_general_thread (ptid_t ptid)
2489 {
2490 set_thread (ptid, 1);
2491 }
2492
2493 static void
2494 set_continue_thread (ptid_t ptid)
2495 {
2496 set_thread (ptid, 0);
2497 }
2498
2499 /* Change the remote current process. Which thread within the process
2500 ends up selected isn't important, as long as it is the same process
2501 as what INFERIOR_PTID points to.
2502
2503 This comes from that fact that there is no explicit notion of
2504 "selected process" in the protocol. The selected process for
2505 general operations is the process the selected general thread
2506 belongs to. */
2507
2508 static void
2509 set_general_process (void)
2510 {
2511 struct remote_state *rs = get_remote_state ();
2512
2513 /* If the remote can't handle multiple processes, don't bother. */
2514 if (!remote_multi_process_p (rs))
2515 return;
2516
2517 /* We only need to change the remote current thread if it's pointing
2518 at some other process. */
2519 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2520 set_general_thread (inferior_ptid);
2521 }
2522
2523 \f
2524 /* Return nonzero if this is the main thread that we made up ourselves
2525 to model non-threaded targets as single-threaded. */
2526
2527 static int
2528 remote_thread_always_alive (ptid_t ptid)
2529 {
2530 if (ptid_equal (ptid, magic_null_ptid))
2531 /* The main thread is always alive. */
2532 return 1;
2533
2534 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2535 /* The main thread is always alive. This can happen after a
2536 vAttach, if the remote side doesn't support
2537 multi-threading. */
2538 return 1;
2539
2540 return 0;
2541 }
2542
2543 /* Return nonzero if the thread PTID is still alive on the remote
2544 system. */
2545
2546 bool
2547 remote_target::thread_alive (ptid_t ptid)
2548 {
2549 struct remote_state *rs = get_remote_state ();
2550 char *p, *endp;
2551
2552 /* Check if this is a thread that we made up ourselves to model
2553 non-threaded targets as single-threaded. */
2554 if (remote_thread_always_alive (ptid))
2555 return 1;
2556
2557 p = rs->buf;
2558 endp = rs->buf + get_remote_packet_size ();
2559
2560 *p++ = 'T';
2561 write_ptid (p, endp, ptid);
2562
2563 putpkt (rs->buf);
2564 getpkt (&rs->buf, &rs->buf_size, 0);
2565 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2566 }
2567
2568 /* Return a pointer to a thread name if we know it and NULL otherwise.
2569 The thread_info object owns the memory for the name. */
2570
2571 const char *
2572 remote_target::thread_name (struct thread_info *info)
2573 {
2574 if (info->priv != NULL)
2575 {
2576 const std::string &name = get_remote_thread_info (info)->name;
2577 return !name.empty () ? name.c_str () : NULL;
2578 }
2579
2580 return NULL;
2581 }
2582
2583 /* About these extended threadlist and threadinfo packets. They are
2584 variable length packets but, the fields within them are often fixed
2585 length. They are redundent enough to send over UDP as is the
2586 remote protocol in general. There is a matching unit test module
2587 in libstub. */
2588
2589 /* WARNING: This threadref data structure comes from the remote O.S.,
2590 libstub protocol encoding, and remote.c. It is not particularly
2591 changable. */
2592
2593 /* Right now, the internal structure is int. We want it to be bigger.
2594 Plan to fix this. */
2595
2596 typedef int gdb_threadref; /* Internal GDB thread reference. */
2597
2598 /* gdb_ext_thread_info is an internal GDB data structure which is
2599 equivalent to the reply of the remote threadinfo packet. */
2600
2601 struct gdb_ext_thread_info
2602 {
2603 threadref threadid; /* External form of thread reference. */
2604 int active; /* Has state interesting to GDB?
2605 regs, stack. */
2606 char display[256]; /* Brief state display, name,
2607 blocked/suspended. */
2608 char shortname[32]; /* To be used to name threads. */
2609 char more_display[256]; /* Long info, statistics, queue depth,
2610 whatever. */
2611 };
2612
2613 /* The volume of remote transfers can be limited by submitting
2614 a mask containing bits specifying the desired information.
2615 Use a union of these values as the 'selection' parameter to
2616 get_thread_info. FIXME: Make these TAG names more thread specific. */
2617
2618 #define TAG_THREADID 1
2619 #define TAG_EXISTS 2
2620 #define TAG_DISPLAY 4
2621 #define TAG_THREADNAME 8
2622 #define TAG_MOREDISPLAY 16
2623
2624 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2625
2626 static char *unpack_nibble (char *buf, int *val);
2627
2628 static char *unpack_byte (char *buf, int *value);
2629
2630 static char *pack_int (char *buf, int value);
2631
2632 static char *unpack_int (char *buf, int *value);
2633
2634 static char *unpack_string (char *src, char *dest, int length);
2635
2636 static char *pack_threadid (char *pkt, threadref *id);
2637
2638 static char *unpack_threadid (char *inbuf, threadref *id);
2639
2640 void int_to_threadref (threadref *id, int value);
2641
2642 static int threadref_to_int (threadref *ref);
2643
2644 static void copy_threadref (threadref *dest, threadref *src);
2645
2646 static int threadmatch (threadref *dest, threadref *src);
2647
2648 static char *pack_threadinfo_request (char *pkt, int mode,
2649 threadref *id);
2650
2651 static int remote_unpack_thread_info_response (char *pkt,
2652 threadref *expectedref,
2653 struct gdb_ext_thread_info
2654 *info);
2655
2656
2657 static int remote_get_threadinfo (threadref *threadid,
2658 int fieldset, /*TAG mask */
2659 struct gdb_ext_thread_info *info);
2660
2661 static char *pack_threadlist_request (char *pkt, int startflag,
2662 int threadcount,
2663 threadref *nextthread);
2664
2665 static int parse_threadlist_response (char *pkt,
2666 int result_limit,
2667 threadref *original_echo,
2668 threadref *resultlist,
2669 int *doneflag);
2670
2671 static int remote_get_threadlist (int startflag,
2672 threadref *nextthread,
2673 int result_limit,
2674 int *done,
2675 int *result_count,
2676 threadref *threadlist);
2677
2678 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2679
2680 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2681 void *context, int looplimit);
2682
2683 static int remote_newthread_step (threadref *ref, void *context);
2684
2685
2686 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2687 buffer we're allowed to write to. Returns
2688 BUF+CHARACTERS_WRITTEN. */
2689
2690 static char *
2691 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2692 {
2693 int pid, tid;
2694 struct remote_state *rs = get_remote_state ();
2695
2696 if (remote_multi_process_p (rs))
2697 {
2698 pid = ptid_get_pid (ptid);
2699 if (pid < 0)
2700 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2701 else
2702 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2703 }
2704 tid = ptid_get_lwp (ptid);
2705 if (tid < 0)
2706 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2707 else
2708 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2709
2710 return buf;
2711 }
2712
2713 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2714 last parsed char. Returns null_ptid if no thread id is found, and
2715 throws an error if the thread id has an invalid format. */
2716
2717 static ptid_t
2718 read_ptid (const char *buf, const char **obuf)
2719 {
2720 const char *p = buf;
2721 const char *pp;
2722 ULONGEST pid = 0, tid = 0;
2723
2724 if (*p == 'p')
2725 {
2726 /* Multi-process ptid. */
2727 pp = unpack_varlen_hex (p + 1, &pid);
2728 if (*pp != '.')
2729 error (_("invalid remote ptid: %s"), p);
2730
2731 p = pp;
2732 pp = unpack_varlen_hex (p + 1, &tid);
2733 if (obuf)
2734 *obuf = pp;
2735 return ptid_build (pid, tid, 0);
2736 }
2737
2738 /* No multi-process. Just a tid. */
2739 pp = unpack_varlen_hex (p, &tid);
2740
2741 /* Return null_ptid when no thread id is found. */
2742 if (p == pp)
2743 {
2744 if (obuf)
2745 *obuf = pp;
2746 return null_ptid;
2747 }
2748
2749 /* Since the stub is not sending a process id, then default to
2750 what's in inferior_ptid, unless it's null at this point. If so,
2751 then since there's no way to know the pid of the reported
2752 threads, use the magic number. */
2753 if (ptid_equal (inferior_ptid, null_ptid))
2754 pid = ptid_get_pid (magic_null_ptid);
2755 else
2756 pid = ptid_get_pid (inferior_ptid);
2757
2758 if (obuf)
2759 *obuf = pp;
2760 return ptid_build (pid, tid, 0);
2761 }
2762
2763 static int
2764 stubhex (int ch)
2765 {
2766 if (ch >= 'a' && ch <= 'f')
2767 return ch - 'a' + 10;
2768 if (ch >= '0' && ch <= '9')
2769 return ch - '0';
2770 if (ch >= 'A' && ch <= 'F')
2771 return ch - 'A' + 10;
2772 return -1;
2773 }
2774
2775 static int
2776 stub_unpack_int (char *buff, int fieldlength)
2777 {
2778 int nibble;
2779 int retval = 0;
2780
2781 while (fieldlength)
2782 {
2783 nibble = stubhex (*buff++);
2784 retval |= nibble;
2785 fieldlength--;
2786 if (fieldlength)
2787 retval = retval << 4;
2788 }
2789 return retval;
2790 }
2791
2792 static char *
2793 unpack_nibble (char *buf, int *val)
2794 {
2795 *val = fromhex (*buf++);
2796 return buf;
2797 }
2798
2799 static char *
2800 unpack_byte (char *buf, int *value)
2801 {
2802 *value = stub_unpack_int (buf, 2);
2803 return buf + 2;
2804 }
2805
2806 static char *
2807 pack_int (char *buf, int value)
2808 {
2809 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2810 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2811 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2812 buf = pack_hex_byte (buf, (value & 0xff));
2813 return buf;
2814 }
2815
2816 static char *
2817 unpack_int (char *buf, int *value)
2818 {
2819 *value = stub_unpack_int (buf, 8);
2820 return buf + 8;
2821 }
2822
2823 #if 0 /* Currently unused, uncomment when needed. */
2824 static char *pack_string (char *pkt, char *string);
2825
2826 static char *
2827 pack_string (char *pkt, char *string)
2828 {
2829 char ch;
2830 int len;
2831
2832 len = strlen (string);
2833 if (len > 200)
2834 len = 200; /* Bigger than most GDB packets, junk??? */
2835 pkt = pack_hex_byte (pkt, len);
2836 while (len-- > 0)
2837 {
2838 ch = *string++;
2839 if ((ch == '\0') || (ch == '#'))
2840 ch = '*'; /* Protect encapsulation. */
2841 *pkt++ = ch;
2842 }
2843 return pkt;
2844 }
2845 #endif /* 0 (unused) */
2846
2847 static char *
2848 unpack_string (char *src, char *dest, int length)
2849 {
2850 while (length--)
2851 *dest++ = *src++;
2852 *dest = '\0';
2853 return src;
2854 }
2855
2856 static char *
2857 pack_threadid (char *pkt, threadref *id)
2858 {
2859 char *limit;
2860 unsigned char *altid;
2861
2862 altid = (unsigned char *) id;
2863 limit = pkt + BUF_THREAD_ID_SIZE;
2864 while (pkt < limit)
2865 pkt = pack_hex_byte (pkt, *altid++);
2866 return pkt;
2867 }
2868
2869
2870 static char *
2871 unpack_threadid (char *inbuf, threadref *id)
2872 {
2873 char *altref;
2874 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2875 int x, y;
2876
2877 altref = (char *) id;
2878
2879 while (inbuf < limit)
2880 {
2881 x = stubhex (*inbuf++);
2882 y = stubhex (*inbuf++);
2883 *altref++ = (x << 4) | y;
2884 }
2885 return inbuf;
2886 }
2887
2888 /* Externally, threadrefs are 64 bits but internally, they are still
2889 ints. This is due to a mismatch of specifications. We would like
2890 to use 64bit thread references internally. This is an adapter
2891 function. */
2892
2893 void
2894 int_to_threadref (threadref *id, int value)
2895 {
2896 unsigned char *scan;
2897
2898 scan = (unsigned char *) id;
2899 {
2900 int i = 4;
2901 while (i--)
2902 *scan++ = 0;
2903 }
2904 *scan++ = (value >> 24) & 0xff;
2905 *scan++ = (value >> 16) & 0xff;
2906 *scan++ = (value >> 8) & 0xff;
2907 *scan++ = (value & 0xff);
2908 }
2909
2910 static int
2911 threadref_to_int (threadref *ref)
2912 {
2913 int i, value = 0;
2914 unsigned char *scan;
2915
2916 scan = *ref;
2917 scan += 4;
2918 i = 4;
2919 while (i-- > 0)
2920 value = (value << 8) | ((*scan++) & 0xff);
2921 return value;
2922 }
2923
2924 static void
2925 copy_threadref (threadref *dest, threadref *src)
2926 {
2927 int i;
2928 unsigned char *csrc, *cdest;
2929
2930 csrc = (unsigned char *) src;
2931 cdest = (unsigned char *) dest;
2932 i = 8;
2933 while (i--)
2934 *cdest++ = *csrc++;
2935 }
2936
2937 static int
2938 threadmatch (threadref *dest, threadref *src)
2939 {
2940 /* Things are broken right now, so just assume we got a match. */
2941 #if 0
2942 unsigned char *srcp, *destp;
2943 int i, result;
2944 srcp = (char *) src;
2945 destp = (char *) dest;
2946
2947 result = 1;
2948 while (i-- > 0)
2949 result &= (*srcp++ == *destp++) ? 1 : 0;
2950 return result;
2951 #endif
2952 return 1;
2953 }
2954
2955 /*
2956 threadid:1, # always request threadid
2957 context_exists:2,
2958 display:4,
2959 unique_name:8,
2960 more_display:16
2961 */
2962
2963 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2964
2965 static char *
2966 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2967 {
2968 *pkt++ = 'q'; /* Info Query */
2969 *pkt++ = 'P'; /* process or thread info */
2970 pkt = pack_int (pkt, mode); /* mode */
2971 pkt = pack_threadid (pkt, id); /* threadid */
2972 *pkt = '\0'; /* terminate */
2973 return pkt;
2974 }
2975
2976 /* These values tag the fields in a thread info response packet. */
2977 /* Tagging the fields allows us to request specific fields and to
2978 add more fields as time goes by. */
2979
2980 #define TAG_THREADID 1 /* Echo the thread identifier. */
2981 #define TAG_EXISTS 2 /* Is this process defined enough to
2982 fetch registers and its stack? */
2983 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2984 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2985 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2986 the process. */
2987
2988 static int
2989 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2990 struct gdb_ext_thread_info *info)
2991 {
2992 struct remote_state *rs = get_remote_state ();
2993 int mask, length;
2994 int tag;
2995 threadref ref;
2996 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2997 int retval = 1;
2998
2999 /* info->threadid = 0; FIXME: implement zero_threadref. */
3000 info->active = 0;
3001 info->display[0] = '\0';
3002 info->shortname[0] = '\0';
3003 info->more_display[0] = '\0';
3004
3005 /* Assume the characters indicating the packet type have been
3006 stripped. */
3007 pkt = unpack_int (pkt, &mask); /* arg mask */
3008 pkt = unpack_threadid (pkt, &ref);
3009
3010 if (mask == 0)
3011 warning (_("Incomplete response to threadinfo request."));
3012 if (!threadmatch (&ref, expectedref))
3013 { /* This is an answer to a different request. */
3014 warning (_("ERROR RMT Thread info mismatch."));
3015 return 0;
3016 }
3017 copy_threadref (&info->threadid, &ref);
3018
3019 /* Loop on tagged fields , try to bail if somthing goes wrong. */
3020
3021 /* Packets are terminated with nulls. */
3022 while ((pkt < limit) && mask && *pkt)
3023 {
3024 pkt = unpack_int (pkt, &tag); /* tag */
3025 pkt = unpack_byte (pkt, &length); /* length */
3026 if (!(tag & mask)) /* Tags out of synch with mask. */
3027 {
3028 warning (_("ERROR RMT: threadinfo tag mismatch."));
3029 retval = 0;
3030 break;
3031 }
3032 if (tag == TAG_THREADID)
3033 {
3034 if (length != 16)
3035 {
3036 warning (_("ERROR RMT: length of threadid is not 16."));
3037 retval = 0;
3038 break;
3039 }
3040 pkt = unpack_threadid (pkt, &ref);
3041 mask = mask & ~TAG_THREADID;
3042 continue;
3043 }
3044 if (tag == TAG_EXISTS)
3045 {
3046 info->active = stub_unpack_int (pkt, length);
3047 pkt += length;
3048 mask = mask & ~(TAG_EXISTS);
3049 if (length > 8)
3050 {
3051 warning (_("ERROR RMT: 'exists' length too long."));
3052 retval = 0;
3053 break;
3054 }
3055 continue;
3056 }
3057 if (tag == TAG_THREADNAME)
3058 {
3059 pkt = unpack_string (pkt, &info->shortname[0], length);
3060 mask = mask & ~TAG_THREADNAME;
3061 continue;
3062 }
3063 if (tag == TAG_DISPLAY)
3064 {
3065 pkt = unpack_string (pkt, &info->display[0], length);
3066 mask = mask & ~TAG_DISPLAY;
3067 continue;
3068 }
3069 if (tag == TAG_MOREDISPLAY)
3070 {
3071 pkt = unpack_string (pkt, &info->more_display[0], length);
3072 mask = mask & ~TAG_MOREDISPLAY;
3073 continue;
3074 }
3075 warning (_("ERROR RMT: unknown thread info tag."));
3076 break; /* Not a tag we know about. */
3077 }
3078 return retval;
3079 }
3080
3081 static int
3082 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
3083 struct gdb_ext_thread_info *info)
3084 {
3085 struct remote_state *rs = get_remote_state ();
3086 int result;
3087
3088 pack_threadinfo_request (rs->buf, fieldset, threadid);
3089 putpkt (rs->buf);
3090 getpkt (&rs->buf, &rs->buf_size, 0);
3091
3092 if (rs->buf[0] == '\0')
3093 return 0;
3094
3095 result = remote_unpack_thread_info_response (rs->buf + 2,
3096 threadid, info);
3097 return result;
3098 }
3099
3100 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3101
3102 static char *
3103 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3104 threadref *nextthread)
3105 {
3106 *pkt++ = 'q'; /* info query packet */
3107 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3108 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3109 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3110 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3111 *pkt = '\0';
3112 return pkt;
3113 }
3114
3115 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3116
3117 static int
3118 parse_threadlist_response (char *pkt, int result_limit,
3119 threadref *original_echo, threadref *resultlist,
3120 int *doneflag)
3121 {
3122 struct remote_state *rs = get_remote_state ();
3123 char *limit;
3124 int count, resultcount, done;
3125
3126 resultcount = 0;
3127 /* Assume the 'q' and 'M chars have been stripped. */
3128 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3129 /* done parse past here */
3130 pkt = unpack_byte (pkt, &count); /* count field */
3131 pkt = unpack_nibble (pkt, &done);
3132 /* The first threadid is the argument threadid. */
3133 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3134 while ((count-- > 0) && (pkt < limit))
3135 {
3136 pkt = unpack_threadid (pkt, resultlist++);
3137 if (resultcount++ >= result_limit)
3138 break;
3139 }
3140 if (doneflag)
3141 *doneflag = done;
3142 return resultcount;
3143 }
3144
3145 /* Fetch the next batch of threads from the remote. Returns -1 if the
3146 qL packet is not supported, 0 on error and 1 on success. */
3147
3148 static int
3149 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
3150 int *done, int *result_count, threadref *threadlist)
3151 {
3152 struct remote_state *rs = get_remote_state ();
3153 int result = 1;
3154
3155 /* Trancate result limit to be smaller than the packet size. */
3156 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3157 >= get_remote_packet_size ())
3158 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3159
3160 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3161 putpkt (rs->buf);
3162 getpkt (&rs->buf, &rs->buf_size, 0);
3163 if (*rs->buf == '\0')
3164 {
3165 /* Packet not supported. */
3166 return -1;
3167 }
3168
3169 *result_count =
3170 parse_threadlist_response (rs->buf + 2, result_limit,
3171 &rs->echo_nextthread, threadlist, done);
3172
3173 if (!threadmatch (&rs->echo_nextthread, nextthread))
3174 {
3175 /* FIXME: This is a good reason to drop the packet. */
3176 /* Possably, there is a duplicate response. */
3177 /* Possabilities :
3178 retransmit immediatly - race conditions
3179 retransmit after timeout - yes
3180 exit
3181 wait for packet, then exit
3182 */
3183 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3184 return 0; /* I choose simply exiting. */
3185 }
3186 if (*result_count <= 0)
3187 {
3188 if (*done != 1)
3189 {
3190 warning (_("RMT ERROR : failed to get remote thread list."));
3191 result = 0;
3192 }
3193 return result; /* break; */
3194 }
3195 if (*result_count > result_limit)
3196 {
3197 *result_count = 0;
3198 warning (_("RMT ERROR: threadlist response longer than requested."));
3199 return 0;
3200 }
3201 return result;
3202 }
3203
3204 /* Fetch the list of remote threads, with the qL packet, and call
3205 STEPFUNCTION for each thread found. Stops iterating and returns 1
3206 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3207 STEPFUNCTION returns false. If the packet is not supported,
3208 returns -1. */
3209
3210 static int
3211 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
3212 int looplimit)
3213 {
3214 struct remote_state *rs = get_remote_state ();
3215 int done, i, result_count;
3216 int startflag = 1;
3217 int result = 1;
3218 int loopcount = 0;
3219
3220 done = 0;
3221 while (!done)
3222 {
3223 if (loopcount++ > looplimit)
3224 {
3225 result = 0;
3226 warning (_("Remote fetch threadlist -infinite loop-."));
3227 break;
3228 }
3229 result = remote_get_threadlist (startflag, &rs->nextthread,
3230 MAXTHREADLISTRESULTS,
3231 &done, &result_count,
3232 rs->resultthreadlist);
3233 if (result <= 0)
3234 break;
3235 /* Clear for later iterations. */
3236 startflag = 0;
3237 /* Setup to resume next batch of thread references, set nextthread. */
3238 if (result_count >= 1)
3239 copy_threadref (&rs->nextthread,
3240 &rs->resultthreadlist[result_count - 1]);
3241 i = 0;
3242 while (result_count--)
3243 {
3244 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3245 {
3246 result = 0;
3247 break;
3248 }
3249 }
3250 }
3251 return result;
3252 }
3253
3254 /* A thread found on the remote target. */
3255
3256 struct thread_item
3257 {
3258 explicit thread_item (ptid_t ptid_)
3259 : ptid (ptid_)
3260 {}
3261
3262 thread_item (thread_item &&other) = default;
3263 thread_item &operator= (thread_item &&other) = default;
3264
3265 DISABLE_COPY_AND_ASSIGN (thread_item);
3266
3267 /* The thread's PTID. */
3268 ptid_t ptid;
3269
3270 /* The thread's extra info. */
3271 std::string extra;
3272
3273 /* The thread's name. */
3274 std::string name;
3275
3276 /* The core the thread was running on. -1 if not known. */
3277 int core = -1;
3278
3279 /* The thread handle associated with the thread. */
3280 gdb::byte_vector thread_handle;
3281 };
3282
3283 /* Context passed around to the various methods listing remote
3284 threads. As new threads are found, they're added to the ITEMS
3285 vector. */
3286
3287 struct threads_listing_context
3288 {
3289 /* Return true if this object contains an entry for a thread with ptid
3290 PTID. */
3291
3292 bool contains_thread (ptid_t ptid) const
3293 {
3294 auto match_ptid = [&] (const thread_item &item)
3295 {
3296 return item.ptid == ptid;
3297 };
3298
3299 auto it = std::find_if (this->items.begin (),
3300 this->items.end (),
3301 match_ptid);
3302
3303 return it != this->items.end ();
3304 }
3305
3306 /* Remove the thread with ptid PTID. */
3307
3308 void remove_thread (ptid_t ptid)
3309 {
3310 auto match_ptid = [&] (const thread_item &item)
3311 {
3312 return item.ptid == ptid;
3313 };
3314
3315 auto it = std::remove_if (this->items.begin (),
3316 this->items.end (),
3317 match_ptid);
3318
3319 if (it != this->items.end ())
3320 this->items.erase (it);
3321 }
3322
3323 /* The threads found on the remote target. */
3324 std::vector<thread_item> items;
3325 };
3326
3327 static int
3328 remote_newthread_step (threadref *ref, void *data)
3329 {
3330 struct threads_listing_context *context
3331 = (struct threads_listing_context *) data;
3332 int pid = inferior_ptid.pid ();
3333 int lwp = threadref_to_int (ref);
3334 ptid_t ptid (pid, lwp);
3335
3336 context->items.emplace_back (ptid);
3337
3338 return 1; /* continue iterator */
3339 }
3340
3341 #define CRAZY_MAX_THREADS 1000
3342
3343 static ptid_t
3344 remote_current_thread (ptid_t oldpid)
3345 {
3346 struct remote_state *rs = get_remote_state ();
3347
3348 putpkt ("qC");
3349 getpkt (&rs->buf, &rs->buf_size, 0);
3350 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3351 {
3352 const char *obuf;
3353 ptid_t result;
3354
3355 result = read_ptid (&rs->buf[2], &obuf);
3356 if (*obuf != '\0' && remote_debug)
3357 fprintf_unfiltered (gdb_stdlog,
3358 "warning: garbage in qC reply\n");
3359
3360 return result;
3361 }
3362 else
3363 return oldpid;
3364 }
3365
3366 /* List remote threads using the deprecated qL packet. */
3367
3368 static int
3369 remote_get_threads_with_ql (struct target_ops *ops,
3370 struct threads_listing_context *context)
3371 {
3372 if (remote_threadlist_iterator (remote_newthread_step, context,
3373 CRAZY_MAX_THREADS) >= 0)
3374 return 1;
3375
3376 return 0;
3377 }
3378
3379 #if defined(HAVE_LIBEXPAT)
3380
3381 static void
3382 start_thread (struct gdb_xml_parser *parser,
3383 const struct gdb_xml_element *element,
3384 void *user_data,
3385 std::vector<gdb_xml_value> &attributes)
3386 {
3387 struct threads_listing_context *data
3388 = (struct threads_listing_context *) user_data;
3389 struct gdb_xml_value *attr;
3390
3391 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3392 ptid_t ptid = read_ptid (id, NULL);
3393
3394 data->items.emplace_back (ptid);
3395 thread_item &item = data->items.back ();
3396
3397 attr = xml_find_attribute (attributes, "core");
3398 if (attr != NULL)
3399 item.core = *(ULONGEST *) attr->value.get ();
3400
3401 attr = xml_find_attribute (attributes, "name");
3402 if (attr != NULL)
3403 item.name = (const char *) attr->value.get ();
3404
3405 attr = xml_find_attribute (attributes, "handle");
3406 if (attr != NULL)
3407 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3408 }
3409
3410 static void
3411 end_thread (struct gdb_xml_parser *parser,
3412 const struct gdb_xml_element *element,
3413 void *user_data, const char *body_text)
3414 {
3415 struct threads_listing_context *data
3416 = (struct threads_listing_context *) user_data;
3417
3418 if (body_text != NULL && *body_text != '\0')
3419 data->items.back ().extra = body_text;
3420 }
3421
3422 const struct gdb_xml_attribute thread_attributes[] = {
3423 { "id", GDB_XML_AF_NONE, NULL, NULL },
3424 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3425 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3426 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3427 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3428 };
3429
3430 const struct gdb_xml_element thread_children[] = {
3431 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3432 };
3433
3434 const struct gdb_xml_element threads_children[] = {
3435 { "thread", thread_attributes, thread_children,
3436 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3437 start_thread, end_thread },
3438 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3439 };
3440
3441 const struct gdb_xml_element threads_elements[] = {
3442 { "threads", NULL, threads_children,
3443 GDB_XML_EF_NONE, NULL, NULL },
3444 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3445 };
3446
3447 #endif
3448
3449 /* List remote threads using qXfer:threads:read. */
3450
3451 static int
3452 remote_get_threads_with_qxfer (struct target_ops *ops,
3453 struct threads_listing_context *context)
3454 {
3455 #if defined(HAVE_LIBEXPAT)
3456 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3457 {
3458 gdb::optional<gdb::char_vector> xml
3459 = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3460
3461 if (xml && (*xml)[0] != '\0')
3462 {
3463 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3464 threads_elements, xml->data (), context);
3465 }
3466
3467 return 1;
3468 }
3469 #endif
3470
3471 return 0;
3472 }
3473
3474 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3475
3476 static int
3477 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3478 struct threads_listing_context *context)
3479 {
3480 struct remote_state *rs = get_remote_state ();
3481
3482 if (rs->use_threadinfo_query)
3483 {
3484 const char *bufp;
3485
3486 putpkt ("qfThreadInfo");
3487 getpkt (&rs->buf, &rs->buf_size, 0);
3488 bufp = rs->buf;
3489 if (bufp[0] != '\0') /* q packet recognized */
3490 {
3491 while (*bufp++ == 'm') /* reply contains one or more TID */
3492 {
3493 do
3494 {
3495 ptid_t ptid = read_ptid (bufp, &bufp);
3496 context->items.emplace_back (ptid);
3497 }
3498 while (*bufp++ == ','); /* comma-separated list */
3499 putpkt ("qsThreadInfo");
3500 getpkt (&rs->buf, &rs->buf_size, 0);
3501 bufp = rs->buf;
3502 }
3503 return 1;
3504 }
3505 else
3506 {
3507 /* Packet not recognized. */
3508 rs->use_threadinfo_query = 0;
3509 }
3510 }
3511
3512 return 0;
3513 }
3514
3515 /* Implement the to_update_thread_list function for the remote
3516 targets. */
3517
3518 void
3519 remote_target::update_thread_list ()
3520 {
3521 struct threads_listing_context context;
3522 int got_list = 0;
3523
3524 /* We have a few different mechanisms to fetch the thread list. Try
3525 them all, starting with the most preferred one first, falling
3526 back to older methods. */
3527 if (remote_get_threads_with_qxfer (this, &context)
3528 || remote_get_threads_with_qthreadinfo (this, &context)
3529 || remote_get_threads_with_ql (this, &context))
3530 {
3531 struct thread_info *tp, *tmp;
3532
3533 got_list = 1;
3534
3535 if (context.items.empty ()
3536 && remote_thread_always_alive (inferior_ptid))
3537 {
3538 /* Some targets don't really support threads, but still
3539 reply an (empty) thread list in response to the thread
3540 listing packets, instead of replying "packet not
3541 supported". Exit early so we don't delete the main
3542 thread. */
3543 return;
3544 }
3545
3546 /* CONTEXT now holds the current thread list on the remote
3547 target end. Delete GDB-side threads no longer found on the
3548 target. */
3549 ALL_THREADS_SAFE (tp, tmp)
3550 {
3551 if (!context.contains_thread (tp->ptid))
3552 {
3553 /* Not found. */
3554 delete_thread (tp->ptid);
3555 }
3556 }
3557
3558 /* Remove any unreported fork child threads from CONTEXT so
3559 that we don't interfere with follow fork, which is where
3560 creation of such threads is handled. */
3561 remove_new_fork_children (&context);
3562
3563 /* And now add threads we don't know about yet to our list. */
3564 for (thread_item &item : context.items)
3565 {
3566 if (item.ptid != null_ptid)
3567 {
3568 /* In non-stop mode, we assume new found threads are
3569 executing until proven otherwise with a stop reply.
3570 In all-stop, we can only get here if all threads are
3571 stopped. */
3572 int executing = target_is_non_stop_p () ? 1 : 0;
3573
3574 remote_notice_new_inferior (item.ptid, executing);
3575
3576 remote_thread_info *info = get_remote_thread_info (item.ptid);
3577 info->core = item.core;
3578 info->extra = std::move (item.extra);
3579 info->name = std::move (item.name);
3580 info->thread_handle = std::move (item.thread_handle);
3581 }
3582 }
3583 }
3584
3585 if (!got_list)
3586 {
3587 /* If no thread listing method is supported, then query whether
3588 each known thread is alive, one by one, with the T packet.
3589 If the target doesn't support threads at all, then this is a
3590 no-op. See remote_thread_alive. */
3591 prune_threads ();
3592 }
3593 }
3594
3595 /*
3596 * Collect a descriptive string about the given thread.
3597 * The target may say anything it wants to about the thread
3598 * (typically info about its blocked / runnable state, name, etc.).
3599 * This string will appear in the info threads display.
3600 *
3601 * Optional: targets are not required to implement this function.
3602 */
3603
3604 const char *
3605 remote_target::extra_thread_info (thread_info *tp)
3606 {
3607 struct remote_state *rs = get_remote_state ();
3608 int result;
3609 int set;
3610 threadref id;
3611 struct gdb_ext_thread_info threadinfo;
3612 static char display_buf[100]; /* arbitrary... */
3613 int n = 0; /* position in display_buf */
3614
3615 if (rs->remote_desc == 0) /* paranoia */
3616 internal_error (__FILE__, __LINE__,
3617 _("remote_threads_extra_info"));
3618
3619 if (ptid_equal (tp->ptid, magic_null_ptid)
3620 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3621 /* This is the main thread which was added by GDB. The remote
3622 server doesn't know about it. */
3623 return NULL;
3624
3625 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3626 {
3627 struct thread_info *info = find_thread_ptid (tp->ptid);
3628
3629 if (info != NULL && info->priv != NULL)
3630 {
3631 const std::string &extra = get_remote_thread_info (info)->extra;
3632 return !extra.empty () ? extra.c_str () : NULL;
3633 }
3634 else
3635 return NULL;
3636 }
3637
3638 if (rs->use_threadextra_query)
3639 {
3640 char *b = rs->buf;
3641 char *endb = rs->buf + get_remote_packet_size ();
3642
3643 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3644 b += strlen (b);
3645 write_ptid (b, endb, tp->ptid);
3646
3647 putpkt (rs->buf);
3648 getpkt (&rs->buf, &rs->buf_size, 0);
3649 if (rs->buf[0] != 0)
3650 {
3651 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3652 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3653 display_buf [result] = '\0';
3654 return display_buf;
3655 }
3656 }
3657
3658 /* If the above query fails, fall back to the old method. */
3659 rs->use_threadextra_query = 0;
3660 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3661 | TAG_MOREDISPLAY | TAG_DISPLAY;
3662 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3663 if (remote_get_threadinfo (&id, set, &threadinfo))
3664 if (threadinfo.active)
3665 {
3666 if (*threadinfo.shortname)
3667 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3668 " Name: %s,", threadinfo.shortname);
3669 if (*threadinfo.display)
3670 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3671 " State: %s,", threadinfo.display);
3672 if (*threadinfo.more_display)
3673 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3674 " Priority: %s", threadinfo.more_display);
3675
3676 if (n > 0)
3677 {
3678 /* For purely cosmetic reasons, clear up trailing commas. */
3679 if (',' == display_buf[n-1])
3680 display_buf[n-1] = ' ';
3681 return display_buf;
3682 }
3683 }
3684 return NULL;
3685 }
3686 \f
3687
3688 bool
3689 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3690 struct static_tracepoint_marker *marker)
3691 {
3692 struct remote_state *rs = get_remote_state ();
3693 char *p = rs->buf;
3694
3695 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3696 p += strlen (p);
3697 p += hexnumstr (p, addr);
3698 putpkt (rs->buf);
3699 getpkt (&rs->buf, &rs->buf_size, 0);
3700 p = rs->buf;
3701
3702 if (*p == 'E')
3703 error (_("Remote failure reply: %s"), p);
3704
3705 if (*p++ == 'm')
3706 {
3707 parse_static_tracepoint_marker_definition (p, NULL, marker);
3708 return true;
3709 }
3710
3711 return false;
3712 }
3713
3714 std::vector<static_tracepoint_marker>
3715 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3716 {
3717 struct remote_state *rs = get_remote_state ();
3718 std::vector<static_tracepoint_marker> markers;
3719 const char *p;
3720 static_tracepoint_marker marker;
3721
3722 /* Ask for a first packet of static tracepoint marker
3723 definition. */
3724 putpkt ("qTfSTM");
3725 getpkt (&rs->buf, &rs->buf_size, 0);
3726 p = rs->buf;
3727 if (*p == 'E')
3728 error (_("Remote failure reply: %s"), p);
3729
3730 while (*p++ == 'm')
3731 {
3732 do
3733 {
3734 parse_static_tracepoint_marker_definition (p, &p, &marker);
3735
3736 if (strid == NULL || marker.str_id == strid)
3737 markers.push_back (std::move (marker));
3738 }
3739 while (*p++ == ','); /* comma-separated list */
3740 /* Ask for another packet of static tracepoint definition. */
3741 putpkt ("qTsSTM");
3742 getpkt (&rs->buf, &rs->buf_size, 0);
3743 p = rs->buf;
3744 }
3745
3746 return markers;
3747 }
3748
3749 \f
3750 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3751
3752 ptid_t
3753 remote_target::get_ada_task_ptid (long lwp, long thread)
3754 {
3755 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3756 }
3757 \f
3758
3759 /* Restart the remote side; this is an extended protocol operation. */
3760
3761 static void
3762 extended_remote_restart (void)
3763 {
3764 struct remote_state *rs = get_remote_state ();
3765
3766 /* Send the restart command; for reasons I don't understand the
3767 remote side really expects a number after the "R". */
3768 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3769 putpkt (rs->buf);
3770
3771 remote_fileio_reset ();
3772 }
3773 \f
3774 /* Clean up connection to a remote debugger. */
3775
3776 void
3777 remote_target::close ()
3778 {
3779 struct remote_state *rs = get_remote_state ();
3780
3781 if (rs->remote_desc == NULL)
3782 return; /* already closed */
3783
3784 /* Make sure we leave stdin registered in the event loop. */
3785 terminal_ours ();
3786
3787 serial_close (rs->remote_desc);
3788 rs->remote_desc = NULL;
3789
3790 /* We don't have a connection to the remote stub anymore. Get rid
3791 of all the inferiors and their threads we were controlling.
3792 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3793 will be unable to find the thread corresponding to (pid, 0, 0). */
3794 inferior_ptid = null_ptid;
3795 discard_all_inferiors ();
3796
3797 /* We are closing the remote target, so we should discard
3798 everything of this target. */
3799 discard_pending_stop_replies_in_queue (rs);
3800
3801 if (remote_async_inferior_event_token)
3802 delete_async_event_handler (&remote_async_inferior_event_token);
3803
3804 remote_notif_state_xfree (rs->notif_state);
3805
3806 trace_reset_local_state ();
3807 }
3808
3809 /* Query the remote side for the text, data and bss offsets. */
3810
3811 static void
3812 get_offsets (void)
3813 {
3814 struct remote_state *rs = get_remote_state ();
3815 char *buf;
3816 char *ptr;
3817 int lose, num_segments = 0, do_sections, do_segments;
3818 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3819 struct section_offsets *offs;
3820 struct symfile_segment_data *data;
3821
3822 if (symfile_objfile == NULL)
3823 return;
3824
3825 putpkt ("qOffsets");
3826 getpkt (&rs->buf, &rs->buf_size, 0);
3827 buf = rs->buf;
3828
3829 if (buf[0] == '\000')
3830 return; /* Return silently. Stub doesn't support
3831 this command. */
3832 if (buf[0] == 'E')
3833 {
3834 warning (_("Remote failure reply: %s"), buf);
3835 return;
3836 }
3837
3838 /* Pick up each field in turn. This used to be done with scanf, but
3839 scanf will make trouble if CORE_ADDR size doesn't match
3840 conversion directives correctly. The following code will work
3841 with any size of CORE_ADDR. */
3842 text_addr = data_addr = bss_addr = 0;
3843 ptr = buf;
3844 lose = 0;
3845
3846 if (startswith (ptr, "Text="))
3847 {
3848 ptr += 5;
3849 /* Don't use strtol, could lose on big values. */
3850 while (*ptr && *ptr != ';')
3851 text_addr = (text_addr << 4) + fromhex (*ptr++);
3852
3853 if (startswith (ptr, ";Data="))
3854 {
3855 ptr += 6;
3856 while (*ptr && *ptr != ';')
3857 data_addr = (data_addr << 4) + fromhex (*ptr++);
3858 }
3859 else
3860 lose = 1;
3861
3862 if (!lose && startswith (ptr, ";Bss="))
3863 {
3864 ptr += 5;
3865 while (*ptr && *ptr != ';')
3866 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3867
3868 if (bss_addr != data_addr)
3869 warning (_("Target reported unsupported offsets: %s"), buf);
3870 }
3871 else
3872 lose = 1;
3873 }
3874 else if (startswith (ptr, "TextSeg="))
3875 {
3876 ptr += 8;
3877 /* Don't use strtol, could lose on big values. */
3878 while (*ptr && *ptr != ';')
3879 text_addr = (text_addr << 4) + fromhex (*ptr++);
3880 num_segments = 1;
3881
3882 if (startswith (ptr, ";DataSeg="))
3883 {
3884 ptr += 9;
3885 while (*ptr && *ptr != ';')
3886 data_addr = (data_addr << 4) + fromhex (*ptr++);
3887 num_segments++;
3888 }
3889 }
3890 else
3891 lose = 1;
3892
3893 if (lose)
3894 error (_("Malformed response to offset query, %s"), buf);
3895 else if (*ptr != '\0')
3896 warning (_("Target reported unsupported offsets: %s"), buf);
3897
3898 offs = ((struct section_offsets *)
3899 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3900 memcpy (offs, symfile_objfile->section_offsets,
3901 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3902
3903 data = get_symfile_segment_data (symfile_objfile->obfd);
3904 do_segments = (data != NULL);
3905 do_sections = num_segments == 0;
3906
3907 if (num_segments > 0)
3908 {
3909 segments[0] = text_addr;
3910 segments[1] = data_addr;
3911 }
3912 /* If we have two segments, we can still try to relocate everything
3913 by assuming that the .text and .data offsets apply to the whole
3914 text and data segments. Convert the offsets given in the packet
3915 to base addresses for symfile_map_offsets_to_segments. */
3916 else if (data && data->num_segments == 2)
3917 {
3918 segments[0] = data->segment_bases[0] + text_addr;
3919 segments[1] = data->segment_bases[1] + data_addr;
3920 num_segments = 2;
3921 }
3922 /* If the object file has only one segment, assume that it is text
3923 rather than data; main programs with no writable data are rare,
3924 but programs with no code are useless. Of course the code might
3925 have ended up in the data segment... to detect that we would need
3926 the permissions here. */
3927 else if (data && data->num_segments == 1)
3928 {
3929 segments[0] = data->segment_bases[0] + text_addr;
3930 num_segments = 1;
3931 }
3932 /* There's no way to relocate by segment. */
3933 else
3934 do_segments = 0;
3935
3936 if (do_segments)
3937 {
3938 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3939 offs, num_segments, segments);
3940
3941 if (ret == 0 && !do_sections)
3942 error (_("Can not handle qOffsets TextSeg "
3943 "response with this symbol file"));
3944
3945 if (ret > 0)
3946 do_sections = 0;
3947 }
3948
3949 if (data)
3950 free_symfile_segment_data (data);
3951
3952 if (do_sections)
3953 {
3954 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3955
3956 /* This is a temporary kludge to force data and bss to use the
3957 same offsets because that's what nlmconv does now. The real
3958 solution requires changes to the stub and remote.c that I
3959 don't have time to do right now. */
3960
3961 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3962 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3963 }
3964
3965 objfile_relocate (symfile_objfile, offs);
3966 }
3967
3968 /* Send interrupt_sequence to remote target. */
3969 static void
3970 send_interrupt_sequence (void)
3971 {
3972 struct remote_state *rs = get_remote_state ();
3973
3974 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3975 remote_serial_write ("\x03", 1);
3976 else if (interrupt_sequence_mode == interrupt_sequence_break)
3977 serial_send_break (rs->remote_desc);
3978 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3979 {
3980 serial_send_break (rs->remote_desc);
3981 remote_serial_write ("g", 1);
3982 }
3983 else
3984 internal_error (__FILE__, __LINE__,
3985 _("Invalid value for interrupt_sequence_mode: %s."),
3986 interrupt_sequence_mode);
3987 }
3988
3989
3990 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3991 and extract the PTID. Returns NULL_PTID if not found. */
3992
3993 static ptid_t
3994 stop_reply_extract_thread (char *stop_reply)
3995 {
3996 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3997 {
3998 const char *p;
3999
4000 /* Txx r:val ; r:val (...) */
4001 p = &stop_reply[3];
4002
4003 /* Look for "register" named "thread". */
4004 while (*p != '\0')
4005 {
4006 const char *p1;
4007
4008 p1 = strchr (p, ':');
4009 if (p1 == NULL)
4010 return null_ptid;
4011
4012 if (strncmp (p, "thread", p1 - p) == 0)
4013 return read_ptid (++p1, &p);
4014
4015 p1 = strchr (p, ';');
4016 if (p1 == NULL)
4017 return null_ptid;
4018 p1++;
4019
4020 p = p1;
4021 }
4022 }
4023
4024 return null_ptid;
4025 }
4026
4027 /* Determine the remote side's current thread. If we have a stop
4028 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4029 "thread" register we can extract the current thread from. If not,
4030 ask the remote which is the current thread with qC. The former
4031 method avoids a roundtrip. */
4032
4033 static ptid_t
4034 get_current_thread (char *wait_status)
4035 {
4036 ptid_t ptid = null_ptid;
4037
4038 /* Note we don't use remote_parse_stop_reply as that makes use of
4039 the target architecture, which we haven't yet fully determined at
4040 this point. */
4041 if (wait_status != NULL)
4042 ptid = stop_reply_extract_thread (wait_status);
4043 if (ptid_equal (ptid, null_ptid))
4044 ptid = remote_current_thread (inferior_ptid);
4045
4046 return ptid;
4047 }
4048
4049 /* Query the remote target for which is the current thread/process,
4050 add it to our tables, and update INFERIOR_PTID. The caller is
4051 responsible for setting the state such that the remote end is ready
4052 to return the current thread.
4053
4054 This function is called after handling the '?' or 'vRun' packets,
4055 whose response is a stop reply from which we can also try
4056 extracting the thread. If the target doesn't support the explicit
4057 qC query, we infer the current thread from that stop reply, passed
4058 in in WAIT_STATUS, which may be NULL. */
4059
4060 static void
4061 add_current_inferior_and_thread (char *wait_status)
4062 {
4063 struct remote_state *rs = get_remote_state ();
4064 int fake_pid_p = 0;
4065
4066 inferior_ptid = null_ptid;
4067
4068 /* Now, if we have thread information, update inferior_ptid. */
4069 ptid_t curr_ptid = get_current_thread (wait_status);
4070
4071 if (curr_ptid != null_ptid)
4072 {
4073 if (!remote_multi_process_p (rs))
4074 fake_pid_p = 1;
4075 }
4076 else
4077 {
4078 /* Without this, some commands which require an active target
4079 (such as kill) won't work. This variable serves (at least)
4080 double duty as both the pid of the target process (if it has
4081 such), and as a flag indicating that a target is active. */
4082 curr_ptid = magic_null_ptid;
4083 fake_pid_p = 1;
4084 }
4085
4086 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
4087
4088 /* Add the main thread and switch to it. Don't try reading
4089 registers yet, since we haven't fetched the target description
4090 yet. */
4091 thread_info *tp = add_thread_silent (curr_ptid);
4092 switch_to_thread_no_regs (tp);
4093 }
4094
4095 /* Print info about a thread that was found already stopped on
4096 connection. */
4097
4098 static void
4099 print_one_stopped_thread (struct thread_info *thread)
4100 {
4101 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4102
4103 switch_to_thread (thread->ptid);
4104 stop_pc = get_frame_pc (get_current_frame ());
4105 set_current_sal_from_frame (get_current_frame ());
4106
4107 thread->suspend.waitstatus_pending_p = 0;
4108
4109 if (ws->kind == TARGET_WAITKIND_STOPPED)
4110 {
4111 enum gdb_signal sig = ws->value.sig;
4112
4113 if (signal_print_state (sig))
4114 gdb::observers::signal_received.notify (sig);
4115 }
4116 gdb::observers::normal_stop.notify (NULL, 1);
4117 }
4118
4119 /* Process all initial stop replies the remote side sent in response
4120 to the ? packet. These indicate threads that were already stopped
4121 on initial connection. We mark these threads as stopped and print
4122 their current frame before giving the user the prompt. */
4123
4124 static void
4125 process_initial_stop_replies (int from_tty)
4126 {
4127 int pending_stop_replies = stop_reply_queue_length ();
4128 struct inferior *inf;
4129 struct thread_info *thread;
4130 struct thread_info *selected = NULL;
4131 struct thread_info *lowest_stopped = NULL;
4132 struct thread_info *first = NULL;
4133
4134 /* Consume the initial pending events. */
4135 while (pending_stop_replies-- > 0)
4136 {
4137 ptid_t waiton_ptid = minus_one_ptid;
4138 ptid_t event_ptid;
4139 struct target_waitstatus ws;
4140 int ignore_event = 0;
4141 struct thread_info *thread;
4142
4143 memset (&ws, 0, sizeof (ws));
4144 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4145 if (remote_debug)
4146 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4147
4148 switch (ws.kind)
4149 {
4150 case TARGET_WAITKIND_IGNORE:
4151 case TARGET_WAITKIND_NO_RESUMED:
4152 case TARGET_WAITKIND_SIGNALLED:
4153 case TARGET_WAITKIND_EXITED:
4154 /* We shouldn't see these, but if we do, just ignore. */
4155 if (remote_debug)
4156 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4157 ignore_event = 1;
4158 break;
4159
4160 case TARGET_WAITKIND_EXECD:
4161 xfree (ws.value.execd_pathname);
4162 break;
4163 default:
4164 break;
4165 }
4166
4167 if (ignore_event)
4168 continue;
4169
4170 thread = find_thread_ptid (event_ptid);
4171
4172 if (ws.kind == TARGET_WAITKIND_STOPPED)
4173 {
4174 enum gdb_signal sig = ws.value.sig;
4175
4176 /* Stubs traditionally report SIGTRAP as initial signal,
4177 instead of signal 0. Suppress it. */
4178 if (sig == GDB_SIGNAL_TRAP)
4179 sig = GDB_SIGNAL_0;
4180 thread->suspend.stop_signal = sig;
4181 ws.value.sig = sig;
4182 }
4183
4184 thread->suspend.waitstatus = ws;
4185
4186 if (ws.kind != TARGET_WAITKIND_STOPPED
4187 || ws.value.sig != GDB_SIGNAL_0)
4188 thread->suspend.waitstatus_pending_p = 1;
4189
4190 set_executing (event_ptid, 0);
4191 set_running (event_ptid, 0);
4192 get_remote_thread_info (thread)->vcont_resumed = 0;
4193 }
4194
4195 /* "Notice" the new inferiors before anything related to
4196 registers/memory. */
4197 ALL_INFERIORS (inf)
4198 {
4199 if (inf->pid == 0)
4200 continue;
4201
4202 inf->needs_setup = 1;
4203
4204 if (non_stop)
4205 {
4206 thread = any_live_thread_of_process (inf->pid);
4207 notice_new_inferior (thread->ptid,
4208 thread->state == THREAD_RUNNING,
4209 from_tty);
4210 }
4211 }
4212
4213 /* If all-stop on top of non-stop, pause all threads. Note this
4214 records the threads' stop pc, so must be done after "noticing"
4215 the inferiors. */
4216 if (!non_stop)
4217 {
4218 stop_all_threads ();
4219
4220 /* If all threads of an inferior were already stopped, we
4221 haven't setup the inferior yet. */
4222 ALL_INFERIORS (inf)
4223 {
4224 if (inf->pid == 0)
4225 continue;
4226
4227 if (inf->needs_setup)
4228 {
4229 thread = any_live_thread_of_process (inf->pid);
4230 switch_to_thread_no_regs (thread);
4231 setup_inferior (0);
4232 }
4233 }
4234 }
4235
4236 /* Now go over all threads that are stopped, and print their current
4237 frame. If all-stop, then if there's a signalled thread, pick
4238 that as current. */
4239 ALL_NON_EXITED_THREADS (thread)
4240 {
4241 if (first == NULL)
4242 first = thread;
4243
4244 if (!non_stop)
4245 set_running (thread->ptid, 0);
4246 else if (thread->state != THREAD_STOPPED)
4247 continue;
4248
4249 if (selected == NULL
4250 && thread->suspend.waitstatus_pending_p)
4251 selected = thread;
4252
4253 if (lowest_stopped == NULL
4254 || thread->inf->num < lowest_stopped->inf->num
4255 || thread->per_inf_num < lowest_stopped->per_inf_num)
4256 lowest_stopped = thread;
4257
4258 if (non_stop)
4259 print_one_stopped_thread (thread);
4260 }
4261
4262 /* In all-stop, we only print the status of one thread, and leave
4263 others with their status pending. */
4264 if (!non_stop)
4265 {
4266 thread = selected;
4267 if (thread == NULL)
4268 thread = lowest_stopped;
4269 if (thread == NULL)
4270 thread = first;
4271
4272 print_one_stopped_thread (thread);
4273 }
4274
4275 /* For "info program". */
4276 thread = inferior_thread ();
4277 if (thread->state == THREAD_STOPPED)
4278 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4279 }
4280
4281 /* Start the remote connection and sync state. */
4282
4283 void
4284 remote_target::start_remote (int from_tty, int extended_p)
4285 {
4286 struct remote_state *rs = get_remote_state ();
4287 struct packet_config *noack_config;
4288 char *wait_status = NULL;
4289
4290 /* Signal other parts that we're going through the initial setup,
4291 and so things may not be stable yet. E.g., we don't try to
4292 install tracepoints until we've relocated symbols. Also, a
4293 Ctrl-C before we're connected and synced up can't interrupt the
4294 target. Instead, it offers to drop the (potentially wedged)
4295 connection. */
4296 rs->starting_up = 1;
4297
4298 QUIT;
4299
4300 if (interrupt_on_connect)
4301 send_interrupt_sequence ();
4302
4303 /* Ack any packet which the remote side has already sent. */
4304 remote_serial_write ("+", 1);
4305
4306 /* The first packet we send to the target is the optional "supported
4307 packets" request. If the target can answer this, it will tell us
4308 which later probes to skip. */
4309 remote_query_supported ();
4310
4311 /* If the stub wants to get a QAllow, compose one and send it. */
4312 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4313 set_permissions ();
4314
4315 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4316 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4317 as a reply to known packet. For packet "vFile:setfs:" it is an
4318 invalid reply and GDB would return error in
4319 remote_hostio_set_filesystem, making remote files access impossible.
4320 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4321 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4322 {
4323 const char v_mustreplyempty[] = "vMustReplyEmpty";
4324
4325 putpkt (v_mustreplyempty);
4326 getpkt (&rs->buf, &rs->buf_size, 0);
4327 if (strcmp (rs->buf, "OK") == 0)
4328 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4329 else if (strcmp (rs->buf, "") != 0)
4330 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4331 rs->buf);
4332 }
4333
4334 /* Next, we possibly activate noack mode.
4335
4336 If the QStartNoAckMode packet configuration is set to AUTO,
4337 enable noack mode if the stub reported a wish for it with
4338 qSupported.
4339
4340 If set to TRUE, then enable noack mode even if the stub didn't
4341 report it in qSupported. If the stub doesn't reply OK, the
4342 session ends with an error.
4343
4344 If FALSE, then don't activate noack mode, regardless of what the
4345 stub claimed should be the default with qSupported. */
4346
4347 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4348 if (packet_config_support (noack_config) != PACKET_DISABLE)
4349 {
4350 putpkt ("QStartNoAckMode");
4351 getpkt (&rs->buf, &rs->buf_size, 0);
4352 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4353 rs->noack_mode = 1;
4354 }
4355
4356 if (extended_p)
4357 {
4358 /* Tell the remote that we are using the extended protocol. */
4359 putpkt ("!");
4360 getpkt (&rs->buf, &rs->buf_size, 0);
4361 }
4362
4363 /* Let the target know which signals it is allowed to pass down to
4364 the program. */
4365 update_signals_program_target ();
4366
4367 /* Next, if the target can specify a description, read it. We do
4368 this before anything involving memory or registers. */
4369 target_find_description ();
4370
4371 /* Next, now that we know something about the target, update the
4372 address spaces in the program spaces. */
4373 update_address_spaces ();
4374
4375 /* On OSs where the list of libraries is global to all
4376 processes, we fetch them early. */
4377 if (gdbarch_has_global_solist (target_gdbarch ()))
4378 solib_add (NULL, from_tty, auto_solib_add);
4379
4380 if (target_is_non_stop_p ())
4381 {
4382 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4383 error (_("Non-stop mode requested, but remote "
4384 "does not support non-stop"));
4385
4386 putpkt ("QNonStop:1");
4387 getpkt (&rs->buf, &rs->buf_size, 0);
4388
4389 if (strcmp (rs->buf, "OK") != 0)
4390 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4391
4392 /* Find about threads and processes the stub is already
4393 controlling. We default to adding them in the running state.
4394 The '?' query below will then tell us about which threads are
4395 stopped. */
4396 this->update_thread_list ();
4397 }
4398 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4399 {
4400 /* Don't assume that the stub can operate in all-stop mode.
4401 Request it explicitly. */
4402 putpkt ("QNonStop:0");
4403 getpkt (&rs->buf, &rs->buf_size, 0);
4404
4405 if (strcmp (rs->buf, "OK") != 0)
4406 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4407 }
4408
4409 /* Upload TSVs regardless of whether the target is running or not. The
4410 remote stub, such as GDBserver, may have some predefined or builtin
4411 TSVs, even if the target is not running. */
4412 if (get_trace_status (current_trace_status ()) != -1)
4413 {
4414 struct uploaded_tsv *uploaded_tsvs = NULL;
4415
4416 upload_trace_state_variables (&uploaded_tsvs);
4417 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4418 }
4419
4420 /* Check whether the target is running now. */
4421 putpkt ("?");
4422 getpkt (&rs->buf, &rs->buf_size, 0);
4423
4424 if (!target_is_non_stop_p ())
4425 {
4426 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4427 {
4428 if (!extended_p)
4429 error (_("The target is not running (try extended-remote?)"));
4430
4431 /* We're connected, but not running. Drop out before we
4432 call start_remote. */
4433 rs->starting_up = 0;
4434 return;
4435 }
4436 else
4437 {
4438 /* Save the reply for later. */
4439 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4440 strcpy (wait_status, rs->buf);
4441 }
4442
4443 /* Fetch thread list. */
4444 target_update_thread_list ();
4445
4446 /* Let the stub know that we want it to return the thread. */
4447 set_continue_thread (minus_one_ptid);
4448
4449 if (thread_count () == 0)
4450 {
4451 /* Target has no concept of threads at all. GDB treats
4452 non-threaded target as single-threaded; add a main
4453 thread. */
4454 add_current_inferior_and_thread (wait_status);
4455 }
4456 else
4457 {
4458 /* We have thread information; select the thread the target
4459 says should be current. If we're reconnecting to a
4460 multi-threaded program, this will ideally be the thread
4461 that last reported an event before GDB disconnected. */
4462 inferior_ptid = get_current_thread (wait_status);
4463 if (ptid_equal (inferior_ptid, null_ptid))
4464 {
4465 /* Odd... The target was able to list threads, but not
4466 tell us which thread was current (no "thread"
4467 register in T stop reply?). Just pick the first
4468 thread in the thread list then. */
4469
4470 if (remote_debug)
4471 fprintf_unfiltered (gdb_stdlog,
4472 "warning: couldn't determine remote "
4473 "current thread; picking first in list.\n");
4474
4475 inferior_ptid = thread_list->ptid;
4476 }
4477 }
4478
4479 /* init_wait_for_inferior should be called before get_offsets in order
4480 to manage `inserted' flag in bp loc in a correct state.
4481 breakpoint_init_inferior, called from init_wait_for_inferior, set
4482 `inserted' flag to 0, while before breakpoint_re_set, called from
4483 start_remote, set `inserted' flag to 1. In the initialization of
4484 inferior, breakpoint_init_inferior should be called first, and then
4485 breakpoint_re_set can be called. If this order is broken, state of
4486 `inserted' flag is wrong, and cause some problems on breakpoint
4487 manipulation. */
4488 init_wait_for_inferior ();
4489
4490 get_offsets (); /* Get text, data & bss offsets. */
4491
4492 /* If we could not find a description using qXfer, and we know
4493 how to do it some other way, try again. This is not
4494 supported for non-stop; it could be, but it is tricky if
4495 there are no stopped threads when we connect. */
4496 if (remote_read_description_p (this)
4497 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4498 {
4499 target_clear_description ();
4500 target_find_description ();
4501 }
4502
4503 /* Use the previously fetched status. */
4504 gdb_assert (wait_status != NULL);
4505 strcpy (rs->buf, wait_status);
4506 rs->cached_wait_status = 1;
4507
4508 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4509 }
4510 else
4511 {
4512 /* Clear WFI global state. Do this before finding about new
4513 threads and inferiors, and setting the current inferior.
4514 Otherwise we would clear the proceed status of the current
4515 inferior when we want its stop_soon state to be preserved
4516 (see notice_new_inferior). */
4517 init_wait_for_inferior ();
4518
4519 /* In non-stop, we will either get an "OK", meaning that there
4520 are no stopped threads at this time; or, a regular stop
4521 reply. In the latter case, there may be more than one thread
4522 stopped --- we pull them all out using the vStopped
4523 mechanism. */
4524 if (strcmp (rs->buf, "OK") != 0)
4525 {
4526 struct notif_client *notif = &notif_client_stop;
4527
4528 /* remote_notif_get_pending_replies acks this one, and gets
4529 the rest out. */
4530 rs->notif_state->pending_event[notif_client_stop.id]
4531 = remote_notif_parse (notif, rs->buf);
4532 remote_notif_get_pending_events (notif);
4533 }
4534
4535 if (thread_count () == 0)
4536 {
4537 if (!extended_p)
4538 error (_("The target is not running (try extended-remote?)"));
4539
4540 /* We're connected, but not running. Drop out before we
4541 call start_remote. */
4542 rs->starting_up = 0;
4543 return;
4544 }
4545
4546 /* In non-stop mode, any cached wait status will be stored in
4547 the stop reply queue. */
4548 gdb_assert (wait_status == NULL);
4549
4550 /* Report all signals during attach/startup. */
4551 pass_signals (0, NULL);
4552
4553 /* If there are already stopped threads, mark them stopped and
4554 report their stops before giving the prompt to the user. */
4555 process_initial_stop_replies (from_tty);
4556
4557 if (target_can_async_p ())
4558 target_async (1);
4559 }
4560
4561 /* If we connected to a live target, do some additional setup. */
4562 if (target_has_execution)
4563 {
4564 if (symfile_objfile) /* No use without a symbol-file. */
4565 remote_check_symbols ();
4566 }
4567
4568 /* Possibly the target has been engaged in a trace run started
4569 previously; find out where things are at. */
4570 if (get_trace_status (current_trace_status ()) != -1)
4571 {
4572 struct uploaded_tp *uploaded_tps = NULL;
4573
4574 if (current_trace_status ()->running)
4575 printf_filtered (_("Trace is already running on the target.\n"));
4576
4577 upload_tracepoints (&uploaded_tps);
4578
4579 merge_uploaded_tracepoints (&uploaded_tps);
4580 }
4581
4582 /* Possibly the target has been engaged in a btrace record started
4583 previously; find out where things are at. */
4584 remote_btrace_maybe_reopen ();
4585
4586 /* The thread and inferior lists are now synchronized with the
4587 target, our symbols have been relocated, and we're merged the
4588 target's tracepoints with ours. We're done with basic start
4589 up. */
4590 rs->starting_up = 0;
4591
4592 /* Maybe breakpoints are global and need to be inserted now. */
4593 if (breakpoints_should_be_inserted_now ())
4594 insert_breakpoints ();
4595 }
4596
4597 /* Open a connection to a remote debugger.
4598 NAME is the filename used for communication. */
4599
4600 void
4601 remote_target::open (const char *name, int from_tty)
4602 {
4603 open_1 (name, from_tty, 0);
4604 }
4605
4606 /* Open a connection to a remote debugger using the extended
4607 remote gdb protocol. NAME is the filename used for communication. */
4608
4609 void
4610 extended_remote_target::open (const char *name, int from_tty)
4611 {
4612 open_1 (name, from_tty, 1 /*extended_p */);
4613 }
4614
4615 /* Reset all packets back to "unknown support". Called when opening a
4616 new connection to a remote target. */
4617
4618 static void
4619 reset_all_packet_configs_support (void)
4620 {
4621 int i;
4622
4623 for (i = 0; i < PACKET_MAX; i++)
4624 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4625 }
4626
4627 /* Initialize all packet configs. */
4628
4629 static void
4630 init_all_packet_configs (void)
4631 {
4632 int i;
4633
4634 for (i = 0; i < PACKET_MAX; i++)
4635 {
4636 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4637 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4638 }
4639 }
4640
4641 /* Symbol look-up. */
4642
4643 static void
4644 remote_check_symbols (void)
4645 {
4646 char *msg, *reply, *tmp;
4647 int end;
4648 long reply_size;
4649 struct cleanup *old_chain;
4650
4651 /* The remote side has no concept of inferiors that aren't running
4652 yet, it only knows about running processes. If we're connected
4653 but our current inferior is not running, we should not invite the
4654 remote target to request symbol lookups related to its
4655 (unrelated) current process. */
4656 if (!target_has_execution)
4657 return;
4658
4659 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4660 return;
4661
4662 /* Make sure the remote is pointing at the right process. Note
4663 there's no way to select "no process". */
4664 set_general_process ();
4665
4666 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4667 because we need both at the same time. */
4668 msg = (char *) xmalloc (get_remote_packet_size ());
4669 old_chain = make_cleanup (xfree, msg);
4670 reply = (char *) xmalloc (get_remote_packet_size ());
4671 make_cleanup (free_current_contents, &reply);
4672 reply_size = get_remote_packet_size ();
4673
4674 /* Invite target to request symbol lookups. */
4675
4676 putpkt ("qSymbol::");
4677 getpkt (&reply, &reply_size, 0);
4678 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4679
4680 while (startswith (reply, "qSymbol:"))
4681 {
4682 struct bound_minimal_symbol sym;
4683
4684 tmp = &reply[8];
4685 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4686 msg[end] = '\0';
4687 sym = lookup_minimal_symbol (msg, NULL, NULL);
4688 if (sym.minsym == NULL)
4689 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4690 else
4691 {
4692 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4693 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4694
4695 /* If this is a function address, return the start of code
4696 instead of any data function descriptor. */
4697 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4698 sym_addr,
4699 target_stack);
4700
4701 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4702 phex_nz (sym_addr, addr_size), &reply[8]);
4703 }
4704
4705 putpkt (msg);
4706 getpkt (&reply, &reply_size, 0);
4707 }
4708
4709 do_cleanups (old_chain);
4710 }
4711
4712 static struct serial *
4713 remote_serial_open (const char *name)
4714 {
4715 static int udp_warning = 0;
4716
4717 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4718 of in ser-tcp.c, because it is the remote protocol assuming that the
4719 serial connection is reliable and not the serial connection promising
4720 to be. */
4721 if (!udp_warning && startswith (name, "udp:"))
4722 {
4723 warning (_("The remote protocol may be unreliable over UDP.\n"
4724 "Some events may be lost, rendering further debugging "
4725 "impossible."));
4726 udp_warning = 1;
4727 }
4728
4729 return serial_open (name);
4730 }
4731
4732 /* Inform the target of our permission settings. The permission flags
4733 work without this, but if the target knows the settings, it can do
4734 a couple things. First, it can add its own check, to catch cases
4735 that somehow manage to get by the permissions checks in target
4736 methods. Second, if the target is wired to disallow particular
4737 settings (for instance, a system in the field that is not set up to
4738 be able to stop at a breakpoint), it can object to any unavailable
4739 permissions. */
4740
4741 void
4742 remote_target::set_permissions ()
4743 {
4744 struct remote_state *rs = get_remote_state ();
4745
4746 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4747 "WriteReg:%x;WriteMem:%x;"
4748 "InsertBreak:%x;InsertTrace:%x;"
4749 "InsertFastTrace:%x;Stop:%x",
4750 may_write_registers, may_write_memory,
4751 may_insert_breakpoints, may_insert_tracepoints,
4752 may_insert_fast_tracepoints, may_stop);
4753 putpkt (rs->buf);
4754 getpkt (&rs->buf, &rs->buf_size, 0);
4755
4756 /* If the target didn't like the packet, warn the user. Do not try
4757 to undo the user's settings, that would just be maddening. */
4758 if (strcmp (rs->buf, "OK") != 0)
4759 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4760 }
4761
4762 /* This type describes each known response to the qSupported
4763 packet. */
4764 struct protocol_feature
4765 {
4766 /* The name of this protocol feature. */
4767 const char *name;
4768
4769 /* The default for this protocol feature. */
4770 enum packet_support default_support;
4771
4772 /* The function to call when this feature is reported, or after
4773 qSupported processing if the feature is not supported.
4774 The first argument points to this structure. The second
4775 argument indicates whether the packet requested support be
4776 enabled, disabled, or probed (or the default, if this function
4777 is being called at the end of processing and this feature was
4778 not reported). The third argument may be NULL; if not NULL, it
4779 is a NUL-terminated string taken from the packet following
4780 this feature's name and an equals sign. */
4781 void (*func) (const struct protocol_feature *, enum packet_support,
4782 const char *);
4783
4784 /* The corresponding packet for this feature. Only used if
4785 FUNC is remote_supported_packet. */
4786 int packet;
4787 };
4788
4789 static void
4790 remote_supported_packet (const struct protocol_feature *feature,
4791 enum packet_support support,
4792 const char *argument)
4793 {
4794 if (argument)
4795 {
4796 warning (_("Remote qSupported response supplied an unexpected value for"
4797 " \"%s\"."), feature->name);
4798 return;
4799 }
4800
4801 remote_protocol_packets[feature->packet].support = support;
4802 }
4803
4804 static void
4805 remote_packet_size (const struct protocol_feature *feature,
4806 enum packet_support support, const char *value)
4807 {
4808 struct remote_state *rs = get_remote_state ();
4809
4810 int packet_size;
4811 char *value_end;
4812
4813 if (support != PACKET_ENABLE)
4814 return;
4815
4816 if (value == NULL || *value == '\0')
4817 {
4818 warning (_("Remote target reported \"%s\" without a size."),
4819 feature->name);
4820 return;
4821 }
4822
4823 errno = 0;
4824 packet_size = strtol (value, &value_end, 16);
4825 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4826 {
4827 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4828 feature->name, value);
4829 return;
4830 }
4831
4832 /* Record the new maximum packet size. */
4833 rs->explicit_packet_size = packet_size;
4834 }
4835
4836 static const struct protocol_feature remote_protocol_features[] = {
4837 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4838 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4839 PACKET_qXfer_auxv },
4840 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4841 PACKET_qXfer_exec_file },
4842 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4843 PACKET_qXfer_features },
4844 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4845 PACKET_qXfer_libraries },
4846 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4847 PACKET_qXfer_libraries_svr4 },
4848 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4849 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4850 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4851 PACKET_qXfer_memory_map },
4852 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4853 PACKET_qXfer_spu_read },
4854 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4855 PACKET_qXfer_spu_write },
4856 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4857 PACKET_qXfer_osdata },
4858 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4859 PACKET_qXfer_threads },
4860 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4861 PACKET_qXfer_traceframe_info },
4862 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4863 PACKET_QPassSignals },
4864 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4865 PACKET_QCatchSyscalls },
4866 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4867 PACKET_QProgramSignals },
4868 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4869 PACKET_QSetWorkingDir },
4870 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4871 PACKET_QStartupWithShell },
4872 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4873 PACKET_QEnvironmentHexEncoded },
4874 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4875 PACKET_QEnvironmentReset },
4876 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4877 PACKET_QEnvironmentUnset },
4878 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4879 PACKET_QStartNoAckMode },
4880 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4881 PACKET_multiprocess_feature },
4882 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4883 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4884 PACKET_qXfer_siginfo_read },
4885 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4886 PACKET_qXfer_siginfo_write },
4887 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4888 PACKET_ConditionalTracepoints },
4889 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4890 PACKET_ConditionalBreakpoints },
4891 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4892 PACKET_BreakpointCommands },
4893 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4894 PACKET_FastTracepoints },
4895 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4896 PACKET_StaticTracepoints },
4897 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4898 PACKET_InstallInTrace},
4899 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4900 PACKET_DisconnectedTracing_feature },
4901 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4902 PACKET_bc },
4903 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4904 PACKET_bs },
4905 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4906 PACKET_TracepointSource },
4907 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4908 PACKET_QAllow },
4909 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4910 PACKET_EnableDisableTracepoints_feature },
4911 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4912 PACKET_qXfer_fdpic },
4913 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4914 PACKET_qXfer_uib },
4915 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4916 PACKET_QDisableRandomization },
4917 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4918 { "QTBuffer:size", PACKET_DISABLE,
4919 remote_supported_packet, PACKET_QTBuffer_size},
4920 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4921 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4922 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4923 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4924 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4925 PACKET_qXfer_btrace },
4926 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4927 PACKET_qXfer_btrace_conf },
4928 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4929 PACKET_Qbtrace_conf_bts_size },
4930 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4931 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4932 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4933 PACKET_fork_event_feature },
4934 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4935 PACKET_vfork_event_feature },
4936 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4937 PACKET_exec_event_feature },
4938 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4939 PACKET_Qbtrace_conf_pt_size },
4940 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4941 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4942 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4943 };
4944
4945 static char *remote_support_xml;
4946
4947 /* Register string appended to "xmlRegisters=" in qSupported query. */
4948
4949 void
4950 register_remote_support_xml (const char *xml)
4951 {
4952 #if defined(HAVE_LIBEXPAT)
4953 if (remote_support_xml == NULL)
4954 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4955 else
4956 {
4957 char *copy = xstrdup (remote_support_xml + 13);
4958 char *p = strtok (copy, ",");
4959
4960 do
4961 {
4962 if (strcmp (p, xml) == 0)
4963 {
4964 /* already there */
4965 xfree (copy);
4966 return;
4967 }
4968 }
4969 while ((p = strtok (NULL, ",")) != NULL);
4970 xfree (copy);
4971
4972 remote_support_xml = reconcat (remote_support_xml,
4973 remote_support_xml, ",", xml,
4974 (char *) NULL);
4975 }
4976 #endif
4977 }
4978
4979 static void
4980 remote_query_supported_append (std::string *msg, const char *append)
4981 {
4982 if (!msg->empty ())
4983 msg->append (";");
4984 msg->append (append);
4985 }
4986
4987 static void
4988 remote_query_supported (void)
4989 {
4990 struct remote_state *rs = get_remote_state ();
4991 char *next;
4992 int i;
4993 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4994
4995 /* The packet support flags are handled differently for this packet
4996 than for most others. We treat an error, a disabled packet, and
4997 an empty response identically: any features which must be reported
4998 to be used will be automatically disabled. An empty buffer
4999 accomplishes this, since that is also the representation for a list
5000 containing no features. */
5001
5002 rs->buf[0] = 0;
5003 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5004 {
5005 std::string q;
5006
5007 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5008 remote_query_supported_append (&q, "multiprocess+");
5009
5010 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5011 remote_query_supported_append (&q, "swbreak+");
5012 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5013 remote_query_supported_append (&q, "hwbreak+");
5014
5015 remote_query_supported_append (&q, "qRelocInsn+");
5016
5017 if (packet_set_cmd_state (PACKET_fork_event_feature)
5018 != AUTO_BOOLEAN_FALSE)
5019 remote_query_supported_append (&q, "fork-events+");
5020 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5021 != AUTO_BOOLEAN_FALSE)
5022 remote_query_supported_append (&q, "vfork-events+");
5023 if (packet_set_cmd_state (PACKET_exec_event_feature)
5024 != AUTO_BOOLEAN_FALSE)
5025 remote_query_supported_append (&q, "exec-events+");
5026
5027 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5028 remote_query_supported_append (&q, "vContSupported+");
5029
5030 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5031 remote_query_supported_append (&q, "QThreadEvents+");
5032
5033 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5034 remote_query_supported_append (&q, "no-resumed+");
5035
5036 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5037 the qSupported:xmlRegisters=i386 handling. */
5038 if (remote_support_xml != NULL
5039 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5040 remote_query_supported_append (&q, remote_support_xml);
5041
5042 q = "qSupported:" + q;
5043 putpkt (q.c_str ());
5044
5045 getpkt (&rs->buf, &rs->buf_size, 0);
5046
5047 /* If an error occured, warn, but do not return - just reset the
5048 buffer to empty and go on to disable features. */
5049 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5050 == PACKET_ERROR)
5051 {
5052 warning (_("Remote failure reply: %s"), rs->buf);
5053 rs->buf[0] = 0;
5054 }
5055 }
5056
5057 memset (seen, 0, sizeof (seen));
5058
5059 next = rs->buf;
5060 while (*next)
5061 {
5062 enum packet_support is_supported;
5063 char *p, *end, *name_end, *value;
5064
5065 /* First separate out this item from the rest of the packet. If
5066 there's another item after this, we overwrite the separator
5067 (terminated strings are much easier to work with). */
5068 p = next;
5069 end = strchr (p, ';');
5070 if (end == NULL)
5071 {
5072 end = p + strlen (p);
5073 next = end;
5074 }
5075 else
5076 {
5077 *end = '\0';
5078 next = end + 1;
5079
5080 if (end == p)
5081 {
5082 warning (_("empty item in \"qSupported\" response"));
5083 continue;
5084 }
5085 }
5086
5087 name_end = strchr (p, '=');
5088 if (name_end)
5089 {
5090 /* This is a name=value entry. */
5091 is_supported = PACKET_ENABLE;
5092 value = name_end + 1;
5093 *name_end = '\0';
5094 }
5095 else
5096 {
5097 value = NULL;
5098 switch (end[-1])
5099 {
5100 case '+':
5101 is_supported = PACKET_ENABLE;
5102 break;
5103
5104 case '-':
5105 is_supported = PACKET_DISABLE;
5106 break;
5107
5108 case '?':
5109 is_supported = PACKET_SUPPORT_UNKNOWN;
5110 break;
5111
5112 default:
5113 warning (_("unrecognized item \"%s\" "
5114 "in \"qSupported\" response"), p);
5115 continue;
5116 }
5117 end[-1] = '\0';
5118 }
5119
5120 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5121 if (strcmp (remote_protocol_features[i].name, p) == 0)
5122 {
5123 const struct protocol_feature *feature;
5124
5125 seen[i] = 1;
5126 feature = &remote_protocol_features[i];
5127 feature->func (feature, is_supported, value);
5128 break;
5129 }
5130 }
5131
5132 /* If we increased the packet size, make sure to increase the global
5133 buffer size also. We delay this until after parsing the entire
5134 qSupported packet, because this is the same buffer we were
5135 parsing. */
5136 if (rs->buf_size < rs->explicit_packet_size)
5137 {
5138 rs->buf_size = rs->explicit_packet_size;
5139 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5140 }
5141
5142 /* Handle the defaults for unmentioned features. */
5143 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5144 if (!seen[i])
5145 {
5146 const struct protocol_feature *feature;
5147
5148 feature = &remote_protocol_features[i];
5149 feature->func (feature, feature->default_support, NULL);
5150 }
5151 }
5152
5153 /* Serial QUIT handler for the remote serial descriptor.
5154
5155 Defers handling a Ctrl-C until we're done with the current
5156 command/response packet sequence, unless:
5157
5158 - We're setting up the connection. Don't send a remote interrupt
5159 request, as we're not fully synced yet. Quit immediately
5160 instead.
5161
5162 - The target has been resumed in the foreground
5163 (target_terminal::is_ours is false) with a synchronous resume
5164 packet, and we're blocked waiting for the stop reply, thus a
5165 Ctrl-C should be immediately sent to the target.
5166
5167 - We get a second Ctrl-C while still within the same serial read or
5168 write. In that case the serial is seemingly wedged --- offer to
5169 quit/disconnect.
5170
5171 - We see a second Ctrl-C without target response, after having
5172 previously interrupted the target. In that case the target/stub
5173 is probably wedged --- offer to quit/disconnect.
5174 */
5175
5176 static void
5177 remote_serial_quit_handler (void)
5178 {
5179 struct remote_state *rs = get_remote_state ();
5180
5181 if (check_quit_flag ())
5182 {
5183 /* If we're starting up, we're not fully synced yet. Quit
5184 immediately. */
5185 if (rs->starting_up)
5186 quit ();
5187 else if (rs->got_ctrlc_during_io)
5188 {
5189 if (query (_("The target is not responding to GDB commands.\n"
5190 "Stop debugging it? ")))
5191 remote_unpush_and_throw ();
5192 }
5193 /* If ^C has already been sent once, offer to disconnect. */
5194 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5195 interrupt_query ();
5196 /* All-stop protocol, and blocked waiting for stop reply. Send
5197 an interrupt request. */
5198 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5199 target_interrupt ();
5200 else
5201 rs->got_ctrlc_during_io = 1;
5202 }
5203 }
5204
5205 /* Remove any of the remote.c targets from target stack. Upper targets depend
5206 on it so remove them first. */
5207
5208 static void
5209 remote_unpush_target (void)
5210 {
5211 pop_all_targets_at_and_above (process_stratum);
5212 }
5213
5214 static void
5215 remote_unpush_and_throw (void)
5216 {
5217 remote_unpush_target ();
5218 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5219 }
5220
5221 void
5222 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5223 {
5224 struct remote_state *rs = get_remote_state ();
5225
5226 if (name == 0)
5227 error (_("To open a remote debug connection, you need to specify what\n"
5228 "serial device is attached to the remote system\n"
5229 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5230
5231 /* See FIXME above. */
5232 if (!target_async_permitted)
5233 wait_forever_enabled_p = 1;
5234
5235 /* If we're connected to a running target, target_preopen will kill it.
5236 Ask this question first, before target_preopen has a chance to kill
5237 anything. */
5238 if (rs->remote_desc != NULL && !have_inferiors ())
5239 {
5240 if (from_tty
5241 && !query (_("Already connected to a remote target. Disconnect? ")))
5242 error (_("Still connected."));
5243 }
5244
5245 /* Here the possibly existing remote target gets unpushed. */
5246 target_preopen (from_tty);
5247
5248 /* Make sure we send the passed signals list the next time we resume. */
5249 xfree (rs->last_pass_packet);
5250 rs->last_pass_packet = NULL;
5251
5252 /* Make sure we send the program signals list the next time we
5253 resume. */
5254 xfree (rs->last_program_signals_packet);
5255 rs->last_program_signals_packet = NULL;
5256
5257 remote_fileio_reset ();
5258 reopen_exec_file ();
5259 reread_symbols ();
5260
5261 rs->remote_desc = remote_serial_open (name);
5262 if (!rs->remote_desc)
5263 perror_with_name (name);
5264
5265 if (baud_rate != -1)
5266 {
5267 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5268 {
5269 /* The requested speed could not be set. Error out to
5270 top level after closing remote_desc. Take care to
5271 set remote_desc to NULL to avoid closing remote_desc
5272 more than once. */
5273 serial_close (rs->remote_desc);
5274 rs->remote_desc = NULL;
5275 perror_with_name (name);
5276 }
5277 }
5278
5279 serial_setparity (rs->remote_desc, serial_parity);
5280 serial_raw (rs->remote_desc);
5281
5282 /* If there is something sitting in the buffer we might take it as a
5283 response to a command, which would be bad. */
5284 serial_flush_input (rs->remote_desc);
5285
5286 if (from_tty)
5287 {
5288 puts_filtered ("Remote debugging using ");
5289 puts_filtered (name);
5290 puts_filtered ("\n");
5291 }
5292
5293 remote_target *target
5294 = extended_p ? &extended_remote_ops : &remote_ops;
5295 push_target (target); /* Switch to using remote target now. */
5296
5297 /* Register extra event sources in the event loop. */
5298 remote_async_inferior_event_token
5299 = create_async_event_handler (remote_async_inferior_event_handler,
5300 NULL);
5301 rs->notif_state = remote_notif_state_allocate ();
5302
5303 /* Reset the target state; these things will be queried either by
5304 remote_query_supported or as they are needed. */
5305 reset_all_packet_configs_support ();
5306 rs->cached_wait_status = 0;
5307 rs->explicit_packet_size = 0;
5308 rs->noack_mode = 0;
5309 rs->extended = extended_p;
5310 rs->waiting_for_stop_reply = 0;
5311 rs->ctrlc_pending_p = 0;
5312 rs->got_ctrlc_during_io = 0;
5313
5314 rs->general_thread = not_sent_ptid;
5315 rs->continue_thread = not_sent_ptid;
5316 rs->remote_traceframe_number = -1;
5317
5318 rs->last_resume_exec_dir = EXEC_FORWARD;
5319
5320 /* Probe for ability to use "ThreadInfo" query, as required. */
5321 rs->use_threadinfo_query = 1;
5322 rs->use_threadextra_query = 1;
5323
5324 rs->readahead_cache.invalidate ();
5325
5326 if (target_async_permitted)
5327 {
5328 /* FIXME: cagney/1999-09-23: During the initial connection it is
5329 assumed that the target is already ready and able to respond to
5330 requests. Unfortunately remote_start_remote() eventually calls
5331 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5332 around this. Eventually a mechanism that allows
5333 wait_for_inferior() to expect/get timeouts will be
5334 implemented. */
5335 wait_forever_enabled_p = 0;
5336 }
5337
5338 /* First delete any symbols previously loaded from shared libraries. */
5339 no_shared_libraries (NULL, 0);
5340
5341 /* Start afresh. */
5342 init_thread_list ();
5343
5344 /* Start the remote connection. If error() or QUIT, discard this
5345 target (we'd otherwise be in an inconsistent state) and then
5346 propogate the error on up the exception chain. This ensures that
5347 the caller doesn't stumble along blindly assuming that the
5348 function succeeded. The CLI doesn't have this problem but other
5349 UI's, such as MI do.
5350
5351 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5352 this function should return an error indication letting the
5353 caller restore the previous state. Unfortunately the command
5354 ``target remote'' is directly wired to this function making that
5355 impossible. On a positive note, the CLI side of this problem has
5356 been fixed - the function set_cmd_context() makes it possible for
5357 all the ``target ....'' commands to share a common callback
5358 function. See cli-dump.c. */
5359 {
5360
5361 TRY
5362 {
5363 target->start_remote (from_tty, extended_p);
5364 }
5365 CATCH (ex, RETURN_MASK_ALL)
5366 {
5367 /* Pop the partially set up target - unless something else did
5368 already before throwing the exception. */
5369 if (rs->remote_desc != NULL)
5370 remote_unpush_target ();
5371 if (target_async_permitted)
5372 wait_forever_enabled_p = 1;
5373 throw_exception (ex);
5374 }
5375 END_CATCH
5376 }
5377
5378 remote_btrace_reset ();
5379
5380 if (target_async_permitted)
5381 wait_forever_enabled_p = 1;
5382 }
5383
5384 /* Detach the specified process. */
5385
5386 static void
5387 remote_detach_pid (int pid)
5388 {
5389 struct remote_state *rs = get_remote_state ();
5390
5391 if (remote_multi_process_p (rs))
5392 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5393 else
5394 strcpy (rs->buf, "D");
5395
5396 putpkt (rs->buf);
5397 getpkt (&rs->buf, &rs->buf_size, 0);
5398
5399 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5400 ;
5401 else if (rs->buf[0] == '\0')
5402 error (_("Remote doesn't know how to detach"));
5403 else
5404 error (_("Can't detach process."));
5405 }
5406
5407 /* This detaches a program to which we previously attached, using
5408 inferior_ptid to identify the process. After this is done, GDB
5409 can be used to debug some other program. We better not have left
5410 any breakpoints in the target program or it'll die when it hits
5411 one. */
5412
5413 static void
5414 remote_detach_1 (int from_tty, inferior *inf)
5415 {
5416 int pid = ptid_get_pid (inferior_ptid);
5417 struct remote_state *rs = get_remote_state ();
5418 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5419 int is_fork_parent;
5420
5421 if (!target_has_execution)
5422 error (_("No process to detach from."));
5423
5424 target_announce_detach (from_tty);
5425
5426 /* Tell the remote target to detach. */
5427 remote_detach_pid (pid);
5428
5429 /* Exit only if this is the only active inferior. */
5430 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5431 puts_filtered (_("Ending remote debugging.\n"));
5432
5433 /* Check to see if we are detaching a fork parent. Note that if we
5434 are detaching a fork child, tp == NULL. */
5435 is_fork_parent = (tp != NULL
5436 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5437
5438 /* If doing detach-on-fork, we don't mourn, because that will delete
5439 breakpoints that should be available for the followed inferior. */
5440 if (!is_fork_parent)
5441 {
5442 /* Save the pid as a string before mourning, since that will
5443 unpush the remote target, and we need the string after. */
5444 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5445
5446 target_mourn_inferior (inferior_ptid);
5447 if (print_inferior_events)
5448 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5449 inf->num, infpid.c_str ());
5450 }
5451 else
5452 {
5453 inferior_ptid = null_ptid;
5454 detach_inferior (pid);
5455 }
5456 }
5457
5458 void
5459 remote_target::detach (inferior *inf, int from_tty)
5460 {
5461 remote_detach_1 (from_tty, inf);
5462 }
5463
5464 void
5465 extended_remote_target::detach (inferior *inf, int from_tty)
5466 {
5467 remote_detach_1 (from_tty, inf);
5468 }
5469
5470 /* Target follow-fork function for remote targets. On entry, and
5471 at return, the current inferior is the fork parent.
5472
5473 Note that although this is currently only used for extended-remote,
5474 it is named remote_follow_fork in anticipation of using it for the
5475 remote target as well. */
5476
5477 int
5478 remote_target::follow_fork (int follow_child, int detach_fork)
5479 {
5480 struct remote_state *rs = get_remote_state ();
5481 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5482
5483 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5484 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5485 {
5486 /* When following the parent and detaching the child, we detach
5487 the child here. For the case of following the child and
5488 detaching the parent, the detach is done in the target-
5489 independent follow fork code in infrun.c. We can't use
5490 target_detach when detaching an unfollowed child because
5491 the client side doesn't know anything about the child. */
5492 if (detach_fork && !follow_child)
5493 {
5494 /* Detach the fork child. */
5495 ptid_t child_ptid;
5496 pid_t child_pid;
5497
5498 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5499 child_pid = ptid_get_pid (child_ptid);
5500
5501 remote_detach_pid (child_pid);
5502 }
5503 }
5504 return 0;
5505 }
5506
5507 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5508 in the program space of the new inferior. On entry and at return the
5509 current inferior is the exec'ing inferior. INF is the new exec'd
5510 inferior, which may be the same as the exec'ing inferior unless
5511 follow-exec-mode is "new". */
5512
5513 void
5514 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5515 {
5516 /* We know that this is a target file name, so if it has the "target:"
5517 prefix we strip it off before saving it in the program space. */
5518 if (is_target_filename (execd_pathname))
5519 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5520
5521 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5522 }
5523
5524 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5525
5526 void
5527 remote_target::disconnect (const char *args, int from_tty)
5528 {
5529 if (args)
5530 error (_("Argument given to \"disconnect\" when remotely debugging."));
5531
5532 /* Make sure we unpush even the extended remote targets. Calling
5533 target_mourn_inferior won't unpush, and remote_mourn won't
5534 unpush if there is more than one inferior left. */
5535 unpush_target (this);
5536 generic_mourn_inferior ();
5537
5538 if (from_tty)
5539 puts_filtered ("Ending remote debugging.\n");
5540 }
5541
5542 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5543 be chatty about it. */
5544
5545 void
5546 extended_remote_target::attach (const char *args, int from_tty)
5547 {
5548 struct remote_state *rs = get_remote_state ();
5549 int pid;
5550 char *wait_status = NULL;
5551
5552 pid = parse_pid_to_attach (args);
5553
5554 /* Remote PID can be freely equal to getpid, do not check it here the same
5555 way as in other targets. */
5556
5557 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5558 error (_("This target does not support attaching to a process"));
5559
5560 if (from_tty)
5561 {
5562 char *exec_file = get_exec_file (0);
5563
5564 if (exec_file)
5565 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5566 target_pid_to_str (pid_to_ptid (pid)));
5567 else
5568 printf_unfiltered (_("Attaching to %s\n"),
5569 target_pid_to_str (pid_to_ptid (pid)));
5570
5571 gdb_flush (gdb_stdout);
5572 }
5573
5574 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5575 putpkt (rs->buf);
5576 getpkt (&rs->buf, &rs->buf_size, 0);
5577
5578 switch (packet_ok (rs->buf,
5579 &remote_protocol_packets[PACKET_vAttach]))
5580 {
5581 case PACKET_OK:
5582 if (!target_is_non_stop_p ())
5583 {
5584 /* Save the reply for later. */
5585 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5586 strcpy (wait_status, rs->buf);
5587 }
5588 else if (strcmp (rs->buf, "OK") != 0)
5589 error (_("Attaching to %s failed with: %s"),
5590 target_pid_to_str (pid_to_ptid (pid)),
5591 rs->buf);
5592 break;
5593 case PACKET_UNKNOWN:
5594 error (_("This target does not support attaching to a process"));
5595 default:
5596 error (_("Attaching to %s failed"),
5597 target_pid_to_str (pid_to_ptid (pid)));
5598 }
5599
5600 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5601
5602 inferior_ptid = pid_to_ptid (pid);
5603
5604 if (target_is_non_stop_p ())
5605 {
5606 struct thread_info *thread;
5607
5608 /* Get list of threads. */
5609 update_thread_list ();
5610
5611 thread = first_thread_of_process (pid);
5612 if (thread)
5613 inferior_ptid = thread->ptid;
5614 else
5615 inferior_ptid = pid_to_ptid (pid);
5616
5617 /* Invalidate our notion of the remote current thread. */
5618 record_currthread (rs, minus_one_ptid);
5619 }
5620 else
5621 {
5622 /* Now, if we have thread information, update inferior_ptid. */
5623 inferior_ptid = remote_current_thread (inferior_ptid);
5624
5625 /* Add the main thread to the thread list. */
5626 thread_info *thr = add_thread_silent (inferior_ptid);
5627 /* Don't consider the thread stopped until we've processed the
5628 saved stop reply. */
5629 set_executing (thr->ptid, true);
5630 }
5631
5632 /* Next, if the target can specify a description, read it. We do
5633 this before anything involving memory or registers. */
5634 target_find_description ();
5635
5636 if (!target_is_non_stop_p ())
5637 {
5638 /* Use the previously fetched status. */
5639 gdb_assert (wait_status != NULL);
5640
5641 if (target_can_async_p ())
5642 {
5643 struct notif_event *reply
5644 = remote_notif_parse (&notif_client_stop, wait_status);
5645
5646 push_stop_reply ((struct stop_reply *) reply);
5647
5648 target_async (1);
5649 }
5650 else
5651 {
5652 gdb_assert (wait_status != NULL);
5653 strcpy (rs->buf, wait_status);
5654 rs->cached_wait_status = 1;
5655 }
5656 }
5657 else
5658 gdb_assert (wait_status == NULL);
5659 }
5660
5661 /* Implementation of the to_post_attach method. */
5662
5663 void
5664 extended_remote_target::post_attach (int pid)
5665 {
5666 /* Get text, data & bss offsets. */
5667 get_offsets ();
5668
5669 /* In certain cases GDB might not have had the chance to start
5670 symbol lookup up until now. This could happen if the debugged
5671 binary is not using shared libraries, the vsyscall page is not
5672 present (on Linux) and the binary itself hadn't changed since the
5673 debugging process was started. */
5674 if (symfile_objfile != NULL)
5675 remote_check_symbols();
5676 }
5677
5678 \f
5679 /* Check for the availability of vCont. This function should also check
5680 the response. */
5681
5682 static void
5683 remote_vcont_probe (struct remote_state *rs)
5684 {
5685 char *buf;
5686
5687 strcpy (rs->buf, "vCont?");
5688 putpkt (rs->buf);
5689 getpkt (&rs->buf, &rs->buf_size, 0);
5690 buf = rs->buf;
5691
5692 /* Make sure that the features we assume are supported. */
5693 if (startswith (buf, "vCont"))
5694 {
5695 char *p = &buf[5];
5696 int support_c, support_C;
5697
5698 rs->supports_vCont.s = 0;
5699 rs->supports_vCont.S = 0;
5700 support_c = 0;
5701 support_C = 0;
5702 rs->supports_vCont.t = 0;
5703 rs->supports_vCont.r = 0;
5704 while (p && *p == ';')
5705 {
5706 p++;
5707 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5708 rs->supports_vCont.s = 1;
5709 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5710 rs->supports_vCont.S = 1;
5711 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5712 support_c = 1;
5713 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5714 support_C = 1;
5715 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5716 rs->supports_vCont.t = 1;
5717 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5718 rs->supports_vCont.r = 1;
5719
5720 p = strchr (p, ';');
5721 }
5722
5723 /* If c, and C are not all supported, we can't use vCont. Clearing
5724 BUF will make packet_ok disable the packet. */
5725 if (!support_c || !support_C)
5726 buf[0] = 0;
5727 }
5728
5729 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5730 }
5731
5732 /* Helper function for building "vCont" resumptions. Write a
5733 resumption to P. ENDP points to one-passed-the-end of the buffer
5734 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5735 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5736 resumed thread should be single-stepped and/or signalled. If PTID
5737 equals minus_one_ptid, then all threads are resumed; if PTID
5738 represents a process, then all threads of the process are resumed;
5739 the thread to be stepped and/or signalled is given in the global
5740 INFERIOR_PTID. */
5741
5742 static char *
5743 append_resumption (char *p, char *endp,
5744 ptid_t ptid, int step, enum gdb_signal siggnal)
5745 {
5746 struct remote_state *rs = get_remote_state ();
5747
5748 if (step && siggnal != GDB_SIGNAL_0)
5749 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5750 else if (step
5751 /* GDB is willing to range step. */
5752 && use_range_stepping
5753 /* Target supports range stepping. */
5754 && rs->supports_vCont.r
5755 /* We don't currently support range stepping multiple
5756 threads with a wildcard (though the protocol allows it,
5757 so stubs shouldn't make an active effort to forbid
5758 it). */
5759 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5760 {
5761 struct thread_info *tp;
5762
5763 if (ptid_equal (ptid, minus_one_ptid))
5764 {
5765 /* If we don't know about the target thread's tid, then
5766 we're resuming magic_null_ptid (see caller). */
5767 tp = find_thread_ptid (magic_null_ptid);
5768 }
5769 else
5770 tp = find_thread_ptid (ptid);
5771 gdb_assert (tp != NULL);
5772
5773 if (tp->control.may_range_step)
5774 {
5775 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5776
5777 p += xsnprintf (p, endp - p, ";r%s,%s",
5778 phex_nz (tp->control.step_range_start,
5779 addr_size),
5780 phex_nz (tp->control.step_range_end,
5781 addr_size));
5782 }
5783 else
5784 p += xsnprintf (p, endp - p, ";s");
5785 }
5786 else if (step)
5787 p += xsnprintf (p, endp - p, ";s");
5788 else if (siggnal != GDB_SIGNAL_0)
5789 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5790 else
5791 p += xsnprintf (p, endp - p, ";c");
5792
5793 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5794 {
5795 ptid_t nptid;
5796
5797 /* All (-1) threads of process. */
5798 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5799
5800 p += xsnprintf (p, endp - p, ":");
5801 p = write_ptid (p, endp, nptid);
5802 }
5803 else if (!ptid_equal (ptid, minus_one_ptid))
5804 {
5805 p += xsnprintf (p, endp - p, ":");
5806 p = write_ptid (p, endp, ptid);
5807 }
5808
5809 return p;
5810 }
5811
5812 /* Clear the thread's private info on resume. */
5813
5814 static void
5815 resume_clear_thread_private_info (struct thread_info *thread)
5816 {
5817 if (thread->priv != NULL)
5818 {
5819 remote_thread_info *priv = get_remote_thread_info (thread);
5820
5821 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5822 priv->watch_data_address = 0;
5823 }
5824 }
5825
5826 /* Append a vCont continue-with-signal action for threads that have a
5827 non-zero stop signal. */
5828
5829 static char *
5830 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5831 {
5832 struct thread_info *thread;
5833
5834 ALL_NON_EXITED_THREADS (thread)
5835 if (ptid_match (thread->ptid, ptid)
5836 && !ptid_equal (inferior_ptid, thread->ptid)
5837 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5838 {
5839 p = append_resumption (p, endp, thread->ptid,
5840 0, thread->suspend.stop_signal);
5841 thread->suspend.stop_signal = GDB_SIGNAL_0;
5842 resume_clear_thread_private_info (thread);
5843 }
5844
5845 return p;
5846 }
5847
5848 /* Set the target running, using the packets that use Hc
5849 (c/s/C/S). */
5850
5851 static void
5852 remote_resume_with_hc (struct target_ops *ops,
5853 ptid_t ptid, int step, enum gdb_signal siggnal)
5854 {
5855 struct remote_state *rs = get_remote_state ();
5856 struct thread_info *thread;
5857 char *buf;
5858
5859 rs->last_sent_signal = siggnal;
5860 rs->last_sent_step = step;
5861
5862 /* The c/s/C/S resume packets use Hc, so set the continue
5863 thread. */
5864 if (ptid_equal (ptid, minus_one_ptid))
5865 set_continue_thread (any_thread_ptid);
5866 else
5867 set_continue_thread (ptid);
5868
5869 ALL_NON_EXITED_THREADS (thread)
5870 resume_clear_thread_private_info (thread);
5871
5872 buf = rs->buf;
5873 if (execution_direction == EXEC_REVERSE)
5874 {
5875 /* We don't pass signals to the target in reverse exec mode. */
5876 if (info_verbose && siggnal != GDB_SIGNAL_0)
5877 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5878 siggnal);
5879
5880 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5881 error (_("Remote reverse-step not supported."));
5882 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5883 error (_("Remote reverse-continue not supported."));
5884
5885 strcpy (buf, step ? "bs" : "bc");
5886 }
5887 else if (siggnal != GDB_SIGNAL_0)
5888 {
5889 buf[0] = step ? 'S' : 'C';
5890 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5891 buf[2] = tohex (((int) siggnal) & 0xf);
5892 buf[3] = '\0';
5893 }
5894 else
5895 strcpy (buf, step ? "s" : "c");
5896
5897 putpkt (buf);
5898 }
5899
5900 /* Resume the remote inferior by using a "vCont" packet. The thread
5901 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5902 resumed thread should be single-stepped and/or signalled. If PTID
5903 equals minus_one_ptid, then all threads are resumed; the thread to
5904 be stepped and/or signalled is given in the global INFERIOR_PTID.
5905 This function returns non-zero iff it resumes the inferior.
5906
5907 This function issues a strict subset of all possible vCont commands
5908 at the moment. */
5909
5910 static int
5911 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5912 {
5913 struct remote_state *rs = get_remote_state ();
5914 char *p;
5915 char *endp;
5916
5917 /* No reverse execution actions defined for vCont. */
5918 if (execution_direction == EXEC_REVERSE)
5919 return 0;
5920
5921 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5922 remote_vcont_probe (rs);
5923
5924 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5925 return 0;
5926
5927 p = rs->buf;
5928 endp = rs->buf + get_remote_packet_size ();
5929
5930 /* If we could generate a wider range of packets, we'd have to worry
5931 about overflowing BUF. Should there be a generic
5932 "multi-part-packet" packet? */
5933
5934 p += xsnprintf (p, endp - p, "vCont");
5935
5936 if (ptid_equal (ptid, magic_null_ptid))
5937 {
5938 /* MAGIC_NULL_PTID means that we don't have any active threads,
5939 so we don't have any TID numbers the inferior will
5940 understand. Make sure to only send forms that do not specify
5941 a TID. */
5942 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5943 }
5944 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5945 {
5946 /* Resume all threads (of all processes, or of a single
5947 process), with preference for INFERIOR_PTID. This assumes
5948 inferior_ptid belongs to the set of all threads we are about
5949 to resume. */
5950 if (step || siggnal != GDB_SIGNAL_0)
5951 {
5952 /* Step inferior_ptid, with or without signal. */
5953 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5954 }
5955
5956 /* Also pass down any pending signaled resumption for other
5957 threads not the current. */
5958 p = append_pending_thread_resumptions (p, endp, ptid);
5959
5960 /* And continue others without a signal. */
5961 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5962 }
5963 else
5964 {
5965 /* Scheduler locking; resume only PTID. */
5966 append_resumption (p, endp, ptid, step, siggnal);
5967 }
5968
5969 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5970 putpkt (rs->buf);
5971
5972 if (target_is_non_stop_p ())
5973 {
5974 /* In non-stop, the stub replies to vCont with "OK". The stop
5975 reply will be reported asynchronously by means of a `%Stop'
5976 notification. */
5977 getpkt (&rs->buf, &rs->buf_size, 0);
5978 if (strcmp (rs->buf, "OK") != 0)
5979 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5980 }
5981
5982 return 1;
5983 }
5984
5985 /* Tell the remote machine to resume. */
5986
5987 void
5988 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5989 {
5990 struct remote_state *rs = get_remote_state ();
5991
5992 /* When connected in non-stop mode, the core resumes threads
5993 individually. Resuming remote threads directly in target_resume
5994 would thus result in sending one packet per thread. Instead, to
5995 minimize roundtrip latency, here we just store the resume
5996 request; the actual remote resumption will be done in
5997 target_commit_resume / remote_commit_resume, where we'll be able
5998 to do vCont action coalescing. */
5999 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6000 {
6001 remote_thread_info *remote_thr;
6002
6003 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
6004 remote_thr = get_remote_thread_info (inferior_ptid);
6005 else
6006 remote_thr = get_remote_thread_info (ptid);
6007
6008 remote_thr->last_resume_step = step;
6009 remote_thr->last_resume_sig = siggnal;
6010 return;
6011 }
6012
6013 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6014 (explained in remote-notif.c:handle_notification) so
6015 remote_notif_process is not called. We need find a place where
6016 it is safe to start a 'vNotif' sequence. It is good to do it
6017 before resuming inferior, because inferior was stopped and no RSP
6018 traffic at that moment. */
6019 if (!target_is_non_stop_p ())
6020 remote_notif_process (rs->notif_state, &notif_client_stop);
6021
6022 rs->last_resume_exec_dir = ::execution_direction;
6023
6024 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6025 if (!remote_resume_with_vcont (ptid, step, siggnal))
6026 remote_resume_with_hc (this, ptid, step, siggnal);
6027
6028 /* We are about to start executing the inferior, let's register it
6029 with the event loop. NOTE: this is the one place where all the
6030 execution commands end up. We could alternatively do this in each
6031 of the execution commands in infcmd.c. */
6032 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6033 into infcmd.c in order to allow inferior function calls to work
6034 NOT asynchronously. */
6035 if (target_can_async_p ())
6036 target_async (1);
6037
6038 /* We've just told the target to resume. The remote server will
6039 wait for the inferior to stop, and then send a stop reply. In
6040 the mean time, we can't start another command/query ourselves
6041 because the stub wouldn't be ready to process it. This applies
6042 only to the base all-stop protocol, however. In non-stop (which
6043 only supports vCont), the stub replies with an "OK", and is
6044 immediate able to process further serial input. */
6045 if (!target_is_non_stop_p ())
6046 rs->waiting_for_stop_reply = 1;
6047 }
6048
6049 static void check_pending_events_prevent_wildcard_vcont
6050 (int *may_global_wildcard_vcont);
6051 static int is_pending_fork_parent_thread (struct thread_info *thread);
6052
6053 /* Private per-inferior info for target remote processes. */
6054
6055 struct remote_inferior : public private_inferior
6056 {
6057 /* Whether we can send a wildcard vCont for this process. */
6058 bool may_wildcard_vcont = true;
6059 };
6060
6061 /* Get the remote private inferior data associated to INF. */
6062
6063 static remote_inferior *
6064 get_remote_inferior (inferior *inf)
6065 {
6066 if (inf->priv == NULL)
6067 inf->priv.reset (new remote_inferior);
6068
6069 return static_cast<remote_inferior *> (inf->priv.get ());
6070 }
6071
6072 /* Structure used to track the construction of a vCont packet in the
6073 outgoing packet buffer. This is used to send multiple vCont
6074 packets if we have more actions than would fit a single packet. */
6075
6076 struct vcont_builder
6077 {
6078 /* Pointer to the first action. P points here if no action has been
6079 appended yet. */
6080 char *first_action;
6081
6082 /* Where the next action will be appended. */
6083 char *p;
6084
6085 /* The end of the buffer. Must never write past this. */
6086 char *endp;
6087 };
6088
6089 /* Prepare the outgoing buffer for a new vCont packet. */
6090
6091 static void
6092 vcont_builder_restart (struct vcont_builder *builder)
6093 {
6094 struct remote_state *rs = get_remote_state ();
6095
6096 builder->p = rs->buf;
6097 builder->endp = rs->buf + get_remote_packet_size ();
6098 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
6099 builder->first_action = builder->p;
6100 }
6101
6102 /* If the vCont packet being built has any action, send it to the
6103 remote end. */
6104
6105 static void
6106 vcont_builder_flush (struct vcont_builder *builder)
6107 {
6108 struct remote_state *rs;
6109
6110 if (builder->p == builder->first_action)
6111 return;
6112
6113 rs = get_remote_state ();
6114 putpkt (rs->buf);
6115 getpkt (&rs->buf, &rs->buf_size, 0);
6116 if (strcmp (rs->buf, "OK") != 0)
6117 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6118 }
6119
6120 /* The largest action is range-stepping, with its two addresses. This
6121 is more than sufficient. If a new, bigger action is created, it'll
6122 quickly trigger a failed assertion in append_resumption (and we'll
6123 just bump this). */
6124 #define MAX_ACTION_SIZE 200
6125
6126 /* Append a new vCont action in the outgoing packet being built. If
6127 the action doesn't fit the packet along with previous actions, push
6128 what we've got so far to the remote end and start over a new vCont
6129 packet (with the new action). */
6130
6131 static void
6132 vcont_builder_push_action (struct vcont_builder *builder,
6133 ptid_t ptid, int step, enum gdb_signal siggnal)
6134 {
6135 char buf[MAX_ACTION_SIZE + 1];
6136 char *endp;
6137 size_t rsize;
6138
6139 endp = append_resumption (buf, buf + sizeof (buf),
6140 ptid, step, siggnal);
6141
6142 /* Check whether this new action would fit in the vCont packet along
6143 with previous actions. If not, send what we've got so far and
6144 start a new vCont packet. */
6145 rsize = endp - buf;
6146 if (rsize > builder->endp - builder->p)
6147 {
6148 vcont_builder_flush (builder);
6149 vcont_builder_restart (builder);
6150
6151 /* Should now fit. */
6152 gdb_assert (rsize <= builder->endp - builder->p);
6153 }
6154
6155 memcpy (builder->p, buf, rsize);
6156 builder->p += rsize;
6157 *builder->p = '\0';
6158 }
6159
6160 /* to_commit_resume implementation. */
6161
6162 void
6163 remote_target::commit_resume ()
6164 {
6165 struct inferior *inf;
6166 struct thread_info *tp;
6167 int any_process_wildcard;
6168 int may_global_wildcard_vcont;
6169 struct vcont_builder vcont_builder;
6170
6171 /* If connected in all-stop mode, we'd send the remote resume
6172 request directly from remote_resume. Likewise if
6173 reverse-debugging, as there are no defined vCont actions for
6174 reverse execution. */
6175 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6176 return;
6177
6178 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6179 instead of resuming all threads of each process individually.
6180 However, if any thread of a process must remain halted, we can't
6181 send wildcard resumes and must send one action per thread.
6182
6183 Care must be taken to not resume threads/processes the server
6184 side already told us are stopped, but the core doesn't know about
6185 yet, because the events are still in the vStopped notification
6186 queue. For example:
6187
6188 #1 => vCont s:p1.1;c
6189 #2 <= OK
6190 #3 <= %Stopped T05 p1.1
6191 #4 => vStopped
6192 #5 <= T05 p1.2
6193 #6 => vStopped
6194 #7 <= OK
6195 #8 (infrun handles the stop for p1.1 and continues stepping)
6196 #9 => vCont s:p1.1;c
6197
6198 The last vCont above would resume thread p1.2 by mistake, because
6199 the server has no idea that the event for p1.2 had not been
6200 handled yet.
6201
6202 The server side must similarly ignore resume actions for the
6203 thread that has a pending %Stopped notification (and any other
6204 threads with events pending), until GDB acks the notification
6205 with vStopped. Otherwise, e.g., the following case is
6206 mishandled:
6207
6208 #1 => g (or any other packet)
6209 #2 <= [registers]
6210 #3 <= %Stopped T05 p1.2
6211 #4 => vCont s:p1.1;c
6212 #5 <= OK
6213
6214 Above, the server must not resume thread p1.2. GDB can't know
6215 that p1.2 stopped until it acks the %Stopped notification, and
6216 since from GDB's perspective all threads should be running, it
6217 sends a "c" action.
6218
6219 Finally, special care must also be given to handling fork/vfork
6220 events. A (v)fork event actually tells us that two processes
6221 stopped -- the parent and the child. Until we follow the fork,
6222 we must not resume the child. Therefore, if we have a pending
6223 fork follow, we must not send a global wildcard resume action
6224 (vCont;c). We can still send process-wide wildcards though. */
6225
6226 /* Start by assuming a global wildcard (vCont;c) is possible. */
6227 may_global_wildcard_vcont = 1;
6228
6229 /* And assume every process is individually wildcard-able too. */
6230 ALL_NON_EXITED_INFERIORS (inf)
6231 {
6232 remote_inferior *priv = get_remote_inferior (inf);
6233
6234 priv->may_wildcard_vcont = true;
6235 }
6236
6237 /* Check for any pending events (not reported or processed yet) and
6238 disable process and global wildcard resumes appropriately. */
6239 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6240
6241 ALL_NON_EXITED_THREADS (tp)
6242 {
6243 /* If a thread of a process is not meant to be resumed, then we
6244 can't wildcard that process. */
6245 if (!tp->executing)
6246 {
6247 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6248
6249 /* And if we can't wildcard a process, we can't wildcard
6250 everything either. */
6251 may_global_wildcard_vcont = 0;
6252 continue;
6253 }
6254
6255 /* If a thread is the parent of an unfollowed fork, then we
6256 can't do a global wildcard, as that would resume the fork
6257 child. */
6258 if (is_pending_fork_parent_thread (tp))
6259 may_global_wildcard_vcont = 0;
6260 }
6261
6262 /* Now let's build the vCont packet(s). Actions must be appended
6263 from narrower to wider scopes (thread -> process -> global). If
6264 we end up with too many actions for a single packet vcont_builder
6265 flushes the current vCont packet to the remote side and starts a
6266 new one. */
6267 vcont_builder_restart (&vcont_builder);
6268
6269 /* Threads first. */
6270 ALL_NON_EXITED_THREADS (tp)
6271 {
6272 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6273
6274 if (!tp->executing || remote_thr->vcont_resumed)
6275 continue;
6276
6277 gdb_assert (!thread_is_in_step_over_chain (tp));
6278
6279 if (!remote_thr->last_resume_step
6280 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6281 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6282 {
6283 /* We'll send a wildcard resume instead. */
6284 remote_thr->vcont_resumed = 1;
6285 continue;
6286 }
6287
6288 vcont_builder_push_action (&vcont_builder, tp->ptid,
6289 remote_thr->last_resume_step,
6290 remote_thr->last_resume_sig);
6291 remote_thr->vcont_resumed = 1;
6292 }
6293
6294 /* Now check whether we can send any process-wide wildcard. This is
6295 to avoid sending a global wildcard in the case nothing is
6296 supposed to be resumed. */
6297 any_process_wildcard = 0;
6298
6299 ALL_NON_EXITED_INFERIORS (inf)
6300 {
6301 if (get_remote_inferior (inf)->may_wildcard_vcont)
6302 {
6303 any_process_wildcard = 1;
6304 break;
6305 }
6306 }
6307
6308 if (any_process_wildcard)
6309 {
6310 /* If all processes are wildcard-able, then send a single "c"
6311 action, otherwise, send an "all (-1) threads of process"
6312 continue action for each running process, if any. */
6313 if (may_global_wildcard_vcont)
6314 {
6315 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6316 0, GDB_SIGNAL_0);
6317 }
6318 else
6319 {
6320 ALL_NON_EXITED_INFERIORS (inf)
6321 {
6322 if (get_remote_inferior (inf)->may_wildcard_vcont)
6323 {
6324 vcont_builder_push_action (&vcont_builder,
6325 pid_to_ptid (inf->pid),
6326 0, GDB_SIGNAL_0);
6327 }
6328 }
6329 }
6330 }
6331
6332 vcont_builder_flush (&vcont_builder);
6333 }
6334
6335 \f
6336
6337 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6338 thread, all threads of a remote process, or all threads of all
6339 processes. */
6340
6341 static void
6342 remote_stop_ns (ptid_t ptid)
6343 {
6344 struct remote_state *rs = get_remote_state ();
6345 char *p = rs->buf;
6346 char *endp = rs->buf + get_remote_packet_size ();
6347
6348 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6349 remote_vcont_probe (rs);
6350
6351 if (!rs->supports_vCont.t)
6352 error (_("Remote server does not support stopping threads"));
6353
6354 if (ptid_equal (ptid, minus_one_ptid)
6355 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6356 p += xsnprintf (p, endp - p, "vCont;t");
6357 else
6358 {
6359 ptid_t nptid;
6360
6361 p += xsnprintf (p, endp - p, "vCont;t:");
6362
6363 if (ptid_is_pid (ptid))
6364 /* All (-1) threads of process. */
6365 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6366 else
6367 {
6368 /* Small optimization: if we already have a stop reply for
6369 this thread, no use in telling the stub we want this
6370 stopped. */
6371 if (peek_stop_reply (ptid))
6372 return;
6373
6374 nptid = ptid;
6375 }
6376
6377 write_ptid (p, endp, nptid);
6378 }
6379
6380 /* In non-stop, we get an immediate OK reply. The stop reply will
6381 come in asynchronously by notification. */
6382 putpkt (rs->buf);
6383 getpkt (&rs->buf, &rs->buf_size, 0);
6384 if (strcmp (rs->buf, "OK") != 0)
6385 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6386 }
6387
6388 /* All-stop version of target_interrupt. Sends a break or a ^C to
6389 interrupt the remote target. It is undefined which thread of which
6390 process reports the interrupt. */
6391
6392 static void
6393 remote_interrupt_as (void)
6394 {
6395 struct remote_state *rs = get_remote_state ();
6396
6397 rs->ctrlc_pending_p = 1;
6398
6399 /* If the inferior is stopped already, but the core didn't know
6400 about it yet, just ignore the request. The cached wait status
6401 will be collected in remote_wait. */
6402 if (rs->cached_wait_status)
6403 return;
6404
6405 /* Send interrupt_sequence to remote target. */
6406 send_interrupt_sequence ();
6407 }
6408
6409 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6410 the remote target. It is undefined which thread of which process
6411 reports the interrupt. Throws an error if the packet is not
6412 supported by the server. */
6413
6414 static void
6415 remote_interrupt_ns (void)
6416 {
6417 struct remote_state *rs = get_remote_state ();
6418 char *p = rs->buf;
6419 char *endp = rs->buf + get_remote_packet_size ();
6420
6421 xsnprintf (p, endp - p, "vCtrlC");
6422
6423 /* In non-stop, we get an immediate OK reply. The stop reply will
6424 come in asynchronously by notification. */
6425 putpkt (rs->buf);
6426 getpkt (&rs->buf, &rs->buf_size, 0);
6427
6428 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6429 {
6430 case PACKET_OK:
6431 break;
6432 case PACKET_UNKNOWN:
6433 error (_("No support for interrupting the remote target."));
6434 case PACKET_ERROR:
6435 error (_("Interrupting target failed: %s"), rs->buf);
6436 }
6437 }
6438
6439 /* Implement the to_stop function for the remote targets. */
6440
6441 void
6442 remote_target::stop (ptid_t ptid)
6443 {
6444 if (remote_debug)
6445 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6446
6447 if (target_is_non_stop_p ())
6448 remote_stop_ns (ptid);
6449 else
6450 {
6451 /* We don't currently have a way to transparently pause the
6452 remote target in all-stop mode. Interrupt it instead. */
6453 remote_interrupt_as ();
6454 }
6455 }
6456
6457 /* Implement the to_interrupt function for the remote targets. */
6458
6459 void
6460 remote_target::interrupt ()
6461 {
6462 if (remote_debug)
6463 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6464
6465 if (target_is_non_stop_p ())
6466 remote_interrupt_ns ();
6467 else
6468 remote_interrupt_as ();
6469 }
6470
6471 /* Implement the to_pass_ctrlc function for the remote targets. */
6472
6473 void
6474 remote_target::pass_ctrlc ()
6475 {
6476 struct remote_state *rs = get_remote_state ();
6477
6478 if (remote_debug)
6479 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6480
6481 /* If we're starting up, we're not fully synced yet. Quit
6482 immediately. */
6483 if (rs->starting_up)
6484 quit ();
6485 /* If ^C has already been sent once, offer to disconnect. */
6486 else if (rs->ctrlc_pending_p)
6487 interrupt_query ();
6488 else
6489 target_interrupt ();
6490 }
6491
6492 /* Ask the user what to do when an interrupt is received. */
6493
6494 static void
6495 interrupt_query (void)
6496 {
6497 struct remote_state *rs = get_remote_state ();
6498
6499 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6500 {
6501 if (query (_("The target is not responding to interrupt requests.\n"
6502 "Stop debugging it? ")))
6503 {
6504 remote_unpush_target ();
6505 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6506 }
6507 }
6508 else
6509 {
6510 if (query (_("Interrupted while waiting for the program.\n"
6511 "Give up waiting? ")))
6512 quit ();
6513 }
6514 }
6515
6516 /* Enable/disable target terminal ownership. Most targets can use
6517 terminal groups to control terminal ownership. Remote targets are
6518 different in that explicit transfer of ownership to/from GDB/target
6519 is required. */
6520
6521 void
6522 remote_target::terminal_inferior ()
6523 {
6524 /* NOTE: At this point we could also register our selves as the
6525 recipient of all input. Any characters typed could then be
6526 passed on down to the target. */
6527 }
6528
6529 void
6530 remote_target::terminal_ours ()
6531 {
6532 }
6533
6534 static void
6535 remote_console_output (char *msg)
6536 {
6537 char *p;
6538
6539 for (p = msg; p[0] && p[1]; p += 2)
6540 {
6541 char tb[2];
6542 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6543
6544 tb[0] = c;
6545 tb[1] = 0;
6546 fputs_unfiltered (tb, gdb_stdtarg);
6547 }
6548 gdb_flush (gdb_stdtarg);
6549 }
6550
6551 DEF_VEC_O(cached_reg_t);
6552
6553 typedef struct stop_reply
6554 {
6555 struct notif_event base;
6556
6557 /* The identifier of the thread about this event */
6558 ptid_t ptid;
6559
6560 /* The remote state this event is associated with. When the remote
6561 connection, represented by a remote_state object, is closed,
6562 all the associated stop_reply events should be released. */
6563 struct remote_state *rs;
6564
6565 struct target_waitstatus ws;
6566
6567 /* The architecture associated with the expedited registers. */
6568 gdbarch *arch;
6569
6570 /* Expedited registers. This makes remote debugging a bit more
6571 efficient for those targets that provide critical registers as
6572 part of their normal status mechanism (as another roundtrip to
6573 fetch them is avoided). */
6574 VEC(cached_reg_t) *regcache;
6575
6576 enum target_stop_reason stop_reason;
6577
6578 CORE_ADDR watch_data_address;
6579
6580 int core;
6581 } *stop_reply_p;
6582
6583 DECLARE_QUEUE_P (stop_reply_p);
6584 DEFINE_QUEUE_P (stop_reply_p);
6585 /* The list of already fetched and acknowledged stop events. This
6586 queue is used for notification Stop, and other notifications
6587 don't need queue for their events, because the notification events
6588 of Stop can't be consumed immediately, so that events should be
6589 queued first, and be consumed by remote_wait_{ns,as} one per
6590 time. Other notifications can consume their events immediately,
6591 so queue is not needed for them. */
6592 static QUEUE (stop_reply_p) *stop_reply_queue;
6593
6594 static void
6595 stop_reply_xfree (struct stop_reply *r)
6596 {
6597 notif_event_xfree ((struct notif_event *) r);
6598 }
6599
6600 /* Return the length of the stop reply queue. */
6601
6602 static int
6603 stop_reply_queue_length (void)
6604 {
6605 return QUEUE_length (stop_reply_p, stop_reply_queue);
6606 }
6607
6608 static void
6609 remote_notif_stop_parse (struct notif_client *self, char *buf,
6610 struct notif_event *event)
6611 {
6612 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6613 }
6614
6615 static void
6616 remote_notif_stop_ack (struct notif_client *self, char *buf,
6617 struct notif_event *event)
6618 {
6619 struct stop_reply *stop_reply = (struct stop_reply *) event;
6620
6621 /* acknowledge */
6622 putpkt (self->ack_command);
6623
6624 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6625 /* We got an unknown stop reply. */
6626 error (_("Unknown stop reply"));
6627
6628 push_stop_reply (stop_reply);
6629 }
6630
6631 static int
6632 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6633 {
6634 /* We can't get pending events in remote_notif_process for
6635 notification stop, and we have to do this in remote_wait_ns
6636 instead. If we fetch all queued events from stub, remote stub
6637 may exit and we have no chance to process them back in
6638 remote_wait_ns. */
6639 mark_async_event_handler (remote_async_inferior_event_token);
6640 return 0;
6641 }
6642
6643 static void
6644 stop_reply_dtr (struct notif_event *event)
6645 {
6646 struct stop_reply *r = (struct stop_reply *) event;
6647 cached_reg_t *reg;
6648 int ix;
6649
6650 for (ix = 0;
6651 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6652 ix++)
6653 xfree (reg->data);
6654
6655 VEC_free (cached_reg_t, r->regcache);
6656 }
6657
6658 static struct notif_event *
6659 remote_notif_stop_alloc_reply (void)
6660 {
6661 /* We cast to a pointer to the "base class". */
6662 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6663
6664 r->dtr = stop_reply_dtr;
6665
6666 return r;
6667 }
6668
6669 /* A client of notification Stop. */
6670
6671 struct notif_client notif_client_stop =
6672 {
6673 "Stop",
6674 "vStopped",
6675 remote_notif_stop_parse,
6676 remote_notif_stop_ack,
6677 remote_notif_stop_can_get_pending_events,
6678 remote_notif_stop_alloc_reply,
6679 REMOTE_NOTIF_STOP,
6680 };
6681
6682 /* A parameter to pass data in and out. */
6683
6684 struct queue_iter_param
6685 {
6686 void *input;
6687 struct stop_reply *output;
6688 };
6689
6690 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6691 the pid of the process that owns the threads we want to check, or
6692 -1 if we want to check all threads. */
6693
6694 static int
6695 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6696 ptid_t thread_ptid)
6697 {
6698 if (ws->kind == TARGET_WAITKIND_FORKED
6699 || ws->kind == TARGET_WAITKIND_VFORKED)
6700 {
6701 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6702 return 1;
6703 }
6704
6705 return 0;
6706 }
6707
6708 /* Return the thread's pending status used to determine whether the
6709 thread is a fork parent stopped at a fork event. */
6710
6711 static struct target_waitstatus *
6712 thread_pending_fork_status (struct thread_info *thread)
6713 {
6714 if (thread->suspend.waitstatus_pending_p)
6715 return &thread->suspend.waitstatus;
6716 else
6717 return &thread->pending_follow;
6718 }
6719
6720 /* Determine if THREAD is a pending fork parent thread. */
6721
6722 static int
6723 is_pending_fork_parent_thread (struct thread_info *thread)
6724 {
6725 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6726 int pid = -1;
6727
6728 return is_pending_fork_parent (ws, pid, thread->ptid);
6729 }
6730
6731 /* Check whether EVENT is a fork event, and if it is, remove the
6732 fork child from the context list passed in DATA. */
6733
6734 static int
6735 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6736 QUEUE_ITER (stop_reply_p) *iter,
6737 stop_reply_p event,
6738 void *data)
6739 {
6740 struct queue_iter_param *param = (struct queue_iter_param *) data;
6741 struct threads_listing_context *context
6742 = (struct threads_listing_context *) param->input;
6743
6744 if (event->ws.kind == TARGET_WAITKIND_FORKED
6745 || event->ws.kind == TARGET_WAITKIND_VFORKED
6746 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6747 context->remove_thread (event->ws.value.related_pid);
6748
6749 return 1;
6750 }
6751
6752 /* If CONTEXT contains any fork child threads that have not been
6753 reported yet, remove them from the CONTEXT list. If such a
6754 thread exists it is because we are stopped at a fork catchpoint
6755 and have not yet called follow_fork, which will set up the
6756 host-side data structures for the new process. */
6757
6758 static void
6759 remove_new_fork_children (struct threads_listing_context *context)
6760 {
6761 struct thread_info * thread;
6762 int pid = -1;
6763 struct notif_client *notif = &notif_client_stop;
6764 struct queue_iter_param param;
6765
6766 /* For any threads stopped at a fork event, remove the corresponding
6767 fork child threads from the CONTEXT list. */
6768 ALL_NON_EXITED_THREADS (thread)
6769 {
6770 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6771
6772 if (is_pending_fork_parent (ws, pid, thread->ptid))
6773 context->remove_thread (ws->value.related_pid);
6774 }
6775
6776 /* Check for any pending fork events (not reported or processed yet)
6777 in process PID and remove those fork child threads from the
6778 CONTEXT list as well. */
6779 remote_notif_get_pending_events (notif);
6780 param.input = context;
6781 param.output = NULL;
6782 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6783 remove_child_of_pending_fork, &param);
6784 }
6785
6786 /* Check whether EVENT would prevent a global or process wildcard
6787 vCont action. */
6788
6789 static int
6790 check_pending_event_prevents_wildcard_vcont_callback
6791 (QUEUE (stop_reply_p) *q,
6792 QUEUE_ITER (stop_reply_p) *iter,
6793 stop_reply_p event,
6794 void *data)
6795 {
6796 struct inferior *inf;
6797 int *may_global_wildcard_vcont = (int *) data;
6798
6799 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6800 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6801 return 1;
6802
6803 if (event->ws.kind == TARGET_WAITKIND_FORKED
6804 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6805 *may_global_wildcard_vcont = 0;
6806
6807 inf = find_inferior_ptid (event->ptid);
6808
6809 /* This may be the first time we heard about this process.
6810 Regardless, we must not do a global wildcard resume, otherwise
6811 we'd resume this process too. */
6812 *may_global_wildcard_vcont = 0;
6813 if (inf != NULL)
6814 get_remote_inferior (inf)->may_wildcard_vcont = false;
6815
6816 return 1;
6817 }
6818
6819 /* Check whether any event pending in the vStopped queue would prevent
6820 a global or process wildcard vCont action. Clear
6821 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6822 and clear the event inferior's may_wildcard_vcont flag if we can't
6823 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6824
6825 static void
6826 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6827 {
6828 struct notif_client *notif = &notif_client_stop;
6829
6830 remote_notif_get_pending_events (notif);
6831 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6832 check_pending_event_prevents_wildcard_vcont_callback,
6833 may_global_wildcard);
6834 }
6835
6836 /* Remove stop replies in the queue if its pid is equal to the given
6837 inferior's pid. */
6838
6839 static int
6840 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6841 QUEUE_ITER (stop_reply_p) *iter,
6842 stop_reply_p event,
6843 void *data)
6844 {
6845 struct queue_iter_param *param = (struct queue_iter_param *) data;
6846 struct inferior *inf = (struct inferior *) param->input;
6847
6848 if (ptid_get_pid (event->ptid) == inf->pid)
6849 {
6850 stop_reply_xfree (event);
6851 QUEUE_remove_elem (stop_reply_p, q, iter);
6852 }
6853
6854 return 1;
6855 }
6856
6857 /* Discard all pending stop replies of inferior INF. */
6858
6859 static void
6860 discard_pending_stop_replies (struct inferior *inf)
6861 {
6862 struct queue_iter_param param;
6863 struct stop_reply *reply;
6864 struct remote_state *rs = get_remote_state ();
6865 struct remote_notif_state *rns = rs->notif_state;
6866
6867 /* This function can be notified when an inferior exists. When the
6868 target is not remote, the notification state is NULL. */
6869 if (rs->remote_desc == NULL)
6870 return;
6871
6872 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6873
6874 /* Discard the in-flight notification. */
6875 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6876 {
6877 stop_reply_xfree (reply);
6878 rns->pending_event[notif_client_stop.id] = NULL;
6879 }
6880
6881 param.input = inf;
6882 param.output = NULL;
6883 /* Discard the stop replies we have already pulled with
6884 vStopped. */
6885 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6886 remove_stop_reply_for_inferior, &param);
6887 }
6888
6889 /* If its remote state is equal to the given remote state,
6890 remove EVENT from the stop reply queue. */
6891
6892 static int
6893 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6894 QUEUE_ITER (stop_reply_p) *iter,
6895 stop_reply_p event,
6896 void *data)
6897 {
6898 struct queue_iter_param *param = (struct queue_iter_param *) data;
6899 struct remote_state *rs = (struct remote_state *) param->input;
6900
6901 if (event->rs == rs)
6902 {
6903 stop_reply_xfree (event);
6904 QUEUE_remove_elem (stop_reply_p, q, iter);
6905 }
6906
6907 return 1;
6908 }
6909
6910 /* Discard the stop replies for RS in stop_reply_queue. */
6911
6912 static void
6913 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6914 {
6915 struct queue_iter_param param;
6916
6917 param.input = rs;
6918 param.output = NULL;
6919 /* Discard the stop replies we have already pulled with
6920 vStopped. */
6921 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6922 remove_stop_reply_of_remote_state, &param);
6923 }
6924
6925 /* A parameter to pass data in and out. */
6926
6927 static int
6928 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6929 QUEUE_ITER (stop_reply_p) *iter,
6930 stop_reply_p event,
6931 void *data)
6932 {
6933 struct queue_iter_param *param = (struct queue_iter_param *) data;
6934 ptid_t *ptid = (ptid_t *) param->input;
6935
6936 if (ptid_match (event->ptid, *ptid))
6937 {
6938 param->output = event;
6939 QUEUE_remove_elem (stop_reply_p, q, iter);
6940 return 0;
6941 }
6942
6943 return 1;
6944 }
6945
6946 /* Remove the first reply in 'stop_reply_queue' which matches
6947 PTID. */
6948
6949 static struct stop_reply *
6950 remote_notif_remove_queued_reply (ptid_t ptid)
6951 {
6952 struct queue_iter_param param;
6953
6954 param.input = &ptid;
6955 param.output = NULL;
6956
6957 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6958 remote_notif_remove_once_on_match, &param);
6959 if (notif_debug)
6960 fprintf_unfiltered (gdb_stdlog,
6961 "notif: discard queued event: 'Stop' in %s\n",
6962 target_pid_to_str (ptid));
6963
6964 return param.output;
6965 }
6966
6967 /* Look for a queued stop reply belonging to PTID. If one is found,
6968 remove it from the queue, and return it. Returns NULL if none is
6969 found. If there are still queued events left to process, tell the
6970 event loop to get back to target_wait soon. */
6971
6972 static struct stop_reply *
6973 queued_stop_reply (ptid_t ptid)
6974 {
6975 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6976
6977 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6978 /* There's still at least an event left. */
6979 mark_async_event_handler (remote_async_inferior_event_token);
6980
6981 return r;
6982 }
6983
6984 /* Push a fully parsed stop reply in the stop reply queue. Since we
6985 know that we now have at least one queued event left to pass to the
6986 core side, tell the event loop to get back to target_wait soon. */
6987
6988 static void
6989 push_stop_reply (struct stop_reply *new_event)
6990 {
6991 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6992
6993 if (notif_debug)
6994 fprintf_unfiltered (gdb_stdlog,
6995 "notif: push 'Stop' %s to queue %d\n",
6996 target_pid_to_str (new_event->ptid),
6997 QUEUE_length (stop_reply_p,
6998 stop_reply_queue));
6999
7000 mark_async_event_handler (remote_async_inferior_event_token);
7001 }
7002
7003 static int
7004 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
7005 QUEUE_ITER (stop_reply_p) *iter,
7006 struct stop_reply *event,
7007 void *data)
7008 {
7009 ptid_t *ptid = (ptid_t *) data;
7010
7011 return !(ptid_equal (*ptid, event->ptid)
7012 && event->ws.kind == TARGET_WAITKIND_STOPPED);
7013 }
7014
7015 /* Returns true if we have a stop reply for PTID. */
7016
7017 static int
7018 peek_stop_reply (ptid_t ptid)
7019 {
7020 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
7021 stop_reply_match_ptid_and_ws, &ptid);
7022 }
7023
7024 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7025 starting with P and ending with PEND matches PREFIX. */
7026
7027 static int
7028 strprefix (const char *p, const char *pend, const char *prefix)
7029 {
7030 for ( ; p < pend; p++, prefix++)
7031 if (*p != *prefix)
7032 return 0;
7033 return *prefix == '\0';
7034 }
7035
7036 /* Parse the stop reply in BUF. Either the function succeeds, and the
7037 result is stored in EVENT, or throws an error. */
7038
7039 static void
7040 remote_parse_stop_reply (char *buf, struct stop_reply *event)
7041 {
7042 remote_arch_state *rsa = NULL;
7043 ULONGEST addr;
7044 const char *p;
7045 int skipregs = 0;
7046
7047 event->ptid = null_ptid;
7048 event->rs = get_remote_state ();
7049 event->ws.kind = TARGET_WAITKIND_IGNORE;
7050 event->ws.value.integer = 0;
7051 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7052 event->regcache = NULL;
7053 event->core = -1;
7054
7055 switch (buf[0])
7056 {
7057 case 'T': /* Status with PC, SP, FP, ... */
7058 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7059 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7060 ss = signal number
7061 n... = register number
7062 r... = register contents
7063 */
7064
7065 p = &buf[3]; /* after Txx */
7066 while (*p)
7067 {
7068 const char *p1;
7069 int fieldsize;
7070
7071 p1 = strchr (p, ':');
7072 if (p1 == NULL)
7073 error (_("Malformed packet(a) (missing colon): %s\n\
7074 Packet: '%s'\n"),
7075 p, buf);
7076 if (p == p1)
7077 error (_("Malformed packet(a) (missing register number): %s\n\
7078 Packet: '%s'\n"),
7079 p, buf);
7080
7081 /* Some "registers" are actually extended stop information.
7082 Note if you're adding a new entry here: GDB 7.9 and
7083 earlier assume that all register "numbers" that start
7084 with an hex digit are real register numbers. Make sure
7085 the server only sends such a packet if it knows the
7086 client understands it. */
7087
7088 if (strprefix (p, p1, "thread"))
7089 event->ptid = read_ptid (++p1, &p);
7090 else if (strprefix (p, p1, "syscall_entry"))
7091 {
7092 ULONGEST sysno;
7093
7094 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7095 p = unpack_varlen_hex (++p1, &sysno);
7096 event->ws.value.syscall_number = (int) sysno;
7097 }
7098 else if (strprefix (p, p1, "syscall_return"))
7099 {
7100 ULONGEST sysno;
7101
7102 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7103 p = unpack_varlen_hex (++p1, &sysno);
7104 event->ws.value.syscall_number = (int) sysno;
7105 }
7106 else if (strprefix (p, p1, "watch")
7107 || strprefix (p, p1, "rwatch")
7108 || strprefix (p, p1, "awatch"))
7109 {
7110 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7111 p = unpack_varlen_hex (++p1, &addr);
7112 event->watch_data_address = (CORE_ADDR) addr;
7113 }
7114 else if (strprefix (p, p1, "swbreak"))
7115 {
7116 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7117
7118 /* Make sure the stub doesn't forget to indicate support
7119 with qSupported. */
7120 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7121 error (_("Unexpected swbreak stop reason"));
7122
7123 /* The value part is documented as "must be empty",
7124 though we ignore it, in case we ever decide to make
7125 use of it in a backward compatible way. */
7126 p = strchrnul (p1 + 1, ';');
7127 }
7128 else if (strprefix (p, p1, "hwbreak"))
7129 {
7130 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7131
7132 /* Make sure the stub doesn't forget to indicate support
7133 with qSupported. */
7134 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7135 error (_("Unexpected hwbreak stop reason"));
7136
7137 /* See above. */
7138 p = strchrnul (p1 + 1, ';');
7139 }
7140 else if (strprefix (p, p1, "library"))
7141 {
7142 event->ws.kind = TARGET_WAITKIND_LOADED;
7143 p = strchrnul (p1 + 1, ';');
7144 }
7145 else if (strprefix (p, p1, "replaylog"))
7146 {
7147 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7148 /* p1 will indicate "begin" or "end", but it makes
7149 no difference for now, so ignore it. */
7150 p = strchrnul (p1 + 1, ';');
7151 }
7152 else if (strprefix (p, p1, "core"))
7153 {
7154 ULONGEST c;
7155
7156 p = unpack_varlen_hex (++p1, &c);
7157 event->core = c;
7158 }
7159 else if (strprefix (p, p1, "fork"))
7160 {
7161 event->ws.value.related_pid = read_ptid (++p1, &p);
7162 event->ws.kind = TARGET_WAITKIND_FORKED;
7163 }
7164 else if (strprefix (p, p1, "vfork"))
7165 {
7166 event->ws.value.related_pid = read_ptid (++p1, &p);
7167 event->ws.kind = TARGET_WAITKIND_VFORKED;
7168 }
7169 else if (strprefix (p, p1, "vforkdone"))
7170 {
7171 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7172 p = strchrnul (p1 + 1, ';');
7173 }
7174 else if (strprefix (p, p1, "exec"))
7175 {
7176 ULONGEST ignored;
7177 char pathname[PATH_MAX];
7178 int pathlen;
7179
7180 /* Determine the length of the execd pathname. */
7181 p = unpack_varlen_hex (++p1, &ignored);
7182 pathlen = (p - p1) / 2;
7183
7184 /* Save the pathname for event reporting and for
7185 the next run command. */
7186 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7187 pathname[pathlen] = '\0';
7188
7189 /* This is freed during event handling. */
7190 event->ws.value.execd_pathname = xstrdup (pathname);
7191 event->ws.kind = TARGET_WAITKIND_EXECD;
7192
7193 /* Skip the registers included in this packet, since
7194 they may be for an architecture different from the
7195 one used by the original program. */
7196 skipregs = 1;
7197 }
7198 else if (strprefix (p, p1, "create"))
7199 {
7200 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7201 p = strchrnul (p1 + 1, ';');
7202 }
7203 else
7204 {
7205 ULONGEST pnum;
7206 const char *p_temp;
7207
7208 if (skipregs)
7209 {
7210 p = strchrnul (p1 + 1, ';');
7211 p++;
7212 continue;
7213 }
7214
7215 /* Maybe a real ``P'' register number. */
7216 p_temp = unpack_varlen_hex (p, &pnum);
7217 /* If the first invalid character is the colon, we got a
7218 register number. Otherwise, it's an unknown stop
7219 reason. */
7220 if (p_temp == p1)
7221 {
7222 /* If we haven't parsed the event's thread yet, find
7223 it now, in order to find the architecture of the
7224 reported expedited registers. */
7225 if (event->ptid == null_ptid)
7226 {
7227 const char *thr = strstr (p1 + 1, ";thread:");
7228 if (thr != NULL)
7229 event->ptid = read_ptid (thr + strlen (";thread:"),
7230 NULL);
7231 else
7232 {
7233 /* Either the current thread hasn't changed,
7234 or the inferior is not multi-threaded.
7235 The event must be for the thread we last
7236 set as (or learned as being) current. */
7237 event->ptid = event->rs->general_thread;
7238 }
7239 }
7240
7241 if (rsa == NULL)
7242 {
7243 inferior *inf = (event->ptid == null_ptid
7244 ? NULL
7245 : find_inferior_ptid (event->ptid));
7246 /* If this is the first time we learn anything
7247 about this process, skip the registers
7248 included in this packet, since we don't yet
7249 know which architecture to use to parse them.
7250 We'll determine the architecture later when
7251 we process the stop reply and retrieve the
7252 target description, via
7253 remote_notice_new_inferior ->
7254 post_create_inferior. */
7255 if (inf == NULL)
7256 {
7257 p = strchrnul (p1 + 1, ';');
7258 p++;
7259 continue;
7260 }
7261
7262 event->arch = inf->gdbarch;
7263 rsa = event->rs->get_remote_arch_state (event->arch);
7264 }
7265
7266 packet_reg *reg
7267 = packet_reg_from_pnum (event->arch, rsa, pnum);
7268 cached_reg_t cached_reg;
7269
7270 if (reg == NULL)
7271 error (_("Remote sent bad register number %s: %s\n\
7272 Packet: '%s'\n"),
7273 hex_string (pnum), p, buf);
7274
7275 cached_reg.num = reg->regnum;
7276 cached_reg.data = (gdb_byte *)
7277 xmalloc (register_size (event->arch, reg->regnum));
7278
7279 p = p1 + 1;
7280 fieldsize = hex2bin (p, cached_reg.data,
7281 register_size (event->arch, reg->regnum));
7282 p += 2 * fieldsize;
7283 if (fieldsize < register_size (event->arch, reg->regnum))
7284 warning (_("Remote reply is too short: %s"), buf);
7285
7286 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7287 }
7288 else
7289 {
7290 /* Not a number. Silently skip unknown optional
7291 info. */
7292 p = strchrnul (p1 + 1, ';');
7293 }
7294 }
7295
7296 if (*p != ';')
7297 error (_("Remote register badly formatted: %s\nhere: %s"),
7298 buf, p);
7299 ++p;
7300 }
7301
7302 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7303 break;
7304
7305 /* fall through */
7306 case 'S': /* Old style status, just signal only. */
7307 {
7308 int sig;
7309
7310 event->ws.kind = TARGET_WAITKIND_STOPPED;
7311 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7312 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7313 event->ws.value.sig = (enum gdb_signal) sig;
7314 else
7315 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7316 }
7317 break;
7318 case 'w': /* Thread exited. */
7319 {
7320 const char *p;
7321 ULONGEST value;
7322
7323 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7324 p = unpack_varlen_hex (&buf[1], &value);
7325 event->ws.value.integer = value;
7326 if (*p != ';')
7327 error (_("stop reply packet badly formatted: %s"), buf);
7328 event->ptid = read_ptid (++p, NULL);
7329 break;
7330 }
7331 case 'W': /* Target exited. */
7332 case 'X':
7333 {
7334 const char *p;
7335 int pid;
7336 ULONGEST value;
7337
7338 /* GDB used to accept only 2 hex chars here. Stubs should
7339 only send more if they detect GDB supports multi-process
7340 support. */
7341 p = unpack_varlen_hex (&buf[1], &value);
7342
7343 if (buf[0] == 'W')
7344 {
7345 /* The remote process exited. */
7346 event->ws.kind = TARGET_WAITKIND_EXITED;
7347 event->ws.value.integer = value;
7348 }
7349 else
7350 {
7351 /* The remote process exited with a signal. */
7352 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7353 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7354 event->ws.value.sig = (enum gdb_signal) value;
7355 else
7356 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7357 }
7358
7359 /* If no process is specified, assume inferior_ptid. */
7360 pid = ptid_get_pid (inferior_ptid);
7361 if (*p == '\0')
7362 ;
7363 else if (*p == ';')
7364 {
7365 p++;
7366
7367 if (*p == '\0')
7368 ;
7369 else if (startswith (p, "process:"))
7370 {
7371 ULONGEST upid;
7372
7373 p += sizeof ("process:") - 1;
7374 unpack_varlen_hex (p, &upid);
7375 pid = upid;
7376 }
7377 else
7378 error (_("unknown stop reply packet: %s"), buf);
7379 }
7380 else
7381 error (_("unknown stop reply packet: %s"), buf);
7382 event->ptid = pid_to_ptid (pid);
7383 }
7384 break;
7385 case 'N':
7386 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7387 event->ptid = minus_one_ptid;
7388 break;
7389 }
7390
7391 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7392 error (_("No process or thread specified in stop reply: %s"), buf);
7393 }
7394
7395 /* When the stub wants to tell GDB about a new notification reply, it
7396 sends a notification (%Stop, for example). Those can come it at
7397 any time, hence, we have to make sure that any pending
7398 putpkt/getpkt sequence we're making is finished, before querying
7399 the stub for more events with the corresponding ack command
7400 (vStopped, for example). E.g., if we started a vStopped sequence
7401 immediately upon receiving the notification, something like this
7402 could happen:
7403
7404 1.1) --> Hg 1
7405 1.2) <-- OK
7406 1.3) --> g
7407 1.4) <-- %Stop
7408 1.5) --> vStopped
7409 1.6) <-- (registers reply to step #1.3)
7410
7411 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7412 query.
7413
7414 To solve this, whenever we parse a %Stop notification successfully,
7415 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7416 doing whatever we were doing:
7417
7418 2.1) --> Hg 1
7419 2.2) <-- OK
7420 2.3) --> g
7421 2.4) <-- %Stop
7422 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7423 2.5) <-- (registers reply to step #2.3)
7424
7425 Eventualy after step #2.5, we return to the event loop, which
7426 notices there's an event on the
7427 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7428 associated callback --- the function below. At this point, we're
7429 always safe to start a vStopped sequence. :
7430
7431 2.6) --> vStopped
7432 2.7) <-- T05 thread:2
7433 2.8) --> vStopped
7434 2.9) --> OK
7435 */
7436
7437 void
7438 remote_notif_get_pending_events (struct notif_client *nc)
7439 {
7440 struct remote_state *rs = get_remote_state ();
7441
7442 if (rs->notif_state->pending_event[nc->id] != NULL)
7443 {
7444 if (notif_debug)
7445 fprintf_unfiltered (gdb_stdlog,
7446 "notif: process: '%s' ack pending event\n",
7447 nc->name);
7448
7449 /* acknowledge */
7450 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7451 rs->notif_state->pending_event[nc->id] = NULL;
7452
7453 while (1)
7454 {
7455 getpkt (&rs->buf, &rs->buf_size, 0);
7456 if (strcmp (rs->buf, "OK") == 0)
7457 break;
7458 else
7459 remote_notif_ack (nc, rs->buf);
7460 }
7461 }
7462 else
7463 {
7464 if (notif_debug)
7465 fprintf_unfiltered (gdb_stdlog,
7466 "notif: process: '%s' no pending reply\n",
7467 nc->name);
7468 }
7469 }
7470
7471 /* Called when it is decided that STOP_REPLY holds the info of the
7472 event that is to be returned to the core. This function always
7473 destroys STOP_REPLY. */
7474
7475 static ptid_t
7476 process_stop_reply (struct stop_reply *stop_reply,
7477 struct target_waitstatus *status)
7478 {
7479 ptid_t ptid;
7480
7481 *status = stop_reply->ws;
7482 ptid = stop_reply->ptid;
7483
7484 /* If no thread/process was reported by the stub, assume the current
7485 inferior. */
7486 if (ptid_equal (ptid, null_ptid))
7487 ptid = inferior_ptid;
7488
7489 if (status->kind != TARGET_WAITKIND_EXITED
7490 && status->kind != TARGET_WAITKIND_SIGNALLED
7491 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7492 {
7493 /* Expedited registers. */
7494 if (stop_reply->regcache)
7495 {
7496 struct regcache *regcache
7497 = get_thread_arch_regcache (ptid, stop_reply->arch);
7498 cached_reg_t *reg;
7499 int ix;
7500
7501 for (ix = 0;
7502 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7503 ix++)
7504 {
7505 regcache_raw_supply (regcache, reg->num, reg->data);
7506 xfree (reg->data);
7507 }
7508
7509 VEC_free (cached_reg_t, stop_reply->regcache);
7510 }
7511
7512 remote_notice_new_inferior (ptid, 0);
7513 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7514 remote_thr->core = stop_reply->core;
7515 remote_thr->stop_reason = stop_reply->stop_reason;
7516 remote_thr->watch_data_address = stop_reply->watch_data_address;
7517 remote_thr->vcont_resumed = 0;
7518 }
7519
7520 stop_reply_xfree (stop_reply);
7521 return ptid;
7522 }
7523
7524 /* The non-stop mode version of target_wait. */
7525
7526 static ptid_t
7527 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7528 {
7529 struct remote_state *rs = get_remote_state ();
7530 struct stop_reply *stop_reply;
7531 int ret;
7532 int is_notif = 0;
7533
7534 /* If in non-stop mode, get out of getpkt even if a
7535 notification is received. */
7536
7537 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7538 0 /* forever */, &is_notif);
7539 while (1)
7540 {
7541 if (ret != -1 && !is_notif)
7542 switch (rs->buf[0])
7543 {
7544 case 'E': /* Error of some sort. */
7545 /* We're out of sync with the target now. Did it continue
7546 or not? We can't tell which thread it was in non-stop,
7547 so just ignore this. */
7548 warning (_("Remote failure reply: %s"), rs->buf);
7549 break;
7550 case 'O': /* Console output. */
7551 remote_console_output (rs->buf + 1);
7552 break;
7553 default:
7554 warning (_("Invalid remote reply: %s"), rs->buf);
7555 break;
7556 }
7557
7558 /* Acknowledge a pending stop reply that may have arrived in the
7559 mean time. */
7560 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7561 remote_notif_get_pending_events (&notif_client_stop);
7562
7563 /* If indeed we noticed a stop reply, we're done. */
7564 stop_reply = queued_stop_reply (ptid);
7565 if (stop_reply != NULL)
7566 return process_stop_reply (stop_reply, status);
7567
7568 /* Still no event. If we're just polling for an event, then
7569 return to the event loop. */
7570 if (options & TARGET_WNOHANG)
7571 {
7572 status->kind = TARGET_WAITKIND_IGNORE;
7573 return minus_one_ptid;
7574 }
7575
7576 /* Otherwise do a blocking wait. */
7577 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7578 1 /* forever */, &is_notif);
7579 }
7580 }
7581
7582 /* Wait until the remote machine stops, then return, storing status in
7583 STATUS just as `wait' would. */
7584
7585 static ptid_t
7586 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7587 {
7588 struct remote_state *rs = get_remote_state ();
7589 ptid_t event_ptid = null_ptid;
7590 char *buf;
7591 struct stop_reply *stop_reply;
7592
7593 again:
7594
7595 status->kind = TARGET_WAITKIND_IGNORE;
7596 status->value.integer = 0;
7597
7598 stop_reply = queued_stop_reply (ptid);
7599 if (stop_reply != NULL)
7600 return process_stop_reply (stop_reply, status);
7601
7602 if (rs->cached_wait_status)
7603 /* Use the cached wait status, but only once. */
7604 rs->cached_wait_status = 0;
7605 else
7606 {
7607 int ret;
7608 int is_notif;
7609 int forever = ((options & TARGET_WNOHANG) == 0
7610 && wait_forever_enabled_p);
7611
7612 if (!rs->waiting_for_stop_reply)
7613 {
7614 status->kind = TARGET_WAITKIND_NO_RESUMED;
7615 return minus_one_ptid;
7616 }
7617
7618 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7619 _never_ wait for ever -> test on target_is_async_p().
7620 However, before we do that we need to ensure that the caller
7621 knows how to take the target into/out of async mode. */
7622 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7623 forever, &is_notif);
7624
7625 /* GDB gets a notification. Return to core as this event is
7626 not interesting. */
7627 if (ret != -1 && is_notif)
7628 return minus_one_ptid;
7629
7630 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7631 return minus_one_ptid;
7632 }
7633
7634 buf = rs->buf;
7635
7636 /* Assume that the target has acknowledged Ctrl-C unless we receive
7637 an 'F' or 'O' packet. */
7638 if (buf[0] != 'F' && buf[0] != 'O')
7639 rs->ctrlc_pending_p = 0;
7640
7641 switch (buf[0])
7642 {
7643 case 'E': /* Error of some sort. */
7644 /* We're out of sync with the target now. Did it continue or
7645 not? Not is more likely, so report a stop. */
7646 rs->waiting_for_stop_reply = 0;
7647
7648 warning (_("Remote failure reply: %s"), buf);
7649 status->kind = TARGET_WAITKIND_STOPPED;
7650 status->value.sig = GDB_SIGNAL_0;
7651 break;
7652 case 'F': /* File-I/O request. */
7653 /* GDB may access the inferior memory while handling the File-I/O
7654 request, but we don't want GDB accessing memory while waiting
7655 for a stop reply. See the comments in putpkt_binary. Set
7656 waiting_for_stop_reply to 0 temporarily. */
7657 rs->waiting_for_stop_reply = 0;
7658 remote_fileio_request (buf, rs->ctrlc_pending_p);
7659 rs->ctrlc_pending_p = 0;
7660 /* GDB handled the File-I/O request, and the target is running
7661 again. Keep waiting for events. */
7662 rs->waiting_for_stop_reply = 1;
7663 break;
7664 case 'N': case 'T': case 'S': case 'X': case 'W':
7665 {
7666 struct stop_reply *stop_reply;
7667
7668 /* There is a stop reply to handle. */
7669 rs->waiting_for_stop_reply = 0;
7670
7671 stop_reply
7672 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7673 rs->buf);
7674
7675 event_ptid = process_stop_reply (stop_reply, status);
7676 break;
7677 }
7678 case 'O': /* Console output. */
7679 remote_console_output (buf + 1);
7680 break;
7681 case '\0':
7682 if (rs->last_sent_signal != GDB_SIGNAL_0)
7683 {
7684 /* Zero length reply means that we tried 'S' or 'C' and the
7685 remote system doesn't support it. */
7686 target_terminal::ours_for_output ();
7687 printf_filtered
7688 ("Can't send signals to this remote system. %s not sent.\n",
7689 gdb_signal_to_name (rs->last_sent_signal));
7690 rs->last_sent_signal = GDB_SIGNAL_0;
7691 target_terminal::inferior ();
7692
7693 strcpy (buf, rs->last_sent_step ? "s" : "c");
7694 putpkt (buf);
7695 break;
7696 }
7697 /* fallthrough */
7698 default:
7699 warning (_("Invalid remote reply: %s"), buf);
7700 break;
7701 }
7702
7703 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7704 return minus_one_ptid;
7705 else if (status->kind == TARGET_WAITKIND_IGNORE)
7706 {
7707 /* Nothing interesting happened. If we're doing a non-blocking
7708 poll, we're done. Otherwise, go back to waiting. */
7709 if (options & TARGET_WNOHANG)
7710 return minus_one_ptid;
7711 else
7712 goto again;
7713 }
7714 else if (status->kind != TARGET_WAITKIND_EXITED
7715 && status->kind != TARGET_WAITKIND_SIGNALLED)
7716 {
7717 if (!ptid_equal (event_ptid, null_ptid))
7718 record_currthread (rs, event_ptid);
7719 else
7720 event_ptid = inferior_ptid;
7721 }
7722 else
7723 /* A process exit. Invalidate our notion of current thread. */
7724 record_currthread (rs, minus_one_ptid);
7725
7726 return event_ptid;
7727 }
7728
7729 /* Wait until the remote machine stops, then return, storing status in
7730 STATUS just as `wait' would. */
7731
7732 ptid_t
7733 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7734 {
7735 ptid_t event_ptid;
7736
7737 if (target_is_non_stop_p ())
7738 event_ptid = remote_wait_ns (ptid, status, options);
7739 else
7740 event_ptid = remote_wait_as (ptid, status, options);
7741
7742 if (target_is_async_p ())
7743 {
7744 /* If there are are events left in the queue tell the event loop
7745 to return here. */
7746 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7747 mark_async_event_handler (remote_async_inferior_event_token);
7748 }
7749
7750 return event_ptid;
7751 }
7752
7753 /* Fetch a single register using a 'p' packet. */
7754
7755 static int
7756 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7757 {
7758 struct gdbarch *gdbarch = regcache->arch ();
7759 struct remote_state *rs = get_remote_state ();
7760 char *buf, *p;
7761 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7762 int i;
7763
7764 if (packet_support (PACKET_p) == PACKET_DISABLE)
7765 return 0;
7766
7767 if (reg->pnum == -1)
7768 return 0;
7769
7770 p = rs->buf;
7771 *p++ = 'p';
7772 p += hexnumstr (p, reg->pnum);
7773 *p++ = '\0';
7774 putpkt (rs->buf);
7775 getpkt (&rs->buf, &rs->buf_size, 0);
7776
7777 buf = rs->buf;
7778
7779 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7780 {
7781 case PACKET_OK:
7782 break;
7783 case PACKET_UNKNOWN:
7784 return 0;
7785 case PACKET_ERROR:
7786 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7787 gdbarch_register_name (regcache->arch (),
7788 reg->regnum),
7789 buf);
7790 }
7791
7792 /* If this register is unfetchable, tell the regcache. */
7793 if (buf[0] == 'x')
7794 {
7795 regcache_raw_supply (regcache, reg->regnum, NULL);
7796 return 1;
7797 }
7798
7799 /* Otherwise, parse and supply the value. */
7800 p = buf;
7801 i = 0;
7802 while (p[0] != 0)
7803 {
7804 if (p[1] == 0)
7805 error (_("fetch_register_using_p: early buf termination"));
7806
7807 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7808 p += 2;
7809 }
7810 regcache_raw_supply (regcache, reg->regnum, regp);
7811 return 1;
7812 }
7813
7814 /* Fetch the registers included in the target's 'g' packet. */
7815
7816 static int
7817 send_g_packet (void)
7818 {
7819 struct remote_state *rs = get_remote_state ();
7820 int buf_len;
7821
7822 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7823 putpkt (rs->buf);
7824 getpkt (&rs->buf, &rs->buf_size, 0);
7825 if (packet_check_result (rs->buf) == PACKET_ERROR)
7826 error (_("Could not read registers; remote failure reply '%s'"),
7827 rs->buf);
7828
7829 /* We can get out of synch in various cases. If the first character
7830 in the buffer is not a hex character, assume that has happened
7831 and try to fetch another packet to read. */
7832 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7833 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7834 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7835 && rs->buf[0] != 'x') /* New: unavailable register value. */
7836 {
7837 if (remote_debug)
7838 fprintf_unfiltered (gdb_stdlog,
7839 "Bad register packet; fetching a new packet\n");
7840 getpkt (&rs->buf, &rs->buf_size, 0);
7841 }
7842
7843 buf_len = strlen (rs->buf);
7844
7845 /* Sanity check the received packet. */
7846 if (buf_len % 2 != 0)
7847 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7848
7849 return buf_len / 2;
7850 }
7851
7852 static void
7853 process_g_packet (struct regcache *regcache)
7854 {
7855 struct gdbarch *gdbarch = regcache->arch ();
7856 struct remote_state *rs = get_remote_state ();
7857 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
7858 int i, buf_len;
7859 char *p;
7860 char *regs;
7861
7862 buf_len = strlen (rs->buf);
7863
7864 /* Further sanity checks, with knowledge of the architecture. */
7865 if (buf_len > 2 * rsa->sizeof_g_packet)
7866 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7867 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7868
7869 /* Save the size of the packet sent to us by the target. It is used
7870 as a heuristic when determining the max size of packets that the
7871 target can safely receive. */
7872 if (rsa->actual_register_packet_size == 0)
7873 rsa->actual_register_packet_size = buf_len;
7874
7875 /* If this is smaller than we guessed the 'g' packet would be,
7876 update our records. A 'g' reply that doesn't include a register's
7877 value implies either that the register is not available, or that
7878 the 'p' packet must be used. */
7879 if (buf_len < 2 * rsa->sizeof_g_packet)
7880 {
7881 long sizeof_g_packet = buf_len / 2;
7882
7883 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7884 {
7885 long offset = rsa->regs[i].offset;
7886 long reg_size = register_size (gdbarch, i);
7887
7888 if (rsa->regs[i].pnum == -1)
7889 continue;
7890
7891 if (offset >= sizeof_g_packet)
7892 rsa->regs[i].in_g_packet = 0;
7893 else if (offset + reg_size > sizeof_g_packet)
7894 error (_("Truncated register %d in remote 'g' packet"), i);
7895 else
7896 rsa->regs[i].in_g_packet = 1;
7897 }
7898
7899 /* Looks valid enough, we can assume this is the correct length
7900 for a 'g' packet. It's important not to adjust
7901 rsa->sizeof_g_packet if we have truncated registers otherwise
7902 this "if" won't be run the next time the method is called
7903 with a packet of the same size and one of the internal errors
7904 below will trigger instead. */
7905 rsa->sizeof_g_packet = sizeof_g_packet;
7906 }
7907
7908 regs = (char *) alloca (rsa->sizeof_g_packet);
7909
7910 /* Unimplemented registers read as all bits zero. */
7911 memset (regs, 0, rsa->sizeof_g_packet);
7912
7913 /* Reply describes registers byte by byte, each byte encoded as two
7914 hex characters. Suck them all up, then supply them to the
7915 register cacheing/storage mechanism. */
7916
7917 p = rs->buf;
7918 for (i = 0; i < rsa->sizeof_g_packet; i++)
7919 {
7920 if (p[0] == 0 || p[1] == 0)
7921 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7922 internal_error (__FILE__, __LINE__,
7923 _("unexpected end of 'g' packet reply"));
7924
7925 if (p[0] == 'x' && p[1] == 'x')
7926 regs[i] = 0; /* 'x' */
7927 else
7928 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7929 p += 2;
7930 }
7931
7932 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7933 {
7934 struct packet_reg *r = &rsa->regs[i];
7935 long reg_size = register_size (gdbarch, i);
7936
7937 if (r->in_g_packet)
7938 {
7939 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7940 /* This shouldn't happen - we adjusted in_g_packet above. */
7941 internal_error (__FILE__, __LINE__,
7942 _("unexpected end of 'g' packet reply"));
7943 else if (rs->buf[r->offset * 2] == 'x')
7944 {
7945 gdb_assert (r->offset * 2 < strlen (rs->buf));
7946 /* The register isn't available, mark it as such (at
7947 the same time setting the value to zero). */
7948 regcache_raw_supply (regcache, r->regnum, NULL);
7949 }
7950 else
7951 regcache_raw_supply (regcache, r->regnum,
7952 regs + r->offset);
7953 }
7954 }
7955 }
7956
7957 static void
7958 fetch_registers_using_g (struct regcache *regcache)
7959 {
7960 send_g_packet ();
7961 process_g_packet (regcache);
7962 }
7963
7964 /* Make the remote selected traceframe match GDB's selected
7965 traceframe. */
7966
7967 static void
7968 set_remote_traceframe (void)
7969 {
7970 int newnum;
7971 struct remote_state *rs = get_remote_state ();
7972
7973 if (rs->remote_traceframe_number == get_traceframe_number ())
7974 return;
7975
7976 /* Avoid recursion, remote_trace_find calls us again. */
7977 rs->remote_traceframe_number = get_traceframe_number ();
7978
7979 newnum = target_trace_find (tfind_number,
7980 get_traceframe_number (), 0, 0, NULL);
7981
7982 /* Should not happen. If it does, all bets are off. */
7983 if (newnum != get_traceframe_number ())
7984 warning (_("could not set remote traceframe"));
7985 }
7986
7987 void
7988 remote_target::fetch_registers (struct regcache *regcache, int regnum)
7989 {
7990 struct gdbarch *gdbarch = regcache->arch ();
7991 struct remote_state *rs = get_remote_state ();
7992 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
7993 int i;
7994
7995 set_remote_traceframe ();
7996 set_general_thread (regcache_get_ptid (regcache));
7997
7998 if (regnum >= 0)
7999 {
8000 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8001
8002 gdb_assert (reg != NULL);
8003
8004 /* If this register might be in the 'g' packet, try that first -
8005 we are likely to read more than one register. If this is the
8006 first 'g' packet, we might be overly optimistic about its
8007 contents, so fall back to 'p'. */
8008 if (reg->in_g_packet)
8009 {
8010 fetch_registers_using_g (regcache);
8011 if (reg->in_g_packet)
8012 return;
8013 }
8014
8015 if (fetch_register_using_p (regcache, reg))
8016 return;
8017
8018 /* This register is not available. */
8019 regcache_raw_supply (regcache, reg->regnum, NULL);
8020
8021 return;
8022 }
8023
8024 fetch_registers_using_g (regcache);
8025
8026 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8027 if (!rsa->regs[i].in_g_packet)
8028 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8029 {
8030 /* This register is not available. */
8031 regcache_raw_supply (regcache, i, NULL);
8032 }
8033 }
8034
8035 /* Prepare to store registers. Since we may send them all (using a
8036 'G' request), we have to read out the ones we don't want to change
8037 first. */
8038
8039 void
8040 remote_target::prepare_to_store (struct regcache *regcache)
8041 {
8042 struct remote_state *rs = get_remote_state ();
8043 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8044 int i;
8045
8046 /* Make sure the entire registers array is valid. */
8047 switch (packet_support (PACKET_P))
8048 {
8049 case PACKET_DISABLE:
8050 case PACKET_SUPPORT_UNKNOWN:
8051 /* Make sure all the necessary registers are cached. */
8052 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8053 if (rsa->regs[i].in_g_packet)
8054 regcache_raw_update (regcache, rsa->regs[i].regnum);
8055 break;
8056 case PACKET_ENABLE:
8057 break;
8058 }
8059 }
8060
8061 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8062 packet was not recognized. */
8063
8064 static int
8065 store_register_using_P (const struct regcache *regcache,
8066 struct packet_reg *reg)
8067 {
8068 struct gdbarch *gdbarch = regcache->arch ();
8069 struct remote_state *rs = get_remote_state ();
8070 /* Try storing a single register. */
8071 char *buf = rs->buf;
8072 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8073 char *p;
8074
8075 if (packet_support (PACKET_P) == PACKET_DISABLE)
8076 return 0;
8077
8078 if (reg->pnum == -1)
8079 return 0;
8080
8081 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8082 p = buf + strlen (buf);
8083 regcache_raw_collect (regcache, reg->regnum, regp);
8084 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8085 putpkt (rs->buf);
8086 getpkt (&rs->buf, &rs->buf_size, 0);
8087
8088 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8089 {
8090 case PACKET_OK:
8091 return 1;
8092 case PACKET_ERROR:
8093 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8094 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8095 case PACKET_UNKNOWN:
8096 return 0;
8097 default:
8098 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8099 }
8100 }
8101
8102 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8103 contents of the register cache buffer. FIXME: ignores errors. */
8104
8105 static void
8106 store_registers_using_G (const struct regcache *regcache)
8107 {
8108 struct remote_state *rs = get_remote_state ();
8109 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8110 gdb_byte *regs;
8111 char *p;
8112
8113 /* Extract all the registers in the regcache copying them into a
8114 local buffer. */
8115 {
8116 int i;
8117
8118 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8119 memset (regs, 0, rsa->sizeof_g_packet);
8120 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8121 {
8122 struct packet_reg *r = &rsa->regs[i];
8123
8124 if (r->in_g_packet)
8125 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
8126 }
8127 }
8128
8129 /* Command describes registers byte by byte,
8130 each byte encoded as two hex characters. */
8131 p = rs->buf;
8132 *p++ = 'G';
8133 bin2hex (regs, p, rsa->sizeof_g_packet);
8134 putpkt (rs->buf);
8135 getpkt (&rs->buf, &rs->buf_size, 0);
8136 if (packet_check_result (rs->buf) == PACKET_ERROR)
8137 error (_("Could not write registers; remote failure reply '%s'"),
8138 rs->buf);
8139 }
8140
8141 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8142 of the register cache buffer. FIXME: ignores errors. */
8143
8144 void
8145 remote_target::store_registers (struct regcache *regcache, int regnum)
8146 {
8147 struct gdbarch *gdbarch = regcache->arch ();
8148 struct remote_state *rs = get_remote_state ();
8149 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8150 int i;
8151
8152 set_remote_traceframe ();
8153 set_general_thread (regcache_get_ptid (regcache));
8154
8155 if (regnum >= 0)
8156 {
8157 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8158
8159 gdb_assert (reg != NULL);
8160
8161 /* Always prefer to store registers using the 'P' packet if
8162 possible; we often change only a small number of registers.
8163 Sometimes we change a larger number; we'd need help from a
8164 higher layer to know to use 'G'. */
8165 if (store_register_using_P (regcache, reg))
8166 return;
8167
8168 /* For now, don't complain if we have no way to write the
8169 register. GDB loses track of unavailable registers too
8170 easily. Some day, this may be an error. We don't have
8171 any way to read the register, either... */
8172 if (!reg->in_g_packet)
8173 return;
8174
8175 store_registers_using_G (regcache);
8176 return;
8177 }
8178
8179 store_registers_using_G (regcache);
8180
8181 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8182 if (!rsa->regs[i].in_g_packet)
8183 if (!store_register_using_P (regcache, &rsa->regs[i]))
8184 /* See above for why we do not issue an error here. */
8185 continue;
8186 }
8187 \f
8188
8189 /* Return the number of hex digits in num. */
8190
8191 static int
8192 hexnumlen (ULONGEST num)
8193 {
8194 int i;
8195
8196 for (i = 0; num != 0; i++)
8197 num >>= 4;
8198
8199 return std::max (i, 1);
8200 }
8201
8202 /* Set BUF to the minimum number of hex digits representing NUM. */
8203
8204 static int
8205 hexnumstr (char *buf, ULONGEST num)
8206 {
8207 int len = hexnumlen (num);
8208
8209 return hexnumnstr (buf, num, len);
8210 }
8211
8212
8213 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8214
8215 static int
8216 hexnumnstr (char *buf, ULONGEST num, int width)
8217 {
8218 int i;
8219
8220 buf[width] = '\0';
8221
8222 for (i = width - 1; i >= 0; i--)
8223 {
8224 buf[i] = "0123456789abcdef"[(num & 0xf)];
8225 num >>= 4;
8226 }
8227
8228 return width;
8229 }
8230
8231 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8232
8233 static CORE_ADDR
8234 remote_address_masked (CORE_ADDR addr)
8235 {
8236 unsigned int address_size = remote_address_size;
8237
8238 /* If "remoteaddresssize" was not set, default to target address size. */
8239 if (!address_size)
8240 address_size = gdbarch_addr_bit (target_gdbarch ());
8241
8242 if (address_size > 0
8243 && address_size < (sizeof (ULONGEST) * 8))
8244 {
8245 /* Only create a mask when that mask can safely be constructed
8246 in a ULONGEST variable. */
8247 ULONGEST mask = 1;
8248
8249 mask = (mask << address_size) - 1;
8250 addr &= mask;
8251 }
8252 return addr;
8253 }
8254
8255 /* Determine whether the remote target supports binary downloading.
8256 This is accomplished by sending a no-op memory write of zero length
8257 to the target at the specified address. It does not suffice to send
8258 the whole packet, since many stubs strip the eighth bit and
8259 subsequently compute a wrong checksum, which causes real havoc with
8260 remote_write_bytes.
8261
8262 NOTE: This can still lose if the serial line is not eight-bit
8263 clean. In cases like this, the user should clear "remote
8264 X-packet". */
8265
8266 static void
8267 check_binary_download (CORE_ADDR addr)
8268 {
8269 struct remote_state *rs = get_remote_state ();
8270
8271 switch (packet_support (PACKET_X))
8272 {
8273 case PACKET_DISABLE:
8274 break;
8275 case PACKET_ENABLE:
8276 break;
8277 case PACKET_SUPPORT_UNKNOWN:
8278 {
8279 char *p;
8280
8281 p = rs->buf;
8282 *p++ = 'X';
8283 p += hexnumstr (p, (ULONGEST) addr);
8284 *p++ = ',';
8285 p += hexnumstr (p, (ULONGEST) 0);
8286 *p++ = ':';
8287 *p = '\0';
8288
8289 putpkt_binary (rs->buf, (int) (p - rs->buf));
8290 getpkt (&rs->buf, &rs->buf_size, 0);
8291
8292 if (rs->buf[0] == '\0')
8293 {
8294 if (remote_debug)
8295 fprintf_unfiltered (gdb_stdlog,
8296 "binary downloading NOT "
8297 "supported by target\n");
8298 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8299 }
8300 else
8301 {
8302 if (remote_debug)
8303 fprintf_unfiltered (gdb_stdlog,
8304 "binary downloading supported by target\n");
8305 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8306 }
8307 break;
8308 }
8309 }
8310 }
8311
8312 /* Helper function to resize the payload in order to try to get a good
8313 alignment. We try to write an amount of data such that the next write will
8314 start on an address aligned on REMOTE_ALIGN_WRITES. */
8315
8316 static int
8317 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8318 {
8319 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8320 }
8321
8322 /* Write memory data directly to the remote machine.
8323 This does not inform the data cache; the data cache uses this.
8324 HEADER is the starting part of the packet.
8325 MEMADDR is the address in the remote memory space.
8326 MYADDR is the address of the buffer in our space.
8327 LEN_UNITS is the number of addressable units to write.
8328 UNIT_SIZE is the length in bytes of an addressable unit.
8329 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8330 should send data as binary ('X'), or hex-encoded ('M').
8331
8332 The function creates packet of the form
8333 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8334
8335 where encoding of <DATA> is terminated by PACKET_FORMAT.
8336
8337 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8338 are omitted.
8339
8340 Return the transferred status, error or OK (an
8341 'enum target_xfer_status' value). Save the number of addressable units
8342 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8343
8344 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8345 exchange between gdb and the stub could look like (?? in place of the
8346 checksum):
8347
8348 -> $m1000,4#??
8349 <- aaaabbbbccccdddd
8350
8351 -> $M1000,3:eeeeffffeeee#??
8352 <- OK
8353
8354 -> $m1000,4#??
8355 <- eeeeffffeeeedddd */
8356
8357 static enum target_xfer_status
8358 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8359 const gdb_byte *myaddr, ULONGEST len_units,
8360 int unit_size, ULONGEST *xfered_len_units,
8361 char packet_format, int use_length)
8362 {
8363 struct remote_state *rs = get_remote_state ();
8364 char *p;
8365 char *plen = NULL;
8366 int plenlen = 0;
8367 int todo_units;
8368 int units_written;
8369 int payload_capacity_bytes;
8370 int payload_length_bytes;
8371
8372 if (packet_format != 'X' && packet_format != 'M')
8373 internal_error (__FILE__, __LINE__,
8374 _("remote_write_bytes_aux: bad packet format"));
8375
8376 if (len_units == 0)
8377 return TARGET_XFER_EOF;
8378
8379 payload_capacity_bytes = get_memory_write_packet_size ();
8380
8381 /* The packet buffer will be large enough for the payload;
8382 get_memory_packet_size ensures this. */
8383 rs->buf[0] = '\0';
8384
8385 /* Compute the size of the actual payload by subtracting out the
8386 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8387
8388 payload_capacity_bytes -= strlen ("$,:#NN");
8389 if (!use_length)
8390 /* The comma won't be used. */
8391 payload_capacity_bytes += 1;
8392 payload_capacity_bytes -= strlen (header);
8393 payload_capacity_bytes -= hexnumlen (memaddr);
8394
8395 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8396
8397 strcat (rs->buf, header);
8398 p = rs->buf + strlen (header);
8399
8400 /* Compute a best guess of the number of bytes actually transfered. */
8401 if (packet_format == 'X')
8402 {
8403 /* Best guess at number of bytes that will fit. */
8404 todo_units = std::min (len_units,
8405 (ULONGEST) payload_capacity_bytes / unit_size);
8406 if (use_length)
8407 payload_capacity_bytes -= hexnumlen (todo_units);
8408 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8409 }
8410 else
8411 {
8412 /* Number of bytes that will fit. */
8413 todo_units
8414 = std::min (len_units,
8415 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8416 if (use_length)
8417 payload_capacity_bytes -= hexnumlen (todo_units);
8418 todo_units = std::min (todo_units,
8419 (payload_capacity_bytes / unit_size) / 2);
8420 }
8421
8422 if (todo_units <= 0)
8423 internal_error (__FILE__, __LINE__,
8424 _("minimum packet size too small to write data"));
8425
8426 /* If we already need another packet, then try to align the end
8427 of this packet to a useful boundary. */
8428 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8429 todo_units = align_for_efficient_write (todo_units, memaddr);
8430
8431 /* Append "<memaddr>". */
8432 memaddr = remote_address_masked (memaddr);
8433 p += hexnumstr (p, (ULONGEST) memaddr);
8434
8435 if (use_length)
8436 {
8437 /* Append ",". */
8438 *p++ = ',';
8439
8440 /* Append the length and retain its location and size. It may need to be
8441 adjusted once the packet body has been created. */
8442 plen = p;
8443 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8444 p += plenlen;
8445 }
8446
8447 /* Append ":". */
8448 *p++ = ':';
8449 *p = '\0';
8450
8451 /* Append the packet body. */
8452 if (packet_format == 'X')
8453 {
8454 /* Binary mode. Send target system values byte by byte, in
8455 increasing byte addresses. Only escape certain critical
8456 characters. */
8457 payload_length_bytes =
8458 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8459 &units_written, payload_capacity_bytes);
8460
8461 /* If not all TODO units fit, then we'll need another packet. Make
8462 a second try to keep the end of the packet aligned. Don't do
8463 this if the packet is tiny. */
8464 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8465 {
8466 int new_todo_units;
8467
8468 new_todo_units = align_for_efficient_write (units_written, memaddr);
8469
8470 if (new_todo_units != units_written)
8471 payload_length_bytes =
8472 remote_escape_output (myaddr, new_todo_units, unit_size,
8473 (gdb_byte *) p, &units_written,
8474 payload_capacity_bytes);
8475 }
8476
8477 p += payload_length_bytes;
8478 if (use_length && units_written < todo_units)
8479 {
8480 /* Escape chars have filled up the buffer prematurely,
8481 and we have actually sent fewer units than planned.
8482 Fix-up the length field of the packet. Use the same
8483 number of characters as before. */
8484 plen += hexnumnstr (plen, (ULONGEST) units_written,
8485 plenlen);
8486 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8487 }
8488 }
8489 else
8490 {
8491 /* Normal mode: Send target system values byte by byte, in
8492 increasing byte addresses. Each byte is encoded as a two hex
8493 value. */
8494 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8495 units_written = todo_units;
8496 }
8497
8498 putpkt_binary (rs->buf, (int) (p - rs->buf));
8499 getpkt (&rs->buf, &rs->buf_size, 0);
8500
8501 if (rs->buf[0] == 'E')
8502 return TARGET_XFER_E_IO;
8503
8504 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8505 send fewer units than we'd planned. */
8506 *xfered_len_units = (ULONGEST) units_written;
8507 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8508 }
8509
8510 /* Write memory data directly to the remote machine.
8511 This does not inform the data cache; the data cache uses this.
8512 MEMADDR is the address in the remote memory space.
8513 MYADDR is the address of the buffer in our space.
8514 LEN is the number of bytes.
8515
8516 Return the transferred status, error or OK (an
8517 'enum target_xfer_status' value). Save the number of bytes
8518 transferred in *XFERED_LEN. Only transfer a single packet. */
8519
8520 static enum target_xfer_status
8521 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8522 int unit_size, ULONGEST *xfered_len)
8523 {
8524 const char *packet_format = NULL;
8525
8526 /* Check whether the target supports binary download. */
8527 check_binary_download (memaddr);
8528
8529 switch (packet_support (PACKET_X))
8530 {
8531 case PACKET_ENABLE:
8532 packet_format = "X";
8533 break;
8534 case PACKET_DISABLE:
8535 packet_format = "M";
8536 break;
8537 case PACKET_SUPPORT_UNKNOWN:
8538 internal_error (__FILE__, __LINE__,
8539 _("remote_write_bytes: bad internal state"));
8540 default:
8541 internal_error (__FILE__, __LINE__, _("bad switch"));
8542 }
8543
8544 return remote_write_bytes_aux (packet_format,
8545 memaddr, myaddr, len, unit_size, xfered_len,
8546 packet_format[0], 1);
8547 }
8548
8549 /* Read memory data directly from the remote machine.
8550 This does not use the data cache; the data cache uses this.
8551 MEMADDR is the address in the remote memory space.
8552 MYADDR is the address of the buffer in our space.
8553 LEN_UNITS is the number of addressable memory units to read..
8554 UNIT_SIZE is the length in bytes of an addressable unit.
8555
8556 Return the transferred status, error or OK (an
8557 'enum target_xfer_status' value). Save the number of bytes
8558 transferred in *XFERED_LEN_UNITS.
8559
8560 See the comment of remote_write_bytes_aux for an example of
8561 memory read/write exchange between gdb and the stub. */
8562
8563 static enum target_xfer_status
8564 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8565 int unit_size, ULONGEST *xfered_len_units)
8566 {
8567 struct remote_state *rs = get_remote_state ();
8568 int buf_size_bytes; /* Max size of packet output buffer. */
8569 char *p;
8570 int todo_units;
8571 int decoded_bytes;
8572
8573 buf_size_bytes = get_memory_read_packet_size ();
8574 /* The packet buffer will be large enough for the payload;
8575 get_memory_packet_size ensures this. */
8576
8577 /* Number of units that will fit. */
8578 todo_units = std::min (len_units,
8579 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8580
8581 /* Construct "m"<memaddr>","<len>". */
8582 memaddr = remote_address_masked (memaddr);
8583 p = rs->buf;
8584 *p++ = 'm';
8585 p += hexnumstr (p, (ULONGEST) memaddr);
8586 *p++ = ',';
8587 p += hexnumstr (p, (ULONGEST) todo_units);
8588 *p = '\0';
8589 putpkt (rs->buf);
8590 getpkt (&rs->buf, &rs->buf_size, 0);
8591 if (rs->buf[0] == 'E'
8592 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8593 && rs->buf[3] == '\0')
8594 return TARGET_XFER_E_IO;
8595 /* Reply describes memory byte by byte, each byte encoded as two hex
8596 characters. */
8597 p = rs->buf;
8598 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8599 /* Return what we have. Let higher layers handle partial reads. */
8600 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8601 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8602 }
8603
8604 /* Using the set of read-only target sections of remote, read live
8605 read-only memory.
8606
8607 For interface/parameters/return description see target.h,
8608 to_xfer_partial. */
8609
8610 static enum target_xfer_status
8611 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8612 ULONGEST memaddr, ULONGEST len,
8613 int unit_size, ULONGEST *xfered_len)
8614 {
8615 struct target_section *secp;
8616 struct target_section_table *table;
8617
8618 secp = target_section_by_addr (ops, memaddr);
8619 if (secp != NULL
8620 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8621 secp->the_bfd_section)
8622 & SEC_READONLY))
8623 {
8624 struct target_section *p;
8625 ULONGEST memend = memaddr + len;
8626
8627 table = target_get_section_table (ops);
8628
8629 for (p = table->sections; p < table->sections_end; p++)
8630 {
8631 if (memaddr >= p->addr)
8632 {
8633 if (memend <= p->endaddr)
8634 {
8635 /* Entire transfer is within this section. */
8636 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8637 xfered_len);
8638 }
8639 else if (memaddr >= p->endaddr)
8640 {
8641 /* This section ends before the transfer starts. */
8642 continue;
8643 }
8644 else
8645 {
8646 /* This section overlaps the transfer. Just do half. */
8647 len = p->endaddr - memaddr;
8648 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8649 xfered_len);
8650 }
8651 }
8652 }
8653 }
8654
8655 return TARGET_XFER_EOF;
8656 }
8657
8658 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8659 first if the requested memory is unavailable in traceframe.
8660 Otherwise, fall back to remote_read_bytes_1. */
8661
8662 static enum target_xfer_status
8663 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8664 gdb_byte *myaddr, ULONGEST len, int unit_size,
8665 ULONGEST *xfered_len)
8666 {
8667 if (len == 0)
8668 return TARGET_XFER_EOF;
8669
8670 if (get_traceframe_number () != -1)
8671 {
8672 std::vector<mem_range> available;
8673
8674 /* If we fail to get the set of available memory, then the
8675 target does not support querying traceframe info, and so we
8676 attempt reading from the traceframe anyway (assuming the
8677 target implements the old QTro packet then). */
8678 if (traceframe_available_memory (&available, memaddr, len))
8679 {
8680 if (available.empty () || available[0].start != memaddr)
8681 {
8682 enum target_xfer_status res;
8683
8684 /* Don't read into the traceframe's available
8685 memory. */
8686 if (!available.empty ())
8687 {
8688 LONGEST oldlen = len;
8689
8690 len = available[0].start - memaddr;
8691 gdb_assert (len <= oldlen);
8692 }
8693
8694 /* This goes through the topmost target again. */
8695 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8696 len, unit_size, xfered_len);
8697 if (res == TARGET_XFER_OK)
8698 return TARGET_XFER_OK;
8699 else
8700 {
8701 /* No use trying further, we know some memory starting
8702 at MEMADDR isn't available. */
8703 *xfered_len = len;
8704 return (*xfered_len != 0) ?
8705 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8706 }
8707 }
8708
8709 /* Don't try to read more than how much is available, in
8710 case the target implements the deprecated QTro packet to
8711 cater for older GDBs (the target's knowledge of read-only
8712 sections may be outdated by now). */
8713 len = available[0].length;
8714 }
8715 }
8716
8717 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8718 }
8719
8720 \f
8721
8722 /* Sends a packet with content determined by the printf format string
8723 FORMAT and the remaining arguments, then gets the reply. Returns
8724 whether the packet was a success, a failure, or unknown. */
8725
8726 static enum packet_result remote_send_printf (const char *format, ...)
8727 ATTRIBUTE_PRINTF (1, 2);
8728
8729 static enum packet_result
8730 remote_send_printf (const char *format, ...)
8731 {
8732 struct remote_state *rs = get_remote_state ();
8733 int max_size = get_remote_packet_size ();
8734 va_list ap;
8735
8736 va_start (ap, format);
8737
8738 rs->buf[0] = '\0';
8739 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8740 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8741
8742 if (putpkt (rs->buf) < 0)
8743 error (_("Communication problem with target."));
8744
8745 rs->buf[0] = '\0';
8746 getpkt (&rs->buf, &rs->buf_size, 0);
8747
8748 return packet_check_result (rs->buf);
8749 }
8750
8751 /* Flash writing can take quite some time. We'll set
8752 effectively infinite timeout for flash operations.
8753 In future, we'll need to decide on a better approach. */
8754 static const int remote_flash_timeout = 1000;
8755
8756 void
8757 remote_target::flash_erase (ULONGEST address, LONGEST length)
8758 {
8759 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8760 enum packet_result ret;
8761 scoped_restore restore_timeout
8762 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8763
8764 ret = remote_send_printf ("vFlashErase:%s,%s",
8765 phex (address, addr_size),
8766 phex (length, 4));
8767 switch (ret)
8768 {
8769 case PACKET_UNKNOWN:
8770 error (_("Remote target does not support flash erase"));
8771 case PACKET_ERROR:
8772 error (_("Error erasing flash with vFlashErase packet"));
8773 default:
8774 break;
8775 }
8776 }
8777
8778 static enum target_xfer_status
8779 remote_flash_write (struct target_ops *ops, ULONGEST address,
8780 ULONGEST length, ULONGEST *xfered_len,
8781 const gdb_byte *data)
8782 {
8783 scoped_restore restore_timeout
8784 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8785 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8786 xfered_len,'X', 0);
8787 }
8788
8789 void
8790 remote_target::flash_done ()
8791 {
8792 int ret;
8793
8794 scoped_restore restore_timeout
8795 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8796
8797 ret = remote_send_printf ("vFlashDone");
8798
8799 switch (ret)
8800 {
8801 case PACKET_UNKNOWN:
8802 error (_("Remote target does not support vFlashDone"));
8803 case PACKET_ERROR:
8804 error (_("Error finishing flash operation"));
8805 default:
8806 break;
8807 }
8808 }
8809
8810 void
8811 remote_target::files_info ()
8812 {
8813 puts_filtered ("Debugging a target over a serial line.\n");
8814 }
8815 \f
8816 /* Stuff for dealing with the packets which are part of this protocol.
8817 See comment at top of file for details. */
8818
8819 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8820 error to higher layers. Called when a serial error is detected.
8821 The exception message is STRING, followed by a colon and a blank,
8822 the system error message for errno at function entry and final dot
8823 for output compatibility with throw_perror_with_name. */
8824
8825 static void
8826 unpush_and_perror (const char *string)
8827 {
8828 int saved_errno = errno;
8829
8830 remote_unpush_target ();
8831 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8832 safe_strerror (saved_errno));
8833 }
8834
8835 /* Read a single character from the remote end. The current quit
8836 handler is overridden to avoid quitting in the middle of packet
8837 sequence, as that would break communication with the remote server.
8838 See remote_serial_quit_handler for more detail. */
8839
8840 static int
8841 readchar (int timeout)
8842 {
8843 int ch;
8844 struct remote_state *rs = get_remote_state ();
8845
8846 {
8847 scoped_restore restore_quit
8848 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8849
8850 rs->got_ctrlc_during_io = 0;
8851
8852 ch = serial_readchar (rs->remote_desc, timeout);
8853
8854 if (rs->got_ctrlc_during_io)
8855 set_quit_flag ();
8856 }
8857
8858 if (ch >= 0)
8859 return ch;
8860
8861 switch ((enum serial_rc) ch)
8862 {
8863 case SERIAL_EOF:
8864 remote_unpush_target ();
8865 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8866 /* no return */
8867 case SERIAL_ERROR:
8868 unpush_and_perror (_("Remote communication error. "
8869 "Target disconnected."));
8870 /* no return */
8871 case SERIAL_TIMEOUT:
8872 break;
8873 }
8874 return ch;
8875 }
8876
8877 /* Wrapper for serial_write that closes the target and throws if
8878 writing fails. The current quit handler is overridden to avoid
8879 quitting in the middle of packet sequence, as that would break
8880 communication with the remote server. See
8881 remote_serial_quit_handler for more detail. */
8882
8883 static void
8884 remote_serial_write (const char *str, int len)
8885 {
8886 struct remote_state *rs = get_remote_state ();
8887
8888 scoped_restore restore_quit
8889 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8890
8891 rs->got_ctrlc_during_io = 0;
8892
8893 if (serial_write (rs->remote_desc, str, len))
8894 {
8895 unpush_and_perror (_("Remote communication error. "
8896 "Target disconnected."));
8897 }
8898
8899 if (rs->got_ctrlc_during_io)
8900 set_quit_flag ();
8901 }
8902
8903 /* Return a string representing an escaped version of BUF, of len N.
8904 E.g. \n is converted to \\n, \t to \\t, etc. */
8905
8906 static std::string
8907 escape_buffer (const char *buf, int n)
8908 {
8909 string_file stb;
8910
8911 stb.putstrn (buf, n, '\\');
8912 return std::move (stb.string ());
8913 }
8914
8915 /* Display a null-terminated packet on stdout, for debugging, using C
8916 string notation. */
8917
8918 static void
8919 print_packet (const char *buf)
8920 {
8921 puts_filtered ("\"");
8922 fputstr_filtered (buf, '"', gdb_stdout);
8923 puts_filtered ("\"");
8924 }
8925
8926 int
8927 putpkt (const char *buf)
8928 {
8929 return putpkt_binary (buf, strlen (buf));
8930 }
8931
8932 /* Send a packet to the remote machine, with error checking. The data
8933 of the packet is in BUF. The string in BUF can be at most
8934 get_remote_packet_size () - 5 to account for the $, # and checksum,
8935 and for a possible /0 if we are debugging (remote_debug) and want
8936 to print the sent packet as a string. */
8937
8938 static int
8939 putpkt_binary (const char *buf, int cnt)
8940 {
8941 struct remote_state *rs = get_remote_state ();
8942 int i;
8943 unsigned char csum = 0;
8944 gdb::def_vector<char> data (cnt + 6);
8945 char *buf2 = data.data ();
8946
8947 int ch;
8948 int tcount = 0;
8949 char *p;
8950
8951 /* Catch cases like trying to read memory or listing threads while
8952 we're waiting for a stop reply. The remote server wouldn't be
8953 ready to handle this request, so we'd hang and timeout. We don't
8954 have to worry about this in synchronous mode, because in that
8955 case it's not possible to issue a command while the target is
8956 running. This is not a problem in non-stop mode, because in that
8957 case, the stub is always ready to process serial input. */
8958 if (!target_is_non_stop_p ()
8959 && target_is_async_p ()
8960 && rs->waiting_for_stop_reply)
8961 {
8962 error (_("Cannot execute this command while the target is running.\n"
8963 "Use the \"interrupt\" command to stop the target\n"
8964 "and then try again."));
8965 }
8966
8967 /* We're sending out a new packet. Make sure we don't look at a
8968 stale cached response. */
8969 rs->cached_wait_status = 0;
8970
8971 /* Copy the packet into buffer BUF2, encapsulating it
8972 and giving it a checksum. */
8973
8974 p = buf2;
8975 *p++ = '$';
8976
8977 for (i = 0; i < cnt; i++)
8978 {
8979 csum += buf[i];
8980 *p++ = buf[i];
8981 }
8982 *p++ = '#';
8983 *p++ = tohex ((csum >> 4) & 0xf);
8984 *p++ = tohex (csum & 0xf);
8985
8986 /* Send it over and over until we get a positive ack. */
8987
8988 while (1)
8989 {
8990 int started_error_output = 0;
8991
8992 if (remote_debug)
8993 {
8994 *p = '\0';
8995
8996 int len = (int) (p - buf2);
8997
8998 std::string str
8999 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9000
9001 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9002
9003 if (len > REMOTE_DEBUG_MAX_CHAR)
9004 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9005 len - REMOTE_DEBUG_MAX_CHAR);
9006
9007 fprintf_unfiltered (gdb_stdlog, "...");
9008
9009 gdb_flush (gdb_stdlog);
9010 }
9011 remote_serial_write (buf2, p - buf2);
9012
9013 /* If this is a no acks version of the remote protocol, send the
9014 packet and move on. */
9015 if (rs->noack_mode)
9016 break;
9017
9018 /* Read until either a timeout occurs (-2) or '+' is read.
9019 Handle any notification that arrives in the mean time. */
9020 while (1)
9021 {
9022 ch = readchar (remote_timeout);
9023
9024 if (remote_debug)
9025 {
9026 switch (ch)
9027 {
9028 case '+':
9029 case '-':
9030 case SERIAL_TIMEOUT:
9031 case '$':
9032 case '%':
9033 if (started_error_output)
9034 {
9035 putchar_unfiltered ('\n');
9036 started_error_output = 0;
9037 }
9038 }
9039 }
9040
9041 switch (ch)
9042 {
9043 case '+':
9044 if (remote_debug)
9045 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9046 return 1;
9047 case '-':
9048 if (remote_debug)
9049 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9050 /* FALLTHROUGH */
9051 case SERIAL_TIMEOUT:
9052 tcount++;
9053 if (tcount > 3)
9054 return 0;
9055 break; /* Retransmit buffer. */
9056 case '$':
9057 {
9058 if (remote_debug)
9059 fprintf_unfiltered (gdb_stdlog,
9060 "Packet instead of Ack, ignoring it\n");
9061 /* It's probably an old response sent because an ACK
9062 was lost. Gobble up the packet and ack it so it
9063 doesn't get retransmitted when we resend this
9064 packet. */
9065 skip_frame ();
9066 remote_serial_write ("+", 1);
9067 continue; /* Now, go look for +. */
9068 }
9069
9070 case '%':
9071 {
9072 int val;
9073
9074 /* If we got a notification, handle it, and go back to looking
9075 for an ack. */
9076 /* We've found the start of a notification. Now
9077 collect the data. */
9078 val = read_frame (&rs->buf, &rs->buf_size);
9079 if (val >= 0)
9080 {
9081 if (remote_debug)
9082 {
9083 std::string str = escape_buffer (rs->buf, val);
9084
9085 fprintf_unfiltered (gdb_stdlog,
9086 " Notification received: %s\n",
9087 str.c_str ());
9088 }
9089 handle_notification (rs->notif_state, rs->buf);
9090 /* We're in sync now, rewait for the ack. */
9091 tcount = 0;
9092 }
9093 else
9094 {
9095 if (remote_debug)
9096 {
9097 if (!started_error_output)
9098 {
9099 started_error_output = 1;
9100 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9101 }
9102 fputc_unfiltered (ch & 0177, gdb_stdlog);
9103 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9104 }
9105 }
9106 continue;
9107 }
9108 /* fall-through */
9109 default:
9110 if (remote_debug)
9111 {
9112 if (!started_error_output)
9113 {
9114 started_error_output = 1;
9115 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9116 }
9117 fputc_unfiltered (ch & 0177, gdb_stdlog);
9118 }
9119 continue;
9120 }
9121 break; /* Here to retransmit. */
9122 }
9123
9124 #if 0
9125 /* This is wrong. If doing a long backtrace, the user should be
9126 able to get out next time we call QUIT, without anything as
9127 violent as interrupt_query. If we want to provide a way out of
9128 here without getting to the next QUIT, it should be based on
9129 hitting ^C twice as in remote_wait. */
9130 if (quit_flag)
9131 {
9132 quit_flag = 0;
9133 interrupt_query ();
9134 }
9135 #endif
9136 }
9137
9138 return 0;
9139 }
9140
9141 /* Come here after finding the start of a frame when we expected an
9142 ack. Do our best to discard the rest of this packet. */
9143
9144 static void
9145 skip_frame (void)
9146 {
9147 int c;
9148
9149 while (1)
9150 {
9151 c = readchar (remote_timeout);
9152 switch (c)
9153 {
9154 case SERIAL_TIMEOUT:
9155 /* Nothing we can do. */
9156 return;
9157 case '#':
9158 /* Discard the two bytes of checksum and stop. */
9159 c = readchar (remote_timeout);
9160 if (c >= 0)
9161 c = readchar (remote_timeout);
9162
9163 return;
9164 case '*': /* Run length encoding. */
9165 /* Discard the repeat count. */
9166 c = readchar (remote_timeout);
9167 if (c < 0)
9168 return;
9169 break;
9170 default:
9171 /* A regular character. */
9172 break;
9173 }
9174 }
9175 }
9176
9177 /* Come here after finding the start of the frame. Collect the rest
9178 into *BUF, verifying the checksum, length, and handling run-length
9179 compression. NUL terminate the buffer. If there is not enough room,
9180 expand *BUF using xrealloc.
9181
9182 Returns -1 on error, number of characters in buffer (ignoring the
9183 trailing NULL) on success. (could be extended to return one of the
9184 SERIAL status indications). */
9185
9186 static long
9187 read_frame (char **buf_p,
9188 long *sizeof_buf)
9189 {
9190 unsigned char csum;
9191 long bc;
9192 int c;
9193 char *buf = *buf_p;
9194 struct remote_state *rs = get_remote_state ();
9195
9196 csum = 0;
9197 bc = 0;
9198
9199 while (1)
9200 {
9201 c = readchar (remote_timeout);
9202 switch (c)
9203 {
9204 case SERIAL_TIMEOUT:
9205 if (remote_debug)
9206 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9207 return -1;
9208 case '$':
9209 if (remote_debug)
9210 fputs_filtered ("Saw new packet start in middle of old one\n",
9211 gdb_stdlog);
9212 return -1; /* Start a new packet, count retries. */
9213 case '#':
9214 {
9215 unsigned char pktcsum;
9216 int check_0 = 0;
9217 int check_1 = 0;
9218
9219 buf[bc] = '\0';
9220
9221 check_0 = readchar (remote_timeout);
9222 if (check_0 >= 0)
9223 check_1 = readchar (remote_timeout);
9224
9225 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9226 {
9227 if (remote_debug)
9228 fputs_filtered ("Timeout in checksum, retrying\n",
9229 gdb_stdlog);
9230 return -1;
9231 }
9232 else if (check_0 < 0 || check_1 < 0)
9233 {
9234 if (remote_debug)
9235 fputs_filtered ("Communication error in checksum\n",
9236 gdb_stdlog);
9237 return -1;
9238 }
9239
9240 /* Don't recompute the checksum; with no ack packets we
9241 don't have any way to indicate a packet retransmission
9242 is necessary. */
9243 if (rs->noack_mode)
9244 return bc;
9245
9246 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9247 if (csum == pktcsum)
9248 return bc;
9249
9250 if (remote_debug)
9251 {
9252 std::string str = escape_buffer (buf, bc);
9253
9254 fprintf_unfiltered (gdb_stdlog,
9255 "Bad checksum, sentsum=0x%x, "
9256 "csum=0x%x, buf=%s\n",
9257 pktcsum, csum, str.c_str ());
9258 }
9259 /* Number of characters in buffer ignoring trailing
9260 NULL. */
9261 return -1;
9262 }
9263 case '*': /* Run length encoding. */
9264 {
9265 int repeat;
9266
9267 csum += c;
9268 c = readchar (remote_timeout);
9269 csum += c;
9270 repeat = c - ' ' + 3; /* Compute repeat count. */
9271
9272 /* The character before ``*'' is repeated. */
9273
9274 if (repeat > 0 && repeat <= 255 && bc > 0)
9275 {
9276 if (bc + repeat - 1 >= *sizeof_buf - 1)
9277 {
9278 /* Make some more room in the buffer. */
9279 *sizeof_buf += repeat;
9280 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9281 buf = *buf_p;
9282 }
9283
9284 memset (&buf[bc], buf[bc - 1], repeat);
9285 bc += repeat;
9286 continue;
9287 }
9288
9289 buf[bc] = '\0';
9290 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9291 return -1;
9292 }
9293 default:
9294 if (bc >= *sizeof_buf - 1)
9295 {
9296 /* Make some more room in the buffer. */
9297 *sizeof_buf *= 2;
9298 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9299 buf = *buf_p;
9300 }
9301
9302 buf[bc++] = c;
9303 csum += c;
9304 continue;
9305 }
9306 }
9307 }
9308
9309 /* Read a packet from the remote machine, with error checking, and
9310 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9311 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9312 rather than timing out; this is used (in synchronous mode) to wait
9313 for a target that is is executing user code to stop. */
9314 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9315 don't have to change all the calls to getpkt to deal with the
9316 return value, because at the moment I don't know what the right
9317 thing to do it for those. */
9318 void
9319 getpkt (char **buf,
9320 long *sizeof_buf,
9321 int forever)
9322 {
9323 getpkt_sane (buf, sizeof_buf, forever);
9324 }
9325
9326
9327 /* Read a packet from the remote machine, with error checking, and
9328 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9329 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9330 rather than timing out; this is used (in synchronous mode) to wait
9331 for a target that is is executing user code to stop. If FOREVER ==
9332 0, this function is allowed to time out gracefully and return an
9333 indication of this to the caller. Otherwise return the number of
9334 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9335 enough reason to return to the caller. *IS_NOTIF is an output
9336 boolean that indicates whether *BUF holds a notification or not
9337 (a regular packet). */
9338
9339 static int
9340 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9341 int expecting_notif, int *is_notif)
9342 {
9343 struct remote_state *rs = get_remote_state ();
9344 int c;
9345 int tries;
9346 int timeout;
9347 int val = -1;
9348
9349 /* We're reading a new response. Make sure we don't look at a
9350 previously cached response. */
9351 rs->cached_wait_status = 0;
9352
9353 strcpy (*buf, "timeout");
9354
9355 if (forever)
9356 timeout = watchdog > 0 ? watchdog : -1;
9357 else if (expecting_notif)
9358 timeout = 0; /* There should already be a char in the buffer. If
9359 not, bail out. */
9360 else
9361 timeout = remote_timeout;
9362
9363 #define MAX_TRIES 3
9364
9365 /* Process any number of notifications, and then return when
9366 we get a packet. */
9367 for (;;)
9368 {
9369 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9370 times. */
9371 for (tries = 1; tries <= MAX_TRIES; tries++)
9372 {
9373 /* This can loop forever if the remote side sends us
9374 characters continuously, but if it pauses, we'll get
9375 SERIAL_TIMEOUT from readchar because of timeout. Then
9376 we'll count that as a retry.
9377
9378 Note that even when forever is set, we will only wait
9379 forever prior to the start of a packet. After that, we
9380 expect characters to arrive at a brisk pace. They should
9381 show up within remote_timeout intervals. */
9382 do
9383 c = readchar (timeout);
9384 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9385
9386 if (c == SERIAL_TIMEOUT)
9387 {
9388 if (expecting_notif)
9389 return -1; /* Don't complain, it's normal to not get
9390 anything in this case. */
9391
9392 if (forever) /* Watchdog went off? Kill the target. */
9393 {
9394 remote_unpush_target ();
9395 throw_error (TARGET_CLOSE_ERROR,
9396 _("Watchdog timeout has expired. "
9397 "Target detached."));
9398 }
9399 if (remote_debug)
9400 fputs_filtered ("Timed out.\n", gdb_stdlog);
9401 }
9402 else
9403 {
9404 /* We've found the start of a packet or notification.
9405 Now collect the data. */
9406 val = read_frame (buf, sizeof_buf);
9407 if (val >= 0)
9408 break;
9409 }
9410
9411 remote_serial_write ("-", 1);
9412 }
9413
9414 if (tries > MAX_TRIES)
9415 {
9416 /* We have tried hard enough, and just can't receive the
9417 packet/notification. Give up. */
9418 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9419
9420 /* Skip the ack char if we're in no-ack mode. */
9421 if (!rs->noack_mode)
9422 remote_serial_write ("+", 1);
9423 return -1;
9424 }
9425
9426 /* If we got an ordinary packet, return that to our caller. */
9427 if (c == '$')
9428 {
9429 if (remote_debug)
9430 {
9431 std::string str
9432 = escape_buffer (*buf,
9433 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9434
9435 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9436 str.c_str ());
9437
9438 if (val > REMOTE_DEBUG_MAX_CHAR)
9439 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9440 val - REMOTE_DEBUG_MAX_CHAR);
9441
9442 fprintf_unfiltered (gdb_stdlog, "\n");
9443 }
9444
9445 /* Skip the ack char if we're in no-ack mode. */
9446 if (!rs->noack_mode)
9447 remote_serial_write ("+", 1);
9448 if (is_notif != NULL)
9449 *is_notif = 0;
9450 return val;
9451 }
9452
9453 /* If we got a notification, handle it, and go back to looking
9454 for a packet. */
9455 else
9456 {
9457 gdb_assert (c == '%');
9458
9459 if (remote_debug)
9460 {
9461 std::string str = escape_buffer (*buf, val);
9462
9463 fprintf_unfiltered (gdb_stdlog,
9464 " Notification received: %s\n",
9465 str.c_str ());
9466 }
9467 if (is_notif != NULL)
9468 *is_notif = 1;
9469
9470 handle_notification (rs->notif_state, *buf);
9471
9472 /* Notifications require no acknowledgement. */
9473
9474 if (expecting_notif)
9475 return val;
9476 }
9477 }
9478 }
9479
9480 static int
9481 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9482 {
9483 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9484 }
9485
9486 static int
9487 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9488 int *is_notif)
9489 {
9490 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9491 is_notif);
9492 }
9493
9494 /* Check whether EVENT is a fork event for the process specified
9495 by the pid passed in DATA, and if it is, kill the fork child. */
9496
9497 static int
9498 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9499 QUEUE_ITER (stop_reply_p) *iter,
9500 stop_reply_p event,
9501 void *data)
9502 {
9503 struct queue_iter_param *param = (struct queue_iter_param *) data;
9504 int parent_pid = *(int *) param->input;
9505
9506 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9507 {
9508 struct remote_state *rs = get_remote_state ();
9509 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9510 int res;
9511
9512 res = remote_vkill (child_pid, rs);
9513 if (res != 0)
9514 error (_("Can't kill fork child process %d"), child_pid);
9515 }
9516
9517 return 1;
9518 }
9519
9520 /* Kill any new fork children of process PID that haven't been
9521 processed by follow_fork. */
9522
9523 static void
9524 kill_new_fork_children (int pid, struct remote_state *rs)
9525 {
9526 struct thread_info *thread;
9527 struct notif_client *notif = &notif_client_stop;
9528 struct queue_iter_param param;
9529
9530 /* Kill the fork child threads of any threads in process PID
9531 that are stopped at a fork event. */
9532 ALL_NON_EXITED_THREADS (thread)
9533 {
9534 struct target_waitstatus *ws = &thread->pending_follow;
9535
9536 if (is_pending_fork_parent (ws, pid, thread->ptid))
9537 {
9538 struct remote_state *rs = get_remote_state ();
9539 int child_pid = ptid_get_pid (ws->value.related_pid);
9540 int res;
9541
9542 res = remote_vkill (child_pid, rs);
9543 if (res != 0)
9544 error (_("Can't kill fork child process %d"), child_pid);
9545 }
9546 }
9547
9548 /* Check for any pending fork events (not reported or processed yet)
9549 in process PID and kill those fork child threads as well. */
9550 remote_notif_get_pending_events (notif);
9551 param.input = &pid;
9552 param.output = NULL;
9553 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9554 kill_child_of_pending_fork, &param);
9555 }
9556
9557 \f
9558 /* Target hook to kill the current inferior. */
9559
9560 void
9561 remote_target::kill ()
9562 {
9563 int res = -1;
9564 int pid = ptid_get_pid (inferior_ptid);
9565 struct remote_state *rs = get_remote_state ();
9566
9567 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9568 {
9569 /* If we're stopped while forking and we haven't followed yet,
9570 kill the child task. We need to do this before killing the
9571 parent task because if this is a vfork then the parent will
9572 be sleeping. */
9573 kill_new_fork_children (pid, rs);
9574
9575 res = remote_vkill (pid, rs);
9576 if (res == 0)
9577 {
9578 target_mourn_inferior (inferior_ptid);
9579 return;
9580 }
9581 }
9582
9583 /* If we are in 'target remote' mode and we are killing the only
9584 inferior, then we will tell gdbserver to exit and unpush the
9585 target. */
9586 if (res == -1 && !remote_multi_process_p (rs)
9587 && number_of_live_inferiors () == 1)
9588 {
9589 remote_kill_k ();
9590
9591 /* We've killed the remote end, we get to mourn it. If we are
9592 not in extended mode, mourning the inferior also unpushes
9593 remote_ops from the target stack, which closes the remote
9594 connection. */
9595 target_mourn_inferior (inferior_ptid);
9596
9597 return;
9598 }
9599
9600 error (_("Can't kill process"));
9601 }
9602
9603 /* Send a kill request to the target using the 'vKill' packet. */
9604
9605 static int
9606 remote_vkill (int pid, struct remote_state *rs)
9607 {
9608 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9609 return -1;
9610
9611 /* Tell the remote target to detach. */
9612 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9613 putpkt (rs->buf);
9614 getpkt (&rs->buf, &rs->buf_size, 0);
9615
9616 switch (packet_ok (rs->buf,
9617 &remote_protocol_packets[PACKET_vKill]))
9618 {
9619 case PACKET_OK:
9620 return 0;
9621 case PACKET_ERROR:
9622 return 1;
9623 case PACKET_UNKNOWN:
9624 return -1;
9625 default:
9626 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9627 }
9628 }
9629
9630 /* Send a kill request to the target using the 'k' packet. */
9631
9632 static void
9633 remote_kill_k (void)
9634 {
9635 /* Catch errors so the user can quit from gdb even when we
9636 aren't on speaking terms with the remote system. */
9637 TRY
9638 {
9639 putpkt ("k");
9640 }
9641 CATCH (ex, RETURN_MASK_ERROR)
9642 {
9643 if (ex.error == TARGET_CLOSE_ERROR)
9644 {
9645 /* If we got an (EOF) error that caused the target
9646 to go away, then we're done, that's what we wanted.
9647 "k" is susceptible to cause a premature EOF, given
9648 that the remote server isn't actually required to
9649 reply to "k", and it can happen that it doesn't
9650 even get to reply ACK to the "k". */
9651 return;
9652 }
9653
9654 /* Otherwise, something went wrong. We didn't actually kill
9655 the target. Just propagate the exception, and let the
9656 user or higher layers decide what to do. */
9657 throw_exception (ex);
9658 }
9659 END_CATCH
9660 }
9661
9662 void
9663 remote_target::mourn_inferior ()
9664 {
9665 struct remote_state *rs = get_remote_state ();
9666
9667 /* In 'target remote' mode with one inferior, we close the connection. */
9668 if (!rs->extended && number_of_live_inferiors () <= 1)
9669 {
9670 unpush_target (this);
9671
9672 /* remote_close takes care of doing most of the clean up. */
9673 generic_mourn_inferior ();
9674 return;
9675 }
9676
9677 /* In case we got here due to an error, but we're going to stay
9678 connected. */
9679 rs->waiting_for_stop_reply = 0;
9680
9681 /* If the current general thread belonged to the process we just
9682 detached from or has exited, the remote side current general
9683 thread becomes undefined. Considering a case like this:
9684
9685 - We just got here due to a detach.
9686 - The process that we're detaching from happens to immediately
9687 report a global breakpoint being hit in non-stop mode, in the
9688 same thread we had selected before.
9689 - GDB attaches to this process again.
9690 - This event happens to be the next event we handle.
9691
9692 GDB would consider that the current general thread didn't need to
9693 be set on the stub side (with Hg), since for all it knew,
9694 GENERAL_THREAD hadn't changed.
9695
9696 Notice that although in all-stop mode, the remote server always
9697 sets the current thread to the thread reporting the stop event,
9698 that doesn't happen in non-stop mode; in non-stop, the stub *must
9699 not* change the current thread when reporting a breakpoint hit,
9700 due to the decoupling of event reporting and event handling.
9701
9702 To keep things simple, we always invalidate our notion of the
9703 current thread. */
9704 record_currthread (rs, minus_one_ptid);
9705
9706 /* Call common code to mark the inferior as not running. */
9707 generic_mourn_inferior ();
9708
9709 if (!have_inferiors ())
9710 {
9711 if (!remote_multi_process_p (rs))
9712 {
9713 /* Check whether the target is running now - some remote stubs
9714 automatically restart after kill. */
9715 putpkt ("?");
9716 getpkt (&rs->buf, &rs->buf_size, 0);
9717
9718 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9719 {
9720 /* Assume that the target has been restarted. Set
9721 inferior_ptid so that bits of core GDB realizes
9722 there's something here, e.g., so that the user can
9723 say "kill" again. */
9724 inferior_ptid = magic_null_ptid;
9725 }
9726 }
9727 }
9728 }
9729
9730 bool
9731 extended_remote_target::supports_disable_randomization ()
9732 {
9733 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9734 }
9735
9736 static void
9737 extended_remote_disable_randomization (int val)
9738 {
9739 struct remote_state *rs = get_remote_state ();
9740 char *reply;
9741
9742 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9743 val);
9744 putpkt (rs->buf);
9745 reply = remote_get_noisy_reply ();
9746 if (*reply == '\0')
9747 error (_("Target does not support QDisableRandomization."));
9748 if (strcmp (reply, "OK") != 0)
9749 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9750 }
9751
9752 static int
9753 extended_remote_run (const std::string &args)
9754 {
9755 struct remote_state *rs = get_remote_state ();
9756 int len;
9757 const char *remote_exec_file = get_remote_exec_file ();
9758
9759 /* If the user has disabled vRun support, or we have detected that
9760 support is not available, do not try it. */
9761 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9762 return -1;
9763
9764 strcpy (rs->buf, "vRun;");
9765 len = strlen (rs->buf);
9766
9767 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9768 error (_("Remote file name too long for run packet"));
9769 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9770 strlen (remote_exec_file));
9771
9772 if (!args.empty ())
9773 {
9774 int i;
9775
9776 gdb_argv argv (args.c_str ());
9777 for (i = 0; argv[i] != NULL; i++)
9778 {
9779 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9780 error (_("Argument list too long for run packet"));
9781 rs->buf[len++] = ';';
9782 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9783 strlen (argv[i]));
9784 }
9785 }
9786
9787 rs->buf[len++] = '\0';
9788
9789 putpkt (rs->buf);
9790 getpkt (&rs->buf, &rs->buf_size, 0);
9791
9792 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9793 {
9794 case PACKET_OK:
9795 /* We have a wait response. All is well. */
9796 return 0;
9797 case PACKET_UNKNOWN:
9798 return -1;
9799 case PACKET_ERROR:
9800 if (remote_exec_file[0] == '\0')
9801 error (_("Running the default executable on the remote target failed; "
9802 "try \"set remote exec-file\"?"));
9803 else
9804 error (_("Running \"%s\" on the remote target failed"),
9805 remote_exec_file);
9806 default:
9807 gdb_assert_not_reached (_("bad switch"));
9808 }
9809 }
9810
9811 /* Helper function to send set/unset environment packets. ACTION is
9812 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9813 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9814 sent. */
9815
9816 static void
9817 send_environment_packet (struct remote_state *rs,
9818 const char *action,
9819 const char *packet,
9820 const char *value)
9821 {
9822 /* Convert the environment variable to an hex string, which
9823 is the best format to be transmitted over the wire. */
9824 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9825 strlen (value));
9826
9827 xsnprintf (rs->buf, get_remote_packet_size (),
9828 "%s:%s", packet, encoded_value.c_str ());
9829
9830 putpkt (rs->buf);
9831 getpkt (&rs->buf, &rs->buf_size, 0);
9832 if (strcmp (rs->buf, "OK") != 0)
9833 warning (_("Unable to %s environment variable '%s' on remote."),
9834 action, value);
9835 }
9836
9837 /* Helper function to handle the QEnvironment* packets. */
9838
9839 static void
9840 extended_remote_environment_support (struct remote_state *rs)
9841 {
9842 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9843 {
9844 putpkt ("QEnvironmentReset");
9845 getpkt (&rs->buf, &rs->buf_size, 0);
9846 if (strcmp (rs->buf, "OK") != 0)
9847 warning (_("Unable to reset environment on remote."));
9848 }
9849
9850 gdb_environ *e = &current_inferior ()->environment;
9851
9852 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9853 for (const std::string &el : e->user_set_env ())
9854 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9855 el.c_str ());
9856
9857 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9858 for (const std::string &el : e->user_unset_env ())
9859 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9860 }
9861
9862 /* Helper function to set the current working directory for the
9863 inferior in the remote target. */
9864
9865 static void
9866 extended_remote_set_inferior_cwd (struct remote_state *rs)
9867 {
9868 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9869 {
9870 const char *inferior_cwd = get_inferior_cwd ();
9871
9872 if (inferior_cwd != NULL)
9873 {
9874 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9875 strlen (inferior_cwd));
9876
9877 xsnprintf (rs->buf, get_remote_packet_size (),
9878 "QSetWorkingDir:%s", hexpath.c_str ());
9879 }
9880 else
9881 {
9882 /* An empty inferior_cwd means that the user wants us to
9883 reset the remote server's inferior's cwd. */
9884 xsnprintf (rs->buf, get_remote_packet_size (),
9885 "QSetWorkingDir:");
9886 }
9887
9888 putpkt (rs->buf);
9889 getpkt (&rs->buf, &rs->buf_size, 0);
9890 if (packet_ok (rs->buf,
9891 &remote_protocol_packets[PACKET_QSetWorkingDir])
9892 != PACKET_OK)
9893 error (_("\
9894 Remote replied unexpectedly while setting the inferior's working\n\
9895 directory: %s"),
9896 rs->buf);
9897
9898 }
9899 }
9900
9901 /* In the extended protocol we want to be able to do things like
9902 "run" and have them basically work as expected. So we need
9903 a special create_inferior function. We support changing the
9904 executable file and the command line arguments, but not the
9905 environment. */
9906
9907 void
9908 extended_remote_target::create_inferior (const char *exec_file,
9909 const std::string &args,
9910 char **env, int from_tty)
9911 {
9912 int run_worked;
9913 char *stop_reply;
9914 struct remote_state *rs = get_remote_state ();
9915 const char *remote_exec_file = get_remote_exec_file ();
9916
9917 /* If running asynchronously, register the target file descriptor
9918 with the event loop. */
9919 if (target_can_async_p ())
9920 target_async (1);
9921
9922 /* Disable address space randomization if requested (and supported). */
9923 if (supports_disable_randomization ())
9924 extended_remote_disable_randomization (disable_randomization);
9925
9926 /* If startup-with-shell is on, we inform gdbserver to start the
9927 remote inferior using a shell. */
9928 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9929 {
9930 xsnprintf (rs->buf, get_remote_packet_size (),
9931 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9932 putpkt (rs->buf);
9933 getpkt (&rs->buf, &rs->buf_size, 0);
9934 if (strcmp (rs->buf, "OK") != 0)
9935 error (_("\
9936 Remote replied unexpectedly while setting startup-with-shell: %s"),
9937 rs->buf);
9938 }
9939
9940 extended_remote_environment_support (rs);
9941
9942 extended_remote_set_inferior_cwd (rs);
9943
9944 /* Now restart the remote server. */
9945 run_worked = extended_remote_run (args) != -1;
9946 if (!run_worked)
9947 {
9948 /* vRun was not supported. Fail if we need it to do what the
9949 user requested. */
9950 if (remote_exec_file[0])
9951 error (_("Remote target does not support \"set remote exec-file\""));
9952 if (!args.empty ())
9953 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9954
9955 /* Fall back to "R". */
9956 extended_remote_restart ();
9957 }
9958
9959 if (!have_inferiors ())
9960 {
9961 /* Clean up from the last time we ran, before we mark the target
9962 running again. This will mark breakpoints uninserted, and
9963 get_offsets may insert breakpoints. */
9964 init_thread_list ();
9965 init_wait_for_inferior ();
9966 }
9967
9968 /* vRun's success return is a stop reply. */
9969 stop_reply = run_worked ? rs->buf : NULL;
9970 add_current_inferior_and_thread (stop_reply);
9971
9972 /* Get updated offsets, if the stub uses qOffsets. */
9973 get_offsets ();
9974 }
9975 \f
9976
9977 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9978 the list of conditions (in agent expression bytecode format), if any, the
9979 target needs to evaluate. The output is placed into the packet buffer
9980 started from BUF and ended at BUF_END. */
9981
9982 static int
9983 remote_add_target_side_condition (struct gdbarch *gdbarch,
9984 struct bp_target_info *bp_tgt, char *buf,
9985 char *buf_end)
9986 {
9987 if (bp_tgt->conditions.empty ())
9988 return 0;
9989
9990 buf += strlen (buf);
9991 xsnprintf (buf, buf_end - buf, "%s", ";");
9992 buf++;
9993
9994 /* Send conditions to the target. */
9995 for (agent_expr *aexpr : bp_tgt->conditions)
9996 {
9997 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9998 buf += strlen (buf);
9999 for (int i = 0; i < aexpr->len; ++i)
10000 buf = pack_hex_byte (buf, aexpr->buf[i]);
10001 *buf = '\0';
10002 }
10003 return 0;
10004 }
10005
10006 static void
10007 remote_add_target_side_commands (struct gdbarch *gdbarch,
10008 struct bp_target_info *bp_tgt, char *buf)
10009 {
10010 if (bp_tgt->tcommands.empty ())
10011 return;
10012
10013 buf += strlen (buf);
10014
10015 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10016 buf += strlen (buf);
10017
10018 /* Concatenate all the agent expressions that are commands into the
10019 cmds parameter. */
10020 for (agent_expr *aexpr : bp_tgt->tcommands)
10021 {
10022 sprintf (buf, "X%x,", aexpr->len);
10023 buf += strlen (buf);
10024 for (int i = 0; i < aexpr->len; ++i)
10025 buf = pack_hex_byte (buf, aexpr->buf[i]);
10026 *buf = '\0';
10027 }
10028 }
10029
10030 /* Insert a breakpoint. On targets that have software breakpoint
10031 support, we ask the remote target to do the work; on targets
10032 which don't, we insert a traditional memory breakpoint. */
10033
10034 int
10035 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10036 struct bp_target_info *bp_tgt)
10037 {
10038 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10039 If it succeeds, then set the support to PACKET_ENABLE. If it
10040 fails, and the user has explicitly requested the Z support then
10041 report an error, otherwise, mark it disabled and go on. */
10042
10043 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10044 {
10045 CORE_ADDR addr = bp_tgt->reqstd_address;
10046 struct remote_state *rs;
10047 char *p, *endbuf;
10048
10049 /* Make sure the remote is pointing at the right process, if
10050 necessary. */
10051 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10052 set_general_process ();
10053
10054 rs = get_remote_state ();
10055 p = rs->buf;
10056 endbuf = rs->buf + get_remote_packet_size ();
10057
10058 *(p++) = 'Z';
10059 *(p++) = '0';
10060 *(p++) = ',';
10061 addr = (ULONGEST) remote_address_masked (addr);
10062 p += hexnumstr (p, addr);
10063 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10064
10065 if (supports_evaluation_of_breakpoint_conditions ())
10066 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10067
10068 if (can_run_breakpoint_commands ())
10069 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10070
10071 putpkt (rs->buf);
10072 getpkt (&rs->buf, &rs->buf_size, 0);
10073
10074 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10075 {
10076 case PACKET_ERROR:
10077 return -1;
10078 case PACKET_OK:
10079 return 0;
10080 case PACKET_UNKNOWN:
10081 break;
10082 }
10083 }
10084
10085 /* If this breakpoint has target-side commands but this stub doesn't
10086 support Z0 packets, throw error. */
10087 if (!bp_tgt->tcommands.empty ())
10088 throw_error (NOT_SUPPORTED_ERROR, _("\
10089 Target doesn't support breakpoints that have target side commands."));
10090
10091 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10092 }
10093
10094 int
10095 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10096 struct bp_target_info *bp_tgt,
10097 enum remove_bp_reason reason)
10098 {
10099 CORE_ADDR addr = bp_tgt->placed_address;
10100 struct remote_state *rs = get_remote_state ();
10101
10102 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10103 {
10104 char *p = rs->buf;
10105 char *endbuf = rs->buf + get_remote_packet_size ();
10106
10107 /* Make sure the remote is pointing at the right process, if
10108 necessary. */
10109 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10110 set_general_process ();
10111
10112 *(p++) = 'z';
10113 *(p++) = '0';
10114 *(p++) = ',';
10115
10116 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10117 p += hexnumstr (p, addr);
10118 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10119
10120 putpkt (rs->buf);
10121 getpkt (&rs->buf, &rs->buf_size, 0);
10122
10123 return (rs->buf[0] == 'E');
10124 }
10125
10126 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10127 }
10128
10129 static enum Z_packet_type
10130 watchpoint_to_Z_packet (int type)
10131 {
10132 switch (type)
10133 {
10134 case hw_write:
10135 return Z_PACKET_WRITE_WP;
10136 break;
10137 case hw_read:
10138 return Z_PACKET_READ_WP;
10139 break;
10140 case hw_access:
10141 return Z_PACKET_ACCESS_WP;
10142 break;
10143 default:
10144 internal_error (__FILE__, __LINE__,
10145 _("hw_bp_to_z: bad watchpoint type %d"), type);
10146 }
10147 }
10148
10149 int
10150 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10151 enum target_hw_bp_type type, struct expression *cond)
10152 {
10153 struct remote_state *rs = get_remote_state ();
10154 char *endbuf = rs->buf + get_remote_packet_size ();
10155 char *p;
10156 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10157
10158 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10159 return 1;
10160
10161 /* Make sure the remote is pointing at the right process, if
10162 necessary. */
10163 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10164 set_general_process ();
10165
10166 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10167 p = strchr (rs->buf, '\0');
10168 addr = remote_address_masked (addr);
10169 p += hexnumstr (p, (ULONGEST) addr);
10170 xsnprintf (p, endbuf - p, ",%x", len);
10171
10172 putpkt (rs->buf);
10173 getpkt (&rs->buf, &rs->buf_size, 0);
10174
10175 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10176 {
10177 case PACKET_ERROR:
10178 return -1;
10179 case PACKET_UNKNOWN:
10180 return 1;
10181 case PACKET_OK:
10182 return 0;
10183 }
10184 internal_error (__FILE__, __LINE__,
10185 _("remote_insert_watchpoint: reached end of function"));
10186 }
10187
10188 bool
10189 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10190 CORE_ADDR start, int length)
10191 {
10192 CORE_ADDR diff = remote_address_masked (addr - start);
10193
10194 return diff < length;
10195 }
10196
10197
10198 int
10199 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10200 enum target_hw_bp_type type, struct expression *cond)
10201 {
10202 struct remote_state *rs = get_remote_state ();
10203 char *endbuf = rs->buf + get_remote_packet_size ();
10204 char *p;
10205 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10206
10207 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10208 return -1;
10209
10210 /* Make sure the remote is pointing at the right process, if
10211 necessary. */
10212 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10213 set_general_process ();
10214
10215 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10216 p = strchr (rs->buf, '\0');
10217 addr = remote_address_masked (addr);
10218 p += hexnumstr (p, (ULONGEST) addr);
10219 xsnprintf (p, endbuf - p, ",%x", len);
10220 putpkt (rs->buf);
10221 getpkt (&rs->buf, &rs->buf_size, 0);
10222
10223 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10224 {
10225 case PACKET_ERROR:
10226 case PACKET_UNKNOWN:
10227 return -1;
10228 case PACKET_OK:
10229 return 0;
10230 }
10231 internal_error (__FILE__, __LINE__,
10232 _("remote_remove_watchpoint: reached end of function"));
10233 }
10234
10235
10236 int remote_hw_watchpoint_limit = -1;
10237 int remote_hw_watchpoint_length_limit = -1;
10238 int remote_hw_breakpoint_limit = -1;
10239
10240 int
10241 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10242 {
10243 if (remote_hw_watchpoint_length_limit == 0)
10244 return 0;
10245 else if (remote_hw_watchpoint_length_limit < 0)
10246 return 1;
10247 else if (len <= remote_hw_watchpoint_length_limit)
10248 return 1;
10249 else
10250 return 0;
10251 }
10252
10253 int
10254 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10255 {
10256 if (type == bp_hardware_breakpoint)
10257 {
10258 if (remote_hw_breakpoint_limit == 0)
10259 return 0;
10260 else if (remote_hw_breakpoint_limit < 0)
10261 return 1;
10262 else if (cnt <= remote_hw_breakpoint_limit)
10263 return 1;
10264 }
10265 else
10266 {
10267 if (remote_hw_watchpoint_limit == 0)
10268 return 0;
10269 else if (remote_hw_watchpoint_limit < 0)
10270 return 1;
10271 else if (ot)
10272 return -1;
10273 else if (cnt <= remote_hw_watchpoint_limit)
10274 return 1;
10275 }
10276 return -1;
10277 }
10278
10279 /* The to_stopped_by_sw_breakpoint method of target remote. */
10280
10281 bool
10282 remote_target::stopped_by_sw_breakpoint ()
10283 {
10284 struct thread_info *thread = inferior_thread ();
10285
10286 return (thread->priv != NULL
10287 && (get_remote_thread_info (thread)->stop_reason
10288 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10289 }
10290
10291 /* The to_supports_stopped_by_sw_breakpoint method of target
10292 remote. */
10293
10294 bool
10295 remote_target::supports_stopped_by_sw_breakpoint ()
10296 {
10297 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10298 }
10299
10300 /* The to_stopped_by_hw_breakpoint method of target remote. */
10301
10302 bool
10303 remote_target::stopped_by_hw_breakpoint ()
10304 {
10305 struct thread_info *thread = inferior_thread ();
10306
10307 return (thread->priv != NULL
10308 && (get_remote_thread_info (thread)->stop_reason
10309 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10310 }
10311
10312 /* The to_supports_stopped_by_hw_breakpoint method of target
10313 remote. */
10314
10315 bool
10316 remote_target::supports_stopped_by_hw_breakpoint ()
10317 {
10318 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10319 }
10320
10321 bool
10322 remote_target::stopped_by_watchpoint ()
10323 {
10324 struct thread_info *thread = inferior_thread ();
10325
10326 return (thread->priv != NULL
10327 && (get_remote_thread_info (thread)->stop_reason
10328 == TARGET_STOPPED_BY_WATCHPOINT));
10329 }
10330
10331 bool
10332 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10333 {
10334 struct thread_info *thread = inferior_thread ();
10335
10336 if (thread->priv != NULL
10337 && (get_remote_thread_info (thread)->stop_reason
10338 == TARGET_STOPPED_BY_WATCHPOINT))
10339 {
10340 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10341 return true;
10342 }
10343
10344 return false;
10345 }
10346
10347
10348 int
10349 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10350 struct bp_target_info *bp_tgt)
10351 {
10352 CORE_ADDR addr = bp_tgt->reqstd_address;
10353 struct remote_state *rs;
10354 char *p, *endbuf;
10355 char *message;
10356
10357 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10358 return -1;
10359
10360 /* Make sure the remote is pointing at the right process, if
10361 necessary. */
10362 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10363 set_general_process ();
10364
10365 rs = get_remote_state ();
10366 p = rs->buf;
10367 endbuf = rs->buf + get_remote_packet_size ();
10368
10369 *(p++) = 'Z';
10370 *(p++) = '1';
10371 *(p++) = ',';
10372
10373 addr = remote_address_masked (addr);
10374 p += hexnumstr (p, (ULONGEST) addr);
10375 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10376
10377 if (supports_evaluation_of_breakpoint_conditions ())
10378 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10379
10380 if (can_run_breakpoint_commands ())
10381 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10382
10383 putpkt (rs->buf);
10384 getpkt (&rs->buf, &rs->buf_size, 0);
10385
10386 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10387 {
10388 case PACKET_ERROR:
10389 if (rs->buf[1] == '.')
10390 {
10391 message = strchr (rs->buf + 2, '.');
10392 if (message)
10393 error (_("Remote failure reply: %s"), message + 1);
10394 }
10395 return -1;
10396 case PACKET_UNKNOWN:
10397 return -1;
10398 case PACKET_OK:
10399 return 0;
10400 }
10401 internal_error (__FILE__, __LINE__,
10402 _("remote_insert_hw_breakpoint: reached end of function"));
10403 }
10404
10405
10406 int
10407 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10408 struct bp_target_info *bp_tgt)
10409 {
10410 CORE_ADDR addr;
10411 struct remote_state *rs = get_remote_state ();
10412 char *p = rs->buf;
10413 char *endbuf = rs->buf + get_remote_packet_size ();
10414
10415 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10416 return -1;
10417
10418 /* Make sure the remote is pointing at the right process, if
10419 necessary. */
10420 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10421 set_general_process ();
10422
10423 *(p++) = 'z';
10424 *(p++) = '1';
10425 *(p++) = ',';
10426
10427 addr = remote_address_masked (bp_tgt->placed_address);
10428 p += hexnumstr (p, (ULONGEST) addr);
10429 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10430
10431 putpkt (rs->buf);
10432 getpkt (&rs->buf, &rs->buf_size, 0);
10433
10434 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10435 {
10436 case PACKET_ERROR:
10437 case PACKET_UNKNOWN:
10438 return -1;
10439 case PACKET_OK:
10440 return 0;
10441 }
10442 internal_error (__FILE__, __LINE__,
10443 _("remote_remove_hw_breakpoint: reached end of function"));
10444 }
10445
10446 /* Verify memory using the "qCRC:" request. */
10447
10448 int
10449 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10450 {
10451 struct remote_state *rs = get_remote_state ();
10452 unsigned long host_crc, target_crc;
10453 char *tmp;
10454
10455 /* It doesn't make sense to use qCRC if the remote target is
10456 connected but not running. */
10457 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10458 {
10459 enum packet_result result;
10460
10461 /* Make sure the remote is pointing at the right process. */
10462 set_general_process ();
10463
10464 /* FIXME: assumes lma can fit into long. */
10465 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10466 (long) lma, (long) size);
10467 putpkt (rs->buf);
10468
10469 /* Be clever; compute the host_crc before waiting for target
10470 reply. */
10471 host_crc = xcrc32 (data, size, 0xffffffff);
10472
10473 getpkt (&rs->buf, &rs->buf_size, 0);
10474
10475 result = packet_ok (rs->buf,
10476 &remote_protocol_packets[PACKET_qCRC]);
10477 if (result == PACKET_ERROR)
10478 return -1;
10479 else if (result == PACKET_OK)
10480 {
10481 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10482 target_crc = target_crc * 16 + fromhex (*tmp);
10483
10484 return (host_crc == target_crc);
10485 }
10486 }
10487
10488 return simple_verify_memory (this, data, lma, size);
10489 }
10490
10491 /* compare-sections command
10492
10493 With no arguments, compares each loadable section in the exec bfd
10494 with the same memory range on the target, and reports mismatches.
10495 Useful for verifying the image on the target against the exec file. */
10496
10497 static void
10498 compare_sections_command (const char *args, int from_tty)
10499 {
10500 asection *s;
10501 const char *sectname;
10502 bfd_size_type size;
10503 bfd_vma lma;
10504 int matched = 0;
10505 int mismatched = 0;
10506 int res;
10507 int read_only = 0;
10508
10509 if (!exec_bfd)
10510 error (_("command cannot be used without an exec file"));
10511
10512 /* Make sure the remote is pointing at the right process. */
10513 set_general_process ();
10514
10515 if (args != NULL && strcmp (args, "-r") == 0)
10516 {
10517 read_only = 1;
10518 args = NULL;
10519 }
10520
10521 for (s = exec_bfd->sections; s; s = s->next)
10522 {
10523 if (!(s->flags & SEC_LOAD))
10524 continue; /* Skip non-loadable section. */
10525
10526 if (read_only && (s->flags & SEC_READONLY) == 0)
10527 continue; /* Skip writeable sections */
10528
10529 size = bfd_get_section_size (s);
10530 if (size == 0)
10531 continue; /* Skip zero-length section. */
10532
10533 sectname = bfd_get_section_name (exec_bfd, s);
10534 if (args && strcmp (args, sectname) != 0)
10535 continue; /* Not the section selected by user. */
10536
10537 matched = 1; /* Do this section. */
10538 lma = s->lma;
10539
10540 gdb::byte_vector sectdata (size);
10541 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10542
10543 res = target_verify_memory (sectdata.data (), lma, size);
10544
10545 if (res == -1)
10546 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10547 paddress (target_gdbarch (), lma),
10548 paddress (target_gdbarch (), lma + size));
10549
10550 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10551 paddress (target_gdbarch (), lma),
10552 paddress (target_gdbarch (), lma + size));
10553 if (res)
10554 printf_filtered ("matched.\n");
10555 else
10556 {
10557 printf_filtered ("MIS-MATCHED!\n");
10558 mismatched++;
10559 }
10560 }
10561 if (mismatched > 0)
10562 warning (_("One or more sections of the target image does not match\n\
10563 the loaded file\n"));
10564 if (args && !matched)
10565 printf_filtered (_("No loaded section named '%s'.\n"), args);
10566 }
10567
10568 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10569 into remote target. The number of bytes written to the remote
10570 target is returned, or -1 for error. */
10571
10572 static enum target_xfer_status
10573 remote_write_qxfer (const char *object_name,
10574 const char *annex, const gdb_byte *writebuf,
10575 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10576 struct packet_config *packet)
10577 {
10578 int i, buf_len;
10579 ULONGEST n;
10580 struct remote_state *rs = get_remote_state ();
10581 int max_size = get_memory_write_packet_size ();
10582
10583 if (packet_config_support (packet) == PACKET_DISABLE)
10584 return TARGET_XFER_E_IO;
10585
10586 /* Insert header. */
10587 i = snprintf (rs->buf, max_size,
10588 "qXfer:%s:write:%s:%s:",
10589 object_name, annex ? annex : "",
10590 phex_nz (offset, sizeof offset));
10591 max_size -= (i + 1);
10592
10593 /* Escape as much data as fits into rs->buf. */
10594 buf_len = remote_escape_output
10595 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10596
10597 if (putpkt_binary (rs->buf, i + buf_len) < 0
10598 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10599 || packet_ok (rs->buf, packet) != PACKET_OK)
10600 return TARGET_XFER_E_IO;
10601
10602 unpack_varlen_hex (rs->buf, &n);
10603
10604 *xfered_len = n;
10605 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10606 }
10607
10608 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10609 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10610 number of bytes read is returned, or 0 for EOF, or -1 for error.
10611 The number of bytes read may be less than LEN without indicating an
10612 EOF. PACKET is checked and updated to indicate whether the remote
10613 target supports this object. */
10614
10615 static enum target_xfer_status
10616 remote_read_qxfer (const char *object_name,
10617 const char *annex,
10618 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10619 ULONGEST *xfered_len,
10620 struct packet_config *packet)
10621 {
10622 struct remote_state *rs = get_remote_state ();
10623 LONGEST i, n, packet_len;
10624
10625 if (packet_config_support (packet) == PACKET_DISABLE)
10626 return TARGET_XFER_E_IO;
10627
10628 /* Check whether we've cached an end-of-object packet that matches
10629 this request. */
10630 if (rs->finished_object)
10631 {
10632 if (strcmp (object_name, rs->finished_object) == 0
10633 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10634 && offset == rs->finished_offset)
10635 return TARGET_XFER_EOF;
10636
10637
10638 /* Otherwise, we're now reading something different. Discard
10639 the cache. */
10640 xfree (rs->finished_object);
10641 xfree (rs->finished_annex);
10642 rs->finished_object = NULL;
10643 rs->finished_annex = NULL;
10644 }
10645
10646 /* Request only enough to fit in a single packet. The actual data
10647 may not, since we don't know how much of it will need to be escaped;
10648 the target is free to respond with slightly less data. We subtract
10649 five to account for the response type and the protocol frame. */
10650 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10651 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10652 object_name, annex ? annex : "",
10653 phex_nz (offset, sizeof offset),
10654 phex_nz (n, sizeof n));
10655 i = putpkt (rs->buf);
10656 if (i < 0)
10657 return TARGET_XFER_E_IO;
10658
10659 rs->buf[0] = '\0';
10660 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10661 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10662 return TARGET_XFER_E_IO;
10663
10664 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10665 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10666
10667 /* 'm' means there is (or at least might be) more data after this
10668 batch. That does not make sense unless there's at least one byte
10669 of data in this reply. */
10670 if (rs->buf[0] == 'm' && packet_len == 1)
10671 error (_("Remote qXfer reply contained no data."));
10672
10673 /* Got some data. */
10674 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10675 packet_len - 1, readbuf, n);
10676
10677 /* 'l' is an EOF marker, possibly including a final block of data,
10678 or possibly empty. If we have the final block of a non-empty
10679 object, record this fact to bypass a subsequent partial read. */
10680 if (rs->buf[0] == 'l' && offset + i > 0)
10681 {
10682 rs->finished_object = xstrdup (object_name);
10683 rs->finished_annex = xstrdup (annex ? annex : "");
10684 rs->finished_offset = offset + i;
10685 }
10686
10687 if (i == 0)
10688 return TARGET_XFER_EOF;
10689 else
10690 {
10691 *xfered_len = i;
10692 return TARGET_XFER_OK;
10693 }
10694 }
10695
10696 enum target_xfer_status
10697 remote_target::xfer_partial (enum target_object object,
10698 const char *annex, gdb_byte *readbuf,
10699 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10700 ULONGEST *xfered_len)
10701 {
10702 struct remote_state *rs;
10703 int i;
10704 char *p2;
10705 char query_type;
10706 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10707
10708 set_remote_traceframe ();
10709 set_general_thread (inferior_ptid);
10710
10711 rs = get_remote_state ();
10712
10713 /* Handle memory using the standard memory routines. */
10714 if (object == TARGET_OBJECT_MEMORY)
10715 {
10716 /* If the remote target is connected but not running, we should
10717 pass this request down to a lower stratum (e.g. the executable
10718 file). */
10719 if (!target_has_execution)
10720 return TARGET_XFER_EOF;
10721
10722 if (writebuf != NULL)
10723 return remote_write_bytes (offset, writebuf, len, unit_size,
10724 xfered_len);
10725 else
10726 return remote_read_bytes (this, offset, readbuf, len, unit_size,
10727 xfered_len);
10728 }
10729
10730 /* Handle SPU memory using qxfer packets. */
10731 if (object == TARGET_OBJECT_SPU)
10732 {
10733 if (readbuf)
10734 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10735 xfered_len, &remote_protocol_packets
10736 [PACKET_qXfer_spu_read]);
10737 else
10738 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10739 xfered_len, &remote_protocol_packets
10740 [PACKET_qXfer_spu_write]);
10741 }
10742
10743 /* Handle extra signal info using qxfer packets. */
10744 if (object == TARGET_OBJECT_SIGNAL_INFO)
10745 {
10746 if (readbuf)
10747 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10748 xfered_len, &remote_protocol_packets
10749 [PACKET_qXfer_siginfo_read]);
10750 else
10751 return remote_write_qxfer ("siginfo", annex,
10752 writebuf, offset, len, xfered_len,
10753 &remote_protocol_packets
10754 [PACKET_qXfer_siginfo_write]);
10755 }
10756
10757 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10758 {
10759 if (readbuf)
10760 return remote_read_qxfer ("statictrace", annex,
10761 readbuf, offset, len, xfered_len,
10762 &remote_protocol_packets
10763 [PACKET_qXfer_statictrace_read]);
10764 else
10765 return TARGET_XFER_E_IO;
10766 }
10767
10768 /* Only handle flash writes. */
10769 if (writebuf != NULL)
10770 {
10771 switch (object)
10772 {
10773 case TARGET_OBJECT_FLASH:
10774 return remote_flash_write (this, offset, len, xfered_len,
10775 writebuf);
10776
10777 default:
10778 return TARGET_XFER_E_IO;
10779 }
10780 }
10781
10782 /* Map pre-existing objects onto letters. DO NOT do this for new
10783 objects!!! Instead specify new query packets. */
10784 switch (object)
10785 {
10786 case TARGET_OBJECT_AVR:
10787 query_type = 'R';
10788 break;
10789
10790 case TARGET_OBJECT_AUXV:
10791 gdb_assert (annex == NULL);
10792 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10793 xfered_len,
10794 &remote_protocol_packets[PACKET_qXfer_auxv]);
10795
10796 case TARGET_OBJECT_AVAILABLE_FEATURES:
10797 return remote_read_qxfer
10798 ("features", annex, readbuf, offset, len, xfered_len,
10799 &remote_protocol_packets[PACKET_qXfer_features]);
10800
10801 case TARGET_OBJECT_LIBRARIES:
10802 return remote_read_qxfer
10803 ("libraries", annex, readbuf, offset, len, xfered_len,
10804 &remote_protocol_packets[PACKET_qXfer_libraries]);
10805
10806 case TARGET_OBJECT_LIBRARIES_SVR4:
10807 return remote_read_qxfer
10808 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10809 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10810
10811 case TARGET_OBJECT_MEMORY_MAP:
10812 gdb_assert (annex == NULL);
10813 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10814 xfered_len,
10815 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10816
10817 case TARGET_OBJECT_OSDATA:
10818 /* Should only get here if we're connected. */
10819 gdb_assert (rs->remote_desc);
10820 return remote_read_qxfer
10821 ("osdata", annex, readbuf, offset, len, xfered_len,
10822 &remote_protocol_packets[PACKET_qXfer_osdata]);
10823
10824 case TARGET_OBJECT_THREADS:
10825 gdb_assert (annex == NULL);
10826 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10827 xfered_len,
10828 &remote_protocol_packets[PACKET_qXfer_threads]);
10829
10830 case TARGET_OBJECT_TRACEFRAME_INFO:
10831 gdb_assert (annex == NULL);
10832 return remote_read_qxfer
10833 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
10834 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10835
10836 case TARGET_OBJECT_FDPIC:
10837 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
10838 xfered_len,
10839 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10840
10841 case TARGET_OBJECT_OPENVMS_UIB:
10842 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
10843 xfered_len,
10844 &remote_protocol_packets[PACKET_qXfer_uib]);
10845
10846 case TARGET_OBJECT_BTRACE:
10847 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
10848 xfered_len,
10849 &remote_protocol_packets[PACKET_qXfer_btrace]);
10850
10851 case TARGET_OBJECT_BTRACE_CONF:
10852 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
10853 len, xfered_len,
10854 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10855
10856 case TARGET_OBJECT_EXEC_FILE:
10857 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
10858 len, xfered_len,
10859 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10860
10861 default:
10862 return TARGET_XFER_E_IO;
10863 }
10864
10865 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10866 large enough let the caller deal with it. */
10867 if (len < get_remote_packet_size ())
10868 return TARGET_XFER_E_IO;
10869 len = get_remote_packet_size ();
10870
10871 /* Except for querying the minimum buffer size, target must be open. */
10872 if (!rs->remote_desc)
10873 error (_("remote query is only available after target open"));
10874
10875 gdb_assert (annex != NULL);
10876 gdb_assert (readbuf != NULL);
10877
10878 p2 = rs->buf;
10879 *p2++ = 'q';
10880 *p2++ = query_type;
10881
10882 /* We used one buffer char for the remote protocol q command and
10883 another for the query type. As the remote protocol encapsulation
10884 uses 4 chars plus one extra in case we are debugging
10885 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10886 string. */
10887 i = 0;
10888 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10889 {
10890 /* Bad caller may have sent forbidden characters. */
10891 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10892 *p2++ = annex[i];
10893 i++;
10894 }
10895 *p2 = '\0';
10896 gdb_assert (annex[i] == '\0');
10897
10898 i = putpkt (rs->buf);
10899 if (i < 0)
10900 return TARGET_XFER_E_IO;
10901
10902 getpkt (&rs->buf, &rs->buf_size, 0);
10903 strcpy ((char *) readbuf, rs->buf);
10904
10905 *xfered_len = strlen ((char *) readbuf);
10906 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10907 }
10908
10909 /* Implementation of to_get_memory_xfer_limit. */
10910
10911 ULONGEST
10912 remote_target::get_memory_xfer_limit ()
10913 {
10914 return get_memory_write_packet_size ();
10915 }
10916
10917 int
10918 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
10919 const gdb_byte *pattern, ULONGEST pattern_len,
10920 CORE_ADDR *found_addrp)
10921 {
10922 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10923 struct remote_state *rs = get_remote_state ();
10924 int max_size = get_memory_write_packet_size ();
10925 struct packet_config *packet =
10926 &remote_protocol_packets[PACKET_qSearch_memory];
10927 /* Number of packet bytes used to encode the pattern;
10928 this could be more than PATTERN_LEN due to escape characters. */
10929 int escaped_pattern_len;
10930 /* Amount of pattern that was encodable in the packet. */
10931 int used_pattern_len;
10932 int i;
10933 int found;
10934 ULONGEST found_addr;
10935
10936 /* Don't go to the target if we don't have to. This is done before
10937 checking packet_config_support to avoid the possibility that a
10938 success for this edge case means the facility works in
10939 general. */
10940 if (pattern_len > search_space_len)
10941 return 0;
10942 if (pattern_len == 0)
10943 {
10944 *found_addrp = start_addr;
10945 return 1;
10946 }
10947
10948 /* If we already know the packet isn't supported, fall back to the simple
10949 way of searching memory. */
10950
10951 if (packet_config_support (packet) == PACKET_DISABLE)
10952 {
10953 /* Target doesn't provided special support, fall back and use the
10954 standard support (copy memory and do the search here). */
10955 return simple_search_memory (this, start_addr, search_space_len,
10956 pattern, pattern_len, found_addrp);
10957 }
10958
10959 /* Make sure the remote is pointing at the right process. */
10960 set_general_process ();
10961
10962 /* Insert header. */
10963 i = snprintf (rs->buf, max_size,
10964 "qSearch:memory:%s;%s;",
10965 phex_nz (start_addr, addr_size),
10966 phex_nz (search_space_len, sizeof (search_space_len)));
10967 max_size -= (i + 1);
10968
10969 /* Escape as much data as fits into rs->buf. */
10970 escaped_pattern_len =
10971 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10972 &used_pattern_len, max_size);
10973
10974 /* Bail if the pattern is too large. */
10975 if (used_pattern_len != pattern_len)
10976 error (_("Pattern is too large to transmit to remote target."));
10977
10978 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10979 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10980 || packet_ok (rs->buf, packet) != PACKET_OK)
10981 {
10982 /* The request may not have worked because the command is not
10983 supported. If so, fall back to the simple way. */
10984 if (packet_config_support (packet) == PACKET_DISABLE)
10985 {
10986 return simple_search_memory (this, start_addr, search_space_len,
10987 pattern, pattern_len, found_addrp);
10988 }
10989 return -1;
10990 }
10991
10992 if (rs->buf[0] == '0')
10993 found = 0;
10994 else if (rs->buf[0] == '1')
10995 {
10996 found = 1;
10997 if (rs->buf[1] != ',')
10998 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10999 unpack_varlen_hex (rs->buf + 2, &found_addr);
11000 *found_addrp = found_addr;
11001 }
11002 else
11003 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11004
11005 return found;
11006 }
11007
11008 void
11009 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11010 {
11011 struct remote_state *rs = get_remote_state ();
11012 char *p = rs->buf;
11013
11014 if (!rs->remote_desc)
11015 error (_("remote rcmd is only available after target open"));
11016
11017 /* Send a NULL command across as an empty command. */
11018 if (command == NULL)
11019 command = "";
11020
11021 /* The query prefix. */
11022 strcpy (rs->buf, "qRcmd,");
11023 p = strchr (rs->buf, '\0');
11024
11025 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11026 > get_remote_packet_size ())
11027 error (_("\"monitor\" command ``%s'' is too long."), command);
11028
11029 /* Encode the actual command. */
11030 bin2hex ((const gdb_byte *) command, p, strlen (command));
11031
11032 if (putpkt (rs->buf) < 0)
11033 error (_("Communication problem with target."));
11034
11035 /* get/display the response */
11036 while (1)
11037 {
11038 char *buf;
11039
11040 /* XXX - see also remote_get_noisy_reply(). */
11041 QUIT; /* Allow user to bail out with ^C. */
11042 rs->buf[0] = '\0';
11043 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11044 {
11045 /* Timeout. Continue to (try to) read responses.
11046 This is better than stopping with an error, assuming the stub
11047 is still executing the (long) monitor command.
11048 If needed, the user can interrupt gdb using C-c, obtaining
11049 an effect similar to stop on timeout. */
11050 continue;
11051 }
11052 buf = rs->buf;
11053 if (buf[0] == '\0')
11054 error (_("Target does not support this command."));
11055 if (buf[0] == 'O' && buf[1] != 'K')
11056 {
11057 remote_console_output (buf + 1); /* 'O' message from stub. */
11058 continue;
11059 }
11060 if (strcmp (buf, "OK") == 0)
11061 break;
11062 if (strlen (buf) == 3 && buf[0] == 'E'
11063 && isdigit (buf[1]) && isdigit (buf[2]))
11064 {
11065 error (_("Protocol error with Rcmd"));
11066 }
11067 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11068 {
11069 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11070
11071 fputc_unfiltered (c, outbuf);
11072 }
11073 break;
11074 }
11075 }
11076
11077 std::vector<mem_region>
11078 remote_target::memory_map ()
11079 {
11080 std::vector<mem_region> result;
11081 gdb::optional<gdb::char_vector> text
11082 = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
11083
11084 if (text)
11085 result = parse_memory_map (text->data ());
11086
11087 return result;
11088 }
11089
11090 static void
11091 packet_command (const char *args, int from_tty)
11092 {
11093 struct remote_state *rs = get_remote_state ();
11094
11095 if (!rs->remote_desc)
11096 error (_("command can only be used with remote target"));
11097
11098 if (!args)
11099 error (_("remote-packet command requires packet text as argument"));
11100
11101 puts_filtered ("sending: ");
11102 print_packet (args);
11103 puts_filtered ("\n");
11104 putpkt (args);
11105
11106 getpkt (&rs->buf, &rs->buf_size, 0);
11107 puts_filtered ("received: ");
11108 print_packet (rs->buf);
11109 puts_filtered ("\n");
11110 }
11111
11112 #if 0
11113 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11114
11115 static void display_thread_info (struct gdb_ext_thread_info *info);
11116
11117 static void threadset_test_cmd (char *cmd, int tty);
11118
11119 static void threadalive_test (char *cmd, int tty);
11120
11121 static void threadlist_test_cmd (char *cmd, int tty);
11122
11123 int get_and_display_threadinfo (threadref *ref);
11124
11125 static void threadinfo_test_cmd (char *cmd, int tty);
11126
11127 static int thread_display_step (threadref *ref, void *context);
11128
11129 static void threadlist_update_test_cmd (char *cmd, int tty);
11130
11131 static void init_remote_threadtests (void);
11132
11133 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11134
11135 static void
11136 threadset_test_cmd (const char *cmd, int tty)
11137 {
11138 int sample_thread = SAMPLE_THREAD;
11139
11140 printf_filtered (_("Remote threadset test\n"));
11141 set_general_thread (sample_thread);
11142 }
11143
11144
11145 static void
11146 threadalive_test (const char *cmd, int tty)
11147 {
11148 int sample_thread = SAMPLE_THREAD;
11149 int pid = ptid_get_pid (inferior_ptid);
11150 ptid_t ptid = ptid_build (pid, sample_thread, 0);
11151
11152 if (remote_thread_alive (ptid))
11153 printf_filtered ("PASS: Thread alive test\n");
11154 else
11155 printf_filtered ("FAIL: Thread alive test\n");
11156 }
11157
11158 void output_threadid (char *title, threadref *ref);
11159
11160 void
11161 output_threadid (char *title, threadref *ref)
11162 {
11163 char hexid[20];
11164
11165 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
11166 hexid[16] = 0;
11167 printf_filtered ("%s %s\n", title, (&hexid[0]));
11168 }
11169
11170 static void
11171 threadlist_test_cmd (const char *cmd, int tty)
11172 {
11173 int startflag = 1;
11174 threadref nextthread;
11175 int done, result_count;
11176 threadref threadlist[3];
11177
11178 printf_filtered ("Remote Threadlist test\n");
11179 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11180 &result_count, &threadlist[0]))
11181 printf_filtered ("FAIL: threadlist test\n");
11182 else
11183 {
11184 threadref *scan = threadlist;
11185 threadref *limit = scan + result_count;
11186
11187 while (scan < limit)
11188 output_threadid (" thread ", scan++);
11189 }
11190 }
11191
11192 void
11193 display_thread_info (struct gdb_ext_thread_info *info)
11194 {
11195 output_threadid ("Threadid: ", &info->threadid);
11196 printf_filtered ("Name: %s\n ", info->shortname);
11197 printf_filtered ("State: %s\n", info->display);
11198 printf_filtered ("other: %s\n\n", info->more_display);
11199 }
11200
11201 int
11202 get_and_display_threadinfo (threadref *ref)
11203 {
11204 int result;
11205 int set;
11206 struct gdb_ext_thread_info threadinfo;
11207
11208 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11209 | TAG_MOREDISPLAY | TAG_DISPLAY;
11210 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11211 display_thread_info (&threadinfo);
11212 return result;
11213 }
11214
11215 static void
11216 threadinfo_test_cmd (const char *cmd, int tty)
11217 {
11218 int athread = SAMPLE_THREAD;
11219 threadref thread;
11220 int set;
11221
11222 int_to_threadref (&thread, athread);
11223 printf_filtered ("Remote Threadinfo test\n");
11224 if (!get_and_display_threadinfo (&thread))
11225 printf_filtered ("FAIL cannot get thread info\n");
11226 }
11227
11228 static int
11229 thread_display_step (threadref *ref, void *context)
11230 {
11231 /* output_threadid(" threadstep ",ref); *//* simple test */
11232 return get_and_display_threadinfo (ref);
11233 }
11234
11235 static void
11236 threadlist_update_test_cmd (const char *cmd, int tty)
11237 {
11238 printf_filtered ("Remote Threadlist update test\n");
11239 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11240 }
11241
11242 static void
11243 init_remote_threadtests (void)
11244 {
11245 add_com ("tlist", class_obscure, threadlist_test_cmd,
11246 _("Fetch and print the remote list of "
11247 "thread identifiers, one pkt only"));
11248 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11249 _("Fetch and display info about one thread"));
11250 add_com ("tset", class_obscure, threadset_test_cmd,
11251 _("Test setting to a different thread"));
11252 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11253 _("Iterate through updating all remote thread info"));
11254 add_com ("talive", class_obscure, threadalive_test,
11255 _(" Remote thread alive test "));
11256 }
11257
11258 #endif /* 0 */
11259
11260 /* Convert a thread ID to a string. Returns the string in a static
11261 buffer. */
11262
11263 const char *
11264 remote_target::pid_to_str (ptid_t ptid)
11265 {
11266 static char buf[64];
11267 struct remote_state *rs = get_remote_state ();
11268
11269 if (ptid_equal (ptid, null_ptid))
11270 return normal_pid_to_str (ptid);
11271 else if (ptid_is_pid (ptid))
11272 {
11273 /* Printing an inferior target id. */
11274
11275 /* When multi-process extensions are off, there's no way in the
11276 remote protocol to know the remote process id, if there's any
11277 at all. There's one exception --- when we're connected with
11278 target extended-remote, and we manually attached to a process
11279 with "attach PID". We don't record anywhere a flag that
11280 allows us to distinguish that case from the case of
11281 connecting with extended-remote and the stub already being
11282 attached to a process, and reporting yes to qAttached, hence
11283 no smart special casing here. */
11284 if (!remote_multi_process_p (rs))
11285 {
11286 xsnprintf (buf, sizeof buf, "Remote target");
11287 return buf;
11288 }
11289
11290 return normal_pid_to_str (ptid);
11291 }
11292 else
11293 {
11294 if (ptid_equal (magic_null_ptid, ptid))
11295 xsnprintf (buf, sizeof buf, "Thread <main>");
11296 else if (remote_multi_process_p (rs))
11297 if (ptid_get_lwp (ptid) == 0)
11298 return normal_pid_to_str (ptid);
11299 else
11300 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11301 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11302 else
11303 xsnprintf (buf, sizeof buf, "Thread %ld",
11304 ptid_get_lwp (ptid));
11305 return buf;
11306 }
11307 }
11308
11309 /* Get the address of the thread local variable in OBJFILE which is
11310 stored at OFFSET within the thread local storage for thread PTID. */
11311
11312 CORE_ADDR
11313 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11314 CORE_ADDR offset)
11315 {
11316 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11317 {
11318 struct remote_state *rs = get_remote_state ();
11319 char *p = rs->buf;
11320 char *endp = rs->buf + get_remote_packet_size ();
11321 enum packet_result result;
11322
11323 strcpy (p, "qGetTLSAddr:");
11324 p += strlen (p);
11325 p = write_ptid (p, endp, ptid);
11326 *p++ = ',';
11327 p += hexnumstr (p, offset);
11328 *p++ = ',';
11329 p += hexnumstr (p, lm);
11330 *p++ = '\0';
11331
11332 putpkt (rs->buf);
11333 getpkt (&rs->buf, &rs->buf_size, 0);
11334 result = packet_ok (rs->buf,
11335 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11336 if (result == PACKET_OK)
11337 {
11338 ULONGEST result;
11339
11340 unpack_varlen_hex (rs->buf, &result);
11341 return result;
11342 }
11343 else if (result == PACKET_UNKNOWN)
11344 throw_error (TLS_GENERIC_ERROR,
11345 _("Remote target doesn't support qGetTLSAddr packet"));
11346 else
11347 throw_error (TLS_GENERIC_ERROR,
11348 _("Remote target failed to process qGetTLSAddr request"));
11349 }
11350 else
11351 throw_error (TLS_GENERIC_ERROR,
11352 _("TLS not supported or disabled on this target"));
11353 /* Not reached. */
11354 return 0;
11355 }
11356
11357 /* Provide thread local base, i.e. Thread Information Block address.
11358 Returns 1 if ptid is found and thread_local_base is non zero. */
11359
11360 bool
11361 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11362 {
11363 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11364 {
11365 struct remote_state *rs = get_remote_state ();
11366 char *p = rs->buf;
11367 char *endp = rs->buf + get_remote_packet_size ();
11368 enum packet_result result;
11369
11370 strcpy (p, "qGetTIBAddr:");
11371 p += strlen (p);
11372 p = write_ptid (p, endp, ptid);
11373 *p++ = '\0';
11374
11375 putpkt (rs->buf);
11376 getpkt (&rs->buf, &rs->buf_size, 0);
11377 result = packet_ok (rs->buf,
11378 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11379 if (result == PACKET_OK)
11380 {
11381 ULONGEST result;
11382
11383 unpack_varlen_hex (rs->buf, &result);
11384 if (addr)
11385 *addr = (CORE_ADDR) result;
11386 return true;
11387 }
11388 else if (result == PACKET_UNKNOWN)
11389 error (_("Remote target doesn't support qGetTIBAddr packet"));
11390 else
11391 error (_("Remote target failed to process qGetTIBAddr request"));
11392 }
11393 else
11394 error (_("qGetTIBAddr not supported or disabled on this target"));
11395 /* Not reached. */
11396 return false;
11397 }
11398
11399 /* Support for inferring a target description based on the current
11400 architecture and the size of a 'g' packet. While the 'g' packet
11401 can have any size (since optional registers can be left off the
11402 end), some sizes are easily recognizable given knowledge of the
11403 approximate architecture. */
11404
11405 struct remote_g_packet_guess
11406 {
11407 int bytes;
11408 const struct target_desc *tdesc;
11409 };
11410 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11411 DEF_VEC_O(remote_g_packet_guess_s);
11412
11413 struct remote_g_packet_data
11414 {
11415 VEC(remote_g_packet_guess_s) *guesses;
11416 };
11417
11418 static struct gdbarch_data *remote_g_packet_data_handle;
11419
11420 static void *
11421 remote_g_packet_data_init (struct obstack *obstack)
11422 {
11423 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11424 }
11425
11426 void
11427 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11428 const struct target_desc *tdesc)
11429 {
11430 struct remote_g_packet_data *data
11431 = ((struct remote_g_packet_data *)
11432 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11433 struct remote_g_packet_guess new_guess, *guess;
11434 int ix;
11435
11436 gdb_assert (tdesc != NULL);
11437
11438 for (ix = 0;
11439 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11440 ix++)
11441 if (guess->bytes == bytes)
11442 internal_error (__FILE__, __LINE__,
11443 _("Duplicate g packet description added for size %d"),
11444 bytes);
11445
11446 new_guess.bytes = bytes;
11447 new_guess.tdesc = tdesc;
11448 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11449 }
11450
11451 /* Return 1 if remote_read_description would do anything on this target
11452 and architecture, 0 otherwise. */
11453
11454 static int
11455 remote_read_description_p (struct target_ops *target)
11456 {
11457 struct remote_g_packet_data *data
11458 = ((struct remote_g_packet_data *)
11459 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11460
11461 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11462 return 1;
11463
11464 return 0;
11465 }
11466
11467 const struct target_desc *
11468 remote_target::read_description ()
11469 {
11470 struct remote_g_packet_data *data
11471 = ((struct remote_g_packet_data *)
11472 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11473
11474 /* Do not try this during initial connection, when we do not know
11475 whether there is a running but stopped thread. */
11476 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11477 return beneath->read_description ();
11478
11479 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11480 {
11481 struct remote_g_packet_guess *guess;
11482 int ix;
11483 int bytes = send_g_packet ();
11484
11485 for (ix = 0;
11486 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11487 ix++)
11488 if (guess->bytes == bytes)
11489 return guess->tdesc;
11490
11491 /* We discard the g packet. A minor optimization would be to
11492 hold on to it, and fill the register cache once we have selected
11493 an architecture, but it's too tricky to do safely. */
11494 }
11495
11496 return beneath->read_description ();
11497 }
11498
11499 /* Remote file transfer support. This is host-initiated I/O, not
11500 target-initiated; for target-initiated, see remote-fileio.c. */
11501
11502 /* If *LEFT is at least the length of STRING, copy STRING to
11503 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11504 decrease *LEFT. Otherwise raise an error. */
11505
11506 static void
11507 remote_buffer_add_string (char **buffer, int *left, const char *string)
11508 {
11509 int len = strlen (string);
11510
11511 if (len > *left)
11512 error (_("Packet too long for target."));
11513
11514 memcpy (*buffer, string, len);
11515 *buffer += len;
11516 *left -= len;
11517
11518 /* NUL-terminate the buffer as a convenience, if there is
11519 room. */
11520 if (*left)
11521 **buffer = '\0';
11522 }
11523
11524 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11525 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11526 decrease *LEFT. Otherwise raise an error. */
11527
11528 static void
11529 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11530 int len)
11531 {
11532 if (2 * len > *left)
11533 error (_("Packet too long for target."));
11534
11535 bin2hex (bytes, *buffer, len);
11536 *buffer += 2 * len;
11537 *left -= 2 * len;
11538
11539 /* NUL-terminate the buffer as a convenience, if there is
11540 room. */
11541 if (*left)
11542 **buffer = '\0';
11543 }
11544
11545 /* If *LEFT is large enough, convert VALUE to hex and add it to
11546 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11547 decrease *LEFT. Otherwise raise an error. */
11548
11549 static void
11550 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11551 {
11552 int len = hexnumlen (value);
11553
11554 if (len > *left)
11555 error (_("Packet too long for target."));
11556
11557 hexnumstr (*buffer, value);
11558 *buffer += len;
11559 *left -= len;
11560
11561 /* NUL-terminate the buffer as a convenience, if there is
11562 room. */
11563 if (*left)
11564 **buffer = '\0';
11565 }
11566
11567 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11568 value, *REMOTE_ERRNO to the remote error number or zero if none
11569 was included, and *ATTACHMENT to point to the start of the annex
11570 if any. The length of the packet isn't needed here; there may
11571 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11572
11573 Return 0 if the packet could be parsed, -1 if it could not. If
11574 -1 is returned, the other variables may not be initialized. */
11575
11576 static int
11577 remote_hostio_parse_result (char *buffer, int *retcode,
11578 int *remote_errno, char **attachment)
11579 {
11580 char *p, *p2;
11581
11582 *remote_errno = 0;
11583 *attachment = NULL;
11584
11585 if (buffer[0] != 'F')
11586 return -1;
11587
11588 errno = 0;
11589 *retcode = strtol (&buffer[1], &p, 16);
11590 if (errno != 0 || p == &buffer[1])
11591 return -1;
11592
11593 /* Check for ",errno". */
11594 if (*p == ',')
11595 {
11596 errno = 0;
11597 *remote_errno = strtol (p + 1, &p2, 16);
11598 if (errno != 0 || p + 1 == p2)
11599 return -1;
11600 p = p2;
11601 }
11602
11603 /* Check for ";attachment". If there is no attachment, the
11604 packet should end here. */
11605 if (*p == ';')
11606 {
11607 *attachment = p + 1;
11608 return 0;
11609 }
11610 else if (*p == '\0')
11611 return 0;
11612 else
11613 return -1;
11614 }
11615
11616 /* Send a prepared I/O packet to the target and read its response.
11617 The prepared packet is in the global RS->BUF before this function
11618 is called, and the answer is there when we return.
11619
11620 COMMAND_BYTES is the length of the request to send, which may include
11621 binary data. WHICH_PACKET is the packet configuration to check
11622 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11623 is set to the error number and -1 is returned. Otherwise the value
11624 returned by the function is returned.
11625
11626 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11627 attachment is expected; an error will be reported if there's a
11628 mismatch. If one is found, *ATTACHMENT will be set to point into
11629 the packet buffer and *ATTACHMENT_LEN will be set to the
11630 attachment's length. */
11631
11632 static int
11633 remote_hostio_send_command (int command_bytes, int which_packet,
11634 int *remote_errno, char **attachment,
11635 int *attachment_len)
11636 {
11637 struct remote_state *rs = get_remote_state ();
11638 int ret, bytes_read;
11639 char *attachment_tmp;
11640
11641 if (packet_support (which_packet) == PACKET_DISABLE)
11642 {
11643 *remote_errno = FILEIO_ENOSYS;
11644 return -1;
11645 }
11646
11647 putpkt_binary (rs->buf, command_bytes);
11648 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11649
11650 /* If it timed out, something is wrong. Don't try to parse the
11651 buffer. */
11652 if (bytes_read < 0)
11653 {
11654 *remote_errno = FILEIO_EINVAL;
11655 return -1;
11656 }
11657
11658 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11659 {
11660 case PACKET_ERROR:
11661 *remote_errno = FILEIO_EINVAL;
11662 return -1;
11663 case PACKET_UNKNOWN:
11664 *remote_errno = FILEIO_ENOSYS;
11665 return -1;
11666 case PACKET_OK:
11667 break;
11668 }
11669
11670 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11671 &attachment_tmp))
11672 {
11673 *remote_errno = FILEIO_EINVAL;
11674 return -1;
11675 }
11676
11677 /* Make sure we saw an attachment if and only if we expected one. */
11678 if ((attachment_tmp == NULL && attachment != NULL)
11679 || (attachment_tmp != NULL && attachment == NULL))
11680 {
11681 *remote_errno = FILEIO_EINVAL;
11682 return -1;
11683 }
11684
11685 /* If an attachment was found, it must point into the packet buffer;
11686 work out how many bytes there were. */
11687 if (attachment_tmp != NULL)
11688 {
11689 *attachment = attachment_tmp;
11690 *attachment_len = bytes_read - (*attachment - rs->buf);
11691 }
11692
11693 return ret;
11694 }
11695
11696 /* See declaration.h. */
11697
11698 void
11699 readahead_cache::invalidate ()
11700 {
11701 this->fd = -1;
11702 }
11703
11704 /* See declaration.h. */
11705
11706 void
11707 readahead_cache::invalidate_fd (int fd)
11708 {
11709 if (this->fd == fd)
11710 this->fd = -1;
11711 }
11712
11713 /* Set the filesystem remote_hostio functions that take FILENAME
11714 arguments will use. Return 0 on success, or -1 if an error
11715 occurs (and set *REMOTE_ERRNO). */
11716
11717 static int
11718 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11719 {
11720 struct remote_state *rs = get_remote_state ();
11721 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11722 char *p = rs->buf;
11723 int left = get_remote_packet_size () - 1;
11724 char arg[9];
11725 int ret;
11726
11727 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11728 return 0;
11729
11730 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11731 return 0;
11732
11733 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11734
11735 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11736 remote_buffer_add_string (&p, &left, arg);
11737
11738 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11739 remote_errno, NULL, NULL);
11740
11741 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11742 return 0;
11743
11744 if (ret == 0)
11745 rs->fs_pid = required_pid;
11746
11747 return ret;
11748 }
11749
11750 /* Implementation of to_fileio_open. */
11751
11752 static int
11753 remote_hostio_open (struct target_ops *self,
11754 struct inferior *inf, const char *filename,
11755 int flags, int mode, int warn_if_slow,
11756 int *remote_errno)
11757 {
11758 struct remote_state *rs = get_remote_state ();
11759 char *p = rs->buf;
11760 int left = get_remote_packet_size () - 1;
11761
11762 if (warn_if_slow)
11763 {
11764 static int warning_issued = 0;
11765
11766 printf_unfiltered (_("Reading %s from remote target...\n"),
11767 filename);
11768
11769 if (!warning_issued)
11770 {
11771 warning (_("File transfers from remote targets can be slow."
11772 " Use \"set sysroot\" to access files locally"
11773 " instead."));
11774 warning_issued = 1;
11775 }
11776 }
11777
11778 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11779 return -1;
11780
11781 remote_buffer_add_string (&p, &left, "vFile:open:");
11782
11783 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11784 strlen (filename));
11785 remote_buffer_add_string (&p, &left, ",");
11786
11787 remote_buffer_add_int (&p, &left, flags);
11788 remote_buffer_add_string (&p, &left, ",");
11789
11790 remote_buffer_add_int (&p, &left, mode);
11791
11792 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11793 remote_errno, NULL, NULL);
11794 }
11795
11796 int
11797 remote_target::fileio_open (struct inferior *inf, const char *filename,
11798 int flags, int mode, int warn_if_slow,
11799 int *remote_errno)
11800 {
11801 return remote_hostio_open (this, inf, filename, flags, mode, warn_if_slow,
11802 remote_errno);
11803 }
11804
11805 /* Implementation of to_fileio_pwrite. */
11806
11807 static int
11808 remote_hostio_pwrite (struct target_ops *self,
11809 int fd, const gdb_byte *write_buf, int len,
11810 ULONGEST offset, int *remote_errno)
11811 {
11812 struct remote_state *rs = get_remote_state ();
11813 char *p = rs->buf;
11814 int left = get_remote_packet_size ();
11815 int out_len;
11816
11817 rs->readahead_cache.invalidate_fd (fd);
11818
11819 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11820
11821 remote_buffer_add_int (&p, &left, fd);
11822 remote_buffer_add_string (&p, &left, ",");
11823
11824 remote_buffer_add_int (&p, &left, offset);
11825 remote_buffer_add_string (&p, &left, ",");
11826
11827 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11828 get_remote_packet_size () - (p - rs->buf));
11829
11830 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11831 remote_errno, NULL, NULL);
11832 }
11833
11834 int
11835 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
11836 ULONGEST offset, int *remote_errno)
11837 {
11838 return remote_hostio_pwrite (this, fd, write_buf, len, offset, remote_errno);
11839 }
11840
11841 /* Helper for the implementation of to_fileio_pread. Read the file
11842 from the remote side with vFile:pread. */
11843
11844 static int
11845 remote_hostio_pread_vFile (struct target_ops *self,
11846 int fd, gdb_byte *read_buf, int len,
11847 ULONGEST offset, int *remote_errno)
11848 {
11849 struct remote_state *rs = get_remote_state ();
11850 char *p = rs->buf;
11851 char *attachment;
11852 int left = get_remote_packet_size ();
11853 int ret, attachment_len;
11854 int read_len;
11855
11856 remote_buffer_add_string (&p, &left, "vFile:pread:");
11857
11858 remote_buffer_add_int (&p, &left, fd);
11859 remote_buffer_add_string (&p, &left, ",");
11860
11861 remote_buffer_add_int (&p, &left, len);
11862 remote_buffer_add_string (&p, &left, ",");
11863
11864 remote_buffer_add_int (&p, &left, offset);
11865
11866 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11867 remote_errno, &attachment,
11868 &attachment_len);
11869
11870 if (ret < 0)
11871 return ret;
11872
11873 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11874 read_buf, len);
11875 if (read_len != ret)
11876 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11877
11878 return ret;
11879 }
11880
11881 /* See declaration.h. */
11882
11883 int
11884 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
11885 ULONGEST offset)
11886 {
11887 if (this->fd == fd
11888 && this->offset <= offset
11889 && offset < this->offset + this->bufsize)
11890 {
11891 ULONGEST max = this->offset + this->bufsize;
11892
11893 if (offset + len > max)
11894 len = max - offset;
11895
11896 memcpy (read_buf, this->buf + offset - this->offset, len);
11897 return len;
11898 }
11899
11900 return 0;
11901 }
11902
11903 /* Implementation of to_fileio_pread. */
11904
11905 static int
11906 remote_hostio_pread (struct target_ops *self,
11907 int fd, gdb_byte *read_buf, int len,
11908 ULONGEST offset, int *remote_errno)
11909 {
11910 int ret;
11911 struct remote_state *rs = get_remote_state ();
11912 readahead_cache *cache = &rs->readahead_cache;
11913
11914 ret = cache->pread (fd, read_buf, len, offset);
11915 if (ret > 0)
11916 {
11917 cache->hit_count++;
11918
11919 if (remote_debug)
11920 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11921 pulongest (cache->hit_count));
11922 return ret;
11923 }
11924
11925 cache->miss_count++;
11926 if (remote_debug)
11927 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11928 pulongest (cache->miss_count));
11929
11930 cache->fd = fd;
11931 cache->offset = offset;
11932 cache->bufsize = get_remote_packet_size ();
11933 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11934
11935 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11936 cache->offset, remote_errno);
11937 if (ret <= 0)
11938 {
11939 cache->invalidate_fd (fd);
11940 return ret;
11941 }
11942
11943 cache->bufsize = ret;
11944 return cache->pread (fd, read_buf, len, offset);
11945 }
11946
11947 int
11948 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
11949 ULONGEST offset, int *remote_errno)
11950 {
11951 return remote_hostio_pread (this, fd, read_buf, len, offset, remote_errno);
11952 }
11953
11954 /* Implementation of to_fileio_close. */
11955
11956 static int
11957 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11958 {
11959 struct remote_state *rs = get_remote_state ();
11960 char *p = rs->buf;
11961 int left = get_remote_packet_size () - 1;
11962
11963 rs->readahead_cache.invalidate_fd (fd);
11964
11965 remote_buffer_add_string (&p, &left, "vFile:close:");
11966
11967 remote_buffer_add_int (&p, &left, fd);
11968
11969 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11970 remote_errno, NULL, NULL);
11971 }
11972
11973 int
11974 remote_target::fileio_close (int fd, int *remote_errno)
11975 {
11976 return remote_hostio_close (this, fd, remote_errno);
11977 }
11978
11979 /* Implementation of to_fileio_unlink. */
11980
11981 static int
11982 remote_hostio_unlink (struct target_ops *self,
11983 struct inferior *inf, const char *filename,
11984 int *remote_errno)
11985 {
11986 struct remote_state *rs = get_remote_state ();
11987 char *p = rs->buf;
11988 int left = get_remote_packet_size () - 1;
11989
11990 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11991 return -1;
11992
11993 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11994
11995 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11996 strlen (filename));
11997
11998 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11999 remote_errno, NULL, NULL);
12000 }
12001
12002 int
12003 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12004 int *remote_errno)
12005 {
12006 return remote_hostio_unlink (this, inf, filename, remote_errno);
12007 }
12008
12009 /* Implementation of to_fileio_readlink. */
12010
12011 gdb::optional<std::string>
12012 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12013 int *remote_errno)
12014 {
12015 struct remote_state *rs = get_remote_state ();
12016 char *p = rs->buf;
12017 char *attachment;
12018 int left = get_remote_packet_size ();
12019 int len, attachment_len;
12020 int read_len;
12021
12022 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12023 return {};
12024
12025 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12026
12027 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12028 strlen (filename));
12029
12030 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12031 remote_errno, &attachment,
12032 &attachment_len);
12033
12034 if (len < 0)
12035 return {};
12036
12037 std::string ret (len, '\0');
12038
12039 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12040 (gdb_byte *) &ret[0], len);
12041 if (read_len != len)
12042 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12043
12044 return ret;
12045 }
12046
12047 /* Implementation of to_fileio_fstat. */
12048
12049 int
12050 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12051 {
12052 struct remote_state *rs = get_remote_state ();
12053 char *p = rs->buf;
12054 int left = get_remote_packet_size ();
12055 int attachment_len, ret;
12056 char *attachment;
12057 struct fio_stat fst;
12058 int read_len;
12059
12060 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12061
12062 remote_buffer_add_int (&p, &left, fd);
12063
12064 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12065 remote_errno, &attachment,
12066 &attachment_len);
12067 if (ret < 0)
12068 {
12069 if (*remote_errno != FILEIO_ENOSYS)
12070 return ret;
12071
12072 /* Strictly we should return -1, ENOSYS here, but when
12073 "set sysroot remote:" was implemented in August 2008
12074 BFD's need for a stat function was sidestepped with
12075 this hack. This was not remedied until March 2015
12076 so we retain the previous behavior to avoid breaking
12077 compatibility.
12078
12079 Note that the memset is a March 2015 addition; older
12080 GDBs set st_size *and nothing else* so the structure
12081 would have garbage in all other fields. This might
12082 break something but retaining the previous behavior
12083 here would be just too wrong. */
12084
12085 memset (st, 0, sizeof (struct stat));
12086 st->st_size = INT_MAX;
12087 return 0;
12088 }
12089
12090 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12091 (gdb_byte *) &fst, sizeof (fst));
12092
12093 if (read_len != ret)
12094 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12095
12096 if (read_len != sizeof (fst))
12097 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12098 read_len, (int) sizeof (fst));
12099
12100 remote_fileio_to_host_stat (&fst, st);
12101
12102 return 0;
12103 }
12104
12105 /* Implementation of to_filesystem_is_local. */
12106
12107 bool
12108 remote_target::filesystem_is_local ()
12109 {
12110 /* Valgrind GDB presents itself as a remote target but works
12111 on the local filesystem: it does not implement remote get
12112 and users are not expected to set a sysroot. To handle
12113 this case we treat the remote filesystem as local if the
12114 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12115 does not support vFile:open. */
12116 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12117 {
12118 enum packet_support ps = packet_support (PACKET_vFile_open);
12119
12120 if (ps == PACKET_SUPPORT_UNKNOWN)
12121 {
12122 int fd, remote_errno;
12123
12124 /* Try opening a file to probe support. The supplied
12125 filename is irrelevant, we only care about whether
12126 the stub recognizes the packet or not. */
12127 fd = remote_hostio_open (this, NULL, "just probing",
12128 FILEIO_O_RDONLY, 0700, 0,
12129 &remote_errno);
12130
12131 if (fd >= 0)
12132 remote_hostio_close (this, fd, &remote_errno);
12133
12134 ps = packet_support (PACKET_vFile_open);
12135 }
12136
12137 if (ps == PACKET_DISABLE)
12138 {
12139 static int warning_issued = 0;
12140
12141 if (!warning_issued)
12142 {
12143 warning (_("remote target does not support file"
12144 " transfer, attempting to access files"
12145 " from local filesystem."));
12146 warning_issued = 1;
12147 }
12148
12149 return true;
12150 }
12151 }
12152
12153 return false;
12154 }
12155
12156 static int
12157 remote_fileio_errno_to_host (int errnum)
12158 {
12159 switch (errnum)
12160 {
12161 case FILEIO_EPERM:
12162 return EPERM;
12163 case FILEIO_ENOENT:
12164 return ENOENT;
12165 case FILEIO_EINTR:
12166 return EINTR;
12167 case FILEIO_EIO:
12168 return EIO;
12169 case FILEIO_EBADF:
12170 return EBADF;
12171 case FILEIO_EACCES:
12172 return EACCES;
12173 case FILEIO_EFAULT:
12174 return EFAULT;
12175 case FILEIO_EBUSY:
12176 return EBUSY;
12177 case FILEIO_EEXIST:
12178 return EEXIST;
12179 case FILEIO_ENODEV:
12180 return ENODEV;
12181 case FILEIO_ENOTDIR:
12182 return ENOTDIR;
12183 case FILEIO_EISDIR:
12184 return EISDIR;
12185 case FILEIO_EINVAL:
12186 return EINVAL;
12187 case FILEIO_ENFILE:
12188 return ENFILE;
12189 case FILEIO_EMFILE:
12190 return EMFILE;
12191 case FILEIO_EFBIG:
12192 return EFBIG;
12193 case FILEIO_ENOSPC:
12194 return ENOSPC;
12195 case FILEIO_ESPIPE:
12196 return ESPIPE;
12197 case FILEIO_EROFS:
12198 return EROFS;
12199 case FILEIO_ENOSYS:
12200 return ENOSYS;
12201 case FILEIO_ENAMETOOLONG:
12202 return ENAMETOOLONG;
12203 }
12204 return -1;
12205 }
12206
12207 static char *
12208 remote_hostio_error (int errnum)
12209 {
12210 int host_error = remote_fileio_errno_to_host (errnum);
12211
12212 if (host_error == -1)
12213 error (_("Unknown remote I/O error %d"), errnum);
12214 else
12215 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12216 }
12217
12218 /* A RAII wrapper around a remote file descriptor. */
12219
12220 class scoped_remote_fd
12221 {
12222 public:
12223 explicit scoped_remote_fd (int fd)
12224 : m_fd (fd)
12225 {
12226 }
12227
12228 ~scoped_remote_fd ()
12229 {
12230 if (m_fd != -1)
12231 {
12232 try
12233 {
12234 int remote_errno;
12235 remote_hostio_close (find_target_at (process_stratum),
12236 m_fd, &remote_errno);
12237 }
12238 catch (...)
12239 {
12240 /* Swallow exception before it escapes the dtor. If
12241 something goes wrong, likely the connection is gone,
12242 and there's nothing else that can be done. */
12243 }
12244 }
12245 }
12246
12247 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12248
12249 /* Release ownership of the file descriptor, and return it. */
12250 int release () noexcept
12251 {
12252 int fd = m_fd;
12253 m_fd = -1;
12254 return fd;
12255 }
12256
12257 /* Return the owned file descriptor. */
12258 int get () const noexcept
12259 {
12260 return m_fd;
12261 }
12262
12263 private:
12264 /* The owned remote I/O file descriptor. */
12265 int m_fd;
12266 };
12267
12268 void
12269 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12270 {
12271 struct cleanup *back_to;
12272 int retcode, remote_errno, bytes, io_size;
12273 gdb_byte *buffer;
12274 int bytes_in_buffer;
12275 int saw_eof;
12276 ULONGEST offset;
12277 struct remote_state *rs = get_remote_state ();
12278
12279 if (!rs->remote_desc)
12280 error (_("command can only be used with remote target"));
12281
12282 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12283 if (file == NULL)
12284 perror_with_name (local_file);
12285
12286 scoped_remote_fd fd
12287 (remote_hostio_open (find_target_at (process_stratum), NULL,
12288 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12289 | FILEIO_O_TRUNC),
12290 0700, 0, &remote_errno));
12291 if (fd.get () == -1)
12292 remote_hostio_error (remote_errno);
12293
12294 /* Send up to this many bytes at once. They won't all fit in the
12295 remote packet limit, so we'll transfer slightly fewer. */
12296 io_size = get_remote_packet_size ();
12297 buffer = (gdb_byte *) xmalloc (io_size);
12298 back_to = make_cleanup (xfree, buffer);
12299
12300 bytes_in_buffer = 0;
12301 saw_eof = 0;
12302 offset = 0;
12303 while (bytes_in_buffer || !saw_eof)
12304 {
12305 if (!saw_eof)
12306 {
12307 bytes = fread (buffer + bytes_in_buffer, 1,
12308 io_size - bytes_in_buffer,
12309 file.get ());
12310 if (bytes == 0)
12311 {
12312 if (ferror (file.get ()))
12313 error (_("Error reading %s."), local_file);
12314 else
12315 {
12316 /* EOF. Unless there is something still in the
12317 buffer from the last iteration, we are done. */
12318 saw_eof = 1;
12319 if (bytes_in_buffer == 0)
12320 break;
12321 }
12322 }
12323 }
12324 else
12325 bytes = 0;
12326
12327 bytes += bytes_in_buffer;
12328 bytes_in_buffer = 0;
12329
12330 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12331 fd.get (), buffer, bytes,
12332 offset, &remote_errno);
12333
12334 if (retcode < 0)
12335 remote_hostio_error (remote_errno);
12336 else if (retcode == 0)
12337 error (_("Remote write of %d bytes returned 0!"), bytes);
12338 else if (retcode < bytes)
12339 {
12340 /* Short write. Save the rest of the read data for the next
12341 write. */
12342 bytes_in_buffer = bytes - retcode;
12343 memmove (buffer, buffer + retcode, bytes_in_buffer);
12344 }
12345
12346 offset += retcode;
12347 }
12348
12349 if (remote_hostio_close (find_target_at (process_stratum),
12350 fd.release (), &remote_errno))
12351 remote_hostio_error (remote_errno);
12352
12353 if (from_tty)
12354 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12355 do_cleanups (back_to);
12356 }
12357
12358 void
12359 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12360 {
12361 struct cleanup *back_to;
12362 int remote_errno, bytes, io_size;
12363 gdb_byte *buffer;
12364 ULONGEST offset;
12365 struct remote_state *rs = get_remote_state ();
12366
12367 if (!rs->remote_desc)
12368 error (_("command can only be used with remote target"));
12369
12370 scoped_remote_fd fd
12371 (remote_hostio_open (find_target_at (process_stratum), NULL,
12372 remote_file, FILEIO_O_RDONLY, 0, 0,
12373 &remote_errno));
12374 if (fd.get () == -1)
12375 remote_hostio_error (remote_errno);
12376
12377 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12378 if (file == NULL)
12379 perror_with_name (local_file);
12380
12381 /* Send up to this many bytes at once. They won't all fit in the
12382 remote packet limit, so we'll transfer slightly fewer. */
12383 io_size = get_remote_packet_size ();
12384 buffer = (gdb_byte *) xmalloc (io_size);
12385 back_to = make_cleanup (xfree, buffer);
12386
12387 offset = 0;
12388 while (1)
12389 {
12390 bytes = remote_hostio_pread (find_target_at (process_stratum),
12391 fd.get (), buffer, io_size, offset,
12392 &remote_errno);
12393 if (bytes == 0)
12394 /* Success, but no bytes, means end-of-file. */
12395 break;
12396 if (bytes == -1)
12397 remote_hostio_error (remote_errno);
12398
12399 offset += bytes;
12400
12401 bytes = fwrite (buffer, 1, bytes, file.get ());
12402 if (bytes == 0)
12403 perror_with_name (local_file);
12404 }
12405
12406 if (remote_hostio_close (find_target_at (process_stratum),
12407 fd.release (), &remote_errno))
12408 remote_hostio_error (remote_errno);
12409
12410 if (from_tty)
12411 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12412 do_cleanups (back_to);
12413 }
12414
12415 void
12416 remote_file_delete (const char *remote_file, int from_tty)
12417 {
12418 int retcode, remote_errno;
12419 struct remote_state *rs = get_remote_state ();
12420
12421 if (!rs->remote_desc)
12422 error (_("command can only be used with remote target"));
12423
12424 retcode = remote_hostio_unlink (find_target_at (process_stratum),
12425 NULL, remote_file, &remote_errno);
12426 if (retcode == -1)
12427 remote_hostio_error (remote_errno);
12428
12429 if (from_tty)
12430 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12431 }
12432
12433 static void
12434 remote_put_command (const char *args, int from_tty)
12435 {
12436 if (args == NULL)
12437 error_no_arg (_("file to put"));
12438
12439 gdb_argv argv (args);
12440 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12441 error (_("Invalid parameters to remote put"));
12442
12443 remote_file_put (argv[0], argv[1], from_tty);
12444 }
12445
12446 static void
12447 remote_get_command (const char *args, int from_tty)
12448 {
12449 if (args == NULL)
12450 error_no_arg (_("file to get"));
12451
12452 gdb_argv argv (args);
12453 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12454 error (_("Invalid parameters to remote get"));
12455
12456 remote_file_get (argv[0], argv[1], from_tty);
12457 }
12458
12459 static void
12460 remote_delete_command (const char *args, int from_tty)
12461 {
12462 if (args == NULL)
12463 error_no_arg (_("file to delete"));
12464
12465 gdb_argv argv (args);
12466 if (argv[0] == NULL || argv[1] != NULL)
12467 error (_("Invalid parameters to remote delete"));
12468
12469 remote_file_delete (argv[0], from_tty);
12470 }
12471
12472 static void
12473 remote_command (const char *args, int from_tty)
12474 {
12475 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12476 }
12477
12478 bool
12479 remote_target::can_execute_reverse ()
12480 {
12481 if (packet_support (PACKET_bs) == PACKET_ENABLE
12482 || packet_support (PACKET_bc) == PACKET_ENABLE)
12483 return true;
12484 else
12485 return false;
12486 }
12487
12488 bool
12489 remote_target::supports_non_stop ()
12490 {
12491 return true;
12492 }
12493
12494 bool
12495 remote_target::supports_disable_randomization ()
12496 {
12497 /* Only supported in extended mode. */
12498 return false;
12499 }
12500
12501 bool
12502 remote_target::supports_multi_process ()
12503 {
12504 struct remote_state *rs = get_remote_state ();
12505
12506 return remote_multi_process_p (rs);
12507 }
12508
12509 static int
12510 remote_supports_cond_tracepoints ()
12511 {
12512 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12513 }
12514
12515 bool
12516 remote_target::supports_evaluation_of_breakpoint_conditions ()
12517 {
12518 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12519 }
12520
12521 static int
12522 remote_supports_fast_tracepoints ()
12523 {
12524 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12525 }
12526
12527 static int
12528 remote_supports_static_tracepoints ()
12529 {
12530 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12531 }
12532
12533 static int
12534 remote_supports_install_in_trace ()
12535 {
12536 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12537 }
12538
12539 bool
12540 remote_target::supports_enable_disable_tracepoint ()
12541 {
12542 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12543 == PACKET_ENABLE);
12544 }
12545
12546 bool
12547 remote_target::supports_string_tracing ()
12548 {
12549 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12550 }
12551
12552 bool
12553 remote_target::can_run_breakpoint_commands ()
12554 {
12555 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12556 }
12557
12558 void
12559 remote_target::trace_init ()
12560 {
12561 struct remote_state *rs = get_remote_state ();
12562
12563 putpkt ("QTinit");
12564 remote_get_noisy_reply ();
12565 if (strcmp (rs->buf, "OK") != 0)
12566 error (_("Target does not support this command."));
12567 }
12568
12569 /* Recursive routine to walk through command list including loops, and
12570 download packets for each command. */
12571
12572 static void
12573 remote_download_command_source (int num, ULONGEST addr,
12574 struct command_line *cmds)
12575 {
12576 struct remote_state *rs = get_remote_state ();
12577 struct command_line *cmd;
12578
12579 for (cmd = cmds; cmd; cmd = cmd->next)
12580 {
12581 QUIT; /* Allow user to bail out with ^C. */
12582 strcpy (rs->buf, "QTDPsrc:");
12583 encode_source_string (num, addr, "cmd", cmd->line,
12584 rs->buf + strlen (rs->buf),
12585 rs->buf_size - strlen (rs->buf));
12586 putpkt (rs->buf);
12587 remote_get_noisy_reply ();
12588 if (strcmp (rs->buf, "OK"))
12589 warning (_("Target does not support source download."));
12590
12591 if (cmd->control_type == while_control
12592 || cmd->control_type == while_stepping_control)
12593 {
12594 remote_download_command_source (num, addr, cmd->body_list_0.get ());
12595
12596 QUIT; /* Allow user to bail out with ^C. */
12597 strcpy (rs->buf, "QTDPsrc:");
12598 encode_source_string (num, addr, "cmd", "end",
12599 rs->buf + strlen (rs->buf),
12600 rs->buf_size - strlen (rs->buf));
12601 putpkt (rs->buf);
12602 remote_get_noisy_reply ();
12603 if (strcmp (rs->buf, "OK"))
12604 warning (_("Target does not support source download."));
12605 }
12606 }
12607 }
12608
12609 void
12610 remote_target::download_tracepoint (struct bp_location *loc)
12611 {
12612 #define BUF_SIZE 2048
12613
12614 CORE_ADDR tpaddr;
12615 char addrbuf[40];
12616 char buf[BUF_SIZE];
12617 std::vector<std::string> tdp_actions;
12618 std::vector<std::string> stepping_actions;
12619 char *pkt;
12620 struct breakpoint *b = loc->owner;
12621 struct tracepoint *t = (struct tracepoint *) b;
12622 struct remote_state *rs = get_remote_state ();
12623
12624 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12625
12626 tpaddr = loc->address;
12627 sprintf_vma (addrbuf, tpaddr);
12628 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12629 addrbuf, /* address */
12630 (b->enable_state == bp_enabled ? 'E' : 'D'),
12631 t->step_count, t->pass_count);
12632 /* Fast tracepoints are mostly handled by the target, but we can
12633 tell the target how big of an instruction block should be moved
12634 around. */
12635 if (b->type == bp_fast_tracepoint)
12636 {
12637 /* Only test for support at download time; we may not know
12638 target capabilities at definition time. */
12639 if (remote_supports_fast_tracepoints ())
12640 {
12641 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12642 NULL))
12643 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12644 gdb_insn_length (loc->gdbarch, tpaddr));
12645 else
12646 /* If it passed validation at definition but fails now,
12647 something is very wrong. */
12648 internal_error (__FILE__, __LINE__,
12649 _("Fast tracepoint not "
12650 "valid during download"));
12651 }
12652 else
12653 /* Fast tracepoints are functionally identical to regular
12654 tracepoints, so don't take lack of support as a reason to
12655 give up on the trace run. */
12656 warning (_("Target does not support fast tracepoints, "
12657 "downloading %d as regular tracepoint"), b->number);
12658 }
12659 else if (b->type == bp_static_tracepoint)
12660 {
12661 /* Only test for support at download time; we may not know
12662 target capabilities at definition time. */
12663 if (remote_supports_static_tracepoints ())
12664 {
12665 struct static_tracepoint_marker marker;
12666
12667 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12668 strcat (buf, ":S");
12669 else
12670 error (_("Static tracepoint not valid during download"));
12671 }
12672 else
12673 /* Fast tracepoints are functionally identical to regular
12674 tracepoints, so don't take lack of support as a reason
12675 to give up on the trace run. */
12676 error (_("Target does not support static tracepoints"));
12677 }
12678 /* If the tracepoint has a conditional, make it into an agent
12679 expression and append to the definition. */
12680 if (loc->cond)
12681 {
12682 /* Only test support at download time, we may not know target
12683 capabilities at definition time. */
12684 if (remote_supports_cond_tracepoints ())
12685 {
12686 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12687 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12688 aexpr->len);
12689 pkt = buf + strlen (buf);
12690 for (int ndx = 0; ndx < aexpr->len; ++ndx)
12691 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12692 *pkt = '\0';
12693 }
12694 else
12695 warning (_("Target does not support conditional tracepoints, "
12696 "ignoring tp %d cond"), b->number);
12697 }
12698
12699 if (b->commands || *default_collect)
12700 strcat (buf, "-");
12701 putpkt (buf);
12702 remote_get_noisy_reply ();
12703 if (strcmp (rs->buf, "OK"))
12704 error (_("Target does not support tracepoints."));
12705
12706 /* do_single_steps (t); */
12707 for (auto action_it = tdp_actions.begin ();
12708 action_it != tdp_actions.end (); action_it++)
12709 {
12710 QUIT; /* Allow user to bail out with ^C. */
12711
12712 bool has_more = (action_it != tdp_actions.end ()
12713 || !stepping_actions.empty ());
12714
12715 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12716 b->number, addrbuf, /* address */
12717 action_it->c_str (),
12718 has_more ? '-' : 0);
12719 putpkt (buf);
12720 remote_get_noisy_reply ();
12721 if (strcmp (rs->buf, "OK"))
12722 error (_("Error on target while setting tracepoints."));
12723 }
12724
12725 for (auto action_it = stepping_actions.begin ();
12726 action_it != stepping_actions.end (); action_it++)
12727 {
12728 QUIT; /* Allow user to bail out with ^C. */
12729
12730 bool is_first = action_it == stepping_actions.begin ();
12731 bool has_more = action_it != stepping_actions.end ();
12732
12733 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12734 b->number, addrbuf, /* address */
12735 is_first ? "S" : "",
12736 action_it->c_str (),
12737 has_more ? "-" : "");
12738 putpkt (buf);
12739 remote_get_noisy_reply ();
12740 if (strcmp (rs->buf, "OK"))
12741 error (_("Error on target while setting tracepoints."));
12742 }
12743
12744 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12745 {
12746 if (b->location != NULL)
12747 {
12748 strcpy (buf, "QTDPsrc:");
12749 encode_source_string (b->number, loc->address, "at",
12750 event_location_to_string (b->location.get ()),
12751 buf + strlen (buf), 2048 - strlen (buf));
12752 putpkt (buf);
12753 remote_get_noisy_reply ();
12754 if (strcmp (rs->buf, "OK"))
12755 warning (_("Target does not support source download."));
12756 }
12757 if (b->cond_string)
12758 {
12759 strcpy (buf, "QTDPsrc:");
12760 encode_source_string (b->number, loc->address,
12761 "cond", b->cond_string, buf + strlen (buf),
12762 2048 - strlen (buf));
12763 putpkt (buf);
12764 remote_get_noisy_reply ();
12765 if (strcmp (rs->buf, "OK"))
12766 warning (_("Target does not support source download."));
12767 }
12768 remote_download_command_source (b->number, loc->address,
12769 breakpoint_commands (b));
12770 }
12771 }
12772
12773 bool
12774 remote_target::can_download_tracepoint ()
12775 {
12776 struct remote_state *rs = get_remote_state ();
12777 struct trace_status *ts;
12778 int status;
12779
12780 /* Don't try to install tracepoints until we've relocated our
12781 symbols, and fetched and merged the target's tracepoint list with
12782 ours. */
12783 if (rs->starting_up)
12784 return false;
12785
12786 ts = current_trace_status ();
12787 status = get_trace_status (ts);
12788
12789 if (status == -1 || !ts->running_known || !ts->running)
12790 return false;
12791
12792 /* If we are in a tracing experiment, but remote stub doesn't support
12793 installing tracepoint in trace, we have to return. */
12794 if (!remote_supports_install_in_trace ())
12795 return false;
12796
12797 return true;
12798 }
12799
12800
12801 void
12802 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12803 {
12804 struct remote_state *rs = get_remote_state ();
12805 char *p;
12806
12807 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12808 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12809 tsv.builtin);
12810 p = rs->buf + strlen (rs->buf);
12811 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12812 error (_("Trace state variable name too long for tsv definition packet"));
12813 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12814 *p++ = '\0';
12815 putpkt (rs->buf);
12816 remote_get_noisy_reply ();
12817 if (*rs->buf == '\0')
12818 error (_("Target does not support this command."));
12819 if (strcmp (rs->buf, "OK") != 0)
12820 error (_("Error on target while downloading trace state variable."));
12821 }
12822
12823 void
12824 remote_target::enable_tracepoint (struct bp_location *location)
12825 {
12826 struct remote_state *rs = get_remote_state ();
12827 char addr_buf[40];
12828
12829 sprintf_vma (addr_buf, location->address);
12830 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12831 location->owner->number, addr_buf);
12832 putpkt (rs->buf);
12833 remote_get_noisy_reply ();
12834 if (*rs->buf == '\0')
12835 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12836 if (strcmp (rs->buf, "OK") != 0)
12837 error (_("Error on target while enabling tracepoint."));
12838 }
12839
12840 void
12841 remote_target::disable_tracepoint (struct bp_location *location)
12842 {
12843 struct remote_state *rs = get_remote_state ();
12844 char addr_buf[40];
12845
12846 sprintf_vma (addr_buf, location->address);
12847 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12848 location->owner->number, addr_buf);
12849 putpkt (rs->buf);
12850 remote_get_noisy_reply ();
12851 if (*rs->buf == '\0')
12852 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12853 if (strcmp (rs->buf, "OK") != 0)
12854 error (_("Error on target while disabling tracepoint."));
12855 }
12856
12857 void
12858 remote_target::trace_set_readonly_regions ()
12859 {
12860 asection *s;
12861 bfd *abfd = NULL;
12862 bfd_size_type size;
12863 bfd_vma vma;
12864 int anysecs = 0;
12865 int offset = 0;
12866
12867 if (!exec_bfd)
12868 return; /* No information to give. */
12869
12870 struct remote_state *rs = get_remote_state ();
12871
12872 strcpy (rs->buf, "QTro");
12873 offset = strlen (rs->buf);
12874 for (s = exec_bfd->sections; s; s = s->next)
12875 {
12876 char tmp1[40], tmp2[40];
12877 int sec_length;
12878
12879 if ((s->flags & SEC_LOAD) == 0 ||
12880 /* (s->flags & SEC_CODE) == 0 || */
12881 (s->flags & SEC_READONLY) == 0)
12882 continue;
12883
12884 anysecs = 1;
12885 vma = bfd_get_section_vma (abfd, s);
12886 size = bfd_get_section_size (s);
12887 sprintf_vma (tmp1, vma);
12888 sprintf_vma (tmp2, vma + size);
12889 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12890 if (offset + sec_length + 1 > rs->buf_size)
12891 {
12892 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12893 warning (_("\
12894 Too many sections for read-only sections definition packet."));
12895 break;
12896 }
12897 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
12898 tmp1, tmp2);
12899 offset += sec_length;
12900 }
12901 if (anysecs)
12902 {
12903 putpkt (rs->buf);
12904 getpkt (&rs->buf, &rs->buf_size, 0);
12905 }
12906 }
12907
12908 void
12909 remote_target::trace_start ()
12910 {
12911 struct remote_state *rs = get_remote_state ();
12912
12913 putpkt ("QTStart");
12914 remote_get_noisy_reply ();
12915 if (*rs->buf == '\0')
12916 error (_("Target does not support this command."));
12917 if (strcmp (rs->buf, "OK") != 0)
12918 error (_("Bogus reply from target: %s"), rs->buf);
12919 }
12920
12921 int
12922 remote_target::get_trace_status (struct trace_status *ts)
12923 {
12924 /* Initialize it just to avoid a GCC false warning. */
12925 char *p = NULL;
12926 /* FIXME we need to get register block size some other way. */
12927 extern int trace_regblock_size;
12928 enum packet_result result;
12929 struct remote_state *rs = get_remote_state ();
12930
12931 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12932 return -1;
12933
12934 trace_regblock_size
12935 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
12936
12937 putpkt ("qTStatus");
12938
12939 TRY
12940 {
12941 p = remote_get_noisy_reply ();
12942 }
12943 CATCH (ex, RETURN_MASK_ERROR)
12944 {
12945 if (ex.error != TARGET_CLOSE_ERROR)
12946 {
12947 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12948 return -1;
12949 }
12950 throw_exception (ex);
12951 }
12952 END_CATCH
12953
12954 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12955
12956 /* If the remote target doesn't do tracing, flag it. */
12957 if (result == PACKET_UNKNOWN)
12958 return -1;
12959
12960 /* We're working with a live target. */
12961 ts->filename = NULL;
12962
12963 if (*p++ != 'T')
12964 error (_("Bogus trace status reply from target: %s"), rs->buf);
12965
12966 /* Function 'parse_trace_status' sets default value of each field of
12967 'ts' at first, so we don't have to do it here. */
12968 parse_trace_status (p, ts);
12969
12970 return ts->running;
12971 }
12972
12973 void
12974 remote_target::get_tracepoint_status (struct breakpoint *bp,
12975 struct uploaded_tp *utp)
12976 {
12977 struct remote_state *rs = get_remote_state ();
12978 char *reply;
12979 struct bp_location *loc;
12980 struct tracepoint *tp = (struct tracepoint *) bp;
12981 size_t size = get_remote_packet_size ();
12982
12983 if (tp)
12984 {
12985 tp->hit_count = 0;
12986 tp->traceframe_usage = 0;
12987 for (loc = tp->loc; loc; loc = loc->next)
12988 {
12989 /* If the tracepoint was never downloaded, don't go asking for
12990 any status. */
12991 if (tp->number_on_target == 0)
12992 continue;
12993 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12994 phex_nz (loc->address, 0));
12995 putpkt (rs->buf);
12996 reply = remote_get_noisy_reply ();
12997 if (reply && *reply)
12998 {
12999 if (*reply == 'V')
13000 parse_tracepoint_status (reply + 1, bp, utp);
13001 }
13002 }
13003 }
13004 else if (utp)
13005 {
13006 utp->hit_count = 0;
13007 utp->traceframe_usage = 0;
13008 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13009 phex_nz (utp->addr, 0));
13010 putpkt (rs->buf);
13011 reply = remote_get_noisy_reply ();
13012 if (reply && *reply)
13013 {
13014 if (*reply == 'V')
13015 parse_tracepoint_status (reply + 1, bp, utp);
13016 }
13017 }
13018 }
13019
13020 void
13021 remote_target::trace_stop ()
13022 {
13023 struct remote_state *rs = get_remote_state ();
13024
13025 putpkt ("QTStop");
13026 remote_get_noisy_reply ();
13027 if (*rs->buf == '\0')
13028 error (_("Target does not support this command."));
13029 if (strcmp (rs->buf, "OK") != 0)
13030 error (_("Bogus reply from target: %s"), rs->buf);
13031 }
13032
13033 int
13034 remote_target::trace_find (enum trace_find_type type, int num,
13035 CORE_ADDR addr1, CORE_ADDR addr2,
13036 int *tpp)
13037 {
13038 struct remote_state *rs = get_remote_state ();
13039 char *endbuf = rs->buf + get_remote_packet_size ();
13040 char *p, *reply;
13041 int target_frameno = -1, target_tracept = -1;
13042
13043 /* Lookups other than by absolute frame number depend on the current
13044 trace selected, so make sure it is correct on the remote end
13045 first. */
13046 if (type != tfind_number)
13047 set_remote_traceframe ();
13048
13049 p = rs->buf;
13050 strcpy (p, "QTFrame:");
13051 p = strchr (p, '\0');
13052 switch (type)
13053 {
13054 case tfind_number:
13055 xsnprintf (p, endbuf - p, "%x", num);
13056 break;
13057 case tfind_pc:
13058 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13059 break;
13060 case tfind_tp:
13061 xsnprintf (p, endbuf - p, "tdp:%x", num);
13062 break;
13063 case tfind_range:
13064 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13065 phex_nz (addr2, 0));
13066 break;
13067 case tfind_outside:
13068 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13069 phex_nz (addr2, 0));
13070 break;
13071 default:
13072 error (_("Unknown trace find type %d"), type);
13073 }
13074
13075 putpkt (rs->buf);
13076 reply = remote_get_noisy_reply ();
13077 if (*reply == '\0')
13078 error (_("Target does not support this command."));
13079
13080 while (reply && *reply)
13081 switch (*reply)
13082 {
13083 case 'F':
13084 p = ++reply;
13085 target_frameno = (int) strtol (p, &reply, 16);
13086 if (reply == p)
13087 error (_("Unable to parse trace frame number"));
13088 /* Don't update our remote traceframe number cache on failure
13089 to select a remote traceframe. */
13090 if (target_frameno == -1)
13091 return -1;
13092 break;
13093 case 'T':
13094 p = ++reply;
13095 target_tracept = (int) strtol (p, &reply, 16);
13096 if (reply == p)
13097 error (_("Unable to parse tracepoint number"));
13098 break;
13099 case 'O': /* "OK"? */
13100 if (reply[1] == 'K' && reply[2] == '\0')
13101 reply += 2;
13102 else
13103 error (_("Bogus reply from target: %s"), reply);
13104 break;
13105 default:
13106 error (_("Bogus reply from target: %s"), reply);
13107 }
13108 if (tpp)
13109 *tpp = target_tracept;
13110
13111 rs->remote_traceframe_number = target_frameno;
13112 return target_frameno;
13113 }
13114
13115 bool
13116 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13117 {
13118 struct remote_state *rs = get_remote_state ();
13119 char *reply;
13120 ULONGEST uval;
13121
13122 set_remote_traceframe ();
13123
13124 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13125 putpkt (rs->buf);
13126 reply = remote_get_noisy_reply ();
13127 if (reply && *reply)
13128 {
13129 if (*reply == 'V')
13130 {
13131 unpack_varlen_hex (reply + 1, &uval);
13132 *val = (LONGEST) uval;
13133 return true;
13134 }
13135 }
13136 return false;
13137 }
13138
13139 int
13140 remote_target::save_trace_data (const char *filename)
13141 {
13142 struct remote_state *rs = get_remote_state ();
13143 char *p, *reply;
13144
13145 p = rs->buf;
13146 strcpy (p, "QTSave:");
13147 p += strlen (p);
13148 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13149 error (_("Remote file name too long for trace save packet"));
13150 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13151 *p++ = '\0';
13152 putpkt (rs->buf);
13153 reply = remote_get_noisy_reply ();
13154 if (*reply == '\0')
13155 error (_("Target does not support this command."));
13156 if (strcmp (reply, "OK") != 0)
13157 error (_("Bogus reply from target: %s"), reply);
13158 return 0;
13159 }
13160
13161 /* This is basically a memory transfer, but needs to be its own packet
13162 because we don't know how the target actually organizes its trace
13163 memory, plus we want to be able to ask for as much as possible, but
13164 not be unhappy if we don't get as much as we ask for. */
13165
13166 LONGEST
13167 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13168 {
13169 struct remote_state *rs = get_remote_state ();
13170 char *reply;
13171 char *p;
13172 int rslt;
13173
13174 p = rs->buf;
13175 strcpy (p, "qTBuffer:");
13176 p += strlen (p);
13177 p += hexnumstr (p, offset);
13178 *p++ = ',';
13179 p += hexnumstr (p, len);
13180 *p++ = '\0';
13181
13182 putpkt (rs->buf);
13183 reply = remote_get_noisy_reply ();
13184 if (reply && *reply)
13185 {
13186 /* 'l' by itself means we're at the end of the buffer and
13187 there is nothing more to get. */
13188 if (*reply == 'l')
13189 return 0;
13190
13191 /* Convert the reply into binary. Limit the number of bytes to
13192 convert according to our passed-in buffer size, rather than
13193 what was returned in the packet; if the target is
13194 unexpectedly generous and gives us a bigger reply than we
13195 asked for, we don't want to crash. */
13196 rslt = hex2bin (reply, buf, len);
13197 return rslt;
13198 }
13199
13200 /* Something went wrong, flag as an error. */
13201 return -1;
13202 }
13203
13204 void
13205 remote_target::set_disconnected_tracing (int val)
13206 {
13207 struct remote_state *rs = get_remote_state ();
13208
13209 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13210 {
13211 char *reply;
13212
13213 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13214 putpkt (rs->buf);
13215 reply = remote_get_noisy_reply ();
13216 if (*reply == '\0')
13217 error (_("Target does not support this command."));
13218 if (strcmp (reply, "OK") != 0)
13219 error (_("Bogus reply from target: %s"), reply);
13220 }
13221 else if (val)
13222 warning (_("Target does not support disconnected tracing."));
13223 }
13224
13225 int
13226 remote_target::core_of_thread (ptid_t ptid)
13227 {
13228 struct thread_info *info = find_thread_ptid (ptid);
13229
13230 if (info != NULL && info->priv != NULL)
13231 return get_remote_thread_info (info)->core;
13232
13233 return -1;
13234 }
13235
13236 void
13237 remote_target::set_circular_trace_buffer (int val)
13238 {
13239 struct remote_state *rs = get_remote_state ();
13240 char *reply;
13241
13242 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13243 putpkt (rs->buf);
13244 reply = remote_get_noisy_reply ();
13245 if (*reply == '\0')
13246 error (_("Target does not support this command."));
13247 if (strcmp (reply, "OK") != 0)
13248 error (_("Bogus reply from target: %s"), reply);
13249 }
13250
13251 traceframe_info_up
13252 remote_target::traceframe_info ()
13253 {
13254 gdb::optional<gdb::char_vector> text
13255 = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
13256 NULL);
13257 if (text)
13258 return parse_traceframe_info (text->data ());
13259
13260 return NULL;
13261 }
13262
13263 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13264 instruction on which a fast tracepoint may be placed. Returns -1
13265 if the packet is not supported, and 0 if the minimum instruction
13266 length is unknown. */
13267
13268 int
13269 remote_target::get_min_fast_tracepoint_insn_len ()
13270 {
13271 struct remote_state *rs = get_remote_state ();
13272 char *reply;
13273
13274 /* If we're not debugging a process yet, the IPA can't be
13275 loaded. */
13276 if (!target_has_execution)
13277 return 0;
13278
13279 /* Make sure the remote is pointing at the right process. */
13280 set_general_process ();
13281
13282 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13283 putpkt (rs->buf);
13284 reply = remote_get_noisy_reply ();
13285 if (*reply == '\0')
13286 return -1;
13287 else
13288 {
13289 ULONGEST min_insn_len;
13290
13291 unpack_varlen_hex (reply, &min_insn_len);
13292
13293 return (int) min_insn_len;
13294 }
13295 }
13296
13297 void
13298 remote_target::set_trace_buffer_size (LONGEST val)
13299 {
13300 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13301 {
13302 struct remote_state *rs = get_remote_state ();
13303 char *buf = rs->buf;
13304 char *endbuf = rs->buf + get_remote_packet_size ();
13305 enum packet_result result;
13306
13307 gdb_assert (val >= 0 || val == -1);
13308 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13309 /* Send -1 as literal "-1" to avoid host size dependency. */
13310 if (val < 0)
13311 {
13312 *buf++ = '-';
13313 buf += hexnumstr (buf, (ULONGEST) -val);
13314 }
13315 else
13316 buf += hexnumstr (buf, (ULONGEST) val);
13317
13318 putpkt (rs->buf);
13319 remote_get_noisy_reply ();
13320 result = packet_ok (rs->buf,
13321 &remote_protocol_packets[PACKET_QTBuffer_size]);
13322
13323 if (result != PACKET_OK)
13324 warning (_("Bogus reply from target: %s"), rs->buf);
13325 }
13326 }
13327
13328 bool
13329 remote_target::set_trace_notes (const char *user, const char *notes,
13330 const char *stop_notes)
13331 {
13332 struct remote_state *rs = get_remote_state ();
13333 char *reply;
13334 char *buf = rs->buf;
13335 char *endbuf = rs->buf + get_remote_packet_size ();
13336 int nbytes;
13337
13338 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13339 if (user)
13340 {
13341 buf += xsnprintf (buf, endbuf - buf, "user:");
13342 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13343 buf += 2 * nbytes;
13344 *buf++ = ';';
13345 }
13346 if (notes)
13347 {
13348 buf += xsnprintf (buf, endbuf - buf, "notes:");
13349 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13350 buf += 2 * nbytes;
13351 *buf++ = ';';
13352 }
13353 if (stop_notes)
13354 {
13355 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13356 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13357 buf += 2 * nbytes;
13358 *buf++ = ';';
13359 }
13360 /* Ensure the buffer is terminated. */
13361 *buf = '\0';
13362
13363 putpkt (rs->buf);
13364 reply = remote_get_noisy_reply ();
13365 if (*reply == '\0')
13366 return false;
13367
13368 if (strcmp (reply, "OK") != 0)
13369 error (_("Bogus reply from target: %s"), reply);
13370
13371 return true;
13372 }
13373
13374 bool
13375 remote_target::use_agent (bool use)
13376 {
13377 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13378 {
13379 struct remote_state *rs = get_remote_state ();
13380
13381 /* If the stub supports QAgent. */
13382 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13383 putpkt (rs->buf);
13384 getpkt (&rs->buf, &rs->buf_size, 0);
13385
13386 if (strcmp (rs->buf, "OK") == 0)
13387 {
13388 ::use_agent = use;
13389 return true;
13390 }
13391 }
13392
13393 return false;
13394 }
13395
13396 bool
13397 remote_target::can_use_agent ()
13398 {
13399 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13400 }
13401
13402 struct btrace_target_info
13403 {
13404 /* The ptid of the traced thread. */
13405 ptid_t ptid;
13406
13407 /* The obtained branch trace configuration. */
13408 struct btrace_config conf;
13409 };
13410
13411 /* Reset our idea of our target's btrace configuration. */
13412
13413 static void
13414 remote_btrace_reset (void)
13415 {
13416 struct remote_state *rs = get_remote_state ();
13417
13418 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13419 }
13420
13421 /* Synchronize the configuration with the target. */
13422
13423 static void
13424 btrace_sync_conf (const struct btrace_config *conf)
13425 {
13426 struct packet_config *packet;
13427 struct remote_state *rs;
13428 char *buf, *pos, *endbuf;
13429
13430 rs = get_remote_state ();
13431 buf = rs->buf;
13432 endbuf = buf + get_remote_packet_size ();
13433
13434 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13435 if (packet_config_support (packet) == PACKET_ENABLE
13436 && conf->bts.size != rs->btrace_config.bts.size)
13437 {
13438 pos = buf;
13439 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13440 conf->bts.size);
13441
13442 putpkt (buf);
13443 getpkt (&buf, &rs->buf_size, 0);
13444
13445 if (packet_ok (buf, packet) == PACKET_ERROR)
13446 {
13447 if (buf[0] == 'E' && buf[1] == '.')
13448 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13449 else
13450 error (_("Failed to configure the BTS buffer size."));
13451 }
13452
13453 rs->btrace_config.bts.size = conf->bts.size;
13454 }
13455
13456 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13457 if (packet_config_support (packet) == PACKET_ENABLE
13458 && conf->pt.size != rs->btrace_config.pt.size)
13459 {
13460 pos = buf;
13461 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13462 conf->pt.size);
13463
13464 putpkt (buf);
13465 getpkt (&buf, &rs->buf_size, 0);
13466
13467 if (packet_ok (buf, packet) == PACKET_ERROR)
13468 {
13469 if (buf[0] == 'E' && buf[1] == '.')
13470 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13471 else
13472 error (_("Failed to configure the trace buffer size."));
13473 }
13474
13475 rs->btrace_config.pt.size = conf->pt.size;
13476 }
13477 }
13478
13479 /* Read the current thread's btrace configuration from the target and
13480 store it into CONF. */
13481
13482 static void
13483 btrace_read_config (struct btrace_config *conf)
13484 {
13485 gdb::optional<gdb::char_vector> xml
13486 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
13487 if (xml)
13488 parse_xml_btrace_conf (conf, xml->data ());
13489 }
13490
13491 /* Maybe reopen target btrace. */
13492
13493 static void
13494 remote_btrace_maybe_reopen (void)
13495 {
13496 struct remote_state *rs = get_remote_state ();
13497 struct thread_info *tp;
13498 int btrace_target_pushed = 0;
13499 int warned = 0;
13500
13501 scoped_restore_current_thread restore_thread;
13502
13503 ALL_NON_EXITED_THREADS (tp)
13504 {
13505 set_general_thread (tp->ptid);
13506
13507 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13508 btrace_read_config (&rs->btrace_config);
13509
13510 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13511 continue;
13512
13513 #if !defined (HAVE_LIBIPT)
13514 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13515 {
13516 if (!warned)
13517 {
13518 warned = 1;
13519 warning (_("Target is recording using Intel Processor Trace "
13520 "but support was disabled at compile time."));
13521 }
13522
13523 continue;
13524 }
13525 #endif /* !defined (HAVE_LIBIPT) */
13526
13527 /* Push target, once, but before anything else happens. This way our
13528 changes to the threads will be cleaned up by unpushing the target
13529 in case btrace_read_config () throws. */
13530 if (!btrace_target_pushed)
13531 {
13532 btrace_target_pushed = 1;
13533 record_btrace_push_target ();
13534 printf_filtered (_("Target is recording using %s.\n"),
13535 btrace_format_string (rs->btrace_config.format));
13536 }
13537
13538 tp->btrace.target = XCNEW (struct btrace_target_info);
13539 tp->btrace.target->ptid = tp->ptid;
13540 tp->btrace.target->conf = rs->btrace_config;
13541 }
13542 }
13543
13544 /* Enable branch tracing. */
13545
13546 struct btrace_target_info *
13547 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13548 {
13549 struct btrace_target_info *tinfo = NULL;
13550 struct packet_config *packet = NULL;
13551 struct remote_state *rs = get_remote_state ();
13552 char *buf = rs->buf;
13553 char *endbuf = rs->buf + get_remote_packet_size ();
13554
13555 switch (conf->format)
13556 {
13557 case BTRACE_FORMAT_BTS:
13558 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13559 break;
13560
13561 case BTRACE_FORMAT_PT:
13562 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13563 break;
13564 }
13565
13566 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13567 error (_("Target does not support branch tracing."));
13568
13569 btrace_sync_conf (conf);
13570
13571 set_general_thread (ptid);
13572
13573 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13574 putpkt (rs->buf);
13575 getpkt (&rs->buf, &rs->buf_size, 0);
13576
13577 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13578 {
13579 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13580 error (_("Could not enable branch tracing for %s: %s"),
13581 target_pid_to_str (ptid), rs->buf + 2);
13582 else
13583 error (_("Could not enable branch tracing for %s."),
13584 target_pid_to_str (ptid));
13585 }
13586
13587 tinfo = XCNEW (struct btrace_target_info);
13588 tinfo->ptid = ptid;
13589
13590 /* If we fail to read the configuration, we lose some information, but the
13591 tracing itself is not impacted. */
13592 TRY
13593 {
13594 btrace_read_config (&tinfo->conf);
13595 }
13596 CATCH (err, RETURN_MASK_ERROR)
13597 {
13598 if (err.message != NULL)
13599 warning ("%s", err.message);
13600 }
13601 END_CATCH
13602
13603 return tinfo;
13604 }
13605
13606 /* Disable branch tracing. */
13607
13608 void
13609 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13610 {
13611 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13612 struct remote_state *rs = get_remote_state ();
13613 char *buf = rs->buf;
13614 char *endbuf = rs->buf + get_remote_packet_size ();
13615
13616 if (packet_config_support (packet) != PACKET_ENABLE)
13617 error (_("Target does not support branch tracing."));
13618
13619 set_general_thread (tinfo->ptid);
13620
13621 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13622 putpkt (rs->buf);
13623 getpkt (&rs->buf, &rs->buf_size, 0);
13624
13625 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13626 {
13627 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13628 error (_("Could not disable branch tracing for %s: %s"),
13629 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13630 else
13631 error (_("Could not disable branch tracing for %s."),
13632 target_pid_to_str (tinfo->ptid));
13633 }
13634
13635 xfree (tinfo);
13636 }
13637
13638 /* Teardown branch tracing. */
13639
13640 void
13641 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13642 {
13643 /* We must not talk to the target during teardown. */
13644 xfree (tinfo);
13645 }
13646
13647 /* Read the branch trace. */
13648
13649 enum btrace_error
13650 remote_target::read_btrace (struct btrace_data *btrace,
13651 struct btrace_target_info *tinfo,
13652 enum btrace_read_type type)
13653 {
13654 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13655 const char *annex;
13656
13657 if (packet_config_support (packet) != PACKET_ENABLE)
13658 error (_("Target does not support branch tracing."));
13659
13660 #if !defined(HAVE_LIBEXPAT)
13661 error (_("Cannot process branch tracing result. XML parsing not supported."));
13662 #endif
13663
13664 switch (type)
13665 {
13666 case BTRACE_READ_ALL:
13667 annex = "all";
13668 break;
13669 case BTRACE_READ_NEW:
13670 annex = "new";
13671 break;
13672 case BTRACE_READ_DELTA:
13673 annex = "delta";
13674 break;
13675 default:
13676 internal_error (__FILE__, __LINE__,
13677 _("Bad branch tracing read type: %u."),
13678 (unsigned int) type);
13679 }
13680
13681 gdb::optional<gdb::char_vector> xml
13682 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
13683 if (!xml)
13684 return BTRACE_ERR_UNKNOWN;
13685
13686 parse_xml_btrace (btrace, xml->data ());
13687
13688 return BTRACE_ERR_NONE;
13689 }
13690
13691 const struct btrace_config *
13692 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13693 {
13694 return &tinfo->conf;
13695 }
13696
13697 bool
13698 remote_target::augmented_libraries_svr4_read ()
13699 {
13700 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13701 == PACKET_ENABLE);
13702 }
13703
13704 /* Implementation of to_load. */
13705
13706 void
13707 remote_target::load (const char *name, int from_tty)
13708 {
13709 generic_load (name, from_tty);
13710 }
13711
13712 /* Accepts an integer PID; returns a string representing a file that
13713 can be opened on the remote side to get the symbols for the child
13714 process. Returns NULL if the operation is not supported. */
13715
13716 char *
13717 remote_target::pid_to_exec_file (int pid)
13718 {
13719 static gdb::optional<gdb::char_vector> filename;
13720 struct inferior *inf;
13721 char *annex = NULL;
13722
13723 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13724 return NULL;
13725
13726 inf = find_inferior_pid (pid);
13727 if (inf == NULL)
13728 internal_error (__FILE__, __LINE__,
13729 _("not currently attached to process %d"), pid);
13730
13731 if (!inf->fake_pid_p)
13732 {
13733 const int annex_size = 9;
13734
13735 annex = (char *) alloca (annex_size);
13736 xsnprintf (annex, annex_size, "%x", pid);
13737 }
13738
13739 filename = target_read_stralloc (target_stack,
13740 TARGET_OBJECT_EXEC_FILE, annex);
13741
13742 return filename ? filename->data () : nullptr;
13743 }
13744
13745 /* Implement the to_can_do_single_step target_ops method. */
13746
13747 int
13748 remote_target::can_do_single_step ()
13749 {
13750 /* We can only tell whether target supports single step or not by
13751 supported s and S vCont actions if the stub supports vContSupported
13752 feature. If the stub doesn't support vContSupported feature,
13753 we have conservatively to think target doesn't supports single
13754 step. */
13755 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13756 {
13757 struct remote_state *rs = get_remote_state ();
13758
13759 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13760 remote_vcont_probe (rs);
13761
13762 return rs->supports_vCont.s && rs->supports_vCont.S;
13763 }
13764 else
13765 return 0;
13766 }
13767
13768 /* Implementation of the to_execution_direction method for the remote
13769 target. */
13770
13771 enum exec_direction_kind
13772 remote_target::execution_direction ()
13773 {
13774 struct remote_state *rs = get_remote_state ();
13775
13776 return rs->last_resume_exec_dir;
13777 }
13778
13779 /* Return pointer to the thread_info struct which corresponds to
13780 THREAD_HANDLE (having length HANDLE_LEN). */
13781
13782 thread_info *
13783 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13784 int handle_len,
13785 inferior *inf)
13786 {
13787 struct thread_info *tp;
13788
13789 ALL_NON_EXITED_THREADS (tp)
13790 {
13791 remote_thread_info *priv = get_remote_thread_info (tp);
13792
13793 if (tp->inf == inf && priv != NULL)
13794 {
13795 if (handle_len != priv->thread_handle.size ())
13796 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13797 handle_len, priv->thread_handle.size ());
13798 if (memcmp (thread_handle, priv->thread_handle.data (),
13799 handle_len) == 0)
13800 return tp;
13801 }
13802 }
13803
13804 return NULL;
13805 }
13806
13807 bool
13808 remote_target::can_async_p ()
13809 {
13810 struct remote_state *rs = get_remote_state ();
13811
13812 /* We don't go async if the user has explicitly prevented it with the
13813 "maint set target-async" command. */
13814 if (!target_async_permitted)
13815 return false;
13816
13817 /* We're async whenever the serial device is. */
13818 return serial_can_async_p (rs->remote_desc);
13819 }
13820
13821 bool
13822 remote_target::is_async_p ()
13823 {
13824 struct remote_state *rs = get_remote_state ();
13825
13826 if (!target_async_permitted)
13827 /* We only enable async when the user specifically asks for it. */
13828 return false;
13829
13830 /* We're async whenever the serial device is. */
13831 return serial_is_async_p (rs->remote_desc);
13832 }
13833
13834 /* Pass the SERIAL event on and up to the client. One day this code
13835 will be able to delay notifying the client of an event until the
13836 point where an entire packet has been received. */
13837
13838 static serial_event_ftype remote_async_serial_handler;
13839
13840 static void
13841 remote_async_serial_handler (struct serial *scb, void *context)
13842 {
13843 /* Don't propogate error information up to the client. Instead let
13844 the client find out about the error by querying the target. */
13845 inferior_event_handler (INF_REG_EVENT, NULL);
13846 }
13847
13848 static void
13849 remote_async_inferior_event_handler (gdb_client_data data)
13850 {
13851 inferior_event_handler (INF_REG_EVENT, NULL);
13852 }
13853
13854 void
13855 remote_target::async (int enable)
13856 {
13857 struct remote_state *rs = get_remote_state ();
13858
13859 if (enable)
13860 {
13861 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13862
13863 /* If there are pending events in the stop reply queue tell the
13864 event loop to process them. */
13865 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13866 mark_async_event_handler (remote_async_inferior_event_token);
13867 /* For simplicity, below we clear the pending events token
13868 without remembering whether it is marked, so here we always
13869 mark it. If there's actually no pending notification to
13870 process, this ends up being a no-op (other than a spurious
13871 event-loop wakeup). */
13872 if (target_is_non_stop_p ())
13873 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13874 }
13875 else
13876 {
13877 serial_async (rs->remote_desc, NULL, NULL);
13878 /* If the core is disabling async, it doesn't want to be
13879 disturbed with target events. Clear all async event sources
13880 too. */
13881 clear_async_event_handler (remote_async_inferior_event_token);
13882 if (target_is_non_stop_p ())
13883 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13884 }
13885 }
13886
13887 /* Implementation of the to_thread_events method. */
13888
13889 void
13890 remote_target::thread_events (int enable)
13891 {
13892 struct remote_state *rs = get_remote_state ();
13893 size_t size = get_remote_packet_size ();
13894
13895 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13896 return;
13897
13898 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13899 putpkt (rs->buf);
13900 getpkt (&rs->buf, &rs->buf_size, 0);
13901
13902 switch (packet_ok (rs->buf,
13903 &remote_protocol_packets[PACKET_QThreadEvents]))
13904 {
13905 case PACKET_OK:
13906 if (strcmp (rs->buf, "OK") != 0)
13907 error (_("Remote refused setting thread events: %s"), rs->buf);
13908 break;
13909 case PACKET_ERROR:
13910 warning (_("Remote failure reply: %s"), rs->buf);
13911 break;
13912 case PACKET_UNKNOWN:
13913 break;
13914 }
13915 }
13916
13917 static void
13918 set_remote_cmd (const char *args, int from_tty)
13919 {
13920 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13921 }
13922
13923 static void
13924 show_remote_cmd (const char *args, int from_tty)
13925 {
13926 /* We can't just use cmd_show_list here, because we want to skip
13927 the redundant "show remote Z-packet" and the legacy aliases. */
13928 struct cmd_list_element *list = remote_show_cmdlist;
13929 struct ui_out *uiout = current_uiout;
13930
13931 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13932 for (; list != NULL; list = list->next)
13933 if (strcmp (list->name, "Z-packet") == 0)
13934 continue;
13935 else if (list->type == not_set_cmd)
13936 /* Alias commands are exactly like the original, except they
13937 don't have the normal type. */
13938 continue;
13939 else
13940 {
13941 ui_out_emit_tuple option_emitter (uiout, "option");
13942
13943 uiout->field_string ("name", list->name);
13944 uiout->text (": ");
13945 if (list->type == show_cmd)
13946 do_show_command (NULL, from_tty, list);
13947 else
13948 cmd_func (list, NULL, from_tty);
13949 }
13950 }
13951
13952
13953 /* Function to be called whenever a new objfile (shlib) is detected. */
13954 static void
13955 remote_new_objfile (struct objfile *objfile)
13956 {
13957 struct remote_state *rs = get_remote_state ();
13958
13959 if (rs->remote_desc != 0) /* Have a remote connection. */
13960 remote_check_symbols ();
13961 }
13962
13963 /* Pull all the tracepoints defined on the target and create local
13964 data structures representing them. We don't want to create real
13965 tracepoints yet, we don't want to mess up the user's existing
13966 collection. */
13967
13968 int
13969 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
13970 {
13971 struct remote_state *rs = get_remote_state ();
13972 char *p;
13973
13974 /* Ask for a first packet of tracepoint definition. */
13975 putpkt ("qTfP");
13976 getpkt (&rs->buf, &rs->buf_size, 0);
13977 p = rs->buf;
13978 while (*p && *p != 'l')
13979 {
13980 parse_tracepoint_definition (p, utpp);
13981 /* Ask for another packet of tracepoint definition. */
13982 putpkt ("qTsP");
13983 getpkt (&rs->buf, &rs->buf_size, 0);
13984 p = rs->buf;
13985 }
13986 return 0;
13987 }
13988
13989 int
13990 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
13991 {
13992 struct remote_state *rs = get_remote_state ();
13993 char *p;
13994
13995 /* Ask for a first packet of variable definition. */
13996 putpkt ("qTfV");
13997 getpkt (&rs->buf, &rs->buf_size, 0);
13998 p = rs->buf;
13999 while (*p && *p != 'l')
14000 {
14001 parse_tsv_definition (p, utsvp);
14002 /* Ask for another packet of variable definition. */
14003 putpkt ("qTsV");
14004 getpkt (&rs->buf, &rs->buf_size, 0);
14005 p = rs->buf;
14006 }
14007 return 0;
14008 }
14009
14010 /* The "set/show range-stepping" show hook. */
14011
14012 static void
14013 show_range_stepping (struct ui_file *file, int from_tty,
14014 struct cmd_list_element *c,
14015 const char *value)
14016 {
14017 fprintf_filtered (file,
14018 _("Debugger's willingness to use range stepping "
14019 "is %s.\n"), value);
14020 }
14021
14022 /* The "set/show range-stepping" set hook. */
14023
14024 static void
14025 set_range_stepping (const char *ignore_args, int from_tty,
14026 struct cmd_list_element *c)
14027 {
14028 struct remote_state *rs = get_remote_state ();
14029
14030 /* Whene enabling, check whether range stepping is actually
14031 supported by the target, and warn if not. */
14032 if (use_range_stepping)
14033 {
14034 if (rs->remote_desc != NULL)
14035 {
14036 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14037 remote_vcont_probe (rs);
14038
14039 if (packet_support (PACKET_vCont) == PACKET_ENABLE
14040 && rs->supports_vCont.r)
14041 return;
14042 }
14043
14044 warning (_("Range stepping is not supported by the current target"));
14045 }
14046 }
14047
14048 void
14049 _initialize_remote (void)
14050 {
14051 struct cmd_list_element *cmd;
14052 const char *cmd_name;
14053
14054 /* architecture specific data */
14055 remote_g_packet_data_handle =
14056 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14057
14058 remote_pspace_data
14059 = register_program_space_data_with_cleanup (NULL,
14060 remote_pspace_data_cleanup);
14061
14062 /* Initialize the per-target state. At the moment there is only one
14063 of these, not one per target. Only one target is active at a
14064 time. */
14065 remote_state = new struct remote_state ();
14066
14067 add_target (remote_target_info, remote_target::open);
14068 add_target (extended_remote_target_info, extended_remote_target::open);
14069
14070 /* Hook into new objfile notification. */
14071 gdb::observers::new_objfile.attach (remote_new_objfile);
14072 /* We're no longer interested in notification events of an inferior
14073 when it exits. */
14074 gdb::observers::inferior_exit.attach (discard_pending_stop_replies);
14075
14076 #if 0
14077 init_remote_threadtests ();
14078 #endif
14079
14080 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14081 /* set/show remote ... */
14082
14083 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14084 Remote protocol specific variables\n\
14085 Configure various remote-protocol specific variables such as\n\
14086 the packets being used"),
14087 &remote_set_cmdlist, "set remote ",
14088 0 /* allow-unknown */, &setlist);
14089 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14090 Remote protocol specific variables\n\
14091 Configure various remote-protocol specific variables such as\n\
14092 the packets being used"),
14093 &remote_show_cmdlist, "show remote ",
14094 0 /* allow-unknown */, &showlist);
14095
14096 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14097 Compare section data on target to the exec file.\n\
14098 Argument is a single section name (default: all loaded sections).\n\
14099 To compare only read-only loaded sections, specify the -r option."),
14100 &cmdlist);
14101
14102 add_cmd ("packet", class_maintenance, packet_command, _("\
14103 Send an arbitrary packet to a remote target.\n\
14104 maintenance packet TEXT\n\
14105 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14106 this command sends the string TEXT to the inferior, and displays the\n\
14107 response packet. GDB supplies the initial `$' character, and the\n\
14108 terminating `#' character and checksum."),
14109 &maintenancelist);
14110
14111 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14112 Set whether to send break if interrupted."), _("\
14113 Show whether to send break if interrupted."), _("\
14114 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14115 set_remotebreak, show_remotebreak,
14116 &setlist, &showlist);
14117 cmd_name = "remotebreak";
14118 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14119 deprecate_cmd (cmd, "set remote interrupt-sequence");
14120 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14121 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14122 deprecate_cmd (cmd, "show remote interrupt-sequence");
14123
14124 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14125 interrupt_sequence_modes, &interrupt_sequence_mode,
14126 _("\
14127 Set interrupt sequence to remote target."), _("\
14128 Show interrupt sequence to remote target."), _("\
14129 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14130 NULL, show_interrupt_sequence,
14131 &remote_set_cmdlist,
14132 &remote_show_cmdlist);
14133
14134 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14135 &interrupt_on_connect, _("\
14136 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14137 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14138 If set, interrupt sequence is sent to remote target."),
14139 NULL, NULL,
14140 &remote_set_cmdlist, &remote_show_cmdlist);
14141
14142 /* Install commands for configuring memory read/write packets. */
14143
14144 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14145 Set the maximum number of bytes per memory write packet (deprecated)."),
14146 &setlist);
14147 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14148 Show the maximum number of bytes per memory write packet (deprecated)."),
14149 &showlist);
14150 add_cmd ("memory-write-packet-size", no_class,
14151 set_memory_write_packet_size, _("\
14152 Set the maximum number of bytes per memory-write packet.\n\
14153 Specify the number of bytes in a packet or 0 (zero) for the\n\
14154 default packet size. The actual limit is further reduced\n\
14155 dependent on the target. Specify ``fixed'' to disable the\n\
14156 further restriction and ``limit'' to enable that restriction."),
14157 &remote_set_cmdlist);
14158 add_cmd ("memory-read-packet-size", no_class,
14159 set_memory_read_packet_size, _("\
14160 Set the maximum number of bytes per memory-read packet.\n\
14161 Specify the number of bytes in a packet or 0 (zero) for the\n\
14162 default packet size. The actual limit is further reduced\n\
14163 dependent on the target. Specify ``fixed'' to disable the\n\
14164 further restriction and ``limit'' to enable that restriction."),
14165 &remote_set_cmdlist);
14166 add_cmd ("memory-write-packet-size", no_class,
14167 show_memory_write_packet_size,
14168 _("Show the maximum number of bytes per memory-write packet."),
14169 &remote_show_cmdlist);
14170 add_cmd ("memory-read-packet-size", no_class,
14171 show_memory_read_packet_size,
14172 _("Show the maximum number of bytes per memory-read packet."),
14173 &remote_show_cmdlist);
14174
14175 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14176 &remote_hw_watchpoint_limit, _("\
14177 Set the maximum number of target hardware watchpoints."), _("\
14178 Show the maximum number of target hardware watchpoints."), _("\
14179 Specify a negative limit for unlimited."),
14180 NULL, NULL, /* FIXME: i18n: The maximum
14181 number of target hardware
14182 watchpoints is %s. */
14183 &remote_set_cmdlist, &remote_show_cmdlist);
14184 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14185 &remote_hw_watchpoint_length_limit, _("\
14186 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14187 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14188 Specify a negative limit for unlimited."),
14189 NULL, NULL, /* FIXME: i18n: The maximum
14190 length (in bytes) of a target
14191 hardware watchpoint is %s. */
14192 &remote_set_cmdlist, &remote_show_cmdlist);
14193 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14194 &remote_hw_breakpoint_limit, _("\
14195 Set the maximum number of target hardware breakpoints."), _("\
14196 Show the maximum number of target hardware breakpoints."), _("\
14197 Specify a negative limit for unlimited."),
14198 NULL, NULL, /* FIXME: i18n: The maximum
14199 number of target hardware
14200 breakpoints is %s. */
14201 &remote_set_cmdlist, &remote_show_cmdlist);
14202
14203 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14204 &remote_address_size, _("\
14205 Set the maximum size of the address (in bits) in a memory packet."), _("\
14206 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14207 NULL,
14208 NULL, /* FIXME: i18n: */
14209 &setlist, &showlist);
14210
14211 init_all_packet_configs ();
14212
14213 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14214 "X", "binary-download", 1);
14215
14216 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14217 "vCont", "verbose-resume", 0);
14218
14219 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14220 "QPassSignals", "pass-signals", 0);
14221
14222 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14223 "QCatchSyscalls", "catch-syscalls", 0);
14224
14225 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14226 "QProgramSignals", "program-signals", 0);
14227
14228 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14229 "QSetWorkingDir", "set-working-dir", 0);
14230
14231 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14232 "QStartupWithShell", "startup-with-shell", 0);
14233
14234 add_packet_config_cmd (&remote_protocol_packets
14235 [PACKET_QEnvironmentHexEncoded],
14236 "QEnvironmentHexEncoded", "environment-hex-encoded",
14237 0);
14238
14239 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14240 "QEnvironmentReset", "environment-reset",
14241 0);
14242
14243 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14244 "QEnvironmentUnset", "environment-unset",
14245 0);
14246
14247 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14248 "qSymbol", "symbol-lookup", 0);
14249
14250 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14251 "P", "set-register", 1);
14252
14253 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14254 "p", "fetch-register", 1);
14255
14256 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14257 "Z0", "software-breakpoint", 0);
14258
14259 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14260 "Z1", "hardware-breakpoint", 0);
14261
14262 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14263 "Z2", "write-watchpoint", 0);
14264
14265 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14266 "Z3", "read-watchpoint", 0);
14267
14268 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14269 "Z4", "access-watchpoint", 0);
14270
14271 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14272 "qXfer:auxv:read", "read-aux-vector", 0);
14273
14274 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14275 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14276
14277 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14278 "qXfer:features:read", "target-features", 0);
14279
14280 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14281 "qXfer:libraries:read", "library-info", 0);
14282
14283 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14284 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14285
14286 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14287 "qXfer:memory-map:read", "memory-map", 0);
14288
14289 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14290 "qXfer:spu:read", "read-spu-object", 0);
14291
14292 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14293 "qXfer:spu:write", "write-spu-object", 0);
14294
14295 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14296 "qXfer:osdata:read", "osdata", 0);
14297
14298 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14299 "qXfer:threads:read", "threads", 0);
14300
14301 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14302 "qXfer:siginfo:read", "read-siginfo-object", 0);
14303
14304 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14305 "qXfer:siginfo:write", "write-siginfo-object", 0);
14306
14307 add_packet_config_cmd
14308 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14309 "qXfer:traceframe-info:read", "traceframe-info", 0);
14310
14311 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14312 "qXfer:uib:read", "unwind-info-block", 0);
14313
14314 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14315 "qGetTLSAddr", "get-thread-local-storage-address",
14316 0);
14317
14318 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14319 "qGetTIBAddr", "get-thread-information-block-address",
14320 0);
14321
14322 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14323 "bc", "reverse-continue", 0);
14324
14325 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14326 "bs", "reverse-step", 0);
14327
14328 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14329 "qSupported", "supported-packets", 0);
14330
14331 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14332 "qSearch:memory", "search-memory", 0);
14333
14334 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14335 "qTStatus", "trace-status", 0);
14336
14337 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14338 "vFile:setfs", "hostio-setfs", 0);
14339
14340 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14341 "vFile:open", "hostio-open", 0);
14342
14343 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14344 "vFile:pread", "hostio-pread", 0);
14345
14346 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14347 "vFile:pwrite", "hostio-pwrite", 0);
14348
14349 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14350 "vFile:close", "hostio-close", 0);
14351
14352 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14353 "vFile:unlink", "hostio-unlink", 0);
14354
14355 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14356 "vFile:readlink", "hostio-readlink", 0);
14357
14358 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14359 "vFile:fstat", "hostio-fstat", 0);
14360
14361 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14362 "vAttach", "attach", 0);
14363
14364 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14365 "vRun", "run", 0);
14366
14367 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14368 "QStartNoAckMode", "noack", 0);
14369
14370 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14371 "vKill", "kill", 0);
14372
14373 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14374 "qAttached", "query-attached", 0);
14375
14376 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14377 "ConditionalTracepoints",
14378 "conditional-tracepoints", 0);
14379
14380 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14381 "ConditionalBreakpoints",
14382 "conditional-breakpoints", 0);
14383
14384 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14385 "BreakpointCommands",
14386 "breakpoint-commands", 0);
14387
14388 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14389 "FastTracepoints", "fast-tracepoints", 0);
14390
14391 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14392 "TracepointSource", "TracepointSource", 0);
14393
14394 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14395 "QAllow", "allow", 0);
14396
14397 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14398 "StaticTracepoints", "static-tracepoints", 0);
14399
14400 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14401 "InstallInTrace", "install-in-trace", 0);
14402
14403 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14404 "qXfer:statictrace:read", "read-sdata-object", 0);
14405
14406 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14407 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14408
14409 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14410 "QDisableRandomization", "disable-randomization", 0);
14411
14412 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14413 "QAgent", "agent", 0);
14414
14415 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14416 "QTBuffer:size", "trace-buffer-size", 0);
14417
14418 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14419 "Qbtrace:off", "disable-btrace", 0);
14420
14421 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14422 "Qbtrace:bts", "enable-btrace-bts", 0);
14423
14424 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14425 "Qbtrace:pt", "enable-btrace-pt", 0);
14426
14427 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14428 "qXfer:btrace", "read-btrace", 0);
14429
14430 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14431 "qXfer:btrace-conf", "read-btrace-conf", 0);
14432
14433 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14434 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14435
14436 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14437 "multiprocess-feature", "multiprocess-feature", 0);
14438
14439 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14440 "swbreak-feature", "swbreak-feature", 0);
14441
14442 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14443 "hwbreak-feature", "hwbreak-feature", 0);
14444
14445 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14446 "fork-event-feature", "fork-event-feature", 0);
14447
14448 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14449 "vfork-event-feature", "vfork-event-feature", 0);
14450
14451 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14452 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14453
14454 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14455 "vContSupported", "verbose-resume-supported", 0);
14456
14457 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14458 "exec-event-feature", "exec-event-feature", 0);
14459
14460 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14461 "vCtrlC", "ctrl-c", 0);
14462
14463 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14464 "QThreadEvents", "thread-events", 0);
14465
14466 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14467 "N stop reply", "no-resumed-stop-reply", 0);
14468
14469 /* Assert that we've registered "set remote foo-packet" commands
14470 for all packet configs. */
14471 {
14472 int i;
14473
14474 for (i = 0; i < PACKET_MAX; i++)
14475 {
14476 /* Ideally all configs would have a command associated. Some
14477 still don't though. */
14478 int excepted;
14479
14480 switch (i)
14481 {
14482 case PACKET_QNonStop:
14483 case PACKET_EnableDisableTracepoints_feature:
14484 case PACKET_tracenz_feature:
14485 case PACKET_DisconnectedTracing_feature:
14486 case PACKET_augmented_libraries_svr4_read_feature:
14487 case PACKET_qCRC:
14488 /* Additions to this list need to be well justified:
14489 pre-existing packets are OK; new packets are not. */
14490 excepted = 1;
14491 break;
14492 default:
14493 excepted = 0;
14494 break;
14495 }
14496
14497 /* This catches both forgetting to add a config command, and
14498 forgetting to remove a packet from the exception list. */
14499 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14500 }
14501 }
14502
14503 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14504 Z sub-packet has its own set and show commands, but users may
14505 have sets to this variable in their .gdbinit files (or in their
14506 documentation). */
14507 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14508 &remote_Z_packet_detect, _("\
14509 Set use of remote protocol `Z' packets"), _("\
14510 Show use of remote protocol `Z' packets "), _("\
14511 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14512 packets."),
14513 set_remote_protocol_Z_packet_cmd,
14514 show_remote_protocol_Z_packet_cmd,
14515 /* FIXME: i18n: Use of remote protocol
14516 `Z' packets is %s. */
14517 &remote_set_cmdlist, &remote_show_cmdlist);
14518
14519 add_prefix_cmd ("remote", class_files, remote_command, _("\
14520 Manipulate files on the remote system\n\
14521 Transfer files to and from the remote target system."),
14522 &remote_cmdlist, "remote ",
14523 0 /* allow-unknown */, &cmdlist);
14524
14525 add_cmd ("put", class_files, remote_put_command,
14526 _("Copy a local file to the remote system."),
14527 &remote_cmdlist);
14528
14529 add_cmd ("get", class_files, remote_get_command,
14530 _("Copy a remote file to the local system."),
14531 &remote_cmdlist);
14532
14533 add_cmd ("delete", class_files, remote_delete_command,
14534 _("Delete a remote file."),
14535 &remote_cmdlist);
14536
14537 add_setshow_string_noescape_cmd ("exec-file", class_files,
14538 &remote_exec_file_var, _("\
14539 Set the remote pathname for \"run\""), _("\
14540 Show the remote pathname for \"run\""), NULL,
14541 set_remote_exec_file,
14542 show_remote_exec_file,
14543 &remote_set_cmdlist,
14544 &remote_show_cmdlist);
14545
14546 add_setshow_boolean_cmd ("range-stepping", class_run,
14547 &use_range_stepping, _("\
14548 Enable or disable range stepping."), _("\
14549 Show whether target-assisted range stepping is enabled."), _("\
14550 If on, and the target supports it, when stepping a source line, GDB\n\
14551 tells the target to step the corresponding range of addresses itself instead\n\
14552 of issuing multiple single-steps. This speeds up source level\n\
14553 stepping. If off, GDB always issues single-steps, even if range\n\
14554 stepping is supported by the target. The default is on."),
14555 set_range_stepping,
14556 show_range_stepping,
14557 &setlist,
14558 &showlist);
14559
14560 /* Eventually initialize fileio. See fileio.c */
14561 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14562
14563 /* Take advantage of the fact that the TID field is not used, to tag
14564 special ptids with it set to != 0. */
14565 magic_null_ptid = ptid_build (42000, -1, 1);
14566 not_sent_ptid = ptid_build (42000, -2, 1);
14567 any_thread_ptid = ptid_build (42000, 0, 1);
14568 }
This page took 0.360189 seconds and 4 git commands to generate.