Convert struct target_ops to C++
[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
79 /* The remote target. */
80
81 class remote_target : public target_ops
82 {
83 public:
84 remote_target ()
85 {
86 to_stratum = process_stratum;
87 }
88
89 const char *shortname () override
90 { return "remote"; }
91
92 const char *longname () override
93 { return _("Remote serial target in gdb-specific protocol"); }
94
95 const char *doc () override
96 {
97 return _("\
98 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
99 Specify the serial device it is connected to\n\
100 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
101 }
102
103 thread_control_capabilities get_thread_control_capabilities () override
104 { return tc_schedlock; }
105
106 void open (const char *, int) override;
107 void close () override;
108
109 void detach (inferior *, int) override;
110 void disconnect (const char *, int) override;
111
112 void commit_resume () override;
113 void resume (ptid_t, int, enum gdb_signal) override;
114 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
115
116 void fetch_registers (struct regcache *, int) override;
117 void store_registers (struct regcache *, int) override;
118 void prepare_to_store (struct regcache *) override;
119
120 void files_info () override;
121
122 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
123
124 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
125 enum remove_bp_reason) override;
126
127
128 int stopped_by_sw_breakpoint () override;
129 int supports_stopped_by_sw_breakpoint () override;
130
131 int stopped_by_hw_breakpoint () override;
132
133 int supports_stopped_by_hw_breakpoint () override;
134
135 int stopped_by_watchpoint () override;
136
137 int stopped_data_address (CORE_ADDR *) override;
138
139 int watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
140
141 int can_use_hw_breakpoint (enum bptype, int, int) override;
142
143 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
144
145 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
146
147 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
148
149 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
150 struct expression *) override;
151
152 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
153 struct expression *) override;
154
155 void kill () override;
156
157 void load (const char *, int) override;
158
159 void mourn_inferior () override;
160
161 void pass_signals (int, unsigned char *) override;
162
163 int set_syscall_catchpoint (int, bool, int,
164 gdb::array_view<const int>) override;
165
166 void program_signals (int, unsigned char *) override;
167
168 int thread_alive (ptid_t ptid) override;
169
170 const char *thread_name (struct thread_info *) override;
171
172 void update_thread_list () override;
173
174 const char *pid_to_str (ptid_t) override;
175
176 const char *extra_thread_info (struct thread_info *) override;
177
178 ptid_t get_ada_task_ptid (long lwp, long thread) override;
179
180 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
181 int handle_len,
182 inferior *inf) override;
183
184 void stop (ptid_t) override;
185
186 void interrupt () override;
187
188 void pass_ctrlc () override;
189
190 enum target_xfer_status xfer_partial (enum target_object object,
191 const char *annex,
192 gdb_byte *readbuf,
193 const gdb_byte *writebuf,
194 ULONGEST offset, ULONGEST len,
195 ULONGEST *xfered_len) override;
196
197 ULONGEST get_memory_xfer_limit () override;
198
199 void rcmd (const char *command, struct ui_file *output) override;
200
201 char *pid_to_exec_file (int pid) override;
202
203 void log_command (const char *cmd) override
204 {
205 serial_log_command (this, cmd);
206 }
207
208 CORE_ADDR get_thread_local_address (ptid_t ptid,
209 CORE_ADDR load_module_addr,
210 CORE_ADDR offset) override;
211
212 int has_all_memory () override { return default_child_has_all_memory (); }
213 int has_memory () override { return default_child_has_memory (); }
214 int has_stack () override { return default_child_has_stack (); }
215 int has_registers () override { return default_child_has_registers (); }
216 int has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
217
218 int can_execute_reverse () override;
219
220 std::vector<mem_region> memory_map () override;
221
222 void flash_erase (ULONGEST address, LONGEST length) override;
223
224 void flash_done () override;
225
226 const struct target_desc *read_description () override;
227
228 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
229 const gdb_byte *pattern, ULONGEST pattern_len,
230 CORE_ADDR *found_addrp) override;
231
232 int can_async_p () override;
233
234 int is_async_p () override;
235
236 void async (int) override;
237
238 void thread_events (int) override;
239
240 int can_do_single_step () override;
241
242 void terminal_inferior () override;
243
244 void terminal_ours () override;
245
246 int supports_non_stop () override;
247
248 int supports_multi_process () override;
249
250 int supports_disable_randomization () override;
251
252 int filesystem_is_local () override;
253
254
255 int fileio_open (struct inferior *inf, const char *filename,
256 int flags, int mode, int warn_if_slow,
257 int *target_errno) override;
258
259 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
260 ULONGEST offset, int *target_errno) override;
261
262 int fileio_pread (int fd, gdb_byte *read_buf, int len,
263 ULONGEST offset, int *target_errno) override;
264
265 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
266
267 int fileio_close (int fd, int *target_errno) override;
268
269 int fileio_unlink (struct inferior *inf,
270 const char *filename,
271 int *target_errno) override;
272
273 gdb::optional<std::string>
274 fileio_readlink (struct inferior *inf,
275 const char *filename,
276 int *target_errno) override;
277
278 int supports_enable_disable_tracepoint () override;
279
280 int supports_string_tracing () override;
281
282 int supports_evaluation_of_breakpoint_conditions () override;
283
284 int can_run_breakpoint_commands () override;
285
286 void trace_init () override;
287
288 void download_tracepoint (struct bp_location *location) override;
289
290 int can_download_tracepoint () override;
291
292 void download_trace_state_variable (const trace_state_variable &tsv) override;
293
294 void enable_tracepoint (struct bp_location *location) override;
295
296 void disable_tracepoint (struct bp_location *location) override;
297
298 void trace_set_readonly_regions () override;
299
300 void trace_start () override;
301
302 int get_trace_status (struct trace_status *ts) override;
303
304 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
305 override;
306
307 void trace_stop () override;
308
309 int trace_find (enum trace_find_type type, int num,
310 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
311
312 int get_trace_state_variable_value (int tsv, LONGEST *val) override;
313
314 int save_trace_data (const char *filename) override;
315
316 int upload_tracepoints (struct uploaded_tp **utpp) override;
317
318 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
319
320 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
321
322 int get_min_fast_tracepoint_insn_len () override;
323
324 void set_disconnected_tracing (int val) override;
325
326 void set_circular_trace_buffer (int val) override;
327
328 void set_trace_buffer_size (LONGEST val) override;
329
330 int set_trace_notes (const char *user, const char *notes,
331 const char *stopnotes) override;
332
333 int core_of_thread (ptid_t ptid) override;
334
335 int verify_memory (const gdb_byte *data,
336 CORE_ADDR memaddr, ULONGEST size) override;
337
338
339 int get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
340
341 void set_permissions () override;
342
343 bool static_tracepoint_marker_at (CORE_ADDR,
344 struct static_tracepoint_marker *marker)
345 override;
346
347 std::vector<static_tracepoint_marker>
348 static_tracepoint_markers_by_strid (const char *id) override;
349
350 traceframe_info_up traceframe_info () override;
351
352 int use_agent (int use) override;
353 int can_use_agent () override;
354
355 struct btrace_target_info *enable_btrace (ptid_t ptid,
356 const struct btrace_config *conf) override;
357
358 void disable_btrace (struct btrace_target_info *tinfo) override;
359
360 void teardown_btrace (struct btrace_target_info *tinfo) override;
361
362 enum btrace_error read_btrace (struct btrace_data *data,
363 struct btrace_target_info *btinfo,
364 enum btrace_read_type type) override;
365
366 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
367 int augmented_libraries_svr4_read () override;
368 int follow_fork (int, int) override;
369 void follow_exec (struct inferior *, char *) override;
370 int insert_fork_catchpoint (int) override;
371 int remove_fork_catchpoint (int) override;
372 int insert_vfork_catchpoint (int) override;
373 int remove_vfork_catchpoint (int) override;
374 int insert_exec_catchpoint (int) override;
375 int remove_exec_catchpoint (int) override;
376 enum exec_direction_kind execution_direction () override;
377
378 protected:
379 void open_1 (const char *name, int from_tty, int extended_p);
380 void start_remote (int from_tty, int extended_p);
381 };
382
383 /* Set up the extended remote target by extending the standard remote
384 target and adding to it. */
385
386 class extended_remote_target final : public remote_target
387 {
388 public:
389 const char *shortname () override
390 { return "extended-remote"; }
391
392 const char *longname () override
393 { return _("Extended remote serial target in gdb-specific protocol"); }
394
395 void open (const char *, int) override;
396
397 bool can_create_inferior () override { return true; }
398 void create_inferior (const char *, const std::string &,
399 char **, int) override;
400
401 void detach (inferior *, int) override;
402
403 bool can_attach () override { return true; }
404 void attach (const char *, int) override;
405
406 void post_attach (int) override;
407 int supports_disable_randomization () override;
408 };
409
410 /* Per-program-space data key. */
411 static const struct program_space_data *remote_pspace_data;
412
413 /* The variable registered as the control variable used by the
414 remote exec-file commands. While the remote exec-file setting is
415 per-program-space, the set/show machinery uses this as the
416 location of the remote exec-file value. */
417 static char *remote_exec_file_var;
418
419 /* The size to align memory write packets, when practical. The protocol
420 does not guarantee any alignment, and gdb will generate short
421 writes and unaligned writes, but even as a best-effort attempt this
422 can improve bulk transfers. For instance, if a write is misaligned
423 relative to the target's data bus, the stub may need to make an extra
424 round trip fetching data from the target. This doesn't make a
425 huge difference, but it's easy to do, so we try to be helpful.
426
427 The alignment chosen is arbitrary; usually data bus width is
428 important here, not the possibly larger cache line size. */
429 enum { REMOTE_ALIGN_WRITES = 16 };
430
431 /* Prototypes for local functions. */
432 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
433 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
434 int forever, int *is_notif);
435
436 struct remote_state;
437
438 static int remote_vkill (int pid, struct remote_state *rs);
439
440 static void remote_kill_k (void);
441
442 static int readchar (int timeout);
443
444 static void remote_serial_write (const char *str, int len);
445
446 static void interrupt_query (void);
447
448 static void set_general_thread (ptid_t ptid);
449 static void set_continue_thread (ptid_t ptid);
450
451 static void get_offsets (void);
452
453 static void skip_frame (void);
454
455 static long read_frame (char **buf_p, long *sizeof_buf);
456
457 static int hexnumlen (ULONGEST num);
458
459 static int stubhex (int ch);
460
461 static int hexnumstr (char *, ULONGEST);
462
463 static int hexnumnstr (char *, ULONGEST, int);
464
465 static CORE_ADDR remote_address_masked (CORE_ADDR);
466
467 static void print_packet (const char *);
468
469 static int stub_unpack_int (char *buff, int fieldlength);
470
471 static ptid_t remote_current_thread (ptid_t oldptid);
472
473 static int putpkt_binary (const char *buf, int cnt);
474
475 static void check_binary_download (CORE_ADDR addr);
476
477 struct packet_config;
478
479 static void show_packet_config_cmd (struct packet_config *config);
480
481 static void show_remote_protocol_packet_cmd (struct ui_file *file,
482 int from_tty,
483 struct cmd_list_element *c,
484 const char *value);
485
486 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
487 static ptid_t read_ptid (const char *buf, const char **obuf);
488
489 static void remote_query_supported (void);
490
491 static void remote_check_symbols (void);
492
493 struct stop_reply;
494 static void stop_reply_xfree (struct stop_reply *);
495 static void remote_parse_stop_reply (char *, struct stop_reply *);
496 static void push_stop_reply (struct stop_reply *);
497 static void discard_pending_stop_replies_in_queue (struct remote_state *);
498 static int peek_stop_reply (ptid_t ptid);
499
500 struct threads_listing_context;
501 static void remove_new_fork_children (struct threads_listing_context *);
502
503 static void remote_async_inferior_event_handler (gdb_client_data);
504
505 static int remote_read_description_p (struct target_ops *target);
506
507 static void remote_console_output (char *msg);
508
509 static void remote_btrace_reset (void);
510
511 static void remote_btrace_maybe_reopen (void);
512
513 static int stop_reply_queue_length (void);
514
515 static void readahead_cache_invalidate (void);
516
517 static void remote_unpush_and_throw (void);
518
519 static struct remote_state *get_remote_state (void);
520
521 /* For "remote". */
522
523 static struct cmd_list_element *remote_cmdlist;
524
525 /* For "set remote" and "show remote". */
526
527 static struct cmd_list_element *remote_set_cmdlist;
528 static struct cmd_list_element *remote_show_cmdlist;
529
530 /* Stub vCont actions support.
531
532 Each field is a boolean flag indicating whether the stub reports
533 support for the corresponding action. */
534
535 struct vCont_action_support
536 {
537 /* vCont;t */
538 int t;
539
540 /* vCont;r */
541 int r;
542
543 /* vCont;s */
544 int s;
545
546 /* vCont;S */
547 int S;
548 };
549
550 /* Controls whether GDB is willing to use range stepping. */
551
552 static int use_range_stepping = 1;
553
554 #define OPAQUETHREADBYTES 8
555
556 /* a 64 bit opaque identifier */
557 typedef unsigned char threadref[OPAQUETHREADBYTES];
558
559 /* About this many threadisds fit in a packet. */
560
561 #define MAXTHREADLISTRESULTS 32
562
563 /* The max number of chars in debug output. The rest of chars are
564 omitted. */
565
566 #define REMOTE_DEBUG_MAX_CHAR 512
567
568 /* Data for the vFile:pread readahead cache. */
569
570 struct readahead_cache
571 {
572 /* The file descriptor for the file that is being cached. -1 if the
573 cache is invalid. */
574 int fd;
575
576 /* The offset into the file that the cache buffer corresponds
577 to. */
578 ULONGEST offset;
579
580 /* The buffer holding the cache contents. */
581 gdb_byte *buf;
582 /* The buffer's size. We try to read as much as fits into a packet
583 at a time. */
584 size_t bufsize;
585
586 /* Cache hit and miss counters. */
587 ULONGEST hit_count;
588 ULONGEST miss_count;
589 };
590
591 /* Description of the remote protocol state for the currently
592 connected target. This is per-target state, and independent of the
593 selected architecture. */
594
595 struct remote_state
596 {
597 /* A buffer to use for incoming packets, and its current size. The
598 buffer is grown dynamically for larger incoming packets.
599 Outgoing packets may also be constructed in this buffer.
600 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
601 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
602 packets. */
603 char *buf;
604 long buf_size;
605
606 /* True if we're going through initial connection setup (finding out
607 about the remote side's threads, relocating symbols, etc.). */
608 int starting_up;
609
610 /* If we negotiated packet size explicitly (and thus can bypass
611 heuristics for the largest packet size that will not overflow
612 a buffer in the stub), this will be set to that packet size.
613 Otherwise zero, meaning to use the guessed size. */
614 long explicit_packet_size;
615
616 /* remote_wait is normally called when the target is running and
617 waits for a stop reply packet. But sometimes we need to call it
618 when the target is already stopped. We can send a "?" packet
619 and have remote_wait read the response. Or, if we already have
620 the response, we can stash it in BUF and tell remote_wait to
621 skip calling getpkt. This flag is set when BUF contains a
622 stop reply packet and the target is not waiting. */
623 int cached_wait_status;
624
625 /* True, if in no ack mode. That is, neither GDB nor the stub will
626 expect acks from each other. The connection is assumed to be
627 reliable. */
628 int noack_mode;
629
630 /* True if we're connected in extended remote mode. */
631 int extended;
632
633 /* True if we resumed the target and we're waiting for the target to
634 stop. In the mean time, we can't start another command/query.
635 The remote server wouldn't be ready to process it, so we'd
636 timeout waiting for a reply that would never come and eventually
637 we'd close the connection. This can happen in asynchronous mode
638 because we allow GDB commands while the target is running. */
639 int waiting_for_stop_reply;
640
641 /* The status of the stub support for the various vCont actions. */
642 struct vCont_action_support supports_vCont;
643
644 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
645 responded to that. */
646 int ctrlc_pending_p;
647
648 /* True if we saw a Ctrl-C while reading or writing from/to the
649 remote descriptor. At that point it is not safe to send a remote
650 interrupt packet, so we instead remember we saw the Ctrl-C and
651 process it once we're done with sending/receiving the current
652 packet, which should be shortly. If however that takes too long,
653 and the user presses Ctrl-C again, we offer to disconnect. */
654 int got_ctrlc_during_io;
655
656 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
657 remote_open knows that we don't have a file open when the program
658 starts. */
659 struct serial *remote_desc;
660
661 /* These are the threads which we last sent to the remote system. The
662 TID member will be -1 for all or -2 for not sent yet. */
663 ptid_t general_thread;
664 ptid_t continue_thread;
665
666 /* This is the traceframe which we last selected on the remote system.
667 It will be -1 if no traceframe is selected. */
668 int remote_traceframe_number;
669
670 char *last_pass_packet;
671
672 /* The last QProgramSignals packet sent to the target. We bypass
673 sending a new program signals list down to the target if the new
674 packet is exactly the same as the last we sent. IOW, we only let
675 the target know about program signals list changes. */
676 char *last_program_signals_packet;
677
678 enum gdb_signal last_sent_signal;
679
680 int last_sent_step;
681
682 /* The execution direction of the last resume we got. */
683 enum exec_direction_kind last_resume_exec_dir;
684
685 char *finished_object;
686 char *finished_annex;
687 ULONGEST finished_offset;
688
689 /* Should we try the 'ThreadInfo' query packet?
690
691 This variable (NOT available to the user: auto-detect only!)
692 determines whether GDB will use the new, simpler "ThreadInfo"
693 query or the older, more complex syntax for thread queries.
694 This is an auto-detect variable (set to true at each connect,
695 and set to false when the target fails to recognize it). */
696 int use_threadinfo_query;
697 int use_threadextra_query;
698
699 threadref echo_nextthread;
700 threadref nextthread;
701 threadref resultthreadlist[MAXTHREADLISTRESULTS];
702
703 /* The state of remote notification. */
704 struct remote_notif_state *notif_state;
705
706 /* The branch trace configuration. */
707 struct btrace_config btrace_config;
708
709 /* The argument to the last "vFile:setfs:" packet we sent, used
710 to avoid sending repeated unnecessary "vFile:setfs:" packets.
711 Initialized to -1 to indicate that no "vFile:setfs:" packet
712 has yet been sent. */
713 int fs_pid;
714
715 /* A readahead cache for vFile:pread. Often, reading a binary
716 involves a sequence of small reads. E.g., when parsing an ELF
717 file. A readahead cache helps mostly the case of remote
718 debugging on a connection with higher latency, due to the
719 request/reply nature of the RSP. We only cache data for a single
720 file descriptor at a time. */
721 struct readahead_cache readahead_cache;
722 };
723
724 /* Private data that we'll store in (struct thread_info)->priv. */
725 struct remote_thread_info : public private_thread_info
726 {
727 std::string extra;
728 std::string name;
729 int core = -1;
730
731 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
732 sequence of bytes. */
733 gdb::byte_vector thread_handle;
734
735 /* Whether the target stopped for a breakpoint/watchpoint. */
736 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
737
738 /* This is set to the data address of the access causing the target
739 to stop for a watchpoint. */
740 CORE_ADDR watch_data_address = 0;
741
742 /* Fields used by the vCont action coalescing implemented in
743 remote_resume / remote_commit_resume. remote_resume stores each
744 thread's last resume request in these fields, so that a later
745 remote_commit_resume knows which is the proper action for this
746 thread to include in the vCont packet. */
747
748 /* True if the last target_resume call for this thread was a step
749 request, false if a continue request. */
750 int last_resume_step = 0;
751
752 /* The signal specified in the last target_resume call for this
753 thread. */
754 gdb_signal last_resume_sig = GDB_SIGNAL_0;
755
756 /* Whether this thread was already vCont-resumed on the remote
757 side. */
758 int vcont_resumed = 0;
759 };
760
761 /* This data could be associated with a target, but we do not always
762 have access to the current target when we need it, so for now it is
763 static. This will be fine for as long as only one target is in use
764 at a time. */
765 static struct remote_state *remote_state;
766
767 static struct remote_state *
768 get_remote_state_raw (void)
769 {
770 return remote_state;
771 }
772
773 /* Allocate a new struct remote_state with xmalloc, initialize it, and
774 return it. */
775
776 static struct remote_state *
777 new_remote_state (void)
778 {
779 struct remote_state *result = XCNEW (struct remote_state);
780
781 /* The default buffer size is unimportant; it will be expanded
782 whenever a larger buffer is needed. */
783 result->buf_size = 400;
784 result->buf = (char *) xmalloc (result->buf_size);
785 result->remote_traceframe_number = -1;
786 result->last_sent_signal = GDB_SIGNAL_0;
787 result->last_resume_exec_dir = EXEC_FORWARD;
788 result->fs_pid = -1;
789
790 return result;
791 }
792
793 /* Description of the remote protocol for a given architecture. */
794
795 struct packet_reg
796 {
797 long offset; /* Offset into G packet. */
798 long regnum; /* GDB's internal register number. */
799 LONGEST pnum; /* Remote protocol register number. */
800 int in_g_packet; /* Always part of G packet. */
801 /* long size in bytes; == register_size (target_gdbarch (), regnum);
802 at present. */
803 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
804 at present. */
805 };
806
807 struct remote_arch_state
808 {
809 /* Description of the remote protocol registers. */
810 long sizeof_g_packet;
811
812 /* Description of the remote protocol registers indexed by REGNUM
813 (making an array gdbarch_num_regs in size). */
814 struct packet_reg *regs;
815
816 /* This is the size (in chars) of the first response to the ``g''
817 packet. It is used as a heuristic when determining the maximum
818 size of memory-read and memory-write packets. A target will
819 typically only reserve a buffer large enough to hold the ``g''
820 packet. The size does not include packet overhead (headers and
821 trailers). */
822 long actual_register_packet_size;
823
824 /* This is the maximum size (in chars) of a non read/write packet.
825 It is also used as a cap on the size of read/write packets. */
826 long remote_packet_size;
827 };
828
829 /* Utility: generate error from an incoming stub packet. */
830 static void
831 trace_error (char *buf)
832 {
833 if (*buf++ != 'E')
834 return; /* not an error msg */
835 switch (*buf)
836 {
837 case '1': /* malformed packet error */
838 if (*++buf == '0') /* general case: */
839 error (_("remote.c: error in outgoing packet."));
840 else
841 error (_("remote.c: error in outgoing packet at field #%ld."),
842 strtol (buf, NULL, 16));
843 default:
844 error (_("Target returns error code '%s'."), buf);
845 }
846 }
847
848 /* Utility: wait for reply from stub, while accepting "O" packets. */
849
850 static char *
851 remote_get_noisy_reply ()
852 {
853 struct remote_state *rs = get_remote_state ();
854
855 do /* Loop on reply from remote stub. */
856 {
857 char *buf;
858
859 QUIT; /* Allow user to bail out with ^C. */
860 getpkt (&rs->buf, &rs->buf_size, 0);
861 buf = rs->buf;
862 if (buf[0] == 'E')
863 trace_error (buf);
864 else if (startswith (buf, "qRelocInsn:"))
865 {
866 ULONGEST ul;
867 CORE_ADDR from, to, org_to;
868 const char *p, *pp;
869 int adjusted_size = 0;
870 int relocated = 0;
871
872 p = buf + strlen ("qRelocInsn:");
873 pp = unpack_varlen_hex (p, &ul);
874 if (*pp != ';')
875 error (_("invalid qRelocInsn packet: %s"), buf);
876 from = ul;
877
878 p = pp + 1;
879 unpack_varlen_hex (p, &ul);
880 to = ul;
881
882 org_to = to;
883
884 TRY
885 {
886 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
887 relocated = 1;
888 }
889 CATCH (ex, RETURN_MASK_ALL)
890 {
891 if (ex.error == MEMORY_ERROR)
892 {
893 /* Propagate memory errors silently back to the
894 target. The stub may have limited the range of
895 addresses we can write to, for example. */
896 }
897 else
898 {
899 /* Something unexpectedly bad happened. Be verbose
900 so we can tell what, and propagate the error back
901 to the stub, so it doesn't get stuck waiting for
902 a response. */
903 exception_fprintf (gdb_stderr, ex,
904 _("warning: relocating instruction: "));
905 }
906 putpkt ("E01");
907 }
908 END_CATCH
909
910 if (relocated)
911 {
912 adjusted_size = to - org_to;
913
914 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
915 putpkt (buf);
916 }
917 }
918 else if (buf[0] == 'O' && buf[1] != 'K')
919 remote_console_output (buf + 1); /* 'O' message from stub */
920 else
921 return buf; /* Here's the actual reply. */
922 }
923 while (1);
924 }
925
926 /* Handle for retreving the remote protocol data from gdbarch. */
927 static struct gdbarch_data *remote_gdbarch_data_handle;
928
929 static struct remote_arch_state *
930 get_remote_arch_state (struct gdbarch *gdbarch)
931 {
932 gdb_assert (gdbarch != NULL);
933 return ((struct remote_arch_state *)
934 gdbarch_data (gdbarch, remote_gdbarch_data_handle));
935 }
936
937 /* Fetch the global remote target state. */
938
939 static struct remote_state *
940 get_remote_state (void)
941 {
942 /* Make sure that the remote architecture state has been
943 initialized, because doing so might reallocate rs->buf. Any
944 function which calls getpkt also needs to be mindful of changes
945 to rs->buf, but this call limits the number of places which run
946 into trouble. */
947 get_remote_arch_state (target_gdbarch ());
948
949 return get_remote_state_raw ();
950 }
951
952 /* Cleanup routine for the remote module's pspace data. */
953
954 static void
955 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
956 {
957 char *remote_exec_file = (char *) arg;
958
959 xfree (remote_exec_file);
960 }
961
962 /* Fetch the remote exec-file from the current program space. */
963
964 static const char *
965 get_remote_exec_file (void)
966 {
967 char *remote_exec_file;
968
969 remote_exec_file
970 = (char *) program_space_data (current_program_space,
971 remote_pspace_data);
972 if (remote_exec_file == NULL)
973 return "";
974
975 return remote_exec_file;
976 }
977
978 /* Set the remote exec file for PSPACE. */
979
980 static void
981 set_pspace_remote_exec_file (struct program_space *pspace,
982 char *remote_exec_file)
983 {
984 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
985
986 xfree (old_file);
987 set_program_space_data (pspace, remote_pspace_data,
988 xstrdup (remote_exec_file));
989 }
990
991 /* The "set/show remote exec-file" set command hook. */
992
993 static void
994 set_remote_exec_file (const char *ignored, int from_tty,
995 struct cmd_list_element *c)
996 {
997 gdb_assert (remote_exec_file_var != NULL);
998 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
999 }
1000
1001 /* The "set/show remote exec-file" show command hook. */
1002
1003 static void
1004 show_remote_exec_file (struct ui_file *file, int from_tty,
1005 struct cmd_list_element *cmd, const char *value)
1006 {
1007 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1008 }
1009
1010 static int
1011 compare_pnums (const void *lhs_, const void *rhs_)
1012 {
1013 const struct packet_reg * const *lhs
1014 = (const struct packet_reg * const *) lhs_;
1015 const struct packet_reg * const *rhs
1016 = (const struct packet_reg * const *) rhs_;
1017
1018 if ((*lhs)->pnum < (*rhs)->pnum)
1019 return -1;
1020 else if ((*lhs)->pnum == (*rhs)->pnum)
1021 return 0;
1022 else
1023 return 1;
1024 }
1025
1026 static int
1027 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1028 {
1029 int regnum, num_remote_regs, offset;
1030 struct packet_reg **remote_regs;
1031
1032 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1033 {
1034 struct packet_reg *r = &regs[regnum];
1035
1036 if (register_size (gdbarch, regnum) == 0)
1037 /* Do not try to fetch zero-sized (placeholder) registers. */
1038 r->pnum = -1;
1039 else
1040 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1041
1042 r->regnum = regnum;
1043 }
1044
1045 /* Define the g/G packet format as the contents of each register
1046 with a remote protocol number, in order of ascending protocol
1047 number. */
1048
1049 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1050 for (num_remote_regs = 0, regnum = 0;
1051 regnum < gdbarch_num_regs (gdbarch);
1052 regnum++)
1053 if (regs[regnum].pnum != -1)
1054 remote_regs[num_remote_regs++] = &regs[regnum];
1055
1056 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1057 compare_pnums);
1058
1059 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1060 {
1061 remote_regs[regnum]->in_g_packet = 1;
1062 remote_regs[regnum]->offset = offset;
1063 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1064 }
1065
1066 return offset;
1067 }
1068
1069 /* Given the architecture described by GDBARCH, return the remote
1070 protocol register's number and the register's offset in the g/G
1071 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1072 If the target does not have a mapping for REGNUM, return false,
1073 otherwise, return true. */
1074
1075 int
1076 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1077 int *pnum, int *poffset)
1078 {
1079 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1080
1081 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1082
1083 map_regcache_remote_table (gdbarch, regs.data ());
1084
1085 *pnum = regs[regnum].pnum;
1086 *poffset = regs[regnum].offset;
1087
1088 return *pnum != -1;
1089 }
1090
1091 static void *
1092 init_remote_state (struct gdbarch *gdbarch)
1093 {
1094 struct remote_state *rs = get_remote_state_raw ();
1095 struct remote_arch_state *rsa;
1096
1097 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
1098
1099 /* Use the architecture to build a regnum<->pnum table, which will be
1100 1:1 unless a feature set specifies otherwise. */
1101 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
1102 gdbarch_num_regs (gdbarch),
1103 struct packet_reg);
1104
1105 /* Record the maximum possible size of the g packet - it may turn out
1106 to be smaller. */
1107 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
1108
1109 /* Default maximum number of characters in a packet body. Many
1110 remote stubs have a hardwired buffer size of 400 bytes
1111 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1112 as the maximum packet-size to ensure that the packet and an extra
1113 NUL character can always fit in the buffer. This stops GDB
1114 trashing stubs that try to squeeze an extra NUL into what is
1115 already a full buffer (As of 1999-12-04 that was most stubs). */
1116 rsa->remote_packet_size = 400 - 1;
1117
1118 /* This one is filled in when a ``g'' packet is received. */
1119 rsa->actual_register_packet_size = 0;
1120
1121 /* Should rsa->sizeof_g_packet needs more space than the
1122 default, adjust the size accordingly. Remember that each byte is
1123 encoded as two characters. 32 is the overhead for the packet
1124 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1125 (``$NN:G...#NN'') is a better guess, the below has been padded a
1126 little. */
1127 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
1128 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
1129
1130 /* Make sure that the packet buffer is plenty big enough for
1131 this architecture. */
1132 if (rs->buf_size < rsa->remote_packet_size)
1133 {
1134 rs->buf_size = 2 * rsa->remote_packet_size;
1135 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
1136 }
1137
1138 return rsa;
1139 }
1140
1141 /* Return the current allowed size of a remote packet. This is
1142 inferred from the current architecture, and should be used to
1143 limit the length of outgoing packets. */
1144 static long
1145 get_remote_packet_size (void)
1146 {
1147 struct remote_state *rs = get_remote_state ();
1148 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1149
1150 if (rs->explicit_packet_size)
1151 return rs->explicit_packet_size;
1152
1153 return rsa->remote_packet_size;
1154 }
1155
1156 static struct packet_reg *
1157 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1158 long regnum)
1159 {
1160 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1161 return NULL;
1162 else
1163 {
1164 struct packet_reg *r = &rsa->regs[regnum];
1165
1166 gdb_assert (r->regnum == regnum);
1167 return r;
1168 }
1169 }
1170
1171 static struct packet_reg *
1172 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1173 LONGEST pnum)
1174 {
1175 int i;
1176
1177 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1178 {
1179 struct packet_reg *r = &rsa->regs[i];
1180
1181 if (r->pnum == pnum)
1182 return r;
1183 }
1184 return NULL;
1185 }
1186
1187 static remote_target remote_ops;
1188
1189 static extended_remote_target extended_remote_ops;
1190
1191 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
1192 ``forever'' still use the normal timeout mechanism. This is
1193 currently used by the ASYNC code to guarentee that target reads
1194 during the initial connect always time-out. Once getpkt has been
1195 modified to return a timeout indication and, in turn
1196 remote_wait()/wait_for_inferior() have gained a timeout parameter
1197 this can go away. */
1198 static int wait_forever_enabled_p = 1;
1199
1200 /* Allow the user to specify what sequence to send to the remote
1201 when he requests a program interruption: Although ^C is usually
1202 what remote systems expect (this is the default, here), it is
1203 sometimes preferable to send a break. On other systems such
1204 as the Linux kernel, a break followed by g, which is Magic SysRq g
1205 is required in order to interrupt the execution. */
1206 const char interrupt_sequence_control_c[] = "Ctrl-C";
1207 const char interrupt_sequence_break[] = "BREAK";
1208 const char interrupt_sequence_break_g[] = "BREAK-g";
1209 static const char *const interrupt_sequence_modes[] =
1210 {
1211 interrupt_sequence_control_c,
1212 interrupt_sequence_break,
1213 interrupt_sequence_break_g,
1214 NULL
1215 };
1216 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1217
1218 static void
1219 show_interrupt_sequence (struct ui_file *file, int from_tty,
1220 struct cmd_list_element *c,
1221 const char *value)
1222 {
1223 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1224 fprintf_filtered (file,
1225 _("Send the ASCII ETX character (Ctrl-c) "
1226 "to the remote target to interrupt the "
1227 "execution of the program.\n"));
1228 else if (interrupt_sequence_mode == interrupt_sequence_break)
1229 fprintf_filtered (file,
1230 _("send a break signal to the remote target "
1231 "to interrupt the execution of the program.\n"));
1232 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1233 fprintf_filtered (file,
1234 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1235 "the remote target to interrupt the execution "
1236 "of Linux kernel.\n"));
1237 else
1238 internal_error (__FILE__, __LINE__,
1239 _("Invalid value for interrupt_sequence_mode: %s."),
1240 interrupt_sequence_mode);
1241 }
1242
1243 /* This boolean variable specifies whether interrupt_sequence is sent
1244 to the remote target when gdb connects to it.
1245 This is mostly needed when you debug the Linux kernel: The Linux kernel
1246 expects BREAK g which is Magic SysRq g for connecting gdb. */
1247 static int interrupt_on_connect = 0;
1248
1249 /* This variable is used to implement the "set/show remotebreak" commands.
1250 Since these commands are now deprecated in favor of "set/show remote
1251 interrupt-sequence", it no longer has any effect on the code. */
1252 static int remote_break;
1253
1254 static void
1255 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1256 {
1257 if (remote_break)
1258 interrupt_sequence_mode = interrupt_sequence_break;
1259 else
1260 interrupt_sequence_mode = interrupt_sequence_control_c;
1261 }
1262
1263 static void
1264 show_remotebreak (struct ui_file *file, int from_tty,
1265 struct cmd_list_element *c,
1266 const char *value)
1267 {
1268 }
1269
1270 /* This variable sets the number of bits in an address that are to be
1271 sent in a memory ("M" or "m") packet. Normally, after stripping
1272 leading zeros, the entire address would be sent. This variable
1273 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1274 initial implementation of remote.c restricted the address sent in
1275 memory packets to ``host::sizeof long'' bytes - (typically 32
1276 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1277 address was never sent. Since fixing this bug may cause a break in
1278 some remote targets this variable is principly provided to
1279 facilitate backward compatibility. */
1280
1281 static unsigned int remote_address_size;
1282
1283 \f
1284 /* User configurable variables for the number of characters in a
1285 memory read/write packet. MIN (rsa->remote_packet_size,
1286 rsa->sizeof_g_packet) is the default. Some targets need smaller
1287 values (fifo overruns, et.al.) and some users need larger values
1288 (speed up transfers). The variables ``preferred_*'' (the user
1289 request), ``current_*'' (what was actually set) and ``forced_*''
1290 (Positive - a soft limit, negative - a hard limit). */
1291
1292 struct memory_packet_config
1293 {
1294 const char *name;
1295 long size;
1296 int fixed_p;
1297 };
1298
1299 /* The default max memory-write-packet-size. The 16k is historical.
1300 (It came from older GDB's using alloca for buffers and the
1301 knowledge (folklore?) that some hosts don't cope very well with
1302 large alloca calls.) */
1303 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1304
1305 /* The minimum remote packet size for memory transfers. Ensures we
1306 can write at least one byte. */
1307 #define MIN_MEMORY_PACKET_SIZE 20
1308
1309 /* Compute the current size of a read/write packet. Since this makes
1310 use of ``actual_register_packet_size'' the computation is dynamic. */
1311
1312 static long
1313 get_memory_packet_size (struct memory_packet_config *config)
1314 {
1315 struct remote_state *rs = get_remote_state ();
1316 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1317
1318 long what_they_get;
1319 if (config->fixed_p)
1320 {
1321 if (config->size <= 0)
1322 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1323 else
1324 what_they_get = config->size;
1325 }
1326 else
1327 {
1328 what_they_get = get_remote_packet_size ();
1329 /* Limit the packet to the size specified by the user. */
1330 if (config->size > 0
1331 && what_they_get > config->size)
1332 what_they_get = config->size;
1333
1334 /* Limit it to the size of the targets ``g'' response unless we have
1335 permission from the stub to use a larger packet size. */
1336 if (rs->explicit_packet_size == 0
1337 && rsa->actual_register_packet_size > 0
1338 && what_they_get > rsa->actual_register_packet_size)
1339 what_they_get = rsa->actual_register_packet_size;
1340 }
1341 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1342 what_they_get = MIN_MEMORY_PACKET_SIZE;
1343
1344 /* Make sure there is room in the global buffer for this packet
1345 (including its trailing NUL byte). */
1346 if (rs->buf_size < what_they_get + 1)
1347 {
1348 rs->buf_size = 2 * what_they_get;
1349 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1350 }
1351
1352 return what_they_get;
1353 }
1354
1355 /* Update the size of a read/write packet. If they user wants
1356 something really big then do a sanity check. */
1357
1358 static void
1359 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1360 {
1361 int fixed_p = config->fixed_p;
1362 long size = config->size;
1363
1364 if (args == NULL)
1365 error (_("Argument required (integer, `fixed' or `limited')."));
1366 else if (strcmp (args, "hard") == 0
1367 || strcmp (args, "fixed") == 0)
1368 fixed_p = 1;
1369 else if (strcmp (args, "soft") == 0
1370 || strcmp (args, "limit") == 0)
1371 fixed_p = 0;
1372 else
1373 {
1374 char *end;
1375
1376 size = strtoul (args, &end, 0);
1377 if (args == end)
1378 error (_("Invalid %s (bad syntax)."), config->name);
1379
1380 /* Instead of explicitly capping the size of a packet to or
1381 disallowing it, the user is allowed to set the size to
1382 something arbitrarily large. */
1383 }
1384
1385 /* So that the query shows the correct value. */
1386 if (size <= 0)
1387 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1388
1389 /* Extra checks? */
1390 if (fixed_p && !config->fixed_p)
1391 {
1392 if (! query (_("The target may not be able to correctly handle a %s\n"
1393 "of %ld bytes. Change the packet size? "),
1394 config->name, size))
1395 error (_("Packet size not changed."));
1396 }
1397 /* Update the config. */
1398 config->fixed_p = fixed_p;
1399 config->size = size;
1400 }
1401
1402 static void
1403 show_memory_packet_size (struct memory_packet_config *config)
1404 {
1405 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1406 if (config->fixed_p)
1407 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1408 get_memory_packet_size (config));
1409 else
1410 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1411 get_memory_packet_size (config));
1412 }
1413
1414 static struct memory_packet_config memory_write_packet_config =
1415 {
1416 "memory-write-packet-size",
1417 };
1418
1419 static void
1420 set_memory_write_packet_size (const char *args, int from_tty)
1421 {
1422 set_memory_packet_size (args, &memory_write_packet_config);
1423 }
1424
1425 static void
1426 show_memory_write_packet_size (const char *args, int from_tty)
1427 {
1428 show_memory_packet_size (&memory_write_packet_config);
1429 }
1430
1431 static long
1432 get_memory_write_packet_size (void)
1433 {
1434 return get_memory_packet_size (&memory_write_packet_config);
1435 }
1436
1437 static struct memory_packet_config memory_read_packet_config =
1438 {
1439 "memory-read-packet-size",
1440 };
1441
1442 static void
1443 set_memory_read_packet_size (const char *args, int from_tty)
1444 {
1445 set_memory_packet_size (args, &memory_read_packet_config);
1446 }
1447
1448 static void
1449 show_memory_read_packet_size (const char *args, int from_tty)
1450 {
1451 show_memory_packet_size (&memory_read_packet_config);
1452 }
1453
1454 static long
1455 get_memory_read_packet_size (void)
1456 {
1457 long size = get_memory_packet_size (&memory_read_packet_config);
1458
1459 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1460 extra buffer size argument before the memory read size can be
1461 increased beyond this. */
1462 if (size > get_remote_packet_size ())
1463 size = get_remote_packet_size ();
1464 return size;
1465 }
1466
1467 \f
1468 /* Generic configuration support for packets the stub optionally
1469 supports. Allows the user to specify the use of the packet as well
1470 as allowing GDB to auto-detect support in the remote stub. */
1471
1472 enum packet_support
1473 {
1474 PACKET_SUPPORT_UNKNOWN = 0,
1475 PACKET_ENABLE,
1476 PACKET_DISABLE
1477 };
1478
1479 struct packet_config
1480 {
1481 const char *name;
1482 const char *title;
1483
1484 /* If auto, GDB auto-detects support for this packet or feature,
1485 either through qSupported, or by trying the packet and looking
1486 at the response. If true, GDB assumes the target supports this
1487 packet. If false, the packet is disabled. Configs that don't
1488 have an associated command always have this set to auto. */
1489 enum auto_boolean detect;
1490
1491 /* Does the target support this packet? */
1492 enum packet_support support;
1493 };
1494
1495 /* Analyze a packet's return value and update the packet config
1496 accordingly. */
1497
1498 enum packet_result
1499 {
1500 PACKET_ERROR,
1501 PACKET_OK,
1502 PACKET_UNKNOWN
1503 };
1504
1505 static enum packet_support packet_config_support (struct packet_config *config);
1506 static enum packet_support packet_support (int packet);
1507
1508 static void
1509 show_packet_config_cmd (struct packet_config *config)
1510 {
1511 const char *support = "internal-error";
1512
1513 switch (packet_config_support (config))
1514 {
1515 case PACKET_ENABLE:
1516 support = "enabled";
1517 break;
1518 case PACKET_DISABLE:
1519 support = "disabled";
1520 break;
1521 case PACKET_SUPPORT_UNKNOWN:
1522 support = "unknown";
1523 break;
1524 }
1525 switch (config->detect)
1526 {
1527 case AUTO_BOOLEAN_AUTO:
1528 printf_filtered (_("Support for the `%s' packet "
1529 "is auto-detected, currently %s.\n"),
1530 config->name, support);
1531 break;
1532 case AUTO_BOOLEAN_TRUE:
1533 case AUTO_BOOLEAN_FALSE:
1534 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1535 config->name, support);
1536 break;
1537 }
1538 }
1539
1540 static void
1541 add_packet_config_cmd (struct packet_config *config, const char *name,
1542 const char *title, int legacy)
1543 {
1544 char *set_doc;
1545 char *show_doc;
1546 char *cmd_name;
1547
1548 config->name = name;
1549 config->title = title;
1550 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1551 name, title);
1552 show_doc = xstrprintf ("Show current use of remote "
1553 "protocol `%s' (%s) packet",
1554 name, title);
1555 /* set/show TITLE-packet {auto,on,off} */
1556 cmd_name = xstrprintf ("%s-packet", title);
1557 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1558 &config->detect, set_doc,
1559 show_doc, NULL, /* help_doc */
1560 NULL,
1561 show_remote_protocol_packet_cmd,
1562 &remote_set_cmdlist, &remote_show_cmdlist);
1563 /* The command code copies the documentation strings. */
1564 xfree (set_doc);
1565 xfree (show_doc);
1566 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1567 if (legacy)
1568 {
1569 char *legacy_name;
1570
1571 legacy_name = xstrprintf ("%s-packet", name);
1572 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1573 &remote_set_cmdlist);
1574 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1575 &remote_show_cmdlist);
1576 }
1577 }
1578
1579 static enum packet_result
1580 packet_check_result (const char *buf)
1581 {
1582 if (buf[0] != '\0')
1583 {
1584 /* The stub recognized the packet request. Check that the
1585 operation succeeded. */
1586 if (buf[0] == 'E'
1587 && isxdigit (buf[1]) && isxdigit (buf[2])
1588 && buf[3] == '\0')
1589 /* "Enn" - definitly an error. */
1590 return PACKET_ERROR;
1591
1592 /* Always treat "E." as an error. This will be used for
1593 more verbose error messages, such as E.memtypes. */
1594 if (buf[0] == 'E' && buf[1] == '.')
1595 return PACKET_ERROR;
1596
1597 /* The packet may or may not be OK. Just assume it is. */
1598 return PACKET_OK;
1599 }
1600 else
1601 /* The stub does not support the packet. */
1602 return PACKET_UNKNOWN;
1603 }
1604
1605 static enum packet_result
1606 packet_ok (const char *buf, struct packet_config *config)
1607 {
1608 enum packet_result result;
1609
1610 if (config->detect != AUTO_BOOLEAN_TRUE
1611 && config->support == PACKET_DISABLE)
1612 internal_error (__FILE__, __LINE__,
1613 _("packet_ok: attempt to use a disabled packet"));
1614
1615 result = packet_check_result (buf);
1616 switch (result)
1617 {
1618 case PACKET_OK:
1619 case PACKET_ERROR:
1620 /* The stub recognized the packet request. */
1621 if (config->support == PACKET_SUPPORT_UNKNOWN)
1622 {
1623 if (remote_debug)
1624 fprintf_unfiltered (gdb_stdlog,
1625 "Packet %s (%s) is supported\n",
1626 config->name, config->title);
1627 config->support = PACKET_ENABLE;
1628 }
1629 break;
1630 case PACKET_UNKNOWN:
1631 /* The stub does not support the packet. */
1632 if (config->detect == AUTO_BOOLEAN_AUTO
1633 && config->support == PACKET_ENABLE)
1634 {
1635 /* If the stub previously indicated that the packet was
1636 supported then there is a protocol error. */
1637 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1638 config->name, config->title);
1639 }
1640 else if (config->detect == AUTO_BOOLEAN_TRUE)
1641 {
1642 /* The user set it wrong. */
1643 error (_("Enabled packet %s (%s) not recognized by stub"),
1644 config->name, config->title);
1645 }
1646
1647 if (remote_debug)
1648 fprintf_unfiltered (gdb_stdlog,
1649 "Packet %s (%s) is NOT supported\n",
1650 config->name, config->title);
1651 config->support = PACKET_DISABLE;
1652 break;
1653 }
1654
1655 return result;
1656 }
1657
1658 enum {
1659 PACKET_vCont = 0,
1660 PACKET_X,
1661 PACKET_qSymbol,
1662 PACKET_P,
1663 PACKET_p,
1664 PACKET_Z0,
1665 PACKET_Z1,
1666 PACKET_Z2,
1667 PACKET_Z3,
1668 PACKET_Z4,
1669 PACKET_vFile_setfs,
1670 PACKET_vFile_open,
1671 PACKET_vFile_pread,
1672 PACKET_vFile_pwrite,
1673 PACKET_vFile_close,
1674 PACKET_vFile_unlink,
1675 PACKET_vFile_readlink,
1676 PACKET_vFile_fstat,
1677 PACKET_qXfer_auxv,
1678 PACKET_qXfer_features,
1679 PACKET_qXfer_exec_file,
1680 PACKET_qXfer_libraries,
1681 PACKET_qXfer_libraries_svr4,
1682 PACKET_qXfer_memory_map,
1683 PACKET_qXfer_spu_read,
1684 PACKET_qXfer_spu_write,
1685 PACKET_qXfer_osdata,
1686 PACKET_qXfer_threads,
1687 PACKET_qXfer_statictrace_read,
1688 PACKET_qXfer_traceframe_info,
1689 PACKET_qXfer_uib,
1690 PACKET_qGetTIBAddr,
1691 PACKET_qGetTLSAddr,
1692 PACKET_qSupported,
1693 PACKET_qTStatus,
1694 PACKET_QPassSignals,
1695 PACKET_QCatchSyscalls,
1696 PACKET_QProgramSignals,
1697 PACKET_QSetWorkingDir,
1698 PACKET_QStartupWithShell,
1699 PACKET_QEnvironmentHexEncoded,
1700 PACKET_QEnvironmentReset,
1701 PACKET_QEnvironmentUnset,
1702 PACKET_qCRC,
1703 PACKET_qSearch_memory,
1704 PACKET_vAttach,
1705 PACKET_vRun,
1706 PACKET_QStartNoAckMode,
1707 PACKET_vKill,
1708 PACKET_qXfer_siginfo_read,
1709 PACKET_qXfer_siginfo_write,
1710 PACKET_qAttached,
1711
1712 /* Support for conditional tracepoints. */
1713 PACKET_ConditionalTracepoints,
1714
1715 /* Support for target-side breakpoint conditions. */
1716 PACKET_ConditionalBreakpoints,
1717
1718 /* Support for target-side breakpoint commands. */
1719 PACKET_BreakpointCommands,
1720
1721 /* Support for fast tracepoints. */
1722 PACKET_FastTracepoints,
1723
1724 /* Support for static tracepoints. */
1725 PACKET_StaticTracepoints,
1726
1727 /* Support for installing tracepoints while a trace experiment is
1728 running. */
1729 PACKET_InstallInTrace,
1730
1731 PACKET_bc,
1732 PACKET_bs,
1733 PACKET_TracepointSource,
1734 PACKET_QAllow,
1735 PACKET_qXfer_fdpic,
1736 PACKET_QDisableRandomization,
1737 PACKET_QAgent,
1738 PACKET_QTBuffer_size,
1739 PACKET_Qbtrace_off,
1740 PACKET_Qbtrace_bts,
1741 PACKET_Qbtrace_pt,
1742 PACKET_qXfer_btrace,
1743
1744 /* Support for the QNonStop packet. */
1745 PACKET_QNonStop,
1746
1747 /* Support for the QThreadEvents packet. */
1748 PACKET_QThreadEvents,
1749
1750 /* Support for multi-process extensions. */
1751 PACKET_multiprocess_feature,
1752
1753 /* Support for enabling and disabling tracepoints while a trace
1754 experiment is running. */
1755 PACKET_EnableDisableTracepoints_feature,
1756
1757 /* Support for collecting strings using the tracenz bytecode. */
1758 PACKET_tracenz_feature,
1759
1760 /* Support for continuing to run a trace experiment while GDB is
1761 disconnected. */
1762 PACKET_DisconnectedTracing_feature,
1763
1764 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1765 PACKET_augmented_libraries_svr4_read_feature,
1766
1767 /* Support for the qXfer:btrace-conf:read packet. */
1768 PACKET_qXfer_btrace_conf,
1769
1770 /* Support for the Qbtrace-conf:bts:size packet. */
1771 PACKET_Qbtrace_conf_bts_size,
1772
1773 /* Support for swbreak+ feature. */
1774 PACKET_swbreak_feature,
1775
1776 /* Support for hwbreak+ feature. */
1777 PACKET_hwbreak_feature,
1778
1779 /* Support for fork events. */
1780 PACKET_fork_event_feature,
1781
1782 /* Support for vfork events. */
1783 PACKET_vfork_event_feature,
1784
1785 /* Support for the Qbtrace-conf:pt:size packet. */
1786 PACKET_Qbtrace_conf_pt_size,
1787
1788 /* Support for exec events. */
1789 PACKET_exec_event_feature,
1790
1791 /* Support for query supported vCont actions. */
1792 PACKET_vContSupported,
1793
1794 /* Support remote CTRL-C. */
1795 PACKET_vCtrlC,
1796
1797 /* Support TARGET_WAITKIND_NO_RESUMED. */
1798 PACKET_no_resumed,
1799
1800 PACKET_MAX
1801 };
1802
1803 static struct packet_config remote_protocol_packets[PACKET_MAX];
1804
1805 /* Returns the packet's corresponding "set remote foo-packet" command
1806 state. See struct packet_config for more details. */
1807
1808 static enum auto_boolean
1809 packet_set_cmd_state (int packet)
1810 {
1811 return remote_protocol_packets[packet].detect;
1812 }
1813
1814 /* Returns whether a given packet or feature is supported. This takes
1815 into account the state of the corresponding "set remote foo-packet"
1816 command, which may be used to bypass auto-detection. */
1817
1818 static enum packet_support
1819 packet_config_support (struct packet_config *config)
1820 {
1821 switch (config->detect)
1822 {
1823 case AUTO_BOOLEAN_TRUE:
1824 return PACKET_ENABLE;
1825 case AUTO_BOOLEAN_FALSE:
1826 return PACKET_DISABLE;
1827 case AUTO_BOOLEAN_AUTO:
1828 return config->support;
1829 default:
1830 gdb_assert_not_reached (_("bad switch"));
1831 }
1832 }
1833
1834 /* Same as packet_config_support, but takes the packet's enum value as
1835 argument. */
1836
1837 static enum packet_support
1838 packet_support (int packet)
1839 {
1840 struct packet_config *config = &remote_protocol_packets[packet];
1841
1842 return packet_config_support (config);
1843 }
1844
1845 static void
1846 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1847 struct cmd_list_element *c,
1848 const char *value)
1849 {
1850 struct packet_config *packet;
1851
1852 for (packet = remote_protocol_packets;
1853 packet < &remote_protocol_packets[PACKET_MAX];
1854 packet++)
1855 {
1856 if (&packet->detect == c->var)
1857 {
1858 show_packet_config_cmd (packet);
1859 return;
1860 }
1861 }
1862 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1863 c->name);
1864 }
1865
1866 /* Should we try one of the 'Z' requests? */
1867
1868 enum Z_packet_type
1869 {
1870 Z_PACKET_SOFTWARE_BP,
1871 Z_PACKET_HARDWARE_BP,
1872 Z_PACKET_WRITE_WP,
1873 Z_PACKET_READ_WP,
1874 Z_PACKET_ACCESS_WP,
1875 NR_Z_PACKET_TYPES
1876 };
1877
1878 /* For compatibility with older distributions. Provide a ``set remote
1879 Z-packet ...'' command that updates all the Z packet types. */
1880
1881 static enum auto_boolean remote_Z_packet_detect;
1882
1883 static void
1884 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
1885 struct cmd_list_element *c)
1886 {
1887 int i;
1888
1889 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1890 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1891 }
1892
1893 static void
1894 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1895 struct cmd_list_element *c,
1896 const char *value)
1897 {
1898 int i;
1899
1900 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1901 {
1902 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1903 }
1904 }
1905
1906 /* Returns true if the multi-process extensions are in effect. */
1907
1908 static int
1909 remote_multi_process_p (struct remote_state *rs)
1910 {
1911 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1912 }
1913
1914 /* Returns true if fork events are supported. */
1915
1916 static int
1917 remote_fork_event_p (struct remote_state *rs)
1918 {
1919 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1920 }
1921
1922 /* Returns true if vfork events are supported. */
1923
1924 static int
1925 remote_vfork_event_p (struct remote_state *rs)
1926 {
1927 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1928 }
1929
1930 /* Returns true if exec events are supported. */
1931
1932 static int
1933 remote_exec_event_p (struct remote_state *rs)
1934 {
1935 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1936 }
1937
1938 /* Insert fork catchpoint target routine. If fork events are enabled
1939 then return success, nothing more to do. */
1940
1941 int
1942 remote_target::insert_fork_catchpoint (int pid)
1943 {
1944 struct remote_state *rs = get_remote_state ();
1945
1946 return !remote_fork_event_p (rs);
1947 }
1948
1949 /* Remove fork catchpoint target routine. Nothing to do, just
1950 return success. */
1951
1952 int
1953 remote_target::remove_fork_catchpoint (int pid)
1954 {
1955 return 0;
1956 }
1957
1958 /* Insert vfork catchpoint target routine. If vfork events are enabled
1959 then return success, nothing more to do. */
1960
1961 int
1962 remote_target::insert_vfork_catchpoint (int pid)
1963 {
1964 struct remote_state *rs = get_remote_state ();
1965
1966 return !remote_vfork_event_p (rs);
1967 }
1968
1969 /* Remove vfork catchpoint target routine. Nothing to do, just
1970 return success. */
1971
1972 int
1973 remote_target::remove_vfork_catchpoint (int pid)
1974 {
1975 return 0;
1976 }
1977
1978 /* Insert exec catchpoint target routine. If exec events are
1979 enabled, just return success. */
1980
1981 int
1982 remote_target::insert_exec_catchpoint (int pid)
1983 {
1984 struct remote_state *rs = get_remote_state ();
1985
1986 return !remote_exec_event_p (rs);
1987 }
1988
1989 /* Remove exec catchpoint target routine. Nothing to do, just
1990 return success. */
1991
1992 int
1993 remote_target::remove_exec_catchpoint (int pid)
1994 {
1995 return 0;
1996 }
1997
1998 \f
1999 /* Asynchronous signal handle registered as event loop source for
2000 when we have pending events ready to be passed to the core. */
2001
2002 static struct async_event_handler *remote_async_inferior_event_token;
2003
2004 \f
2005
2006 static ptid_t magic_null_ptid;
2007 static ptid_t not_sent_ptid;
2008 static ptid_t any_thread_ptid;
2009
2010 /* Find out if the stub attached to PID (and hence GDB should offer to
2011 detach instead of killing it when bailing out). */
2012
2013 static int
2014 remote_query_attached (int pid)
2015 {
2016 struct remote_state *rs = get_remote_state ();
2017 size_t size = get_remote_packet_size ();
2018
2019 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2020 return 0;
2021
2022 if (remote_multi_process_p (rs))
2023 xsnprintf (rs->buf, size, "qAttached:%x", pid);
2024 else
2025 xsnprintf (rs->buf, size, "qAttached");
2026
2027 putpkt (rs->buf);
2028 getpkt (&rs->buf, &rs->buf_size, 0);
2029
2030 switch (packet_ok (rs->buf,
2031 &remote_protocol_packets[PACKET_qAttached]))
2032 {
2033 case PACKET_OK:
2034 if (strcmp (rs->buf, "1") == 0)
2035 return 1;
2036 break;
2037 case PACKET_ERROR:
2038 warning (_("Remote failure reply: %s"), rs->buf);
2039 break;
2040 case PACKET_UNKNOWN:
2041 break;
2042 }
2043
2044 return 0;
2045 }
2046
2047 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2048 has been invented by GDB, instead of reported by the target. Since
2049 we can be connected to a remote system before before knowing about
2050 any inferior, mark the target with execution when we find the first
2051 inferior. If ATTACHED is 1, then we had just attached to this
2052 inferior. If it is 0, then we just created this inferior. If it
2053 is -1, then try querying the remote stub to find out if it had
2054 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2055 attempt to open this inferior's executable as the main executable
2056 if no main executable is open already. */
2057
2058 static struct inferior *
2059 remote_add_inferior (int fake_pid_p, int pid, int attached,
2060 int try_open_exec)
2061 {
2062 struct inferior *inf;
2063
2064 /* Check whether this process we're learning about is to be
2065 considered attached, or if is to be considered to have been
2066 spawned by the stub. */
2067 if (attached == -1)
2068 attached = remote_query_attached (pid);
2069
2070 if (gdbarch_has_global_solist (target_gdbarch ()))
2071 {
2072 /* If the target shares code across all inferiors, then every
2073 attach adds a new inferior. */
2074 inf = add_inferior (pid);
2075
2076 /* ... and every inferior is bound to the same program space.
2077 However, each inferior may still have its own address
2078 space. */
2079 inf->aspace = maybe_new_address_space ();
2080 inf->pspace = current_program_space;
2081 }
2082 else
2083 {
2084 /* In the traditional debugging scenario, there's a 1-1 match
2085 between program/address spaces. We simply bind the inferior
2086 to the program space's address space. */
2087 inf = current_inferior ();
2088 inferior_appeared (inf, pid);
2089 }
2090
2091 inf->attach_flag = attached;
2092 inf->fake_pid_p = fake_pid_p;
2093
2094 /* If no main executable is currently open then attempt to
2095 open the file that was executed to create this inferior. */
2096 if (try_open_exec && get_exec_file (0) == NULL)
2097 exec_file_locate_attach (pid, 0, 1);
2098
2099 return inf;
2100 }
2101
2102 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2103
2104 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2105 according to RUNNING. */
2106
2107 static void
2108 remote_add_thread (ptid_t ptid, int running, int executing)
2109 {
2110 struct remote_state *rs = get_remote_state ();
2111 struct thread_info *thread;
2112
2113 /* GDB historically didn't pull threads in the initial connection
2114 setup. If the remote target doesn't even have a concept of
2115 threads (e.g., a bare-metal target), even if internally we
2116 consider that a single-threaded target, mentioning a new thread
2117 might be confusing to the user. Be silent then, preserving the
2118 age old behavior. */
2119 if (rs->starting_up)
2120 thread = add_thread_silent (ptid);
2121 else
2122 thread = add_thread (ptid);
2123
2124 get_remote_thread_info (thread)->vcont_resumed = executing;
2125 set_executing (ptid, executing);
2126 set_running (ptid, running);
2127 }
2128
2129 /* Come here when we learn about a thread id from the remote target.
2130 It may be the first time we hear about such thread, so take the
2131 opportunity to add it to GDB's thread list. In case this is the
2132 first time we're noticing its corresponding inferior, add it to
2133 GDB's inferior list as well. EXECUTING indicates whether the
2134 thread is (internally) executing or stopped. */
2135
2136 static void
2137 remote_notice_new_inferior (ptid_t currthread, int executing)
2138 {
2139 /* In non-stop mode, we assume new found threads are (externally)
2140 running until proven otherwise with a stop reply. In all-stop,
2141 we can only get here if all threads are stopped. */
2142 int running = target_is_non_stop_p () ? 1 : 0;
2143
2144 /* If this is a new thread, add it to GDB's thread list.
2145 If we leave it up to WFI to do this, bad things will happen. */
2146
2147 if (in_thread_list (currthread) && is_exited (currthread))
2148 {
2149 /* We're seeing an event on a thread id we knew had exited.
2150 This has to be a new thread reusing the old id. Add it. */
2151 remote_add_thread (currthread, running, executing);
2152 return;
2153 }
2154
2155 if (!in_thread_list (currthread))
2156 {
2157 struct inferior *inf = NULL;
2158 int pid = ptid_get_pid (currthread);
2159
2160 if (ptid_is_pid (inferior_ptid)
2161 && pid == ptid_get_pid (inferior_ptid))
2162 {
2163 /* inferior_ptid has no thread member yet. This can happen
2164 with the vAttach -> remote_wait,"TAAthread:" path if the
2165 stub doesn't support qC. This is the first stop reported
2166 after an attach, so this is the main thread. Update the
2167 ptid in the thread list. */
2168 if (in_thread_list (pid_to_ptid (pid)))
2169 thread_change_ptid (inferior_ptid, currthread);
2170 else
2171 {
2172 remote_add_thread (currthread, running, executing);
2173 inferior_ptid = currthread;
2174 }
2175 return;
2176 }
2177
2178 if (ptid_equal (magic_null_ptid, inferior_ptid))
2179 {
2180 /* inferior_ptid is not set yet. This can happen with the
2181 vRun -> remote_wait,"TAAthread:" path if the stub
2182 doesn't support qC. This is the first stop reported
2183 after an attach, so this is the main thread. Update the
2184 ptid in the thread list. */
2185 thread_change_ptid (inferior_ptid, currthread);
2186 return;
2187 }
2188
2189 /* When connecting to a target remote, or to a target
2190 extended-remote which already was debugging an inferior, we
2191 may not know about it yet. Add it before adding its child
2192 thread, so notifications are emitted in a sensible order. */
2193 if (!in_inferior_list (ptid_get_pid (currthread)))
2194 {
2195 struct remote_state *rs = get_remote_state ();
2196 int fake_pid_p = !remote_multi_process_p (rs);
2197
2198 inf = remote_add_inferior (fake_pid_p,
2199 ptid_get_pid (currthread), -1, 1);
2200 }
2201
2202 /* This is really a new thread. Add it. */
2203 remote_add_thread (currthread, running, executing);
2204
2205 /* If we found a new inferior, let the common code do whatever
2206 it needs to with it (e.g., read shared libraries, insert
2207 breakpoints), unless we're just setting up an all-stop
2208 connection. */
2209 if (inf != NULL)
2210 {
2211 struct remote_state *rs = get_remote_state ();
2212
2213 if (!rs->starting_up)
2214 notice_new_inferior (currthread, executing, 0);
2215 }
2216 }
2217 }
2218
2219 /* Return THREAD's private thread data, creating it if necessary. */
2220
2221 static remote_thread_info *
2222 get_remote_thread_info (thread_info *thread)
2223 {
2224 gdb_assert (thread != NULL);
2225
2226 if (thread->priv == NULL)
2227 thread->priv.reset (new remote_thread_info);
2228
2229 return static_cast<remote_thread_info *> (thread->priv.get ());
2230 }
2231
2232 /* Return PTID's private thread data, creating it if necessary. */
2233
2234 static remote_thread_info *
2235 get_remote_thread_info (ptid_t ptid)
2236 {
2237 struct thread_info *info = find_thread_ptid (ptid);
2238
2239 return get_remote_thread_info (info);
2240 }
2241
2242 /* Call this function as a result of
2243 1) A halt indication (T packet) containing a thread id
2244 2) A direct query of currthread
2245 3) Successful execution of set thread */
2246
2247 static void
2248 record_currthread (struct remote_state *rs, ptid_t currthread)
2249 {
2250 rs->general_thread = currthread;
2251 }
2252
2253 /* If 'QPassSignals' is supported, tell the remote stub what signals
2254 it can simply pass through to the inferior without reporting. */
2255
2256 void
2257 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2258 {
2259 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2260 {
2261 char *pass_packet, *p;
2262 int count = 0, i;
2263 struct remote_state *rs = get_remote_state ();
2264
2265 gdb_assert (numsigs < 256);
2266 for (i = 0; i < numsigs; i++)
2267 {
2268 if (pass_signals[i])
2269 count++;
2270 }
2271 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2272 strcpy (pass_packet, "QPassSignals:");
2273 p = pass_packet + strlen (pass_packet);
2274 for (i = 0; i < numsigs; i++)
2275 {
2276 if (pass_signals[i])
2277 {
2278 if (i >= 16)
2279 *p++ = tohex (i >> 4);
2280 *p++ = tohex (i & 15);
2281 if (count)
2282 *p++ = ';';
2283 else
2284 break;
2285 count--;
2286 }
2287 }
2288 *p = 0;
2289 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2290 {
2291 putpkt (pass_packet);
2292 getpkt (&rs->buf, &rs->buf_size, 0);
2293 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2294 if (rs->last_pass_packet)
2295 xfree (rs->last_pass_packet);
2296 rs->last_pass_packet = pass_packet;
2297 }
2298 else
2299 xfree (pass_packet);
2300 }
2301 }
2302
2303 /* If 'QCatchSyscalls' is supported, tell the remote stub
2304 to report syscalls to GDB. */
2305
2306 int
2307 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2308 gdb::array_view<const int> syscall_counts)
2309 {
2310 const char *catch_packet;
2311 enum packet_result result;
2312 int n_sysno = 0;
2313
2314 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2315 {
2316 /* Not supported. */
2317 return 1;
2318 }
2319
2320 if (needed && any_count == 0)
2321 {
2322 /* Count how many syscalls are to be caught. */
2323 for (size_t i = 0; i < syscall_counts.size (); i++)
2324 {
2325 if (syscall_counts[i] != 0)
2326 n_sysno++;
2327 }
2328 }
2329
2330 if (remote_debug)
2331 {
2332 fprintf_unfiltered (gdb_stdlog,
2333 "remote_set_syscall_catchpoint "
2334 "pid %d needed %d any_count %d n_sysno %d\n",
2335 pid, needed, any_count, n_sysno);
2336 }
2337
2338 std::string built_packet;
2339 if (needed)
2340 {
2341 /* Prepare a packet with the sysno list, assuming max 8+1
2342 characters for a sysno. If the resulting packet size is too
2343 big, fallback on the non-selective packet. */
2344 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2345 built_packet.reserve (maxpktsz);
2346 built_packet = "QCatchSyscalls:1";
2347 if (any_count == 0)
2348 {
2349 /* Add in each syscall to be caught. */
2350 for (size_t i = 0; i < syscall_counts.size (); i++)
2351 {
2352 if (syscall_counts[i] != 0)
2353 string_appendf (built_packet, ";%zx", i);
2354 }
2355 }
2356 if (built_packet.size () > get_remote_packet_size ())
2357 {
2358 /* catch_packet too big. Fallback to less efficient
2359 non selective mode, with GDB doing the filtering. */
2360 catch_packet = "QCatchSyscalls:1";
2361 }
2362 else
2363 catch_packet = built_packet.c_str ();
2364 }
2365 else
2366 catch_packet = "QCatchSyscalls:0";
2367
2368 struct remote_state *rs = get_remote_state ();
2369
2370 putpkt (catch_packet);
2371 getpkt (&rs->buf, &rs->buf_size, 0);
2372 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2373 if (result == PACKET_OK)
2374 return 0;
2375 else
2376 return -1;
2377 }
2378
2379 /* If 'QProgramSignals' is supported, tell the remote stub what
2380 signals it should pass through to the inferior when detaching. */
2381
2382 void
2383 remote_target::program_signals (int numsigs, unsigned char *signals)
2384 {
2385 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2386 {
2387 char *packet, *p;
2388 int count = 0, i;
2389 struct remote_state *rs = get_remote_state ();
2390
2391 gdb_assert (numsigs < 256);
2392 for (i = 0; i < numsigs; i++)
2393 {
2394 if (signals[i])
2395 count++;
2396 }
2397 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2398 strcpy (packet, "QProgramSignals:");
2399 p = packet + strlen (packet);
2400 for (i = 0; i < numsigs; i++)
2401 {
2402 if (signal_pass_state (i))
2403 {
2404 if (i >= 16)
2405 *p++ = tohex (i >> 4);
2406 *p++ = tohex (i & 15);
2407 if (count)
2408 *p++ = ';';
2409 else
2410 break;
2411 count--;
2412 }
2413 }
2414 *p = 0;
2415 if (!rs->last_program_signals_packet
2416 || strcmp (rs->last_program_signals_packet, packet) != 0)
2417 {
2418 putpkt (packet);
2419 getpkt (&rs->buf, &rs->buf_size, 0);
2420 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2421 xfree (rs->last_program_signals_packet);
2422 rs->last_program_signals_packet = packet;
2423 }
2424 else
2425 xfree (packet);
2426 }
2427 }
2428
2429 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2430 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2431 thread. If GEN is set, set the general thread, if not, then set
2432 the step/continue thread. */
2433 static void
2434 set_thread (ptid_t ptid, int gen)
2435 {
2436 struct remote_state *rs = get_remote_state ();
2437 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2438 char *buf = rs->buf;
2439 char *endbuf = rs->buf + get_remote_packet_size ();
2440
2441 if (ptid_equal (state, ptid))
2442 return;
2443
2444 *buf++ = 'H';
2445 *buf++ = gen ? 'g' : 'c';
2446 if (ptid_equal (ptid, magic_null_ptid))
2447 xsnprintf (buf, endbuf - buf, "0");
2448 else if (ptid_equal (ptid, any_thread_ptid))
2449 xsnprintf (buf, endbuf - buf, "0");
2450 else if (ptid_equal (ptid, minus_one_ptid))
2451 xsnprintf (buf, endbuf - buf, "-1");
2452 else
2453 write_ptid (buf, endbuf, ptid);
2454 putpkt (rs->buf);
2455 getpkt (&rs->buf, &rs->buf_size, 0);
2456 if (gen)
2457 rs->general_thread = ptid;
2458 else
2459 rs->continue_thread = ptid;
2460 }
2461
2462 static void
2463 set_general_thread (ptid_t ptid)
2464 {
2465 set_thread (ptid, 1);
2466 }
2467
2468 static void
2469 set_continue_thread (ptid_t ptid)
2470 {
2471 set_thread (ptid, 0);
2472 }
2473
2474 /* Change the remote current process. Which thread within the process
2475 ends up selected isn't important, as long as it is the same process
2476 as what INFERIOR_PTID points to.
2477
2478 This comes from that fact that there is no explicit notion of
2479 "selected process" in the protocol. The selected process for
2480 general operations is the process the selected general thread
2481 belongs to. */
2482
2483 static void
2484 set_general_process (void)
2485 {
2486 struct remote_state *rs = get_remote_state ();
2487
2488 /* If the remote can't handle multiple processes, don't bother. */
2489 if (!remote_multi_process_p (rs))
2490 return;
2491
2492 /* We only need to change the remote current thread if it's pointing
2493 at some other process. */
2494 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2495 set_general_thread (inferior_ptid);
2496 }
2497
2498 \f
2499 /* Return nonzero if this is the main thread that we made up ourselves
2500 to model non-threaded targets as single-threaded. */
2501
2502 static int
2503 remote_thread_always_alive (ptid_t ptid)
2504 {
2505 if (ptid_equal (ptid, magic_null_ptid))
2506 /* The main thread is always alive. */
2507 return 1;
2508
2509 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2510 /* The main thread is always alive. This can happen after a
2511 vAttach, if the remote side doesn't support
2512 multi-threading. */
2513 return 1;
2514
2515 return 0;
2516 }
2517
2518 /* Return nonzero if the thread PTID is still alive on the remote
2519 system. */
2520
2521 int
2522 remote_target::thread_alive (ptid_t ptid)
2523 {
2524 struct remote_state *rs = get_remote_state ();
2525 char *p, *endp;
2526
2527 /* Check if this is a thread that we made up ourselves to model
2528 non-threaded targets as single-threaded. */
2529 if (remote_thread_always_alive (ptid))
2530 return 1;
2531
2532 p = rs->buf;
2533 endp = rs->buf + get_remote_packet_size ();
2534
2535 *p++ = 'T';
2536 write_ptid (p, endp, ptid);
2537
2538 putpkt (rs->buf);
2539 getpkt (&rs->buf, &rs->buf_size, 0);
2540 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2541 }
2542
2543 /* Return a pointer to a thread name if we know it and NULL otherwise.
2544 The thread_info object owns the memory for the name. */
2545
2546 const char *
2547 remote_target::thread_name (struct thread_info *info)
2548 {
2549 if (info->priv != NULL)
2550 {
2551 const std::string &name = get_remote_thread_info (info)->name;
2552 return !name.empty () ? name.c_str () : NULL;
2553 }
2554
2555 return NULL;
2556 }
2557
2558 /* About these extended threadlist and threadinfo packets. They are
2559 variable length packets but, the fields within them are often fixed
2560 length. They are redundent enough to send over UDP as is the
2561 remote protocol in general. There is a matching unit test module
2562 in libstub. */
2563
2564 /* WARNING: This threadref data structure comes from the remote O.S.,
2565 libstub protocol encoding, and remote.c. It is not particularly
2566 changable. */
2567
2568 /* Right now, the internal structure is int. We want it to be bigger.
2569 Plan to fix this. */
2570
2571 typedef int gdb_threadref; /* Internal GDB thread reference. */
2572
2573 /* gdb_ext_thread_info is an internal GDB data structure which is
2574 equivalent to the reply of the remote threadinfo packet. */
2575
2576 struct gdb_ext_thread_info
2577 {
2578 threadref threadid; /* External form of thread reference. */
2579 int active; /* Has state interesting to GDB?
2580 regs, stack. */
2581 char display[256]; /* Brief state display, name,
2582 blocked/suspended. */
2583 char shortname[32]; /* To be used to name threads. */
2584 char more_display[256]; /* Long info, statistics, queue depth,
2585 whatever. */
2586 };
2587
2588 /* The volume of remote transfers can be limited by submitting
2589 a mask containing bits specifying the desired information.
2590 Use a union of these values as the 'selection' parameter to
2591 get_thread_info. FIXME: Make these TAG names more thread specific. */
2592
2593 #define TAG_THREADID 1
2594 #define TAG_EXISTS 2
2595 #define TAG_DISPLAY 4
2596 #define TAG_THREADNAME 8
2597 #define TAG_MOREDISPLAY 16
2598
2599 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2600
2601 static char *unpack_nibble (char *buf, int *val);
2602
2603 static char *unpack_byte (char *buf, int *value);
2604
2605 static char *pack_int (char *buf, int value);
2606
2607 static char *unpack_int (char *buf, int *value);
2608
2609 static char *unpack_string (char *src, char *dest, int length);
2610
2611 static char *pack_threadid (char *pkt, threadref *id);
2612
2613 static char *unpack_threadid (char *inbuf, threadref *id);
2614
2615 void int_to_threadref (threadref *id, int value);
2616
2617 static int threadref_to_int (threadref *ref);
2618
2619 static void copy_threadref (threadref *dest, threadref *src);
2620
2621 static int threadmatch (threadref *dest, threadref *src);
2622
2623 static char *pack_threadinfo_request (char *pkt, int mode,
2624 threadref *id);
2625
2626 static int remote_unpack_thread_info_response (char *pkt,
2627 threadref *expectedref,
2628 struct gdb_ext_thread_info
2629 *info);
2630
2631
2632 static int remote_get_threadinfo (threadref *threadid,
2633 int fieldset, /*TAG mask */
2634 struct gdb_ext_thread_info *info);
2635
2636 static char *pack_threadlist_request (char *pkt, int startflag,
2637 int threadcount,
2638 threadref *nextthread);
2639
2640 static int parse_threadlist_response (char *pkt,
2641 int result_limit,
2642 threadref *original_echo,
2643 threadref *resultlist,
2644 int *doneflag);
2645
2646 static int remote_get_threadlist (int startflag,
2647 threadref *nextthread,
2648 int result_limit,
2649 int *done,
2650 int *result_count,
2651 threadref *threadlist);
2652
2653 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2654
2655 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2656 void *context, int looplimit);
2657
2658 static int remote_newthread_step (threadref *ref, void *context);
2659
2660
2661 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2662 buffer we're allowed to write to. Returns
2663 BUF+CHARACTERS_WRITTEN. */
2664
2665 static char *
2666 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2667 {
2668 int pid, tid;
2669 struct remote_state *rs = get_remote_state ();
2670
2671 if (remote_multi_process_p (rs))
2672 {
2673 pid = ptid_get_pid (ptid);
2674 if (pid < 0)
2675 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2676 else
2677 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2678 }
2679 tid = ptid_get_lwp (ptid);
2680 if (tid < 0)
2681 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2682 else
2683 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2684
2685 return buf;
2686 }
2687
2688 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2689 last parsed char. Returns null_ptid if no thread id is found, and
2690 throws an error if the thread id has an invalid format. */
2691
2692 static ptid_t
2693 read_ptid (const char *buf, const char **obuf)
2694 {
2695 const char *p = buf;
2696 const char *pp;
2697 ULONGEST pid = 0, tid = 0;
2698
2699 if (*p == 'p')
2700 {
2701 /* Multi-process ptid. */
2702 pp = unpack_varlen_hex (p + 1, &pid);
2703 if (*pp != '.')
2704 error (_("invalid remote ptid: %s"), p);
2705
2706 p = pp;
2707 pp = unpack_varlen_hex (p + 1, &tid);
2708 if (obuf)
2709 *obuf = pp;
2710 return ptid_build (pid, tid, 0);
2711 }
2712
2713 /* No multi-process. Just a tid. */
2714 pp = unpack_varlen_hex (p, &tid);
2715
2716 /* Return null_ptid when no thread id is found. */
2717 if (p == pp)
2718 {
2719 if (obuf)
2720 *obuf = pp;
2721 return null_ptid;
2722 }
2723
2724 /* Since the stub is not sending a process id, then default to
2725 what's in inferior_ptid, unless it's null at this point. If so,
2726 then since there's no way to know the pid of the reported
2727 threads, use the magic number. */
2728 if (ptid_equal (inferior_ptid, null_ptid))
2729 pid = ptid_get_pid (magic_null_ptid);
2730 else
2731 pid = ptid_get_pid (inferior_ptid);
2732
2733 if (obuf)
2734 *obuf = pp;
2735 return ptid_build (pid, tid, 0);
2736 }
2737
2738 static int
2739 stubhex (int ch)
2740 {
2741 if (ch >= 'a' && ch <= 'f')
2742 return ch - 'a' + 10;
2743 if (ch >= '0' && ch <= '9')
2744 return ch - '0';
2745 if (ch >= 'A' && ch <= 'F')
2746 return ch - 'A' + 10;
2747 return -1;
2748 }
2749
2750 static int
2751 stub_unpack_int (char *buff, int fieldlength)
2752 {
2753 int nibble;
2754 int retval = 0;
2755
2756 while (fieldlength)
2757 {
2758 nibble = stubhex (*buff++);
2759 retval |= nibble;
2760 fieldlength--;
2761 if (fieldlength)
2762 retval = retval << 4;
2763 }
2764 return retval;
2765 }
2766
2767 static char *
2768 unpack_nibble (char *buf, int *val)
2769 {
2770 *val = fromhex (*buf++);
2771 return buf;
2772 }
2773
2774 static char *
2775 unpack_byte (char *buf, int *value)
2776 {
2777 *value = stub_unpack_int (buf, 2);
2778 return buf + 2;
2779 }
2780
2781 static char *
2782 pack_int (char *buf, int value)
2783 {
2784 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2785 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2786 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2787 buf = pack_hex_byte (buf, (value & 0xff));
2788 return buf;
2789 }
2790
2791 static char *
2792 unpack_int (char *buf, int *value)
2793 {
2794 *value = stub_unpack_int (buf, 8);
2795 return buf + 8;
2796 }
2797
2798 #if 0 /* Currently unused, uncomment when needed. */
2799 static char *pack_string (char *pkt, char *string);
2800
2801 static char *
2802 pack_string (char *pkt, char *string)
2803 {
2804 char ch;
2805 int len;
2806
2807 len = strlen (string);
2808 if (len > 200)
2809 len = 200; /* Bigger than most GDB packets, junk??? */
2810 pkt = pack_hex_byte (pkt, len);
2811 while (len-- > 0)
2812 {
2813 ch = *string++;
2814 if ((ch == '\0') || (ch == '#'))
2815 ch = '*'; /* Protect encapsulation. */
2816 *pkt++ = ch;
2817 }
2818 return pkt;
2819 }
2820 #endif /* 0 (unused) */
2821
2822 static char *
2823 unpack_string (char *src, char *dest, int length)
2824 {
2825 while (length--)
2826 *dest++ = *src++;
2827 *dest = '\0';
2828 return src;
2829 }
2830
2831 static char *
2832 pack_threadid (char *pkt, threadref *id)
2833 {
2834 char *limit;
2835 unsigned char *altid;
2836
2837 altid = (unsigned char *) id;
2838 limit = pkt + BUF_THREAD_ID_SIZE;
2839 while (pkt < limit)
2840 pkt = pack_hex_byte (pkt, *altid++);
2841 return pkt;
2842 }
2843
2844
2845 static char *
2846 unpack_threadid (char *inbuf, threadref *id)
2847 {
2848 char *altref;
2849 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2850 int x, y;
2851
2852 altref = (char *) id;
2853
2854 while (inbuf < limit)
2855 {
2856 x = stubhex (*inbuf++);
2857 y = stubhex (*inbuf++);
2858 *altref++ = (x << 4) | y;
2859 }
2860 return inbuf;
2861 }
2862
2863 /* Externally, threadrefs are 64 bits but internally, they are still
2864 ints. This is due to a mismatch of specifications. We would like
2865 to use 64bit thread references internally. This is an adapter
2866 function. */
2867
2868 void
2869 int_to_threadref (threadref *id, int value)
2870 {
2871 unsigned char *scan;
2872
2873 scan = (unsigned char *) id;
2874 {
2875 int i = 4;
2876 while (i--)
2877 *scan++ = 0;
2878 }
2879 *scan++ = (value >> 24) & 0xff;
2880 *scan++ = (value >> 16) & 0xff;
2881 *scan++ = (value >> 8) & 0xff;
2882 *scan++ = (value & 0xff);
2883 }
2884
2885 static int
2886 threadref_to_int (threadref *ref)
2887 {
2888 int i, value = 0;
2889 unsigned char *scan;
2890
2891 scan = *ref;
2892 scan += 4;
2893 i = 4;
2894 while (i-- > 0)
2895 value = (value << 8) | ((*scan++) & 0xff);
2896 return value;
2897 }
2898
2899 static void
2900 copy_threadref (threadref *dest, threadref *src)
2901 {
2902 int i;
2903 unsigned char *csrc, *cdest;
2904
2905 csrc = (unsigned char *) src;
2906 cdest = (unsigned char *) dest;
2907 i = 8;
2908 while (i--)
2909 *cdest++ = *csrc++;
2910 }
2911
2912 static int
2913 threadmatch (threadref *dest, threadref *src)
2914 {
2915 /* Things are broken right now, so just assume we got a match. */
2916 #if 0
2917 unsigned char *srcp, *destp;
2918 int i, result;
2919 srcp = (char *) src;
2920 destp = (char *) dest;
2921
2922 result = 1;
2923 while (i-- > 0)
2924 result &= (*srcp++ == *destp++) ? 1 : 0;
2925 return result;
2926 #endif
2927 return 1;
2928 }
2929
2930 /*
2931 threadid:1, # always request threadid
2932 context_exists:2,
2933 display:4,
2934 unique_name:8,
2935 more_display:16
2936 */
2937
2938 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2939
2940 static char *
2941 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2942 {
2943 *pkt++ = 'q'; /* Info Query */
2944 *pkt++ = 'P'; /* process or thread info */
2945 pkt = pack_int (pkt, mode); /* mode */
2946 pkt = pack_threadid (pkt, id); /* threadid */
2947 *pkt = '\0'; /* terminate */
2948 return pkt;
2949 }
2950
2951 /* These values tag the fields in a thread info response packet. */
2952 /* Tagging the fields allows us to request specific fields and to
2953 add more fields as time goes by. */
2954
2955 #define TAG_THREADID 1 /* Echo the thread identifier. */
2956 #define TAG_EXISTS 2 /* Is this process defined enough to
2957 fetch registers and its stack? */
2958 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2959 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2960 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2961 the process. */
2962
2963 static int
2964 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2965 struct gdb_ext_thread_info *info)
2966 {
2967 struct remote_state *rs = get_remote_state ();
2968 int mask, length;
2969 int tag;
2970 threadref ref;
2971 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2972 int retval = 1;
2973
2974 /* info->threadid = 0; FIXME: implement zero_threadref. */
2975 info->active = 0;
2976 info->display[0] = '\0';
2977 info->shortname[0] = '\0';
2978 info->more_display[0] = '\0';
2979
2980 /* Assume the characters indicating the packet type have been
2981 stripped. */
2982 pkt = unpack_int (pkt, &mask); /* arg mask */
2983 pkt = unpack_threadid (pkt, &ref);
2984
2985 if (mask == 0)
2986 warning (_("Incomplete response to threadinfo request."));
2987 if (!threadmatch (&ref, expectedref))
2988 { /* This is an answer to a different request. */
2989 warning (_("ERROR RMT Thread info mismatch."));
2990 return 0;
2991 }
2992 copy_threadref (&info->threadid, &ref);
2993
2994 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2995
2996 /* Packets are terminated with nulls. */
2997 while ((pkt < limit) && mask && *pkt)
2998 {
2999 pkt = unpack_int (pkt, &tag); /* tag */
3000 pkt = unpack_byte (pkt, &length); /* length */
3001 if (!(tag & mask)) /* Tags out of synch with mask. */
3002 {
3003 warning (_("ERROR RMT: threadinfo tag mismatch."));
3004 retval = 0;
3005 break;
3006 }
3007 if (tag == TAG_THREADID)
3008 {
3009 if (length != 16)
3010 {
3011 warning (_("ERROR RMT: length of threadid is not 16."));
3012 retval = 0;
3013 break;
3014 }
3015 pkt = unpack_threadid (pkt, &ref);
3016 mask = mask & ~TAG_THREADID;
3017 continue;
3018 }
3019 if (tag == TAG_EXISTS)
3020 {
3021 info->active = stub_unpack_int (pkt, length);
3022 pkt += length;
3023 mask = mask & ~(TAG_EXISTS);
3024 if (length > 8)
3025 {
3026 warning (_("ERROR RMT: 'exists' length too long."));
3027 retval = 0;
3028 break;
3029 }
3030 continue;
3031 }
3032 if (tag == TAG_THREADNAME)
3033 {
3034 pkt = unpack_string (pkt, &info->shortname[0], length);
3035 mask = mask & ~TAG_THREADNAME;
3036 continue;
3037 }
3038 if (tag == TAG_DISPLAY)
3039 {
3040 pkt = unpack_string (pkt, &info->display[0], length);
3041 mask = mask & ~TAG_DISPLAY;
3042 continue;
3043 }
3044 if (tag == TAG_MOREDISPLAY)
3045 {
3046 pkt = unpack_string (pkt, &info->more_display[0], length);
3047 mask = mask & ~TAG_MOREDISPLAY;
3048 continue;
3049 }
3050 warning (_("ERROR RMT: unknown thread info tag."));
3051 break; /* Not a tag we know about. */
3052 }
3053 return retval;
3054 }
3055
3056 static int
3057 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
3058 struct gdb_ext_thread_info *info)
3059 {
3060 struct remote_state *rs = get_remote_state ();
3061 int result;
3062
3063 pack_threadinfo_request (rs->buf, fieldset, threadid);
3064 putpkt (rs->buf);
3065 getpkt (&rs->buf, &rs->buf_size, 0);
3066
3067 if (rs->buf[0] == '\0')
3068 return 0;
3069
3070 result = remote_unpack_thread_info_response (rs->buf + 2,
3071 threadid, info);
3072 return result;
3073 }
3074
3075 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3076
3077 static char *
3078 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3079 threadref *nextthread)
3080 {
3081 *pkt++ = 'q'; /* info query packet */
3082 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3083 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3084 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3085 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3086 *pkt = '\0';
3087 return pkt;
3088 }
3089
3090 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3091
3092 static int
3093 parse_threadlist_response (char *pkt, int result_limit,
3094 threadref *original_echo, threadref *resultlist,
3095 int *doneflag)
3096 {
3097 struct remote_state *rs = get_remote_state ();
3098 char *limit;
3099 int count, resultcount, done;
3100
3101 resultcount = 0;
3102 /* Assume the 'q' and 'M chars have been stripped. */
3103 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3104 /* done parse past here */
3105 pkt = unpack_byte (pkt, &count); /* count field */
3106 pkt = unpack_nibble (pkt, &done);
3107 /* The first threadid is the argument threadid. */
3108 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3109 while ((count-- > 0) && (pkt < limit))
3110 {
3111 pkt = unpack_threadid (pkt, resultlist++);
3112 if (resultcount++ >= result_limit)
3113 break;
3114 }
3115 if (doneflag)
3116 *doneflag = done;
3117 return resultcount;
3118 }
3119
3120 /* Fetch the next batch of threads from the remote. Returns -1 if the
3121 qL packet is not supported, 0 on error and 1 on success. */
3122
3123 static int
3124 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
3125 int *done, int *result_count, threadref *threadlist)
3126 {
3127 struct remote_state *rs = get_remote_state ();
3128 int result = 1;
3129
3130 /* Trancate result limit to be smaller than the packet size. */
3131 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3132 >= get_remote_packet_size ())
3133 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3134
3135 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3136 putpkt (rs->buf);
3137 getpkt (&rs->buf, &rs->buf_size, 0);
3138 if (*rs->buf == '\0')
3139 {
3140 /* Packet not supported. */
3141 return -1;
3142 }
3143
3144 *result_count =
3145 parse_threadlist_response (rs->buf + 2, result_limit,
3146 &rs->echo_nextthread, threadlist, done);
3147
3148 if (!threadmatch (&rs->echo_nextthread, nextthread))
3149 {
3150 /* FIXME: This is a good reason to drop the packet. */
3151 /* Possably, there is a duplicate response. */
3152 /* Possabilities :
3153 retransmit immediatly - race conditions
3154 retransmit after timeout - yes
3155 exit
3156 wait for packet, then exit
3157 */
3158 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3159 return 0; /* I choose simply exiting. */
3160 }
3161 if (*result_count <= 0)
3162 {
3163 if (*done != 1)
3164 {
3165 warning (_("RMT ERROR : failed to get remote thread list."));
3166 result = 0;
3167 }
3168 return result; /* break; */
3169 }
3170 if (*result_count > result_limit)
3171 {
3172 *result_count = 0;
3173 warning (_("RMT ERROR: threadlist response longer than requested."));
3174 return 0;
3175 }
3176 return result;
3177 }
3178
3179 /* Fetch the list of remote threads, with the qL packet, and call
3180 STEPFUNCTION for each thread found. Stops iterating and returns 1
3181 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3182 STEPFUNCTION returns false. If the packet is not supported,
3183 returns -1. */
3184
3185 static int
3186 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
3187 int looplimit)
3188 {
3189 struct remote_state *rs = get_remote_state ();
3190 int done, i, result_count;
3191 int startflag = 1;
3192 int result = 1;
3193 int loopcount = 0;
3194
3195 done = 0;
3196 while (!done)
3197 {
3198 if (loopcount++ > looplimit)
3199 {
3200 result = 0;
3201 warning (_("Remote fetch threadlist -infinite loop-."));
3202 break;
3203 }
3204 result = remote_get_threadlist (startflag, &rs->nextthread,
3205 MAXTHREADLISTRESULTS,
3206 &done, &result_count,
3207 rs->resultthreadlist);
3208 if (result <= 0)
3209 break;
3210 /* Clear for later iterations. */
3211 startflag = 0;
3212 /* Setup to resume next batch of thread references, set nextthread. */
3213 if (result_count >= 1)
3214 copy_threadref (&rs->nextthread,
3215 &rs->resultthreadlist[result_count - 1]);
3216 i = 0;
3217 while (result_count--)
3218 {
3219 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3220 {
3221 result = 0;
3222 break;
3223 }
3224 }
3225 }
3226 return result;
3227 }
3228
3229 /* A thread found on the remote target. */
3230
3231 struct thread_item
3232 {
3233 explicit thread_item (ptid_t ptid_)
3234 : ptid (ptid_)
3235 {}
3236
3237 thread_item (thread_item &&other) = default;
3238 thread_item &operator= (thread_item &&other) = default;
3239
3240 DISABLE_COPY_AND_ASSIGN (thread_item);
3241
3242 /* The thread's PTID. */
3243 ptid_t ptid;
3244
3245 /* The thread's extra info. */
3246 std::string extra;
3247
3248 /* The thread's name. */
3249 std::string name;
3250
3251 /* The core the thread was running on. -1 if not known. */
3252 int core = -1;
3253
3254 /* The thread handle associated with the thread. */
3255 gdb::byte_vector thread_handle;
3256 };
3257
3258 /* Context passed around to the various methods listing remote
3259 threads. As new threads are found, they're added to the ITEMS
3260 vector. */
3261
3262 struct threads_listing_context
3263 {
3264 /* Return true if this object contains an entry for a thread with ptid
3265 PTID. */
3266
3267 bool contains_thread (ptid_t ptid) const
3268 {
3269 auto match_ptid = [&] (const thread_item &item)
3270 {
3271 return item.ptid == ptid;
3272 };
3273
3274 auto it = std::find_if (this->items.begin (),
3275 this->items.end (),
3276 match_ptid);
3277
3278 return it != this->items.end ();
3279 }
3280
3281 /* Remove the thread with ptid PTID. */
3282
3283 void remove_thread (ptid_t ptid)
3284 {
3285 auto match_ptid = [&] (const thread_item &item)
3286 {
3287 return item.ptid == ptid;
3288 };
3289
3290 auto it = std::remove_if (this->items.begin (),
3291 this->items.end (),
3292 match_ptid);
3293
3294 if (it != this->items.end ())
3295 this->items.erase (it);
3296 }
3297
3298 /* The threads found on the remote target. */
3299 std::vector<thread_item> items;
3300 };
3301
3302 static int
3303 remote_newthread_step (threadref *ref, void *data)
3304 {
3305 struct threads_listing_context *context
3306 = (struct threads_listing_context *) data;
3307 int pid = inferior_ptid.pid ();
3308 int lwp = threadref_to_int (ref);
3309 ptid_t ptid (pid, lwp);
3310
3311 context->items.emplace_back (ptid);
3312
3313 return 1; /* continue iterator */
3314 }
3315
3316 #define CRAZY_MAX_THREADS 1000
3317
3318 static ptid_t
3319 remote_current_thread (ptid_t oldpid)
3320 {
3321 struct remote_state *rs = get_remote_state ();
3322
3323 putpkt ("qC");
3324 getpkt (&rs->buf, &rs->buf_size, 0);
3325 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3326 {
3327 const char *obuf;
3328 ptid_t result;
3329
3330 result = read_ptid (&rs->buf[2], &obuf);
3331 if (*obuf != '\0' && remote_debug)
3332 fprintf_unfiltered (gdb_stdlog,
3333 "warning: garbage in qC reply\n");
3334
3335 return result;
3336 }
3337 else
3338 return oldpid;
3339 }
3340
3341 /* List remote threads using the deprecated qL packet. */
3342
3343 static int
3344 remote_get_threads_with_ql (struct target_ops *ops,
3345 struct threads_listing_context *context)
3346 {
3347 if (remote_threadlist_iterator (remote_newthread_step, context,
3348 CRAZY_MAX_THREADS) >= 0)
3349 return 1;
3350
3351 return 0;
3352 }
3353
3354 #if defined(HAVE_LIBEXPAT)
3355
3356 static void
3357 start_thread (struct gdb_xml_parser *parser,
3358 const struct gdb_xml_element *element,
3359 void *user_data,
3360 std::vector<gdb_xml_value> &attributes)
3361 {
3362 struct threads_listing_context *data
3363 = (struct threads_listing_context *) user_data;
3364 struct gdb_xml_value *attr;
3365
3366 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3367 ptid_t ptid = read_ptid (id, NULL);
3368
3369 data->items.emplace_back (ptid);
3370 thread_item &item = data->items.back ();
3371
3372 attr = xml_find_attribute (attributes, "core");
3373 if (attr != NULL)
3374 item.core = *(ULONGEST *) attr->value.get ();
3375
3376 attr = xml_find_attribute (attributes, "name");
3377 if (attr != NULL)
3378 item.name = (const char *) attr->value.get ();
3379
3380 attr = xml_find_attribute (attributes, "handle");
3381 if (attr != NULL)
3382 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3383 }
3384
3385 static void
3386 end_thread (struct gdb_xml_parser *parser,
3387 const struct gdb_xml_element *element,
3388 void *user_data, const char *body_text)
3389 {
3390 struct threads_listing_context *data
3391 = (struct threads_listing_context *) user_data;
3392
3393 if (body_text != NULL && *body_text != '\0')
3394 data->items.back ().extra = body_text;
3395 }
3396
3397 const struct gdb_xml_attribute thread_attributes[] = {
3398 { "id", GDB_XML_AF_NONE, NULL, NULL },
3399 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3400 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3401 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3402 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3403 };
3404
3405 const struct gdb_xml_element thread_children[] = {
3406 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3407 };
3408
3409 const struct gdb_xml_element threads_children[] = {
3410 { "thread", thread_attributes, thread_children,
3411 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3412 start_thread, end_thread },
3413 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3414 };
3415
3416 const struct gdb_xml_element threads_elements[] = {
3417 { "threads", NULL, threads_children,
3418 GDB_XML_EF_NONE, NULL, NULL },
3419 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3420 };
3421
3422 #endif
3423
3424 /* List remote threads using qXfer:threads:read. */
3425
3426 static int
3427 remote_get_threads_with_qxfer (struct target_ops *ops,
3428 struct threads_listing_context *context)
3429 {
3430 #if defined(HAVE_LIBEXPAT)
3431 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3432 {
3433 gdb::optional<gdb::char_vector> xml
3434 = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3435
3436 if (xml && (*xml)[0] != '\0')
3437 {
3438 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3439 threads_elements, xml->data (), context);
3440 }
3441
3442 return 1;
3443 }
3444 #endif
3445
3446 return 0;
3447 }
3448
3449 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3450
3451 static int
3452 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3453 struct threads_listing_context *context)
3454 {
3455 struct remote_state *rs = get_remote_state ();
3456
3457 if (rs->use_threadinfo_query)
3458 {
3459 const char *bufp;
3460
3461 putpkt ("qfThreadInfo");
3462 getpkt (&rs->buf, &rs->buf_size, 0);
3463 bufp = rs->buf;
3464 if (bufp[0] != '\0') /* q packet recognized */
3465 {
3466 while (*bufp++ == 'm') /* reply contains one or more TID */
3467 {
3468 do
3469 {
3470 ptid_t ptid = read_ptid (bufp, &bufp);
3471 context->items.emplace_back (ptid);
3472 }
3473 while (*bufp++ == ','); /* comma-separated list */
3474 putpkt ("qsThreadInfo");
3475 getpkt (&rs->buf, &rs->buf_size, 0);
3476 bufp = rs->buf;
3477 }
3478 return 1;
3479 }
3480 else
3481 {
3482 /* Packet not recognized. */
3483 rs->use_threadinfo_query = 0;
3484 }
3485 }
3486
3487 return 0;
3488 }
3489
3490 /* Implement the to_update_thread_list function for the remote
3491 targets. */
3492
3493 void
3494 remote_target::update_thread_list ()
3495 {
3496 struct threads_listing_context context;
3497 int got_list = 0;
3498
3499 /* We have a few different mechanisms to fetch the thread list. Try
3500 them all, starting with the most preferred one first, falling
3501 back to older methods. */
3502 if (remote_get_threads_with_qxfer (this, &context)
3503 || remote_get_threads_with_qthreadinfo (this, &context)
3504 || remote_get_threads_with_ql (this, &context))
3505 {
3506 struct thread_info *tp, *tmp;
3507
3508 got_list = 1;
3509
3510 if (context.items.empty ()
3511 && remote_thread_always_alive (inferior_ptid))
3512 {
3513 /* Some targets don't really support threads, but still
3514 reply an (empty) thread list in response to the thread
3515 listing packets, instead of replying "packet not
3516 supported". Exit early so we don't delete the main
3517 thread. */
3518 return;
3519 }
3520
3521 /* CONTEXT now holds the current thread list on the remote
3522 target end. Delete GDB-side threads no longer found on the
3523 target. */
3524 ALL_THREADS_SAFE (tp, tmp)
3525 {
3526 if (!context.contains_thread (tp->ptid))
3527 {
3528 /* Not found. */
3529 delete_thread (tp->ptid);
3530 }
3531 }
3532
3533 /* Remove any unreported fork child threads from CONTEXT so
3534 that we don't interfere with follow fork, which is where
3535 creation of such threads is handled. */
3536 remove_new_fork_children (&context);
3537
3538 /* And now add threads we don't know about yet to our list. */
3539 for (thread_item &item : context.items)
3540 {
3541 if (item.ptid != null_ptid)
3542 {
3543 /* In non-stop mode, we assume new found threads are
3544 executing until proven otherwise with a stop reply.
3545 In all-stop, we can only get here if all threads are
3546 stopped. */
3547 int executing = target_is_non_stop_p () ? 1 : 0;
3548
3549 remote_notice_new_inferior (item.ptid, executing);
3550
3551 remote_thread_info *info = get_remote_thread_info (item.ptid);
3552 info->core = item.core;
3553 info->extra = std::move (item.extra);
3554 info->name = std::move (item.name);
3555 info->thread_handle = std::move (item.thread_handle);
3556 }
3557 }
3558 }
3559
3560 if (!got_list)
3561 {
3562 /* If no thread listing method is supported, then query whether
3563 each known thread is alive, one by one, with the T packet.
3564 If the target doesn't support threads at all, then this is a
3565 no-op. See remote_thread_alive. */
3566 prune_threads ();
3567 }
3568 }
3569
3570 /*
3571 * Collect a descriptive string about the given thread.
3572 * The target may say anything it wants to about the thread
3573 * (typically info about its blocked / runnable state, name, etc.).
3574 * This string will appear in the info threads display.
3575 *
3576 * Optional: targets are not required to implement this function.
3577 */
3578
3579 const char *
3580 remote_target::extra_thread_info (thread_info *tp)
3581 {
3582 struct remote_state *rs = get_remote_state ();
3583 int result;
3584 int set;
3585 threadref id;
3586 struct gdb_ext_thread_info threadinfo;
3587 static char display_buf[100]; /* arbitrary... */
3588 int n = 0; /* position in display_buf */
3589
3590 if (rs->remote_desc == 0) /* paranoia */
3591 internal_error (__FILE__, __LINE__,
3592 _("remote_threads_extra_info"));
3593
3594 if (ptid_equal (tp->ptid, magic_null_ptid)
3595 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3596 /* This is the main thread which was added by GDB. The remote
3597 server doesn't know about it. */
3598 return NULL;
3599
3600 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3601 {
3602 struct thread_info *info = find_thread_ptid (tp->ptid);
3603
3604 if (info != NULL && info->priv != NULL)
3605 {
3606 const std::string &extra = get_remote_thread_info (info)->extra;
3607 return !extra.empty () ? extra.c_str () : NULL;
3608 }
3609 else
3610 return NULL;
3611 }
3612
3613 if (rs->use_threadextra_query)
3614 {
3615 char *b = rs->buf;
3616 char *endb = rs->buf + get_remote_packet_size ();
3617
3618 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3619 b += strlen (b);
3620 write_ptid (b, endb, tp->ptid);
3621
3622 putpkt (rs->buf);
3623 getpkt (&rs->buf, &rs->buf_size, 0);
3624 if (rs->buf[0] != 0)
3625 {
3626 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3627 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3628 display_buf [result] = '\0';
3629 return display_buf;
3630 }
3631 }
3632
3633 /* If the above query fails, fall back to the old method. */
3634 rs->use_threadextra_query = 0;
3635 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3636 | TAG_MOREDISPLAY | TAG_DISPLAY;
3637 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3638 if (remote_get_threadinfo (&id, set, &threadinfo))
3639 if (threadinfo.active)
3640 {
3641 if (*threadinfo.shortname)
3642 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3643 " Name: %s,", threadinfo.shortname);
3644 if (*threadinfo.display)
3645 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3646 " State: %s,", threadinfo.display);
3647 if (*threadinfo.more_display)
3648 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3649 " Priority: %s", threadinfo.more_display);
3650
3651 if (n > 0)
3652 {
3653 /* For purely cosmetic reasons, clear up trailing commas. */
3654 if (',' == display_buf[n-1])
3655 display_buf[n-1] = ' ';
3656 return display_buf;
3657 }
3658 }
3659 return NULL;
3660 }
3661 \f
3662
3663 bool
3664 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3665 struct static_tracepoint_marker *marker)
3666 {
3667 struct remote_state *rs = get_remote_state ();
3668 char *p = rs->buf;
3669
3670 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3671 p += strlen (p);
3672 p += hexnumstr (p, addr);
3673 putpkt (rs->buf);
3674 getpkt (&rs->buf, &rs->buf_size, 0);
3675 p = rs->buf;
3676
3677 if (*p == 'E')
3678 error (_("Remote failure reply: %s"), p);
3679
3680 if (*p++ == 'm')
3681 {
3682 parse_static_tracepoint_marker_definition (p, NULL, marker);
3683 return true;
3684 }
3685
3686 return false;
3687 }
3688
3689 std::vector<static_tracepoint_marker>
3690 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3691 {
3692 struct remote_state *rs = get_remote_state ();
3693 std::vector<static_tracepoint_marker> markers;
3694 const char *p;
3695 static_tracepoint_marker marker;
3696
3697 /* Ask for a first packet of static tracepoint marker
3698 definition. */
3699 putpkt ("qTfSTM");
3700 getpkt (&rs->buf, &rs->buf_size, 0);
3701 p = rs->buf;
3702 if (*p == 'E')
3703 error (_("Remote failure reply: %s"), p);
3704
3705 while (*p++ == 'm')
3706 {
3707 do
3708 {
3709 parse_static_tracepoint_marker_definition (p, &p, &marker);
3710
3711 if (strid == NULL || marker.str_id == strid)
3712 markers.push_back (std::move (marker));
3713 }
3714 while (*p++ == ','); /* comma-separated list */
3715 /* Ask for another packet of static tracepoint definition. */
3716 putpkt ("qTsSTM");
3717 getpkt (&rs->buf, &rs->buf_size, 0);
3718 p = rs->buf;
3719 }
3720
3721 return markers;
3722 }
3723
3724 \f
3725 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3726
3727 ptid_t
3728 remote_target::get_ada_task_ptid (long lwp, long thread)
3729 {
3730 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3731 }
3732 \f
3733
3734 /* Restart the remote side; this is an extended protocol operation. */
3735
3736 static void
3737 extended_remote_restart (void)
3738 {
3739 struct remote_state *rs = get_remote_state ();
3740
3741 /* Send the restart command; for reasons I don't understand the
3742 remote side really expects a number after the "R". */
3743 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3744 putpkt (rs->buf);
3745
3746 remote_fileio_reset ();
3747 }
3748 \f
3749 /* Clean up connection to a remote debugger. */
3750
3751 void
3752 remote_target::close ()
3753 {
3754 struct remote_state *rs = get_remote_state ();
3755
3756 if (rs->remote_desc == NULL)
3757 return; /* already closed */
3758
3759 /* Make sure we leave stdin registered in the event loop. */
3760 terminal_ours ();
3761
3762 serial_close (rs->remote_desc);
3763 rs->remote_desc = NULL;
3764
3765 /* We don't have a connection to the remote stub anymore. Get rid
3766 of all the inferiors and their threads we were controlling.
3767 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3768 will be unable to find the thread corresponding to (pid, 0, 0). */
3769 inferior_ptid = null_ptid;
3770 discard_all_inferiors ();
3771
3772 /* We are closing the remote target, so we should discard
3773 everything of this target. */
3774 discard_pending_stop_replies_in_queue (rs);
3775
3776 if (remote_async_inferior_event_token)
3777 delete_async_event_handler (&remote_async_inferior_event_token);
3778
3779 remote_notif_state_xfree (rs->notif_state);
3780
3781 trace_reset_local_state ();
3782 }
3783
3784 /* Query the remote side for the text, data and bss offsets. */
3785
3786 static void
3787 get_offsets (void)
3788 {
3789 struct remote_state *rs = get_remote_state ();
3790 char *buf;
3791 char *ptr;
3792 int lose, num_segments = 0, do_sections, do_segments;
3793 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3794 struct section_offsets *offs;
3795 struct symfile_segment_data *data;
3796
3797 if (symfile_objfile == NULL)
3798 return;
3799
3800 putpkt ("qOffsets");
3801 getpkt (&rs->buf, &rs->buf_size, 0);
3802 buf = rs->buf;
3803
3804 if (buf[0] == '\000')
3805 return; /* Return silently. Stub doesn't support
3806 this command. */
3807 if (buf[0] == 'E')
3808 {
3809 warning (_("Remote failure reply: %s"), buf);
3810 return;
3811 }
3812
3813 /* Pick up each field in turn. This used to be done with scanf, but
3814 scanf will make trouble if CORE_ADDR size doesn't match
3815 conversion directives correctly. The following code will work
3816 with any size of CORE_ADDR. */
3817 text_addr = data_addr = bss_addr = 0;
3818 ptr = buf;
3819 lose = 0;
3820
3821 if (startswith (ptr, "Text="))
3822 {
3823 ptr += 5;
3824 /* Don't use strtol, could lose on big values. */
3825 while (*ptr && *ptr != ';')
3826 text_addr = (text_addr << 4) + fromhex (*ptr++);
3827
3828 if (startswith (ptr, ";Data="))
3829 {
3830 ptr += 6;
3831 while (*ptr && *ptr != ';')
3832 data_addr = (data_addr << 4) + fromhex (*ptr++);
3833 }
3834 else
3835 lose = 1;
3836
3837 if (!lose && startswith (ptr, ";Bss="))
3838 {
3839 ptr += 5;
3840 while (*ptr && *ptr != ';')
3841 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3842
3843 if (bss_addr != data_addr)
3844 warning (_("Target reported unsupported offsets: %s"), buf);
3845 }
3846 else
3847 lose = 1;
3848 }
3849 else if (startswith (ptr, "TextSeg="))
3850 {
3851 ptr += 8;
3852 /* Don't use strtol, could lose on big values. */
3853 while (*ptr && *ptr != ';')
3854 text_addr = (text_addr << 4) + fromhex (*ptr++);
3855 num_segments = 1;
3856
3857 if (startswith (ptr, ";DataSeg="))
3858 {
3859 ptr += 9;
3860 while (*ptr && *ptr != ';')
3861 data_addr = (data_addr << 4) + fromhex (*ptr++);
3862 num_segments++;
3863 }
3864 }
3865 else
3866 lose = 1;
3867
3868 if (lose)
3869 error (_("Malformed response to offset query, %s"), buf);
3870 else if (*ptr != '\0')
3871 warning (_("Target reported unsupported offsets: %s"), buf);
3872
3873 offs = ((struct section_offsets *)
3874 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3875 memcpy (offs, symfile_objfile->section_offsets,
3876 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3877
3878 data = get_symfile_segment_data (symfile_objfile->obfd);
3879 do_segments = (data != NULL);
3880 do_sections = num_segments == 0;
3881
3882 if (num_segments > 0)
3883 {
3884 segments[0] = text_addr;
3885 segments[1] = data_addr;
3886 }
3887 /* If we have two segments, we can still try to relocate everything
3888 by assuming that the .text and .data offsets apply to the whole
3889 text and data segments. Convert the offsets given in the packet
3890 to base addresses for symfile_map_offsets_to_segments. */
3891 else if (data && data->num_segments == 2)
3892 {
3893 segments[0] = data->segment_bases[0] + text_addr;
3894 segments[1] = data->segment_bases[1] + data_addr;
3895 num_segments = 2;
3896 }
3897 /* If the object file has only one segment, assume that it is text
3898 rather than data; main programs with no writable data are rare,
3899 but programs with no code are useless. Of course the code might
3900 have ended up in the data segment... to detect that we would need
3901 the permissions here. */
3902 else if (data && data->num_segments == 1)
3903 {
3904 segments[0] = data->segment_bases[0] + text_addr;
3905 num_segments = 1;
3906 }
3907 /* There's no way to relocate by segment. */
3908 else
3909 do_segments = 0;
3910
3911 if (do_segments)
3912 {
3913 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3914 offs, num_segments, segments);
3915
3916 if (ret == 0 && !do_sections)
3917 error (_("Can not handle qOffsets TextSeg "
3918 "response with this symbol file"));
3919
3920 if (ret > 0)
3921 do_sections = 0;
3922 }
3923
3924 if (data)
3925 free_symfile_segment_data (data);
3926
3927 if (do_sections)
3928 {
3929 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3930
3931 /* This is a temporary kludge to force data and bss to use the
3932 same offsets because that's what nlmconv does now. The real
3933 solution requires changes to the stub and remote.c that I
3934 don't have time to do right now. */
3935
3936 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3937 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3938 }
3939
3940 objfile_relocate (symfile_objfile, offs);
3941 }
3942
3943 /* Send interrupt_sequence to remote target. */
3944 static void
3945 send_interrupt_sequence (void)
3946 {
3947 struct remote_state *rs = get_remote_state ();
3948
3949 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3950 remote_serial_write ("\x03", 1);
3951 else if (interrupt_sequence_mode == interrupt_sequence_break)
3952 serial_send_break (rs->remote_desc);
3953 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3954 {
3955 serial_send_break (rs->remote_desc);
3956 remote_serial_write ("g", 1);
3957 }
3958 else
3959 internal_error (__FILE__, __LINE__,
3960 _("Invalid value for interrupt_sequence_mode: %s."),
3961 interrupt_sequence_mode);
3962 }
3963
3964
3965 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3966 and extract the PTID. Returns NULL_PTID if not found. */
3967
3968 static ptid_t
3969 stop_reply_extract_thread (char *stop_reply)
3970 {
3971 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3972 {
3973 const char *p;
3974
3975 /* Txx r:val ; r:val (...) */
3976 p = &stop_reply[3];
3977
3978 /* Look for "register" named "thread". */
3979 while (*p != '\0')
3980 {
3981 const char *p1;
3982
3983 p1 = strchr (p, ':');
3984 if (p1 == NULL)
3985 return null_ptid;
3986
3987 if (strncmp (p, "thread", p1 - p) == 0)
3988 return read_ptid (++p1, &p);
3989
3990 p1 = strchr (p, ';');
3991 if (p1 == NULL)
3992 return null_ptid;
3993 p1++;
3994
3995 p = p1;
3996 }
3997 }
3998
3999 return null_ptid;
4000 }
4001
4002 /* Determine the remote side's current thread. If we have a stop
4003 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4004 "thread" register we can extract the current thread from. If not,
4005 ask the remote which is the current thread with qC. The former
4006 method avoids a roundtrip. */
4007
4008 static ptid_t
4009 get_current_thread (char *wait_status)
4010 {
4011 ptid_t ptid = null_ptid;
4012
4013 /* Note we don't use remote_parse_stop_reply as that makes use of
4014 the target architecture, which we haven't yet fully determined at
4015 this point. */
4016 if (wait_status != NULL)
4017 ptid = stop_reply_extract_thread (wait_status);
4018 if (ptid_equal (ptid, null_ptid))
4019 ptid = remote_current_thread (inferior_ptid);
4020
4021 return ptid;
4022 }
4023
4024 /* Query the remote target for which is the current thread/process,
4025 add it to our tables, and update INFERIOR_PTID. The caller is
4026 responsible for setting the state such that the remote end is ready
4027 to return the current thread.
4028
4029 This function is called after handling the '?' or 'vRun' packets,
4030 whose response is a stop reply from which we can also try
4031 extracting the thread. If the target doesn't support the explicit
4032 qC query, we infer the current thread from that stop reply, passed
4033 in in WAIT_STATUS, which may be NULL. */
4034
4035 static void
4036 add_current_inferior_and_thread (char *wait_status)
4037 {
4038 struct remote_state *rs = get_remote_state ();
4039 int fake_pid_p = 0;
4040
4041 inferior_ptid = null_ptid;
4042
4043 /* Now, if we have thread information, update inferior_ptid. */
4044 ptid_t curr_ptid = get_current_thread (wait_status);
4045
4046 if (curr_ptid != null_ptid)
4047 {
4048 if (!remote_multi_process_p (rs))
4049 fake_pid_p = 1;
4050 }
4051 else
4052 {
4053 /* Without this, some commands which require an active target
4054 (such as kill) won't work. This variable serves (at least)
4055 double duty as both the pid of the target process (if it has
4056 such), and as a flag indicating that a target is active. */
4057 curr_ptid = magic_null_ptid;
4058 fake_pid_p = 1;
4059 }
4060
4061 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
4062
4063 /* Add the main thread and switch to it. Don't try reading
4064 registers yet, since we haven't fetched the target description
4065 yet. */
4066 thread_info *tp = add_thread_silent (curr_ptid);
4067 switch_to_thread_no_regs (tp);
4068 }
4069
4070 /* Print info about a thread that was found already stopped on
4071 connection. */
4072
4073 static void
4074 print_one_stopped_thread (struct thread_info *thread)
4075 {
4076 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4077
4078 switch_to_thread (thread->ptid);
4079 stop_pc = get_frame_pc (get_current_frame ());
4080 set_current_sal_from_frame (get_current_frame ());
4081
4082 thread->suspend.waitstatus_pending_p = 0;
4083
4084 if (ws->kind == TARGET_WAITKIND_STOPPED)
4085 {
4086 enum gdb_signal sig = ws->value.sig;
4087
4088 if (signal_print_state (sig))
4089 gdb::observers::signal_received.notify (sig);
4090 }
4091 gdb::observers::normal_stop.notify (NULL, 1);
4092 }
4093
4094 /* Process all initial stop replies the remote side sent in response
4095 to the ? packet. These indicate threads that were already stopped
4096 on initial connection. We mark these threads as stopped and print
4097 their current frame before giving the user the prompt. */
4098
4099 static void
4100 process_initial_stop_replies (int from_tty)
4101 {
4102 int pending_stop_replies = stop_reply_queue_length ();
4103 struct inferior *inf;
4104 struct thread_info *thread;
4105 struct thread_info *selected = NULL;
4106 struct thread_info *lowest_stopped = NULL;
4107 struct thread_info *first = NULL;
4108
4109 /* Consume the initial pending events. */
4110 while (pending_stop_replies-- > 0)
4111 {
4112 ptid_t waiton_ptid = minus_one_ptid;
4113 ptid_t event_ptid;
4114 struct target_waitstatus ws;
4115 int ignore_event = 0;
4116 struct thread_info *thread;
4117
4118 memset (&ws, 0, sizeof (ws));
4119 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4120 if (remote_debug)
4121 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4122
4123 switch (ws.kind)
4124 {
4125 case TARGET_WAITKIND_IGNORE:
4126 case TARGET_WAITKIND_NO_RESUMED:
4127 case TARGET_WAITKIND_SIGNALLED:
4128 case TARGET_WAITKIND_EXITED:
4129 /* We shouldn't see these, but if we do, just ignore. */
4130 if (remote_debug)
4131 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4132 ignore_event = 1;
4133 break;
4134
4135 case TARGET_WAITKIND_EXECD:
4136 xfree (ws.value.execd_pathname);
4137 break;
4138 default:
4139 break;
4140 }
4141
4142 if (ignore_event)
4143 continue;
4144
4145 thread = find_thread_ptid (event_ptid);
4146
4147 if (ws.kind == TARGET_WAITKIND_STOPPED)
4148 {
4149 enum gdb_signal sig = ws.value.sig;
4150
4151 /* Stubs traditionally report SIGTRAP as initial signal,
4152 instead of signal 0. Suppress it. */
4153 if (sig == GDB_SIGNAL_TRAP)
4154 sig = GDB_SIGNAL_0;
4155 thread->suspend.stop_signal = sig;
4156 ws.value.sig = sig;
4157 }
4158
4159 thread->suspend.waitstatus = ws;
4160
4161 if (ws.kind != TARGET_WAITKIND_STOPPED
4162 || ws.value.sig != GDB_SIGNAL_0)
4163 thread->suspend.waitstatus_pending_p = 1;
4164
4165 set_executing (event_ptid, 0);
4166 set_running (event_ptid, 0);
4167 get_remote_thread_info (thread)->vcont_resumed = 0;
4168 }
4169
4170 /* "Notice" the new inferiors before anything related to
4171 registers/memory. */
4172 ALL_INFERIORS (inf)
4173 {
4174 if (inf->pid == 0)
4175 continue;
4176
4177 inf->needs_setup = 1;
4178
4179 if (non_stop)
4180 {
4181 thread = any_live_thread_of_process (inf->pid);
4182 notice_new_inferior (thread->ptid,
4183 thread->state == THREAD_RUNNING,
4184 from_tty);
4185 }
4186 }
4187
4188 /* If all-stop on top of non-stop, pause all threads. Note this
4189 records the threads' stop pc, so must be done after "noticing"
4190 the inferiors. */
4191 if (!non_stop)
4192 {
4193 stop_all_threads ();
4194
4195 /* If all threads of an inferior were already stopped, we
4196 haven't setup the inferior yet. */
4197 ALL_INFERIORS (inf)
4198 {
4199 if (inf->pid == 0)
4200 continue;
4201
4202 if (inf->needs_setup)
4203 {
4204 thread = any_live_thread_of_process (inf->pid);
4205 switch_to_thread_no_regs (thread);
4206 setup_inferior (0);
4207 }
4208 }
4209 }
4210
4211 /* Now go over all threads that are stopped, and print their current
4212 frame. If all-stop, then if there's a signalled thread, pick
4213 that as current. */
4214 ALL_NON_EXITED_THREADS (thread)
4215 {
4216 if (first == NULL)
4217 first = thread;
4218
4219 if (!non_stop)
4220 set_running (thread->ptid, 0);
4221 else if (thread->state != THREAD_STOPPED)
4222 continue;
4223
4224 if (selected == NULL
4225 && thread->suspend.waitstatus_pending_p)
4226 selected = thread;
4227
4228 if (lowest_stopped == NULL
4229 || thread->inf->num < lowest_stopped->inf->num
4230 || thread->per_inf_num < lowest_stopped->per_inf_num)
4231 lowest_stopped = thread;
4232
4233 if (non_stop)
4234 print_one_stopped_thread (thread);
4235 }
4236
4237 /* In all-stop, we only print the status of one thread, and leave
4238 others with their status pending. */
4239 if (!non_stop)
4240 {
4241 thread = selected;
4242 if (thread == NULL)
4243 thread = lowest_stopped;
4244 if (thread == NULL)
4245 thread = first;
4246
4247 print_one_stopped_thread (thread);
4248 }
4249
4250 /* For "info program". */
4251 thread = inferior_thread ();
4252 if (thread->state == THREAD_STOPPED)
4253 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4254 }
4255
4256 /* Start the remote connection and sync state. */
4257
4258 void
4259 remote_target::start_remote (int from_tty, int extended_p)
4260 {
4261 struct remote_state *rs = get_remote_state ();
4262 struct packet_config *noack_config;
4263 char *wait_status = NULL;
4264
4265 /* Signal other parts that we're going through the initial setup,
4266 and so things may not be stable yet. E.g., we don't try to
4267 install tracepoints until we've relocated symbols. Also, a
4268 Ctrl-C before we're connected and synced up can't interrupt the
4269 target. Instead, it offers to drop the (potentially wedged)
4270 connection. */
4271 rs->starting_up = 1;
4272
4273 QUIT;
4274
4275 if (interrupt_on_connect)
4276 send_interrupt_sequence ();
4277
4278 /* Ack any packet which the remote side has already sent. */
4279 remote_serial_write ("+", 1);
4280
4281 /* The first packet we send to the target is the optional "supported
4282 packets" request. If the target can answer this, it will tell us
4283 which later probes to skip. */
4284 remote_query_supported ();
4285
4286 /* If the stub wants to get a QAllow, compose one and send it. */
4287 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4288 set_permissions ();
4289
4290 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4291 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4292 as a reply to known packet. For packet "vFile:setfs:" it is an
4293 invalid reply and GDB would return error in
4294 remote_hostio_set_filesystem, making remote files access impossible.
4295 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4296 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4297 {
4298 const char v_mustreplyempty[] = "vMustReplyEmpty";
4299
4300 putpkt (v_mustreplyempty);
4301 getpkt (&rs->buf, &rs->buf_size, 0);
4302 if (strcmp (rs->buf, "OK") == 0)
4303 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4304 else if (strcmp (rs->buf, "") != 0)
4305 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4306 rs->buf);
4307 }
4308
4309 /* Next, we possibly activate noack mode.
4310
4311 If the QStartNoAckMode packet configuration is set to AUTO,
4312 enable noack mode if the stub reported a wish for it with
4313 qSupported.
4314
4315 If set to TRUE, then enable noack mode even if the stub didn't
4316 report it in qSupported. If the stub doesn't reply OK, the
4317 session ends with an error.
4318
4319 If FALSE, then don't activate noack mode, regardless of what the
4320 stub claimed should be the default with qSupported. */
4321
4322 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4323 if (packet_config_support (noack_config) != PACKET_DISABLE)
4324 {
4325 putpkt ("QStartNoAckMode");
4326 getpkt (&rs->buf, &rs->buf_size, 0);
4327 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4328 rs->noack_mode = 1;
4329 }
4330
4331 if (extended_p)
4332 {
4333 /* Tell the remote that we are using the extended protocol. */
4334 putpkt ("!");
4335 getpkt (&rs->buf, &rs->buf_size, 0);
4336 }
4337
4338 /* Let the target know which signals it is allowed to pass down to
4339 the program. */
4340 update_signals_program_target ();
4341
4342 /* Next, if the target can specify a description, read it. We do
4343 this before anything involving memory or registers. */
4344 target_find_description ();
4345
4346 /* Next, now that we know something about the target, update the
4347 address spaces in the program spaces. */
4348 update_address_spaces ();
4349
4350 /* On OSs where the list of libraries is global to all
4351 processes, we fetch them early. */
4352 if (gdbarch_has_global_solist (target_gdbarch ()))
4353 solib_add (NULL, from_tty, auto_solib_add);
4354
4355 if (target_is_non_stop_p ())
4356 {
4357 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4358 error (_("Non-stop mode requested, but remote "
4359 "does not support non-stop"));
4360
4361 putpkt ("QNonStop:1");
4362 getpkt (&rs->buf, &rs->buf_size, 0);
4363
4364 if (strcmp (rs->buf, "OK") != 0)
4365 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4366
4367 /* Find about threads and processes the stub is already
4368 controlling. We default to adding them in the running state.
4369 The '?' query below will then tell us about which threads are
4370 stopped. */
4371 this->update_thread_list ();
4372 }
4373 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4374 {
4375 /* Don't assume that the stub can operate in all-stop mode.
4376 Request it explicitly. */
4377 putpkt ("QNonStop:0");
4378 getpkt (&rs->buf, &rs->buf_size, 0);
4379
4380 if (strcmp (rs->buf, "OK") != 0)
4381 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4382 }
4383
4384 /* Upload TSVs regardless of whether the target is running or not. The
4385 remote stub, such as GDBserver, may have some predefined or builtin
4386 TSVs, even if the target is not running. */
4387 if (get_trace_status (current_trace_status ()) != -1)
4388 {
4389 struct uploaded_tsv *uploaded_tsvs = NULL;
4390
4391 upload_trace_state_variables (&uploaded_tsvs);
4392 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4393 }
4394
4395 /* Check whether the target is running now. */
4396 putpkt ("?");
4397 getpkt (&rs->buf, &rs->buf_size, 0);
4398
4399 if (!target_is_non_stop_p ())
4400 {
4401 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4402 {
4403 if (!extended_p)
4404 error (_("The target is not running (try extended-remote?)"));
4405
4406 /* We're connected, but not running. Drop out before we
4407 call start_remote. */
4408 rs->starting_up = 0;
4409 return;
4410 }
4411 else
4412 {
4413 /* Save the reply for later. */
4414 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4415 strcpy (wait_status, rs->buf);
4416 }
4417
4418 /* Fetch thread list. */
4419 target_update_thread_list ();
4420
4421 /* Let the stub know that we want it to return the thread. */
4422 set_continue_thread (minus_one_ptid);
4423
4424 if (thread_count () == 0)
4425 {
4426 /* Target has no concept of threads at all. GDB treats
4427 non-threaded target as single-threaded; add a main
4428 thread. */
4429 add_current_inferior_and_thread (wait_status);
4430 }
4431 else
4432 {
4433 /* We have thread information; select the thread the target
4434 says should be current. If we're reconnecting to a
4435 multi-threaded program, this will ideally be the thread
4436 that last reported an event before GDB disconnected. */
4437 inferior_ptid = get_current_thread (wait_status);
4438 if (ptid_equal (inferior_ptid, null_ptid))
4439 {
4440 /* Odd... The target was able to list threads, but not
4441 tell us which thread was current (no "thread"
4442 register in T stop reply?). Just pick the first
4443 thread in the thread list then. */
4444
4445 if (remote_debug)
4446 fprintf_unfiltered (gdb_stdlog,
4447 "warning: couldn't determine remote "
4448 "current thread; picking first in list.\n");
4449
4450 inferior_ptid = thread_list->ptid;
4451 }
4452 }
4453
4454 /* init_wait_for_inferior should be called before get_offsets in order
4455 to manage `inserted' flag in bp loc in a correct state.
4456 breakpoint_init_inferior, called from init_wait_for_inferior, set
4457 `inserted' flag to 0, while before breakpoint_re_set, called from
4458 start_remote, set `inserted' flag to 1. In the initialization of
4459 inferior, breakpoint_init_inferior should be called first, and then
4460 breakpoint_re_set can be called. If this order is broken, state of
4461 `inserted' flag is wrong, and cause some problems on breakpoint
4462 manipulation. */
4463 init_wait_for_inferior ();
4464
4465 get_offsets (); /* Get text, data & bss offsets. */
4466
4467 /* If we could not find a description using qXfer, and we know
4468 how to do it some other way, try again. This is not
4469 supported for non-stop; it could be, but it is tricky if
4470 there are no stopped threads when we connect. */
4471 if (remote_read_description_p (this)
4472 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4473 {
4474 target_clear_description ();
4475 target_find_description ();
4476 }
4477
4478 /* Use the previously fetched status. */
4479 gdb_assert (wait_status != NULL);
4480 strcpy (rs->buf, wait_status);
4481 rs->cached_wait_status = 1;
4482
4483 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4484 }
4485 else
4486 {
4487 /* Clear WFI global state. Do this before finding about new
4488 threads and inferiors, and setting the current inferior.
4489 Otherwise we would clear the proceed status of the current
4490 inferior when we want its stop_soon state to be preserved
4491 (see notice_new_inferior). */
4492 init_wait_for_inferior ();
4493
4494 /* In non-stop, we will either get an "OK", meaning that there
4495 are no stopped threads at this time; or, a regular stop
4496 reply. In the latter case, there may be more than one thread
4497 stopped --- we pull them all out using the vStopped
4498 mechanism. */
4499 if (strcmp (rs->buf, "OK") != 0)
4500 {
4501 struct notif_client *notif = &notif_client_stop;
4502
4503 /* remote_notif_get_pending_replies acks this one, and gets
4504 the rest out. */
4505 rs->notif_state->pending_event[notif_client_stop.id]
4506 = remote_notif_parse (notif, rs->buf);
4507 remote_notif_get_pending_events (notif);
4508 }
4509
4510 if (thread_count () == 0)
4511 {
4512 if (!extended_p)
4513 error (_("The target is not running (try extended-remote?)"));
4514
4515 /* We're connected, but not running. Drop out before we
4516 call start_remote. */
4517 rs->starting_up = 0;
4518 return;
4519 }
4520
4521 /* In non-stop mode, any cached wait status will be stored in
4522 the stop reply queue. */
4523 gdb_assert (wait_status == NULL);
4524
4525 /* Report all signals during attach/startup. */
4526 pass_signals (0, NULL);
4527
4528 /* If there are already stopped threads, mark them stopped and
4529 report their stops before giving the prompt to the user. */
4530 process_initial_stop_replies (from_tty);
4531
4532 if (target_can_async_p ())
4533 target_async (1);
4534 }
4535
4536 /* If we connected to a live target, do some additional setup. */
4537 if (target_has_execution)
4538 {
4539 if (symfile_objfile) /* No use without a symbol-file. */
4540 remote_check_symbols ();
4541 }
4542
4543 /* Possibly the target has been engaged in a trace run started
4544 previously; find out where things are at. */
4545 if (get_trace_status (current_trace_status ()) != -1)
4546 {
4547 struct uploaded_tp *uploaded_tps = NULL;
4548
4549 if (current_trace_status ()->running)
4550 printf_filtered (_("Trace is already running on the target.\n"));
4551
4552 upload_tracepoints (&uploaded_tps);
4553
4554 merge_uploaded_tracepoints (&uploaded_tps);
4555 }
4556
4557 /* Possibly the target has been engaged in a btrace record started
4558 previously; find out where things are at. */
4559 remote_btrace_maybe_reopen ();
4560
4561 /* The thread and inferior lists are now synchronized with the
4562 target, our symbols have been relocated, and we're merged the
4563 target's tracepoints with ours. We're done with basic start
4564 up. */
4565 rs->starting_up = 0;
4566
4567 /* Maybe breakpoints are global and need to be inserted now. */
4568 if (breakpoints_should_be_inserted_now ())
4569 insert_breakpoints ();
4570 }
4571
4572 /* Open a connection to a remote debugger.
4573 NAME is the filename used for communication. */
4574
4575 void
4576 remote_target::open (const char *name, int from_tty)
4577 {
4578 open_1 (name, from_tty, 0);
4579 }
4580
4581 /* Open a connection to a remote debugger using the extended
4582 remote gdb protocol. NAME is the filename used for communication. */
4583
4584 void
4585 extended_remote_target::open (const char *name, int from_tty)
4586 {
4587 open_1 (name, from_tty, 1 /*extended_p */);
4588 }
4589
4590 /* Reset all packets back to "unknown support". Called when opening a
4591 new connection to a remote target. */
4592
4593 static void
4594 reset_all_packet_configs_support (void)
4595 {
4596 int i;
4597
4598 for (i = 0; i < PACKET_MAX; i++)
4599 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4600 }
4601
4602 /* Initialize all packet configs. */
4603
4604 static void
4605 init_all_packet_configs (void)
4606 {
4607 int i;
4608
4609 for (i = 0; i < PACKET_MAX; i++)
4610 {
4611 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4612 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4613 }
4614 }
4615
4616 /* Symbol look-up. */
4617
4618 static void
4619 remote_check_symbols (void)
4620 {
4621 char *msg, *reply, *tmp;
4622 int end;
4623 long reply_size;
4624 struct cleanup *old_chain;
4625
4626 /* The remote side has no concept of inferiors that aren't running
4627 yet, it only knows about running processes. If we're connected
4628 but our current inferior is not running, we should not invite the
4629 remote target to request symbol lookups related to its
4630 (unrelated) current process. */
4631 if (!target_has_execution)
4632 return;
4633
4634 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4635 return;
4636
4637 /* Make sure the remote is pointing at the right process. Note
4638 there's no way to select "no process". */
4639 set_general_process ();
4640
4641 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4642 because we need both at the same time. */
4643 msg = (char *) xmalloc (get_remote_packet_size ());
4644 old_chain = make_cleanup (xfree, msg);
4645 reply = (char *) xmalloc (get_remote_packet_size ());
4646 make_cleanup (free_current_contents, &reply);
4647 reply_size = get_remote_packet_size ();
4648
4649 /* Invite target to request symbol lookups. */
4650
4651 putpkt ("qSymbol::");
4652 getpkt (&reply, &reply_size, 0);
4653 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4654
4655 while (startswith (reply, "qSymbol:"))
4656 {
4657 struct bound_minimal_symbol sym;
4658
4659 tmp = &reply[8];
4660 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4661 msg[end] = '\0';
4662 sym = lookup_minimal_symbol (msg, NULL, NULL);
4663 if (sym.minsym == NULL)
4664 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4665 else
4666 {
4667 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4668 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4669
4670 /* If this is a function address, return the start of code
4671 instead of any data function descriptor. */
4672 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4673 sym_addr,
4674 target_stack);
4675
4676 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4677 phex_nz (sym_addr, addr_size), &reply[8]);
4678 }
4679
4680 putpkt (msg);
4681 getpkt (&reply, &reply_size, 0);
4682 }
4683
4684 do_cleanups (old_chain);
4685 }
4686
4687 static struct serial *
4688 remote_serial_open (const char *name)
4689 {
4690 static int udp_warning = 0;
4691
4692 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4693 of in ser-tcp.c, because it is the remote protocol assuming that the
4694 serial connection is reliable and not the serial connection promising
4695 to be. */
4696 if (!udp_warning && startswith (name, "udp:"))
4697 {
4698 warning (_("The remote protocol may be unreliable over UDP.\n"
4699 "Some events may be lost, rendering further debugging "
4700 "impossible."));
4701 udp_warning = 1;
4702 }
4703
4704 return serial_open (name);
4705 }
4706
4707 /* Inform the target of our permission settings. The permission flags
4708 work without this, but if the target knows the settings, it can do
4709 a couple things. First, it can add its own check, to catch cases
4710 that somehow manage to get by the permissions checks in target
4711 methods. Second, if the target is wired to disallow particular
4712 settings (for instance, a system in the field that is not set up to
4713 be able to stop at a breakpoint), it can object to any unavailable
4714 permissions. */
4715
4716 void
4717 remote_target::set_permissions ()
4718 {
4719 struct remote_state *rs = get_remote_state ();
4720
4721 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4722 "WriteReg:%x;WriteMem:%x;"
4723 "InsertBreak:%x;InsertTrace:%x;"
4724 "InsertFastTrace:%x;Stop:%x",
4725 may_write_registers, may_write_memory,
4726 may_insert_breakpoints, may_insert_tracepoints,
4727 may_insert_fast_tracepoints, may_stop);
4728 putpkt (rs->buf);
4729 getpkt (&rs->buf, &rs->buf_size, 0);
4730
4731 /* If the target didn't like the packet, warn the user. Do not try
4732 to undo the user's settings, that would just be maddening. */
4733 if (strcmp (rs->buf, "OK") != 0)
4734 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4735 }
4736
4737 /* This type describes each known response to the qSupported
4738 packet. */
4739 struct protocol_feature
4740 {
4741 /* The name of this protocol feature. */
4742 const char *name;
4743
4744 /* The default for this protocol feature. */
4745 enum packet_support default_support;
4746
4747 /* The function to call when this feature is reported, or after
4748 qSupported processing if the feature is not supported.
4749 The first argument points to this structure. The second
4750 argument indicates whether the packet requested support be
4751 enabled, disabled, or probed (or the default, if this function
4752 is being called at the end of processing and this feature was
4753 not reported). The third argument may be NULL; if not NULL, it
4754 is a NUL-terminated string taken from the packet following
4755 this feature's name and an equals sign. */
4756 void (*func) (const struct protocol_feature *, enum packet_support,
4757 const char *);
4758
4759 /* The corresponding packet for this feature. Only used if
4760 FUNC is remote_supported_packet. */
4761 int packet;
4762 };
4763
4764 static void
4765 remote_supported_packet (const struct protocol_feature *feature,
4766 enum packet_support support,
4767 const char *argument)
4768 {
4769 if (argument)
4770 {
4771 warning (_("Remote qSupported response supplied an unexpected value for"
4772 " \"%s\"."), feature->name);
4773 return;
4774 }
4775
4776 remote_protocol_packets[feature->packet].support = support;
4777 }
4778
4779 static void
4780 remote_packet_size (const struct protocol_feature *feature,
4781 enum packet_support support, const char *value)
4782 {
4783 struct remote_state *rs = get_remote_state ();
4784
4785 int packet_size;
4786 char *value_end;
4787
4788 if (support != PACKET_ENABLE)
4789 return;
4790
4791 if (value == NULL || *value == '\0')
4792 {
4793 warning (_("Remote target reported \"%s\" without a size."),
4794 feature->name);
4795 return;
4796 }
4797
4798 errno = 0;
4799 packet_size = strtol (value, &value_end, 16);
4800 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4801 {
4802 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4803 feature->name, value);
4804 return;
4805 }
4806
4807 /* Record the new maximum packet size. */
4808 rs->explicit_packet_size = packet_size;
4809 }
4810
4811 static const struct protocol_feature remote_protocol_features[] = {
4812 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4813 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4814 PACKET_qXfer_auxv },
4815 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4816 PACKET_qXfer_exec_file },
4817 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4818 PACKET_qXfer_features },
4819 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4820 PACKET_qXfer_libraries },
4821 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4822 PACKET_qXfer_libraries_svr4 },
4823 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4824 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4825 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4826 PACKET_qXfer_memory_map },
4827 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4828 PACKET_qXfer_spu_read },
4829 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4830 PACKET_qXfer_spu_write },
4831 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4832 PACKET_qXfer_osdata },
4833 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4834 PACKET_qXfer_threads },
4835 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4836 PACKET_qXfer_traceframe_info },
4837 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4838 PACKET_QPassSignals },
4839 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4840 PACKET_QCatchSyscalls },
4841 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4842 PACKET_QProgramSignals },
4843 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4844 PACKET_QSetWorkingDir },
4845 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4846 PACKET_QStartupWithShell },
4847 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4848 PACKET_QEnvironmentHexEncoded },
4849 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4850 PACKET_QEnvironmentReset },
4851 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4852 PACKET_QEnvironmentUnset },
4853 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4854 PACKET_QStartNoAckMode },
4855 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4856 PACKET_multiprocess_feature },
4857 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4858 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4859 PACKET_qXfer_siginfo_read },
4860 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4861 PACKET_qXfer_siginfo_write },
4862 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4863 PACKET_ConditionalTracepoints },
4864 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4865 PACKET_ConditionalBreakpoints },
4866 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4867 PACKET_BreakpointCommands },
4868 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4869 PACKET_FastTracepoints },
4870 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4871 PACKET_StaticTracepoints },
4872 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4873 PACKET_InstallInTrace},
4874 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4875 PACKET_DisconnectedTracing_feature },
4876 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4877 PACKET_bc },
4878 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4879 PACKET_bs },
4880 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4881 PACKET_TracepointSource },
4882 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4883 PACKET_QAllow },
4884 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4885 PACKET_EnableDisableTracepoints_feature },
4886 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4887 PACKET_qXfer_fdpic },
4888 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4889 PACKET_qXfer_uib },
4890 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4891 PACKET_QDisableRandomization },
4892 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4893 { "QTBuffer:size", PACKET_DISABLE,
4894 remote_supported_packet, PACKET_QTBuffer_size},
4895 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4896 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4897 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4898 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4899 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4900 PACKET_qXfer_btrace },
4901 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4902 PACKET_qXfer_btrace_conf },
4903 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4904 PACKET_Qbtrace_conf_bts_size },
4905 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4906 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4907 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4908 PACKET_fork_event_feature },
4909 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4910 PACKET_vfork_event_feature },
4911 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4912 PACKET_exec_event_feature },
4913 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4914 PACKET_Qbtrace_conf_pt_size },
4915 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4916 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4917 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4918 };
4919
4920 static char *remote_support_xml;
4921
4922 /* Register string appended to "xmlRegisters=" in qSupported query. */
4923
4924 void
4925 register_remote_support_xml (const char *xml)
4926 {
4927 #if defined(HAVE_LIBEXPAT)
4928 if (remote_support_xml == NULL)
4929 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4930 else
4931 {
4932 char *copy = xstrdup (remote_support_xml + 13);
4933 char *p = strtok (copy, ",");
4934
4935 do
4936 {
4937 if (strcmp (p, xml) == 0)
4938 {
4939 /* already there */
4940 xfree (copy);
4941 return;
4942 }
4943 }
4944 while ((p = strtok (NULL, ",")) != NULL);
4945 xfree (copy);
4946
4947 remote_support_xml = reconcat (remote_support_xml,
4948 remote_support_xml, ",", xml,
4949 (char *) NULL);
4950 }
4951 #endif
4952 }
4953
4954 static char *
4955 remote_query_supported_append (char *msg, const char *append)
4956 {
4957 if (msg)
4958 return reconcat (msg, msg, ";", append, (char *) NULL);
4959 else
4960 return xstrdup (append);
4961 }
4962
4963 static void
4964 remote_query_supported (void)
4965 {
4966 struct remote_state *rs = get_remote_state ();
4967 char *next;
4968 int i;
4969 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4970
4971 /* The packet support flags are handled differently for this packet
4972 than for most others. We treat an error, a disabled packet, and
4973 an empty response identically: any features which must be reported
4974 to be used will be automatically disabled. An empty buffer
4975 accomplishes this, since that is also the representation for a list
4976 containing no features. */
4977
4978 rs->buf[0] = 0;
4979 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4980 {
4981 char *q = NULL;
4982 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4983
4984 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4985 q = remote_query_supported_append (q, "multiprocess+");
4986
4987 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4988 q = remote_query_supported_append (q, "swbreak+");
4989 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4990 q = remote_query_supported_append (q, "hwbreak+");
4991
4992 q = remote_query_supported_append (q, "qRelocInsn+");
4993
4994 if (packet_set_cmd_state (PACKET_fork_event_feature)
4995 != AUTO_BOOLEAN_FALSE)
4996 q = remote_query_supported_append (q, "fork-events+");
4997 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4998 != AUTO_BOOLEAN_FALSE)
4999 q = remote_query_supported_append (q, "vfork-events+");
5000 if (packet_set_cmd_state (PACKET_exec_event_feature)
5001 != AUTO_BOOLEAN_FALSE)
5002 q = remote_query_supported_append (q, "exec-events+");
5003
5004 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5005 q = remote_query_supported_append (q, "vContSupported+");
5006
5007 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5008 q = remote_query_supported_append (q, "QThreadEvents+");
5009
5010 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5011 q = remote_query_supported_append (q, "no-resumed+");
5012
5013 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5014 the qSupported:xmlRegisters=i386 handling. */
5015 if (remote_support_xml != NULL
5016 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5017 q = remote_query_supported_append (q, remote_support_xml);
5018
5019 q = reconcat (q, "qSupported:", q, (char *) NULL);
5020 putpkt (q);
5021
5022 do_cleanups (old_chain);
5023
5024 getpkt (&rs->buf, &rs->buf_size, 0);
5025
5026 /* If an error occured, warn, but do not return - just reset the
5027 buffer to empty and go on to disable features. */
5028 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5029 == PACKET_ERROR)
5030 {
5031 warning (_("Remote failure reply: %s"), rs->buf);
5032 rs->buf[0] = 0;
5033 }
5034 }
5035
5036 memset (seen, 0, sizeof (seen));
5037
5038 next = rs->buf;
5039 while (*next)
5040 {
5041 enum packet_support is_supported;
5042 char *p, *end, *name_end, *value;
5043
5044 /* First separate out this item from the rest of the packet. If
5045 there's another item after this, we overwrite the separator
5046 (terminated strings are much easier to work with). */
5047 p = next;
5048 end = strchr (p, ';');
5049 if (end == NULL)
5050 {
5051 end = p + strlen (p);
5052 next = end;
5053 }
5054 else
5055 {
5056 *end = '\0';
5057 next = end + 1;
5058
5059 if (end == p)
5060 {
5061 warning (_("empty item in \"qSupported\" response"));
5062 continue;
5063 }
5064 }
5065
5066 name_end = strchr (p, '=');
5067 if (name_end)
5068 {
5069 /* This is a name=value entry. */
5070 is_supported = PACKET_ENABLE;
5071 value = name_end + 1;
5072 *name_end = '\0';
5073 }
5074 else
5075 {
5076 value = NULL;
5077 switch (end[-1])
5078 {
5079 case '+':
5080 is_supported = PACKET_ENABLE;
5081 break;
5082
5083 case '-':
5084 is_supported = PACKET_DISABLE;
5085 break;
5086
5087 case '?':
5088 is_supported = PACKET_SUPPORT_UNKNOWN;
5089 break;
5090
5091 default:
5092 warning (_("unrecognized item \"%s\" "
5093 "in \"qSupported\" response"), p);
5094 continue;
5095 }
5096 end[-1] = '\0';
5097 }
5098
5099 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5100 if (strcmp (remote_protocol_features[i].name, p) == 0)
5101 {
5102 const struct protocol_feature *feature;
5103
5104 seen[i] = 1;
5105 feature = &remote_protocol_features[i];
5106 feature->func (feature, is_supported, value);
5107 break;
5108 }
5109 }
5110
5111 /* If we increased the packet size, make sure to increase the global
5112 buffer size also. We delay this until after parsing the entire
5113 qSupported packet, because this is the same buffer we were
5114 parsing. */
5115 if (rs->buf_size < rs->explicit_packet_size)
5116 {
5117 rs->buf_size = rs->explicit_packet_size;
5118 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5119 }
5120
5121 /* Handle the defaults for unmentioned features. */
5122 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5123 if (!seen[i])
5124 {
5125 const struct protocol_feature *feature;
5126
5127 feature = &remote_protocol_features[i];
5128 feature->func (feature, feature->default_support, NULL);
5129 }
5130 }
5131
5132 /* Serial QUIT handler for the remote serial descriptor.
5133
5134 Defers handling a Ctrl-C until we're done with the current
5135 command/response packet sequence, unless:
5136
5137 - We're setting up the connection. Don't send a remote interrupt
5138 request, as we're not fully synced yet. Quit immediately
5139 instead.
5140
5141 - The target has been resumed in the foreground
5142 (target_terminal::is_ours is false) with a synchronous resume
5143 packet, and we're blocked waiting for the stop reply, thus a
5144 Ctrl-C should be immediately sent to the target.
5145
5146 - We get a second Ctrl-C while still within the same serial read or
5147 write. In that case the serial is seemingly wedged --- offer to
5148 quit/disconnect.
5149
5150 - We see a second Ctrl-C without target response, after having
5151 previously interrupted the target. In that case the target/stub
5152 is probably wedged --- offer to quit/disconnect.
5153 */
5154
5155 static void
5156 remote_serial_quit_handler (void)
5157 {
5158 struct remote_state *rs = get_remote_state ();
5159
5160 if (check_quit_flag ())
5161 {
5162 /* If we're starting up, we're not fully synced yet. Quit
5163 immediately. */
5164 if (rs->starting_up)
5165 quit ();
5166 else if (rs->got_ctrlc_during_io)
5167 {
5168 if (query (_("The target is not responding to GDB commands.\n"
5169 "Stop debugging it? ")))
5170 remote_unpush_and_throw ();
5171 }
5172 /* If ^C has already been sent once, offer to disconnect. */
5173 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5174 interrupt_query ();
5175 /* All-stop protocol, and blocked waiting for stop reply. Send
5176 an interrupt request. */
5177 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5178 target_interrupt ();
5179 else
5180 rs->got_ctrlc_during_io = 1;
5181 }
5182 }
5183
5184 /* Remove any of the remote.c targets from target stack. Upper targets depend
5185 on it so remove them first. */
5186
5187 static void
5188 remote_unpush_target (void)
5189 {
5190 pop_all_targets_at_and_above (process_stratum);
5191 }
5192
5193 static void
5194 remote_unpush_and_throw (void)
5195 {
5196 remote_unpush_target ();
5197 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5198 }
5199
5200 void
5201 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5202 {
5203 struct remote_state *rs = get_remote_state ();
5204
5205 if (name == 0)
5206 error (_("To open a remote debug connection, you need to specify what\n"
5207 "serial device is attached to the remote system\n"
5208 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5209
5210 /* See FIXME above. */
5211 if (!target_async_permitted)
5212 wait_forever_enabled_p = 1;
5213
5214 /* If we're connected to a running target, target_preopen will kill it.
5215 Ask this question first, before target_preopen has a chance to kill
5216 anything. */
5217 if (rs->remote_desc != NULL && !have_inferiors ())
5218 {
5219 if (from_tty
5220 && !query (_("Already connected to a remote target. Disconnect? ")))
5221 error (_("Still connected."));
5222 }
5223
5224 /* Here the possibly existing remote target gets unpushed. */
5225 target_preopen (from_tty);
5226
5227 /* Make sure we send the passed signals list the next time we resume. */
5228 xfree (rs->last_pass_packet);
5229 rs->last_pass_packet = NULL;
5230
5231 /* Make sure we send the program signals list the next time we
5232 resume. */
5233 xfree (rs->last_program_signals_packet);
5234 rs->last_program_signals_packet = NULL;
5235
5236 remote_fileio_reset ();
5237 reopen_exec_file ();
5238 reread_symbols ();
5239
5240 rs->remote_desc = remote_serial_open (name);
5241 if (!rs->remote_desc)
5242 perror_with_name (name);
5243
5244 if (baud_rate != -1)
5245 {
5246 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5247 {
5248 /* The requested speed could not be set. Error out to
5249 top level after closing remote_desc. Take care to
5250 set remote_desc to NULL to avoid closing remote_desc
5251 more than once. */
5252 serial_close (rs->remote_desc);
5253 rs->remote_desc = NULL;
5254 perror_with_name (name);
5255 }
5256 }
5257
5258 serial_setparity (rs->remote_desc, serial_parity);
5259 serial_raw (rs->remote_desc);
5260
5261 /* If there is something sitting in the buffer we might take it as a
5262 response to a command, which would be bad. */
5263 serial_flush_input (rs->remote_desc);
5264
5265 if (from_tty)
5266 {
5267 puts_filtered ("Remote debugging using ");
5268 puts_filtered (name);
5269 puts_filtered ("\n");
5270 }
5271 push_target (this); /* Switch to using remote target now. */
5272
5273 /* Register extra event sources in the event loop. */
5274 remote_async_inferior_event_token
5275 = create_async_event_handler (remote_async_inferior_event_handler,
5276 NULL);
5277 rs->notif_state = remote_notif_state_allocate ();
5278
5279 /* Reset the target state; these things will be queried either by
5280 remote_query_supported or as they are needed. */
5281 reset_all_packet_configs_support ();
5282 rs->cached_wait_status = 0;
5283 rs->explicit_packet_size = 0;
5284 rs->noack_mode = 0;
5285 rs->extended = extended_p;
5286 rs->waiting_for_stop_reply = 0;
5287 rs->ctrlc_pending_p = 0;
5288 rs->got_ctrlc_during_io = 0;
5289
5290 rs->general_thread = not_sent_ptid;
5291 rs->continue_thread = not_sent_ptid;
5292 rs->remote_traceframe_number = -1;
5293
5294 rs->last_resume_exec_dir = EXEC_FORWARD;
5295
5296 /* Probe for ability to use "ThreadInfo" query, as required. */
5297 rs->use_threadinfo_query = 1;
5298 rs->use_threadextra_query = 1;
5299
5300 readahead_cache_invalidate ();
5301
5302 if (target_async_permitted)
5303 {
5304 /* FIXME: cagney/1999-09-23: During the initial connection it is
5305 assumed that the target is already ready and able to respond to
5306 requests. Unfortunately remote_start_remote() eventually calls
5307 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5308 around this. Eventually a mechanism that allows
5309 wait_for_inferior() to expect/get timeouts will be
5310 implemented. */
5311 wait_forever_enabled_p = 0;
5312 }
5313
5314 /* First delete any symbols previously loaded from shared libraries. */
5315 no_shared_libraries (NULL, 0);
5316
5317 /* Start afresh. */
5318 init_thread_list ();
5319
5320 /* Start the remote connection. If error() or QUIT, discard this
5321 target (we'd otherwise be in an inconsistent state) and then
5322 propogate the error on up the exception chain. This ensures that
5323 the caller doesn't stumble along blindly assuming that the
5324 function succeeded. The CLI doesn't have this problem but other
5325 UI's, such as MI do.
5326
5327 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5328 this function should return an error indication letting the
5329 caller restore the previous state. Unfortunately the command
5330 ``target remote'' is directly wired to this function making that
5331 impossible. On a positive note, the CLI side of this problem has
5332 been fixed - the function set_cmd_context() makes it possible for
5333 all the ``target ....'' commands to share a common callback
5334 function. See cli-dump.c. */
5335 {
5336
5337 TRY
5338 {
5339 start_remote (from_tty, extended_p);
5340 }
5341 CATCH (ex, RETURN_MASK_ALL)
5342 {
5343 /* Pop the partially set up target - unless something else did
5344 already before throwing the exception. */
5345 if (rs->remote_desc != NULL)
5346 remote_unpush_target ();
5347 if (target_async_permitted)
5348 wait_forever_enabled_p = 1;
5349 throw_exception (ex);
5350 }
5351 END_CATCH
5352 }
5353
5354 remote_btrace_reset ();
5355
5356 if (target_async_permitted)
5357 wait_forever_enabled_p = 1;
5358 }
5359
5360 /* Detach the specified process. */
5361
5362 static void
5363 remote_detach_pid (int pid)
5364 {
5365 struct remote_state *rs = get_remote_state ();
5366
5367 if (remote_multi_process_p (rs))
5368 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5369 else
5370 strcpy (rs->buf, "D");
5371
5372 putpkt (rs->buf);
5373 getpkt (&rs->buf, &rs->buf_size, 0);
5374
5375 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5376 ;
5377 else if (rs->buf[0] == '\0')
5378 error (_("Remote doesn't know how to detach"));
5379 else
5380 error (_("Can't detach process."));
5381 }
5382
5383 /* This detaches a program to which we previously attached, using
5384 inferior_ptid to identify the process. After this is done, GDB
5385 can be used to debug some other program. We better not have left
5386 any breakpoints in the target program or it'll die when it hits
5387 one. */
5388
5389 static void
5390 remote_detach_1 (int from_tty, inferior *inf)
5391 {
5392 int pid = ptid_get_pid (inferior_ptid);
5393 struct remote_state *rs = get_remote_state ();
5394 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5395 int is_fork_parent;
5396
5397 if (!target_has_execution)
5398 error (_("No process to detach from."));
5399
5400 target_announce_detach (from_tty);
5401
5402 /* Tell the remote target to detach. */
5403 remote_detach_pid (pid);
5404
5405 /* Exit only if this is the only active inferior. */
5406 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5407 puts_filtered (_("Ending remote debugging.\n"));
5408
5409 /* Check to see if we are detaching a fork parent. Note that if we
5410 are detaching a fork child, tp == NULL. */
5411 is_fork_parent = (tp != NULL
5412 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5413
5414 /* If doing detach-on-fork, we don't mourn, because that will delete
5415 breakpoints that should be available for the followed inferior. */
5416 if (!is_fork_parent)
5417 {
5418 /* Save the pid as a string before mourning, since that will
5419 unpush the remote target, and we need the string after. */
5420 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5421
5422 target_mourn_inferior (inferior_ptid);
5423 if (print_inferior_events)
5424 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5425 inf->num, infpid.c_str ());
5426 }
5427 else
5428 {
5429 inferior_ptid = null_ptid;
5430 detach_inferior (pid);
5431 }
5432 }
5433
5434 void
5435 remote_target::detach (inferior *inf, int from_tty)
5436 {
5437 remote_detach_1 (from_tty, inf);
5438 }
5439
5440 void
5441 extended_remote_target::detach (inferior *inf, int from_tty)
5442 {
5443 remote_detach_1 (from_tty, inf);
5444 }
5445
5446 /* Target follow-fork function for remote targets. On entry, and
5447 at return, the current inferior is the fork parent.
5448
5449 Note that although this is currently only used for extended-remote,
5450 it is named remote_follow_fork in anticipation of using it for the
5451 remote target as well. */
5452
5453 int
5454 remote_target::follow_fork (int follow_child, int detach_fork)
5455 {
5456 struct remote_state *rs = get_remote_state ();
5457 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5458
5459 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5460 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5461 {
5462 /* When following the parent and detaching the child, we detach
5463 the child here. For the case of following the child and
5464 detaching the parent, the detach is done in the target-
5465 independent follow fork code in infrun.c. We can't use
5466 target_detach when detaching an unfollowed child because
5467 the client side doesn't know anything about the child. */
5468 if (detach_fork && !follow_child)
5469 {
5470 /* Detach the fork child. */
5471 ptid_t child_ptid;
5472 pid_t child_pid;
5473
5474 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5475 child_pid = ptid_get_pid (child_ptid);
5476
5477 remote_detach_pid (child_pid);
5478 }
5479 }
5480 return 0;
5481 }
5482
5483 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5484 in the program space of the new inferior. On entry and at return the
5485 current inferior is the exec'ing inferior. INF is the new exec'd
5486 inferior, which may be the same as the exec'ing inferior unless
5487 follow-exec-mode is "new". */
5488
5489 void
5490 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5491 {
5492 /* We know that this is a target file name, so if it has the "target:"
5493 prefix we strip it off before saving it in the program space. */
5494 if (is_target_filename (execd_pathname))
5495 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5496
5497 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5498 }
5499
5500 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5501
5502 void
5503 remote_target::disconnect (const char *args, int from_tty)
5504 {
5505 if (args)
5506 error (_("Argument given to \"disconnect\" when remotely debugging."));
5507
5508 /* Make sure we unpush even the extended remote targets. Calling
5509 target_mourn_inferior won't unpush, and remote_mourn won't
5510 unpush if there is more than one inferior left. */
5511 unpush_target (this);
5512 generic_mourn_inferior ();
5513
5514 if (from_tty)
5515 puts_filtered ("Ending remote debugging.\n");
5516 }
5517
5518 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5519 be chatty about it. */
5520
5521 void
5522 extended_remote_target::attach (const char *args, int from_tty)
5523 {
5524 struct remote_state *rs = get_remote_state ();
5525 int pid;
5526 char *wait_status = NULL;
5527
5528 pid = parse_pid_to_attach (args);
5529
5530 /* Remote PID can be freely equal to getpid, do not check it here the same
5531 way as in other targets. */
5532
5533 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5534 error (_("This target does not support attaching to a process"));
5535
5536 if (from_tty)
5537 {
5538 char *exec_file = get_exec_file (0);
5539
5540 if (exec_file)
5541 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5542 target_pid_to_str (pid_to_ptid (pid)));
5543 else
5544 printf_unfiltered (_("Attaching to %s\n"),
5545 target_pid_to_str (pid_to_ptid (pid)));
5546
5547 gdb_flush (gdb_stdout);
5548 }
5549
5550 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5551 putpkt (rs->buf);
5552 getpkt (&rs->buf, &rs->buf_size, 0);
5553
5554 switch (packet_ok (rs->buf,
5555 &remote_protocol_packets[PACKET_vAttach]))
5556 {
5557 case PACKET_OK:
5558 if (!target_is_non_stop_p ())
5559 {
5560 /* Save the reply for later. */
5561 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5562 strcpy (wait_status, rs->buf);
5563 }
5564 else if (strcmp (rs->buf, "OK") != 0)
5565 error (_("Attaching to %s failed with: %s"),
5566 target_pid_to_str (pid_to_ptid (pid)),
5567 rs->buf);
5568 break;
5569 case PACKET_UNKNOWN:
5570 error (_("This target does not support attaching to a process"));
5571 default:
5572 error (_("Attaching to %s failed"),
5573 target_pid_to_str (pid_to_ptid (pid)));
5574 }
5575
5576 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5577
5578 inferior_ptid = pid_to_ptid (pid);
5579
5580 if (target_is_non_stop_p ())
5581 {
5582 struct thread_info *thread;
5583
5584 /* Get list of threads. */
5585 update_thread_list ();
5586
5587 thread = first_thread_of_process (pid);
5588 if (thread)
5589 inferior_ptid = thread->ptid;
5590 else
5591 inferior_ptid = pid_to_ptid (pid);
5592
5593 /* Invalidate our notion of the remote current thread. */
5594 record_currthread (rs, minus_one_ptid);
5595 }
5596 else
5597 {
5598 /* Now, if we have thread information, update inferior_ptid. */
5599 inferior_ptid = remote_current_thread (inferior_ptid);
5600
5601 /* Add the main thread to the thread list. */
5602 thread_info *thr = add_thread_silent (inferior_ptid);
5603 /* Don't consider the thread stopped until we've processed the
5604 saved stop reply. */
5605 set_executing (thr->ptid, true);
5606 }
5607
5608 /* Next, if the target can specify a description, read it. We do
5609 this before anything involving memory or registers. */
5610 target_find_description ();
5611
5612 if (!target_is_non_stop_p ())
5613 {
5614 /* Use the previously fetched status. */
5615 gdb_assert (wait_status != NULL);
5616
5617 if (target_can_async_p ())
5618 {
5619 struct notif_event *reply
5620 = remote_notif_parse (&notif_client_stop, wait_status);
5621
5622 push_stop_reply ((struct stop_reply *) reply);
5623
5624 target_async (1);
5625 }
5626 else
5627 {
5628 gdb_assert (wait_status != NULL);
5629 strcpy (rs->buf, wait_status);
5630 rs->cached_wait_status = 1;
5631 }
5632 }
5633 else
5634 gdb_assert (wait_status == NULL);
5635 }
5636
5637 /* Implementation of the to_post_attach method. */
5638
5639 void
5640 extended_remote_target::post_attach (int pid)
5641 {
5642 /* Get text, data & bss offsets. */
5643 get_offsets ();
5644
5645 /* In certain cases GDB might not have had the chance to start
5646 symbol lookup up until now. This could happen if the debugged
5647 binary is not using shared libraries, the vsyscall page is not
5648 present (on Linux) and the binary itself hadn't changed since the
5649 debugging process was started. */
5650 if (symfile_objfile != NULL)
5651 remote_check_symbols();
5652 }
5653
5654 \f
5655 /* Check for the availability of vCont. This function should also check
5656 the response. */
5657
5658 static void
5659 remote_vcont_probe (struct remote_state *rs)
5660 {
5661 char *buf;
5662
5663 strcpy (rs->buf, "vCont?");
5664 putpkt (rs->buf);
5665 getpkt (&rs->buf, &rs->buf_size, 0);
5666 buf = rs->buf;
5667
5668 /* Make sure that the features we assume are supported. */
5669 if (startswith (buf, "vCont"))
5670 {
5671 char *p = &buf[5];
5672 int support_c, support_C;
5673
5674 rs->supports_vCont.s = 0;
5675 rs->supports_vCont.S = 0;
5676 support_c = 0;
5677 support_C = 0;
5678 rs->supports_vCont.t = 0;
5679 rs->supports_vCont.r = 0;
5680 while (p && *p == ';')
5681 {
5682 p++;
5683 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5684 rs->supports_vCont.s = 1;
5685 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5686 rs->supports_vCont.S = 1;
5687 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5688 support_c = 1;
5689 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5690 support_C = 1;
5691 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5692 rs->supports_vCont.t = 1;
5693 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5694 rs->supports_vCont.r = 1;
5695
5696 p = strchr (p, ';');
5697 }
5698
5699 /* If c, and C are not all supported, we can't use vCont. Clearing
5700 BUF will make packet_ok disable the packet. */
5701 if (!support_c || !support_C)
5702 buf[0] = 0;
5703 }
5704
5705 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5706 }
5707
5708 /* Helper function for building "vCont" resumptions. Write a
5709 resumption to P. ENDP points to one-passed-the-end of the buffer
5710 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5711 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5712 resumed thread should be single-stepped and/or signalled. If PTID
5713 equals minus_one_ptid, then all threads are resumed; if PTID
5714 represents a process, then all threads of the process are resumed;
5715 the thread to be stepped and/or signalled is given in the global
5716 INFERIOR_PTID. */
5717
5718 static char *
5719 append_resumption (char *p, char *endp,
5720 ptid_t ptid, int step, enum gdb_signal siggnal)
5721 {
5722 struct remote_state *rs = get_remote_state ();
5723
5724 if (step && siggnal != GDB_SIGNAL_0)
5725 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5726 else if (step
5727 /* GDB is willing to range step. */
5728 && use_range_stepping
5729 /* Target supports range stepping. */
5730 && rs->supports_vCont.r
5731 /* We don't currently support range stepping multiple
5732 threads with a wildcard (though the protocol allows it,
5733 so stubs shouldn't make an active effort to forbid
5734 it). */
5735 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5736 {
5737 struct thread_info *tp;
5738
5739 if (ptid_equal (ptid, minus_one_ptid))
5740 {
5741 /* If we don't know about the target thread's tid, then
5742 we're resuming magic_null_ptid (see caller). */
5743 tp = find_thread_ptid (magic_null_ptid);
5744 }
5745 else
5746 tp = find_thread_ptid (ptid);
5747 gdb_assert (tp != NULL);
5748
5749 if (tp->control.may_range_step)
5750 {
5751 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5752
5753 p += xsnprintf (p, endp - p, ";r%s,%s",
5754 phex_nz (tp->control.step_range_start,
5755 addr_size),
5756 phex_nz (tp->control.step_range_end,
5757 addr_size));
5758 }
5759 else
5760 p += xsnprintf (p, endp - p, ";s");
5761 }
5762 else if (step)
5763 p += xsnprintf (p, endp - p, ";s");
5764 else if (siggnal != GDB_SIGNAL_0)
5765 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5766 else
5767 p += xsnprintf (p, endp - p, ";c");
5768
5769 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5770 {
5771 ptid_t nptid;
5772
5773 /* All (-1) threads of process. */
5774 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5775
5776 p += xsnprintf (p, endp - p, ":");
5777 p = write_ptid (p, endp, nptid);
5778 }
5779 else if (!ptid_equal (ptid, minus_one_ptid))
5780 {
5781 p += xsnprintf (p, endp - p, ":");
5782 p = write_ptid (p, endp, ptid);
5783 }
5784
5785 return p;
5786 }
5787
5788 /* Clear the thread's private info on resume. */
5789
5790 static void
5791 resume_clear_thread_private_info (struct thread_info *thread)
5792 {
5793 if (thread->priv != NULL)
5794 {
5795 remote_thread_info *priv = get_remote_thread_info (thread);
5796
5797 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5798 priv->watch_data_address = 0;
5799 }
5800 }
5801
5802 /* Append a vCont continue-with-signal action for threads that have a
5803 non-zero stop signal. */
5804
5805 static char *
5806 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5807 {
5808 struct thread_info *thread;
5809
5810 ALL_NON_EXITED_THREADS (thread)
5811 if (ptid_match (thread->ptid, ptid)
5812 && !ptid_equal (inferior_ptid, thread->ptid)
5813 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5814 {
5815 p = append_resumption (p, endp, thread->ptid,
5816 0, thread->suspend.stop_signal);
5817 thread->suspend.stop_signal = GDB_SIGNAL_0;
5818 resume_clear_thread_private_info (thread);
5819 }
5820
5821 return p;
5822 }
5823
5824 /* Set the target running, using the packets that use Hc
5825 (c/s/C/S). */
5826
5827 static void
5828 remote_resume_with_hc (struct target_ops *ops,
5829 ptid_t ptid, int step, enum gdb_signal siggnal)
5830 {
5831 struct remote_state *rs = get_remote_state ();
5832 struct thread_info *thread;
5833 char *buf;
5834
5835 rs->last_sent_signal = siggnal;
5836 rs->last_sent_step = step;
5837
5838 /* The c/s/C/S resume packets use Hc, so set the continue
5839 thread. */
5840 if (ptid_equal (ptid, minus_one_ptid))
5841 set_continue_thread (any_thread_ptid);
5842 else
5843 set_continue_thread (ptid);
5844
5845 ALL_NON_EXITED_THREADS (thread)
5846 resume_clear_thread_private_info (thread);
5847
5848 buf = rs->buf;
5849 if (execution_direction == EXEC_REVERSE)
5850 {
5851 /* We don't pass signals to the target in reverse exec mode. */
5852 if (info_verbose && siggnal != GDB_SIGNAL_0)
5853 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5854 siggnal);
5855
5856 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5857 error (_("Remote reverse-step not supported."));
5858 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5859 error (_("Remote reverse-continue not supported."));
5860
5861 strcpy (buf, step ? "bs" : "bc");
5862 }
5863 else if (siggnal != GDB_SIGNAL_0)
5864 {
5865 buf[0] = step ? 'S' : 'C';
5866 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5867 buf[2] = tohex (((int) siggnal) & 0xf);
5868 buf[3] = '\0';
5869 }
5870 else
5871 strcpy (buf, step ? "s" : "c");
5872
5873 putpkt (buf);
5874 }
5875
5876 /* Resume the remote inferior by using a "vCont" packet. The thread
5877 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5878 resumed thread should be single-stepped and/or signalled. If PTID
5879 equals minus_one_ptid, then all threads are resumed; the thread to
5880 be stepped and/or signalled is given in the global INFERIOR_PTID.
5881 This function returns non-zero iff it resumes the inferior.
5882
5883 This function issues a strict subset of all possible vCont commands
5884 at the moment. */
5885
5886 static int
5887 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5888 {
5889 struct remote_state *rs = get_remote_state ();
5890 char *p;
5891 char *endp;
5892
5893 /* No reverse execution actions defined for vCont. */
5894 if (execution_direction == EXEC_REVERSE)
5895 return 0;
5896
5897 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5898 remote_vcont_probe (rs);
5899
5900 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5901 return 0;
5902
5903 p = rs->buf;
5904 endp = rs->buf + get_remote_packet_size ();
5905
5906 /* If we could generate a wider range of packets, we'd have to worry
5907 about overflowing BUF. Should there be a generic
5908 "multi-part-packet" packet? */
5909
5910 p += xsnprintf (p, endp - p, "vCont");
5911
5912 if (ptid_equal (ptid, magic_null_ptid))
5913 {
5914 /* MAGIC_NULL_PTID means that we don't have any active threads,
5915 so we don't have any TID numbers the inferior will
5916 understand. Make sure to only send forms that do not specify
5917 a TID. */
5918 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5919 }
5920 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5921 {
5922 /* Resume all threads (of all processes, or of a single
5923 process), with preference for INFERIOR_PTID. This assumes
5924 inferior_ptid belongs to the set of all threads we are about
5925 to resume. */
5926 if (step || siggnal != GDB_SIGNAL_0)
5927 {
5928 /* Step inferior_ptid, with or without signal. */
5929 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5930 }
5931
5932 /* Also pass down any pending signaled resumption for other
5933 threads not the current. */
5934 p = append_pending_thread_resumptions (p, endp, ptid);
5935
5936 /* And continue others without a signal. */
5937 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5938 }
5939 else
5940 {
5941 /* Scheduler locking; resume only PTID. */
5942 append_resumption (p, endp, ptid, step, siggnal);
5943 }
5944
5945 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5946 putpkt (rs->buf);
5947
5948 if (target_is_non_stop_p ())
5949 {
5950 /* In non-stop, the stub replies to vCont with "OK". The stop
5951 reply will be reported asynchronously by means of a `%Stop'
5952 notification. */
5953 getpkt (&rs->buf, &rs->buf_size, 0);
5954 if (strcmp (rs->buf, "OK") != 0)
5955 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5956 }
5957
5958 return 1;
5959 }
5960
5961 /* Tell the remote machine to resume. */
5962
5963 void
5964 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5965 {
5966 struct remote_state *rs = get_remote_state ();
5967
5968 /* When connected in non-stop mode, the core resumes threads
5969 individually. Resuming remote threads directly in target_resume
5970 would thus result in sending one packet per thread. Instead, to
5971 minimize roundtrip latency, here we just store the resume
5972 request; the actual remote resumption will be done in
5973 target_commit_resume / remote_commit_resume, where we'll be able
5974 to do vCont action coalescing. */
5975 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
5976 {
5977 remote_thread_info *remote_thr;
5978
5979 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5980 remote_thr = get_remote_thread_info (inferior_ptid);
5981 else
5982 remote_thr = get_remote_thread_info (ptid);
5983
5984 remote_thr->last_resume_step = step;
5985 remote_thr->last_resume_sig = siggnal;
5986 return;
5987 }
5988
5989 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5990 (explained in remote-notif.c:handle_notification) so
5991 remote_notif_process is not called. We need find a place where
5992 it is safe to start a 'vNotif' sequence. It is good to do it
5993 before resuming inferior, because inferior was stopped and no RSP
5994 traffic at that moment. */
5995 if (!target_is_non_stop_p ())
5996 remote_notif_process (rs->notif_state, &notif_client_stop);
5997
5998 rs->last_resume_exec_dir = ::execution_direction;
5999
6000 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6001 if (!remote_resume_with_vcont (ptid, step, siggnal))
6002 remote_resume_with_hc (this, ptid, step, siggnal);
6003
6004 /* We are about to start executing the inferior, let's register it
6005 with the event loop. NOTE: this is the one place where all the
6006 execution commands end up. We could alternatively do this in each
6007 of the execution commands in infcmd.c. */
6008 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6009 into infcmd.c in order to allow inferior function calls to work
6010 NOT asynchronously. */
6011 if (target_can_async_p ())
6012 target_async (1);
6013
6014 /* We've just told the target to resume. The remote server will
6015 wait for the inferior to stop, and then send a stop reply. In
6016 the mean time, we can't start another command/query ourselves
6017 because the stub wouldn't be ready to process it. This applies
6018 only to the base all-stop protocol, however. In non-stop (which
6019 only supports vCont), the stub replies with an "OK", and is
6020 immediate able to process further serial input. */
6021 if (!target_is_non_stop_p ())
6022 rs->waiting_for_stop_reply = 1;
6023 }
6024
6025 static void check_pending_events_prevent_wildcard_vcont
6026 (int *may_global_wildcard_vcont);
6027 static int is_pending_fork_parent_thread (struct thread_info *thread);
6028
6029 /* Private per-inferior info for target remote processes. */
6030
6031 struct remote_inferior : public private_inferior
6032 {
6033 /* Whether we can send a wildcard vCont for this process. */
6034 bool may_wildcard_vcont = true;
6035 };
6036
6037 /* Get the remote private inferior data associated to INF. */
6038
6039 static remote_inferior *
6040 get_remote_inferior (inferior *inf)
6041 {
6042 if (inf->priv == NULL)
6043 inf->priv.reset (new remote_inferior);
6044
6045 return static_cast<remote_inferior *> (inf->priv.get ());
6046 }
6047
6048 /* Structure used to track the construction of a vCont packet in the
6049 outgoing packet buffer. This is used to send multiple vCont
6050 packets if we have more actions than would fit a single packet. */
6051
6052 struct vcont_builder
6053 {
6054 /* Pointer to the first action. P points here if no action has been
6055 appended yet. */
6056 char *first_action;
6057
6058 /* Where the next action will be appended. */
6059 char *p;
6060
6061 /* The end of the buffer. Must never write past this. */
6062 char *endp;
6063 };
6064
6065 /* Prepare the outgoing buffer for a new vCont packet. */
6066
6067 static void
6068 vcont_builder_restart (struct vcont_builder *builder)
6069 {
6070 struct remote_state *rs = get_remote_state ();
6071
6072 builder->p = rs->buf;
6073 builder->endp = rs->buf + get_remote_packet_size ();
6074 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
6075 builder->first_action = builder->p;
6076 }
6077
6078 /* If the vCont packet being built has any action, send it to the
6079 remote end. */
6080
6081 static void
6082 vcont_builder_flush (struct vcont_builder *builder)
6083 {
6084 struct remote_state *rs;
6085
6086 if (builder->p == builder->first_action)
6087 return;
6088
6089 rs = get_remote_state ();
6090 putpkt (rs->buf);
6091 getpkt (&rs->buf, &rs->buf_size, 0);
6092 if (strcmp (rs->buf, "OK") != 0)
6093 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6094 }
6095
6096 /* The largest action is range-stepping, with its two addresses. This
6097 is more than sufficient. If a new, bigger action is created, it'll
6098 quickly trigger a failed assertion in append_resumption (and we'll
6099 just bump this). */
6100 #define MAX_ACTION_SIZE 200
6101
6102 /* Append a new vCont action in the outgoing packet being built. If
6103 the action doesn't fit the packet along with previous actions, push
6104 what we've got so far to the remote end and start over a new vCont
6105 packet (with the new action). */
6106
6107 static void
6108 vcont_builder_push_action (struct vcont_builder *builder,
6109 ptid_t ptid, int step, enum gdb_signal siggnal)
6110 {
6111 char buf[MAX_ACTION_SIZE + 1];
6112 char *endp;
6113 size_t rsize;
6114
6115 endp = append_resumption (buf, buf + sizeof (buf),
6116 ptid, step, siggnal);
6117
6118 /* Check whether this new action would fit in the vCont packet along
6119 with previous actions. If not, send what we've got so far and
6120 start a new vCont packet. */
6121 rsize = endp - buf;
6122 if (rsize > builder->endp - builder->p)
6123 {
6124 vcont_builder_flush (builder);
6125 vcont_builder_restart (builder);
6126
6127 /* Should now fit. */
6128 gdb_assert (rsize <= builder->endp - builder->p);
6129 }
6130
6131 memcpy (builder->p, buf, rsize);
6132 builder->p += rsize;
6133 *builder->p = '\0';
6134 }
6135
6136 /* to_commit_resume implementation. */
6137
6138 void
6139 remote_target::commit_resume ()
6140 {
6141 struct inferior *inf;
6142 struct thread_info *tp;
6143 int any_process_wildcard;
6144 int may_global_wildcard_vcont;
6145 struct vcont_builder vcont_builder;
6146
6147 /* If connected in all-stop mode, we'd send the remote resume
6148 request directly from remote_resume. Likewise if
6149 reverse-debugging, as there are no defined vCont actions for
6150 reverse execution. */
6151 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6152 return;
6153
6154 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6155 instead of resuming all threads of each process individually.
6156 However, if any thread of a process must remain halted, we can't
6157 send wildcard resumes and must send one action per thread.
6158
6159 Care must be taken to not resume threads/processes the server
6160 side already told us are stopped, but the core doesn't know about
6161 yet, because the events are still in the vStopped notification
6162 queue. For example:
6163
6164 #1 => vCont s:p1.1;c
6165 #2 <= OK
6166 #3 <= %Stopped T05 p1.1
6167 #4 => vStopped
6168 #5 <= T05 p1.2
6169 #6 => vStopped
6170 #7 <= OK
6171 #8 (infrun handles the stop for p1.1 and continues stepping)
6172 #9 => vCont s:p1.1;c
6173
6174 The last vCont above would resume thread p1.2 by mistake, because
6175 the server has no idea that the event for p1.2 had not been
6176 handled yet.
6177
6178 The server side must similarly ignore resume actions for the
6179 thread that has a pending %Stopped notification (and any other
6180 threads with events pending), until GDB acks the notification
6181 with vStopped. Otherwise, e.g., the following case is
6182 mishandled:
6183
6184 #1 => g (or any other packet)
6185 #2 <= [registers]
6186 #3 <= %Stopped T05 p1.2
6187 #4 => vCont s:p1.1;c
6188 #5 <= OK
6189
6190 Above, the server must not resume thread p1.2. GDB can't know
6191 that p1.2 stopped until it acks the %Stopped notification, and
6192 since from GDB's perspective all threads should be running, it
6193 sends a "c" action.
6194
6195 Finally, special care must also be given to handling fork/vfork
6196 events. A (v)fork event actually tells us that two processes
6197 stopped -- the parent and the child. Until we follow the fork,
6198 we must not resume the child. Therefore, if we have a pending
6199 fork follow, we must not send a global wildcard resume action
6200 (vCont;c). We can still send process-wide wildcards though. */
6201
6202 /* Start by assuming a global wildcard (vCont;c) is possible. */
6203 may_global_wildcard_vcont = 1;
6204
6205 /* And assume every process is individually wildcard-able too. */
6206 ALL_NON_EXITED_INFERIORS (inf)
6207 {
6208 remote_inferior *priv = get_remote_inferior (inf);
6209
6210 priv->may_wildcard_vcont = true;
6211 }
6212
6213 /* Check for any pending events (not reported or processed yet) and
6214 disable process and global wildcard resumes appropriately. */
6215 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6216
6217 ALL_NON_EXITED_THREADS (tp)
6218 {
6219 /* If a thread of a process is not meant to be resumed, then we
6220 can't wildcard that process. */
6221 if (!tp->executing)
6222 {
6223 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6224
6225 /* And if we can't wildcard a process, we can't wildcard
6226 everything either. */
6227 may_global_wildcard_vcont = 0;
6228 continue;
6229 }
6230
6231 /* If a thread is the parent of an unfollowed fork, then we
6232 can't do a global wildcard, as that would resume the fork
6233 child. */
6234 if (is_pending_fork_parent_thread (tp))
6235 may_global_wildcard_vcont = 0;
6236 }
6237
6238 /* Now let's build the vCont packet(s). Actions must be appended
6239 from narrower to wider scopes (thread -> process -> global). If
6240 we end up with too many actions for a single packet vcont_builder
6241 flushes the current vCont packet to the remote side and starts a
6242 new one. */
6243 vcont_builder_restart (&vcont_builder);
6244
6245 /* Threads first. */
6246 ALL_NON_EXITED_THREADS (tp)
6247 {
6248 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6249
6250 if (!tp->executing || remote_thr->vcont_resumed)
6251 continue;
6252
6253 gdb_assert (!thread_is_in_step_over_chain (tp));
6254
6255 if (!remote_thr->last_resume_step
6256 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6257 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6258 {
6259 /* We'll send a wildcard resume instead. */
6260 remote_thr->vcont_resumed = 1;
6261 continue;
6262 }
6263
6264 vcont_builder_push_action (&vcont_builder, tp->ptid,
6265 remote_thr->last_resume_step,
6266 remote_thr->last_resume_sig);
6267 remote_thr->vcont_resumed = 1;
6268 }
6269
6270 /* Now check whether we can send any process-wide wildcard. This is
6271 to avoid sending a global wildcard in the case nothing is
6272 supposed to be resumed. */
6273 any_process_wildcard = 0;
6274
6275 ALL_NON_EXITED_INFERIORS (inf)
6276 {
6277 if (get_remote_inferior (inf)->may_wildcard_vcont)
6278 {
6279 any_process_wildcard = 1;
6280 break;
6281 }
6282 }
6283
6284 if (any_process_wildcard)
6285 {
6286 /* If all processes are wildcard-able, then send a single "c"
6287 action, otherwise, send an "all (-1) threads of process"
6288 continue action for each running process, if any. */
6289 if (may_global_wildcard_vcont)
6290 {
6291 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6292 0, GDB_SIGNAL_0);
6293 }
6294 else
6295 {
6296 ALL_NON_EXITED_INFERIORS (inf)
6297 {
6298 if (get_remote_inferior (inf)->may_wildcard_vcont)
6299 {
6300 vcont_builder_push_action (&vcont_builder,
6301 pid_to_ptid (inf->pid),
6302 0, GDB_SIGNAL_0);
6303 }
6304 }
6305 }
6306 }
6307
6308 vcont_builder_flush (&vcont_builder);
6309 }
6310
6311 \f
6312
6313 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6314 thread, all threads of a remote process, or all threads of all
6315 processes. */
6316
6317 static void
6318 remote_stop_ns (ptid_t ptid)
6319 {
6320 struct remote_state *rs = get_remote_state ();
6321 char *p = rs->buf;
6322 char *endp = rs->buf + get_remote_packet_size ();
6323
6324 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6325 remote_vcont_probe (rs);
6326
6327 if (!rs->supports_vCont.t)
6328 error (_("Remote server does not support stopping threads"));
6329
6330 if (ptid_equal (ptid, minus_one_ptid)
6331 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6332 p += xsnprintf (p, endp - p, "vCont;t");
6333 else
6334 {
6335 ptid_t nptid;
6336
6337 p += xsnprintf (p, endp - p, "vCont;t:");
6338
6339 if (ptid_is_pid (ptid))
6340 /* All (-1) threads of process. */
6341 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6342 else
6343 {
6344 /* Small optimization: if we already have a stop reply for
6345 this thread, no use in telling the stub we want this
6346 stopped. */
6347 if (peek_stop_reply (ptid))
6348 return;
6349
6350 nptid = ptid;
6351 }
6352
6353 write_ptid (p, endp, nptid);
6354 }
6355
6356 /* In non-stop, we get an immediate OK reply. The stop reply will
6357 come in asynchronously by notification. */
6358 putpkt (rs->buf);
6359 getpkt (&rs->buf, &rs->buf_size, 0);
6360 if (strcmp (rs->buf, "OK") != 0)
6361 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6362 }
6363
6364 /* All-stop version of target_interrupt. Sends a break or a ^C to
6365 interrupt the remote target. It is undefined which thread of which
6366 process reports the interrupt. */
6367
6368 static void
6369 remote_interrupt_as (void)
6370 {
6371 struct remote_state *rs = get_remote_state ();
6372
6373 rs->ctrlc_pending_p = 1;
6374
6375 /* If the inferior is stopped already, but the core didn't know
6376 about it yet, just ignore the request. The cached wait status
6377 will be collected in remote_wait. */
6378 if (rs->cached_wait_status)
6379 return;
6380
6381 /* Send interrupt_sequence to remote target. */
6382 send_interrupt_sequence ();
6383 }
6384
6385 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6386 the remote target. It is undefined which thread of which process
6387 reports the interrupt. Throws an error if the packet is not
6388 supported by the server. */
6389
6390 static void
6391 remote_interrupt_ns (void)
6392 {
6393 struct remote_state *rs = get_remote_state ();
6394 char *p = rs->buf;
6395 char *endp = rs->buf + get_remote_packet_size ();
6396
6397 xsnprintf (p, endp - p, "vCtrlC");
6398
6399 /* In non-stop, we get an immediate OK reply. The stop reply will
6400 come in asynchronously by notification. */
6401 putpkt (rs->buf);
6402 getpkt (&rs->buf, &rs->buf_size, 0);
6403
6404 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6405 {
6406 case PACKET_OK:
6407 break;
6408 case PACKET_UNKNOWN:
6409 error (_("No support for interrupting the remote target."));
6410 case PACKET_ERROR:
6411 error (_("Interrupting target failed: %s"), rs->buf);
6412 }
6413 }
6414
6415 /* Implement the to_stop function for the remote targets. */
6416
6417 void
6418 remote_target::stop (ptid_t ptid)
6419 {
6420 if (remote_debug)
6421 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6422
6423 if (target_is_non_stop_p ())
6424 remote_stop_ns (ptid);
6425 else
6426 {
6427 /* We don't currently have a way to transparently pause the
6428 remote target in all-stop mode. Interrupt it instead. */
6429 remote_interrupt_as ();
6430 }
6431 }
6432
6433 /* Implement the to_interrupt function for the remote targets. */
6434
6435 void
6436 remote_target::interrupt ()
6437 {
6438 if (remote_debug)
6439 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6440
6441 if (target_is_non_stop_p ())
6442 remote_interrupt_ns ();
6443 else
6444 remote_interrupt_as ();
6445 }
6446
6447 /* Implement the to_pass_ctrlc function for the remote targets. */
6448
6449 void
6450 remote_target::pass_ctrlc ()
6451 {
6452 struct remote_state *rs = get_remote_state ();
6453
6454 if (remote_debug)
6455 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6456
6457 /* If we're starting up, we're not fully synced yet. Quit
6458 immediately. */
6459 if (rs->starting_up)
6460 quit ();
6461 /* If ^C has already been sent once, offer to disconnect. */
6462 else if (rs->ctrlc_pending_p)
6463 interrupt_query ();
6464 else
6465 target_interrupt ();
6466 }
6467
6468 /* Ask the user what to do when an interrupt is received. */
6469
6470 static void
6471 interrupt_query (void)
6472 {
6473 struct remote_state *rs = get_remote_state ();
6474
6475 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6476 {
6477 if (query (_("The target is not responding to interrupt requests.\n"
6478 "Stop debugging it? ")))
6479 {
6480 remote_unpush_target ();
6481 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6482 }
6483 }
6484 else
6485 {
6486 if (query (_("Interrupted while waiting for the program.\n"
6487 "Give up waiting? ")))
6488 quit ();
6489 }
6490 }
6491
6492 /* Enable/disable target terminal ownership. Most targets can use
6493 terminal groups to control terminal ownership. Remote targets are
6494 different in that explicit transfer of ownership to/from GDB/target
6495 is required. */
6496
6497 void
6498 remote_target::terminal_inferior ()
6499 {
6500 /* NOTE: At this point we could also register our selves as the
6501 recipient of all input. Any characters typed could then be
6502 passed on down to the target. */
6503 }
6504
6505 void
6506 remote_target::terminal_ours ()
6507 {
6508 }
6509
6510 static void
6511 remote_console_output (char *msg)
6512 {
6513 char *p;
6514
6515 for (p = msg; p[0] && p[1]; p += 2)
6516 {
6517 char tb[2];
6518 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6519
6520 tb[0] = c;
6521 tb[1] = 0;
6522 fputs_unfiltered (tb, gdb_stdtarg);
6523 }
6524 gdb_flush (gdb_stdtarg);
6525 }
6526
6527 DEF_VEC_O(cached_reg_t);
6528
6529 typedef struct stop_reply
6530 {
6531 struct notif_event base;
6532
6533 /* The identifier of the thread about this event */
6534 ptid_t ptid;
6535
6536 /* The remote state this event is associated with. When the remote
6537 connection, represented by a remote_state object, is closed,
6538 all the associated stop_reply events should be released. */
6539 struct remote_state *rs;
6540
6541 struct target_waitstatus ws;
6542
6543 /* The architecture associated with the expedited registers. */
6544 gdbarch *arch;
6545
6546 /* Expedited registers. This makes remote debugging a bit more
6547 efficient for those targets that provide critical registers as
6548 part of their normal status mechanism (as another roundtrip to
6549 fetch them is avoided). */
6550 VEC(cached_reg_t) *regcache;
6551
6552 enum target_stop_reason stop_reason;
6553
6554 CORE_ADDR watch_data_address;
6555
6556 int core;
6557 } *stop_reply_p;
6558
6559 DECLARE_QUEUE_P (stop_reply_p);
6560 DEFINE_QUEUE_P (stop_reply_p);
6561 /* The list of already fetched and acknowledged stop events. This
6562 queue is used for notification Stop, and other notifications
6563 don't need queue for their events, because the notification events
6564 of Stop can't be consumed immediately, so that events should be
6565 queued first, and be consumed by remote_wait_{ns,as} one per
6566 time. Other notifications can consume their events immediately,
6567 so queue is not needed for them. */
6568 static QUEUE (stop_reply_p) *stop_reply_queue;
6569
6570 static void
6571 stop_reply_xfree (struct stop_reply *r)
6572 {
6573 notif_event_xfree ((struct notif_event *) r);
6574 }
6575
6576 /* Return the length of the stop reply queue. */
6577
6578 static int
6579 stop_reply_queue_length (void)
6580 {
6581 return QUEUE_length (stop_reply_p, stop_reply_queue);
6582 }
6583
6584 static void
6585 remote_notif_stop_parse (struct notif_client *self, char *buf,
6586 struct notif_event *event)
6587 {
6588 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6589 }
6590
6591 static void
6592 remote_notif_stop_ack (struct notif_client *self, char *buf,
6593 struct notif_event *event)
6594 {
6595 struct stop_reply *stop_reply = (struct stop_reply *) event;
6596
6597 /* acknowledge */
6598 putpkt (self->ack_command);
6599
6600 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6601 /* We got an unknown stop reply. */
6602 error (_("Unknown stop reply"));
6603
6604 push_stop_reply (stop_reply);
6605 }
6606
6607 static int
6608 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6609 {
6610 /* We can't get pending events in remote_notif_process for
6611 notification stop, and we have to do this in remote_wait_ns
6612 instead. If we fetch all queued events from stub, remote stub
6613 may exit and we have no chance to process them back in
6614 remote_wait_ns. */
6615 mark_async_event_handler (remote_async_inferior_event_token);
6616 return 0;
6617 }
6618
6619 static void
6620 stop_reply_dtr (struct notif_event *event)
6621 {
6622 struct stop_reply *r = (struct stop_reply *) event;
6623 cached_reg_t *reg;
6624 int ix;
6625
6626 for (ix = 0;
6627 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6628 ix++)
6629 xfree (reg->data);
6630
6631 VEC_free (cached_reg_t, r->regcache);
6632 }
6633
6634 static struct notif_event *
6635 remote_notif_stop_alloc_reply (void)
6636 {
6637 /* We cast to a pointer to the "base class". */
6638 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6639
6640 r->dtr = stop_reply_dtr;
6641
6642 return r;
6643 }
6644
6645 /* A client of notification Stop. */
6646
6647 struct notif_client notif_client_stop =
6648 {
6649 "Stop",
6650 "vStopped",
6651 remote_notif_stop_parse,
6652 remote_notif_stop_ack,
6653 remote_notif_stop_can_get_pending_events,
6654 remote_notif_stop_alloc_reply,
6655 REMOTE_NOTIF_STOP,
6656 };
6657
6658 /* A parameter to pass data in and out. */
6659
6660 struct queue_iter_param
6661 {
6662 void *input;
6663 struct stop_reply *output;
6664 };
6665
6666 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6667 the pid of the process that owns the threads we want to check, or
6668 -1 if we want to check all threads. */
6669
6670 static int
6671 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6672 ptid_t thread_ptid)
6673 {
6674 if (ws->kind == TARGET_WAITKIND_FORKED
6675 || ws->kind == TARGET_WAITKIND_VFORKED)
6676 {
6677 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6678 return 1;
6679 }
6680
6681 return 0;
6682 }
6683
6684 /* Return the thread's pending status used to determine whether the
6685 thread is a fork parent stopped at a fork event. */
6686
6687 static struct target_waitstatus *
6688 thread_pending_fork_status (struct thread_info *thread)
6689 {
6690 if (thread->suspend.waitstatus_pending_p)
6691 return &thread->suspend.waitstatus;
6692 else
6693 return &thread->pending_follow;
6694 }
6695
6696 /* Determine if THREAD is a pending fork parent thread. */
6697
6698 static int
6699 is_pending_fork_parent_thread (struct thread_info *thread)
6700 {
6701 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6702 int pid = -1;
6703
6704 return is_pending_fork_parent (ws, pid, thread->ptid);
6705 }
6706
6707 /* Check whether EVENT is a fork event, and if it is, remove the
6708 fork child from the context list passed in DATA. */
6709
6710 static int
6711 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6712 QUEUE_ITER (stop_reply_p) *iter,
6713 stop_reply_p event,
6714 void *data)
6715 {
6716 struct queue_iter_param *param = (struct queue_iter_param *) data;
6717 struct threads_listing_context *context
6718 = (struct threads_listing_context *) param->input;
6719
6720 if (event->ws.kind == TARGET_WAITKIND_FORKED
6721 || event->ws.kind == TARGET_WAITKIND_VFORKED
6722 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6723 context->remove_thread (event->ws.value.related_pid);
6724
6725 return 1;
6726 }
6727
6728 /* If CONTEXT contains any fork child threads that have not been
6729 reported yet, remove them from the CONTEXT list. If such a
6730 thread exists it is because we are stopped at a fork catchpoint
6731 and have not yet called follow_fork, which will set up the
6732 host-side data structures for the new process. */
6733
6734 static void
6735 remove_new_fork_children (struct threads_listing_context *context)
6736 {
6737 struct thread_info * thread;
6738 int pid = -1;
6739 struct notif_client *notif = &notif_client_stop;
6740 struct queue_iter_param param;
6741
6742 /* For any threads stopped at a fork event, remove the corresponding
6743 fork child threads from the CONTEXT list. */
6744 ALL_NON_EXITED_THREADS (thread)
6745 {
6746 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6747
6748 if (is_pending_fork_parent (ws, pid, thread->ptid))
6749 context->remove_thread (ws->value.related_pid);
6750 }
6751
6752 /* Check for any pending fork events (not reported or processed yet)
6753 in process PID and remove those fork child threads from the
6754 CONTEXT list as well. */
6755 remote_notif_get_pending_events (notif);
6756 param.input = context;
6757 param.output = NULL;
6758 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6759 remove_child_of_pending_fork, &param);
6760 }
6761
6762 /* Check whether EVENT would prevent a global or process wildcard
6763 vCont action. */
6764
6765 static int
6766 check_pending_event_prevents_wildcard_vcont_callback
6767 (QUEUE (stop_reply_p) *q,
6768 QUEUE_ITER (stop_reply_p) *iter,
6769 stop_reply_p event,
6770 void *data)
6771 {
6772 struct inferior *inf;
6773 int *may_global_wildcard_vcont = (int *) data;
6774
6775 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6776 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6777 return 1;
6778
6779 if (event->ws.kind == TARGET_WAITKIND_FORKED
6780 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6781 *may_global_wildcard_vcont = 0;
6782
6783 inf = find_inferior_ptid (event->ptid);
6784
6785 /* This may be the first time we heard about this process.
6786 Regardless, we must not do a global wildcard resume, otherwise
6787 we'd resume this process too. */
6788 *may_global_wildcard_vcont = 0;
6789 if (inf != NULL)
6790 get_remote_inferior (inf)->may_wildcard_vcont = false;
6791
6792 return 1;
6793 }
6794
6795 /* Check whether any event pending in the vStopped queue would prevent
6796 a global or process wildcard vCont action. Clear
6797 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6798 and clear the event inferior's may_wildcard_vcont flag if we can't
6799 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6800
6801 static void
6802 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6803 {
6804 struct notif_client *notif = &notif_client_stop;
6805
6806 remote_notif_get_pending_events (notif);
6807 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6808 check_pending_event_prevents_wildcard_vcont_callback,
6809 may_global_wildcard);
6810 }
6811
6812 /* Remove stop replies in the queue if its pid is equal to the given
6813 inferior's pid. */
6814
6815 static int
6816 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6817 QUEUE_ITER (stop_reply_p) *iter,
6818 stop_reply_p event,
6819 void *data)
6820 {
6821 struct queue_iter_param *param = (struct queue_iter_param *) data;
6822 struct inferior *inf = (struct inferior *) param->input;
6823
6824 if (ptid_get_pid (event->ptid) == inf->pid)
6825 {
6826 stop_reply_xfree (event);
6827 QUEUE_remove_elem (stop_reply_p, q, iter);
6828 }
6829
6830 return 1;
6831 }
6832
6833 /* Discard all pending stop replies of inferior INF. */
6834
6835 static void
6836 discard_pending_stop_replies (struct inferior *inf)
6837 {
6838 struct queue_iter_param param;
6839 struct stop_reply *reply;
6840 struct remote_state *rs = get_remote_state ();
6841 struct remote_notif_state *rns = rs->notif_state;
6842
6843 /* This function can be notified when an inferior exists. When the
6844 target is not remote, the notification state is NULL. */
6845 if (rs->remote_desc == NULL)
6846 return;
6847
6848 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6849
6850 /* Discard the in-flight notification. */
6851 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6852 {
6853 stop_reply_xfree (reply);
6854 rns->pending_event[notif_client_stop.id] = NULL;
6855 }
6856
6857 param.input = inf;
6858 param.output = NULL;
6859 /* Discard the stop replies we have already pulled with
6860 vStopped. */
6861 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6862 remove_stop_reply_for_inferior, &param);
6863 }
6864
6865 /* If its remote state is equal to the given remote state,
6866 remove EVENT from the stop reply queue. */
6867
6868 static int
6869 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6870 QUEUE_ITER (stop_reply_p) *iter,
6871 stop_reply_p event,
6872 void *data)
6873 {
6874 struct queue_iter_param *param = (struct queue_iter_param *) data;
6875 struct remote_state *rs = (struct remote_state *) param->input;
6876
6877 if (event->rs == rs)
6878 {
6879 stop_reply_xfree (event);
6880 QUEUE_remove_elem (stop_reply_p, q, iter);
6881 }
6882
6883 return 1;
6884 }
6885
6886 /* Discard the stop replies for RS in stop_reply_queue. */
6887
6888 static void
6889 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6890 {
6891 struct queue_iter_param param;
6892
6893 param.input = rs;
6894 param.output = NULL;
6895 /* Discard the stop replies we have already pulled with
6896 vStopped. */
6897 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6898 remove_stop_reply_of_remote_state, &param);
6899 }
6900
6901 /* A parameter to pass data in and out. */
6902
6903 static int
6904 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6905 QUEUE_ITER (stop_reply_p) *iter,
6906 stop_reply_p event,
6907 void *data)
6908 {
6909 struct queue_iter_param *param = (struct queue_iter_param *) data;
6910 ptid_t *ptid = (ptid_t *) param->input;
6911
6912 if (ptid_match (event->ptid, *ptid))
6913 {
6914 param->output = event;
6915 QUEUE_remove_elem (stop_reply_p, q, iter);
6916 return 0;
6917 }
6918
6919 return 1;
6920 }
6921
6922 /* Remove the first reply in 'stop_reply_queue' which matches
6923 PTID. */
6924
6925 static struct stop_reply *
6926 remote_notif_remove_queued_reply (ptid_t ptid)
6927 {
6928 struct queue_iter_param param;
6929
6930 param.input = &ptid;
6931 param.output = NULL;
6932
6933 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6934 remote_notif_remove_once_on_match, &param);
6935 if (notif_debug)
6936 fprintf_unfiltered (gdb_stdlog,
6937 "notif: discard queued event: 'Stop' in %s\n",
6938 target_pid_to_str (ptid));
6939
6940 return param.output;
6941 }
6942
6943 /* Look for a queued stop reply belonging to PTID. If one is found,
6944 remove it from the queue, and return it. Returns NULL if none is
6945 found. If there are still queued events left to process, tell the
6946 event loop to get back to target_wait soon. */
6947
6948 static struct stop_reply *
6949 queued_stop_reply (ptid_t ptid)
6950 {
6951 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6952
6953 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6954 /* There's still at least an event left. */
6955 mark_async_event_handler (remote_async_inferior_event_token);
6956
6957 return r;
6958 }
6959
6960 /* Push a fully parsed stop reply in the stop reply queue. Since we
6961 know that we now have at least one queued event left to pass to the
6962 core side, tell the event loop to get back to target_wait soon. */
6963
6964 static void
6965 push_stop_reply (struct stop_reply *new_event)
6966 {
6967 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6968
6969 if (notif_debug)
6970 fprintf_unfiltered (gdb_stdlog,
6971 "notif: push 'Stop' %s to queue %d\n",
6972 target_pid_to_str (new_event->ptid),
6973 QUEUE_length (stop_reply_p,
6974 stop_reply_queue));
6975
6976 mark_async_event_handler (remote_async_inferior_event_token);
6977 }
6978
6979 static int
6980 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6981 QUEUE_ITER (stop_reply_p) *iter,
6982 struct stop_reply *event,
6983 void *data)
6984 {
6985 ptid_t *ptid = (ptid_t *) data;
6986
6987 return !(ptid_equal (*ptid, event->ptid)
6988 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6989 }
6990
6991 /* Returns true if we have a stop reply for PTID. */
6992
6993 static int
6994 peek_stop_reply (ptid_t ptid)
6995 {
6996 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6997 stop_reply_match_ptid_and_ws, &ptid);
6998 }
6999
7000 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7001 starting with P and ending with PEND matches PREFIX. */
7002
7003 static int
7004 strprefix (const char *p, const char *pend, const char *prefix)
7005 {
7006 for ( ; p < pend; p++, prefix++)
7007 if (*p != *prefix)
7008 return 0;
7009 return *prefix == '\0';
7010 }
7011
7012 /* Parse the stop reply in BUF. Either the function succeeds, and the
7013 result is stored in EVENT, or throws an error. */
7014
7015 static void
7016 remote_parse_stop_reply (char *buf, struct stop_reply *event)
7017 {
7018 remote_arch_state *rsa = NULL;
7019 ULONGEST addr;
7020 const char *p;
7021 int skipregs = 0;
7022
7023 event->ptid = null_ptid;
7024 event->rs = get_remote_state ();
7025 event->ws.kind = TARGET_WAITKIND_IGNORE;
7026 event->ws.value.integer = 0;
7027 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7028 event->regcache = NULL;
7029 event->core = -1;
7030
7031 switch (buf[0])
7032 {
7033 case 'T': /* Status with PC, SP, FP, ... */
7034 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7035 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7036 ss = signal number
7037 n... = register number
7038 r... = register contents
7039 */
7040
7041 p = &buf[3]; /* after Txx */
7042 while (*p)
7043 {
7044 const char *p1;
7045 int fieldsize;
7046
7047 p1 = strchr (p, ':');
7048 if (p1 == NULL)
7049 error (_("Malformed packet(a) (missing colon): %s\n\
7050 Packet: '%s'\n"),
7051 p, buf);
7052 if (p == p1)
7053 error (_("Malformed packet(a) (missing register number): %s\n\
7054 Packet: '%s'\n"),
7055 p, buf);
7056
7057 /* Some "registers" are actually extended stop information.
7058 Note if you're adding a new entry here: GDB 7.9 and
7059 earlier assume that all register "numbers" that start
7060 with an hex digit are real register numbers. Make sure
7061 the server only sends such a packet if it knows the
7062 client understands it. */
7063
7064 if (strprefix (p, p1, "thread"))
7065 event->ptid = read_ptid (++p1, &p);
7066 else if (strprefix (p, p1, "syscall_entry"))
7067 {
7068 ULONGEST sysno;
7069
7070 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7071 p = unpack_varlen_hex (++p1, &sysno);
7072 event->ws.value.syscall_number = (int) sysno;
7073 }
7074 else if (strprefix (p, p1, "syscall_return"))
7075 {
7076 ULONGEST sysno;
7077
7078 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7079 p = unpack_varlen_hex (++p1, &sysno);
7080 event->ws.value.syscall_number = (int) sysno;
7081 }
7082 else if (strprefix (p, p1, "watch")
7083 || strprefix (p, p1, "rwatch")
7084 || strprefix (p, p1, "awatch"))
7085 {
7086 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7087 p = unpack_varlen_hex (++p1, &addr);
7088 event->watch_data_address = (CORE_ADDR) addr;
7089 }
7090 else if (strprefix (p, p1, "swbreak"))
7091 {
7092 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7093
7094 /* Make sure the stub doesn't forget to indicate support
7095 with qSupported. */
7096 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7097 error (_("Unexpected swbreak stop reason"));
7098
7099 /* The value part is documented as "must be empty",
7100 though we ignore it, in case we ever decide to make
7101 use of it in a backward compatible way. */
7102 p = strchrnul (p1 + 1, ';');
7103 }
7104 else if (strprefix (p, p1, "hwbreak"))
7105 {
7106 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7107
7108 /* Make sure the stub doesn't forget to indicate support
7109 with qSupported. */
7110 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7111 error (_("Unexpected hwbreak stop reason"));
7112
7113 /* See above. */
7114 p = strchrnul (p1 + 1, ';');
7115 }
7116 else if (strprefix (p, p1, "library"))
7117 {
7118 event->ws.kind = TARGET_WAITKIND_LOADED;
7119 p = strchrnul (p1 + 1, ';');
7120 }
7121 else if (strprefix (p, p1, "replaylog"))
7122 {
7123 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7124 /* p1 will indicate "begin" or "end", but it makes
7125 no difference for now, so ignore it. */
7126 p = strchrnul (p1 + 1, ';');
7127 }
7128 else if (strprefix (p, p1, "core"))
7129 {
7130 ULONGEST c;
7131
7132 p = unpack_varlen_hex (++p1, &c);
7133 event->core = c;
7134 }
7135 else if (strprefix (p, p1, "fork"))
7136 {
7137 event->ws.value.related_pid = read_ptid (++p1, &p);
7138 event->ws.kind = TARGET_WAITKIND_FORKED;
7139 }
7140 else if (strprefix (p, p1, "vfork"))
7141 {
7142 event->ws.value.related_pid = read_ptid (++p1, &p);
7143 event->ws.kind = TARGET_WAITKIND_VFORKED;
7144 }
7145 else if (strprefix (p, p1, "vforkdone"))
7146 {
7147 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7148 p = strchrnul (p1 + 1, ';');
7149 }
7150 else if (strprefix (p, p1, "exec"))
7151 {
7152 ULONGEST ignored;
7153 char pathname[PATH_MAX];
7154 int pathlen;
7155
7156 /* Determine the length of the execd pathname. */
7157 p = unpack_varlen_hex (++p1, &ignored);
7158 pathlen = (p - p1) / 2;
7159
7160 /* Save the pathname for event reporting and for
7161 the next run command. */
7162 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7163 pathname[pathlen] = '\0';
7164
7165 /* This is freed during event handling. */
7166 event->ws.value.execd_pathname = xstrdup (pathname);
7167 event->ws.kind = TARGET_WAITKIND_EXECD;
7168
7169 /* Skip the registers included in this packet, since
7170 they may be for an architecture different from the
7171 one used by the original program. */
7172 skipregs = 1;
7173 }
7174 else if (strprefix (p, p1, "create"))
7175 {
7176 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7177 p = strchrnul (p1 + 1, ';');
7178 }
7179 else
7180 {
7181 ULONGEST pnum;
7182 const char *p_temp;
7183
7184 if (skipregs)
7185 {
7186 p = strchrnul (p1 + 1, ';');
7187 p++;
7188 continue;
7189 }
7190
7191 /* Maybe a real ``P'' register number. */
7192 p_temp = unpack_varlen_hex (p, &pnum);
7193 /* If the first invalid character is the colon, we got a
7194 register number. Otherwise, it's an unknown stop
7195 reason. */
7196 if (p_temp == p1)
7197 {
7198 /* If we haven't parsed the event's thread yet, find
7199 it now, in order to find the architecture of the
7200 reported expedited registers. */
7201 if (event->ptid == null_ptid)
7202 {
7203 const char *thr = strstr (p1 + 1, ";thread:");
7204 if (thr != NULL)
7205 event->ptid = read_ptid (thr + strlen (";thread:"),
7206 NULL);
7207 else
7208 {
7209 /* Either the current thread hasn't changed,
7210 or the inferior is not multi-threaded.
7211 The event must be for the thread we last
7212 set as (or learned as being) current. */
7213 event->ptid = event->rs->general_thread;
7214 }
7215 }
7216
7217 if (rsa == NULL)
7218 {
7219 inferior *inf = (event->ptid == null_ptid
7220 ? NULL
7221 : find_inferior_ptid (event->ptid));
7222 /* If this is the first time we learn anything
7223 about this process, skip the registers
7224 included in this packet, since we don't yet
7225 know which architecture to use to parse them.
7226 We'll determine the architecture later when
7227 we process the stop reply and retrieve the
7228 target description, via
7229 remote_notice_new_inferior ->
7230 post_create_inferior. */
7231 if (inf == NULL)
7232 {
7233 p = strchrnul (p1 + 1, ';');
7234 p++;
7235 continue;
7236 }
7237
7238 event->arch = inf->gdbarch;
7239 rsa = get_remote_arch_state (event->arch);
7240 }
7241
7242 packet_reg *reg
7243 = packet_reg_from_pnum (event->arch, rsa, pnum);
7244 cached_reg_t cached_reg;
7245
7246 if (reg == NULL)
7247 error (_("Remote sent bad register number %s: %s\n\
7248 Packet: '%s'\n"),
7249 hex_string (pnum), p, buf);
7250
7251 cached_reg.num = reg->regnum;
7252 cached_reg.data = (gdb_byte *)
7253 xmalloc (register_size (event->arch, reg->regnum));
7254
7255 p = p1 + 1;
7256 fieldsize = hex2bin (p, cached_reg.data,
7257 register_size (event->arch, reg->regnum));
7258 p += 2 * fieldsize;
7259 if (fieldsize < register_size (event->arch, reg->regnum))
7260 warning (_("Remote reply is too short: %s"), buf);
7261
7262 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7263 }
7264 else
7265 {
7266 /* Not a number. Silently skip unknown optional
7267 info. */
7268 p = strchrnul (p1 + 1, ';');
7269 }
7270 }
7271
7272 if (*p != ';')
7273 error (_("Remote register badly formatted: %s\nhere: %s"),
7274 buf, p);
7275 ++p;
7276 }
7277
7278 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7279 break;
7280
7281 /* fall through */
7282 case 'S': /* Old style status, just signal only. */
7283 {
7284 int sig;
7285
7286 event->ws.kind = TARGET_WAITKIND_STOPPED;
7287 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7288 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7289 event->ws.value.sig = (enum gdb_signal) sig;
7290 else
7291 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7292 }
7293 break;
7294 case 'w': /* Thread exited. */
7295 {
7296 const char *p;
7297 ULONGEST value;
7298
7299 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7300 p = unpack_varlen_hex (&buf[1], &value);
7301 event->ws.value.integer = value;
7302 if (*p != ';')
7303 error (_("stop reply packet badly formatted: %s"), buf);
7304 event->ptid = read_ptid (++p, NULL);
7305 break;
7306 }
7307 case 'W': /* Target exited. */
7308 case 'X':
7309 {
7310 const char *p;
7311 int pid;
7312 ULONGEST value;
7313
7314 /* GDB used to accept only 2 hex chars here. Stubs should
7315 only send more if they detect GDB supports multi-process
7316 support. */
7317 p = unpack_varlen_hex (&buf[1], &value);
7318
7319 if (buf[0] == 'W')
7320 {
7321 /* The remote process exited. */
7322 event->ws.kind = TARGET_WAITKIND_EXITED;
7323 event->ws.value.integer = value;
7324 }
7325 else
7326 {
7327 /* The remote process exited with a signal. */
7328 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7329 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7330 event->ws.value.sig = (enum gdb_signal) value;
7331 else
7332 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7333 }
7334
7335 /* If no process is specified, assume inferior_ptid. */
7336 pid = ptid_get_pid (inferior_ptid);
7337 if (*p == '\0')
7338 ;
7339 else if (*p == ';')
7340 {
7341 p++;
7342
7343 if (*p == '\0')
7344 ;
7345 else if (startswith (p, "process:"))
7346 {
7347 ULONGEST upid;
7348
7349 p += sizeof ("process:") - 1;
7350 unpack_varlen_hex (p, &upid);
7351 pid = upid;
7352 }
7353 else
7354 error (_("unknown stop reply packet: %s"), buf);
7355 }
7356 else
7357 error (_("unknown stop reply packet: %s"), buf);
7358 event->ptid = pid_to_ptid (pid);
7359 }
7360 break;
7361 case 'N':
7362 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7363 event->ptid = minus_one_ptid;
7364 break;
7365 }
7366
7367 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7368 error (_("No process or thread specified in stop reply: %s"), buf);
7369 }
7370
7371 /* When the stub wants to tell GDB about a new notification reply, it
7372 sends a notification (%Stop, for example). Those can come it at
7373 any time, hence, we have to make sure that any pending
7374 putpkt/getpkt sequence we're making is finished, before querying
7375 the stub for more events with the corresponding ack command
7376 (vStopped, for example). E.g., if we started a vStopped sequence
7377 immediately upon receiving the notification, something like this
7378 could happen:
7379
7380 1.1) --> Hg 1
7381 1.2) <-- OK
7382 1.3) --> g
7383 1.4) <-- %Stop
7384 1.5) --> vStopped
7385 1.6) <-- (registers reply to step #1.3)
7386
7387 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7388 query.
7389
7390 To solve this, whenever we parse a %Stop notification successfully,
7391 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7392 doing whatever we were doing:
7393
7394 2.1) --> Hg 1
7395 2.2) <-- OK
7396 2.3) --> g
7397 2.4) <-- %Stop
7398 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7399 2.5) <-- (registers reply to step #2.3)
7400
7401 Eventualy after step #2.5, we return to the event loop, which
7402 notices there's an event on the
7403 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7404 associated callback --- the function below. At this point, we're
7405 always safe to start a vStopped sequence. :
7406
7407 2.6) --> vStopped
7408 2.7) <-- T05 thread:2
7409 2.8) --> vStopped
7410 2.9) --> OK
7411 */
7412
7413 void
7414 remote_notif_get_pending_events (struct notif_client *nc)
7415 {
7416 struct remote_state *rs = get_remote_state ();
7417
7418 if (rs->notif_state->pending_event[nc->id] != NULL)
7419 {
7420 if (notif_debug)
7421 fprintf_unfiltered (gdb_stdlog,
7422 "notif: process: '%s' ack pending event\n",
7423 nc->name);
7424
7425 /* acknowledge */
7426 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7427 rs->notif_state->pending_event[nc->id] = NULL;
7428
7429 while (1)
7430 {
7431 getpkt (&rs->buf, &rs->buf_size, 0);
7432 if (strcmp (rs->buf, "OK") == 0)
7433 break;
7434 else
7435 remote_notif_ack (nc, rs->buf);
7436 }
7437 }
7438 else
7439 {
7440 if (notif_debug)
7441 fprintf_unfiltered (gdb_stdlog,
7442 "notif: process: '%s' no pending reply\n",
7443 nc->name);
7444 }
7445 }
7446
7447 /* Called when it is decided that STOP_REPLY holds the info of the
7448 event that is to be returned to the core. This function always
7449 destroys STOP_REPLY. */
7450
7451 static ptid_t
7452 process_stop_reply (struct stop_reply *stop_reply,
7453 struct target_waitstatus *status)
7454 {
7455 ptid_t ptid;
7456
7457 *status = stop_reply->ws;
7458 ptid = stop_reply->ptid;
7459
7460 /* If no thread/process was reported by the stub, assume the current
7461 inferior. */
7462 if (ptid_equal (ptid, null_ptid))
7463 ptid = inferior_ptid;
7464
7465 if (status->kind != TARGET_WAITKIND_EXITED
7466 && status->kind != TARGET_WAITKIND_SIGNALLED
7467 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7468 {
7469 /* Expedited registers. */
7470 if (stop_reply->regcache)
7471 {
7472 struct regcache *regcache
7473 = get_thread_arch_regcache (ptid, stop_reply->arch);
7474 cached_reg_t *reg;
7475 int ix;
7476
7477 for (ix = 0;
7478 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7479 ix++)
7480 {
7481 regcache_raw_supply (regcache, reg->num, reg->data);
7482 xfree (reg->data);
7483 }
7484
7485 VEC_free (cached_reg_t, stop_reply->regcache);
7486 }
7487
7488 remote_notice_new_inferior (ptid, 0);
7489 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7490 remote_thr->core = stop_reply->core;
7491 remote_thr->stop_reason = stop_reply->stop_reason;
7492 remote_thr->watch_data_address = stop_reply->watch_data_address;
7493 remote_thr->vcont_resumed = 0;
7494 }
7495
7496 stop_reply_xfree (stop_reply);
7497 return ptid;
7498 }
7499
7500 /* The non-stop mode version of target_wait. */
7501
7502 static ptid_t
7503 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7504 {
7505 struct remote_state *rs = get_remote_state ();
7506 struct stop_reply *stop_reply;
7507 int ret;
7508 int is_notif = 0;
7509
7510 /* If in non-stop mode, get out of getpkt even if a
7511 notification is received. */
7512
7513 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7514 0 /* forever */, &is_notif);
7515 while (1)
7516 {
7517 if (ret != -1 && !is_notif)
7518 switch (rs->buf[0])
7519 {
7520 case 'E': /* Error of some sort. */
7521 /* We're out of sync with the target now. Did it continue
7522 or not? We can't tell which thread it was in non-stop,
7523 so just ignore this. */
7524 warning (_("Remote failure reply: %s"), rs->buf);
7525 break;
7526 case 'O': /* Console output. */
7527 remote_console_output (rs->buf + 1);
7528 break;
7529 default:
7530 warning (_("Invalid remote reply: %s"), rs->buf);
7531 break;
7532 }
7533
7534 /* Acknowledge a pending stop reply that may have arrived in the
7535 mean time. */
7536 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7537 remote_notif_get_pending_events (&notif_client_stop);
7538
7539 /* If indeed we noticed a stop reply, we're done. */
7540 stop_reply = queued_stop_reply (ptid);
7541 if (stop_reply != NULL)
7542 return process_stop_reply (stop_reply, status);
7543
7544 /* Still no event. If we're just polling for an event, then
7545 return to the event loop. */
7546 if (options & TARGET_WNOHANG)
7547 {
7548 status->kind = TARGET_WAITKIND_IGNORE;
7549 return minus_one_ptid;
7550 }
7551
7552 /* Otherwise do a blocking wait. */
7553 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7554 1 /* forever */, &is_notif);
7555 }
7556 }
7557
7558 /* Wait until the remote machine stops, then return, storing status in
7559 STATUS just as `wait' would. */
7560
7561 static ptid_t
7562 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7563 {
7564 struct remote_state *rs = get_remote_state ();
7565 ptid_t event_ptid = null_ptid;
7566 char *buf;
7567 struct stop_reply *stop_reply;
7568
7569 again:
7570
7571 status->kind = TARGET_WAITKIND_IGNORE;
7572 status->value.integer = 0;
7573
7574 stop_reply = queued_stop_reply (ptid);
7575 if (stop_reply != NULL)
7576 return process_stop_reply (stop_reply, status);
7577
7578 if (rs->cached_wait_status)
7579 /* Use the cached wait status, but only once. */
7580 rs->cached_wait_status = 0;
7581 else
7582 {
7583 int ret;
7584 int is_notif;
7585 int forever = ((options & TARGET_WNOHANG) == 0
7586 && wait_forever_enabled_p);
7587
7588 if (!rs->waiting_for_stop_reply)
7589 {
7590 status->kind = TARGET_WAITKIND_NO_RESUMED;
7591 return minus_one_ptid;
7592 }
7593
7594 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7595 _never_ wait for ever -> test on target_is_async_p().
7596 However, before we do that we need to ensure that the caller
7597 knows how to take the target into/out of async mode. */
7598 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7599 forever, &is_notif);
7600
7601 /* GDB gets a notification. Return to core as this event is
7602 not interesting. */
7603 if (ret != -1 && is_notif)
7604 return minus_one_ptid;
7605
7606 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7607 return minus_one_ptid;
7608 }
7609
7610 buf = rs->buf;
7611
7612 /* Assume that the target has acknowledged Ctrl-C unless we receive
7613 an 'F' or 'O' packet. */
7614 if (buf[0] != 'F' && buf[0] != 'O')
7615 rs->ctrlc_pending_p = 0;
7616
7617 switch (buf[0])
7618 {
7619 case 'E': /* Error of some sort. */
7620 /* We're out of sync with the target now. Did it continue or
7621 not? Not is more likely, so report a stop. */
7622 rs->waiting_for_stop_reply = 0;
7623
7624 warning (_("Remote failure reply: %s"), buf);
7625 status->kind = TARGET_WAITKIND_STOPPED;
7626 status->value.sig = GDB_SIGNAL_0;
7627 break;
7628 case 'F': /* File-I/O request. */
7629 /* GDB may access the inferior memory while handling the File-I/O
7630 request, but we don't want GDB accessing memory while waiting
7631 for a stop reply. See the comments in putpkt_binary. Set
7632 waiting_for_stop_reply to 0 temporarily. */
7633 rs->waiting_for_stop_reply = 0;
7634 remote_fileio_request (buf, rs->ctrlc_pending_p);
7635 rs->ctrlc_pending_p = 0;
7636 /* GDB handled the File-I/O request, and the target is running
7637 again. Keep waiting for events. */
7638 rs->waiting_for_stop_reply = 1;
7639 break;
7640 case 'N': case 'T': case 'S': case 'X': case 'W':
7641 {
7642 struct stop_reply *stop_reply;
7643
7644 /* There is a stop reply to handle. */
7645 rs->waiting_for_stop_reply = 0;
7646
7647 stop_reply
7648 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7649 rs->buf);
7650
7651 event_ptid = process_stop_reply (stop_reply, status);
7652 break;
7653 }
7654 case 'O': /* Console output. */
7655 remote_console_output (buf + 1);
7656 break;
7657 case '\0':
7658 if (rs->last_sent_signal != GDB_SIGNAL_0)
7659 {
7660 /* Zero length reply means that we tried 'S' or 'C' and the
7661 remote system doesn't support it. */
7662 target_terminal::ours_for_output ();
7663 printf_filtered
7664 ("Can't send signals to this remote system. %s not sent.\n",
7665 gdb_signal_to_name (rs->last_sent_signal));
7666 rs->last_sent_signal = GDB_SIGNAL_0;
7667 target_terminal::inferior ();
7668
7669 strcpy (buf, rs->last_sent_step ? "s" : "c");
7670 putpkt (buf);
7671 break;
7672 }
7673 /* else fallthrough */
7674 default:
7675 warning (_("Invalid remote reply: %s"), buf);
7676 break;
7677 }
7678
7679 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7680 return minus_one_ptid;
7681 else if (status->kind == TARGET_WAITKIND_IGNORE)
7682 {
7683 /* Nothing interesting happened. If we're doing a non-blocking
7684 poll, we're done. Otherwise, go back to waiting. */
7685 if (options & TARGET_WNOHANG)
7686 return minus_one_ptid;
7687 else
7688 goto again;
7689 }
7690 else if (status->kind != TARGET_WAITKIND_EXITED
7691 && status->kind != TARGET_WAITKIND_SIGNALLED)
7692 {
7693 if (!ptid_equal (event_ptid, null_ptid))
7694 record_currthread (rs, event_ptid);
7695 else
7696 event_ptid = inferior_ptid;
7697 }
7698 else
7699 /* A process exit. Invalidate our notion of current thread. */
7700 record_currthread (rs, minus_one_ptid);
7701
7702 return event_ptid;
7703 }
7704
7705 /* Wait until the remote machine stops, then return, storing status in
7706 STATUS just as `wait' would. */
7707
7708 ptid_t
7709 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7710 {
7711 ptid_t event_ptid;
7712
7713 if (target_is_non_stop_p ())
7714 event_ptid = remote_wait_ns (ptid, status, options);
7715 else
7716 event_ptid = remote_wait_as (ptid, status, options);
7717
7718 if (target_is_async_p ())
7719 {
7720 /* If there are are events left in the queue tell the event loop
7721 to return here. */
7722 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7723 mark_async_event_handler (remote_async_inferior_event_token);
7724 }
7725
7726 return event_ptid;
7727 }
7728
7729 /* Fetch a single register using a 'p' packet. */
7730
7731 static int
7732 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7733 {
7734 struct gdbarch *gdbarch = regcache->arch ();
7735 struct remote_state *rs = get_remote_state ();
7736 char *buf, *p;
7737 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7738 int i;
7739
7740 if (packet_support (PACKET_p) == PACKET_DISABLE)
7741 return 0;
7742
7743 if (reg->pnum == -1)
7744 return 0;
7745
7746 p = rs->buf;
7747 *p++ = 'p';
7748 p += hexnumstr (p, reg->pnum);
7749 *p++ = '\0';
7750 putpkt (rs->buf);
7751 getpkt (&rs->buf, &rs->buf_size, 0);
7752
7753 buf = rs->buf;
7754
7755 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7756 {
7757 case PACKET_OK:
7758 break;
7759 case PACKET_UNKNOWN:
7760 return 0;
7761 case PACKET_ERROR:
7762 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7763 gdbarch_register_name (regcache->arch (),
7764 reg->regnum),
7765 buf);
7766 }
7767
7768 /* If this register is unfetchable, tell the regcache. */
7769 if (buf[0] == 'x')
7770 {
7771 regcache_raw_supply (regcache, reg->regnum, NULL);
7772 return 1;
7773 }
7774
7775 /* Otherwise, parse and supply the value. */
7776 p = buf;
7777 i = 0;
7778 while (p[0] != 0)
7779 {
7780 if (p[1] == 0)
7781 error (_("fetch_register_using_p: early buf termination"));
7782
7783 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7784 p += 2;
7785 }
7786 regcache_raw_supply (regcache, reg->regnum, regp);
7787 return 1;
7788 }
7789
7790 /* Fetch the registers included in the target's 'g' packet. */
7791
7792 static int
7793 send_g_packet (void)
7794 {
7795 struct remote_state *rs = get_remote_state ();
7796 int buf_len;
7797
7798 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7799 putpkt (rs->buf);
7800 getpkt (&rs->buf, &rs->buf_size, 0);
7801 if (packet_check_result (rs->buf) == PACKET_ERROR)
7802 error (_("Could not read registers; remote failure reply '%s'"),
7803 rs->buf);
7804
7805 /* We can get out of synch in various cases. If the first character
7806 in the buffer is not a hex character, assume that has happened
7807 and try to fetch another packet to read. */
7808 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7809 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7810 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7811 && rs->buf[0] != 'x') /* New: unavailable register value. */
7812 {
7813 if (remote_debug)
7814 fprintf_unfiltered (gdb_stdlog,
7815 "Bad register packet; fetching a new packet\n");
7816 getpkt (&rs->buf, &rs->buf_size, 0);
7817 }
7818
7819 buf_len = strlen (rs->buf);
7820
7821 /* Sanity check the received packet. */
7822 if (buf_len % 2 != 0)
7823 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7824
7825 return buf_len / 2;
7826 }
7827
7828 static void
7829 process_g_packet (struct regcache *regcache)
7830 {
7831 struct gdbarch *gdbarch = regcache->arch ();
7832 struct remote_state *rs = get_remote_state ();
7833 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7834 int i, buf_len;
7835 char *p;
7836 char *regs;
7837
7838 buf_len = strlen (rs->buf);
7839
7840 /* Further sanity checks, with knowledge of the architecture. */
7841 if (buf_len > 2 * rsa->sizeof_g_packet)
7842 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7843 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7844
7845 /* Save the size of the packet sent to us by the target. It is used
7846 as a heuristic when determining the max size of packets that the
7847 target can safely receive. */
7848 if (rsa->actual_register_packet_size == 0)
7849 rsa->actual_register_packet_size = buf_len;
7850
7851 /* If this is smaller than we guessed the 'g' packet would be,
7852 update our records. A 'g' reply that doesn't include a register's
7853 value implies either that the register is not available, or that
7854 the 'p' packet must be used. */
7855 if (buf_len < 2 * rsa->sizeof_g_packet)
7856 {
7857 long sizeof_g_packet = buf_len / 2;
7858
7859 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7860 {
7861 long offset = rsa->regs[i].offset;
7862 long reg_size = register_size (gdbarch, i);
7863
7864 if (rsa->regs[i].pnum == -1)
7865 continue;
7866
7867 if (offset >= sizeof_g_packet)
7868 rsa->regs[i].in_g_packet = 0;
7869 else if (offset + reg_size > sizeof_g_packet)
7870 error (_("Truncated register %d in remote 'g' packet"), i);
7871 else
7872 rsa->regs[i].in_g_packet = 1;
7873 }
7874
7875 /* Looks valid enough, we can assume this is the correct length
7876 for a 'g' packet. It's important not to adjust
7877 rsa->sizeof_g_packet if we have truncated registers otherwise
7878 this "if" won't be run the next time the method is called
7879 with a packet of the same size and one of the internal errors
7880 below will trigger instead. */
7881 rsa->sizeof_g_packet = sizeof_g_packet;
7882 }
7883
7884 regs = (char *) alloca (rsa->sizeof_g_packet);
7885
7886 /* Unimplemented registers read as all bits zero. */
7887 memset (regs, 0, rsa->sizeof_g_packet);
7888
7889 /* Reply describes registers byte by byte, each byte encoded as two
7890 hex characters. Suck them all up, then supply them to the
7891 register cacheing/storage mechanism. */
7892
7893 p = rs->buf;
7894 for (i = 0; i < rsa->sizeof_g_packet; i++)
7895 {
7896 if (p[0] == 0 || p[1] == 0)
7897 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7898 internal_error (__FILE__, __LINE__,
7899 _("unexpected end of 'g' packet reply"));
7900
7901 if (p[0] == 'x' && p[1] == 'x')
7902 regs[i] = 0; /* 'x' */
7903 else
7904 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7905 p += 2;
7906 }
7907
7908 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7909 {
7910 struct packet_reg *r = &rsa->regs[i];
7911 long reg_size = register_size (gdbarch, i);
7912
7913 if (r->in_g_packet)
7914 {
7915 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7916 /* This shouldn't happen - we adjusted in_g_packet above. */
7917 internal_error (__FILE__, __LINE__,
7918 _("unexpected end of 'g' packet reply"));
7919 else if (rs->buf[r->offset * 2] == 'x')
7920 {
7921 gdb_assert (r->offset * 2 < strlen (rs->buf));
7922 /* The register isn't available, mark it as such (at
7923 the same time setting the value to zero). */
7924 regcache_raw_supply (regcache, r->regnum, NULL);
7925 }
7926 else
7927 regcache_raw_supply (regcache, r->regnum,
7928 regs + r->offset);
7929 }
7930 }
7931 }
7932
7933 static void
7934 fetch_registers_using_g (struct regcache *regcache)
7935 {
7936 send_g_packet ();
7937 process_g_packet (regcache);
7938 }
7939
7940 /* Make the remote selected traceframe match GDB's selected
7941 traceframe. */
7942
7943 static void
7944 set_remote_traceframe (void)
7945 {
7946 int newnum;
7947 struct remote_state *rs = get_remote_state ();
7948
7949 if (rs->remote_traceframe_number == get_traceframe_number ())
7950 return;
7951
7952 /* Avoid recursion, remote_trace_find calls us again. */
7953 rs->remote_traceframe_number = get_traceframe_number ();
7954
7955 newnum = target_trace_find (tfind_number,
7956 get_traceframe_number (), 0, 0, NULL);
7957
7958 /* Should not happen. If it does, all bets are off. */
7959 if (newnum != get_traceframe_number ())
7960 warning (_("could not set remote traceframe"));
7961 }
7962
7963 void
7964 remote_target::fetch_registers (struct regcache *regcache, int regnum)
7965 {
7966 struct gdbarch *gdbarch = regcache->arch ();
7967 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7968 int i;
7969
7970 set_remote_traceframe ();
7971 set_general_thread (regcache_get_ptid (regcache));
7972
7973 if (regnum >= 0)
7974 {
7975 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
7976
7977 gdb_assert (reg != NULL);
7978
7979 /* If this register might be in the 'g' packet, try that first -
7980 we are likely to read more than one register. If this is the
7981 first 'g' packet, we might be overly optimistic about its
7982 contents, so fall back to 'p'. */
7983 if (reg->in_g_packet)
7984 {
7985 fetch_registers_using_g (regcache);
7986 if (reg->in_g_packet)
7987 return;
7988 }
7989
7990 if (fetch_register_using_p (regcache, reg))
7991 return;
7992
7993 /* This register is not available. */
7994 regcache_raw_supply (regcache, reg->regnum, NULL);
7995
7996 return;
7997 }
7998
7999 fetch_registers_using_g (regcache);
8000
8001 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8002 if (!rsa->regs[i].in_g_packet)
8003 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8004 {
8005 /* This register is not available. */
8006 regcache_raw_supply (regcache, i, NULL);
8007 }
8008 }
8009
8010 /* Prepare to store registers. Since we may send them all (using a
8011 'G' request), we have to read out the ones we don't want to change
8012 first. */
8013
8014 void
8015 remote_target::prepare_to_store (struct regcache *regcache)
8016 {
8017 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8018 int i;
8019
8020 /* Make sure the entire registers array is valid. */
8021 switch (packet_support (PACKET_P))
8022 {
8023 case PACKET_DISABLE:
8024 case PACKET_SUPPORT_UNKNOWN:
8025 /* Make sure all the necessary registers are cached. */
8026 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8027 if (rsa->regs[i].in_g_packet)
8028 regcache_raw_update (regcache, rsa->regs[i].regnum);
8029 break;
8030 case PACKET_ENABLE:
8031 break;
8032 }
8033 }
8034
8035 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8036 packet was not recognized. */
8037
8038 static int
8039 store_register_using_P (const struct regcache *regcache,
8040 struct packet_reg *reg)
8041 {
8042 struct gdbarch *gdbarch = regcache->arch ();
8043 struct remote_state *rs = get_remote_state ();
8044 /* Try storing a single register. */
8045 char *buf = rs->buf;
8046 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8047 char *p;
8048
8049 if (packet_support (PACKET_P) == PACKET_DISABLE)
8050 return 0;
8051
8052 if (reg->pnum == -1)
8053 return 0;
8054
8055 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8056 p = buf + strlen (buf);
8057 regcache_raw_collect (regcache, reg->regnum, regp);
8058 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8059 putpkt (rs->buf);
8060 getpkt (&rs->buf, &rs->buf_size, 0);
8061
8062 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8063 {
8064 case PACKET_OK:
8065 return 1;
8066 case PACKET_ERROR:
8067 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8068 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8069 case PACKET_UNKNOWN:
8070 return 0;
8071 default:
8072 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8073 }
8074 }
8075
8076 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8077 contents of the register cache buffer. FIXME: ignores errors. */
8078
8079 static void
8080 store_registers_using_G (const struct regcache *regcache)
8081 {
8082 struct remote_state *rs = get_remote_state ();
8083 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8084 gdb_byte *regs;
8085 char *p;
8086
8087 /* Extract all the registers in the regcache copying them into a
8088 local buffer. */
8089 {
8090 int i;
8091
8092 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8093 memset (regs, 0, rsa->sizeof_g_packet);
8094 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8095 {
8096 struct packet_reg *r = &rsa->regs[i];
8097
8098 if (r->in_g_packet)
8099 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
8100 }
8101 }
8102
8103 /* Command describes registers byte by byte,
8104 each byte encoded as two hex characters. */
8105 p = rs->buf;
8106 *p++ = 'G';
8107 bin2hex (regs, p, rsa->sizeof_g_packet);
8108 putpkt (rs->buf);
8109 getpkt (&rs->buf, &rs->buf_size, 0);
8110 if (packet_check_result (rs->buf) == PACKET_ERROR)
8111 error (_("Could not write registers; remote failure reply '%s'"),
8112 rs->buf);
8113 }
8114
8115 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8116 of the register cache buffer. FIXME: ignores errors. */
8117
8118 void
8119 remote_target::store_registers (struct regcache *regcache, int regnum)
8120 {
8121 struct gdbarch *gdbarch = regcache->arch ();
8122 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
8123 int i;
8124
8125 set_remote_traceframe ();
8126 set_general_thread (regcache_get_ptid (regcache));
8127
8128 if (regnum >= 0)
8129 {
8130 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8131
8132 gdb_assert (reg != NULL);
8133
8134 /* Always prefer to store registers using the 'P' packet if
8135 possible; we often change only a small number of registers.
8136 Sometimes we change a larger number; we'd need help from a
8137 higher layer to know to use 'G'. */
8138 if (store_register_using_P (regcache, reg))
8139 return;
8140
8141 /* For now, don't complain if we have no way to write the
8142 register. GDB loses track of unavailable registers too
8143 easily. Some day, this may be an error. We don't have
8144 any way to read the register, either... */
8145 if (!reg->in_g_packet)
8146 return;
8147
8148 store_registers_using_G (regcache);
8149 return;
8150 }
8151
8152 store_registers_using_G (regcache);
8153
8154 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8155 if (!rsa->regs[i].in_g_packet)
8156 if (!store_register_using_P (regcache, &rsa->regs[i]))
8157 /* See above for why we do not issue an error here. */
8158 continue;
8159 }
8160 \f
8161
8162 /* Return the number of hex digits in num. */
8163
8164 static int
8165 hexnumlen (ULONGEST num)
8166 {
8167 int i;
8168
8169 for (i = 0; num != 0; i++)
8170 num >>= 4;
8171
8172 return std::max (i, 1);
8173 }
8174
8175 /* Set BUF to the minimum number of hex digits representing NUM. */
8176
8177 static int
8178 hexnumstr (char *buf, ULONGEST num)
8179 {
8180 int len = hexnumlen (num);
8181
8182 return hexnumnstr (buf, num, len);
8183 }
8184
8185
8186 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8187
8188 static int
8189 hexnumnstr (char *buf, ULONGEST num, int width)
8190 {
8191 int i;
8192
8193 buf[width] = '\0';
8194
8195 for (i = width - 1; i >= 0; i--)
8196 {
8197 buf[i] = "0123456789abcdef"[(num & 0xf)];
8198 num >>= 4;
8199 }
8200
8201 return width;
8202 }
8203
8204 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8205
8206 static CORE_ADDR
8207 remote_address_masked (CORE_ADDR addr)
8208 {
8209 unsigned int address_size = remote_address_size;
8210
8211 /* If "remoteaddresssize" was not set, default to target address size. */
8212 if (!address_size)
8213 address_size = gdbarch_addr_bit (target_gdbarch ());
8214
8215 if (address_size > 0
8216 && address_size < (sizeof (ULONGEST) * 8))
8217 {
8218 /* Only create a mask when that mask can safely be constructed
8219 in a ULONGEST variable. */
8220 ULONGEST mask = 1;
8221
8222 mask = (mask << address_size) - 1;
8223 addr &= mask;
8224 }
8225 return addr;
8226 }
8227
8228 /* Determine whether the remote target supports binary downloading.
8229 This is accomplished by sending a no-op memory write of zero length
8230 to the target at the specified address. It does not suffice to send
8231 the whole packet, since many stubs strip the eighth bit and
8232 subsequently compute a wrong checksum, which causes real havoc with
8233 remote_write_bytes.
8234
8235 NOTE: This can still lose if the serial line is not eight-bit
8236 clean. In cases like this, the user should clear "remote
8237 X-packet". */
8238
8239 static void
8240 check_binary_download (CORE_ADDR addr)
8241 {
8242 struct remote_state *rs = get_remote_state ();
8243
8244 switch (packet_support (PACKET_X))
8245 {
8246 case PACKET_DISABLE:
8247 break;
8248 case PACKET_ENABLE:
8249 break;
8250 case PACKET_SUPPORT_UNKNOWN:
8251 {
8252 char *p;
8253
8254 p = rs->buf;
8255 *p++ = 'X';
8256 p += hexnumstr (p, (ULONGEST) addr);
8257 *p++ = ',';
8258 p += hexnumstr (p, (ULONGEST) 0);
8259 *p++ = ':';
8260 *p = '\0';
8261
8262 putpkt_binary (rs->buf, (int) (p - rs->buf));
8263 getpkt (&rs->buf, &rs->buf_size, 0);
8264
8265 if (rs->buf[0] == '\0')
8266 {
8267 if (remote_debug)
8268 fprintf_unfiltered (gdb_stdlog,
8269 "binary downloading NOT "
8270 "supported by target\n");
8271 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8272 }
8273 else
8274 {
8275 if (remote_debug)
8276 fprintf_unfiltered (gdb_stdlog,
8277 "binary downloading supported by target\n");
8278 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8279 }
8280 break;
8281 }
8282 }
8283 }
8284
8285 /* Helper function to resize the payload in order to try to get a good
8286 alignment. We try to write an amount of data such that the next write will
8287 start on an address aligned on REMOTE_ALIGN_WRITES. */
8288
8289 static int
8290 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8291 {
8292 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8293 }
8294
8295 /* Write memory data directly to the remote machine.
8296 This does not inform the data cache; the data cache uses this.
8297 HEADER is the starting part of the packet.
8298 MEMADDR is the address in the remote memory space.
8299 MYADDR is the address of the buffer in our space.
8300 LEN_UNITS is the number of addressable units to write.
8301 UNIT_SIZE is the length in bytes of an addressable unit.
8302 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8303 should send data as binary ('X'), or hex-encoded ('M').
8304
8305 The function creates packet of the form
8306 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8307
8308 where encoding of <DATA> is terminated by PACKET_FORMAT.
8309
8310 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8311 are omitted.
8312
8313 Return the transferred status, error or OK (an
8314 'enum target_xfer_status' value). Save the number of addressable units
8315 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8316
8317 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8318 exchange between gdb and the stub could look like (?? in place of the
8319 checksum):
8320
8321 -> $m1000,4#??
8322 <- aaaabbbbccccdddd
8323
8324 -> $M1000,3:eeeeffffeeee#??
8325 <- OK
8326
8327 -> $m1000,4#??
8328 <- eeeeffffeeeedddd */
8329
8330 static enum target_xfer_status
8331 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8332 const gdb_byte *myaddr, ULONGEST len_units,
8333 int unit_size, ULONGEST *xfered_len_units,
8334 char packet_format, int use_length)
8335 {
8336 struct remote_state *rs = get_remote_state ();
8337 char *p;
8338 char *plen = NULL;
8339 int plenlen = 0;
8340 int todo_units;
8341 int units_written;
8342 int payload_capacity_bytes;
8343 int payload_length_bytes;
8344
8345 if (packet_format != 'X' && packet_format != 'M')
8346 internal_error (__FILE__, __LINE__,
8347 _("remote_write_bytes_aux: bad packet format"));
8348
8349 if (len_units == 0)
8350 return TARGET_XFER_EOF;
8351
8352 payload_capacity_bytes = get_memory_write_packet_size ();
8353
8354 /* The packet buffer will be large enough for the payload;
8355 get_memory_packet_size ensures this. */
8356 rs->buf[0] = '\0';
8357
8358 /* Compute the size of the actual payload by subtracting out the
8359 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8360
8361 payload_capacity_bytes -= strlen ("$,:#NN");
8362 if (!use_length)
8363 /* The comma won't be used. */
8364 payload_capacity_bytes += 1;
8365 payload_capacity_bytes -= strlen (header);
8366 payload_capacity_bytes -= hexnumlen (memaddr);
8367
8368 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8369
8370 strcat (rs->buf, header);
8371 p = rs->buf + strlen (header);
8372
8373 /* Compute a best guess of the number of bytes actually transfered. */
8374 if (packet_format == 'X')
8375 {
8376 /* Best guess at number of bytes that will fit. */
8377 todo_units = std::min (len_units,
8378 (ULONGEST) payload_capacity_bytes / unit_size);
8379 if (use_length)
8380 payload_capacity_bytes -= hexnumlen (todo_units);
8381 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8382 }
8383 else
8384 {
8385 /* Number of bytes that will fit. */
8386 todo_units
8387 = std::min (len_units,
8388 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8389 if (use_length)
8390 payload_capacity_bytes -= hexnumlen (todo_units);
8391 todo_units = std::min (todo_units,
8392 (payload_capacity_bytes / unit_size) / 2);
8393 }
8394
8395 if (todo_units <= 0)
8396 internal_error (__FILE__, __LINE__,
8397 _("minimum packet size too small to write data"));
8398
8399 /* If we already need another packet, then try to align the end
8400 of this packet to a useful boundary. */
8401 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8402 todo_units = align_for_efficient_write (todo_units, memaddr);
8403
8404 /* Append "<memaddr>". */
8405 memaddr = remote_address_masked (memaddr);
8406 p += hexnumstr (p, (ULONGEST) memaddr);
8407
8408 if (use_length)
8409 {
8410 /* Append ",". */
8411 *p++ = ',';
8412
8413 /* Append the length and retain its location and size. It may need to be
8414 adjusted once the packet body has been created. */
8415 plen = p;
8416 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8417 p += plenlen;
8418 }
8419
8420 /* Append ":". */
8421 *p++ = ':';
8422 *p = '\0';
8423
8424 /* Append the packet body. */
8425 if (packet_format == 'X')
8426 {
8427 /* Binary mode. Send target system values byte by byte, in
8428 increasing byte addresses. Only escape certain critical
8429 characters. */
8430 payload_length_bytes =
8431 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8432 &units_written, payload_capacity_bytes);
8433
8434 /* If not all TODO units fit, then we'll need another packet. Make
8435 a second try to keep the end of the packet aligned. Don't do
8436 this if the packet is tiny. */
8437 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8438 {
8439 int new_todo_units;
8440
8441 new_todo_units = align_for_efficient_write (units_written, memaddr);
8442
8443 if (new_todo_units != units_written)
8444 payload_length_bytes =
8445 remote_escape_output (myaddr, new_todo_units, unit_size,
8446 (gdb_byte *) p, &units_written,
8447 payload_capacity_bytes);
8448 }
8449
8450 p += payload_length_bytes;
8451 if (use_length && units_written < todo_units)
8452 {
8453 /* Escape chars have filled up the buffer prematurely,
8454 and we have actually sent fewer units than planned.
8455 Fix-up the length field of the packet. Use the same
8456 number of characters as before. */
8457 plen += hexnumnstr (plen, (ULONGEST) units_written,
8458 plenlen);
8459 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8460 }
8461 }
8462 else
8463 {
8464 /* Normal mode: Send target system values byte by byte, in
8465 increasing byte addresses. Each byte is encoded as a two hex
8466 value. */
8467 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8468 units_written = todo_units;
8469 }
8470
8471 putpkt_binary (rs->buf, (int) (p - rs->buf));
8472 getpkt (&rs->buf, &rs->buf_size, 0);
8473
8474 if (rs->buf[0] == 'E')
8475 return TARGET_XFER_E_IO;
8476
8477 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8478 send fewer units than we'd planned. */
8479 *xfered_len_units = (ULONGEST) units_written;
8480 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8481 }
8482
8483 /* Write memory data directly to the remote machine.
8484 This does not inform the data cache; the data cache uses this.
8485 MEMADDR is the address in the remote memory space.
8486 MYADDR is the address of the buffer in our space.
8487 LEN is the number of bytes.
8488
8489 Return the transferred status, error or OK (an
8490 'enum target_xfer_status' value). Save the number of bytes
8491 transferred in *XFERED_LEN. Only transfer a single packet. */
8492
8493 static enum target_xfer_status
8494 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8495 int unit_size, ULONGEST *xfered_len)
8496 {
8497 const char *packet_format = NULL;
8498
8499 /* Check whether the target supports binary download. */
8500 check_binary_download (memaddr);
8501
8502 switch (packet_support (PACKET_X))
8503 {
8504 case PACKET_ENABLE:
8505 packet_format = "X";
8506 break;
8507 case PACKET_DISABLE:
8508 packet_format = "M";
8509 break;
8510 case PACKET_SUPPORT_UNKNOWN:
8511 internal_error (__FILE__, __LINE__,
8512 _("remote_write_bytes: bad internal state"));
8513 default:
8514 internal_error (__FILE__, __LINE__, _("bad switch"));
8515 }
8516
8517 return remote_write_bytes_aux (packet_format,
8518 memaddr, myaddr, len, unit_size, xfered_len,
8519 packet_format[0], 1);
8520 }
8521
8522 /* Read memory data directly from the remote machine.
8523 This does not use the data cache; the data cache uses this.
8524 MEMADDR is the address in the remote memory space.
8525 MYADDR is the address of the buffer in our space.
8526 LEN_UNITS is the number of addressable memory units to read..
8527 UNIT_SIZE is the length in bytes of an addressable unit.
8528
8529 Return the transferred status, error or OK (an
8530 'enum target_xfer_status' value). Save the number of bytes
8531 transferred in *XFERED_LEN_UNITS.
8532
8533 See the comment of remote_write_bytes_aux for an example of
8534 memory read/write exchange between gdb and the stub. */
8535
8536 static enum target_xfer_status
8537 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8538 int unit_size, ULONGEST *xfered_len_units)
8539 {
8540 struct remote_state *rs = get_remote_state ();
8541 int buf_size_bytes; /* Max size of packet output buffer. */
8542 char *p;
8543 int todo_units;
8544 int decoded_bytes;
8545
8546 buf_size_bytes = get_memory_read_packet_size ();
8547 /* The packet buffer will be large enough for the payload;
8548 get_memory_packet_size ensures this. */
8549
8550 /* Number of units that will fit. */
8551 todo_units = std::min (len_units,
8552 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8553
8554 /* Construct "m"<memaddr>","<len>". */
8555 memaddr = remote_address_masked (memaddr);
8556 p = rs->buf;
8557 *p++ = 'm';
8558 p += hexnumstr (p, (ULONGEST) memaddr);
8559 *p++ = ',';
8560 p += hexnumstr (p, (ULONGEST) todo_units);
8561 *p = '\0';
8562 putpkt (rs->buf);
8563 getpkt (&rs->buf, &rs->buf_size, 0);
8564 if (rs->buf[0] == 'E'
8565 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8566 && rs->buf[3] == '\0')
8567 return TARGET_XFER_E_IO;
8568 /* Reply describes memory byte by byte, each byte encoded as two hex
8569 characters. */
8570 p = rs->buf;
8571 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8572 /* Return what we have. Let higher layers handle partial reads. */
8573 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8574 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8575 }
8576
8577 /* Using the set of read-only target sections of remote, read live
8578 read-only memory.
8579
8580 For interface/parameters/return description see target.h,
8581 to_xfer_partial. */
8582
8583 static enum target_xfer_status
8584 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8585 ULONGEST memaddr, ULONGEST len,
8586 int unit_size, ULONGEST *xfered_len)
8587 {
8588 struct target_section *secp;
8589 struct target_section_table *table;
8590
8591 secp = target_section_by_addr (ops, memaddr);
8592 if (secp != NULL
8593 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8594 secp->the_bfd_section)
8595 & SEC_READONLY))
8596 {
8597 struct target_section *p;
8598 ULONGEST memend = memaddr + len;
8599
8600 table = target_get_section_table (ops);
8601
8602 for (p = table->sections; p < table->sections_end; p++)
8603 {
8604 if (memaddr >= p->addr)
8605 {
8606 if (memend <= p->endaddr)
8607 {
8608 /* Entire transfer is within this section. */
8609 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8610 xfered_len);
8611 }
8612 else if (memaddr >= p->endaddr)
8613 {
8614 /* This section ends before the transfer starts. */
8615 continue;
8616 }
8617 else
8618 {
8619 /* This section overlaps the transfer. Just do half. */
8620 len = p->endaddr - memaddr;
8621 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8622 xfered_len);
8623 }
8624 }
8625 }
8626 }
8627
8628 return TARGET_XFER_EOF;
8629 }
8630
8631 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8632 first if the requested memory is unavailable in traceframe.
8633 Otherwise, fall back to remote_read_bytes_1. */
8634
8635 static enum target_xfer_status
8636 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8637 gdb_byte *myaddr, ULONGEST len, int unit_size,
8638 ULONGEST *xfered_len)
8639 {
8640 if (len == 0)
8641 return TARGET_XFER_EOF;
8642
8643 if (get_traceframe_number () != -1)
8644 {
8645 std::vector<mem_range> available;
8646
8647 /* If we fail to get the set of available memory, then the
8648 target does not support querying traceframe info, and so we
8649 attempt reading from the traceframe anyway (assuming the
8650 target implements the old QTro packet then). */
8651 if (traceframe_available_memory (&available, memaddr, len))
8652 {
8653 if (available.empty () || available[0].start != memaddr)
8654 {
8655 enum target_xfer_status res;
8656
8657 /* Don't read into the traceframe's available
8658 memory. */
8659 if (!available.empty ())
8660 {
8661 LONGEST oldlen = len;
8662
8663 len = available[0].start - memaddr;
8664 gdb_assert (len <= oldlen);
8665 }
8666
8667 /* This goes through the topmost target again. */
8668 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8669 len, unit_size, xfered_len);
8670 if (res == TARGET_XFER_OK)
8671 return TARGET_XFER_OK;
8672 else
8673 {
8674 /* No use trying further, we know some memory starting
8675 at MEMADDR isn't available. */
8676 *xfered_len = len;
8677 return (*xfered_len != 0) ?
8678 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8679 }
8680 }
8681
8682 /* Don't try to read more than how much is available, in
8683 case the target implements the deprecated QTro packet to
8684 cater for older GDBs (the target's knowledge of read-only
8685 sections may be outdated by now). */
8686 len = available[0].length;
8687 }
8688 }
8689
8690 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8691 }
8692
8693 \f
8694
8695 /* Sends a packet with content determined by the printf format string
8696 FORMAT and the remaining arguments, then gets the reply. Returns
8697 whether the packet was a success, a failure, or unknown. */
8698
8699 static enum packet_result remote_send_printf (const char *format, ...)
8700 ATTRIBUTE_PRINTF (1, 2);
8701
8702 static enum packet_result
8703 remote_send_printf (const char *format, ...)
8704 {
8705 struct remote_state *rs = get_remote_state ();
8706 int max_size = get_remote_packet_size ();
8707 va_list ap;
8708
8709 va_start (ap, format);
8710
8711 rs->buf[0] = '\0';
8712 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8713 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8714
8715 if (putpkt (rs->buf) < 0)
8716 error (_("Communication problem with target."));
8717
8718 rs->buf[0] = '\0';
8719 getpkt (&rs->buf, &rs->buf_size, 0);
8720
8721 return packet_check_result (rs->buf);
8722 }
8723
8724 /* Flash writing can take quite some time. We'll set
8725 effectively infinite timeout for flash operations.
8726 In future, we'll need to decide on a better approach. */
8727 static const int remote_flash_timeout = 1000;
8728
8729 void
8730 remote_target::flash_erase (ULONGEST address, LONGEST length)
8731 {
8732 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8733 enum packet_result ret;
8734 scoped_restore restore_timeout
8735 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8736
8737 ret = remote_send_printf ("vFlashErase:%s,%s",
8738 phex (address, addr_size),
8739 phex (length, 4));
8740 switch (ret)
8741 {
8742 case PACKET_UNKNOWN:
8743 error (_("Remote target does not support flash erase"));
8744 case PACKET_ERROR:
8745 error (_("Error erasing flash with vFlashErase packet"));
8746 default:
8747 break;
8748 }
8749 }
8750
8751 static enum target_xfer_status
8752 remote_flash_write (struct target_ops *ops, ULONGEST address,
8753 ULONGEST length, ULONGEST *xfered_len,
8754 const gdb_byte *data)
8755 {
8756 scoped_restore restore_timeout
8757 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8758 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8759 xfered_len,'X', 0);
8760 }
8761
8762 void
8763 remote_target::flash_done ()
8764 {
8765 int ret;
8766
8767 scoped_restore restore_timeout
8768 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8769
8770 ret = remote_send_printf ("vFlashDone");
8771
8772 switch (ret)
8773 {
8774 case PACKET_UNKNOWN:
8775 error (_("Remote target does not support vFlashDone"));
8776 case PACKET_ERROR:
8777 error (_("Error finishing flash operation"));
8778 default:
8779 break;
8780 }
8781 }
8782
8783 void
8784 remote_target::files_info ()
8785 {
8786 puts_filtered ("Debugging a target over a serial line.\n");
8787 }
8788 \f
8789 /* Stuff for dealing with the packets which are part of this protocol.
8790 See comment at top of file for details. */
8791
8792 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8793 error to higher layers. Called when a serial error is detected.
8794 The exception message is STRING, followed by a colon and a blank,
8795 the system error message for errno at function entry and final dot
8796 for output compatibility with throw_perror_with_name. */
8797
8798 static void
8799 unpush_and_perror (const char *string)
8800 {
8801 int saved_errno = errno;
8802
8803 remote_unpush_target ();
8804 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8805 safe_strerror (saved_errno));
8806 }
8807
8808 /* Read a single character from the remote end. The current quit
8809 handler is overridden to avoid quitting in the middle of packet
8810 sequence, as that would break communication with the remote server.
8811 See remote_serial_quit_handler for more detail. */
8812
8813 static int
8814 readchar (int timeout)
8815 {
8816 int ch;
8817 struct remote_state *rs = get_remote_state ();
8818
8819 {
8820 scoped_restore restore_quit
8821 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8822
8823 rs->got_ctrlc_during_io = 0;
8824
8825 ch = serial_readchar (rs->remote_desc, timeout);
8826
8827 if (rs->got_ctrlc_during_io)
8828 set_quit_flag ();
8829 }
8830
8831 if (ch >= 0)
8832 return ch;
8833
8834 switch ((enum serial_rc) ch)
8835 {
8836 case SERIAL_EOF:
8837 remote_unpush_target ();
8838 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8839 /* no return */
8840 case SERIAL_ERROR:
8841 unpush_and_perror (_("Remote communication error. "
8842 "Target disconnected."));
8843 /* no return */
8844 case SERIAL_TIMEOUT:
8845 break;
8846 }
8847 return ch;
8848 }
8849
8850 /* Wrapper for serial_write that closes the target and throws if
8851 writing fails. The current quit handler is overridden to avoid
8852 quitting in the middle of packet sequence, as that would break
8853 communication with the remote server. See
8854 remote_serial_quit_handler for more detail. */
8855
8856 static void
8857 remote_serial_write (const char *str, int len)
8858 {
8859 struct remote_state *rs = get_remote_state ();
8860
8861 scoped_restore restore_quit
8862 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8863
8864 rs->got_ctrlc_during_io = 0;
8865
8866 if (serial_write (rs->remote_desc, str, len))
8867 {
8868 unpush_and_perror (_("Remote communication error. "
8869 "Target disconnected."));
8870 }
8871
8872 if (rs->got_ctrlc_during_io)
8873 set_quit_flag ();
8874 }
8875
8876 /* Return a string representing an escaped version of BUF, of len N.
8877 E.g. \n is converted to \\n, \t to \\t, etc. */
8878
8879 static std::string
8880 escape_buffer (const char *buf, int n)
8881 {
8882 string_file stb;
8883
8884 stb.putstrn (buf, n, '\\');
8885 return std::move (stb.string ());
8886 }
8887
8888 /* Display a null-terminated packet on stdout, for debugging, using C
8889 string notation. */
8890
8891 static void
8892 print_packet (const char *buf)
8893 {
8894 puts_filtered ("\"");
8895 fputstr_filtered (buf, '"', gdb_stdout);
8896 puts_filtered ("\"");
8897 }
8898
8899 int
8900 putpkt (const char *buf)
8901 {
8902 return putpkt_binary (buf, strlen (buf));
8903 }
8904
8905 /* Send a packet to the remote machine, with error checking. The data
8906 of the packet is in BUF. The string in BUF can be at most
8907 get_remote_packet_size () - 5 to account for the $, # and checksum,
8908 and for a possible /0 if we are debugging (remote_debug) and want
8909 to print the sent packet as a string. */
8910
8911 static int
8912 putpkt_binary (const char *buf, int cnt)
8913 {
8914 struct remote_state *rs = get_remote_state ();
8915 int i;
8916 unsigned char csum = 0;
8917 gdb::def_vector<char> data (cnt + 6);
8918 char *buf2 = data.data ();
8919
8920 int ch;
8921 int tcount = 0;
8922 char *p;
8923
8924 /* Catch cases like trying to read memory or listing threads while
8925 we're waiting for a stop reply. The remote server wouldn't be
8926 ready to handle this request, so we'd hang and timeout. We don't
8927 have to worry about this in synchronous mode, because in that
8928 case it's not possible to issue a command while the target is
8929 running. This is not a problem in non-stop mode, because in that
8930 case, the stub is always ready to process serial input. */
8931 if (!target_is_non_stop_p ()
8932 && target_is_async_p ()
8933 && rs->waiting_for_stop_reply)
8934 {
8935 error (_("Cannot execute this command while the target is running.\n"
8936 "Use the \"interrupt\" command to stop the target\n"
8937 "and then try again."));
8938 }
8939
8940 /* We're sending out a new packet. Make sure we don't look at a
8941 stale cached response. */
8942 rs->cached_wait_status = 0;
8943
8944 /* Copy the packet into buffer BUF2, encapsulating it
8945 and giving it a checksum. */
8946
8947 p = buf2;
8948 *p++ = '$';
8949
8950 for (i = 0; i < cnt; i++)
8951 {
8952 csum += buf[i];
8953 *p++ = buf[i];
8954 }
8955 *p++ = '#';
8956 *p++ = tohex ((csum >> 4) & 0xf);
8957 *p++ = tohex (csum & 0xf);
8958
8959 /* Send it over and over until we get a positive ack. */
8960
8961 while (1)
8962 {
8963 int started_error_output = 0;
8964
8965 if (remote_debug)
8966 {
8967 *p = '\0';
8968
8969 int len = (int) (p - buf2);
8970
8971 std::string str
8972 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8973
8974 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8975
8976 if (len > REMOTE_DEBUG_MAX_CHAR)
8977 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
8978 len - REMOTE_DEBUG_MAX_CHAR);
8979
8980 fprintf_unfiltered (gdb_stdlog, "...");
8981
8982 gdb_flush (gdb_stdlog);
8983 }
8984 remote_serial_write (buf2, p - buf2);
8985
8986 /* If this is a no acks version of the remote protocol, send the
8987 packet and move on. */
8988 if (rs->noack_mode)
8989 break;
8990
8991 /* Read until either a timeout occurs (-2) or '+' is read.
8992 Handle any notification that arrives in the mean time. */
8993 while (1)
8994 {
8995 ch = readchar (remote_timeout);
8996
8997 if (remote_debug)
8998 {
8999 switch (ch)
9000 {
9001 case '+':
9002 case '-':
9003 case SERIAL_TIMEOUT:
9004 case '$':
9005 case '%':
9006 if (started_error_output)
9007 {
9008 putchar_unfiltered ('\n');
9009 started_error_output = 0;
9010 }
9011 }
9012 }
9013
9014 switch (ch)
9015 {
9016 case '+':
9017 if (remote_debug)
9018 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9019 return 1;
9020 case '-':
9021 if (remote_debug)
9022 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9023 /* FALLTHROUGH */
9024 case SERIAL_TIMEOUT:
9025 tcount++;
9026 if (tcount > 3)
9027 return 0;
9028 break; /* Retransmit buffer. */
9029 case '$':
9030 {
9031 if (remote_debug)
9032 fprintf_unfiltered (gdb_stdlog,
9033 "Packet instead of Ack, ignoring it\n");
9034 /* It's probably an old response sent because an ACK
9035 was lost. Gobble up the packet and ack it so it
9036 doesn't get retransmitted when we resend this
9037 packet. */
9038 skip_frame ();
9039 remote_serial_write ("+", 1);
9040 continue; /* Now, go look for +. */
9041 }
9042
9043 case '%':
9044 {
9045 int val;
9046
9047 /* If we got a notification, handle it, and go back to looking
9048 for an ack. */
9049 /* We've found the start of a notification. Now
9050 collect the data. */
9051 val = read_frame (&rs->buf, &rs->buf_size);
9052 if (val >= 0)
9053 {
9054 if (remote_debug)
9055 {
9056 std::string str = escape_buffer (rs->buf, val);
9057
9058 fprintf_unfiltered (gdb_stdlog,
9059 " Notification received: %s\n",
9060 str.c_str ());
9061 }
9062 handle_notification (rs->notif_state, rs->buf);
9063 /* We're in sync now, rewait for the ack. */
9064 tcount = 0;
9065 }
9066 else
9067 {
9068 if (remote_debug)
9069 {
9070 if (!started_error_output)
9071 {
9072 started_error_output = 1;
9073 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9074 }
9075 fputc_unfiltered (ch & 0177, gdb_stdlog);
9076 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9077 }
9078 }
9079 continue;
9080 }
9081 /* fall-through */
9082 default:
9083 if (remote_debug)
9084 {
9085 if (!started_error_output)
9086 {
9087 started_error_output = 1;
9088 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9089 }
9090 fputc_unfiltered (ch & 0177, gdb_stdlog);
9091 }
9092 continue;
9093 }
9094 break; /* Here to retransmit. */
9095 }
9096
9097 #if 0
9098 /* This is wrong. If doing a long backtrace, the user should be
9099 able to get out next time we call QUIT, without anything as
9100 violent as interrupt_query. If we want to provide a way out of
9101 here without getting to the next QUIT, it should be based on
9102 hitting ^C twice as in remote_wait. */
9103 if (quit_flag)
9104 {
9105 quit_flag = 0;
9106 interrupt_query ();
9107 }
9108 #endif
9109 }
9110
9111 return 0;
9112 }
9113
9114 /* Come here after finding the start of a frame when we expected an
9115 ack. Do our best to discard the rest of this packet. */
9116
9117 static void
9118 skip_frame (void)
9119 {
9120 int c;
9121
9122 while (1)
9123 {
9124 c = readchar (remote_timeout);
9125 switch (c)
9126 {
9127 case SERIAL_TIMEOUT:
9128 /* Nothing we can do. */
9129 return;
9130 case '#':
9131 /* Discard the two bytes of checksum and stop. */
9132 c = readchar (remote_timeout);
9133 if (c >= 0)
9134 c = readchar (remote_timeout);
9135
9136 return;
9137 case '*': /* Run length encoding. */
9138 /* Discard the repeat count. */
9139 c = readchar (remote_timeout);
9140 if (c < 0)
9141 return;
9142 break;
9143 default:
9144 /* A regular character. */
9145 break;
9146 }
9147 }
9148 }
9149
9150 /* Come here after finding the start of the frame. Collect the rest
9151 into *BUF, verifying the checksum, length, and handling run-length
9152 compression. NUL terminate the buffer. If there is not enough room,
9153 expand *BUF using xrealloc.
9154
9155 Returns -1 on error, number of characters in buffer (ignoring the
9156 trailing NULL) on success. (could be extended to return one of the
9157 SERIAL status indications). */
9158
9159 static long
9160 read_frame (char **buf_p,
9161 long *sizeof_buf)
9162 {
9163 unsigned char csum;
9164 long bc;
9165 int c;
9166 char *buf = *buf_p;
9167 struct remote_state *rs = get_remote_state ();
9168
9169 csum = 0;
9170 bc = 0;
9171
9172 while (1)
9173 {
9174 c = readchar (remote_timeout);
9175 switch (c)
9176 {
9177 case SERIAL_TIMEOUT:
9178 if (remote_debug)
9179 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9180 return -1;
9181 case '$':
9182 if (remote_debug)
9183 fputs_filtered ("Saw new packet start in middle of old one\n",
9184 gdb_stdlog);
9185 return -1; /* Start a new packet, count retries. */
9186 case '#':
9187 {
9188 unsigned char pktcsum;
9189 int check_0 = 0;
9190 int check_1 = 0;
9191
9192 buf[bc] = '\0';
9193
9194 check_0 = readchar (remote_timeout);
9195 if (check_0 >= 0)
9196 check_1 = readchar (remote_timeout);
9197
9198 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9199 {
9200 if (remote_debug)
9201 fputs_filtered ("Timeout in checksum, retrying\n",
9202 gdb_stdlog);
9203 return -1;
9204 }
9205 else if (check_0 < 0 || check_1 < 0)
9206 {
9207 if (remote_debug)
9208 fputs_filtered ("Communication error in checksum\n",
9209 gdb_stdlog);
9210 return -1;
9211 }
9212
9213 /* Don't recompute the checksum; with no ack packets we
9214 don't have any way to indicate a packet retransmission
9215 is necessary. */
9216 if (rs->noack_mode)
9217 return bc;
9218
9219 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9220 if (csum == pktcsum)
9221 return bc;
9222
9223 if (remote_debug)
9224 {
9225 std::string str = escape_buffer (buf, bc);
9226
9227 fprintf_unfiltered (gdb_stdlog,
9228 "Bad checksum, sentsum=0x%x, "
9229 "csum=0x%x, buf=%s\n",
9230 pktcsum, csum, str.c_str ());
9231 }
9232 /* Number of characters in buffer ignoring trailing
9233 NULL. */
9234 return -1;
9235 }
9236 case '*': /* Run length encoding. */
9237 {
9238 int repeat;
9239
9240 csum += c;
9241 c = readchar (remote_timeout);
9242 csum += c;
9243 repeat = c - ' ' + 3; /* Compute repeat count. */
9244
9245 /* The character before ``*'' is repeated. */
9246
9247 if (repeat > 0 && repeat <= 255 && bc > 0)
9248 {
9249 if (bc + repeat - 1 >= *sizeof_buf - 1)
9250 {
9251 /* Make some more room in the buffer. */
9252 *sizeof_buf += repeat;
9253 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9254 buf = *buf_p;
9255 }
9256
9257 memset (&buf[bc], buf[bc - 1], repeat);
9258 bc += repeat;
9259 continue;
9260 }
9261
9262 buf[bc] = '\0';
9263 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9264 return -1;
9265 }
9266 default:
9267 if (bc >= *sizeof_buf - 1)
9268 {
9269 /* Make some more room in the buffer. */
9270 *sizeof_buf *= 2;
9271 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9272 buf = *buf_p;
9273 }
9274
9275 buf[bc++] = c;
9276 csum += c;
9277 continue;
9278 }
9279 }
9280 }
9281
9282 /* Read a packet from the remote machine, with error checking, and
9283 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9284 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9285 rather than timing out; this is used (in synchronous mode) to wait
9286 for a target that is is executing user code to stop. */
9287 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9288 don't have to change all the calls to getpkt to deal with the
9289 return value, because at the moment I don't know what the right
9290 thing to do it for those. */
9291 void
9292 getpkt (char **buf,
9293 long *sizeof_buf,
9294 int forever)
9295 {
9296 getpkt_sane (buf, sizeof_buf, forever);
9297 }
9298
9299
9300 /* Read a packet from the remote machine, with error checking, and
9301 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9302 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9303 rather than timing out; this is used (in synchronous mode) to wait
9304 for a target that is is executing user code to stop. If FOREVER ==
9305 0, this function is allowed to time out gracefully and return an
9306 indication of this to the caller. Otherwise return the number of
9307 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9308 enough reason to return to the caller. *IS_NOTIF is an output
9309 boolean that indicates whether *BUF holds a notification or not
9310 (a regular packet). */
9311
9312 static int
9313 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9314 int expecting_notif, int *is_notif)
9315 {
9316 struct remote_state *rs = get_remote_state ();
9317 int c;
9318 int tries;
9319 int timeout;
9320 int val = -1;
9321
9322 /* We're reading a new response. Make sure we don't look at a
9323 previously cached response. */
9324 rs->cached_wait_status = 0;
9325
9326 strcpy (*buf, "timeout");
9327
9328 if (forever)
9329 timeout = watchdog > 0 ? watchdog : -1;
9330 else if (expecting_notif)
9331 timeout = 0; /* There should already be a char in the buffer. If
9332 not, bail out. */
9333 else
9334 timeout = remote_timeout;
9335
9336 #define MAX_TRIES 3
9337
9338 /* Process any number of notifications, and then return when
9339 we get a packet. */
9340 for (;;)
9341 {
9342 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9343 times. */
9344 for (tries = 1; tries <= MAX_TRIES; tries++)
9345 {
9346 /* This can loop forever if the remote side sends us
9347 characters continuously, but if it pauses, we'll get
9348 SERIAL_TIMEOUT from readchar because of timeout. Then
9349 we'll count that as a retry.
9350
9351 Note that even when forever is set, we will only wait
9352 forever prior to the start of a packet. After that, we
9353 expect characters to arrive at a brisk pace. They should
9354 show up within remote_timeout intervals. */
9355 do
9356 c = readchar (timeout);
9357 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9358
9359 if (c == SERIAL_TIMEOUT)
9360 {
9361 if (expecting_notif)
9362 return -1; /* Don't complain, it's normal to not get
9363 anything in this case. */
9364
9365 if (forever) /* Watchdog went off? Kill the target. */
9366 {
9367 remote_unpush_target ();
9368 throw_error (TARGET_CLOSE_ERROR,
9369 _("Watchdog timeout has expired. "
9370 "Target detached."));
9371 }
9372 if (remote_debug)
9373 fputs_filtered ("Timed out.\n", gdb_stdlog);
9374 }
9375 else
9376 {
9377 /* We've found the start of a packet or notification.
9378 Now collect the data. */
9379 val = read_frame (buf, sizeof_buf);
9380 if (val >= 0)
9381 break;
9382 }
9383
9384 remote_serial_write ("-", 1);
9385 }
9386
9387 if (tries > MAX_TRIES)
9388 {
9389 /* We have tried hard enough, and just can't receive the
9390 packet/notification. Give up. */
9391 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9392
9393 /* Skip the ack char if we're in no-ack mode. */
9394 if (!rs->noack_mode)
9395 remote_serial_write ("+", 1);
9396 return -1;
9397 }
9398
9399 /* If we got an ordinary packet, return that to our caller. */
9400 if (c == '$')
9401 {
9402 if (remote_debug)
9403 {
9404 std::string str
9405 = escape_buffer (*buf,
9406 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9407
9408 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9409 str.c_str ());
9410
9411 if (val > REMOTE_DEBUG_MAX_CHAR)
9412 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9413 val - REMOTE_DEBUG_MAX_CHAR);
9414
9415 fprintf_unfiltered (gdb_stdlog, "\n");
9416 }
9417
9418 /* Skip the ack char if we're in no-ack mode. */
9419 if (!rs->noack_mode)
9420 remote_serial_write ("+", 1);
9421 if (is_notif != NULL)
9422 *is_notif = 0;
9423 return val;
9424 }
9425
9426 /* If we got a notification, handle it, and go back to looking
9427 for a packet. */
9428 else
9429 {
9430 gdb_assert (c == '%');
9431
9432 if (remote_debug)
9433 {
9434 std::string str = escape_buffer (*buf, val);
9435
9436 fprintf_unfiltered (gdb_stdlog,
9437 " Notification received: %s\n",
9438 str.c_str ());
9439 }
9440 if (is_notif != NULL)
9441 *is_notif = 1;
9442
9443 handle_notification (rs->notif_state, *buf);
9444
9445 /* Notifications require no acknowledgement. */
9446
9447 if (expecting_notif)
9448 return val;
9449 }
9450 }
9451 }
9452
9453 static int
9454 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9455 {
9456 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9457 }
9458
9459 static int
9460 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9461 int *is_notif)
9462 {
9463 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9464 is_notif);
9465 }
9466
9467 /* Check whether EVENT is a fork event for the process specified
9468 by the pid passed in DATA, and if it is, kill the fork child. */
9469
9470 static int
9471 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9472 QUEUE_ITER (stop_reply_p) *iter,
9473 stop_reply_p event,
9474 void *data)
9475 {
9476 struct queue_iter_param *param = (struct queue_iter_param *) data;
9477 int parent_pid = *(int *) param->input;
9478
9479 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9480 {
9481 struct remote_state *rs = get_remote_state ();
9482 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9483 int res;
9484
9485 res = remote_vkill (child_pid, rs);
9486 if (res != 0)
9487 error (_("Can't kill fork child process %d"), child_pid);
9488 }
9489
9490 return 1;
9491 }
9492
9493 /* Kill any new fork children of process PID that haven't been
9494 processed by follow_fork. */
9495
9496 static void
9497 kill_new_fork_children (int pid, struct remote_state *rs)
9498 {
9499 struct thread_info *thread;
9500 struct notif_client *notif = &notif_client_stop;
9501 struct queue_iter_param param;
9502
9503 /* Kill the fork child threads of any threads in process PID
9504 that are stopped at a fork event. */
9505 ALL_NON_EXITED_THREADS (thread)
9506 {
9507 struct target_waitstatus *ws = &thread->pending_follow;
9508
9509 if (is_pending_fork_parent (ws, pid, thread->ptid))
9510 {
9511 struct remote_state *rs = get_remote_state ();
9512 int child_pid = ptid_get_pid (ws->value.related_pid);
9513 int res;
9514
9515 res = remote_vkill (child_pid, rs);
9516 if (res != 0)
9517 error (_("Can't kill fork child process %d"), child_pid);
9518 }
9519 }
9520
9521 /* Check for any pending fork events (not reported or processed yet)
9522 in process PID and kill those fork child threads as well. */
9523 remote_notif_get_pending_events (notif);
9524 param.input = &pid;
9525 param.output = NULL;
9526 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9527 kill_child_of_pending_fork, &param);
9528 }
9529
9530 \f
9531 /* Target hook to kill the current inferior. */
9532
9533 void
9534 remote_target::kill ()
9535 {
9536 int res = -1;
9537 int pid = ptid_get_pid (inferior_ptid);
9538 struct remote_state *rs = get_remote_state ();
9539
9540 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9541 {
9542 /* If we're stopped while forking and we haven't followed yet,
9543 kill the child task. We need to do this before killing the
9544 parent task because if this is a vfork then the parent will
9545 be sleeping. */
9546 kill_new_fork_children (pid, rs);
9547
9548 res = remote_vkill (pid, rs);
9549 if (res == 0)
9550 {
9551 target_mourn_inferior (inferior_ptid);
9552 return;
9553 }
9554 }
9555
9556 /* If we are in 'target remote' mode and we are killing the only
9557 inferior, then we will tell gdbserver to exit and unpush the
9558 target. */
9559 if (res == -1 && !remote_multi_process_p (rs)
9560 && number_of_live_inferiors () == 1)
9561 {
9562 remote_kill_k ();
9563
9564 /* We've killed the remote end, we get to mourn it. If we are
9565 not in extended mode, mourning the inferior also unpushes
9566 remote_ops from the target stack, which closes the remote
9567 connection. */
9568 target_mourn_inferior (inferior_ptid);
9569
9570 return;
9571 }
9572
9573 error (_("Can't kill process"));
9574 }
9575
9576 /* Send a kill request to the target using the 'vKill' packet. */
9577
9578 static int
9579 remote_vkill (int pid, struct remote_state *rs)
9580 {
9581 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9582 return -1;
9583
9584 /* Tell the remote target to detach. */
9585 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9586 putpkt (rs->buf);
9587 getpkt (&rs->buf, &rs->buf_size, 0);
9588
9589 switch (packet_ok (rs->buf,
9590 &remote_protocol_packets[PACKET_vKill]))
9591 {
9592 case PACKET_OK:
9593 return 0;
9594 case PACKET_ERROR:
9595 return 1;
9596 case PACKET_UNKNOWN:
9597 return -1;
9598 default:
9599 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9600 }
9601 }
9602
9603 /* Send a kill request to the target using the 'k' packet. */
9604
9605 static void
9606 remote_kill_k (void)
9607 {
9608 /* Catch errors so the user can quit from gdb even when we
9609 aren't on speaking terms with the remote system. */
9610 TRY
9611 {
9612 putpkt ("k");
9613 }
9614 CATCH (ex, RETURN_MASK_ERROR)
9615 {
9616 if (ex.error == TARGET_CLOSE_ERROR)
9617 {
9618 /* If we got an (EOF) error that caused the target
9619 to go away, then we're done, that's what we wanted.
9620 "k" is susceptible to cause a premature EOF, given
9621 that the remote server isn't actually required to
9622 reply to "k", and it can happen that it doesn't
9623 even get to reply ACK to the "k". */
9624 return;
9625 }
9626
9627 /* Otherwise, something went wrong. We didn't actually kill
9628 the target. Just propagate the exception, and let the
9629 user or higher layers decide what to do. */
9630 throw_exception (ex);
9631 }
9632 END_CATCH
9633 }
9634
9635 void
9636 remote_target::mourn_inferior ()
9637 {
9638 struct remote_state *rs = get_remote_state ();
9639
9640 /* In 'target remote' mode with one inferior, we close the connection. */
9641 if (!rs->extended && number_of_live_inferiors () <= 1)
9642 {
9643 unpush_target (this);
9644
9645 /* remote_close takes care of doing most of the clean up. */
9646 generic_mourn_inferior ();
9647 return;
9648 }
9649
9650 /* In case we got here due to an error, but we're going to stay
9651 connected. */
9652 rs->waiting_for_stop_reply = 0;
9653
9654 /* If the current general thread belonged to the process we just
9655 detached from or has exited, the remote side current general
9656 thread becomes undefined. Considering a case like this:
9657
9658 - We just got here due to a detach.
9659 - The process that we're detaching from happens to immediately
9660 report a global breakpoint being hit in non-stop mode, in the
9661 same thread we had selected before.
9662 - GDB attaches to this process again.
9663 - This event happens to be the next event we handle.
9664
9665 GDB would consider that the current general thread didn't need to
9666 be set on the stub side (with Hg), since for all it knew,
9667 GENERAL_THREAD hadn't changed.
9668
9669 Notice that although in all-stop mode, the remote server always
9670 sets the current thread to the thread reporting the stop event,
9671 that doesn't happen in non-stop mode; in non-stop, the stub *must
9672 not* change the current thread when reporting a breakpoint hit,
9673 due to the decoupling of event reporting and event handling.
9674
9675 To keep things simple, we always invalidate our notion of the
9676 current thread. */
9677 record_currthread (rs, minus_one_ptid);
9678
9679 /* Call common code to mark the inferior as not running. */
9680 generic_mourn_inferior ();
9681
9682 if (!have_inferiors ())
9683 {
9684 if (!remote_multi_process_p (rs))
9685 {
9686 /* Check whether the target is running now - some remote stubs
9687 automatically restart after kill. */
9688 putpkt ("?");
9689 getpkt (&rs->buf, &rs->buf_size, 0);
9690
9691 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9692 {
9693 /* Assume that the target has been restarted. Set
9694 inferior_ptid so that bits of core GDB realizes
9695 there's something here, e.g., so that the user can
9696 say "kill" again. */
9697 inferior_ptid = magic_null_ptid;
9698 }
9699 }
9700 }
9701 }
9702
9703 int
9704 extended_remote_target::supports_disable_randomization ()
9705 {
9706 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9707 }
9708
9709 static void
9710 extended_remote_disable_randomization (int val)
9711 {
9712 struct remote_state *rs = get_remote_state ();
9713 char *reply;
9714
9715 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9716 val);
9717 putpkt (rs->buf);
9718 reply = remote_get_noisy_reply ();
9719 if (*reply == '\0')
9720 error (_("Target does not support QDisableRandomization."));
9721 if (strcmp (reply, "OK") != 0)
9722 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9723 }
9724
9725 static int
9726 extended_remote_run (const std::string &args)
9727 {
9728 struct remote_state *rs = get_remote_state ();
9729 int len;
9730 const char *remote_exec_file = get_remote_exec_file ();
9731
9732 /* If the user has disabled vRun support, or we have detected that
9733 support is not available, do not try it. */
9734 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9735 return -1;
9736
9737 strcpy (rs->buf, "vRun;");
9738 len = strlen (rs->buf);
9739
9740 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9741 error (_("Remote file name too long for run packet"));
9742 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9743 strlen (remote_exec_file));
9744
9745 if (!args.empty ())
9746 {
9747 int i;
9748
9749 gdb_argv argv (args.c_str ());
9750 for (i = 0; argv[i] != NULL; i++)
9751 {
9752 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9753 error (_("Argument list too long for run packet"));
9754 rs->buf[len++] = ';';
9755 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9756 strlen (argv[i]));
9757 }
9758 }
9759
9760 rs->buf[len++] = '\0';
9761
9762 putpkt (rs->buf);
9763 getpkt (&rs->buf, &rs->buf_size, 0);
9764
9765 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9766 {
9767 case PACKET_OK:
9768 /* We have a wait response. All is well. */
9769 return 0;
9770 case PACKET_UNKNOWN:
9771 return -1;
9772 case PACKET_ERROR:
9773 if (remote_exec_file[0] == '\0')
9774 error (_("Running the default executable on the remote target failed; "
9775 "try \"set remote exec-file\"?"));
9776 else
9777 error (_("Running \"%s\" on the remote target failed"),
9778 remote_exec_file);
9779 default:
9780 gdb_assert_not_reached (_("bad switch"));
9781 }
9782 }
9783
9784 /* Helper function to send set/unset environment packets. ACTION is
9785 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9786 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9787 sent. */
9788
9789 static void
9790 send_environment_packet (struct remote_state *rs,
9791 const char *action,
9792 const char *packet,
9793 const char *value)
9794 {
9795 /* Convert the environment variable to an hex string, which
9796 is the best format to be transmitted over the wire. */
9797 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9798 strlen (value));
9799
9800 xsnprintf (rs->buf, get_remote_packet_size (),
9801 "%s:%s", packet, encoded_value.c_str ());
9802
9803 putpkt (rs->buf);
9804 getpkt (&rs->buf, &rs->buf_size, 0);
9805 if (strcmp (rs->buf, "OK") != 0)
9806 warning (_("Unable to %s environment variable '%s' on remote."),
9807 action, value);
9808 }
9809
9810 /* Helper function to handle the QEnvironment* packets. */
9811
9812 static void
9813 extended_remote_environment_support (struct remote_state *rs)
9814 {
9815 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9816 {
9817 putpkt ("QEnvironmentReset");
9818 getpkt (&rs->buf, &rs->buf_size, 0);
9819 if (strcmp (rs->buf, "OK") != 0)
9820 warning (_("Unable to reset environment on remote."));
9821 }
9822
9823 gdb_environ *e = &current_inferior ()->environment;
9824
9825 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9826 for (const std::string &el : e->user_set_env ())
9827 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9828 el.c_str ());
9829
9830 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9831 for (const std::string &el : e->user_unset_env ())
9832 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9833 }
9834
9835 /* Helper function to set the current working directory for the
9836 inferior in the remote target. */
9837
9838 static void
9839 extended_remote_set_inferior_cwd (struct remote_state *rs)
9840 {
9841 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9842 {
9843 const char *inferior_cwd = get_inferior_cwd ();
9844
9845 if (inferior_cwd != NULL)
9846 {
9847 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9848 strlen (inferior_cwd));
9849
9850 xsnprintf (rs->buf, get_remote_packet_size (),
9851 "QSetWorkingDir:%s", hexpath.c_str ());
9852 }
9853 else
9854 {
9855 /* An empty inferior_cwd means that the user wants us to
9856 reset the remote server's inferior's cwd. */
9857 xsnprintf (rs->buf, get_remote_packet_size (),
9858 "QSetWorkingDir:");
9859 }
9860
9861 putpkt (rs->buf);
9862 getpkt (&rs->buf, &rs->buf_size, 0);
9863 if (packet_ok (rs->buf,
9864 &remote_protocol_packets[PACKET_QSetWorkingDir])
9865 != PACKET_OK)
9866 error (_("\
9867 Remote replied unexpectedly while setting the inferior's working\n\
9868 directory: %s"),
9869 rs->buf);
9870
9871 }
9872 }
9873
9874 /* In the extended protocol we want to be able to do things like
9875 "run" and have them basically work as expected. So we need
9876 a special create_inferior function. We support changing the
9877 executable file and the command line arguments, but not the
9878 environment. */
9879
9880 void
9881 extended_remote_target::create_inferior (const char *exec_file,
9882 const std::string &args,
9883 char **env, int from_tty)
9884 {
9885 int run_worked;
9886 char *stop_reply;
9887 struct remote_state *rs = get_remote_state ();
9888 const char *remote_exec_file = get_remote_exec_file ();
9889
9890 /* If running asynchronously, register the target file descriptor
9891 with the event loop. */
9892 if (target_can_async_p ())
9893 target_async (1);
9894
9895 /* Disable address space randomization if requested (and supported). */
9896 if (supports_disable_randomization ())
9897 extended_remote_disable_randomization (disable_randomization);
9898
9899 /* If startup-with-shell is on, we inform gdbserver to start the
9900 remote inferior using a shell. */
9901 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9902 {
9903 xsnprintf (rs->buf, get_remote_packet_size (),
9904 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9905 putpkt (rs->buf);
9906 getpkt (&rs->buf, &rs->buf_size, 0);
9907 if (strcmp (rs->buf, "OK") != 0)
9908 error (_("\
9909 Remote replied unexpectedly while setting startup-with-shell: %s"),
9910 rs->buf);
9911 }
9912
9913 extended_remote_environment_support (rs);
9914
9915 extended_remote_set_inferior_cwd (rs);
9916
9917 /* Now restart the remote server. */
9918 run_worked = extended_remote_run (args) != -1;
9919 if (!run_worked)
9920 {
9921 /* vRun was not supported. Fail if we need it to do what the
9922 user requested. */
9923 if (remote_exec_file[0])
9924 error (_("Remote target does not support \"set remote exec-file\""));
9925 if (!args.empty ())
9926 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9927
9928 /* Fall back to "R". */
9929 extended_remote_restart ();
9930 }
9931
9932 if (!have_inferiors ())
9933 {
9934 /* Clean up from the last time we ran, before we mark the target
9935 running again. This will mark breakpoints uninserted, and
9936 get_offsets may insert breakpoints. */
9937 init_thread_list ();
9938 init_wait_for_inferior ();
9939 }
9940
9941 /* vRun's success return is a stop reply. */
9942 stop_reply = run_worked ? rs->buf : NULL;
9943 add_current_inferior_and_thread (stop_reply);
9944
9945 /* Get updated offsets, if the stub uses qOffsets. */
9946 get_offsets ();
9947 }
9948 \f
9949
9950 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9951 the list of conditions (in agent expression bytecode format), if any, the
9952 target needs to evaluate. The output is placed into the packet buffer
9953 started from BUF and ended at BUF_END. */
9954
9955 static int
9956 remote_add_target_side_condition (struct gdbarch *gdbarch,
9957 struct bp_target_info *bp_tgt, char *buf,
9958 char *buf_end)
9959 {
9960 if (bp_tgt->conditions.empty ())
9961 return 0;
9962
9963 buf += strlen (buf);
9964 xsnprintf (buf, buf_end - buf, "%s", ";");
9965 buf++;
9966
9967 /* Send conditions to the target. */
9968 for (agent_expr *aexpr : bp_tgt->conditions)
9969 {
9970 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9971 buf += strlen (buf);
9972 for (int i = 0; i < aexpr->len; ++i)
9973 buf = pack_hex_byte (buf, aexpr->buf[i]);
9974 *buf = '\0';
9975 }
9976 return 0;
9977 }
9978
9979 static void
9980 remote_add_target_side_commands (struct gdbarch *gdbarch,
9981 struct bp_target_info *bp_tgt, char *buf)
9982 {
9983 if (bp_tgt->tcommands.empty ())
9984 return;
9985
9986 buf += strlen (buf);
9987
9988 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9989 buf += strlen (buf);
9990
9991 /* Concatenate all the agent expressions that are commands into the
9992 cmds parameter. */
9993 for (agent_expr *aexpr : bp_tgt->tcommands)
9994 {
9995 sprintf (buf, "X%x,", aexpr->len);
9996 buf += strlen (buf);
9997 for (int i = 0; i < aexpr->len; ++i)
9998 buf = pack_hex_byte (buf, aexpr->buf[i]);
9999 *buf = '\0';
10000 }
10001 }
10002
10003 /* Insert a breakpoint. On targets that have software breakpoint
10004 support, we ask the remote target to do the work; on targets
10005 which don't, we insert a traditional memory breakpoint. */
10006
10007 int
10008 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10009 struct bp_target_info *bp_tgt)
10010 {
10011 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10012 If it succeeds, then set the support to PACKET_ENABLE. If it
10013 fails, and the user has explicitly requested the Z support then
10014 report an error, otherwise, mark it disabled and go on. */
10015
10016 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10017 {
10018 CORE_ADDR addr = bp_tgt->reqstd_address;
10019 struct remote_state *rs;
10020 char *p, *endbuf;
10021
10022 /* Make sure the remote is pointing at the right process, if
10023 necessary. */
10024 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10025 set_general_process ();
10026
10027 rs = get_remote_state ();
10028 p = rs->buf;
10029 endbuf = rs->buf + get_remote_packet_size ();
10030
10031 *(p++) = 'Z';
10032 *(p++) = '0';
10033 *(p++) = ',';
10034 addr = (ULONGEST) remote_address_masked (addr);
10035 p += hexnumstr (p, addr);
10036 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10037
10038 if (supports_evaluation_of_breakpoint_conditions ())
10039 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10040
10041 if (can_run_breakpoint_commands ())
10042 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10043
10044 putpkt (rs->buf);
10045 getpkt (&rs->buf, &rs->buf_size, 0);
10046
10047 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10048 {
10049 case PACKET_ERROR:
10050 return -1;
10051 case PACKET_OK:
10052 return 0;
10053 case PACKET_UNKNOWN:
10054 break;
10055 }
10056 }
10057
10058 /* If this breakpoint has target-side commands but this stub doesn't
10059 support Z0 packets, throw error. */
10060 if (!bp_tgt->tcommands.empty ())
10061 throw_error (NOT_SUPPORTED_ERROR, _("\
10062 Target doesn't support breakpoints that have target side commands."));
10063
10064 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10065 }
10066
10067 int
10068 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10069 struct bp_target_info *bp_tgt,
10070 enum remove_bp_reason reason)
10071 {
10072 CORE_ADDR addr = bp_tgt->placed_address;
10073 struct remote_state *rs = get_remote_state ();
10074
10075 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10076 {
10077 char *p = rs->buf;
10078 char *endbuf = rs->buf + get_remote_packet_size ();
10079
10080 /* Make sure the remote is pointing at the right process, if
10081 necessary. */
10082 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10083 set_general_process ();
10084
10085 *(p++) = 'z';
10086 *(p++) = '0';
10087 *(p++) = ',';
10088
10089 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10090 p += hexnumstr (p, addr);
10091 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10092
10093 putpkt (rs->buf);
10094 getpkt (&rs->buf, &rs->buf_size, 0);
10095
10096 return (rs->buf[0] == 'E');
10097 }
10098
10099 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10100 }
10101
10102 static enum Z_packet_type
10103 watchpoint_to_Z_packet (int type)
10104 {
10105 switch (type)
10106 {
10107 case hw_write:
10108 return Z_PACKET_WRITE_WP;
10109 break;
10110 case hw_read:
10111 return Z_PACKET_READ_WP;
10112 break;
10113 case hw_access:
10114 return Z_PACKET_ACCESS_WP;
10115 break;
10116 default:
10117 internal_error (__FILE__, __LINE__,
10118 _("hw_bp_to_z: bad watchpoint type %d"), type);
10119 }
10120 }
10121
10122 int
10123 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10124 enum target_hw_bp_type type, struct expression *cond)
10125 {
10126 struct remote_state *rs = get_remote_state ();
10127 char *endbuf = rs->buf + get_remote_packet_size ();
10128 char *p;
10129 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10130
10131 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10132 return 1;
10133
10134 /* Make sure the remote is pointing at the right process, if
10135 necessary. */
10136 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10137 set_general_process ();
10138
10139 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10140 p = strchr (rs->buf, '\0');
10141 addr = remote_address_masked (addr);
10142 p += hexnumstr (p, (ULONGEST) addr);
10143 xsnprintf (p, endbuf - p, ",%x", len);
10144
10145 putpkt (rs->buf);
10146 getpkt (&rs->buf, &rs->buf_size, 0);
10147
10148 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10149 {
10150 case PACKET_ERROR:
10151 return -1;
10152 case PACKET_UNKNOWN:
10153 return 1;
10154 case PACKET_OK:
10155 return 0;
10156 }
10157 internal_error (__FILE__, __LINE__,
10158 _("remote_insert_watchpoint: reached end of function"));
10159 }
10160
10161 int
10162 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10163 CORE_ADDR start, int length)
10164 {
10165 CORE_ADDR diff = remote_address_masked (addr - start);
10166
10167 return diff < length;
10168 }
10169
10170
10171 int
10172 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10173 enum target_hw_bp_type type, struct expression *cond)
10174 {
10175 struct remote_state *rs = get_remote_state ();
10176 char *endbuf = rs->buf + get_remote_packet_size ();
10177 char *p;
10178 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10179
10180 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10181 return -1;
10182
10183 /* Make sure the remote is pointing at the right process, if
10184 necessary. */
10185 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10186 set_general_process ();
10187
10188 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10189 p = strchr (rs->buf, '\0');
10190 addr = remote_address_masked (addr);
10191 p += hexnumstr (p, (ULONGEST) addr);
10192 xsnprintf (p, endbuf - p, ",%x", len);
10193 putpkt (rs->buf);
10194 getpkt (&rs->buf, &rs->buf_size, 0);
10195
10196 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10197 {
10198 case PACKET_ERROR:
10199 case PACKET_UNKNOWN:
10200 return -1;
10201 case PACKET_OK:
10202 return 0;
10203 }
10204 internal_error (__FILE__, __LINE__,
10205 _("remote_remove_watchpoint: reached end of function"));
10206 }
10207
10208
10209 int remote_hw_watchpoint_limit = -1;
10210 int remote_hw_watchpoint_length_limit = -1;
10211 int remote_hw_breakpoint_limit = -1;
10212
10213 int
10214 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10215 {
10216 if (remote_hw_watchpoint_length_limit == 0)
10217 return 0;
10218 else if (remote_hw_watchpoint_length_limit < 0)
10219 return 1;
10220 else if (len <= remote_hw_watchpoint_length_limit)
10221 return 1;
10222 else
10223 return 0;
10224 }
10225
10226 int
10227 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10228 {
10229 if (type == bp_hardware_breakpoint)
10230 {
10231 if (remote_hw_breakpoint_limit == 0)
10232 return 0;
10233 else if (remote_hw_breakpoint_limit < 0)
10234 return 1;
10235 else if (cnt <= remote_hw_breakpoint_limit)
10236 return 1;
10237 }
10238 else
10239 {
10240 if (remote_hw_watchpoint_limit == 0)
10241 return 0;
10242 else if (remote_hw_watchpoint_limit < 0)
10243 return 1;
10244 else if (ot)
10245 return -1;
10246 else if (cnt <= remote_hw_watchpoint_limit)
10247 return 1;
10248 }
10249 return -1;
10250 }
10251
10252 /* The to_stopped_by_sw_breakpoint method of target remote. */
10253
10254 int
10255 remote_target::stopped_by_sw_breakpoint ()
10256 {
10257 struct thread_info *thread = inferior_thread ();
10258
10259 return (thread->priv != NULL
10260 && (get_remote_thread_info (thread)->stop_reason
10261 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10262 }
10263
10264 /* The to_supports_stopped_by_sw_breakpoint method of target
10265 remote. */
10266
10267 int
10268 remote_target::supports_stopped_by_sw_breakpoint ()
10269 {
10270 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10271 }
10272
10273 /* The to_stopped_by_hw_breakpoint method of target remote. */
10274
10275 int
10276 remote_target::stopped_by_hw_breakpoint ()
10277 {
10278 struct thread_info *thread = inferior_thread ();
10279
10280 return (thread->priv != NULL
10281 && (get_remote_thread_info (thread)->stop_reason
10282 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10283 }
10284
10285 /* The to_supports_stopped_by_hw_breakpoint method of target
10286 remote. */
10287
10288 int
10289 remote_target::supports_stopped_by_hw_breakpoint ()
10290 {
10291 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10292 }
10293
10294 int
10295 remote_target::stopped_by_watchpoint ()
10296 {
10297 struct thread_info *thread = inferior_thread ();
10298
10299 return (thread->priv != NULL
10300 && (get_remote_thread_info (thread)->stop_reason
10301 == TARGET_STOPPED_BY_WATCHPOINT));
10302 }
10303
10304 int
10305 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10306 {
10307 struct thread_info *thread = inferior_thread ();
10308
10309 if (thread->priv != NULL
10310 && (get_remote_thread_info (thread)->stop_reason
10311 == TARGET_STOPPED_BY_WATCHPOINT))
10312 {
10313 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10314 return 1;
10315 }
10316
10317 return 0;
10318 }
10319
10320
10321 int
10322 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10323 struct bp_target_info *bp_tgt)
10324 {
10325 CORE_ADDR addr = bp_tgt->reqstd_address;
10326 struct remote_state *rs;
10327 char *p, *endbuf;
10328 char *message;
10329
10330 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10331 return -1;
10332
10333 /* Make sure the remote is pointing at the right process, if
10334 necessary. */
10335 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10336 set_general_process ();
10337
10338 rs = get_remote_state ();
10339 p = rs->buf;
10340 endbuf = rs->buf + get_remote_packet_size ();
10341
10342 *(p++) = 'Z';
10343 *(p++) = '1';
10344 *(p++) = ',';
10345
10346 addr = remote_address_masked (addr);
10347 p += hexnumstr (p, (ULONGEST) addr);
10348 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10349
10350 if (supports_evaluation_of_breakpoint_conditions ())
10351 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10352
10353 if (can_run_breakpoint_commands ())
10354 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10355
10356 putpkt (rs->buf);
10357 getpkt (&rs->buf, &rs->buf_size, 0);
10358
10359 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10360 {
10361 case PACKET_ERROR:
10362 if (rs->buf[1] == '.')
10363 {
10364 message = strchr (rs->buf + 2, '.');
10365 if (message)
10366 error (_("Remote failure reply: %s"), message + 1);
10367 }
10368 return -1;
10369 case PACKET_UNKNOWN:
10370 return -1;
10371 case PACKET_OK:
10372 return 0;
10373 }
10374 internal_error (__FILE__, __LINE__,
10375 _("remote_insert_hw_breakpoint: reached end of function"));
10376 }
10377
10378
10379 int
10380 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10381 struct bp_target_info *bp_tgt)
10382 {
10383 CORE_ADDR addr;
10384 struct remote_state *rs = get_remote_state ();
10385 char *p = rs->buf;
10386 char *endbuf = rs->buf + get_remote_packet_size ();
10387
10388 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10389 return -1;
10390
10391 /* Make sure the remote is pointing at the right process, if
10392 necessary. */
10393 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10394 set_general_process ();
10395
10396 *(p++) = 'z';
10397 *(p++) = '1';
10398 *(p++) = ',';
10399
10400 addr = remote_address_masked (bp_tgt->placed_address);
10401 p += hexnumstr (p, (ULONGEST) addr);
10402 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10403
10404 putpkt (rs->buf);
10405 getpkt (&rs->buf, &rs->buf_size, 0);
10406
10407 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10408 {
10409 case PACKET_ERROR:
10410 case PACKET_UNKNOWN:
10411 return -1;
10412 case PACKET_OK:
10413 return 0;
10414 }
10415 internal_error (__FILE__, __LINE__,
10416 _("remote_remove_hw_breakpoint: reached end of function"));
10417 }
10418
10419 /* Verify memory using the "qCRC:" request. */
10420
10421 int
10422 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10423 {
10424 struct remote_state *rs = get_remote_state ();
10425 unsigned long host_crc, target_crc;
10426 char *tmp;
10427
10428 /* It doesn't make sense to use qCRC if the remote target is
10429 connected but not running. */
10430 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10431 {
10432 enum packet_result result;
10433
10434 /* Make sure the remote is pointing at the right process. */
10435 set_general_process ();
10436
10437 /* FIXME: assumes lma can fit into long. */
10438 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10439 (long) lma, (long) size);
10440 putpkt (rs->buf);
10441
10442 /* Be clever; compute the host_crc before waiting for target
10443 reply. */
10444 host_crc = xcrc32 (data, size, 0xffffffff);
10445
10446 getpkt (&rs->buf, &rs->buf_size, 0);
10447
10448 result = packet_ok (rs->buf,
10449 &remote_protocol_packets[PACKET_qCRC]);
10450 if (result == PACKET_ERROR)
10451 return -1;
10452 else if (result == PACKET_OK)
10453 {
10454 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10455 target_crc = target_crc * 16 + fromhex (*tmp);
10456
10457 return (host_crc == target_crc);
10458 }
10459 }
10460
10461 return simple_verify_memory (this, data, lma, size);
10462 }
10463
10464 /* compare-sections command
10465
10466 With no arguments, compares each loadable section in the exec bfd
10467 with the same memory range on the target, and reports mismatches.
10468 Useful for verifying the image on the target against the exec file. */
10469
10470 static void
10471 compare_sections_command (const char *args, int from_tty)
10472 {
10473 asection *s;
10474 const char *sectname;
10475 bfd_size_type size;
10476 bfd_vma lma;
10477 int matched = 0;
10478 int mismatched = 0;
10479 int res;
10480 int read_only = 0;
10481
10482 if (!exec_bfd)
10483 error (_("command cannot be used without an exec file"));
10484
10485 /* Make sure the remote is pointing at the right process. */
10486 set_general_process ();
10487
10488 if (args != NULL && strcmp (args, "-r") == 0)
10489 {
10490 read_only = 1;
10491 args = NULL;
10492 }
10493
10494 for (s = exec_bfd->sections; s; s = s->next)
10495 {
10496 if (!(s->flags & SEC_LOAD))
10497 continue; /* Skip non-loadable section. */
10498
10499 if (read_only && (s->flags & SEC_READONLY) == 0)
10500 continue; /* Skip writeable sections */
10501
10502 size = bfd_get_section_size (s);
10503 if (size == 0)
10504 continue; /* Skip zero-length section. */
10505
10506 sectname = bfd_get_section_name (exec_bfd, s);
10507 if (args && strcmp (args, sectname) != 0)
10508 continue; /* Not the section selected by user. */
10509
10510 matched = 1; /* Do this section. */
10511 lma = s->lma;
10512
10513 gdb::byte_vector sectdata (size);
10514 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10515
10516 res = target_verify_memory (sectdata.data (), lma, size);
10517
10518 if (res == -1)
10519 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10520 paddress (target_gdbarch (), lma),
10521 paddress (target_gdbarch (), lma + size));
10522
10523 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10524 paddress (target_gdbarch (), lma),
10525 paddress (target_gdbarch (), lma + size));
10526 if (res)
10527 printf_filtered ("matched.\n");
10528 else
10529 {
10530 printf_filtered ("MIS-MATCHED!\n");
10531 mismatched++;
10532 }
10533 }
10534 if (mismatched > 0)
10535 warning (_("One or more sections of the target image does not match\n\
10536 the loaded file\n"));
10537 if (args && !matched)
10538 printf_filtered (_("No loaded section named '%s'.\n"), args);
10539 }
10540
10541 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10542 into remote target. The number of bytes written to the remote
10543 target is returned, or -1 for error. */
10544
10545 static enum target_xfer_status
10546 remote_write_qxfer (const char *object_name,
10547 const char *annex, const gdb_byte *writebuf,
10548 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10549 struct packet_config *packet)
10550 {
10551 int i, buf_len;
10552 ULONGEST n;
10553 struct remote_state *rs = get_remote_state ();
10554 int max_size = get_memory_write_packet_size ();
10555
10556 if (packet_config_support (packet) == PACKET_DISABLE)
10557 return TARGET_XFER_E_IO;
10558
10559 /* Insert header. */
10560 i = snprintf (rs->buf, max_size,
10561 "qXfer:%s:write:%s:%s:",
10562 object_name, annex ? annex : "",
10563 phex_nz (offset, sizeof offset));
10564 max_size -= (i + 1);
10565
10566 /* Escape as much data as fits into rs->buf. */
10567 buf_len = remote_escape_output
10568 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10569
10570 if (putpkt_binary (rs->buf, i + buf_len) < 0
10571 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10572 || packet_ok (rs->buf, packet) != PACKET_OK)
10573 return TARGET_XFER_E_IO;
10574
10575 unpack_varlen_hex (rs->buf, &n);
10576
10577 *xfered_len = n;
10578 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10579 }
10580
10581 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10582 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10583 number of bytes read is returned, or 0 for EOF, or -1 for error.
10584 The number of bytes read may be less than LEN without indicating an
10585 EOF. PACKET is checked and updated to indicate whether the remote
10586 target supports this object. */
10587
10588 static enum target_xfer_status
10589 remote_read_qxfer (const char *object_name,
10590 const char *annex,
10591 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10592 ULONGEST *xfered_len,
10593 struct packet_config *packet)
10594 {
10595 struct remote_state *rs = get_remote_state ();
10596 LONGEST i, n, packet_len;
10597
10598 if (packet_config_support (packet) == PACKET_DISABLE)
10599 return TARGET_XFER_E_IO;
10600
10601 /* Check whether we've cached an end-of-object packet that matches
10602 this request. */
10603 if (rs->finished_object)
10604 {
10605 if (strcmp (object_name, rs->finished_object) == 0
10606 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10607 && offset == rs->finished_offset)
10608 return TARGET_XFER_EOF;
10609
10610
10611 /* Otherwise, we're now reading something different. Discard
10612 the cache. */
10613 xfree (rs->finished_object);
10614 xfree (rs->finished_annex);
10615 rs->finished_object = NULL;
10616 rs->finished_annex = NULL;
10617 }
10618
10619 /* Request only enough to fit in a single packet. The actual data
10620 may not, since we don't know how much of it will need to be escaped;
10621 the target is free to respond with slightly less data. We subtract
10622 five to account for the response type and the protocol frame. */
10623 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10624 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10625 object_name, annex ? annex : "",
10626 phex_nz (offset, sizeof offset),
10627 phex_nz (n, sizeof n));
10628 i = putpkt (rs->buf);
10629 if (i < 0)
10630 return TARGET_XFER_E_IO;
10631
10632 rs->buf[0] = '\0';
10633 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10634 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10635 return TARGET_XFER_E_IO;
10636
10637 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10638 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10639
10640 /* 'm' means there is (or at least might be) more data after this
10641 batch. That does not make sense unless there's at least one byte
10642 of data in this reply. */
10643 if (rs->buf[0] == 'm' && packet_len == 1)
10644 error (_("Remote qXfer reply contained no data."));
10645
10646 /* Got some data. */
10647 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10648 packet_len - 1, readbuf, n);
10649
10650 /* 'l' is an EOF marker, possibly including a final block of data,
10651 or possibly empty. If we have the final block of a non-empty
10652 object, record this fact to bypass a subsequent partial read. */
10653 if (rs->buf[0] == 'l' && offset + i > 0)
10654 {
10655 rs->finished_object = xstrdup (object_name);
10656 rs->finished_annex = xstrdup (annex ? annex : "");
10657 rs->finished_offset = offset + i;
10658 }
10659
10660 if (i == 0)
10661 return TARGET_XFER_EOF;
10662 else
10663 {
10664 *xfered_len = i;
10665 return TARGET_XFER_OK;
10666 }
10667 }
10668
10669 enum target_xfer_status
10670 remote_target::xfer_partial (enum target_object object,
10671 const char *annex, gdb_byte *readbuf,
10672 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10673 ULONGEST *xfered_len)
10674 {
10675 struct remote_state *rs;
10676 int i;
10677 char *p2;
10678 char query_type;
10679 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10680
10681 set_remote_traceframe ();
10682 set_general_thread (inferior_ptid);
10683
10684 rs = get_remote_state ();
10685
10686 /* Handle memory using the standard memory routines. */
10687 if (object == TARGET_OBJECT_MEMORY)
10688 {
10689 /* If the remote target is connected but not running, we should
10690 pass this request down to a lower stratum (e.g. the executable
10691 file). */
10692 if (!target_has_execution)
10693 return TARGET_XFER_EOF;
10694
10695 if (writebuf != NULL)
10696 return remote_write_bytes (offset, writebuf, len, unit_size,
10697 xfered_len);
10698 else
10699 return remote_read_bytes (this, offset, readbuf, len, unit_size,
10700 xfered_len);
10701 }
10702
10703 /* Handle SPU memory using qxfer packets. */
10704 if (object == TARGET_OBJECT_SPU)
10705 {
10706 if (readbuf)
10707 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10708 xfered_len, &remote_protocol_packets
10709 [PACKET_qXfer_spu_read]);
10710 else
10711 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10712 xfered_len, &remote_protocol_packets
10713 [PACKET_qXfer_spu_write]);
10714 }
10715
10716 /* Handle extra signal info using qxfer packets. */
10717 if (object == TARGET_OBJECT_SIGNAL_INFO)
10718 {
10719 if (readbuf)
10720 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10721 xfered_len, &remote_protocol_packets
10722 [PACKET_qXfer_siginfo_read]);
10723 else
10724 return remote_write_qxfer ("siginfo", annex,
10725 writebuf, offset, len, xfered_len,
10726 &remote_protocol_packets
10727 [PACKET_qXfer_siginfo_write]);
10728 }
10729
10730 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10731 {
10732 if (readbuf)
10733 return remote_read_qxfer ("statictrace", annex,
10734 readbuf, offset, len, xfered_len,
10735 &remote_protocol_packets
10736 [PACKET_qXfer_statictrace_read]);
10737 else
10738 return TARGET_XFER_E_IO;
10739 }
10740
10741 /* Only handle flash writes. */
10742 if (writebuf != NULL)
10743 {
10744 switch (object)
10745 {
10746 case TARGET_OBJECT_FLASH:
10747 return remote_flash_write (this, offset, len, xfered_len,
10748 writebuf);
10749
10750 default:
10751 return TARGET_XFER_E_IO;
10752 }
10753 }
10754
10755 /* Map pre-existing objects onto letters. DO NOT do this for new
10756 objects!!! Instead specify new query packets. */
10757 switch (object)
10758 {
10759 case TARGET_OBJECT_AVR:
10760 query_type = 'R';
10761 break;
10762
10763 case TARGET_OBJECT_AUXV:
10764 gdb_assert (annex == NULL);
10765 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10766 xfered_len,
10767 &remote_protocol_packets[PACKET_qXfer_auxv]);
10768
10769 case TARGET_OBJECT_AVAILABLE_FEATURES:
10770 return remote_read_qxfer
10771 ("features", annex, readbuf, offset, len, xfered_len,
10772 &remote_protocol_packets[PACKET_qXfer_features]);
10773
10774 case TARGET_OBJECT_LIBRARIES:
10775 return remote_read_qxfer
10776 ("libraries", annex, readbuf, offset, len, xfered_len,
10777 &remote_protocol_packets[PACKET_qXfer_libraries]);
10778
10779 case TARGET_OBJECT_LIBRARIES_SVR4:
10780 return remote_read_qxfer
10781 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10782 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10783
10784 case TARGET_OBJECT_MEMORY_MAP:
10785 gdb_assert (annex == NULL);
10786 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10787 xfered_len,
10788 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10789
10790 case TARGET_OBJECT_OSDATA:
10791 /* Should only get here if we're connected. */
10792 gdb_assert (rs->remote_desc);
10793 return remote_read_qxfer
10794 ("osdata", annex, readbuf, offset, len, xfered_len,
10795 &remote_protocol_packets[PACKET_qXfer_osdata]);
10796
10797 case TARGET_OBJECT_THREADS:
10798 gdb_assert (annex == NULL);
10799 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10800 xfered_len,
10801 &remote_protocol_packets[PACKET_qXfer_threads]);
10802
10803 case TARGET_OBJECT_TRACEFRAME_INFO:
10804 gdb_assert (annex == NULL);
10805 return remote_read_qxfer
10806 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
10807 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10808
10809 case TARGET_OBJECT_FDPIC:
10810 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
10811 xfered_len,
10812 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10813
10814 case TARGET_OBJECT_OPENVMS_UIB:
10815 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
10816 xfered_len,
10817 &remote_protocol_packets[PACKET_qXfer_uib]);
10818
10819 case TARGET_OBJECT_BTRACE:
10820 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
10821 xfered_len,
10822 &remote_protocol_packets[PACKET_qXfer_btrace]);
10823
10824 case TARGET_OBJECT_BTRACE_CONF:
10825 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
10826 len, xfered_len,
10827 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10828
10829 case TARGET_OBJECT_EXEC_FILE:
10830 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
10831 len, xfered_len,
10832 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10833
10834 default:
10835 return TARGET_XFER_E_IO;
10836 }
10837
10838 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10839 large enough let the caller deal with it. */
10840 if (len < get_remote_packet_size ())
10841 return TARGET_XFER_E_IO;
10842 len = get_remote_packet_size ();
10843
10844 /* Except for querying the minimum buffer size, target must be open. */
10845 if (!rs->remote_desc)
10846 error (_("remote query is only available after target open"));
10847
10848 gdb_assert (annex != NULL);
10849 gdb_assert (readbuf != NULL);
10850
10851 p2 = rs->buf;
10852 *p2++ = 'q';
10853 *p2++ = query_type;
10854
10855 /* We used one buffer char for the remote protocol q command and
10856 another for the query type. As the remote protocol encapsulation
10857 uses 4 chars plus one extra in case we are debugging
10858 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10859 string. */
10860 i = 0;
10861 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10862 {
10863 /* Bad caller may have sent forbidden characters. */
10864 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10865 *p2++ = annex[i];
10866 i++;
10867 }
10868 *p2 = '\0';
10869 gdb_assert (annex[i] == '\0');
10870
10871 i = putpkt (rs->buf);
10872 if (i < 0)
10873 return TARGET_XFER_E_IO;
10874
10875 getpkt (&rs->buf, &rs->buf_size, 0);
10876 strcpy ((char *) readbuf, rs->buf);
10877
10878 *xfered_len = strlen ((char *) readbuf);
10879 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10880 }
10881
10882 /* Implementation of to_get_memory_xfer_limit. */
10883
10884 ULONGEST
10885 remote_target::get_memory_xfer_limit ()
10886 {
10887 return get_memory_write_packet_size ();
10888 }
10889
10890 int
10891 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
10892 const gdb_byte *pattern, ULONGEST pattern_len,
10893 CORE_ADDR *found_addrp)
10894 {
10895 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10896 struct remote_state *rs = get_remote_state ();
10897 int max_size = get_memory_write_packet_size ();
10898 struct packet_config *packet =
10899 &remote_protocol_packets[PACKET_qSearch_memory];
10900 /* Number of packet bytes used to encode the pattern;
10901 this could be more than PATTERN_LEN due to escape characters. */
10902 int escaped_pattern_len;
10903 /* Amount of pattern that was encodable in the packet. */
10904 int used_pattern_len;
10905 int i;
10906 int found;
10907 ULONGEST found_addr;
10908
10909 /* Don't go to the target if we don't have to. This is done before
10910 checking packet_config_support to avoid the possibility that a
10911 success for this edge case means the facility works in
10912 general. */
10913 if (pattern_len > search_space_len)
10914 return 0;
10915 if (pattern_len == 0)
10916 {
10917 *found_addrp = start_addr;
10918 return 1;
10919 }
10920
10921 /* If we already know the packet isn't supported, fall back to the simple
10922 way of searching memory. */
10923
10924 if (packet_config_support (packet) == PACKET_DISABLE)
10925 {
10926 /* Target doesn't provided special support, fall back and use the
10927 standard support (copy memory and do the search here). */
10928 return simple_search_memory (this, start_addr, search_space_len,
10929 pattern, pattern_len, found_addrp);
10930 }
10931
10932 /* Make sure the remote is pointing at the right process. */
10933 set_general_process ();
10934
10935 /* Insert header. */
10936 i = snprintf (rs->buf, max_size,
10937 "qSearch:memory:%s;%s;",
10938 phex_nz (start_addr, addr_size),
10939 phex_nz (search_space_len, sizeof (search_space_len)));
10940 max_size -= (i + 1);
10941
10942 /* Escape as much data as fits into rs->buf. */
10943 escaped_pattern_len =
10944 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10945 &used_pattern_len, max_size);
10946
10947 /* Bail if the pattern is too large. */
10948 if (used_pattern_len != pattern_len)
10949 error (_("Pattern is too large to transmit to remote target."));
10950
10951 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10952 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10953 || packet_ok (rs->buf, packet) != PACKET_OK)
10954 {
10955 /* The request may not have worked because the command is not
10956 supported. If so, fall back to the simple way. */
10957 if (packet_config_support (packet) == PACKET_DISABLE)
10958 {
10959 return simple_search_memory (this, start_addr, search_space_len,
10960 pattern, pattern_len, found_addrp);
10961 }
10962 return -1;
10963 }
10964
10965 if (rs->buf[0] == '0')
10966 found = 0;
10967 else if (rs->buf[0] == '1')
10968 {
10969 found = 1;
10970 if (rs->buf[1] != ',')
10971 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10972 unpack_varlen_hex (rs->buf + 2, &found_addr);
10973 *found_addrp = found_addr;
10974 }
10975 else
10976 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10977
10978 return found;
10979 }
10980
10981 void
10982 remote_target::rcmd (const char *command, struct ui_file *outbuf)
10983 {
10984 struct remote_state *rs = get_remote_state ();
10985 char *p = rs->buf;
10986
10987 if (!rs->remote_desc)
10988 error (_("remote rcmd is only available after target open"));
10989
10990 /* Send a NULL command across as an empty command. */
10991 if (command == NULL)
10992 command = "";
10993
10994 /* The query prefix. */
10995 strcpy (rs->buf, "qRcmd,");
10996 p = strchr (rs->buf, '\0');
10997
10998 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10999 > get_remote_packet_size ())
11000 error (_("\"monitor\" command ``%s'' is too long."), command);
11001
11002 /* Encode the actual command. */
11003 bin2hex ((const gdb_byte *) command, p, strlen (command));
11004
11005 if (putpkt (rs->buf) < 0)
11006 error (_("Communication problem with target."));
11007
11008 /* get/display the response */
11009 while (1)
11010 {
11011 char *buf;
11012
11013 /* XXX - see also remote_get_noisy_reply(). */
11014 QUIT; /* Allow user to bail out with ^C. */
11015 rs->buf[0] = '\0';
11016 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11017 {
11018 /* Timeout. Continue to (try to) read responses.
11019 This is better than stopping with an error, assuming the stub
11020 is still executing the (long) monitor command.
11021 If needed, the user can interrupt gdb using C-c, obtaining
11022 an effect similar to stop on timeout. */
11023 continue;
11024 }
11025 buf = rs->buf;
11026 if (buf[0] == '\0')
11027 error (_("Target does not support this command."));
11028 if (buf[0] == 'O' && buf[1] != 'K')
11029 {
11030 remote_console_output (buf + 1); /* 'O' message from stub. */
11031 continue;
11032 }
11033 if (strcmp (buf, "OK") == 0)
11034 break;
11035 if (strlen (buf) == 3 && buf[0] == 'E'
11036 && isdigit (buf[1]) && isdigit (buf[2]))
11037 {
11038 error (_("Protocol error with Rcmd"));
11039 }
11040 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11041 {
11042 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11043
11044 fputc_unfiltered (c, outbuf);
11045 }
11046 break;
11047 }
11048 }
11049
11050 std::vector<mem_region>
11051 remote_target::memory_map ()
11052 {
11053 std::vector<mem_region> result;
11054 gdb::optional<gdb::char_vector> text
11055 = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
11056
11057 if (text)
11058 result = parse_memory_map (text->data ());
11059
11060 return result;
11061 }
11062
11063 static void
11064 packet_command (const char *args, int from_tty)
11065 {
11066 struct remote_state *rs = get_remote_state ();
11067
11068 if (!rs->remote_desc)
11069 error (_("command can only be used with remote target"));
11070
11071 if (!args)
11072 error (_("remote-packet command requires packet text as argument"));
11073
11074 puts_filtered ("sending: ");
11075 print_packet (args);
11076 puts_filtered ("\n");
11077 putpkt (args);
11078
11079 getpkt (&rs->buf, &rs->buf_size, 0);
11080 puts_filtered ("received: ");
11081 print_packet (rs->buf);
11082 puts_filtered ("\n");
11083 }
11084
11085 #if 0
11086 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11087
11088 static void display_thread_info (struct gdb_ext_thread_info *info);
11089
11090 static void threadset_test_cmd (char *cmd, int tty);
11091
11092 static void threadalive_test (char *cmd, int tty);
11093
11094 static void threadlist_test_cmd (char *cmd, int tty);
11095
11096 int get_and_display_threadinfo (threadref *ref);
11097
11098 static void threadinfo_test_cmd (char *cmd, int tty);
11099
11100 static int thread_display_step (threadref *ref, void *context);
11101
11102 static void threadlist_update_test_cmd (char *cmd, int tty);
11103
11104 static void init_remote_threadtests (void);
11105
11106 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11107
11108 static void
11109 threadset_test_cmd (const char *cmd, int tty)
11110 {
11111 int sample_thread = SAMPLE_THREAD;
11112
11113 printf_filtered (_("Remote threadset test\n"));
11114 set_general_thread (sample_thread);
11115 }
11116
11117
11118 static void
11119 threadalive_test (const char *cmd, int tty)
11120 {
11121 int sample_thread = SAMPLE_THREAD;
11122 int pid = ptid_get_pid (inferior_ptid);
11123 ptid_t ptid = ptid_build (pid, sample_thread, 0);
11124
11125 if (remote_thread_alive (ptid))
11126 printf_filtered ("PASS: Thread alive test\n");
11127 else
11128 printf_filtered ("FAIL: Thread alive test\n");
11129 }
11130
11131 void output_threadid (char *title, threadref *ref);
11132
11133 void
11134 output_threadid (char *title, threadref *ref)
11135 {
11136 char hexid[20];
11137
11138 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
11139 hexid[16] = 0;
11140 printf_filtered ("%s %s\n", title, (&hexid[0]));
11141 }
11142
11143 static void
11144 threadlist_test_cmd (const char *cmd, int tty)
11145 {
11146 int startflag = 1;
11147 threadref nextthread;
11148 int done, result_count;
11149 threadref threadlist[3];
11150
11151 printf_filtered ("Remote Threadlist test\n");
11152 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11153 &result_count, &threadlist[0]))
11154 printf_filtered ("FAIL: threadlist test\n");
11155 else
11156 {
11157 threadref *scan = threadlist;
11158 threadref *limit = scan + result_count;
11159
11160 while (scan < limit)
11161 output_threadid (" thread ", scan++);
11162 }
11163 }
11164
11165 void
11166 display_thread_info (struct gdb_ext_thread_info *info)
11167 {
11168 output_threadid ("Threadid: ", &info->threadid);
11169 printf_filtered ("Name: %s\n ", info->shortname);
11170 printf_filtered ("State: %s\n", info->display);
11171 printf_filtered ("other: %s\n\n", info->more_display);
11172 }
11173
11174 int
11175 get_and_display_threadinfo (threadref *ref)
11176 {
11177 int result;
11178 int set;
11179 struct gdb_ext_thread_info threadinfo;
11180
11181 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11182 | TAG_MOREDISPLAY | TAG_DISPLAY;
11183 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11184 display_thread_info (&threadinfo);
11185 return result;
11186 }
11187
11188 static void
11189 threadinfo_test_cmd (const char *cmd, int tty)
11190 {
11191 int athread = SAMPLE_THREAD;
11192 threadref thread;
11193 int set;
11194
11195 int_to_threadref (&thread, athread);
11196 printf_filtered ("Remote Threadinfo test\n");
11197 if (!get_and_display_threadinfo (&thread))
11198 printf_filtered ("FAIL cannot get thread info\n");
11199 }
11200
11201 static int
11202 thread_display_step (threadref *ref, void *context)
11203 {
11204 /* output_threadid(" threadstep ",ref); *//* simple test */
11205 return get_and_display_threadinfo (ref);
11206 }
11207
11208 static void
11209 threadlist_update_test_cmd (const char *cmd, int tty)
11210 {
11211 printf_filtered ("Remote Threadlist update test\n");
11212 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11213 }
11214
11215 static void
11216 init_remote_threadtests (void)
11217 {
11218 add_com ("tlist", class_obscure, threadlist_test_cmd,
11219 _("Fetch and print the remote list of "
11220 "thread identifiers, one pkt only"));
11221 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11222 _("Fetch and display info about one thread"));
11223 add_com ("tset", class_obscure, threadset_test_cmd,
11224 _("Test setting to a different thread"));
11225 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11226 _("Iterate through updating all remote thread info"));
11227 add_com ("talive", class_obscure, threadalive_test,
11228 _(" Remote thread alive test "));
11229 }
11230
11231 #endif /* 0 */
11232
11233 /* Convert a thread ID to a string. Returns the string in a static
11234 buffer. */
11235
11236 const char *
11237 remote_target::pid_to_str (ptid_t ptid)
11238 {
11239 static char buf[64];
11240 struct remote_state *rs = get_remote_state ();
11241
11242 if (ptid_equal (ptid, null_ptid))
11243 return normal_pid_to_str (ptid);
11244 else if (ptid_is_pid (ptid))
11245 {
11246 /* Printing an inferior target id. */
11247
11248 /* When multi-process extensions are off, there's no way in the
11249 remote protocol to know the remote process id, if there's any
11250 at all. There's one exception --- when we're connected with
11251 target extended-remote, and we manually attached to a process
11252 with "attach PID". We don't record anywhere a flag that
11253 allows us to distinguish that case from the case of
11254 connecting with extended-remote and the stub already being
11255 attached to a process, and reporting yes to qAttached, hence
11256 no smart special casing here. */
11257 if (!remote_multi_process_p (rs))
11258 {
11259 xsnprintf (buf, sizeof buf, "Remote target");
11260 return buf;
11261 }
11262
11263 return normal_pid_to_str (ptid);
11264 }
11265 else
11266 {
11267 if (ptid_equal (magic_null_ptid, ptid))
11268 xsnprintf (buf, sizeof buf, "Thread <main>");
11269 else if (remote_multi_process_p (rs))
11270 if (ptid_get_lwp (ptid) == 0)
11271 return normal_pid_to_str (ptid);
11272 else
11273 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11274 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11275 else
11276 xsnprintf (buf, sizeof buf, "Thread %ld",
11277 ptid_get_lwp (ptid));
11278 return buf;
11279 }
11280 }
11281
11282 /* Get the address of the thread local variable in OBJFILE which is
11283 stored at OFFSET within the thread local storage for thread PTID. */
11284
11285 CORE_ADDR
11286 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11287 CORE_ADDR offset)
11288 {
11289 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11290 {
11291 struct remote_state *rs = get_remote_state ();
11292 char *p = rs->buf;
11293 char *endp = rs->buf + get_remote_packet_size ();
11294 enum packet_result result;
11295
11296 strcpy (p, "qGetTLSAddr:");
11297 p += strlen (p);
11298 p = write_ptid (p, endp, ptid);
11299 *p++ = ',';
11300 p += hexnumstr (p, offset);
11301 *p++ = ',';
11302 p += hexnumstr (p, lm);
11303 *p++ = '\0';
11304
11305 putpkt (rs->buf);
11306 getpkt (&rs->buf, &rs->buf_size, 0);
11307 result = packet_ok (rs->buf,
11308 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11309 if (result == PACKET_OK)
11310 {
11311 ULONGEST result;
11312
11313 unpack_varlen_hex (rs->buf, &result);
11314 return result;
11315 }
11316 else if (result == PACKET_UNKNOWN)
11317 throw_error (TLS_GENERIC_ERROR,
11318 _("Remote target doesn't support qGetTLSAddr packet"));
11319 else
11320 throw_error (TLS_GENERIC_ERROR,
11321 _("Remote target failed to process qGetTLSAddr request"));
11322 }
11323 else
11324 throw_error (TLS_GENERIC_ERROR,
11325 _("TLS not supported or disabled on this target"));
11326 /* Not reached. */
11327 return 0;
11328 }
11329
11330 /* Provide thread local base, i.e. Thread Information Block address.
11331 Returns 1 if ptid is found and thread_local_base is non zero. */
11332
11333 int
11334 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11335 {
11336 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11337 {
11338 struct remote_state *rs = get_remote_state ();
11339 char *p = rs->buf;
11340 char *endp = rs->buf + get_remote_packet_size ();
11341 enum packet_result result;
11342
11343 strcpy (p, "qGetTIBAddr:");
11344 p += strlen (p);
11345 p = write_ptid (p, endp, ptid);
11346 *p++ = '\0';
11347
11348 putpkt (rs->buf);
11349 getpkt (&rs->buf, &rs->buf_size, 0);
11350 result = packet_ok (rs->buf,
11351 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11352 if (result == PACKET_OK)
11353 {
11354 ULONGEST result;
11355
11356 unpack_varlen_hex (rs->buf, &result);
11357 if (addr)
11358 *addr = (CORE_ADDR) result;
11359 return 1;
11360 }
11361 else if (result == PACKET_UNKNOWN)
11362 error (_("Remote target doesn't support qGetTIBAddr packet"));
11363 else
11364 error (_("Remote target failed to process qGetTIBAddr request"));
11365 }
11366 else
11367 error (_("qGetTIBAddr not supported or disabled on this target"));
11368 /* Not reached. */
11369 return 0;
11370 }
11371
11372 /* Support for inferring a target description based on the current
11373 architecture and the size of a 'g' packet. While the 'g' packet
11374 can have any size (since optional registers can be left off the
11375 end), some sizes are easily recognizable given knowledge of the
11376 approximate architecture. */
11377
11378 struct remote_g_packet_guess
11379 {
11380 int bytes;
11381 const struct target_desc *tdesc;
11382 };
11383 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11384 DEF_VEC_O(remote_g_packet_guess_s);
11385
11386 struct remote_g_packet_data
11387 {
11388 VEC(remote_g_packet_guess_s) *guesses;
11389 };
11390
11391 static struct gdbarch_data *remote_g_packet_data_handle;
11392
11393 static void *
11394 remote_g_packet_data_init (struct obstack *obstack)
11395 {
11396 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11397 }
11398
11399 void
11400 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11401 const struct target_desc *tdesc)
11402 {
11403 struct remote_g_packet_data *data
11404 = ((struct remote_g_packet_data *)
11405 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11406 struct remote_g_packet_guess new_guess, *guess;
11407 int ix;
11408
11409 gdb_assert (tdesc != NULL);
11410
11411 for (ix = 0;
11412 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11413 ix++)
11414 if (guess->bytes == bytes)
11415 internal_error (__FILE__, __LINE__,
11416 _("Duplicate g packet description added for size %d"),
11417 bytes);
11418
11419 new_guess.bytes = bytes;
11420 new_guess.tdesc = tdesc;
11421 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11422 }
11423
11424 /* Return 1 if remote_read_description would do anything on this target
11425 and architecture, 0 otherwise. */
11426
11427 static int
11428 remote_read_description_p (struct target_ops *target)
11429 {
11430 struct remote_g_packet_data *data
11431 = ((struct remote_g_packet_data *)
11432 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11433
11434 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11435 return 1;
11436
11437 return 0;
11438 }
11439
11440 const struct target_desc *
11441 remote_target::read_description ()
11442 {
11443 struct remote_g_packet_data *data
11444 = ((struct remote_g_packet_data *)
11445 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11446
11447 /* Do not try this during initial connection, when we do not know
11448 whether there is a running but stopped thread. */
11449 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11450 return beneath->read_description ();
11451
11452 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11453 {
11454 struct remote_g_packet_guess *guess;
11455 int ix;
11456 int bytes = send_g_packet ();
11457
11458 for (ix = 0;
11459 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11460 ix++)
11461 if (guess->bytes == bytes)
11462 return guess->tdesc;
11463
11464 /* We discard the g packet. A minor optimization would be to
11465 hold on to it, and fill the register cache once we have selected
11466 an architecture, but it's too tricky to do safely. */
11467 }
11468
11469 return beneath->read_description ();
11470 }
11471
11472 /* Remote file transfer support. This is host-initiated I/O, not
11473 target-initiated; for target-initiated, see remote-fileio.c. */
11474
11475 /* If *LEFT is at least the length of STRING, copy STRING to
11476 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11477 decrease *LEFT. Otherwise raise an error. */
11478
11479 static void
11480 remote_buffer_add_string (char **buffer, int *left, const char *string)
11481 {
11482 int len = strlen (string);
11483
11484 if (len > *left)
11485 error (_("Packet too long for target."));
11486
11487 memcpy (*buffer, string, len);
11488 *buffer += len;
11489 *left -= len;
11490
11491 /* NUL-terminate the buffer as a convenience, if there is
11492 room. */
11493 if (*left)
11494 **buffer = '\0';
11495 }
11496
11497 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11498 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11499 decrease *LEFT. Otherwise raise an error. */
11500
11501 static void
11502 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11503 int len)
11504 {
11505 if (2 * len > *left)
11506 error (_("Packet too long for target."));
11507
11508 bin2hex (bytes, *buffer, len);
11509 *buffer += 2 * len;
11510 *left -= 2 * len;
11511
11512 /* NUL-terminate the buffer as a convenience, if there is
11513 room. */
11514 if (*left)
11515 **buffer = '\0';
11516 }
11517
11518 /* If *LEFT is large enough, convert VALUE to hex and add it to
11519 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11520 decrease *LEFT. Otherwise raise an error. */
11521
11522 static void
11523 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11524 {
11525 int len = hexnumlen (value);
11526
11527 if (len > *left)
11528 error (_("Packet too long for target."));
11529
11530 hexnumstr (*buffer, value);
11531 *buffer += len;
11532 *left -= len;
11533
11534 /* NUL-terminate the buffer as a convenience, if there is
11535 room. */
11536 if (*left)
11537 **buffer = '\0';
11538 }
11539
11540 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11541 value, *REMOTE_ERRNO to the remote error number or zero if none
11542 was included, and *ATTACHMENT to point to the start of the annex
11543 if any. The length of the packet isn't needed here; there may
11544 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11545
11546 Return 0 if the packet could be parsed, -1 if it could not. If
11547 -1 is returned, the other variables may not be initialized. */
11548
11549 static int
11550 remote_hostio_parse_result (char *buffer, int *retcode,
11551 int *remote_errno, char **attachment)
11552 {
11553 char *p, *p2;
11554
11555 *remote_errno = 0;
11556 *attachment = NULL;
11557
11558 if (buffer[0] != 'F')
11559 return -1;
11560
11561 errno = 0;
11562 *retcode = strtol (&buffer[1], &p, 16);
11563 if (errno != 0 || p == &buffer[1])
11564 return -1;
11565
11566 /* Check for ",errno". */
11567 if (*p == ',')
11568 {
11569 errno = 0;
11570 *remote_errno = strtol (p + 1, &p2, 16);
11571 if (errno != 0 || p + 1 == p2)
11572 return -1;
11573 p = p2;
11574 }
11575
11576 /* Check for ";attachment". If there is no attachment, the
11577 packet should end here. */
11578 if (*p == ';')
11579 {
11580 *attachment = p + 1;
11581 return 0;
11582 }
11583 else if (*p == '\0')
11584 return 0;
11585 else
11586 return -1;
11587 }
11588
11589 /* Send a prepared I/O packet to the target and read its response.
11590 The prepared packet is in the global RS->BUF before this function
11591 is called, and the answer is there when we return.
11592
11593 COMMAND_BYTES is the length of the request to send, which may include
11594 binary data. WHICH_PACKET is the packet configuration to check
11595 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11596 is set to the error number and -1 is returned. Otherwise the value
11597 returned by the function is returned.
11598
11599 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11600 attachment is expected; an error will be reported if there's a
11601 mismatch. If one is found, *ATTACHMENT will be set to point into
11602 the packet buffer and *ATTACHMENT_LEN will be set to the
11603 attachment's length. */
11604
11605 static int
11606 remote_hostio_send_command (int command_bytes, int which_packet,
11607 int *remote_errno, char **attachment,
11608 int *attachment_len)
11609 {
11610 struct remote_state *rs = get_remote_state ();
11611 int ret, bytes_read;
11612 char *attachment_tmp;
11613
11614 if (packet_support (which_packet) == PACKET_DISABLE)
11615 {
11616 *remote_errno = FILEIO_ENOSYS;
11617 return -1;
11618 }
11619
11620 putpkt_binary (rs->buf, command_bytes);
11621 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11622
11623 /* If it timed out, something is wrong. Don't try to parse the
11624 buffer. */
11625 if (bytes_read < 0)
11626 {
11627 *remote_errno = FILEIO_EINVAL;
11628 return -1;
11629 }
11630
11631 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11632 {
11633 case PACKET_ERROR:
11634 *remote_errno = FILEIO_EINVAL;
11635 return -1;
11636 case PACKET_UNKNOWN:
11637 *remote_errno = FILEIO_ENOSYS;
11638 return -1;
11639 case PACKET_OK:
11640 break;
11641 }
11642
11643 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11644 &attachment_tmp))
11645 {
11646 *remote_errno = FILEIO_EINVAL;
11647 return -1;
11648 }
11649
11650 /* Make sure we saw an attachment if and only if we expected one. */
11651 if ((attachment_tmp == NULL && attachment != NULL)
11652 || (attachment_tmp != NULL && attachment == NULL))
11653 {
11654 *remote_errno = FILEIO_EINVAL;
11655 return -1;
11656 }
11657
11658 /* If an attachment was found, it must point into the packet buffer;
11659 work out how many bytes there were. */
11660 if (attachment_tmp != NULL)
11661 {
11662 *attachment = attachment_tmp;
11663 *attachment_len = bytes_read - (*attachment - rs->buf);
11664 }
11665
11666 return ret;
11667 }
11668
11669 /* Invalidate the readahead cache. */
11670
11671 static void
11672 readahead_cache_invalidate (void)
11673 {
11674 struct remote_state *rs = get_remote_state ();
11675
11676 rs->readahead_cache.fd = -1;
11677 }
11678
11679 /* Invalidate the readahead cache if it is holding data for FD. */
11680
11681 static void
11682 readahead_cache_invalidate_fd (int fd)
11683 {
11684 struct remote_state *rs = get_remote_state ();
11685
11686 if (rs->readahead_cache.fd == fd)
11687 rs->readahead_cache.fd = -1;
11688 }
11689
11690 /* Set the filesystem remote_hostio functions that take FILENAME
11691 arguments will use. Return 0 on success, or -1 if an error
11692 occurs (and set *REMOTE_ERRNO). */
11693
11694 static int
11695 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11696 {
11697 struct remote_state *rs = get_remote_state ();
11698 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11699 char *p = rs->buf;
11700 int left = get_remote_packet_size () - 1;
11701 char arg[9];
11702 int ret;
11703
11704 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11705 return 0;
11706
11707 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11708 return 0;
11709
11710 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11711
11712 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11713 remote_buffer_add_string (&p, &left, arg);
11714
11715 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11716 remote_errno, NULL, NULL);
11717
11718 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11719 return 0;
11720
11721 if (ret == 0)
11722 rs->fs_pid = required_pid;
11723
11724 return ret;
11725 }
11726
11727 /* Implementation of to_fileio_open. */
11728
11729 static int
11730 remote_hostio_open (struct target_ops *self,
11731 struct inferior *inf, const char *filename,
11732 int flags, int mode, int warn_if_slow,
11733 int *remote_errno)
11734 {
11735 struct remote_state *rs = get_remote_state ();
11736 char *p = rs->buf;
11737 int left = get_remote_packet_size () - 1;
11738
11739 if (warn_if_slow)
11740 {
11741 static int warning_issued = 0;
11742
11743 printf_unfiltered (_("Reading %s from remote target...\n"),
11744 filename);
11745
11746 if (!warning_issued)
11747 {
11748 warning (_("File transfers from remote targets can be slow."
11749 " Use \"set sysroot\" to access files locally"
11750 " instead."));
11751 warning_issued = 1;
11752 }
11753 }
11754
11755 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11756 return -1;
11757
11758 remote_buffer_add_string (&p, &left, "vFile:open:");
11759
11760 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11761 strlen (filename));
11762 remote_buffer_add_string (&p, &left, ",");
11763
11764 remote_buffer_add_int (&p, &left, flags);
11765 remote_buffer_add_string (&p, &left, ",");
11766
11767 remote_buffer_add_int (&p, &left, mode);
11768
11769 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11770 remote_errno, NULL, NULL);
11771 }
11772
11773 int
11774 remote_target::fileio_open (struct inferior *inf, const char *filename,
11775 int flags, int mode, int warn_if_slow,
11776 int *remote_errno)
11777 {
11778 return remote_hostio_open (this, inf, filename, flags, mode, warn_if_slow,
11779 remote_errno);
11780 }
11781
11782 /* Implementation of to_fileio_pwrite. */
11783
11784 static int
11785 remote_hostio_pwrite (struct target_ops *self,
11786 int fd, const gdb_byte *write_buf, int len,
11787 ULONGEST offset, int *remote_errno)
11788 {
11789 struct remote_state *rs = get_remote_state ();
11790 char *p = rs->buf;
11791 int left = get_remote_packet_size ();
11792 int out_len;
11793
11794 readahead_cache_invalidate_fd (fd);
11795
11796 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11797
11798 remote_buffer_add_int (&p, &left, fd);
11799 remote_buffer_add_string (&p, &left, ",");
11800
11801 remote_buffer_add_int (&p, &left, offset);
11802 remote_buffer_add_string (&p, &left, ",");
11803
11804 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11805 get_remote_packet_size () - (p - rs->buf));
11806
11807 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11808 remote_errno, NULL, NULL);
11809 }
11810
11811 int
11812 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
11813 ULONGEST offset, int *remote_errno)
11814 {
11815 return remote_hostio_pwrite (this, fd, write_buf, len, offset, remote_errno);
11816 }
11817
11818 /* Helper for the implementation of to_fileio_pread. Read the file
11819 from the remote side with vFile:pread. */
11820
11821 static int
11822 remote_hostio_pread_vFile (struct target_ops *self,
11823 int fd, gdb_byte *read_buf, int len,
11824 ULONGEST offset, int *remote_errno)
11825 {
11826 struct remote_state *rs = get_remote_state ();
11827 char *p = rs->buf;
11828 char *attachment;
11829 int left = get_remote_packet_size ();
11830 int ret, attachment_len;
11831 int read_len;
11832
11833 remote_buffer_add_string (&p, &left, "vFile:pread:");
11834
11835 remote_buffer_add_int (&p, &left, fd);
11836 remote_buffer_add_string (&p, &left, ",");
11837
11838 remote_buffer_add_int (&p, &left, len);
11839 remote_buffer_add_string (&p, &left, ",");
11840
11841 remote_buffer_add_int (&p, &left, offset);
11842
11843 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11844 remote_errno, &attachment,
11845 &attachment_len);
11846
11847 if (ret < 0)
11848 return ret;
11849
11850 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11851 read_buf, len);
11852 if (read_len != ret)
11853 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11854
11855 return ret;
11856 }
11857
11858 /* Serve pread from the readahead cache. Returns number of bytes
11859 read, or 0 if the request can't be served from the cache. */
11860
11861 static int
11862 remote_hostio_pread_from_cache (struct remote_state *rs,
11863 int fd, gdb_byte *read_buf, size_t len,
11864 ULONGEST offset)
11865 {
11866 struct readahead_cache *cache = &rs->readahead_cache;
11867
11868 if (cache->fd == fd
11869 && cache->offset <= offset
11870 && offset < cache->offset + cache->bufsize)
11871 {
11872 ULONGEST max = cache->offset + cache->bufsize;
11873
11874 if (offset + len > max)
11875 len = max - offset;
11876
11877 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11878 return len;
11879 }
11880
11881 return 0;
11882 }
11883
11884 /* Implementation of to_fileio_pread. */
11885
11886 static int
11887 remote_hostio_pread (struct target_ops *self,
11888 int fd, gdb_byte *read_buf, int len,
11889 ULONGEST offset, int *remote_errno)
11890 {
11891 int ret;
11892 struct remote_state *rs = get_remote_state ();
11893 struct readahead_cache *cache = &rs->readahead_cache;
11894
11895 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11896 if (ret > 0)
11897 {
11898 cache->hit_count++;
11899
11900 if (remote_debug)
11901 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11902 pulongest (cache->hit_count));
11903 return ret;
11904 }
11905
11906 cache->miss_count++;
11907 if (remote_debug)
11908 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11909 pulongest (cache->miss_count));
11910
11911 cache->fd = fd;
11912 cache->offset = offset;
11913 cache->bufsize = get_remote_packet_size ();
11914 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11915
11916 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11917 cache->offset, remote_errno);
11918 if (ret <= 0)
11919 {
11920 readahead_cache_invalidate_fd (fd);
11921 return ret;
11922 }
11923
11924 cache->bufsize = ret;
11925 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11926 }
11927
11928 int
11929 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
11930 ULONGEST offset, int *remote_errno)
11931 {
11932 return remote_hostio_pread (this, fd, read_buf, len, offset, remote_errno);
11933 }
11934
11935 /* Implementation of to_fileio_close. */
11936
11937 static int
11938 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11939 {
11940 struct remote_state *rs = get_remote_state ();
11941 char *p = rs->buf;
11942 int left = get_remote_packet_size () - 1;
11943
11944 readahead_cache_invalidate_fd (fd);
11945
11946 remote_buffer_add_string (&p, &left, "vFile:close:");
11947
11948 remote_buffer_add_int (&p, &left, fd);
11949
11950 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11951 remote_errno, NULL, NULL);
11952 }
11953
11954 int
11955 remote_target::fileio_close (int fd, int *remote_errno)
11956 {
11957 return remote_hostio_close (this, fd, remote_errno);
11958 }
11959
11960 /* Implementation of to_fileio_unlink. */
11961
11962 static int
11963 remote_hostio_unlink (struct target_ops *self,
11964 struct inferior *inf, const char *filename,
11965 int *remote_errno)
11966 {
11967 struct remote_state *rs = get_remote_state ();
11968 char *p = rs->buf;
11969 int left = get_remote_packet_size () - 1;
11970
11971 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11972 return -1;
11973
11974 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11975
11976 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11977 strlen (filename));
11978
11979 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11980 remote_errno, NULL, NULL);
11981 }
11982
11983 int
11984 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
11985 int *remote_errno)
11986 {
11987 return remote_hostio_unlink (this, inf, filename, remote_errno);
11988 }
11989
11990 /* Implementation of to_fileio_readlink. */
11991
11992 gdb::optional<std::string>
11993 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
11994 int *remote_errno)
11995 {
11996 struct remote_state *rs = get_remote_state ();
11997 char *p = rs->buf;
11998 char *attachment;
11999 int left = get_remote_packet_size ();
12000 int len, attachment_len;
12001 int read_len;
12002
12003 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12004 return {};
12005
12006 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12007
12008 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12009 strlen (filename));
12010
12011 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12012 remote_errno, &attachment,
12013 &attachment_len);
12014
12015 if (len < 0)
12016 return {};
12017
12018 std::string ret (len, '\0');
12019
12020 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12021 (gdb_byte *) &ret[0], len);
12022 if (read_len != len)
12023 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12024
12025 return ret;
12026 }
12027
12028 /* Implementation of to_fileio_fstat. */
12029
12030 int
12031 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12032 {
12033 struct remote_state *rs = get_remote_state ();
12034 char *p = rs->buf;
12035 int left = get_remote_packet_size ();
12036 int attachment_len, ret;
12037 char *attachment;
12038 struct fio_stat fst;
12039 int read_len;
12040
12041 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12042
12043 remote_buffer_add_int (&p, &left, fd);
12044
12045 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12046 remote_errno, &attachment,
12047 &attachment_len);
12048 if (ret < 0)
12049 {
12050 if (*remote_errno != FILEIO_ENOSYS)
12051 return ret;
12052
12053 /* Strictly we should return -1, ENOSYS here, but when
12054 "set sysroot remote:" was implemented in August 2008
12055 BFD's need for a stat function was sidestepped with
12056 this hack. This was not remedied until March 2015
12057 so we retain the previous behavior to avoid breaking
12058 compatibility.
12059
12060 Note that the memset is a March 2015 addition; older
12061 GDBs set st_size *and nothing else* so the structure
12062 would have garbage in all other fields. This might
12063 break something but retaining the previous behavior
12064 here would be just too wrong. */
12065
12066 memset (st, 0, sizeof (struct stat));
12067 st->st_size = INT_MAX;
12068 return 0;
12069 }
12070
12071 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12072 (gdb_byte *) &fst, sizeof (fst));
12073
12074 if (read_len != ret)
12075 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12076
12077 if (read_len != sizeof (fst))
12078 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12079 read_len, (int) sizeof (fst));
12080
12081 remote_fileio_to_host_stat (&fst, st);
12082
12083 return 0;
12084 }
12085
12086 /* Implementation of to_filesystem_is_local. */
12087
12088 int
12089 remote_target::filesystem_is_local ()
12090 {
12091 /* Valgrind GDB presents itself as a remote target but works
12092 on the local filesystem: it does not implement remote get
12093 and users are not expected to set a sysroot. To handle
12094 this case we treat the remote filesystem as local if the
12095 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12096 does not support vFile:open. */
12097 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12098 {
12099 enum packet_support ps = packet_support (PACKET_vFile_open);
12100
12101 if (ps == PACKET_SUPPORT_UNKNOWN)
12102 {
12103 int fd, remote_errno;
12104
12105 /* Try opening a file to probe support. The supplied
12106 filename is irrelevant, we only care about whether
12107 the stub recognizes the packet or not. */
12108 fd = remote_hostio_open (this, NULL, "just probing",
12109 FILEIO_O_RDONLY, 0700, 0,
12110 &remote_errno);
12111
12112 if (fd >= 0)
12113 remote_hostio_close (this, fd, &remote_errno);
12114
12115 ps = packet_support (PACKET_vFile_open);
12116 }
12117
12118 if (ps == PACKET_DISABLE)
12119 {
12120 static int warning_issued = 0;
12121
12122 if (!warning_issued)
12123 {
12124 warning (_("remote target does not support file"
12125 " transfer, attempting to access files"
12126 " from local filesystem."));
12127 warning_issued = 1;
12128 }
12129
12130 return 1;
12131 }
12132 }
12133
12134 return 0;
12135 }
12136
12137 static int
12138 remote_fileio_errno_to_host (int errnum)
12139 {
12140 switch (errnum)
12141 {
12142 case FILEIO_EPERM:
12143 return EPERM;
12144 case FILEIO_ENOENT:
12145 return ENOENT;
12146 case FILEIO_EINTR:
12147 return EINTR;
12148 case FILEIO_EIO:
12149 return EIO;
12150 case FILEIO_EBADF:
12151 return EBADF;
12152 case FILEIO_EACCES:
12153 return EACCES;
12154 case FILEIO_EFAULT:
12155 return EFAULT;
12156 case FILEIO_EBUSY:
12157 return EBUSY;
12158 case FILEIO_EEXIST:
12159 return EEXIST;
12160 case FILEIO_ENODEV:
12161 return ENODEV;
12162 case FILEIO_ENOTDIR:
12163 return ENOTDIR;
12164 case FILEIO_EISDIR:
12165 return EISDIR;
12166 case FILEIO_EINVAL:
12167 return EINVAL;
12168 case FILEIO_ENFILE:
12169 return ENFILE;
12170 case FILEIO_EMFILE:
12171 return EMFILE;
12172 case FILEIO_EFBIG:
12173 return EFBIG;
12174 case FILEIO_ENOSPC:
12175 return ENOSPC;
12176 case FILEIO_ESPIPE:
12177 return ESPIPE;
12178 case FILEIO_EROFS:
12179 return EROFS;
12180 case FILEIO_ENOSYS:
12181 return ENOSYS;
12182 case FILEIO_ENAMETOOLONG:
12183 return ENAMETOOLONG;
12184 }
12185 return -1;
12186 }
12187
12188 static char *
12189 remote_hostio_error (int errnum)
12190 {
12191 int host_error = remote_fileio_errno_to_host (errnum);
12192
12193 if (host_error == -1)
12194 error (_("Unknown remote I/O error %d"), errnum);
12195 else
12196 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12197 }
12198
12199 static void
12200 remote_hostio_close_cleanup (void *opaque)
12201 {
12202 int fd = *(int *) opaque;
12203 int remote_errno;
12204
12205 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
12206 }
12207
12208 void
12209 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12210 {
12211 struct cleanup *back_to, *close_cleanup;
12212 int retcode, fd, remote_errno, bytes, io_size;
12213 gdb_byte *buffer;
12214 int bytes_in_buffer;
12215 int saw_eof;
12216 ULONGEST offset;
12217 struct remote_state *rs = get_remote_state ();
12218
12219 if (!rs->remote_desc)
12220 error (_("command can only be used with remote target"));
12221
12222 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12223 if (file == NULL)
12224 perror_with_name (local_file);
12225
12226 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12227 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12228 | FILEIO_O_TRUNC),
12229 0700, 0, &remote_errno);
12230 if (fd == -1)
12231 remote_hostio_error (remote_errno);
12232
12233 /* Send up to this many bytes at once. They won't all fit in the
12234 remote packet limit, so we'll transfer slightly fewer. */
12235 io_size = get_remote_packet_size ();
12236 buffer = (gdb_byte *) xmalloc (io_size);
12237 back_to = make_cleanup (xfree, buffer);
12238
12239 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12240
12241 bytes_in_buffer = 0;
12242 saw_eof = 0;
12243 offset = 0;
12244 while (bytes_in_buffer || !saw_eof)
12245 {
12246 if (!saw_eof)
12247 {
12248 bytes = fread (buffer + bytes_in_buffer, 1,
12249 io_size - bytes_in_buffer,
12250 file.get ());
12251 if (bytes == 0)
12252 {
12253 if (ferror (file.get ()))
12254 error (_("Error reading %s."), local_file);
12255 else
12256 {
12257 /* EOF. Unless there is something still in the
12258 buffer from the last iteration, we are done. */
12259 saw_eof = 1;
12260 if (bytes_in_buffer == 0)
12261 break;
12262 }
12263 }
12264 }
12265 else
12266 bytes = 0;
12267
12268 bytes += bytes_in_buffer;
12269 bytes_in_buffer = 0;
12270
12271 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12272 fd, buffer, bytes,
12273 offset, &remote_errno);
12274
12275 if (retcode < 0)
12276 remote_hostio_error (remote_errno);
12277 else if (retcode == 0)
12278 error (_("Remote write of %d bytes returned 0!"), bytes);
12279 else if (retcode < bytes)
12280 {
12281 /* Short write. Save the rest of the read data for the next
12282 write. */
12283 bytes_in_buffer = bytes - retcode;
12284 memmove (buffer, buffer + retcode, bytes_in_buffer);
12285 }
12286
12287 offset += retcode;
12288 }
12289
12290 discard_cleanups (close_cleanup);
12291 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12292 remote_hostio_error (remote_errno);
12293
12294 if (from_tty)
12295 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12296 do_cleanups (back_to);
12297 }
12298
12299 void
12300 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12301 {
12302 struct cleanup *back_to, *close_cleanup;
12303 int fd, remote_errno, bytes, io_size;
12304 gdb_byte *buffer;
12305 ULONGEST offset;
12306 struct remote_state *rs = get_remote_state ();
12307
12308 if (!rs->remote_desc)
12309 error (_("command can only be used with remote target"));
12310
12311 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12312 remote_file, FILEIO_O_RDONLY, 0, 0,
12313 &remote_errno);
12314 if (fd == -1)
12315 remote_hostio_error (remote_errno);
12316
12317 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12318 if (file == NULL)
12319 perror_with_name (local_file);
12320
12321 /* Send up to this many bytes at once. They won't all fit in the
12322 remote packet limit, so we'll transfer slightly fewer. */
12323 io_size = get_remote_packet_size ();
12324 buffer = (gdb_byte *) xmalloc (io_size);
12325 back_to = make_cleanup (xfree, buffer);
12326
12327 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12328
12329 offset = 0;
12330 while (1)
12331 {
12332 bytes = remote_hostio_pread (find_target_at (process_stratum),
12333 fd, buffer, io_size, offset, &remote_errno);
12334 if (bytes == 0)
12335 /* Success, but no bytes, means end-of-file. */
12336 break;
12337 if (bytes == -1)
12338 remote_hostio_error (remote_errno);
12339
12340 offset += bytes;
12341
12342 bytes = fwrite (buffer, 1, bytes, file.get ());
12343 if (bytes == 0)
12344 perror_with_name (local_file);
12345 }
12346
12347 discard_cleanups (close_cleanup);
12348 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12349 remote_hostio_error (remote_errno);
12350
12351 if (from_tty)
12352 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12353 do_cleanups (back_to);
12354 }
12355
12356 void
12357 remote_file_delete (const char *remote_file, int from_tty)
12358 {
12359 int retcode, remote_errno;
12360 struct remote_state *rs = get_remote_state ();
12361
12362 if (!rs->remote_desc)
12363 error (_("command can only be used with remote target"));
12364
12365 retcode = remote_hostio_unlink (find_target_at (process_stratum),
12366 NULL, remote_file, &remote_errno);
12367 if (retcode == -1)
12368 remote_hostio_error (remote_errno);
12369
12370 if (from_tty)
12371 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12372 }
12373
12374 static void
12375 remote_put_command (const char *args, int from_tty)
12376 {
12377 if (args == NULL)
12378 error_no_arg (_("file to put"));
12379
12380 gdb_argv argv (args);
12381 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12382 error (_("Invalid parameters to remote put"));
12383
12384 remote_file_put (argv[0], argv[1], from_tty);
12385 }
12386
12387 static void
12388 remote_get_command (const char *args, int from_tty)
12389 {
12390 if (args == NULL)
12391 error_no_arg (_("file to get"));
12392
12393 gdb_argv argv (args);
12394 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12395 error (_("Invalid parameters to remote get"));
12396
12397 remote_file_get (argv[0], argv[1], from_tty);
12398 }
12399
12400 static void
12401 remote_delete_command (const char *args, int from_tty)
12402 {
12403 if (args == NULL)
12404 error_no_arg (_("file to delete"));
12405
12406 gdb_argv argv (args);
12407 if (argv[0] == NULL || argv[1] != NULL)
12408 error (_("Invalid parameters to remote delete"));
12409
12410 remote_file_delete (argv[0], from_tty);
12411 }
12412
12413 static void
12414 remote_command (const char *args, int from_tty)
12415 {
12416 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12417 }
12418
12419 int
12420 remote_target::can_execute_reverse ()
12421 {
12422 if (packet_support (PACKET_bs) == PACKET_ENABLE
12423 || packet_support (PACKET_bc) == PACKET_ENABLE)
12424 return 1;
12425 else
12426 return 0;
12427 }
12428
12429 int
12430 remote_target::supports_non_stop ()
12431 {
12432 return 1;
12433 }
12434
12435 int
12436 remote_target::supports_disable_randomization ()
12437 {
12438 /* Only supported in extended mode. */
12439 return 0;
12440 }
12441
12442 int
12443 remote_target::supports_multi_process ()
12444 {
12445 struct remote_state *rs = get_remote_state ();
12446
12447 return remote_multi_process_p (rs);
12448 }
12449
12450 static int
12451 remote_supports_cond_tracepoints ()
12452 {
12453 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12454 }
12455
12456 int
12457 remote_target::supports_evaluation_of_breakpoint_conditions ()
12458 {
12459 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12460 }
12461
12462 static int
12463 remote_supports_fast_tracepoints ()
12464 {
12465 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12466 }
12467
12468 static int
12469 remote_supports_static_tracepoints ()
12470 {
12471 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12472 }
12473
12474 static int
12475 remote_supports_install_in_trace ()
12476 {
12477 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12478 }
12479
12480 int
12481 remote_target::supports_enable_disable_tracepoint ()
12482 {
12483 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12484 == PACKET_ENABLE);
12485 }
12486
12487 int
12488 remote_target::supports_string_tracing ()
12489 {
12490 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12491 }
12492
12493 int
12494 remote_target::can_run_breakpoint_commands ()
12495 {
12496 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12497 }
12498
12499 void
12500 remote_target::trace_init ()
12501 {
12502 struct remote_state *rs = get_remote_state ();
12503
12504 putpkt ("QTinit");
12505 remote_get_noisy_reply ();
12506 if (strcmp (rs->buf, "OK") != 0)
12507 error (_("Target does not support this command."));
12508 }
12509
12510 /* Recursive routine to walk through command list including loops, and
12511 download packets for each command. */
12512
12513 static void
12514 remote_download_command_source (int num, ULONGEST addr,
12515 struct command_line *cmds)
12516 {
12517 struct remote_state *rs = get_remote_state ();
12518 struct command_line *cmd;
12519
12520 for (cmd = cmds; cmd; cmd = cmd->next)
12521 {
12522 QUIT; /* Allow user to bail out with ^C. */
12523 strcpy (rs->buf, "QTDPsrc:");
12524 encode_source_string (num, addr, "cmd", cmd->line,
12525 rs->buf + strlen (rs->buf),
12526 rs->buf_size - strlen (rs->buf));
12527 putpkt (rs->buf);
12528 remote_get_noisy_reply ();
12529 if (strcmp (rs->buf, "OK"))
12530 warning (_("Target does not support source download."));
12531
12532 if (cmd->control_type == while_control
12533 || cmd->control_type == while_stepping_control)
12534 {
12535 remote_download_command_source (num, addr, *cmd->body_list);
12536
12537 QUIT; /* Allow user to bail out with ^C. */
12538 strcpy (rs->buf, "QTDPsrc:");
12539 encode_source_string (num, addr, "cmd", "end",
12540 rs->buf + strlen (rs->buf),
12541 rs->buf_size - strlen (rs->buf));
12542 putpkt (rs->buf);
12543 remote_get_noisy_reply ();
12544 if (strcmp (rs->buf, "OK"))
12545 warning (_("Target does not support source download."));
12546 }
12547 }
12548 }
12549
12550 void
12551 remote_target::download_tracepoint (struct bp_location *loc)
12552 {
12553 #define BUF_SIZE 2048
12554
12555 CORE_ADDR tpaddr;
12556 char addrbuf[40];
12557 char buf[BUF_SIZE];
12558 std::vector<std::string> tdp_actions;
12559 std::vector<std::string> stepping_actions;
12560 char *pkt;
12561 struct breakpoint *b = loc->owner;
12562 struct tracepoint *t = (struct tracepoint *) b;
12563 struct remote_state *rs = get_remote_state ();
12564
12565 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12566
12567 tpaddr = loc->address;
12568 sprintf_vma (addrbuf, tpaddr);
12569 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12570 addrbuf, /* address */
12571 (b->enable_state == bp_enabled ? 'E' : 'D'),
12572 t->step_count, t->pass_count);
12573 /* Fast tracepoints are mostly handled by the target, but we can
12574 tell the target how big of an instruction block should be moved
12575 around. */
12576 if (b->type == bp_fast_tracepoint)
12577 {
12578 /* Only test for support at download time; we may not know
12579 target capabilities at definition time. */
12580 if (remote_supports_fast_tracepoints ())
12581 {
12582 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12583 NULL))
12584 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12585 gdb_insn_length (loc->gdbarch, tpaddr));
12586 else
12587 /* If it passed validation at definition but fails now,
12588 something is very wrong. */
12589 internal_error (__FILE__, __LINE__,
12590 _("Fast tracepoint not "
12591 "valid during download"));
12592 }
12593 else
12594 /* Fast tracepoints are functionally identical to regular
12595 tracepoints, so don't take lack of support as a reason to
12596 give up on the trace run. */
12597 warning (_("Target does not support fast tracepoints, "
12598 "downloading %d as regular tracepoint"), b->number);
12599 }
12600 else if (b->type == bp_static_tracepoint)
12601 {
12602 /* Only test for support at download time; we may not know
12603 target capabilities at definition time. */
12604 if (remote_supports_static_tracepoints ())
12605 {
12606 struct static_tracepoint_marker marker;
12607
12608 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12609 strcat (buf, ":S");
12610 else
12611 error (_("Static tracepoint not valid during download"));
12612 }
12613 else
12614 /* Fast tracepoints are functionally identical to regular
12615 tracepoints, so don't take lack of support as a reason
12616 to give up on the trace run. */
12617 error (_("Target does not support static tracepoints"));
12618 }
12619 /* If the tracepoint has a conditional, make it into an agent
12620 expression and append to the definition. */
12621 if (loc->cond)
12622 {
12623 /* Only test support at download time, we may not know target
12624 capabilities at definition time. */
12625 if (remote_supports_cond_tracepoints ())
12626 {
12627 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12628 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12629 aexpr->len);
12630 pkt = buf + strlen (buf);
12631 for (int ndx = 0; ndx < aexpr->len; ++ndx)
12632 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12633 *pkt = '\0';
12634 }
12635 else
12636 warning (_("Target does not support conditional tracepoints, "
12637 "ignoring tp %d cond"), b->number);
12638 }
12639
12640 if (b->commands || *default_collect)
12641 strcat (buf, "-");
12642 putpkt (buf);
12643 remote_get_noisy_reply ();
12644 if (strcmp (rs->buf, "OK"))
12645 error (_("Target does not support tracepoints."));
12646
12647 /* do_single_steps (t); */
12648 for (auto action_it = tdp_actions.begin ();
12649 action_it != tdp_actions.end (); action_it++)
12650 {
12651 QUIT; /* Allow user to bail out with ^C. */
12652
12653 bool has_more = (action_it != tdp_actions.end ()
12654 || !stepping_actions.empty ());
12655
12656 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12657 b->number, addrbuf, /* address */
12658 action_it->c_str (),
12659 has_more ? '-' : 0);
12660 putpkt (buf);
12661 remote_get_noisy_reply ();
12662 if (strcmp (rs->buf, "OK"))
12663 error (_("Error on target while setting tracepoints."));
12664 }
12665
12666 for (auto action_it = stepping_actions.begin ();
12667 action_it != stepping_actions.end (); action_it++)
12668 {
12669 QUIT; /* Allow user to bail out with ^C. */
12670
12671 bool is_first = action_it == stepping_actions.begin ();
12672 bool has_more = action_it != stepping_actions.end ();
12673
12674 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12675 b->number, addrbuf, /* address */
12676 is_first ? "S" : "",
12677 action_it->c_str (),
12678 has_more ? "-" : "");
12679 putpkt (buf);
12680 remote_get_noisy_reply ();
12681 if (strcmp (rs->buf, "OK"))
12682 error (_("Error on target while setting tracepoints."));
12683 }
12684
12685 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12686 {
12687 if (b->location != NULL)
12688 {
12689 strcpy (buf, "QTDPsrc:");
12690 encode_source_string (b->number, loc->address, "at",
12691 event_location_to_string (b->location.get ()),
12692 buf + strlen (buf), 2048 - strlen (buf));
12693 putpkt (buf);
12694 remote_get_noisy_reply ();
12695 if (strcmp (rs->buf, "OK"))
12696 warning (_("Target does not support source download."));
12697 }
12698 if (b->cond_string)
12699 {
12700 strcpy (buf, "QTDPsrc:");
12701 encode_source_string (b->number, loc->address,
12702 "cond", b->cond_string, buf + strlen (buf),
12703 2048 - strlen (buf));
12704 putpkt (buf);
12705 remote_get_noisy_reply ();
12706 if (strcmp (rs->buf, "OK"))
12707 warning (_("Target does not support source download."));
12708 }
12709 remote_download_command_source (b->number, loc->address,
12710 breakpoint_commands (b));
12711 }
12712 }
12713
12714 int
12715 remote_target::can_download_tracepoint ()
12716 {
12717 struct remote_state *rs = get_remote_state ();
12718 struct trace_status *ts;
12719 int status;
12720
12721 /* Don't try to install tracepoints until we've relocated our
12722 symbols, and fetched and merged the target's tracepoint list with
12723 ours. */
12724 if (rs->starting_up)
12725 return 0;
12726
12727 ts = current_trace_status ();
12728 status = get_trace_status (ts);
12729
12730 if (status == -1 || !ts->running_known || !ts->running)
12731 return 0;
12732
12733 /* If we are in a tracing experiment, but remote stub doesn't support
12734 installing tracepoint in trace, we have to return. */
12735 if (!remote_supports_install_in_trace ())
12736 return 0;
12737
12738 return 1;
12739 }
12740
12741
12742 void
12743 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12744 {
12745 struct remote_state *rs = get_remote_state ();
12746 char *p;
12747
12748 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12749 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12750 tsv.builtin);
12751 p = rs->buf + strlen (rs->buf);
12752 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12753 error (_("Trace state variable name too long for tsv definition packet"));
12754 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12755 *p++ = '\0';
12756 putpkt (rs->buf);
12757 remote_get_noisy_reply ();
12758 if (*rs->buf == '\0')
12759 error (_("Target does not support this command."));
12760 if (strcmp (rs->buf, "OK") != 0)
12761 error (_("Error on target while downloading trace state variable."));
12762 }
12763
12764 void
12765 remote_target::enable_tracepoint (struct bp_location *location)
12766 {
12767 struct remote_state *rs = get_remote_state ();
12768 char addr_buf[40];
12769
12770 sprintf_vma (addr_buf, location->address);
12771 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12772 location->owner->number, addr_buf);
12773 putpkt (rs->buf);
12774 remote_get_noisy_reply ();
12775 if (*rs->buf == '\0')
12776 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12777 if (strcmp (rs->buf, "OK") != 0)
12778 error (_("Error on target while enabling tracepoint."));
12779 }
12780
12781 void
12782 remote_target::disable_tracepoint (struct bp_location *location)
12783 {
12784 struct remote_state *rs = get_remote_state ();
12785 char addr_buf[40];
12786
12787 sprintf_vma (addr_buf, location->address);
12788 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12789 location->owner->number, addr_buf);
12790 putpkt (rs->buf);
12791 remote_get_noisy_reply ();
12792 if (*rs->buf == '\0')
12793 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12794 if (strcmp (rs->buf, "OK") != 0)
12795 error (_("Error on target while disabling tracepoint."));
12796 }
12797
12798 void
12799 remote_target::trace_set_readonly_regions ()
12800 {
12801 asection *s;
12802 bfd *abfd = NULL;
12803 bfd_size_type size;
12804 bfd_vma vma;
12805 int anysecs = 0;
12806 int offset = 0;
12807
12808 if (!exec_bfd)
12809 return; /* No information to give. */
12810
12811 struct remote_state *rs = get_remote_state ();
12812
12813 strcpy (rs->buf, "QTro");
12814 offset = strlen (rs->buf);
12815 for (s = exec_bfd->sections; s; s = s->next)
12816 {
12817 char tmp1[40], tmp2[40];
12818 int sec_length;
12819
12820 if ((s->flags & SEC_LOAD) == 0 ||
12821 /* (s->flags & SEC_CODE) == 0 || */
12822 (s->flags & SEC_READONLY) == 0)
12823 continue;
12824
12825 anysecs = 1;
12826 vma = bfd_get_section_vma (abfd, s);
12827 size = bfd_get_section_size (s);
12828 sprintf_vma (tmp1, vma);
12829 sprintf_vma (tmp2, vma + size);
12830 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12831 if (offset + sec_length + 1 > rs->buf_size)
12832 {
12833 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12834 warning (_("\
12835 Too many sections for read-only sections definition packet."));
12836 break;
12837 }
12838 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
12839 tmp1, tmp2);
12840 offset += sec_length;
12841 }
12842 if (anysecs)
12843 {
12844 putpkt (rs->buf);
12845 getpkt (&rs->buf, &rs->buf_size, 0);
12846 }
12847 }
12848
12849 void
12850 remote_target::trace_start ()
12851 {
12852 struct remote_state *rs = get_remote_state ();
12853
12854 putpkt ("QTStart");
12855 remote_get_noisy_reply ();
12856 if (*rs->buf == '\0')
12857 error (_("Target does not support this command."));
12858 if (strcmp (rs->buf, "OK") != 0)
12859 error (_("Bogus reply from target: %s"), rs->buf);
12860 }
12861
12862 int
12863 remote_target::get_trace_status (struct trace_status *ts)
12864 {
12865 /* Initialize it just to avoid a GCC false warning. */
12866 char *p = NULL;
12867 /* FIXME we need to get register block size some other way. */
12868 extern int trace_regblock_size;
12869 enum packet_result result;
12870 struct remote_state *rs = get_remote_state ();
12871
12872 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12873 return -1;
12874
12875 trace_regblock_size
12876 = get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
12877
12878 putpkt ("qTStatus");
12879
12880 TRY
12881 {
12882 p = remote_get_noisy_reply ();
12883 }
12884 CATCH (ex, RETURN_MASK_ERROR)
12885 {
12886 if (ex.error != TARGET_CLOSE_ERROR)
12887 {
12888 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12889 return -1;
12890 }
12891 throw_exception (ex);
12892 }
12893 END_CATCH
12894
12895 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12896
12897 /* If the remote target doesn't do tracing, flag it. */
12898 if (result == PACKET_UNKNOWN)
12899 return -1;
12900
12901 /* We're working with a live target. */
12902 ts->filename = NULL;
12903
12904 if (*p++ != 'T')
12905 error (_("Bogus trace status reply from target: %s"), rs->buf);
12906
12907 /* Function 'parse_trace_status' sets default value of each field of
12908 'ts' at first, so we don't have to do it here. */
12909 parse_trace_status (p, ts);
12910
12911 return ts->running;
12912 }
12913
12914 void
12915 remote_target::get_tracepoint_status (struct breakpoint *bp,
12916 struct uploaded_tp *utp)
12917 {
12918 struct remote_state *rs = get_remote_state ();
12919 char *reply;
12920 struct bp_location *loc;
12921 struct tracepoint *tp = (struct tracepoint *) bp;
12922 size_t size = get_remote_packet_size ();
12923
12924 if (tp)
12925 {
12926 tp->hit_count = 0;
12927 tp->traceframe_usage = 0;
12928 for (loc = tp->loc; loc; loc = loc->next)
12929 {
12930 /* If the tracepoint was never downloaded, don't go asking for
12931 any status. */
12932 if (tp->number_on_target == 0)
12933 continue;
12934 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12935 phex_nz (loc->address, 0));
12936 putpkt (rs->buf);
12937 reply = remote_get_noisy_reply ();
12938 if (reply && *reply)
12939 {
12940 if (*reply == 'V')
12941 parse_tracepoint_status (reply + 1, bp, utp);
12942 }
12943 }
12944 }
12945 else if (utp)
12946 {
12947 utp->hit_count = 0;
12948 utp->traceframe_usage = 0;
12949 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12950 phex_nz (utp->addr, 0));
12951 putpkt (rs->buf);
12952 reply = remote_get_noisy_reply ();
12953 if (reply && *reply)
12954 {
12955 if (*reply == 'V')
12956 parse_tracepoint_status (reply + 1, bp, utp);
12957 }
12958 }
12959 }
12960
12961 void
12962 remote_target::trace_stop ()
12963 {
12964 struct remote_state *rs = get_remote_state ();
12965
12966 putpkt ("QTStop");
12967 remote_get_noisy_reply ();
12968 if (*rs->buf == '\0')
12969 error (_("Target does not support this command."));
12970 if (strcmp (rs->buf, "OK") != 0)
12971 error (_("Bogus reply from target: %s"), rs->buf);
12972 }
12973
12974 int
12975 remote_target::trace_find (enum trace_find_type type, int num,
12976 CORE_ADDR addr1, CORE_ADDR addr2,
12977 int *tpp)
12978 {
12979 struct remote_state *rs = get_remote_state ();
12980 char *endbuf = rs->buf + get_remote_packet_size ();
12981 char *p, *reply;
12982 int target_frameno = -1, target_tracept = -1;
12983
12984 /* Lookups other than by absolute frame number depend on the current
12985 trace selected, so make sure it is correct on the remote end
12986 first. */
12987 if (type != tfind_number)
12988 set_remote_traceframe ();
12989
12990 p = rs->buf;
12991 strcpy (p, "QTFrame:");
12992 p = strchr (p, '\0');
12993 switch (type)
12994 {
12995 case tfind_number:
12996 xsnprintf (p, endbuf - p, "%x", num);
12997 break;
12998 case tfind_pc:
12999 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13000 break;
13001 case tfind_tp:
13002 xsnprintf (p, endbuf - p, "tdp:%x", num);
13003 break;
13004 case tfind_range:
13005 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13006 phex_nz (addr2, 0));
13007 break;
13008 case tfind_outside:
13009 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13010 phex_nz (addr2, 0));
13011 break;
13012 default:
13013 error (_("Unknown trace find type %d"), type);
13014 }
13015
13016 putpkt (rs->buf);
13017 reply = remote_get_noisy_reply ();
13018 if (*reply == '\0')
13019 error (_("Target does not support this command."));
13020
13021 while (reply && *reply)
13022 switch (*reply)
13023 {
13024 case 'F':
13025 p = ++reply;
13026 target_frameno = (int) strtol (p, &reply, 16);
13027 if (reply == p)
13028 error (_("Unable to parse trace frame number"));
13029 /* Don't update our remote traceframe number cache on failure
13030 to select a remote traceframe. */
13031 if (target_frameno == -1)
13032 return -1;
13033 break;
13034 case 'T':
13035 p = ++reply;
13036 target_tracept = (int) strtol (p, &reply, 16);
13037 if (reply == p)
13038 error (_("Unable to parse tracepoint number"));
13039 break;
13040 case 'O': /* "OK"? */
13041 if (reply[1] == 'K' && reply[2] == '\0')
13042 reply += 2;
13043 else
13044 error (_("Bogus reply from target: %s"), reply);
13045 break;
13046 default:
13047 error (_("Bogus reply from target: %s"), reply);
13048 }
13049 if (tpp)
13050 *tpp = target_tracept;
13051
13052 rs->remote_traceframe_number = target_frameno;
13053 return target_frameno;
13054 }
13055
13056 int
13057 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13058 {
13059 struct remote_state *rs = get_remote_state ();
13060 char *reply;
13061 ULONGEST uval;
13062
13063 set_remote_traceframe ();
13064
13065 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13066 putpkt (rs->buf);
13067 reply = remote_get_noisy_reply ();
13068 if (reply && *reply)
13069 {
13070 if (*reply == 'V')
13071 {
13072 unpack_varlen_hex (reply + 1, &uval);
13073 *val = (LONGEST) uval;
13074 return 1;
13075 }
13076 }
13077 return 0;
13078 }
13079
13080 int
13081 remote_target::save_trace_data (const char *filename)
13082 {
13083 struct remote_state *rs = get_remote_state ();
13084 char *p, *reply;
13085
13086 p = rs->buf;
13087 strcpy (p, "QTSave:");
13088 p += strlen (p);
13089 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13090 error (_("Remote file name too long for trace save packet"));
13091 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13092 *p++ = '\0';
13093 putpkt (rs->buf);
13094 reply = remote_get_noisy_reply ();
13095 if (*reply == '\0')
13096 error (_("Target does not support this command."));
13097 if (strcmp (reply, "OK") != 0)
13098 error (_("Bogus reply from target: %s"), reply);
13099 return 0;
13100 }
13101
13102 /* This is basically a memory transfer, but needs to be its own packet
13103 because we don't know how the target actually organizes its trace
13104 memory, plus we want to be able to ask for as much as possible, but
13105 not be unhappy if we don't get as much as we ask for. */
13106
13107 LONGEST
13108 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13109 {
13110 struct remote_state *rs = get_remote_state ();
13111 char *reply;
13112 char *p;
13113 int rslt;
13114
13115 p = rs->buf;
13116 strcpy (p, "qTBuffer:");
13117 p += strlen (p);
13118 p += hexnumstr (p, offset);
13119 *p++ = ',';
13120 p += hexnumstr (p, len);
13121 *p++ = '\0';
13122
13123 putpkt (rs->buf);
13124 reply = remote_get_noisy_reply ();
13125 if (reply && *reply)
13126 {
13127 /* 'l' by itself means we're at the end of the buffer and
13128 there is nothing more to get. */
13129 if (*reply == 'l')
13130 return 0;
13131
13132 /* Convert the reply into binary. Limit the number of bytes to
13133 convert according to our passed-in buffer size, rather than
13134 what was returned in the packet; if the target is
13135 unexpectedly generous and gives us a bigger reply than we
13136 asked for, we don't want to crash. */
13137 rslt = hex2bin (reply, buf, len);
13138 return rslt;
13139 }
13140
13141 /* Something went wrong, flag as an error. */
13142 return -1;
13143 }
13144
13145 void
13146 remote_target::set_disconnected_tracing (int val)
13147 {
13148 struct remote_state *rs = get_remote_state ();
13149
13150 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13151 {
13152 char *reply;
13153
13154 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13155 putpkt (rs->buf);
13156 reply = remote_get_noisy_reply ();
13157 if (*reply == '\0')
13158 error (_("Target does not support this command."));
13159 if (strcmp (reply, "OK") != 0)
13160 error (_("Bogus reply from target: %s"), reply);
13161 }
13162 else if (val)
13163 warning (_("Target does not support disconnected tracing."));
13164 }
13165
13166 int
13167 remote_target::core_of_thread (ptid_t ptid)
13168 {
13169 struct thread_info *info = find_thread_ptid (ptid);
13170
13171 if (info != NULL && info->priv != NULL)
13172 return get_remote_thread_info (info)->core;
13173
13174 return -1;
13175 }
13176
13177 void
13178 remote_target::set_circular_trace_buffer (int val)
13179 {
13180 struct remote_state *rs = get_remote_state ();
13181 char *reply;
13182
13183 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13184 putpkt (rs->buf);
13185 reply = remote_get_noisy_reply ();
13186 if (*reply == '\0')
13187 error (_("Target does not support this command."));
13188 if (strcmp (reply, "OK") != 0)
13189 error (_("Bogus reply from target: %s"), reply);
13190 }
13191
13192 traceframe_info_up
13193 remote_target::traceframe_info ()
13194 {
13195 gdb::optional<gdb::char_vector> text
13196 = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
13197 NULL);
13198 if (text)
13199 return parse_traceframe_info (text->data ());
13200
13201 return NULL;
13202 }
13203
13204 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13205 instruction on which a fast tracepoint may be placed. Returns -1
13206 if the packet is not supported, and 0 if the minimum instruction
13207 length is unknown. */
13208
13209 int
13210 remote_target::get_min_fast_tracepoint_insn_len ()
13211 {
13212 struct remote_state *rs = get_remote_state ();
13213 char *reply;
13214
13215 /* If we're not debugging a process yet, the IPA can't be
13216 loaded. */
13217 if (!target_has_execution)
13218 return 0;
13219
13220 /* Make sure the remote is pointing at the right process. */
13221 set_general_process ();
13222
13223 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13224 putpkt (rs->buf);
13225 reply = remote_get_noisy_reply ();
13226 if (*reply == '\0')
13227 return -1;
13228 else
13229 {
13230 ULONGEST min_insn_len;
13231
13232 unpack_varlen_hex (reply, &min_insn_len);
13233
13234 return (int) min_insn_len;
13235 }
13236 }
13237
13238 void
13239 remote_target::set_trace_buffer_size (LONGEST val)
13240 {
13241 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13242 {
13243 struct remote_state *rs = get_remote_state ();
13244 char *buf = rs->buf;
13245 char *endbuf = rs->buf + get_remote_packet_size ();
13246 enum packet_result result;
13247
13248 gdb_assert (val >= 0 || val == -1);
13249 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13250 /* Send -1 as literal "-1" to avoid host size dependency. */
13251 if (val < 0)
13252 {
13253 *buf++ = '-';
13254 buf += hexnumstr (buf, (ULONGEST) -val);
13255 }
13256 else
13257 buf += hexnumstr (buf, (ULONGEST) val);
13258
13259 putpkt (rs->buf);
13260 remote_get_noisy_reply ();
13261 result = packet_ok (rs->buf,
13262 &remote_protocol_packets[PACKET_QTBuffer_size]);
13263
13264 if (result != PACKET_OK)
13265 warning (_("Bogus reply from target: %s"), rs->buf);
13266 }
13267 }
13268
13269 int
13270 remote_target::set_trace_notes (const char *user, const char *notes,
13271 const char *stop_notes)
13272 {
13273 struct remote_state *rs = get_remote_state ();
13274 char *reply;
13275 char *buf = rs->buf;
13276 char *endbuf = rs->buf + get_remote_packet_size ();
13277 int nbytes;
13278
13279 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13280 if (user)
13281 {
13282 buf += xsnprintf (buf, endbuf - buf, "user:");
13283 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13284 buf += 2 * nbytes;
13285 *buf++ = ';';
13286 }
13287 if (notes)
13288 {
13289 buf += xsnprintf (buf, endbuf - buf, "notes:");
13290 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13291 buf += 2 * nbytes;
13292 *buf++ = ';';
13293 }
13294 if (stop_notes)
13295 {
13296 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13297 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13298 buf += 2 * nbytes;
13299 *buf++ = ';';
13300 }
13301 /* Ensure the buffer is terminated. */
13302 *buf = '\0';
13303
13304 putpkt (rs->buf);
13305 reply = remote_get_noisy_reply ();
13306 if (*reply == '\0')
13307 return 0;
13308
13309 if (strcmp (reply, "OK") != 0)
13310 error (_("Bogus reply from target: %s"), reply);
13311
13312 return 1;
13313 }
13314
13315 int
13316 remote_target::use_agent (int use)
13317 {
13318 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13319 {
13320 struct remote_state *rs = get_remote_state ();
13321
13322 /* If the stub supports QAgent. */
13323 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13324 putpkt (rs->buf);
13325 getpkt (&rs->buf, &rs->buf_size, 0);
13326
13327 if (strcmp (rs->buf, "OK") == 0)
13328 {
13329 ::use_agent = use;
13330 return 1;
13331 }
13332 }
13333
13334 return 0;
13335 }
13336
13337 int
13338 remote_target::can_use_agent ()
13339 {
13340 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13341 }
13342
13343 struct btrace_target_info
13344 {
13345 /* The ptid of the traced thread. */
13346 ptid_t ptid;
13347
13348 /* The obtained branch trace configuration. */
13349 struct btrace_config conf;
13350 };
13351
13352 /* Reset our idea of our target's btrace configuration. */
13353
13354 static void
13355 remote_btrace_reset (void)
13356 {
13357 struct remote_state *rs = get_remote_state ();
13358
13359 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13360 }
13361
13362 /* Synchronize the configuration with the target. */
13363
13364 static void
13365 btrace_sync_conf (const struct btrace_config *conf)
13366 {
13367 struct packet_config *packet;
13368 struct remote_state *rs;
13369 char *buf, *pos, *endbuf;
13370
13371 rs = get_remote_state ();
13372 buf = rs->buf;
13373 endbuf = buf + get_remote_packet_size ();
13374
13375 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13376 if (packet_config_support (packet) == PACKET_ENABLE
13377 && conf->bts.size != rs->btrace_config.bts.size)
13378 {
13379 pos = buf;
13380 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13381 conf->bts.size);
13382
13383 putpkt (buf);
13384 getpkt (&buf, &rs->buf_size, 0);
13385
13386 if (packet_ok (buf, packet) == PACKET_ERROR)
13387 {
13388 if (buf[0] == 'E' && buf[1] == '.')
13389 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13390 else
13391 error (_("Failed to configure the BTS buffer size."));
13392 }
13393
13394 rs->btrace_config.bts.size = conf->bts.size;
13395 }
13396
13397 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13398 if (packet_config_support (packet) == PACKET_ENABLE
13399 && conf->pt.size != rs->btrace_config.pt.size)
13400 {
13401 pos = buf;
13402 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13403 conf->pt.size);
13404
13405 putpkt (buf);
13406 getpkt (&buf, &rs->buf_size, 0);
13407
13408 if (packet_ok (buf, packet) == PACKET_ERROR)
13409 {
13410 if (buf[0] == 'E' && buf[1] == '.')
13411 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13412 else
13413 error (_("Failed to configure the trace buffer size."));
13414 }
13415
13416 rs->btrace_config.pt.size = conf->pt.size;
13417 }
13418 }
13419
13420 /* Read the current thread's btrace configuration from the target and
13421 store it into CONF. */
13422
13423 static void
13424 btrace_read_config (struct btrace_config *conf)
13425 {
13426 gdb::optional<gdb::char_vector> xml
13427 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
13428 if (xml)
13429 parse_xml_btrace_conf (conf, xml->data ());
13430 }
13431
13432 /* Maybe reopen target btrace. */
13433
13434 static void
13435 remote_btrace_maybe_reopen (void)
13436 {
13437 struct remote_state *rs = get_remote_state ();
13438 struct thread_info *tp;
13439 int btrace_target_pushed = 0;
13440 int warned = 0;
13441
13442 scoped_restore_current_thread restore_thread;
13443
13444 ALL_NON_EXITED_THREADS (tp)
13445 {
13446 set_general_thread (tp->ptid);
13447
13448 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13449 btrace_read_config (&rs->btrace_config);
13450
13451 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13452 continue;
13453
13454 #if !defined (HAVE_LIBIPT)
13455 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13456 {
13457 if (!warned)
13458 {
13459 warned = 1;
13460 warning (_("Target is recording using Intel Processor Trace "
13461 "but support was disabled at compile time."));
13462 }
13463
13464 continue;
13465 }
13466 #endif /* !defined (HAVE_LIBIPT) */
13467
13468 /* Push target, once, but before anything else happens. This way our
13469 changes to the threads will be cleaned up by unpushing the target
13470 in case btrace_read_config () throws. */
13471 if (!btrace_target_pushed)
13472 {
13473 btrace_target_pushed = 1;
13474 record_btrace_push_target ();
13475 printf_filtered (_("Target is recording using %s.\n"),
13476 btrace_format_string (rs->btrace_config.format));
13477 }
13478
13479 tp->btrace.target = XCNEW (struct btrace_target_info);
13480 tp->btrace.target->ptid = tp->ptid;
13481 tp->btrace.target->conf = rs->btrace_config;
13482 }
13483 }
13484
13485 /* Enable branch tracing. */
13486
13487 struct btrace_target_info *
13488 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13489 {
13490 struct btrace_target_info *tinfo = NULL;
13491 struct packet_config *packet = NULL;
13492 struct remote_state *rs = get_remote_state ();
13493 char *buf = rs->buf;
13494 char *endbuf = rs->buf + get_remote_packet_size ();
13495
13496 switch (conf->format)
13497 {
13498 case BTRACE_FORMAT_BTS:
13499 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13500 break;
13501
13502 case BTRACE_FORMAT_PT:
13503 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13504 break;
13505 }
13506
13507 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13508 error (_("Target does not support branch tracing."));
13509
13510 btrace_sync_conf (conf);
13511
13512 set_general_thread (ptid);
13513
13514 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13515 putpkt (rs->buf);
13516 getpkt (&rs->buf, &rs->buf_size, 0);
13517
13518 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13519 {
13520 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13521 error (_("Could not enable branch tracing for %s: %s"),
13522 target_pid_to_str (ptid), rs->buf + 2);
13523 else
13524 error (_("Could not enable branch tracing for %s."),
13525 target_pid_to_str (ptid));
13526 }
13527
13528 tinfo = XCNEW (struct btrace_target_info);
13529 tinfo->ptid = ptid;
13530
13531 /* If we fail to read the configuration, we lose some information, but the
13532 tracing itself is not impacted. */
13533 TRY
13534 {
13535 btrace_read_config (&tinfo->conf);
13536 }
13537 CATCH (err, RETURN_MASK_ERROR)
13538 {
13539 if (err.message != NULL)
13540 warning ("%s", err.message);
13541 }
13542 END_CATCH
13543
13544 return tinfo;
13545 }
13546
13547 /* Disable branch tracing. */
13548
13549 void
13550 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13551 {
13552 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13553 struct remote_state *rs = get_remote_state ();
13554 char *buf = rs->buf;
13555 char *endbuf = rs->buf + get_remote_packet_size ();
13556
13557 if (packet_config_support (packet) != PACKET_ENABLE)
13558 error (_("Target does not support branch tracing."));
13559
13560 set_general_thread (tinfo->ptid);
13561
13562 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13563 putpkt (rs->buf);
13564 getpkt (&rs->buf, &rs->buf_size, 0);
13565
13566 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13567 {
13568 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13569 error (_("Could not disable branch tracing for %s: %s"),
13570 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13571 else
13572 error (_("Could not disable branch tracing for %s."),
13573 target_pid_to_str (tinfo->ptid));
13574 }
13575
13576 xfree (tinfo);
13577 }
13578
13579 /* Teardown branch tracing. */
13580
13581 void
13582 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13583 {
13584 /* We must not talk to the target during teardown. */
13585 xfree (tinfo);
13586 }
13587
13588 /* Read the branch trace. */
13589
13590 enum btrace_error
13591 remote_target::read_btrace (struct btrace_data *btrace,
13592 struct btrace_target_info *tinfo,
13593 enum btrace_read_type type)
13594 {
13595 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13596 const char *annex;
13597
13598 if (packet_config_support (packet) != PACKET_ENABLE)
13599 error (_("Target does not support branch tracing."));
13600
13601 #if !defined(HAVE_LIBEXPAT)
13602 error (_("Cannot process branch tracing result. XML parsing not supported."));
13603 #endif
13604
13605 switch (type)
13606 {
13607 case BTRACE_READ_ALL:
13608 annex = "all";
13609 break;
13610 case BTRACE_READ_NEW:
13611 annex = "new";
13612 break;
13613 case BTRACE_READ_DELTA:
13614 annex = "delta";
13615 break;
13616 default:
13617 internal_error (__FILE__, __LINE__,
13618 _("Bad branch tracing read type: %u."),
13619 (unsigned int) type);
13620 }
13621
13622 gdb::optional<gdb::char_vector> xml
13623 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
13624 if (!xml)
13625 return BTRACE_ERR_UNKNOWN;
13626
13627 parse_xml_btrace (btrace, xml->data ());
13628
13629 return BTRACE_ERR_NONE;
13630 }
13631
13632 const struct btrace_config *
13633 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13634 {
13635 return &tinfo->conf;
13636 }
13637
13638 int
13639 remote_target::augmented_libraries_svr4_read ()
13640 {
13641 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13642 == PACKET_ENABLE);
13643 }
13644
13645 /* Implementation of to_load. */
13646
13647 void
13648 remote_target::load (const char *name, int from_tty)
13649 {
13650 generic_load (name, from_tty);
13651 }
13652
13653 /* Accepts an integer PID; returns a string representing a file that
13654 can be opened on the remote side to get the symbols for the child
13655 process. Returns NULL if the operation is not supported. */
13656
13657 char *
13658 remote_target::pid_to_exec_file (int pid)
13659 {
13660 static gdb::optional<gdb::char_vector> filename;
13661 struct inferior *inf;
13662 char *annex = NULL;
13663
13664 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13665 return NULL;
13666
13667 inf = find_inferior_pid (pid);
13668 if (inf == NULL)
13669 internal_error (__FILE__, __LINE__,
13670 _("not currently attached to process %d"), pid);
13671
13672 if (!inf->fake_pid_p)
13673 {
13674 const int annex_size = 9;
13675
13676 annex = (char *) alloca (annex_size);
13677 xsnprintf (annex, annex_size, "%x", pid);
13678 }
13679
13680 filename = target_read_stralloc (target_stack,
13681 TARGET_OBJECT_EXEC_FILE, annex);
13682
13683 return filename ? filename->data () : nullptr;
13684 }
13685
13686 /* Implement the to_can_do_single_step target_ops method. */
13687
13688 int
13689 remote_target::can_do_single_step ()
13690 {
13691 /* We can only tell whether target supports single step or not by
13692 supported s and S vCont actions if the stub supports vContSupported
13693 feature. If the stub doesn't support vContSupported feature,
13694 we have conservatively to think target doesn't supports single
13695 step. */
13696 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13697 {
13698 struct remote_state *rs = get_remote_state ();
13699
13700 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13701 remote_vcont_probe (rs);
13702
13703 return rs->supports_vCont.s && rs->supports_vCont.S;
13704 }
13705 else
13706 return 0;
13707 }
13708
13709 /* Implementation of the to_execution_direction method for the remote
13710 target. */
13711
13712 enum exec_direction_kind
13713 remote_target::execution_direction ()
13714 {
13715 struct remote_state *rs = get_remote_state ();
13716
13717 return rs->last_resume_exec_dir;
13718 }
13719
13720 /* Return pointer to the thread_info struct which corresponds to
13721 THREAD_HANDLE (having length HANDLE_LEN). */
13722
13723 thread_info *
13724 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13725 int handle_len,
13726 inferior *inf)
13727 {
13728 struct thread_info *tp;
13729
13730 ALL_NON_EXITED_THREADS (tp)
13731 {
13732 remote_thread_info *priv = get_remote_thread_info (tp);
13733
13734 if (tp->inf == inf && priv != NULL)
13735 {
13736 if (handle_len != priv->thread_handle.size ())
13737 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13738 handle_len, priv->thread_handle.size ());
13739 if (memcmp (thread_handle, priv->thread_handle.data (),
13740 handle_len) == 0)
13741 return tp;
13742 }
13743 }
13744
13745 return NULL;
13746 }
13747
13748 int
13749 remote_target::can_async_p ()
13750 {
13751 struct remote_state *rs = get_remote_state ();
13752
13753 /* We don't go async if the user has explicitly prevented it with the
13754 "maint set target-async" command. */
13755 if (!target_async_permitted)
13756 return 0;
13757
13758 /* We're async whenever the serial device is. */
13759 return serial_can_async_p (rs->remote_desc);
13760 }
13761
13762 int
13763 remote_target::is_async_p ()
13764 {
13765 struct remote_state *rs = get_remote_state ();
13766
13767 if (!target_async_permitted)
13768 /* We only enable async when the user specifically asks for it. */
13769 return 0;
13770
13771 /* We're async whenever the serial device is. */
13772 return serial_is_async_p (rs->remote_desc);
13773 }
13774
13775 /* Pass the SERIAL event on and up to the client. One day this code
13776 will be able to delay notifying the client of an event until the
13777 point where an entire packet has been received. */
13778
13779 static serial_event_ftype remote_async_serial_handler;
13780
13781 static void
13782 remote_async_serial_handler (struct serial *scb, void *context)
13783 {
13784 /* Don't propogate error information up to the client. Instead let
13785 the client find out about the error by querying the target. */
13786 inferior_event_handler (INF_REG_EVENT, NULL);
13787 }
13788
13789 static void
13790 remote_async_inferior_event_handler (gdb_client_data data)
13791 {
13792 inferior_event_handler (INF_REG_EVENT, NULL);
13793 }
13794
13795 void
13796 remote_target::async (int enable)
13797 {
13798 struct remote_state *rs = get_remote_state ();
13799
13800 if (enable)
13801 {
13802 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13803
13804 /* If there are pending events in the stop reply queue tell the
13805 event loop to process them. */
13806 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13807 mark_async_event_handler (remote_async_inferior_event_token);
13808 /* For simplicity, below we clear the pending events token
13809 without remembering whether it is marked, so here we always
13810 mark it. If there's actually no pending notification to
13811 process, this ends up being a no-op (other than a spurious
13812 event-loop wakeup). */
13813 if (target_is_non_stop_p ())
13814 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13815 }
13816 else
13817 {
13818 serial_async (rs->remote_desc, NULL, NULL);
13819 /* If the core is disabling async, it doesn't want to be
13820 disturbed with target events. Clear all async event sources
13821 too. */
13822 clear_async_event_handler (remote_async_inferior_event_token);
13823 if (target_is_non_stop_p ())
13824 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13825 }
13826 }
13827
13828 /* Implementation of the to_thread_events method. */
13829
13830 void
13831 remote_target::thread_events (int enable)
13832 {
13833 struct remote_state *rs = get_remote_state ();
13834 size_t size = get_remote_packet_size ();
13835
13836 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13837 return;
13838
13839 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13840 putpkt (rs->buf);
13841 getpkt (&rs->buf, &rs->buf_size, 0);
13842
13843 switch (packet_ok (rs->buf,
13844 &remote_protocol_packets[PACKET_QThreadEvents]))
13845 {
13846 case PACKET_OK:
13847 if (strcmp (rs->buf, "OK") != 0)
13848 error (_("Remote refused setting thread events: %s"), rs->buf);
13849 break;
13850 case PACKET_ERROR:
13851 warning (_("Remote failure reply: %s"), rs->buf);
13852 break;
13853 case PACKET_UNKNOWN:
13854 break;
13855 }
13856 }
13857
13858 static void
13859 set_remote_cmd (const char *args, int from_tty)
13860 {
13861 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13862 }
13863
13864 static void
13865 show_remote_cmd (const char *args, int from_tty)
13866 {
13867 /* We can't just use cmd_show_list here, because we want to skip
13868 the redundant "show remote Z-packet" and the legacy aliases. */
13869 struct cmd_list_element *list = remote_show_cmdlist;
13870 struct ui_out *uiout = current_uiout;
13871
13872 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13873 for (; list != NULL; list = list->next)
13874 if (strcmp (list->name, "Z-packet") == 0)
13875 continue;
13876 else if (list->type == not_set_cmd)
13877 /* Alias commands are exactly like the original, except they
13878 don't have the normal type. */
13879 continue;
13880 else
13881 {
13882 ui_out_emit_tuple option_emitter (uiout, "option");
13883
13884 uiout->field_string ("name", list->name);
13885 uiout->text (": ");
13886 if (list->type == show_cmd)
13887 do_show_command (NULL, from_tty, list);
13888 else
13889 cmd_func (list, NULL, from_tty);
13890 }
13891 }
13892
13893
13894 /* Function to be called whenever a new objfile (shlib) is detected. */
13895 static void
13896 remote_new_objfile (struct objfile *objfile)
13897 {
13898 struct remote_state *rs = get_remote_state ();
13899
13900 if (rs->remote_desc != 0) /* Have a remote connection. */
13901 remote_check_symbols ();
13902 }
13903
13904 /* Pull all the tracepoints defined on the target and create local
13905 data structures representing them. We don't want to create real
13906 tracepoints yet, we don't want to mess up the user's existing
13907 collection. */
13908
13909 int
13910 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
13911 {
13912 struct remote_state *rs = get_remote_state ();
13913 char *p;
13914
13915 /* Ask for a first packet of tracepoint definition. */
13916 putpkt ("qTfP");
13917 getpkt (&rs->buf, &rs->buf_size, 0);
13918 p = rs->buf;
13919 while (*p && *p != 'l')
13920 {
13921 parse_tracepoint_definition (p, utpp);
13922 /* Ask for another packet of tracepoint definition. */
13923 putpkt ("qTsP");
13924 getpkt (&rs->buf, &rs->buf_size, 0);
13925 p = rs->buf;
13926 }
13927 return 0;
13928 }
13929
13930 int
13931 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
13932 {
13933 struct remote_state *rs = get_remote_state ();
13934 char *p;
13935
13936 /* Ask for a first packet of variable definition. */
13937 putpkt ("qTfV");
13938 getpkt (&rs->buf, &rs->buf_size, 0);
13939 p = rs->buf;
13940 while (*p && *p != 'l')
13941 {
13942 parse_tsv_definition (p, utsvp);
13943 /* Ask for another packet of variable definition. */
13944 putpkt ("qTsV");
13945 getpkt (&rs->buf, &rs->buf_size, 0);
13946 p = rs->buf;
13947 }
13948 return 0;
13949 }
13950
13951 /* The "set/show range-stepping" show hook. */
13952
13953 static void
13954 show_range_stepping (struct ui_file *file, int from_tty,
13955 struct cmd_list_element *c,
13956 const char *value)
13957 {
13958 fprintf_filtered (file,
13959 _("Debugger's willingness to use range stepping "
13960 "is %s.\n"), value);
13961 }
13962
13963 /* The "set/show range-stepping" set hook. */
13964
13965 static void
13966 set_range_stepping (const char *ignore_args, int from_tty,
13967 struct cmd_list_element *c)
13968 {
13969 struct remote_state *rs = get_remote_state ();
13970
13971 /* Whene enabling, check whether range stepping is actually
13972 supported by the target, and warn if not. */
13973 if (use_range_stepping)
13974 {
13975 if (rs->remote_desc != NULL)
13976 {
13977 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13978 remote_vcont_probe (rs);
13979
13980 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13981 && rs->supports_vCont.r)
13982 return;
13983 }
13984
13985 warning (_("Range stepping is not supported by the current target"));
13986 }
13987 }
13988
13989 void
13990 _initialize_remote (void)
13991 {
13992 struct cmd_list_element *cmd;
13993 const char *cmd_name;
13994
13995 /* architecture specific data */
13996 remote_gdbarch_data_handle =
13997 gdbarch_data_register_post_init (init_remote_state);
13998 remote_g_packet_data_handle =
13999 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14000
14001 remote_pspace_data
14002 = register_program_space_data_with_cleanup (NULL,
14003 remote_pspace_data_cleanup);
14004
14005 /* Initialize the per-target state. At the moment there is only one
14006 of these, not one per target. Only one target is active at a
14007 time. */
14008 remote_state = new_remote_state ();
14009
14010 add_target (&remote_ops);
14011 add_target (&extended_remote_ops);
14012
14013 /* Hook into new objfile notification. */
14014 gdb::observers::new_objfile.attach (remote_new_objfile);
14015 /* We're no longer interested in notification events of an inferior
14016 when it exits. */
14017 gdb::observers::inferior_exit.attach (discard_pending_stop_replies);
14018
14019 #if 0
14020 init_remote_threadtests ();
14021 #endif
14022
14023 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14024 /* set/show remote ... */
14025
14026 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14027 Remote protocol specific variables\n\
14028 Configure various remote-protocol specific variables such as\n\
14029 the packets being used"),
14030 &remote_set_cmdlist, "set remote ",
14031 0 /* allow-unknown */, &setlist);
14032 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14033 Remote protocol specific variables\n\
14034 Configure various remote-protocol specific variables such as\n\
14035 the packets being used"),
14036 &remote_show_cmdlist, "show remote ",
14037 0 /* allow-unknown */, &showlist);
14038
14039 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14040 Compare section data on target to the exec file.\n\
14041 Argument is a single section name (default: all loaded sections).\n\
14042 To compare only read-only loaded sections, specify the -r option."),
14043 &cmdlist);
14044
14045 add_cmd ("packet", class_maintenance, packet_command, _("\
14046 Send an arbitrary packet to a remote target.\n\
14047 maintenance packet TEXT\n\
14048 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14049 this command sends the string TEXT to the inferior, and displays the\n\
14050 response packet. GDB supplies the initial `$' character, and the\n\
14051 terminating `#' character and checksum."),
14052 &maintenancelist);
14053
14054 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14055 Set whether to send break if interrupted."), _("\
14056 Show whether to send break if interrupted."), _("\
14057 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14058 set_remotebreak, show_remotebreak,
14059 &setlist, &showlist);
14060 cmd_name = "remotebreak";
14061 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14062 deprecate_cmd (cmd, "set remote interrupt-sequence");
14063 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14064 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14065 deprecate_cmd (cmd, "show remote interrupt-sequence");
14066
14067 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14068 interrupt_sequence_modes, &interrupt_sequence_mode,
14069 _("\
14070 Set interrupt sequence to remote target."), _("\
14071 Show interrupt sequence to remote target."), _("\
14072 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14073 NULL, show_interrupt_sequence,
14074 &remote_set_cmdlist,
14075 &remote_show_cmdlist);
14076
14077 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14078 &interrupt_on_connect, _("\
14079 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14080 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14081 If set, interrupt sequence is sent to remote target."),
14082 NULL, NULL,
14083 &remote_set_cmdlist, &remote_show_cmdlist);
14084
14085 /* Install commands for configuring memory read/write packets. */
14086
14087 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14088 Set the maximum number of bytes per memory write packet (deprecated)."),
14089 &setlist);
14090 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14091 Show the maximum number of bytes per memory write packet (deprecated)."),
14092 &showlist);
14093 add_cmd ("memory-write-packet-size", no_class,
14094 set_memory_write_packet_size, _("\
14095 Set the maximum number of bytes per memory-write packet.\n\
14096 Specify the number of bytes in a packet or 0 (zero) for the\n\
14097 default packet size. The actual limit is further reduced\n\
14098 dependent on the target. Specify ``fixed'' to disable the\n\
14099 further restriction and ``limit'' to enable that restriction."),
14100 &remote_set_cmdlist);
14101 add_cmd ("memory-read-packet-size", no_class,
14102 set_memory_read_packet_size, _("\
14103 Set the maximum number of bytes per memory-read packet.\n\
14104 Specify the number of bytes in a packet or 0 (zero) for the\n\
14105 default packet size. The actual limit is further reduced\n\
14106 dependent on the target. Specify ``fixed'' to disable the\n\
14107 further restriction and ``limit'' to enable that restriction."),
14108 &remote_set_cmdlist);
14109 add_cmd ("memory-write-packet-size", no_class,
14110 show_memory_write_packet_size,
14111 _("Show the maximum number of bytes per memory-write packet."),
14112 &remote_show_cmdlist);
14113 add_cmd ("memory-read-packet-size", no_class,
14114 show_memory_read_packet_size,
14115 _("Show the maximum number of bytes per memory-read packet."),
14116 &remote_show_cmdlist);
14117
14118 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14119 &remote_hw_watchpoint_limit, _("\
14120 Set the maximum number of target hardware watchpoints."), _("\
14121 Show the maximum number of target hardware watchpoints."), _("\
14122 Specify a negative limit for unlimited."),
14123 NULL, NULL, /* FIXME: i18n: The maximum
14124 number of target hardware
14125 watchpoints is %s. */
14126 &remote_set_cmdlist, &remote_show_cmdlist);
14127 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14128 &remote_hw_watchpoint_length_limit, _("\
14129 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14130 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14131 Specify a negative limit for unlimited."),
14132 NULL, NULL, /* FIXME: i18n: The maximum
14133 length (in bytes) of a target
14134 hardware watchpoint is %s. */
14135 &remote_set_cmdlist, &remote_show_cmdlist);
14136 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14137 &remote_hw_breakpoint_limit, _("\
14138 Set the maximum number of target hardware breakpoints."), _("\
14139 Show the maximum number of target hardware breakpoints."), _("\
14140 Specify a negative limit for unlimited."),
14141 NULL, NULL, /* FIXME: i18n: The maximum
14142 number of target hardware
14143 breakpoints is %s. */
14144 &remote_set_cmdlist, &remote_show_cmdlist);
14145
14146 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14147 &remote_address_size, _("\
14148 Set the maximum size of the address (in bits) in a memory packet."), _("\
14149 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14150 NULL,
14151 NULL, /* FIXME: i18n: */
14152 &setlist, &showlist);
14153
14154 init_all_packet_configs ();
14155
14156 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14157 "X", "binary-download", 1);
14158
14159 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14160 "vCont", "verbose-resume", 0);
14161
14162 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14163 "QPassSignals", "pass-signals", 0);
14164
14165 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14166 "QCatchSyscalls", "catch-syscalls", 0);
14167
14168 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14169 "QProgramSignals", "program-signals", 0);
14170
14171 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14172 "QSetWorkingDir", "set-working-dir", 0);
14173
14174 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14175 "QStartupWithShell", "startup-with-shell", 0);
14176
14177 add_packet_config_cmd (&remote_protocol_packets
14178 [PACKET_QEnvironmentHexEncoded],
14179 "QEnvironmentHexEncoded", "environment-hex-encoded",
14180 0);
14181
14182 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14183 "QEnvironmentReset", "environment-reset",
14184 0);
14185
14186 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14187 "QEnvironmentUnset", "environment-unset",
14188 0);
14189
14190 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14191 "qSymbol", "symbol-lookup", 0);
14192
14193 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14194 "P", "set-register", 1);
14195
14196 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14197 "p", "fetch-register", 1);
14198
14199 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14200 "Z0", "software-breakpoint", 0);
14201
14202 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14203 "Z1", "hardware-breakpoint", 0);
14204
14205 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14206 "Z2", "write-watchpoint", 0);
14207
14208 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14209 "Z3", "read-watchpoint", 0);
14210
14211 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14212 "Z4", "access-watchpoint", 0);
14213
14214 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14215 "qXfer:auxv:read", "read-aux-vector", 0);
14216
14217 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14218 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14219
14220 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14221 "qXfer:features:read", "target-features", 0);
14222
14223 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14224 "qXfer:libraries:read", "library-info", 0);
14225
14226 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14227 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14228
14229 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14230 "qXfer:memory-map:read", "memory-map", 0);
14231
14232 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14233 "qXfer:spu:read", "read-spu-object", 0);
14234
14235 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14236 "qXfer:spu:write", "write-spu-object", 0);
14237
14238 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14239 "qXfer:osdata:read", "osdata", 0);
14240
14241 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14242 "qXfer:threads:read", "threads", 0);
14243
14244 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14245 "qXfer:siginfo:read", "read-siginfo-object", 0);
14246
14247 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14248 "qXfer:siginfo:write", "write-siginfo-object", 0);
14249
14250 add_packet_config_cmd
14251 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14252 "qXfer:traceframe-info:read", "traceframe-info", 0);
14253
14254 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14255 "qXfer:uib:read", "unwind-info-block", 0);
14256
14257 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14258 "qGetTLSAddr", "get-thread-local-storage-address",
14259 0);
14260
14261 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14262 "qGetTIBAddr", "get-thread-information-block-address",
14263 0);
14264
14265 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14266 "bc", "reverse-continue", 0);
14267
14268 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14269 "bs", "reverse-step", 0);
14270
14271 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14272 "qSupported", "supported-packets", 0);
14273
14274 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14275 "qSearch:memory", "search-memory", 0);
14276
14277 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14278 "qTStatus", "trace-status", 0);
14279
14280 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14281 "vFile:setfs", "hostio-setfs", 0);
14282
14283 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14284 "vFile:open", "hostio-open", 0);
14285
14286 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14287 "vFile:pread", "hostio-pread", 0);
14288
14289 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14290 "vFile:pwrite", "hostio-pwrite", 0);
14291
14292 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14293 "vFile:close", "hostio-close", 0);
14294
14295 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14296 "vFile:unlink", "hostio-unlink", 0);
14297
14298 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14299 "vFile:readlink", "hostio-readlink", 0);
14300
14301 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14302 "vFile:fstat", "hostio-fstat", 0);
14303
14304 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14305 "vAttach", "attach", 0);
14306
14307 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14308 "vRun", "run", 0);
14309
14310 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14311 "QStartNoAckMode", "noack", 0);
14312
14313 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14314 "vKill", "kill", 0);
14315
14316 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14317 "qAttached", "query-attached", 0);
14318
14319 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14320 "ConditionalTracepoints",
14321 "conditional-tracepoints", 0);
14322
14323 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14324 "ConditionalBreakpoints",
14325 "conditional-breakpoints", 0);
14326
14327 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14328 "BreakpointCommands",
14329 "breakpoint-commands", 0);
14330
14331 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14332 "FastTracepoints", "fast-tracepoints", 0);
14333
14334 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14335 "TracepointSource", "TracepointSource", 0);
14336
14337 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14338 "QAllow", "allow", 0);
14339
14340 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14341 "StaticTracepoints", "static-tracepoints", 0);
14342
14343 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14344 "InstallInTrace", "install-in-trace", 0);
14345
14346 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14347 "qXfer:statictrace:read", "read-sdata-object", 0);
14348
14349 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14350 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14351
14352 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14353 "QDisableRandomization", "disable-randomization", 0);
14354
14355 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14356 "QAgent", "agent", 0);
14357
14358 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14359 "QTBuffer:size", "trace-buffer-size", 0);
14360
14361 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14362 "Qbtrace:off", "disable-btrace", 0);
14363
14364 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14365 "Qbtrace:bts", "enable-btrace-bts", 0);
14366
14367 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14368 "Qbtrace:pt", "enable-btrace-pt", 0);
14369
14370 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14371 "qXfer:btrace", "read-btrace", 0);
14372
14373 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14374 "qXfer:btrace-conf", "read-btrace-conf", 0);
14375
14376 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14377 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14378
14379 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14380 "multiprocess-feature", "multiprocess-feature", 0);
14381
14382 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14383 "swbreak-feature", "swbreak-feature", 0);
14384
14385 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14386 "hwbreak-feature", "hwbreak-feature", 0);
14387
14388 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14389 "fork-event-feature", "fork-event-feature", 0);
14390
14391 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14392 "vfork-event-feature", "vfork-event-feature", 0);
14393
14394 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14395 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14396
14397 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14398 "vContSupported", "verbose-resume-supported", 0);
14399
14400 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14401 "exec-event-feature", "exec-event-feature", 0);
14402
14403 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14404 "vCtrlC", "ctrl-c", 0);
14405
14406 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14407 "QThreadEvents", "thread-events", 0);
14408
14409 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14410 "N stop reply", "no-resumed-stop-reply", 0);
14411
14412 /* Assert that we've registered "set remote foo-packet" commands
14413 for all packet configs. */
14414 {
14415 int i;
14416
14417 for (i = 0; i < PACKET_MAX; i++)
14418 {
14419 /* Ideally all configs would have a command associated. Some
14420 still don't though. */
14421 int excepted;
14422
14423 switch (i)
14424 {
14425 case PACKET_QNonStop:
14426 case PACKET_EnableDisableTracepoints_feature:
14427 case PACKET_tracenz_feature:
14428 case PACKET_DisconnectedTracing_feature:
14429 case PACKET_augmented_libraries_svr4_read_feature:
14430 case PACKET_qCRC:
14431 /* Additions to this list need to be well justified:
14432 pre-existing packets are OK; new packets are not. */
14433 excepted = 1;
14434 break;
14435 default:
14436 excepted = 0;
14437 break;
14438 }
14439
14440 /* This catches both forgetting to add a config command, and
14441 forgetting to remove a packet from the exception list. */
14442 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14443 }
14444 }
14445
14446 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14447 Z sub-packet has its own set and show commands, but users may
14448 have sets to this variable in their .gdbinit files (or in their
14449 documentation). */
14450 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14451 &remote_Z_packet_detect, _("\
14452 Set use of remote protocol `Z' packets"), _("\
14453 Show use of remote protocol `Z' packets "), _("\
14454 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14455 packets."),
14456 set_remote_protocol_Z_packet_cmd,
14457 show_remote_protocol_Z_packet_cmd,
14458 /* FIXME: i18n: Use of remote protocol
14459 `Z' packets is %s. */
14460 &remote_set_cmdlist, &remote_show_cmdlist);
14461
14462 add_prefix_cmd ("remote", class_files, remote_command, _("\
14463 Manipulate files on the remote system\n\
14464 Transfer files to and from the remote target system."),
14465 &remote_cmdlist, "remote ",
14466 0 /* allow-unknown */, &cmdlist);
14467
14468 add_cmd ("put", class_files, remote_put_command,
14469 _("Copy a local file to the remote system."),
14470 &remote_cmdlist);
14471
14472 add_cmd ("get", class_files, remote_get_command,
14473 _("Copy a remote file to the local system."),
14474 &remote_cmdlist);
14475
14476 add_cmd ("delete", class_files, remote_delete_command,
14477 _("Delete a remote file."),
14478 &remote_cmdlist);
14479
14480 add_setshow_string_noescape_cmd ("exec-file", class_files,
14481 &remote_exec_file_var, _("\
14482 Set the remote pathname for \"run\""), _("\
14483 Show the remote pathname for \"run\""), NULL,
14484 set_remote_exec_file,
14485 show_remote_exec_file,
14486 &remote_set_cmdlist,
14487 &remote_show_cmdlist);
14488
14489 add_setshow_boolean_cmd ("range-stepping", class_run,
14490 &use_range_stepping, _("\
14491 Enable or disable range stepping."), _("\
14492 Show whether target-assisted range stepping is enabled."), _("\
14493 If on, and the target supports it, when stepping a source line, GDB\n\
14494 tells the target to step the corresponding range of addresses itself instead\n\
14495 of issuing multiple single-steps. This speeds up source level\n\
14496 stepping. If off, GDB always issues single-steps, even if range\n\
14497 stepping is supported by the target. The default is on."),
14498 set_range_stepping,
14499 show_range_stepping,
14500 &setlist,
14501 &showlist);
14502
14503 /* Eventually initialize fileio. See fileio.c */
14504 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14505
14506 /* Take advantage of the fact that the TID field is not used, to tag
14507 special ptids with it set to != 0. */
14508 magic_null_ptid = ptid_build (42000, -1, 1);
14509 not_sent_ptid = ptid_build (42000, -2, 1);
14510 any_thread_ptid = ptid_build (42000, 0, 1);
14511 }
This page took 0.306098 seconds and 5 git commands to generate.