target factories, target open and multiple instances of targets
[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 static const char remote_doc[] = N_("\
82 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
83 Specify the serial device it is connected to\n\
84 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
85
86 static const target_info remote_target_info = {
87 "remote",
88 N_("Remote serial target in gdb-specific protocol"),
89 remote_doc
90 };
91
92 class remote_target : public target_ops
93 {
94 public:
95 remote_target ()
96 {
97 to_stratum = process_stratum;
98 }
99
100 const target_info &info () const override
101 { return remote_target_info; }
102
103 thread_control_capabilities get_thread_control_capabilities () override
104 { return tc_schedlock; }
105
106 /* Open a remote connection. */
107 static void open (const char *, int);
108
109 void close () override;
110
111 void detach (inferior *, int) override;
112 void disconnect (const char *, int) override;
113
114 void commit_resume () override;
115 void resume (ptid_t, int, enum gdb_signal) override;
116 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
117
118 void fetch_registers (struct regcache *, int) override;
119 void store_registers (struct regcache *, int) override;
120 void prepare_to_store (struct regcache *) override;
121
122 void files_info () override;
123
124 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
125
126 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
127 enum remove_bp_reason) override;
128
129
130 bool stopped_by_sw_breakpoint () override;
131 bool supports_stopped_by_sw_breakpoint () override;
132
133 bool stopped_by_hw_breakpoint () override;
134
135 bool supports_stopped_by_hw_breakpoint () override;
136
137 bool stopped_by_watchpoint () override;
138
139 bool stopped_data_address (CORE_ADDR *) override;
140
141 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
142
143 int can_use_hw_breakpoint (enum bptype, int, int) override;
144
145 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
146
147 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
148
149 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
150
151 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
152 struct expression *) override;
153
154 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
155 struct expression *) override;
156
157 void kill () override;
158
159 void load (const char *, int) override;
160
161 void mourn_inferior () override;
162
163 void pass_signals (int, unsigned char *) override;
164
165 int set_syscall_catchpoint (int, bool, int,
166 gdb::array_view<const int>) override;
167
168 void program_signals (int, unsigned char *) override;
169
170 bool thread_alive (ptid_t ptid) override;
171
172 const char *thread_name (struct thread_info *) override;
173
174 void update_thread_list () override;
175
176 const char *pid_to_str (ptid_t) override;
177
178 const char *extra_thread_info (struct thread_info *) override;
179
180 ptid_t get_ada_task_ptid (long lwp, long thread) override;
181
182 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
183 int handle_len,
184 inferior *inf) override;
185
186 void stop (ptid_t) override;
187
188 void interrupt () override;
189
190 void pass_ctrlc () override;
191
192 enum target_xfer_status xfer_partial (enum target_object object,
193 const char *annex,
194 gdb_byte *readbuf,
195 const gdb_byte *writebuf,
196 ULONGEST offset, ULONGEST len,
197 ULONGEST *xfered_len) override;
198
199 ULONGEST get_memory_xfer_limit () override;
200
201 void rcmd (const char *command, struct ui_file *output) override;
202
203 char *pid_to_exec_file (int pid) override;
204
205 void log_command (const char *cmd) override
206 {
207 serial_log_command (this, cmd);
208 }
209
210 CORE_ADDR get_thread_local_address (ptid_t ptid,
211 CORE_ADDR load_module_addr,
212 CORE_ADDR offset) override;
213
214 bool has_all_memory () override { return default_child_has_all_memory (); }
215 bool has_memory () override { return default_child_has_memory (); }
216 bool has_stack () override { return default_child_has_stack (); }
217 bool has_registers () override { return default_child_has_registers (); }
218 bool has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
219
220 bool can_execute_reverse () override;
221
222 std::vector<mem_region> memory_map () override;
223
224 void flash_erase (ULONGEST address, LONGEST length) override;
225
226 void flash_done () override;
227
228 const struct target_desc *read_description () override;
229
230 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
231 const gdb_byte *pattern, ULONGEST pattern_len,
232 CORE_ADDR *found_addrp) override;
233
234 bool can_async_p () override;
235
236 bool is_async_p () override;
237
238 void async (int) override;
239
240 void thread_events (int) override;
241
242 int can_do_single_step () override;
243
244 void terminal_inferior () override;
245
246 void terminal_ours () override;
247
248 bool supports_non_stop () override;
249
250 bool supports_multi_process () override;
251
252 bool supports_disable_randomization () override;
253
254 bool filesystem_is_local () override;
255
256
257 int fileio_open (struct inferior *inf, const char *filename,
258 int flags, int mode, int warn_if_slow,
259 int *target_errno) override;
260
261 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
262 ULONGEST offset, int *target_errno) override;
263
264 int fileio_pread (int fd, gdb_byte *read_buf, int len,
265 ULONGEST offset, int *target_errno) override;
266
267 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
268
269 int fileio_close (int fd, int *target_errno) override;
270
271 int fileio_unlink (struct inferior *inf,
272 const char *filename,
273 int *target_errno) override;
274
275 gdb::optional<std::string>
276 fileio_readlink (struct inferior *inf,
277 const char *filename,
278 int *target_errno) override;
279
280 bool supports_enable_disable_tracepoint () override;
281
282 bool supports_string_tracing () override;
283
284 bool supports_evaluation_of_breakpoint_conditions () override;
285
286 bool can_run_breakpoint_commands () override;
287
288 void trace_init () override;
289
290 void download_tracepoint (struct bp_location *location) override;
291
292 bool can_download_tracepoint () override;
293
294 void download_trace_state_variable (const trace_state_variable &tsv) override;
295
296 void enable_tracepoint (struct bp_location *location) override;
297
298 void disable_tracepoint (struct bp_location *location) override;
299
300 void trace_set_readonly_regions () override;
301
302 void trace_start () override;
303
304 int get_trace_status (struct trace_status *ts) override;
305
306 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
307 override;
308
309 void trace_stop () override;
310
311 int trace_find (enum trace_find_type type, int num,
312 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
313
314 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
315
316 int save_trace_data (const char *filename) override;
317
318 int upload_tracepoints (struct uploaded_tp **utpp) override;
319
320 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
321
322 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
323
324 int get_min_fast_tracepoint_insn_len () override;
325
326 void set_disconnected_tracing (int val) override;
327
328 void set_circular_trace_buffer (int val) override;
329
330 void set_trace_buffer_size (LONGEST val) override;
331
332 bool set_trace_notes (const char *user, const char *notes,
333 const char *stopnotes) override;
334
335 int core_of_thread (ptid_t ptid) override;
336
337 int verify_memory (const gdb_byte *data,
338 CORE_ADDR memaddr, ULONGEST size) override;
339
340
341 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
342
343 void set_permissions () override;
344
345 bool static_tracepoint_marker_at (CORE_ADDR,
346 struct static_tracepoint_marker *marker)
347 override;
348
349 std::vector<static_tracepoint_marker>
350 static_tracepoint_markers_by_strid (const char *id) override;
351
352 traceframe_info_up traceframe_info () override;
353
354 bool use_agent (bool use) override;
355 bool can_use_agent () override;
356
357 struct btrace_target_info *enable_btrace (ptid_t ptid,
358 const struct btrace_config *conf) override;
359
360 void disable_btrace (struct btrace_target_info *tinfo) override;
361
362 void teardown_btrace (struct btrace_target_info *tinfo) override;
363
364 enum btrace_error read_btrace (struct btrace_data *data,
365 struct btrace_target_info *btinfo,
366 enum btrace_read_type type) override;
367
368 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
369 bool augmented_libraries_svr4_read () override;
370 int follow_fork (int, int) override;
371 void follow_exec (struct inferior *, char *) override;
372 int insert_fork_catchpoint (int) override;
373 int remove_fork_catchpoint (int) override;
374 int insert_vfork_catchpoint (int) override;
375 int remove_vfork_catchpoint (int) override;
376 int insert_exec_catchpoint (int) override;
377 int remove_exec_catchpoint (int) override;
378 enum exec_direction_kind execution_direction () override;
379
380 protected:
381 static void open_1 (const char *name, int from_tty, int extended_p);
382 void start_remote (int from_tty, int extended_p);
383 };
384
385 static const target_info extended_remote_target_info = {
386 "extended-remote",
387 N_("Extended remote serial target in gdb-specific protocol"),
388 remote_doc
389 };
390
391 /* Set up the extended remote target by extending the standard remote
392 target and adding to it. */
393
394 class extended_remote_target final : public remote_target
395 {
396 public:
397 const target_info &info () const override
398 { return extended_remote_target_info; }
399
400 /* Open an extended-remote connection. */
401 static void open (const char *, int);
402
403 bool can_create_inferior () override { return true; }
404 void create_inferior (const char *, const std::string &,
405 char **, int) override;
406
407 void detach (inferior *, int) override;
408
409 bool can_attach () override { return true; }
410 void attach (const char *, int) override;
411
412 void post_attach (int) override;
413 bool supports_disable_randomization () override;
414 };
415
416 /* Per-program-space data key. */
417 static const struct program_space_data *remote_pspace_data;
418
419 /* The variable registered as the control variable used by the
420 remote exec-file commands. While the remote exec-file setting is
421 per-program-space, the set/show machinery uses this as the
422 location of the remote exec-file value. */
423 static char *remote_exec_file_var;
424
425 /* The size to align memory write packets, when practical. The protocol
426 does not guarantee any alignment, and gdb will generate short
427 writes and unaligned writes, but even as a best-effort attempt this
428 can improve bulk transfers. For instance, if a write is misaligned
429 relative to the target's data bus, the stub may need to make an extra
430 round trip fetching data from the target. This doesn't make a
431 huge difference, but it's easy to do, so we try to be helpful.
432
433 The alignment chosen is arbitrary; usually data bus width is
434 important here, not the possibly larger cache line size. */
435 enum { REMOTE_ALIGN_WRITES = 16 };
436
437 /* Prototypes for local functions. */
438 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
439 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
440 int forever, int *is_notif);
441
442 struct remote_state;
443
444 static int remote_vkill (int pid, struct remote_state *rs);
445
446 static void remote_kill_k (void);
447
448 static int readchar (int timeout);
449
450 static void remote_serial_write (const char *str, int len);
451
452 static void interrupt_query (void);
453
454 static void set_general_thread (ptid_t ptid);
455 static void set_continue_thread (ptid_t ptid);
456
457 static void get_offsets (void);
458
459 static void skip_frame (void);
460
461 static long read_frame (char **buf_p, long *sizeof_buf);
462
463 static int hexnumlen (ULONGEST num);
464
465 static int stubhex (int ch);
466
467 static int hexnumstr (char *, ULONGEST);
468
469 static int hexnumnstr (char *, ULONGEST, int);
470
471 static CORE_ADDR remote_address_masked (CORE_ADDR);
472
473 static void print_packet (const char *);
474
475 static int stub_unpack_int (char *buff, int fieldlength);
476
477 static ptid_t remote_current_thread (ptid_t oldptid);
478
479 static int putpkt_binary (const char *buf, int cnt);
480
481 static void check_binary_download (CORE_ADDR addr);
482
483 struct packet_config;
484
485 static void show_packet_config_cmd (struct packet_config *config);
486
487 static void show_remote_protocol_packet_cmd (struct ui_file *file,
488 int from_tty,
489 struct cmd_list_element *c,
490 const char *value);
491
492 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
493 static ptid_t read_ptid (const char *buf, const char **obuf);
494
495 static void remote_query_supported (void);
496
497 static void remote_check_symbols (void);
498
499 struct stop_reply;
500 static void stop_reply_xfree (struct stop_reply *);
501 static void remote_parse_stop_reply (char *, struct stop_reply *);
502 static void push_stop_reply (struct stop_reply *);
503 static void discard_pending_stop_replies_in_queue (struct remote_state *);
504 static int peek_stop_reply (ptid_t ptid);
505
506 struct threads_listing_context;
507 static void remove_new_fork_children (struct threads_listing_context *);
508
509 static void remote_async_inferior_event_handler (gdb_client_data);
510
511 static int remote_read_description_p (struct target_ops *target);
512
513 static void remote_console_output (char *msg);
514
515 static void remote_btrace_reset (void);
516
517 static void remote_btrace_maybe_reopen (void);
518
519 static int stop_reply_queue_length (void);
520
521 static void readahead_cache_invalidate (void);
522
523 static void remote_unpush_and_throw (void);
524
525 static struct remote_state *get_remote_state (void);
526
527 /* For "remote". */
528
529 static struct cmd_list_element *remote_cmdlist;
530
531 /* For "set remote" and "show remote". */
532
533 static struct cmd_list_element *remote_set_cmdlist;
534 static struct cmd_list_element *remote_show_cmdlist;
535
536 /* Stub vCont actions support.
537
538 Each field is a boolean flag indicating whether the stub reports
539 support for the corresponding action. */
540
541 struct vCont_action_support
542 {
543 /* vCont;t */
544 int t;
545
546 /* vCont;r */
547 int r;
548
549 /* vCont;s */
550 int s;
551
552 /* vCont;S */
553 int S;
554 };
555
556 /* Controls whether GDB is willing to use range stepping. */
557
558 static int use_range_stepping = 1;
559
560 #define OPAQUETHREADBYTES 8
561
562 /* a 64 bit opaque identifier */
563 typedef unsigned char threadref[OPAQUETHREADBYTES];
564
565 /* About this many threadisds fit in a packet. */
566
567 #define MAXTHREADLISTRESULTS 32
568
569 /* The max number of chars in debug output. The rest of chars are
570 omitted. */
571
572 #define REMOTE_DEBUG_MAX_CHAR 512
573
574 /* Data for the vFile:pread readahead cache. */
575
576 struct readahead_cache
577 {
578 /* The file descriptor for the file that is being cached. -1 if the
579 cache is invalid. */
580 int fd;
581
582 /* The offset into the file that the cache buffer corresponds
583 to. */
584 ULONGEST offset;
585
586 /* The buffer holding the cache contents. */
587 gdb_byte *buf;
588 /* The buffer's size. We try to read as much as fits into a packet
589 at a time. */
590 size_t bufsize;
591
592 /* Cache hit and miss counters. */
593 ULONGEST hit_count;
594 ULONGEST miss_count;
595 };
596
597 /* Description of the remote protocol state for the currently
598 connected target. This is per-target state, and independent of the
599 selected architecture. */
600
601 struct remote_state
602 {
603 /* A buffer to use for incoming packets, and its current size. The
604 buffer is grown dynamically for larger incoming packets.
605 Outgoing packets may also be constructed in this buffer.
606 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
607 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
608 packets. */
609 char *buf;
610 long buf_size;
611
612 /* True if we're going through initial connection setup (finding out
613 about the remote side's threads, relocating symbols, etc.). */
614 int starting_up;
615
616 /* If we negotiated packet size explicitly (and thus can bypass
617 heuristics for the largest packet size that will not overflow
618 a buffer in the stub), this will be set to that packet size.
619 Otherwise zero, meaning to use the guessed size. */
620 long explicit_packet_size;
621
622 /* remote_wait is normally called when the target is running and
623 waits for a stop reply packet. But sometimes we need to call it
624 when the target is already stopped. We can send a "?" packet
625 and have remote_wait read the response. Or, if we already have
626 the response, we can stash it in BUF and tell remote_wait to
627 skip calling getpkt. This flag is set when BUF contains a
628 stop reply packet and the target is not waiting. */
629 int cached_wait_status;
630
631 /* True, if in no ack mode. That is, neither GDB nor the stub will
632 expect acks from each other. The connection is assumed to be
633 reliable. */
634 int noack_mode;
635
636 /* True if we're connected in extended remote mode. */
637 int extended;
638
639 /* True if we resumed the target and we're waiting for the target to
640 stop. In the mean time, we can't start another command/query.
641 The remote server wouldn't be ready to process it, so we'd
642 timeout waiting for a reply that would never come and eventually
643 we'd close the connection. This can happen in asynchronous mode
644 because we allow GDB commands while the target is running. */
645 int waiting_for_stop_reply;
646
647 /* The status of the stub support for the various vCont actions. */
648 struct vCont_action_support supports_vCont;
649
650 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
651 responded to that. */
652 int ctrlc_pending_p;
653
654 /* True if we saw a Ctrl-C while reading or writing from/to the
655 remote descriptor. At that point it is not safe to send a remote
656 interrupt packet, so we instead remember we saw the Ctrl-C and
657 process it once we're done with sending/receiving the current
658 packet, which should be shortly. If however that takes too long,
659 and the user presses Ctrl-C again, we offer to disconnect. */
660 int got_ctrlc_during_io;
661
662 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
663 remote_open knows that we don't have a file open when the program
664 starts. */
665 struct serial *remote_desc;
666
667 /* These are the threads which we last sent to the remote system. The
668 TID member will be -1 for all or -2 for not sent yet. */
669 ptid_t general_thread;
670 ptid_t continue_thread;
671
672 /* This is the traceframe which we last selected on the remote system.
673 It will be -1 if no traceframe is selected. */
674 int remote_traceframe_number;
675
676 char *last_pass_packet;
677
678 /* The last QProgramSignals packet sent to the target. We bypass
679 sending a new program signals list down to the target if the new
680 packet is exactly the same as the last we sent. IOW, we only let
681 the target know about program signals list changes. */
682 char *last_program_signals_packet;
683
684 enum gdb_signal last_sent_signal;
685
686 int last_sent_step;
687
688 /* The execution direction of the last resume we got. */
689 enum exec_direction_kind last_resume_exec_dir;
690
691 char *finished_object;
692 char *finished_annex;
693 ULONGEST finished_offset;
694
695 /* Should we try the 'ThreadInfo' query packet?
696
697 This variable (NOT available to the user: auto-detect only!)
698 determines whether GDB will use the new, simpler "ThreadInfo"
699 query or the older, more complex syntax for thread queries.
700 This is an auto-detect variable (set to true at each connect,
701 and set to false when the target fails to recognize it). */
702 int use_threadinfo_query;
703 int use_threadextra_query;
704
705 threadref echo_nextthread;
706 threadref nextthread;
707 threadref resultthreadlist[MAXTHREADLISTRESULTS];
708
709 /* The state of remote notification. */
710 struct remote_notif_state *notif_state;
711
712 /* The branch trace configuration. */
713 struct btrace_config btrace_config;
714
715 /* The argument to the last "vFile:setfs:" packet we sent, used
716 to avoid sending repeated unnecessary "vFile:setfs:" packets.
717 Initialized to -1 to indicate that no "vFile:setfs:" packet
718 has yet been sent. */
719 int fs_pid;
720
721 /* A readahead cache for vFile:pread. Often, reading a binary
722 involves a sequence of small reads. E.g., when parsing an ELF
723 file. A readahead cache helps mostly the case of remote
724 debugging on a connection with higher latency, due to the
725 request/reply nature of the RSP. We only cache data for a single
726 file descriptor at a time. */
727 struct readahead_cache readahead_cache;
728 };
729
730 /* Private data that we'll store in (struct thread_info)->priv. */
731 struct remote_thread_info : public private_thread_info
732 {
733 std::string extra;
734 std::string name;
735 int core = -1;
736
737 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
738 sequence of bytes. */
739 gdb::byte_vector thread_handle;
740
741 /* Whether the target stopped for a breakpoint/watchpoint. */
742 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
743
744 /* This is set to the data address of the access causing the target
745 to stop for a watchpoint. */
746 CORE_ADDR watch_data_address = 0;
747
748 /* Fields used by the vCont action coalescing implemented in
749 remote_resume / remote_commit_resume. remote_resume stores each
750 thread's last resume request in these fields, so that a later
751 remote_commit_resume knows which is the proper action for this
752 thread to include in the vCont packet. */
753
754 /* True if the last target_resume call for this thread was a step
755 request, false if a continue request. */
756 int last_resume_step = 0;
757
758 /* The signal specified in the last target_resume call for this
759 thread. */
760 gdb_signal last_resume_sig = GDB_SIGNAL_0;
761
762 /* Whether this thread was already vCont-resumed on the remote
763 side. */
764 int vcont_resumed = 0;
765 };
766
767 /* This data could be associated with a target, but we do not always
768 have access to the current target when we need it, so for now it is
769 static. This will be fine for as long as only one target is in use
770 at a time. */
771 static struct remote_state *remote_state;
772
773 static struct remote_state *
774 get_remote_state_raw (void)
775 {
776 return remote_state;
777 }
778
779 /* Allocate a new struct remote_state with xmalloc, initialize it, and
780 return it. */
781
782 static struct remote_state *
783 new_remote_state (void)
784 {
785 struct remote_state *result = XCNEW (struct remote_state);
786
787 /* The default buffer size is unimportant; it will be expanded
788 whenever a larger buffer is needed. */
789 result->buf_size = 400;
790 result->buf = (char *) xmalloc (result->buf_size);
791 result->remote_traceframe_number = -1;
792 result->last_sent_signal = GDB_SIGNAL_0;
793 result->last_resume_exec_dir = EXEC_FORWARD;
794 result->fs_pid = -1;
795
796 return result;
797 }
798
799 /* Description of the remote protocol for a given architecture. */
800
801 struct packet_reg
802 {
803 long offset; /* Offset into G packet. */
804 long regnum; /* GDB's internal register number. */
805 LONGEST pnum; /* Remote protocol register number. */
806 int in_g_packet; /* Always part of G packet. */
807 /* long size in bytes; == register_size (target_gdbarch (), regnum);
808 at present. */
809 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
810 at present. */
811 };
812
813 struct remote_arch_state
814 {
815 /* Description of the remote protocol registers. */
816 long sizeof_g_packet;
817
818 /* Description of the remote protocol registers indexed by REGNUM
819 (making an array gdbarch_num_regs in size). */
820 struct packet_reg *regs;
821
822 /* This is the size (in chars) of the first response to the ``g''
823 packet. It is used as a heuristic when determining the maximum
824 size of memory-read and memory-write packets. A target will
825 typically only reserve a buffer large enough to hold the ``g''
826 packet. The size does not include packet overhead (headers and
827 trailers). */
828 long actual_register_packet_size;
829
830 /* This is the maximum size (in chars) of a non read/write packet.
831 It is also used as a cap on the size of read/write packets. */
832 long remote_packet_size;
833 };
834
835 /* Utility: generate error from an incoming stub packet. */
836 static void
837 trace_error (char *buf)
838 {
839 if (*buf++ != 'E')
840 return; /* not an error msg */
841 switch (*buf)
842 {
843 case '1': /* malformed packet error */
844 if (*++buf == '0') /* general case: */
845 error (_("remote.c: error in outgoing packet."));
846 else
847 error (_("remote.c: error in outgoing packet at field #%ld."),
848 strtol (buf, NULL, 16));
849 default:
850 error (_("Target returns error code '%s'."), buf);
851 }
852 }
853
854 /* Utility: wait for reply from stub, while accepting "O" packets. */
855
856 static char *
857 remote_get_noisy_reply ()
858 {
859 struct remote_state *rs = get_remote_state ();
860
861 do /* Loop on reply from remote stub. */
862 {
863 char *buf;
864
865 QUIT; /* Allow user to bail out with ^C. */
866 getpkt (&rs->buf, &rs->buf_size, 0);
867 buf = rs->buf;
868 if (buf[0] == 'E')
869 trace_error (buf);
870 else if (startswith (buf, "qRelocInsn:"))
871 {
872 ULONGEST ul;
873 CORE_ADDR from, to, org_to;
874 const char *p, *pp;
875 int adjusted_size = 0;
876 int relocated = 0;
877
878 p = buf + strlen ("qRelocInsn:");
879 pp = unpack_varlen_hex (p, &ul);
880 if (*pp != ';')
881 error (_("invalid qRelocInsn packet: %s"), buf);
882 from = ul;
883
884 p = pp + 1;
885 unpack_varlen_hex (p, &ul);
886 to = ul;
887
888 org_to = to;
889
890 TRY
891 {
892 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
893 relocated = 1;
894 }
895 CATCH (ex, RETURN_MASK_ALL)
896 {
897 if (ex.error == MEMORY_ERROR)
898 {
899 /* Propagate memory errors silently back to the
900 target. The stub may have limited the range of
901 addresses we can write to, for example. */
902 }
903 else
904 {
905 /* Something unexpectedly bad happened. Be verbose
906 so we can tell what, and propagate the error back
907 to the stub, so it doesn't get stuck waiting for
908 a response. */
909 exception_fprintf (gdb_stderr, ex,
910 _("warning: relocating instruction: "));
911 }
912 putpkt ("E01");
913 }
914 END_CATCH
915
916 if (relocated)
917 {
918 adjusted_size = to - org_to;
919
920 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
921 putpkt (buf);
922 }
923 }
924 else if (buf[0] == 'O' && buf[1] != 'K')
925 remote_console_output (buf + 1); /* 'O' message from stub */
926 else
927 return buf; /* Here's the actual reply. */
928 }
929 while (1);
930 }
931
932 /* Handle for retreving the remote protocol data from gdbarch. */
933 static struct gdbarch_data *remote_gdbarch_data_handle;
934
935 static struct remote_arch_state *
936 get_remote_arch_state (struct gdbarch *gdbarch)
937 {
938 gdb_assert (gdbarch != NULL);
939 return ((struct remote_arch_state *)
940 gdbarch_data (gdbarch, remote_gdbarch_data_handle));
941 }
942
943 /* Fetch the global remote target state. */
944
945 static struct remote_state *
946 get_remote_state (void)
947 {
948 /* Make sure that the remote architecture state has been
949 initialized, because doing so might reallocate rs->buf. Any
950 function which calls getpkt also needs to be mindful of changes
951 to rs->buf, but this call limits the number of places which run
952 into trouble. */
953 get_remote_arch_state (target_gdbarch ());
954
955 return get_remote_state_raw ();
956 }
957
958 /* Cleanup routine for the remote module's pspace data. */
959
960 static void
961 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
962 {
963 char *remote_exec_file = (char *) arg;
964
965 xfree (remote_exec_file);
966 }
967
968 /* Fetch the remote exec-file from the current program space. */
969
970 static const char *
971 get_remote_exec_file (void)
972 {
973 char *remote_exec_file;
974
975 remote_exec_file
976 = (char *) program_space_data (current_program_space,
977 remote_pspace_data);
978 if (remote_exec_file == NULL)
979 return "";
980
981 return remote_exec_file;
982 }
983
984 /* Set the remote exec file for PSPACE. */
985
986 static void
987 set_pspace_remote_exec_file (struct program_space *pspace,
988 char *remote_exec_file)
989 {
990 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
991
992 xfree (old_file);
993 set_program_space_data (pspace, remote_pspace_data,
994 xstrdup (remote_exec_file));
995 }
996
997 /* The "set/show remote exec-file" set command hook. */
998
999 static void
1000 set_remote_exec_file (const char *ignored, int from_tty,
1001 struct cmd_list_element *c)
1002 {
1003 gdb_assert (remote_exec_file_var != NULL);
1004 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1005 }
1006
1007 /* The "set/show remote exec-file" show command hook. */
1008
1009 static void
1010 show_remote_exec_file (struct ui_file *file, int from_tty,
1011 struct cmd_list_element *cmd, const char *value)
1012 {
1013 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1014 }
1015
1016 static int
1017 compare_pnums (const void *lhs_, const void *rhs_)
1018 {
1019 const struct packet_reg * const *lhs
1020 = (const struct packet_reg * const *) lhs_;
1021 const struct packet_reg * const *rhs
1022 = (const struct packet_reg * const *) rhs_;
1023
1024 if ((*lhs)->pnum < (*rhs)->pnum)
1025 return -1;
1026 else if ((*lhs)->pnum == (*rhs)->pnum)
1027 return 0;
1028 else
1029 return 1;
1030 }
1031
1032 static int
1033 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1034 {
1035 int regnum, num_remote_regs, offset;
1036 struct packet_reg **remote_regs;
1037
1038 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1039 {
1040 struct packet_reg *r = &regs[regnum];
1041
1042 if (register_size (gdbarch, regnum) == 0)
1043 /* Do not try to fetch zero-sized (placeholder) registers. */
1044 r->pnum = -1;
1045 else
1046 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1047
1048 r->regnum = regnum;
1049 }
1050
1051 /* Define the g/G packet format as the contents of each register
1052 with a remote protocol number, in order of ascending protocol
1053 number. */
1054
1055 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1056 for (num_remote_regs = 0, regnum = 0;
1057 regnum < gdbarch_num_regs (gdbarch);
1058 regnum++)
1059 if (regs[regnum].pnum != -1)
1060 remote_regs[num_remote_regs++] = &regs[regnum];
1061
1062 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1063 compare_pnums);
1064
1065 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1066 {
1067 remote_regs[regnum]->in_g_packet = 1;
1068 remote_regs[regnum]->offset = offset;
1069 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1070 }
1071
1072 return offset;
1073 }
1074
1075 /* Given the architecture described by GDBARCH, return the remote
1076 protocol register's number and the register's offset in the g/G
1077 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1078 If the target does not have a mapping for REGNUM, return false,
1079 otherwise, return true. */
1080
1081 int
1082 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1083 int *pnum, int *poffset)
1084 {
1085 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1086
1087 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1088
1089 map_regcache_remote_table (gdbarch, regs.data ());
1090
1091 *pnum = regs[regnum].pnum;
1092 *poffset = regs[regnum].offset;
1093
1094 return *pnum != -1;
1095 }
1096
1097 static void *
1098 init_remote_state (struct gdbarch *gdbarch)
1099 {
1100 struct remote_state *rs = get_remote_state_raw ();
1101 struct remote_arch_state *rsa;
1102
1103 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
1104
1105 /* Use the architecture to build a regnum<->pnum table, which will be
1106 1:1 unless a feature set specifies otherwise. */
1107 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
1108 gdbarch_num_regs (gdbarch),
1109 struct packet_reg);
1110
1111 /* Record the maximum possible size of the g packet - it may turn out
1112 to be smaller. */
1113 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
1114
1115 /* Default maximum number of characters in a packet body. Many
1116 remote stubs have a hardwired buffer size of 400 bytes
1117 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1118 as the maximum packet-size to ensure that the packet and an extra
1119 NUL character can always fit in the buffer. This stops GDB
1120 trashing stubs that try to squeeze an extra NUL into what is
1121 already a full buffer (As of 1999-12-04 that was most stubs). */
1122 rsa->remote_packet_size = 400 - 1;
1123
1124 /* This one is filled in when a ``g'' packet is received. */
1125 rsa->actual_register_packet_size = 0;
1126
1127 /* Should rsa->sizeof_g_packet needs more space than the
1128 default, adjust the size accordingly. Remember that each byte is
1129 encoded as two characters. 32 is the overhead for the packet
1130 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1131 (``$NN:G...#NN'') is a better guess, the below has been padded a
1132 little. */
1133 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
1134 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
1135
1136 /* Make sure that the packet buffer is plenty big enough for
1137 this architecture. */
1138 if (rs->buf_size < rsa->remote_packet_size)
1139 {
1140 rs->buf_size = 2 * rsa->remote_packet_size;
1141 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
1142 }
1143
1144 return rsa;
1145 }
1146
1147 /* Return the current allowed size of a remote packet. This is
1148 inferred from the current architecture, and should be used to
1149 limit the length of outgoing packets. */
1150 static long
1151 get_remote_packet_size (void)
1152 {
1153 struct remote_state *rs = get_remote_state ();
1154 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1155
1156 if (rs->explicit_packet_size)
1157 return rs->explicit_packet_size;
1158
1159 return rsa->remote_packet_size;
1160 }
1161
1162 static struct packet_reg *
1163 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1164 long regnum)
1165 {
1166 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1167 return NULL;
1168 else
1169 {
1170 struct packet_reg *r = &rsa->regs[regnum];
1171
1172 gdb_assert (r->regnum == regnum);
1173 return r;
1174 }
1175 }
1176
1177 static struct packet_reg *
1178 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1179 LONGEST pnum)
1180 {
1181 int i;
1182
1183 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1184 {
1185 struct packet_reg *r = &rsa->regs[i];
1186
1187 if (r->pnum == pnum)
1188 return r;
1189 }
1190 return NULL;
1191 }
1192
1193 static remote_target remote_ops;
1194
1195 static extended_remote_target extended_remote_ops;
1196
1197 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
1198 ``forever'' still use the normal timeout mechanism. This is
1199 currently used by the ASYNC code to guarentee that target reads
1200 during the initial connect always time-out. Once getpkt has been
1201 modified to return a timeout indication and, in turn
1202 remote_wait()/wait_for_inferior() have gained a timeout parameter
1203 this can go away. */
1204 static int wait_forever_enabled_p = 1;
1205
1206 /* Allow the user to specify what sequence to send to the remote
1207 when he requests a program interruption: Although ^C is usually
1208 what remote systems expect (this is the default, here), it is
1209 sometimes preferable to send a break. On other systems such
1210 as the Linux kernel, a break followed by g, which is Magic SysRq g
1211 is required in order to interrupt the execution. */
1212 const char interrupt_sequence_control_c[] = "Ctrl-C";
1213 const char interrupt_sequence_break[] = "BREAK";
1214 const char interrupt_sequence_break_g[] = "BREAK-g";
1215 static const char *const interrupt_sequence_modes[] =
1216 {
1217 interrupt_sequence_control_c,
1218 interrupt_sequence_break,
1219 interrupt_sequence_break_g,
1220 NULL
1221 };
1222 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1223
1224 static void
1225 show_interrupt_sequence (struct ui_file *file, int from_tty,
1226 struct cmd_list_element *c,
1227 const char *value)
1228 {
1229 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1230 fprintf_filtered (file,
1231 _("Send the ASCII ETX character (Ctrl-c) "
1232 "to the remote target to interrupt the "
1233 "execution of the program.\n"));
1234 else if (interrupt_sequence_mode == interrupt_sequence_break)
1235 fprintf_filtered (file,
1236 _("send a break signal to the remote target "
1237 "to interrupt the execution of the program.\n"));
1238 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1239 fprintf_filtered (file,
1240 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1241 "the remote target to interrupt the execution "
1242 "of Linux kernel.\n"));
1243 else
1244 internal_error (__FILE__, __LINE__,
1245 _("Invalid value for interrupt_sequence_mode: %s."),
1246 interrupt_sequence_mode);
1247 }
1248
1249 /* This boolean variable specifies whether interrupt_sequence is sent
1250 to the remote target when gdb connects to it.
1251 This is mostly needed when you debug the Linux kernel: The Linux kernel
1252 expects BREAK g which is Magic SysRq g for connecting gdb. */
1253 static int interrupt_on_connect = 0;
1254
1255 /* This variable is used to implement the "set/show remotebreak" commands.
1256 Since these commands are now deprecated in favor of "set/show remote
1257 interrupt-sequence", it no longer has any effect on the code. */
1258 static int remote_break;
1259
1260 static void
1261 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1262 {
1263 if (remote_break)
1264 interrupt_sequence_mode = interrupt_sequence_break;
1265 else
1266 interrupt_sequence_mode = interrupt_sequence_control_c;
1267 }
1268
1269 static void
1270 show_remotebreak (struct ui_file *file, int from_tty,
1271 struct cmd_list_element *c,
1272 const char *value)
1273 {
1274 }
1275
1276 /* This variable sets the number of bits in an address that are to be
1277 sent in a memory ("M" or "m") packet. Normally, after stripping
1278 leading zeros, the entire address would be sent. This variable
1279 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1280 initial implementation of remote.c restricted the address sent in
1281 memory packets to ``host::sizeof long'' bytes - (typically 32
1282 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1283 address was never sent. Since fixing this bug may cause a break in
1284 some remote targets this variable is principly provided to
1285 facilitate backward compatibility. */
1286
1287 static unsigned int remote_address_size;
1288
1289 \f
1290 /* User configurable variables for the number of characters in a
1291 memory read/write packet. MIN (rsa->remote_packet_size,
1292 rsa->sizeof_g_packet) is the default. Some targets need smaller
1293 values (fifo overruns, et.al.) and some users need larger values
1294 (speed up transfers). The variables ``preferred_*'' (the user
1295 request), ``current_*'' (what was actually set) and ``forced_*''
1296 (Positive - a soft limit, negative - a hard limit). */
1297
1298 struct memory_packet_config
1299 {
1300 const char *name;
1301 long size;
1302 int fixed_p;
1303 };
1304
1305 /* The default max memory-write-packet-size. The 16k is historical.
1306 (It came from older GDB's using alloca for buffers and the
1307 knowledge (folklore?) that some hosts don't cope very well with
1308 large alloca calls.) */
1309 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1310
1311 /* The minimum remote packet size for memory transfers. Ensures we
1312 can write at least one byte. */
1313 #define MIN_MEMORY_PACKET_SIZE 20
1314
1315 /* Compute the current size of a read/write packet. Since this makes
1316 use of ``actual_register_packet_size'' the computation is dynamic. */
1317
1318 static long
1319 get_memory_packet_size (struct memory_packet_config *config)
1320 {
1321 struct remote_state *rs = get_remote_state ();
1322 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1323
1324 long what_they_get;
1325 if (config->fixed_p)
1326 {
1327 if (config->size <= 0)
1328 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1329 else
1330 what_they_get = config->size;
1331 }
1332 else
1333 {
1334 what_they_get = get_remote_packet_size ();
1335 /* Limit the packet to the size specified by the user. */
1336 if (config->size > 0
1337 && what_they_get > config->size)
1338 what_they_get = config->size;
1339
1340 /* Limit it to the size of the targets ``g'' response unless we have
1341 permission from the stub to use a larger packet size. */
1342 if (rs->explicit_packet_size == 0
1343 && rsa->actual_register_packet_size > 0
1344 && what_they_get > rsa->actual_register_packet_size)
1345 what_they_get = rsa->actual_register_packet_size;
1346 }
1347 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1348 what_they_get = MIN_MEMORY_PACKET_SIZE;
1349
1350 /* Make sure there is room in the global buffer for this packet
1351 (including its trailing NUL byte). */
1352 if (rs->buf_size < what_they_get + 1)
1353 {
1354 rs->buf_size = 2 * what_they_get;
1355 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1356 }
1357
1358 return what_they_get;
1359 }
1360
1361 /* Update the size of a read/write packet. If they user wants
1362 something really big then do a sanity check. */
1363
1364 static void
1365 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1366 {
1367 int fixed_p = config->fixed_p;
1368 long size = config->size;
1369
1370 if (args == NULL)
1371 error (_("Argument required (integer, `fixed' or `limited')."));
1372 else if (strcmp (args, "hard") == 0
1373 || strcmp (args, "fixed") == 0)
1374 fixed_p = 1;
1375 else if (strcmp (args, "soft") == 0
1376 || strcmp (args, "limit") == 0)
1377 fixed_p = 0;
1378 else
1379 {
1380 char *end;
1381
1382 size = strtoul (args, &end, 0);
1383 if (args == end)
1384 error (_("Invalid %s (bad syntax)."), config->name);
1385
1386 /* Instead of explicitly capping the size of a packet to or
1387 disallowing it, the user is allowed to set the size to
1388 something arbitrarily large. */
1389 }
1390
1391 /* So that the query shows the correct value. */
1392 if (size <= 0)
1393 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1394
1395 /* Extra checks? */
1396 if (fixed_p && !config->fixed_p)
1397 {
1398 if (! query (_("The target may not be able to correctly handle a %s\n"
1399 "of %ld bytes. Change the packet size? "),
1400 config->name, size))
1401 error (_("Packet size not changed."));
1402 }
1403 /* Update the config. */
1404 config->fixed_p = fixed_p;
1405 config->size = size;
1406 }
1407
1408 static void
1409 show_memory_packet_size (struct memory_packet_config *config)
1410 {
1411 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1412 if (config->fixed_p)
1413 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1414 get_memory_packet_size (config));
1415 else
1416 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1417 get_memory_packet_size (config));
1418 }
1419
1420 static struct memory_packet_config memory_write_packet_config =
1421 {
1422 "memory-write-packet-size",
1423 };
1424
1425 static void
1426 set_memory_write_packet_size (const char *args, int from_tty)
1427 {
1428 set_memory_packet_size (args, &memory_write_packet_config);
1429 }
1430
1431 static void
1432 show_memory_write_packet_size (const char *args, int from_tty)
1433 {
1434 show_memory_packet_size (&memory_write_packet_config);
1435 }
1436
1437 static long
1438 get_memory_write_packet_size (void)
1439 {
1440 return get_memory_packet_size (&memory_write_packet_config);
1441 }
1442
1443 static struct memory_packet_config memory_read_packet_config =
1444 {
1445 "memory-read-packet-size",
1446 };
1447
1448 static void
1449 set_memory_read_packet_size (const char *args, int from_tty)
1450 {
1451 set_memory_packet_size (args, &memory_read_packet_config);
1452 }
1453
1454 static void
1455 show_memory_read_packet_size (const char *args, int from_tty)
1456 {
1457 show_memory_packet_size (&memory_read_packet_config);
1458 }
1459
1460 static long
1461 get_memory_read_packet_size (void)
1462 {
1463 long size = get_memory_packet_size (&memory_read_packet_config);
1464
1465 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1466 extra buffer size argument before the memory read size can be
1467 increased beyond this. */
1468 if (size > get_remote_packet_size ())
1469 size = get_remote_packet_size ();
1470 return size;
1471 }
1472
1473 \f
1474 /* Generic configuration support for packets the stub optionally
1475 supports. Allows the user to specify the use of the packet as well
1476 as allowing GDB to auto-detect support in the remote stub. */
1477
1478 enum packet_support
1479 {
1480 PACKET_SUPPORT_UNKNOWN = 0,
1481 PACKET_ENABLE,
1482 PACKET_DISABLE
1483 };
1484
1485 struct packet_config
1486 {
1487 const char *name;
1488 const char *title;
1489
1490 /* If auto, GDB auto-detects support for this packet or feature,
1491 either through qSupported, or by trying the packet and looking
1492 at the response. If true, GDB assumes the target supports this
1493 packet. If false, the packet is disabled. Configs that don't
1494 have an associated command always have this set to auto. */
1495 enum auto_boolean detect;
1496
1497 /* Does the target support this packet? */
1498 enum packet_support support;
1499 };
1500
1501 /* Analyze a packet's return value and update the packet config
1502 accordingly. */
1503
1504 enum packet_result
1505 {
1506 PACKET_ERROR,
1507 PACKET_OK,
1508 PACKET_UNKNOWN
1509 };
1510
1511 static enum packet_support packet_config_support (struct packet_config *config);
1512 static enum packet_support packet_support (int packet);
1513
1514 static void
1515 show_packet_config_cmd (struct packet_config *config)
1516 {
1517 const char *support = "internal-error";
1518
1519 switch (packet_config_support (config))
1520 {
1521 case PACKET_ENABLE:
1522 support = "enabled";
1523 break;
1524 case PACKET_DISABLE:
1525 support = "disabled";
1526 break;
1527 case PACKET_SUPPORT_UNKNOWN:
1528 support = "unknown";
1529 break;
1530 }
1531 switch (config->detect)
1532 {
1533 case AUTO_BOOLEAN_AUTO:
1534 printf_filtered (_("Support for the `%s' packet "
1535 "is auto-detected, currently %s.\n"),
1536 config->name, support);
1537 break;
1538 case AUTO_BOOLEAN_TRUE:
1539 case AUTO_BOOLEAN_FALSE:
1540 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1541 config->name, support);
1542 break;
1543 }
1544 }
1545
1546 static void
1547 add_packet_config_cmd (struct packet_config *config, const char *name,
1548 const char *title, int legacy)
1549 {
1550 char *set_doc;
1551 char *show_doc;
1552 char *cmd_name;
1553
1554 config->name = name;
1555 config->title = title;
1556 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1557 name, title);
1558 show_doc = xstrprintf ("Show current use of remote "
1559 "protocol `%s' (%s) packet",
1560 name, title);
1561 /* set/show TITLE-packet {auto,on,off} */
1562 cmd_name = xstrprintf ("%s-packet", title);
1563 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1564 &config->detect, set_doc,
1565 show_doc, NULL, /* help_doc */
1566 NULL,
1567 show_remote_protocol_packet_cmd,
1568 &remote_set_cmdlist, &remote_show_cmdlist);
1569 /* The command code copies the documentation strings. */
1570 xfree (set_doc);
1571 xfree (show_doc);
1572 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1573 if (legacy)
1574 {
1575 char *legacy_name;
1576
1577 legacy_name = xstrprintf ("%s-packet", name);
1578 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1579 &remote_set_cmdlist);
1580 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1581 &remote_show_cmdlist);
1582 }
1583 }
1584
1585 static enum packet_result
1586 packet_check_result (const char *buf)
1587 {
1588 if (buf[0] != '\0')
1589 {
1590 /* The stub recognized the packet request. Check that the
1591 operation succeeded. */
1592 if (buf[0] == 'E'
1593 && isxdigit (buf[1]) && isxdigit (buf[2])
1594 && buf[3] == '\0')
1595 /* "Enn" - definitly an error. */
1596 return PACKET_ERROR;
1597
1598 /* Always treat "E." as an error. This will be used for
1599 more verbose error messages, such as E.memtypes. */
1600 if (buf[0] == 'E' && buf[1] == '.')
1601 return PACKET_ERROR;
1602
1603 /* The packet may or may not be OK. Just assume it is. */
1604 return PACKET_OK;
1605 }
1606 else
1607 /* The stub does not support the packet. */
1608 return PACKET_UNKNOWN;
1609 }
1610
1611 static enum packet_result
1612 packet_ok (const char *buf, struct packet_config *config)
1613 {
1614 enum packet_result result;
1615
1616 if (config->detect != AUTO_BOOLEAN_TRUE
1617 && config->support == PACKET_DISABLE)
1618 internal_error (__FILE__, __LINE__,
1619 _("packet_ok: attempt to use a disabled packet"));
1620
1621 result = packet_check_result (buf);
1622 switch (result)
1623 {
1624 case PACKET_OK:
1625 case PACKET_ERROR:
1626 /* The stub recognized the packet request. */
1627 if (config->support == PACKET_SUPPORT_UNKNOWN)
1628 {
1629 if (remote_debug)
1630 fprintf_unfiltered (gdb_stdlog,
1631 "Packet %s (%s) is supported\n",
1632 config->name, config->title);
1633 config->support = PACKET_ENABLE;
1634 }
1635 break;
1636 case PACKET_UNKNOWN:
1637 /* The stub does not support the packet. */
1638 if (config->detect == AUTO_BOOLEAN_AUTO
1639 && config->support == PACKET_ENABLE)
1640 {
1641 /* If the stub previously indicated that the packet was
1642 supported then there is a protocol error. */
1643 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1644 config->name, config->title);
1645 }
1646 else if (config->detect == AUTO_BOOLEAN_TRUE)
1647 {
1648 /* The user set it wrong. */
1649 error (_("Enabled packet %s (%s) not recognized by stub"),
1650 config->name, config->title);
1651 }
1652
1653 if (remote_debug)
1654 fprintf_unfiltered (gdb_stdlog,
1655 "Packet %s (%s) is NOT supported\n",
1656 config->name, config->title);
1657 config->support = PACKET_DISABLE;
1658 break;
1659 }
1660
1661 return result;
1662 }
1663
1664 enum {
1665 PACKET_vCont = 0,
1666 PACKET_X,
1667 PACKET_qSymbol,
1668 PACKET_P,
1669 PACKET_p,
1670 PACKET_Z0,
1671 PACKET_Z1,
1672 PACKET_Z2,
1673 PACKET_Z3,
1674 PACKET_Z4,
1675 PACKET_vFile_setfs,
1676 PACKET_vFile_open,
1677 PACKET_vFile_pread,
1678 PACKET_vFile_pwrite,
1679 PACKET_vFile_close,
1680 PACKET_vFile_unlink,
1681 PACKET_vFile_readlink,
1682 PACKET_vFile_fstat,
1683 PACKET_qXfer_auxv,
1684 PACKET_qXfer_features,
1685 PACKET_qXfer_exec_file,
1686 PACKET_qXfer_libraries,
1687 PACKET_qXfer_libraries_svr4,
1688 PACKET_qXfer_memory_map,
1689 PACKET_qXfer_spu_read,
1690 PACKET_qXfer_spu_write,
1691 PACKET_qXfer_osdata,
1692 PACKET_qXfer_threads,
1693 PACKET_qXfer_statictrace_read,
1694 PACKET_qXfer_traceframe_info,
1695 PACKET_qXfer_uib,
1696 PACKET_qGetTIBAddr,
1697 PACKET_qGetTLSAddr,
1698 PACKET_qSupported,
1699 PACKET_qTStatus,
1700 PACKET_QPassSignals,
1701 PACKET_QCatchSyscalls,
1702 PACKET_QProgramSignals,
1703 PACKET_QSetWorkingDir,
1704 PACKET_QStartupWithShell,
1705 PACKET_QEnvironmentHexEncoded,
1706 PACKET_QEnvironmentReset,
1707 PACKET_QEnvironmentUnset,
1708 PACKET_qCRC,
1709 PACKET_qSearch_memory,
1710 PACKET_vAttach,
1711 PACKET_vRun,
1712 PACKET_QStartNoAckMode,
1713 PACKET_vKill,
1714 PACKET_qXfer_siginfo_read,
1715 PACKET_qXfer_siginfo_write,
1716 PACKET_qAttached,
1717
1718 /* Support for conditional tracepoints. */
1719 PACKET_ConditionalTracepoints,
1720
1721 /* Support for target-side breakpoint conditions. */
1722 PACKET_ConditionalBreakpoints,
1723
1724 /* Support for target-side breakpoint commands. */
1725 PACKET_BreakpointCommands,
1726
1727 /* Support for fast tracepoints. */
1728 PACKET_FastTracepoints,
1729
1730 /* Support for static tracepoints. */
1731 PACKET_StaticTracepoints,
1732
1733 /* Support for installing tracepoints while a trace experiment is
1734 running. */
1735 PACKET_InstallInTrace,
1736
1737 PACKET_bc,
1738 PACKET_bs,
1739 PACKET_TracepointSource,
1740 PACKET_QAllow,
1741 PACKET_qXfer_fdpic,
1742 PACKET_QDisableRandomization,
1743 PACKET_QAgent,
1744 PACKET_QTBuffer_size,
1745 PACKET_Qbtrace_off,
1746 PACKET_Qbtrace_bts,
1747 PACKET_Qbtrace_pt,
1748 PACKET_qXfer_btrace,
1749
1750 /* Support for the QNonStop packet. */
1751 PACKET_QNonStop,
1752
1753 /* Support for the QThreadEvents packet. */
1754 PACKET_QThreadEvents,
1755
1756 /* Support for multi-process extensions. */
1757 PACKET_multiprocess_feature,
1758
1759 /* Support for enabling and disabling tracepoints while a trace
1760 experiment is running. */
1761 PACKET_EnableDisableTracepoints_feature,
1762
1763 /* Support for collecting strings using the tracenz bytecode. */
1764 PACKET_tracenz_feature,
1765
1766 /* Support for continuing to run a trace experiment while GDB is
1767 disconnected. */
1768 PACKET_DisconnectedTracing_feature,
1769
1770 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1771 PACKET_augmented_libraries_svr4_read_feature,
1772
1773 /* Support for the qXfer:btrace-conf:read packet. */
1774 PACKET_qXfer_btrace_conf,
1775
1776 /* Support for the Qbtrace-conf:bts:size packet. */
1777 PACKET_Qbtrace_conf_bts_size,
1778
1779 /* Support for swbreak+ feature. */
1780 PACKET_swbreak_feature,
1781
1782 /* Support for hwbreak+ feature. */
1783 PACKET_hwbreak_feature,
1784
1785 /* Support for fork events. */
1786 PACKET_fork_event_feature,
1787
1788 /* Support for vfork events. */
1789 PACKET_vfork_event_feature,
1790
1791 /* Support for the Qbtrace-conf:pt:size packet. */
1792 PACKET_Qbtrace_conf_pt_size,
1793
1794 /* Support for exec events. */
1795 PACKET_exec_event_feature,
1796
1797 /* Support for query supported vCont actions. */
1798 PACKET_vContSupported,
1799
1800 /* Support remote CTRL-C. */
1801 PACKET_vCtrlC,
1802
1803 /* Support TARGET_WAITKIND_NO_RESUMED. */
1804 PACKET_no_resumed,
1805
1806 PACKET_MAX
1807 };
1808
1809 static struct packet_config remote_protocol_packets[PACKET_MAX];
1810
1811 /* Returns the packet's corresponding "set remote foo-packet" command
1812 state. See struct packet_config for more details. */
1813
1814 static enum auto_boolean
1815 packet_set_cmd_state (int packet)
1816 {
1817 return remote_protocol_packets[packet].detect;
1818 }
1819
1820 /* Returns whether a given packet or feature is supported. This takes
1821 into account the state of the corresponding "set remote foo-packet"
1822 command, which may be used to bypass auto-detection. */
1823
1824 static enum packet_support
1825 packet_config_support (struct packet_config *config)
1826 {
1827 switch (config->detect)
1828 {
1829 case AUTO_BOOLEAN_TRUE:
1830 return PACKET_ENABLE;
1831 case AUTO_BOOLEAN_FALSE:
1832 return PACKET_DISABLE;
1833 case AUTO_BOOLEAN_AUTO:
1834 return config->support;
1835 default:
1836 gdb_assert_not_reached (_("bad switch"));
1837 }
1838 }
1839
1840 /* Same as packet_config_support, but takes the packet's enum value as
1841 argument. */
1842
1843 static enum packet_support
1844 packet_support (int packet)
1845 {
1846 struct packet_config *config = &remote_protocol_packets[packet];
1847
1848 return packet_config_support (config);
1849 }
1850
1851 static void
1852 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1853 struct cmd_list_element *c,
1854 const char *value)
1855 {
1856 struct packet_config *packet;
1857
1858 for (packet = remote_protocol_packets;
1859 packet < &remote_protocol_packets[PACKET_MAX];
1860 packet++)
1861 {
1862 if (&packet->detect == c->var)
1863 {
1864 show_packet_config_cmd (packet);
1865 return;
1866 }
1867 }
1868 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1869 c->name);
1870 }
1871
1872 /* Should we try one of the 'Z' requests? */
1873
1874 enum Z_packet_type
1875 {
1876 Z_PACKET_SOFTWARE_BP,
1877 Z_PACKET_HARDWARE_BP,
1878 Z_PACKET_WRITE_WP,
1879 Z_PACKET_READ_WP,
1880 Z_PACKET_ACCESS_WP,
1881 NR_Z_PACKET_TYPES
1882 };
1883
1884 /* For compatibility with older distributions. Provide a ``set remote
1885 Z-packet ...'' command that updates all the Z packet types. */
1886
1887 static enum auto_boolean remote_Z_packet_detect;
1888
1889 static void
1890 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
1891 struct cmd_list_element *c)
1892 {
1893 int i;
1894
1895 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1896 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1897 }
1898
1899 static void
1900 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1901 struct cmd_list_element *c,
1902 const char *value)
1903 {
1904 int i;
1905
1906 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1907 {
1908 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1909 }
1910 }
1911
1912 /* Returns true if the multi-process extensions are in effect. */
1913
1914 static int
1915 remote_multi_process_p (struct remote_state *rs)
1916 {
1917 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1918 }
1919
1920 /* Returns true if fork events are supported. */
1921
1922 static int
1923 remote_fork_event_p (struct remote_state *rs)
1924 {
1925 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1926 }
1927
1928 /* Returns true if vfork events are supported. */
1929
1930 static int
1931 remote_vfork_event_p (struct remote_state *rs)
1932 {
1933 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1934 }
1935
1936 /* Returns true if exec events are supported. */
1937
1938 static int
1939 remote_exec_event_p (struct remote_state *rs)
1940 {
1941 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1942 }
1943
1944 /* Insert fork catchpoint target routine. If fork events are enabled
1945 then return success, nothing more to do. */
1946
1947 int
1948 remote_target::insert_fork_catchpoint (int pid)
1949 {
1950 struct remote_state *rs = get_remote_state ();
1951
1952 return !remote_fork_event_p (rs);
1953 }
1954
1955 /* Remove fork catchpoint target routine. Nothing to do, just
1956 return success. */
1957
1958 int
1959 remote_target::remove_fork_catchpoint (int pid)
1960 {
1961 return 0;
1962 }
1963
1964 /* Insert vfork catchpoint target routine. If vfork events are enabled
1965 then return success, nothing more to do. */
1966
1967 int
1968 remote_target::insert_vfork_catchpoint (int pid)
1969 {
1970 struct remote_state *rs = get_remote_state ();
1971
1972 return !remote_vfork_event_p (rs);
1973 }
1974
1975 /* Remove vfork catchpoint target routine. Nothing to do, just
1976 return success. */
1977
1978 int
1979 remote_target::remove_vfork_catchpoint (int pid)
1980 {
1981 return 0;
1982 }
1983
1984 /* Insert exec catchpoint target routine. If exec events are
1985 enabled, just return success. */
1986
1987 int
1988 remote_target::insert_exec_catchpoint (int pid)
1989 {
1990 struct remote_state *rs = get_remote_state ();
1991
1992 return !remote_exec_event_p (rs);
1993 }
1994
1995 /* Remove exec catchpoint target routine. Nothing to do, just
1996 return success. */
1997
1998 int
1999 remote_target::remove_exec_catchpoint (int pid)
2000 {
2001 return 0;
2002 }
2003
2004 \f
2005 /* Asynchronous signal handle registered as event loop source for
2006 when we have pending events ready to be passed to the core. */
2007
2008 static struct async_event_handler *remote_async_inferior_event_token;
2009
2010 \f
2011
2012 static ptid_t magic_null_ptid;
2013 static ptid_t not_sent_ptid;
2014 static ptid_t any_thread_ptid;
2015
2016 /* Find out if the stub attached to PID (and hence GDB should offer to
2017 detach instead of killing it when bailing out). */
2018
2019 static int
2020 remote_query_attached (int pid)
2021 {
2022 struct remote_state *rs = get_remote_state ();
2023 size_t size = get_remote_packet_size ();
2024
2025 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2026 return 0;
2027
2028 if (remote_multi_process_p (rs))
2029 xsnprintf (rs->buf, size, "qAttached:%x", pid);
2030 else
2031 xsnprintf (rs->buf, size, "qAttached");
2032
2033 putpkt (rs->buf);
2034 getpkt (&rs->buf, &rs->buf_size, 0);
2035
2036 switch (packet_ok (rs->buf,
2037 &remote_protocol_packets[PACKET_qAttached]))
2038 {
2039 case PACKET_OK:
2040 if (strcmp (rs->buf, "1") == 0)
2041 return 1;
2042 break;
2043 case PACKET_ERROR:
2044 warning (_("Remote failure reply: %s"), rs->buf);
2045 break;
2046 case PACKET_UNKNOWN:
2047 break;
2048 }
2049
2050 return 0;
2051 }
2052
2053 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2054 has been invented by GDB, instead of reported by the target. Since
2055 we can be connected to a remote system before before knowing about
2056 any inferior, mark the target with execution when we find the first
2057 inferior. If ATTACHED is 1, then we had just attached to this
2058 inferior. If it is 0, then we just created this inferior. If it
2059 is -1, then try querying the remote stub to find out if it had
2060 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2061 attempt to open this inferior's executable as the main executable
2062 if no main executable is open already. */
2063
2064 static struct inferior *
2065 remote_add_inferior (int fake_pid_p, int pid, int attached,
2066 int try_open_exec)
2067 {
2068 struct inferior *inf;
2069
2070 /* Check whether this process we're learning about is to be
2071 considered attached, or if is to be considered to have been
2072 spawned by the stub. */
2073 if (attached == -1)
2074 attached = remote_query_attached (pid);
2075
2076 if (gdbarch_has_global_solist (target_gdbarch ()))
2077 {
2078 /* If the target shares code across all inferiors, then every
2079 attach adds a new inferior. */
2080 inf = add_inferior (pid);
2081
2082 /* ... and every inferior is bound to the same program space.
2083 However, each inferior may still have its own address
2084 space. */
2085 inf->aspace = maybe_new_address_space ();
2086 inf->pspace = current_program_space;
2087 }
2088 else
2089 {
2090 /* In the traditional debugging scenario, there's a 1-1 match
2091 between program/address spaces. We simply bind the inferior
2092 to the program space's address space. */
2093 inf = current_inferior ();
2094 inferior_appeared (inf, pid);
2095 }
2096
2097 inf->attach_flag = attached;
2098 inf->fake_pid_p = fake_pid_p;
2099
2100 /* If no main executable is currently open then attempt to
2101 open the file that was executed to create this inferior. */
2102 if (try_open_exec && get_exec_file (0) == NULL)
2103 exec_file_locate_attach (pid, 0, 1);
2104
2105 return inf;
2106 }
2107
2108 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2109
2110 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2111 according to RUNNING. */
2112
2113 static void
2114 remote_add_thread (ptid_t ptid, int running, int executing)
2115 {
2116 struct remote_state *rs = get_remote_state ();
2117 struct thread_info *thread;
2118
2119 /* GDB historically didn't pull threads in the initial connection
2120 setup. If the remote target doesn't even have a concept of
2121 threads (e.g., a bare-metal target), even if internally we
2122 consider that a single-threaded target, mentioning a new thread
2123 might be confusing to the user. Be silent then, preserving the
2124 age old behavior. */
2125 if (rs->starting_up)
2126 thread = add_thread_silent (ptid);
2127 else
2128 thread = add_thread (ptid);
2129
2130 get_remote_thread_info (thread)->vcont_resumed = executing;
2131 set_executing (ptid, executing);
2132 set_running (ptid, running);
2133 }
2134
2135 /* Come here when we learn about a thread id from the remote target.
2136 It may be the first time we hear about such thread, so take the
2137 opportunity to add it to GDB's thread list. In case this is the
2138 first time we're noticing its corresponding inferior, add it to
2139 GDB's inferior list as well. EXECUTING indicates whether the
2140 thread is (internally) executing or stopped. */
2141
2142 static void
2143 remote_notice_new_inferior (ptid_t currthread, int executing)
2144 {
2145 /* In non-stop mode, we assume new found threads are (externally)
2146 running until proven otherwise with a stop reply. In all-stop,
2147 we can only get here if all threads are stopped. */
2148 int running = target_is_non_stop_p () ? 1 : 0;
2149
2150 /* If this is a new thread, add it to GDB's thread list.
2151 If we leave it up to WFI to do this, bad things will happen. */
2152
2153 if (in_thread_list (currthread) && is_exited (currthread))
2154 {
2155 /* We're seeing an event on a thread id we knew had exited.
2156 This has to be a new thread reusing the old id. Add it. */
2157 remote_add_thread (currthread, running, executing);
2158 return;
2159 }
2160
2161 if (!in_thread_list (currthread))
2162 {
2163 struct inferior *inf = NULL;
2164 int pid = ptid_get_pid (currthread);
2165
2166 if (ptid_is_pid (inferior_ptid)
2167 && pid == ptid_get_pid (inferior_ptid))
2168 {
2169 /* inferior_ptid has no thread member yet. This can happen
2170 with the vAttach -> remote_wait,"TAAthread:" path if the
2171 stub doesn't support qC. This is the first stop reported
2172 after an attach, so this is the main thread. Update the
2173 ptid in the thread list. */
2174 if (in_thread_list (pid_to_ptid (pid)))
2175 thread_change_ptid (inferior_ptid, currthread);
2176 else
2177 {
2178 remote_add_thread (currthread, running, executing);
2179 inferior_ptid = currthread;
2180 }
2181 return;
2182 }
2183
2184 if (ptid_equal (magic_null_ptid, inferior_ptid))
2185 {
2186 /* inferior_ptid is not set yet. This can happen with the
2187 vRun -> remote_wait,"TAAthread:" path if the stub
2188 doesn't support qC. This is the first stop reported
2189 after an attach, so this is the main thread. Update the
2190 ptid in the thread list. */
2191 thread_change_ptid (inferior_ptid, currthread);
2192 return;
2193 }
2194
2195 /* When connecting to a target remote, or to a target
2196 extended-remote which already was debugging an inferior, we
2197 may not know about it yet. Add it before adding its child
2198 thread, so notifications are emitted in a sensible order. */
2199 if (!in_inferior_list (ptid_get_pid (currthread)))
2200 {
2201 struct remote_state *rs = get_remote_state ();
2202 int fake_pid_p = !remote_multi_process_p (rs);
2203
2204 inf = remote_add_inferior (fake_pid_p,
2205 ptid_get_pid (currthread), -1, 1);
2206 }
2207
2208 /* This is really a new thread. Add it. */
2209 remote_add_thread (currthread, running, executing);
2210
2211 /* If we found a new inferior, let the common code do whatever
2212 it needs to with it (e.g., read shared libraries, insert
2213 breakpoints), unless we're just setting up an all-stop
2214 connection. */
2215 if (inf != NULL)
2216 {
2217 struct remote_state *rs = get_remote_state ();
2218
2219 if (!rs->starting_up)
2220 notice_new_inferior (currthread, executing, 0);
2221 }
2222 }
2223 }
2224
2225 /* Return THREAD's private thread data, creating it if necessary. */
2226
2227 static remote_thread_info *
2228 get_remote_thread_info (thread_info *thread)
2229 {
2230 gdb_assert (thread != NULL);
2231
2232 if (thread->priv == NULL)
2233 thread->priv.reset (new remote_thread_info);
2234
2235 return static_cast<remote_thread_info *> (thread->priv.get ());
2236 }
2237
2238 /* Return PTID's private thread data, creating it if necessary. */
2239
2240 static remote_thread_info *
2241 get_remote_thread_info (ptid_t ptid)
2242 {
2243 struct thread_info *info = find_thread_ptid (ptid);
2244
2245 return get_remote_thread_info (info);
2246 }
2247
2248 /* Call this function as a result of
2249 1) A halt indication (T packet) containing a thread id
2250 2) A direct query of currthread
2251 3) Successful execution of set thread */
2252
2253 static void
2254 record_currthread (struct remote_state *rs, ptid_t currthread)
2255 {
2256 rs->general_thread = currthread;
2257 }
2258
2259 /* If 'QPassSignals' is supported, tell the remote stub what signals
2260 it can simply pass through to the inferior without reporting. */
2261
2262 void
2263 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2264 {
2265 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2266 {
2267 char *pass_packet, *p;
2268 int count = 0, i;
2269 struct remote_state *rs = get_remote_state ();
2270
2271 gdb_assert (numsigs < 256);
2272 for (i = 0; i < numsigs; i++)
2273 {
2274 if (pass_signals[i])
2275 count++;
2276 }
2277 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2278 strcpy (pass_packet, "QPassSignals:");
2279 p = pass_packet + strlen (pass_packet);
2280 for (i = 0; i < numsigs; i++)
2281 {
2282 if (pass_signals[i])
2283 {
2284 if (i >= 16)
2285 *p++ = tohex (i >> 4);
2286 *p++ = tohex (i & 15);
2287 if (count)
2288 *p++ = ';';
2289 else
2290 break;
2291 count--;
2292 }
2293 }
2294 *p = 0;
2295 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2296 {
2297 putpkt (pass_packet);
2298 getpkt (&rs->buf, &rs->buf_size, 0);
2299 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2300 if (rs->last_pass_packet)
2301 xfree (rs->last_pass_packet);
2302 rs->last_pass_packet = pass_packet;
2303 }
2304 else
2305 xfree (pass_packet);
2306 }
2307 }
2308
2309 /* If 'QCatchSyscalls' is supported, tell the remote stub
2310 to report syscalls to GDB. */
2311
2312 int
2313 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2314 gdb::array_view<const int> syscall_counts)
2315 {
2316 const char *catch_packet;
2317 enum packet_result result;
2318 int n_sysno = 0;
2319
2320 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2321 {
2322 /* Not supported. */
2323 return 1;
2324 }
2325
2326 if (needed && any_count == 0)
2327 {
2328 /* Count how many syscalls are to be caught. */
2329 for (size_t i = 0; i < syscall_counts.size (); i++)
2330 {
2331 if (syscall_counts[i] != 0)
2332 n_sysno++;
2333 }
2334 }
2335
2336 if (remote_debug)
2337 {
2338 fprintf_unfiltered (gdb_stdlog,
2339 "remote_set_syscall_catchpoint "
2340 "pid %d needed %d any_count %d n_sysno %d\n",
2341 pid, needed, any_count, n_sysno);
2342 }
2343
2344 std::string built_packet;
2345 if (needed)
2346 {
2347 /* Prepare a packet with the sysno list, assuming max 8+1
2348 characters for a sysno. If the resulting packet size is too
2349 big, fallback on the non-selective packet. */
2350 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2351 built_packet.reserve (maxpktsz);
2352 built_packet = "QCatchSyscalls:1";
2353 if (any_count == 0)
2354 {
2355 /* Add in each syscall to be caught. */
2356 for (size_t i = 0; i < syscall_counts.size (); i++)
2357 {
2358 if (syscall_counts[i] != 0)
2359 string_appendf (built_packet, ";%zx", i);
2360 }
2361 }
2362 if (built_packet.size () > get_remote_packet_size ())
2363 {
2364 /* catch_packet too big. Fallback to less efficient
2365 non selective mode, with GDB doing the filtering. */
2366 catch_packet = "QCatchSyscalls:1";
2367 }
2368 else
2369 catch_packet = built_packet.c_str ();
2370 }
2371 else
2372 catch_packet = "QCatchSyscalls:0";
2373
2374 struct remote_state *rs = get_remote_state ();
2375
2376 putpkt (catch_packet);
2377 getpkt (&rs->buf, &rs->buf_size, 0);
2378 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2379 if (result == PACKET_OK)
2380 return 0;
2381 else
2382 return -1;
2383 }
2384
2385 /* If 'QProgramSignals' is supported, tell the remote stub what
2386 signals it should pass through to the inferior when detaching. */
2387
2388 void
2389 remote_target::program_signals (int numsigs, unsigned char *signals)
2390 {
2391 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2392 {
2393 char *packet, *p;
2394 int count = 0, i;
2395 struct remote_state *rs = get_remote_state ();
2396
2397 gdb_assert (numsigs < 256);
2398 for (i = 0; i < numsigs; i++)
2399 {
2400 if (signals[i])
2401 count++;
2402 }
2403 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2404 strcpy (packet, "QProgramSignals:");
2405 p = packet + strlen (packet);
2406 for (i = 0; i < numsigs; i++)
2407 {
2408 if (signal_pass_state (i))
2409 {
2410 if (i >= 16)
2411 *p++ = tohex (i >> 4);
2412 *p++ = tohex (i & 15);
2413 if (count)
2414 *p++ = ';';
2415 else
2416 break;
2417 count--;
2418 }
2419 }
2420 *p = 0;
2421 if (!rs->last_program_signals_packet
2422 || strcmp (rs->last_program_signals_packet, packet) != 0)
2423 {
2424 putpkt (packet);
2425 getpkt (&rs->buf, &rs->buf_size, 0);
2426 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2427 xfree (rs->last_program_signals_packet);
2428 rs->last_program_signals_packet = packet;
2429 }
2430 else
2431 xfree (packet);
2432 }
2433 }
2434
2435 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2436 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2437 thread. If GEN is set, set the general thread, if not, then set
2438 the step/continue thread. */
2439 static void
2440 set_thread (ptid_t ptid, int gen)
2441 {
2442 struct remote_state *rs = get_remote_state ();
2443 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2444 char *buf = rs->buf;
2445 char *endbuf = rs->buf + get_remote_packet_size ();
2446
2447 if (ptid_equal (state, ptid))
2448 return;
2449
2450 *buf++ = 'H';
2451 *buf++ = gen ? 'g' : 'c';
2452 if (ptid_equal (ptid, magic_null_ptid))
2453 xsnprintf (buf, endbuf - buf, "0");
2454 else if (ptid_equal (ptid, any_thread_ptid))
2455 xsnprintf (buf, endbuf - buf, "0");
2456 else if (ptid_equal (ptid, minus_one_ptid))
2457 xsnprintf (buf, endbuf - buf, "-1");
2458 else
2459 write_ptid (buf, endbuf, ptid);
2460 putpkt (rs->buf);
2461 getpkt (&rs->buf, &rs->buf_size, 0);
2462 if (gen)
2463 rs->general_thread = ptid;
2464 else
2465 rs->continue_thread = ptid;
2466 }
2467
2468 static void
2469 set_general_thread (ptid_t ptid)
2470 {
2471 set_thread (ptid, 1);
2472 }
2473
2474 static void
2475 set_continue_thread (ptid_t ptid)
2476 {
2477 set_thread (ptid, 0);
2478 }
2479
2480 /* Change the remote current process. Which thread within the process
2481 ends up selected isn't important, as long as it is the same process
2482 as what INFERIOR_PTID points to.
2483
2484 This comes from that fact that there is no explicit notion of
2485 "selected process" in the protocol. The selected process for
2486 general operations is the process the selected general thread
2487 belongs to. */
2488
2489 static void
2490 set_general_process (void)
2491 {
2492 struct remote_state *rs = get_remote_state ();
2493
2494 /* If the remote can't handle multiple processes, don't bother. */
2495 if (!remote_multi_process_p (rs))
2496 return;
2497
2498 /* We only need to change the remote current thread if it's pointing
2499 at some other process. */
2500 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2501 set_general_thread (inferior_ptid);
2502 }
2503
2504 \f
2505 /* Return nonzero if this is the main thread that we made up ourselves
2506 to model non-threaded targets as single-threaded. */
2507
2508 static int
2509 remote_thread_always_alive (ptid_t ptid)
2510 {
2511 if (ptid_equal (ptid, magic_null_ptid))
2512 /* The main thread is always alive. */
2513 return 1;
2514
2515 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2516 /* The main thread is always alive. This can happen after a
2517 vAttach, if the remote side doesn't support
2518 multi-threading. */
2519 return 1;
2520
2521 return 0;
2522 }
2523
2524 /* Return nonzero if the thread PTID is still alive on the remote
2525 system. */
2526
2527 bool
2528 remote_target::thread_alive (ptid_t ptid)
2529 {
2530 struct remote_state *rs = get_remote_state ();
2531 char *p, *endp;
2532
2533 /* Check if this is a thread that we made up ourselves to model
2534 non-threaded targets as single-threaded. */
2535 if (remote_thread_always_alive (ptid))
2536 return 1;
2537
2538 p = rs->buf;
2539 endp = rs->buf + get_remote_packet_size ();
2540
2541 *p++ = 'T';
2542 write_ptid (p, endp, ptid);
2543
2544 putpkt (rs->buf);
2545 getpkt (&rs->buf, &rs->buf_size, 0);
2546 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2547 }
2548
2549 /* Return a pointer to a thread name if we know it and NULL otherwise.
2550 The thread_info object owns the memory for the name. */
2551
2552 const char *
2553 remote_target::thread_name (struct thread_info *info)
2554 {
2555 if (info->priv != NULL)
2556 {
2557 const std::string &name = get_remote_thread_info (info)->name;
2558 return !name.empty () ? name.c_str () : NULL;
2559 }
2560
2561 return NULL;
2562 }
2563
2564 /* About these extended threadlist and threadinfo packets. They are
2565 variable length packets but, the fields within them are often fixed
2566 length. They are redundent enough to send over UDP as is the
2567 remote protocol in general. There is a matching unit test module
2568 in libstub. */
2569
2570 /* WARNING: This threadref data structure comes from the remote O.S.,
2571 libstub protocol encoding, and remote.c. It is not particularly
2572 changable. */
2573
2574 /* Right now, the internal structure is int. We want it to be bigger.
2575 Plan to fix this. */
2576
2577 typedef int gdb_threadref; /* Internal GDB thread reference. */
2578
2579 /* gdb_ext_thread_info is an internal GDB data structure which is
2580 equivalent to the reply of the remote threadinfo packet. */
2581
2582 struct gdb_ext_thread_info
2583 {
2584 threadref threadid; /* External form of thread reference. */
2585 int active; /* Has state interesting to GDB?
2586 regs, stack. */
2587 char display[256]; /* Brief state display, name,
2588 blocked/suspended. */
2589 char shortname[32]; /* To be used to name threads. */
2590 char more_display[256]; /* Long info, statistics, queue depth,
2591 whatever. */
2592 };
2593
2594 /* The volume of remote transfers can be limited by submitting
2595 a mask containing bits specifying the desired information.
2596 Use a union of these values as the 'selection' parameter to
2597 get_thread_info. FIXME: Make these TAG names more thread specific. */
2598
2599 #define TAG_THREADID 1
2600 #define TAG_EXISTS 2
2601 #define TAG_DISPLAY 4
2602 #define TAG_THREADNAME 8
2603 #define TAG_MOREDISPLAY 16
2604
2605 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2606
2607 static char *unpack_nibble (char *buf, int *val);
2608
2609 static char *unpack_byte (char *buf, int *value);
2610
2611 static char *pack_int (char *buf, int value);
2612
2613 static char *unpack_int (char *buf, int *value);
2614
2615 static char *unpack_string (char *src, char *dest, int length);
2616
2617 static char *pack_threadid (char *pkt, threadref *id);
2618
2619 static char *unpack_threadid (char *inbuf, threadref *id);
2620
2621 void int_to_threadref (threadref *id, int value);
2622
2623 static int threadref_to_int (threadref *ref);
2624
2625 static void copy_threadref (threadref *dest, threadref *src);
2626
2627 static int threadmatch (threadref *dest, threadref *src);
2628
2629 static char *pack_threadinfo_request (char *pkt, int mode,
2630 threadref *id);
2631
2632 static int remote_unpack_thread_info_response (char *pkt,
2633 threadref *expectedref,
2634 struct gdb_ext_thread_info
2635 *info);
2636
2637
2638 static int remote_get_threadinfo (threadref *threadid,
2639 int fieldset, /*TAG mask */
2640 struct gdb_ext_thread_info *info);
2641
2642 static char *pack_threadlist_request (char *pkt, int startflag,
2643 int threadcount,
2644 threadref *nextthread);
2645
2646 static int parse_threadlist_response (char *pkt,
2647 int result_limit,
2648 threadref *original_echo,
2649 threadref *resultlist,
2650 int *doneflag);
2651
2652 static int remote_get_threadlist (int startflag,
2653 threadref *nextthread,
2654 int result_limit,
2655 int *done,
2656 int *result_count,
2657 threadref *threadlist);
2658
2659 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2660
2661 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2662 void *context, int looplimit);
2663
2664 static int remote_newthread_step (threadref *ref, void *context);
2665
2666
2667 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2668 buffer we're allowed to write to. Returns
2669 BUF+CHARACTERS_WRITTEN. */
2670
2671 static char *
2672 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2673 {
2674 int pid, tid;
2675 struct remote_state *rs = get_remote_state ();
2676
2677 if (remote_multi_process_p (rs))
2678 {
2679 pid = ptid_get_pid (ptid);
2680 if (pid < 0)
2681 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2682 else
2683 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2684 }
2685 tid = ptid_get_lwp (ptid);
2686 if (tid < 0)
2687 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2688 else
2689 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2690
2691 return buf;
2692 }
2693
2694 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2695 last parsed char. Returns null_ptid if no thread id is found, and
2696 throws an error if the thread id has an invalid format. */
2697
2698 static ptid_t
2699 read_ptid (const char *buf, const char **obuf)
2700 {
2701 const char *p = buf;
2702 const char *pp;
2703 ULONGEST pid = 0, tid = 0;
2704
2705 if (*p == 'p')
2706 {
2707 /* Multi-process ptid. */
2708 pp = unpack_varlen_hex (p + 1, &pid);
2709 if (*pp != '.')
2710 error (_("invalid remote ptid: %s"), p);
2711
2712 p = pp;
2713 pp = unpack_varlen_hex (p + 1, &tid);
2714 if (obuf)
2715 *obuf = pp;
2716 return ptid_build (pid, tid, 0);
2717 }
2718
2719 /* No multi-process. Just a tid. */
2720 pp = unpack_varlen_hex (p, &tid);
2721
2722 /* Return null_ptid when no thread id is found. */
2723 if (p == pp)
2724 {
2725 if (obuf)
2726 *obuf = pp;
2727 return null_ptid;
2728 }
2729
2730 /* Since the stub is not sending a process id, then default to
2731 what's in inferior_ptid, unless it's null at this point. If so,
2732 then since there's no way to know the pid of the reported
2733 threads, use the magic number. */
2734 if (ptid_equal (inferior_ptid, null_ptid))
2735 pid = ptid_get_pid (magic_null_ptid);
2736 else
2737 pid = ptid_get_pid (inferior_ptid);
2738
2739 if (obuf)
2740 *obuf = pp;
2741 return ptid_build (pid, tid, 0);
2742 }
2743
2744 static int
2745 stubhex (int ch)
2746 {
2747 if (ch >= 'a' && ch <= 'f')
2748 return ch - 'a' + 10;
2749 if (ch >= '0' && ch <= '9')
2750 return ch - '0';
2751 if (ch >= 'A' && ch <= 'F')
2752 return ch - 'A' + 10;
2753 return -1;
2754 }
2755
2756 static int
2757 stub_unpack_int (char *buff, int fieldlength)
2758 {
2759 int nibble;
2760 int retval = 0;
2761
2762 while (fieldlength)
2763 {
2764 nibble = stubhex (*buff++);
2765 retval |= nibble;
2766 fieldlength--;
2767 if (fieldlength)
2768 retval = retval << 4;
2769 }
2770 return retval;
2771 }
2772
2773 static char *
2774 unpack_nibble (char *buf, int *val)
2775 {
2776 *val = fromhex (*buf++);
2777 return buf;
2778 }
2779
2780 static char *
2781 unpack_byte (char *buf, int *value)
2782 {
2783 *value = stub_unpack_int (buf, 2);
2784 return buf + 2;
2785 }
2786
2787 static char *
2788 pack_int (char *buf, int value)
2789 {
2790 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2791 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2792 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2793 buf = pack_hex_byte (buf, (value & 0xff));
2794 return buf;
2795 }
2796
2797 static char *
2798 unpack_int (char *buf, int *value)
2799 {
2800 *value = stub_unpack_int (buf, 8);
2801 return buf + 8;
2802 }
2803
2804 #if 0 /* Currently unused, uncomment when needed. */
2805 static char *pack_string (char *pkt, char *string);
2806
2807 static char *
2808 pack_string (char *pkt, char *string)
2809 {
2810 char ch;
2811 int len;
2812
2813 len = strlen (string);
2814 if (len > 200)
2815 len = 200; /* Bigger than most GDB packets, junk??? */
2816 pkt = pack_hex_byte (pkt, len);
2817 while (len-- > 0)
2818 {
2819 ch = *string++;
2820 if ((ch == '\0') || (ch == '#'))
2821 ch = '*'; /* Protect encapsulation. */
2822 *pkt++ = ch;
2823 }
2824 return pkt;
2825 }
2826 #endif /* 0 (unused) */
2827
2828 static char *
2829 unpack_string (char *src, char *dest, int length)
2830 {
2831 while (length--)
2832 *dest++ = *src++;
2833 *dest = '\0';
2834 return src;
2835 }
2836
2837 static char *
2838 pack_threadid (char *pkt, threadref *id)
2839 {
2840 char *limit;
2841 unsigned char *altid;
2842
2843 altid = (unsigned char *) id;
2844 limit = pkt + BUF_THREAD_ID_SIZE;
2845 while (pkt < limit)
2846 pkt = pack_hex_byte (pkt, *altid++);
2847 return pkt;
2848 }
2849
2850
2851 static char *
2852 unpack_threadid (char *inbuf, threadref *id)
2853 {
2854 char *altref;
2855 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2856 int x, y;
2857
2858 altref = (char *) id;
2859
2860 while (inbuf < limit)
2861 {
2862 x = stubhex (*inbuf++);
2863 y = stubhex (*inbuf++);
2864 *altref++ = (x << 4) | y;
2865 }
2866 return inbuf;
2867 }
2868
2869 /* Externally, threadrefs are 64 bits but internally, they are still
2870 ints. This is due to a mismatch of specifications. We would like
2871 to use 64bit thread references internally. This is an adapter
2872 function. */
2873
2874 void
2875 int_to_threadref (threadref *id, int value)
2876 {
2877 unsigned char *scan;
2878
2879 scan = (unsigned char *) id;
2880 {
2881 int i = 4;
2882 while (i--)
2883 *scan++ = 0;
2884 }
2885 *scan++ = (value >> 24) & 0xff;
2886 *scan++ = (value >> 16) & 0xff;
2887 *scan++ = (value >> 8) & 0xff;
2888 *scan++ = (value & 0xff);
2889 }
2890
2891 static int
2892 threadref_to_int (threadref *ref)
2893 {
2894 int i, value = 0;
2895 unsigned char *scan;
2896
2897 scan = *ref;
2898 scan += 4;
2899 i = 4;
2900 while (i-- > 0)
2901 value = (value << 8) | ((*scan++) & 0xff);
2902 return value;
2903 }
2904
2905 static void
2906 copy_threadref (threadref *dest, threadref *src)
2907 {
2908 int i;
2909 unsigned char *csrc, *cdest;
2910
2911 csrc = (unsigned char *) src;
2912 cdest = (unsigned char *) dest;
2913 i = 8;
2914 while (i--)
2915 *cdest++ = *csrc++;
2916 }
2917
2918 static int
2919 threadmatch (threadref *dest, threadref *src)
2920 {
2921 /* Things are broken right now, so just assume we got a match. */
2922 #if 0
2923 unsigned char *srcp, *destp;
2924 int i, result;
2925 srcp = (char *) src;
2926 destp = (char *) dest;
2927
2928 result = 1;
2929 while (i-- > 0)
2930 result &= (*srcp++ == *destp++) ? 1 : 0;
2931 return result;
2932 #endif
2933 return 1;
2934 }
2935
2936 /*
2937 threadid:1, # always request threadid
2938 context_exists:2,
2939 display:4,
2940 unique_name:8,
2941 more_display:16
2942 */
2943
2944 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2945
2946 static char *
2947 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2948 {
2949 *pkt++ = 'q'; /* Info Query */
2950 *pkt++ = 'P'; /* process or thread info */
2951 pkt = pack_int (pkt, mode); /* mode */
2952 pkt = pack_threadid (pkt, id); /* threadid */
2953 *pkt = '\0'; /* terminate */
2954 return pkt;
2955 }
2956
2957 /* These values tag the fields in a thread info response packet. */
2958 /* Tagging the fields allows us to request specific fields and to
2959 add more fields as time goes by. */
2960
2961 #define TAG_THREADID 1 /* Echo the thread identifier. */
2962 #define TAG_EXISTS 2 /* Is this process defined enough to
2963 fetch registers and its stack? */
2964 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2965 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2966 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2967 the process. */
2968
2969 static int
2970 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2971 struct gdb_ext_thread_info *info)
2972 {
2973 struct remote_state *rs = get_remote_state ();
2974 int mask, length;
2975 int tag;
2976 threadref ref;
2977 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2978 int retval = 1;
2979
2980 /* info->threadid = 0; FIXME: implement zero_threadref. */
2981 info->active = 0;
2982 info->display[0] = '\0';
2983 info->shortname[0] = '\0';
2984 info->more_display[0] = '\0';
2985
2986 /* Assume the characters indicating the packet type have been
2987 stripped. */
2988 pkt = unpack_int (pkt, &mask); /* arg mask */
2989 pkt = unpack_threadid (pkt, &ref);
2990
2991 if (mask == 0)
2992 warning (_("Incomplete response to threadinfo request."));
2993 if (!threadmatch (&ref, expectedref))
2994 { /* This is an answer to a different request. */
2995 warning (_("ERROR RMT Thread info mismatch."));
2996 return 0;
2997 }
2998 copy_threadref (&info->threadid, &ref);
2999
3000 /* Loop on tagged fields , try to bail if somthing goes wrong. */
3001
3002 /* Packets are terminated with nulls. */
3003 while ((pkt < limit) && mask && *pkt)
3004 {
3005 pkt = unpack_int (pkt, &tag); /* tag */
3006 pkt = unpack_byte (pkt, &length); /* length */
3007 if (!(tag & mask)) /* Tags out of synch with mask. */
3008 {
3009 warning (_("ERROR RMT: threadinfo tag mismatch."));
3010 retval = 0;
3011 break;
3012 }
3013 if (tag == TAG_THREADID)
3014 {
3015 if (length != 16)
3016 {
3017 warning (_("ERROR RMT: length of threadid is not 16."));
3018 retval = 0;
3019 break;
3020 }
3021 pkt = unpack_threadid (pkt, &ref);
3022 mask = mask & ~TAG_THREADID;
3023 continue;
3024 }
3025 if (tag == TAG_EXISTS)
3026 {
3027 info->active = stub_unpack_int (pkt, length);
3028 pkt += length;
3029 mask = mask & ~(TAG_EXISTS);
3030 if (length > 8)
3031 {
3032 warning (_("ERROR RMT: 'exists' length too long."));
3033 retval = 0;
3034 break;
3035 }
3036 continue;
3037 }
3038 if (tag == TAG_THREADNAME)
3039 {
3040 pkt = unpack_string (pkt, &info->shortname[0], length);
3041 mask = mask & ~TAG_THREADNAME;
3042 continue;
3043 }
3044 if (tag == TAG_DISPLAY)
3045 {
3046 pkt = unpack_string (pkt, &info->display[0], length);
3047 mask = mask & ~TAG_DISPLAY;
3048 continue;
3049 }
3050 if (tag == TAG_MOREDISPLAY)
3051 {
3052 pkt = unpack_string (pkt, &info->more_display[0], length);
3053 mask = mask & ~TAG_MOREDISPLAY;
3054 continue;
3055 }
3056 warning (_("ERROR RMT: unknown thread info tag."));
3057 break; /* Not a tag we know about. */
3058 }
3059 return retval;
3060 }
3061
3062 static int
3063 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
3064 struct gdb_ext_thread_info *info)
3065 {
3066 struct remote_state *rs = get_remote_state ();
3067 int result;
3068
3069 pack_threadinfo_request (rs->buf, fieldset, threadid);
3070 putpkt (rs->buf);
3071 getpkt (&rs->buf, &rs->buf_size, 0);
3072
3073 if (rs->buf[0] == '\0')
3074 return 0;
3075
3076 result = remote_unpack_thread_info_response (rs->buf + 2,
3077 threadid, info);
3078 return result;
3079 }
3080
3081 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3082
3083 static char *
3084 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3085 threadref *nextthread)
3086 {
3087 *pkt++ = 'q'; /* info query packet */
3088 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3089 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3090 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3091 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3092 *pkt = '\0';
3093 return pkt;
3094 }
3095
3096 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3097
3098 static int
3099 parse_threadlist_response (char *pkt, int result_limit,
3100 threadref *original_echo, threadref *resultlist,
3101 int *doneflag)
3102 {
3103 struct remote_state *rs = get_remote_state ();
3104 char *limit;
3105 int count, resultcount, done;
3106
3107 resultcount = 0;
3108 /* Assume the 'q' and 'M chars have been stripped. */
3109 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3110 /* done parse past here */
3111 pkt = unpack_byte (pkt, &count); /* count field */
3112 pkt = unpack_nibble (pkt, &done);
3113 /* The first threadid is the argument threadid. */
3114 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3115 while ((count-- > 0) && (pkt < limit))
3116 {
3117 pkt = unpack_threadid (pkt, resultlist++);
3118 if (resultcount++ >= result_limit)
3119 break;
3120 }
3121 if (doneflag)
3122 *doneflag = done;
3123 return resultcount;
3124 }
3125
3126 /* Fetch the next batch of threads from the remote. Returns -1 if the
3127 qL packet is not supported, 0 on error and 1 on success. */
3128
3129 static int
3130 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
3131 int *done, int *result_count, threadref *threadlist)
3132 {
3133 struct remote_state *rs = get_remote_state ();
3134 int result = 1;
3135
3136 /* Trancate result limit to be smaller than the packet size. */
3137 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3138 >= get_remote_packet_size ())
3139 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3140
3141 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3142 putpkt (rs->buf);
3143 getpkt (&rs->buf, &rs->buf_size, 0);
3144 if (*rs->buf == '\0')
3145 {
3146 /* Packet not supported. */
3147 return -1;
3148 }
3149
3150 *result_count =
3151 parse_threadlist_response (rs->buf + 2, result_limit,
3152 &rs->echo_nextthread, threadlist, done);
3153
3154 if (!threadmatch (&rs->echo_nextthread, nextthread))
3155 {
3156 /* FIXME: This is a good reason to drop the packet. */
3157 /* Possably, there is a duplicate response. */
3158 /* Possabilities :
3159 retransmit immediatly - race conditions
3160 retransmit after timeout - yes
3161 exit
3162 wait for packet, then exit
3163 */
3164 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3165 return 0; /* I choose simply exiting. */
3166 }
3167 if (*result_count <= 0)
3168 {
3169 if (*done != 1)
3170 {
3171 warning (_("RMT ERROR : failed to get remote thread list."));
3172 result = 0;
3173 }
3174 return result; /* break; */
3175 }
3176 if (*result_count > result_limit)
3177 {
3178 *result_count = 0;
3179 warning (_("RMT ERROR: threadlist response longer than requested."));
3180 return 0;
3181 }
3182 return result;
3183 }
3184
3185 /* Fetch the list of remote threads, with the qL packet, and call
3186 STEPFUNCTION for each thread found. Stops iterating and returns 1
3187 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3188 STEPFUNCTION returns false. If the packet is not supported,
3189 returns -1. */
3190
3191 static int
3192 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
3193 int looplimit)
3194 {
3195 struct remote_state *rs = get_remote_state ();
3196 int done, i, result_count;
3197 int startflag = 1;
3198 int result = 1;
3199 int loopcount = 0;
3200
3201 done = 0;
3202 while (!done)
3203 {
3204 if (loopcount++ > looplimit)
3205 {
3206 result = 0;
3207 warning (_("Remote fetch threadlist -infinite loop-."));
3208 break;
3209 }
3210 result = remote_get_threadlist (startflag, &rs->nextthread,
3211 MAXTHREADLISTRESULTS,
3212 &done, &result_count,
3213 rs->resultthreadlist);
3214 if (result <= 0)
3215 break;
3216 /* Clear for later iterations. */
3217 startflag = 0;
3218 /* Setup to resume next batch of thread references, set nextthread. */
3219 if (result_count >= 1)
3220 copy_threadref (&rs->nextthread,
3221 &rs->resultthreadlist[result_count - 1]);
3222 i = 0;
3223 while (result_count--)
3224 {
3225 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3226 {
3227 result = 0;
3228 break;
3229 }
3230 }
3231 }
3232 return result;
3233 }
3234
3235 /* A thread found on the remote target. */
3236
3237 struct thread_item
3238 {
3239 explicit thread_item (ptid_t ptid_)
3240 : ptid (ptid_)
3241 {}
3242
3243 thread_item (thread_item &&other) = default;
3244 thread_item &operator= (thread_item &&other) = default;
3245
3246 DISABLE_COPY_AND_ASSIGN (thread_item);
3247
3248 /* The thread's PTID. */
3249 ptid_t ptid;
3250
3251 /* The thread's extra info. */
3252 std::string extra;
3253
3254 /* The thread's name. */
3255 std::string name;
3256
3257 /* The core the thread was running on. -1 if not known. */
3258 int core = -1;
3259
3260 /* The thread handle associated with the thread. */
3261 gdb::byte_vector thread_handle;
3262 };
3263
3264 /* Context passed around to the various methods listing remote
3265 threads. As new threads are found, they're added to the ITEMS
3266 vector. */
3267
3268 struct threads_listing_context
3269 {
3270 /* Return true if this object contains an entry for a thread with ptid
3271 PTID. */
3272
3273 bool contains_thread (ptid_t ptid) const
3274 {
3275 auto match_ptid = [&] (const thread_item &item)
3276 {
3277 return item.ptid == ptid;
3278 };
3279
3280 auto it = std::find_if (this->items.begin (),
3281 this->items.end (),
3282 match_ptid);
3283
3284 return it != this->items.end ();
3285 }
3286
3287 /* Remove the thread with ptid PTID. */
3288
3289 void remove_thread (ptid_t ptid)
3290 {
3291 auto match_ptid = [&] (const thread_item &item)
3292 {
3293 return item.ptid == ptid;
3294 };
3295
3296 auto it = std::remove_if (this->items.begin (),
3297 this->items.end (),
3298 match_ptid);
3299
3300 if (it != this->items.end ())
3301 this->items.erase (it);
3302 }
3303
3304 /* The threads found on the remote target. */
3305 std::vector<thread_item> items;
3306 };
3307
3308 static int
3309 remote_newthread_step (threadref *ref, void *data)
3310 {
3311 struct threads_listing_context *context
3312 = (struct threads_listing_context *) data;
3313 int pid = inferior_ptid.pid ();
3314 int lwp = threadref_to_int (ref);
3315 ptid_t ptid (pid, lwp);
3316
3317 context->items.emplace_back (ptid);
3318
3319 return 1; /* continue iterator */
3320 }
3321
3322 #define CRAZY_MAX_THREADS 1000
3323
3324 static ptid_t
3325 remote_current_thread (ptid_t oldpid)
3326 {
3327 struct remote_state *rs = get_remote_state ();
3328
3329 putpkt ("qC");
3330 getpkt (&rs->buf, &rs->buf_size, 0);
3331 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3332 {
3333 const char *obuf;
3334 ptid_t result;
3335
3336 result = read_ptid (&rs->buf[2], &obuf);
3337 if (*obuf != '\0' && remote_debug)
3338 fprintf_unfiltered (gdb_stdlog,
3339 "warning: garbage in qC reply\n");
3340
3341 return result;
3342 }
3343 else
3344 return oldpid;
3345 }
3346
3347 /* List remote threads using the deprecated qL packet. */
3348
3349 static int
3350 remote_get_threads_with_ql (struct target_ops *ops,
3351 struct threads_listing_context *context)
3352 {
3353 if (remote_threadlist_iterator (remote_newthread_step, context,
3354 CRAZY_MAX_THREADS) >= 0)
3355 return 1;
3356
3357 return 0;
3358 }
3359
3360 #if defined(HAVE_LIBEXPAT)
3361
3362 static void
3363 start_thread (struct gdb_xml_parser *parser,
3364 const struct gdb_xml_element *element,
3365 void *user_data,
3366 std::vector<gdb_xml_value> &attributes)
3367 {
3368 struct threads_listing_context *data
3369 = (struct threads_listing_context *) user_data;
3370 struct gdb_xml_value *attr;
3371
3372 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3373 ptid_t ptid = read_ptid (id, NULL);
3374
3375 data->items.emplace_back (ptid);
3376 thread_item &item = data->items.back ();
3377
3378 attr = xml_find_attribute (attributes, "core");
3379 if (attr != NULL)
3380 item.core = *(ULONGEST *) attr->value.get ();
3381
3382 attr = xml_find_attribute (attributes, "name");
3383 if (attr != NULL)
3384 item.name = (const char *) attr->value.get ();
3385
3386 attr = xml_find_attribute (attributes, "handle");
3387 if (attr != NULL)
3388 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3389 }
3390
3391 static void
3392 end_thread (struct gdb_xml_parser *parser,
3393 const struct gdb_xml_element *element,
3394 void *user_data, const char *body_text)
3395 {
3396 struct threads_listing_context *data
3397 = (struct threads_listing_context *) user_data;
3398
3399 if (body_text != NULL && *body_text != '\0')
3400 data->items.back ().extra = body_text;
3401 }
3402
3403 const struct gdb_xml_attribute thread_attributes[] = {
3404 { "id", GDB_XML_AF_NONE, NULL, NULL },
3405 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3406 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3407 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3408 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3409 };
3410
3411 const struct gdb_xml_element thread_children[] = {
3412 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3413 };
3414
3415 const struct gdb_xml_element threads_children[] = {
3416 { "thread", thread_attributes, thread_children,
3417 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3418 start_thread, end_thread },
3419 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3420 };
3421
3422 const struct gdb_xml_element threads_elements[] = {
3423 { "threads", NULL, threads_children,
3424 GDB_XML_EF_NONE, NULL, NULL },
3425 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3426 };
3427
3428 #endif
3429
3430 /* List remote threads using qXfer:threads:read. */
3431
3432 static int
3433 remote_get_threads_with_qxfer (struct target_ops *ops,
3434 struct threads_listing_context *context)
3435 {
3436 #if defined(HAVE_LIBEXPAT)
3437 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3438 {
3439 gdb::optional<gdb::char_vector> xml
3440 = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3441
3442 if (xml && (*xml)[0] != '\0')
3443 {
3444 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3445 threads_elements, xml->data (), context);
3446 }
3447
3448 return 1;
3449 }
3450 #endif
3451
3452 return 0;
3453 }
3454
3455 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3456
3457 static int
3458 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3459 struct threads_listing_context *context)
3460 {
3461 struct remote_state *rs = get_remote_state ();
3462
3463 if (rs->use_threadinfo_query)
3464 {
3465 const char *bufp;
3466
3467 putpkt ("qfThreadInfo");
3468 getpkt (&rs->buf, &rs->buf_size, 0);
3469 bufp = rs->buf;
3470 if (bufp[0] != '\0') /* q packet recognized */
3471 {
3472 while (*bufp++ == 'm') /* reply contains one or more TID */
3473 {
3474 do
3475 {
3476 ptid_t ptid = read_ptid (bufp, &bufp);
3477 context->items.emplace_back (ptid);
3478 }
3479 while (*bufp++ == ','); /* comma-separated list */
3480 putpkt ("qsThreadInfo");
3481 getpkt (&rs->buf, &rs->buf_size, 0);
3482 bufp = rs->buf;
3483 }
3484 return 1;
3485 }
3486 else
3487 {
3488 /* Packet not recognized. */
3489 rs->use_threadinfo_query = 0;
3490 }
3491 }
3492
3493 return 0;
3494 }
3495
3496 /* Implement the to_update_thread_list function for the remote
3497 targets. */
3498
3499 void
3500 remote_target::update_thread_list ()
3501 {
3502 struct threads_listing_context context;
3503 int got_list = 0;
3504
3505 /* We have a few different mechanisms to fetch the thread list. Try
3506 them all, starting with the most preferred one first, falling
3507 back to older methods. */
3508 if (remote_get_threads_with_qxfer (this, &context)
3509 || remote_get_threads_with_qthreadinfo (this, &context)
3510 || remote_get_threads_with_ql (this, &context))
3511 {
3512 struct thread_info *tp, *tmp;
3513
3514 got_list = 1;
3515
3516 if (context.items.empty ()
3517 && remote_thread_always_alive (inferior_ptid))
3518 {
3519 /* Some targets don't really support threads, but still
3520 reply an (empty) thread list in response to the thread
3521 listing packets, instead of replying "packet not
3522 supported". Exit early so we don't delete the main
3523 thread. */
3524 return;
3525 }
3526
3527 /* CONTEXT now holds the current thread list on the remote
3528 target end. Delete GDB-side threads no longer found on the
3529 target. */
3530 ALL_THREADS_SAFE (tp, tmp)
3531 {
3532 if (!context.contains_thread (tp->ptid))
3533 {
3534 /* Not found. */
3535 delete_thread (tp->ptid);
3536 }
3537 }
3538
3539 /* Remove any unreported fork child threads from CONTEXT so
3540 that we don't interfere with follow fork, which is where
3541 creation of such threads is handled. */
3542 remove_new_fork_children (&context);
3543
3544 /* And now add threads we don't know about yet to our list. */
3545 for (thread_item &item : context.items)
3546 {
3547 if (item.ptid != null_ptid)
3548 {
3549 /* In non-stop mode, we assume new found threads are
3550 executing until proven otherwise with a stop reply.
3551 In all-stop, we can only get here if all threads are
3552 stopped. */
3553 int executing = target_is_non_stop_p () ? 1 : 0;
3554
3555 remote_notice_new_inferior (item.ptid, executing);
3556
3557 remote_thread_info *info = get_remote_thread_info (item.ptid);
3558 info->core = item.core;
3559 info->extra = std::move (item.extra);
3560 info->name = std::move (item.name);
3561 info->thread_handle = std::move (item.thread_handle);
3562 }
3563 }
3564 }
3565
3566 if (!got_list)
3567 {
3568 /* If no thread listing method is supported, then query whether
3569 each known thread is alive, one by one, with the T packet.
3570 If the target doesn't support threads at all, then this is a
3571 no-op. See remote_thread_alive. */
3572 prune_threads ();
3573 }
3574 }
3575
3576 /*
3577 * Collect a descriptive string about the given thread.
3578 * The target may say anything it wants to about the thread
3579 * (typically info about its blocked / runnable state, name, etc.).
3580 * This string will appear in the info threads display.
3581 *
3582 * Optional: targets are not required to implement this function.
3583 */
3584
3585 const char *
3586 remote_target::extra_thread_info (thread_info *tp)
3587 {
3588 struct remote_state *rs = get_remote_state ();
3589 int result;
3590 int set;
3591 threadref id;
3592 struct gdb_ext_thread_info threadinfo;
3593 static char display_buf[100]; /* arbitrary... */
3594 int n = 0; /* position in display_buf */
3595
3596 if (rs->remote_desc == 0) /* paranoia */
3597 internal_error (__FILE__, __LINE__,
3598 _("remote_threads_extra_info"));
3599
3600 if (ptid_equal (tp->ptid, magic_null_ptid)
3601 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3602 /* This is the main thread which was added by GDB. The remote
3603 server doesn't know about it. */
3604 return NULL;
3605
3606 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3607 {
3608 struct thread_info *info = find_thread_ptid (tp->ptid);
3609
3610 if (info != NULL && info->priv != NULL)
3611 {
3612 const std::string &extra = get_remote_thread_info (info)->extra;
3613 return !extra.empty () ? extra.c_str () : NULL;
3614 }
3615 else
3616 return NULL;
3617 }
3618
3619 if (rs->use_threadextra_query)
3620 {
3621 char *b = rs->buf;
3622 char *endb = rs->buf + get_remote_packet_size ();
3623
3624 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3625 b += strlen (b);
3626 write_ptid (b, endb, tp->ptid);
3627
3628 putpkt (rs->buf);
3629 getpkt (&rs->buf, &rs->buf_size, 0);
3630 if (rs->buf[0] != 0)
3631 {
3632 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3633 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3634 display_buf [result] = '\0';
3635 return display_buf;
3636 }
3637 }
3638
3639 /* If the above query fails, fall back to the old method. */
3640 rs->use_threadextra_query = 0;
3641 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3642 | TAG_MOREDISPLAY | TAG_DISPLAY;
3643 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3644 if (remote_get_threadinfo (&id, set, &threadinfo))
3645 if (threadinfo.active)
3646 {
3647 if (*threadinfo.shortname)
3648 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3649 " Name: %s,", threadinfo.shortname);
3650 if (*threadinfo.display)
3651 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3652 " State: %s,", threadinfo.display);
3653 if (*threadinfo.more_display)
3654 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3655 " Priority: %s", threadinfo.more_display);
3656
3657 if (n > 0)
3658 {
3659 /* For purely cosmetic reasons, clear up trailing commas. */
3660 if (',' == display_buf[n-1])
3661 display_buf[n-1] = ' ';
3662 return display_buf;
3663 }
3664 }
3665 return NULL;
3666 }
3667 \f
3668
3669 bool
3670 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3671 struct static_tracepoint_marker *marker)
3672 {
3673 struct remote_state *rs = get_remote_state ();
3674 char *p = rs->buf;
3675
3676 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3677 p += strlen (p);
3678 p += hexnumstr (p, addr);
3679 putpkt (rs->buf);
3680 getpkt (&rs->buf, &rs->buf_size, 0);
3681 p = rs->buf;
3682
3683 if (*p == 'E')
3684 error (_("Remote failure reply: %s"), p);
3685
3686 if (*p++ == 'm')
3687 {
3688 parse_static_tracepoint_marker_definition (p, NULL, marker);
3689 return true;
3690 }
3691
3692 return false;
3693 }
3694
3695 std::vector<static_tracepoint_marker>
3696 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3697 {
3698 struct remote_state *rs = get_remote_state ();
3699 std::vector<static_tracepoint_marker> markers;
3700 const char *p;
3701 static_tracepoint_marker marker;
3702
3703 /* Ask for a first packet of static tracepoint marker
3704 definition. */
3705 putpkt ("qTfSTM");
3706 getpkt (&rs->buf, &rs->buf_size, 0);
3707 p = rs->buf;
3708 if (*p == 'E')
3709 error (_("Remote failure reply: %s"), p);
3710
3711 while (*p++ == 'm')
3712 {
3713 do
3714 {
3715 parse_static_tracepoint_marker_definition (p, &p, &marker);
3716
3717 if (strid == NULL || marker.str_id == strid)
3718 markers.push_back (std::move (marker));
3719 }
3720 while (*p++ == ','); /* comma-separated list */
3721 /* Ask for another packet of static tracepoint definition. */
3722 putpkt ("qTsSTM");
3723 getpkt (&rs->buf, &rs->buf_size, 0);
3724 p = rs->buf;
3725 }
3726
3727 return markers;
3728 }
3729
3730 \f
3731 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3732
3733 ptid_t
3734 remote_target::get_ada_task_ptid (long lwp, long thread)
3735 {
3736 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3737 }
3738 \f
3739
3740 /* Restart the remote side; this is an extended protocol operation. */
3741
3742 static void
3743 extended_remote_restart (void)
3744 {
3745 struct remote_state *rs = get_remote_state ();
3746
3747 /* Send the restart command; for reasons I don't understand the
3748 remote side really expects a number after the "R". */
3749 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3750 putpkt (rs->buf);
3751
3752 remote_fileio_reset ();
3753 }
3754 \f
3755 /* Clean up connection to a remote debugger. */
3756
3757 void
3758 remote_target::close ()
3759 {
3760 struct remote_state *rs = get_remote_state ();
3761
3762 if (rs->remote_desc == NULL)
3763 return; /* already closed */
3764
3765 /* Make sure we leave stdin registered in the event loop. */
3766 terminal_ours ();
3767
3768 serial_close (rs->remote_desc);
3769 rs->remote_desc = NULL;
3770
3771 /* We don't have a connection to the remote stub anymore. Get rid
3772 of all the inferiors and their threads we were controlling.
3773 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3774 will be unable to find the thread corresponding to (pid, 0, 0). */
3775 inferior_ptid = null_ptid;
3776 discard_all_inferiors ();
3777
3778 /* We are closing the remote target, so we should discard
3779 everything of this target. */
3780 discard_pending_stop_replies_in_queue (rs);
3781
3782 if (remote_async_inferior_event_token)
3783 delete_async_event_handler (&remote_async_inferior_event_token);
3784
3785 remote_notif_state_xfree (rs->notif_state);
3786
3787 trace_reset_local_state ();
3788 }
3789
3790 /* Query the remote side for the text, data and bss offsets. */
3791
3792 static void
3793 get_offsets (void)
3794 {
3795 struct remote_state *rs = get_remote_state ();
3796 char *buf;
3797 char *ptr;
3798 int lose, num_segments = 0, do_sections, do_segments;
3799 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3800 struct section_offsets *offs;
3801 struct symfile_segment_data *data;
3802
3803 if (symfile_objfile == NULL)
3804 return;
3805
3806 putpkt ("qOffsets");
3807 getpkt (&rs->buf, &rs->buf_size, 0);
3808 buf = rs->buf;
3809
3810 if (buf[0] == '\000')
3811 return; /* Return silently. Stub doesn't support
3812 this command. */
3813 if (buf[0] == 'E')
3814 {
3815 warning (_("Remote failure reply: %s"), buf);
3816 return;
3817 }
3818
3819 /* Pick up each field in turn. This used to be done with scanf, but
3820 scanf will make trouble if CORE_ADDR size doesn't match
3821 conversion directives correctly. The following code will work
3822 with any size of CORE_ADDR. */
3823 text_addr = data_addr = bss_addr = 0;
3824 ptr = buf;
3825 lose = 0;
3826
3827 if (startswith (ptr, "Text="))
3828 {
3829 ptr += 5;
3830 /* Don't use strtol, could lose on big values. */
3831 while (*ptr && *ptr != ';')
3832 text_addr = (text_addr << 4) + fromhex (*ptr++);
3833
3834 if (startswith (ptr, ";Data="))
3835 {
3836 ptr += 6;
3837 while (*ptr && *ptr != ';')
3838 data_addr = (data_addr << 4) + fromhex (*ptr++);
3839 }
3840 else
3841 lose = 1;
3842
3843 if (!lose && startswith (ptr, ";Bss="))
3844 {
3845 ptr += 5;
3846 while (*ptr && *ptr != ';')
3847 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3848
3849 if (bss_addr != data_addr)
3850 warning (_("Target reported unsupported offsets: %s"), buf);
3851 }
3852 else
3853 lose = 1;
3854 }
3855 else if (startswith (ptr, "TextSeg="))
3856 {
3857 ptr += 8;
3858 /* Don't use strtol, could lose on big values. */
3859 while (*ptr && *ptr != ';')
3860 text_addr = (text_addr << 4) + fromhex (*ptr++);
3861 num_segments = 1;
3862
3863 if (startswith (ptr, ";DataSeg="))
3864 {
3865 ptr += 9;
3866 while (*ptr && *ptr != ';')
3867 data_addr = (data_addr << 4) + fromhex (*ptr++);
3868 num_segments++;
3869 }
3870 }
3871 else
3872 lose = 1;
3873
3874 if (lose)
3875 error (_("Malformed response to offset query, %s"), buf);
3876 else if (*ptr != '\0')
3877 warning (_("Target reported unsupported offsets: %s"), buf);
3878
3879 offs = ((struct section_offsets *)
3880 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3881 memcpy (offs, symfile_objfile->section_offsets,
3882 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3883
3884 data = get_symfile_segment_data (symfile_objfile->obfd);
3885 do_segments = (data != NULL);
3886 do_sections = num_segments == 0;
3887
3888 if (num_segments > 0)
3889 {
3890 segments[0] = text_addr;
3891 segments[1] = data_addr;
3892 }
3893 /* If we have two segments, we can still try to relocate everything
3894 by assuming that the .text and .data offsets apply to the whole
3895 text and data segments. Convert the offsets given in the packet
3896 to base addresses for symfile_map_offsets_to_segments. */
3897 else if (data && data->num_segments == 2)
3898 {
3899 segments[0] = data->segment_bases[0] + text_addr;
3900 segments[1] = data->segment_bases[1] + data_addr;
3901 num_segments = 2;
3902 }
3903 /* If the object file has only one segment, assume that it is text
3904 rather than data; main programs with no writable data are rare,
3905 but programs with no code are useless. Of course the code might
3906 have ended up in the data segment... to detect that we would need
3907 the permissions here. */
3908 else if (data && data->num_segments == 1)
3909 {
3910 segments[0] = data->segment_bases[0] + text_addr;
3911 num_segments = 1;
3912 }
3913 /* There's no way to relocate by segment. */
3914 else
3915 do_segments = 0;
3916
3917 if (do_segments)
3918 {
3919 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3920 offs, num_segments, segments);
3921
3922 if (ret == 0 && !do_sections)
3923 error (_("Can not handle qOffsets TextSeg "
3924 "response with this symbol file"));
3925
3926 if (ret > 0)
3927 do_sections = 0;
3928 }
3929
3930 if (data)
3931 free_symfile_segment_data (data);
3932
3933 if (do_sections)
3934 {
3935 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3936
3937 /* This is a temporary kludge to force data and bss to use the
3938 same offsets because that's what nlmconv does now. The real
3939 solution requires changes to the stub and remote.c that I
3940 don't have time to do right now. */
3941
3942 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3943 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3944 }
3945
3946 objfile_relocate (symfile_objfile, offs);
3947 }
3948
3949 /* Send interrupt_sequence to remote target. */
3950 static void
3951 send_interrupt_sequence (void)
3952 {
3953 struct remote_state *rs = get_remote_state ();
3954
3955 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3956 remote_serial_write ("\x03", 1);
3957 else if (interrupt_sequence_mode == interrupt_sequence_break)
3958 serial_send_break (rs->remote_desc);
3959 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3960 {
3961 serial_send_break (rs->remote_desc);
3962 remote_serial_write ("g", 1);
3963 }
3964 else
3965 internal_error (__FILE__, __LINE__,
3966 _("Invalid value for interrupt_sequence_mode: %s."),
3967 interrupt_sequence_mode);
3968 }
3969
3970
3971 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3972 and extract the PTID. Returns NULL_PTID if not found. */
3973
3974 static ptid_t
3975 stop_reply_extract_thread (char *stop_reply)
3976 {
3977 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3978 {
3979 const char *p;
3980
3981 /* Txx r:val ; r:val (...) */
3982 p = &stop_reply[3];
3983
3984 /* Look for "register" named "thread". */
3985 while (*p != '\0')
3986 {
3987 const char *p1;
3988
3989 p1 = strchr (p, ':');
3990 if (p1 == NULL)
3991 return null_ptid;
3992
3993 if (strncmp (p, "thread", p1 - p) == 0)
3994 return read_ptid (++p1, &p);
3995
3996 p1 = strchr (p, ';');
3997 if (p1 == NULL)
3998 return null_ptid;
3999 p1++;
4000
4001 p = p1;
4002 }
4003 }
4004
4005 return null_ptid;
4006 }
4007
4008 /* Determine the remote side's current thread. If we have a stop
4009 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4010 "thread" register we can extract the current thread from. If not,
4011 ask the remote which is the current thread with qC. The former
4012 method avoids a roundtrip. */
4013
4014 static ptid_t
4015 get_current_thread (char *wait_status)
4016 {
4017 ptid_t ptid = null_ptid;
4018
4019 /* Note we don't use remote_parse_stop_reply as that makes use of
4020 the target architecture, which we haven't yet fully determined at
4021 this point. */
4022 if (wait_status != NULL)
4023 ptid = stop_reply_extract_thread (wait_status);
4024 if (ptid_equal (ptid, null_ptid))
4025 ptid = remote_current_thread (inferior_ptid);
4026
4027 return ptid;
4028 }
4029
4030 /* Query the remote target for which is the current thread/process,
4031 add it to our tables, and update INFERIOR_PTID. The caller is
4032 responsible for setting the state such that the remote end is ready
4033 to return the current thread.
4034
4035 This function is called after handling the '?' or 'vRun' packets,
4036 whose response is a stop reply from which we can also try
4037 extracting the thread. If the target doesn't support the explicit
4038 qC query, we infer the current thread from that stop reply, passed
4039 in in WAIT_STATUS, which may be NULL. */
4040
4041 static void
4042 add_current_inferior_and_thread (char *wait_status)
4043 {
4044 struct remote_state *rs = get_remote_state ();
4045 int fake_pid_p = 0;
4046
4047 inferior_ptid = null_ptid;
4048
4049 /* Now, if we have thread information, update inferior_ptid. */
4050 ptid_t curr_ptid = get_current_thread (wait_status);
4051
4052 if (curr_ptid != null_ptid)
4053 {
4054 if (!remote_multi_process_p (rs))
4055 fake_pid_p = 1;
4056 }
4057 else
4058 {
4059 /* Without this, some commands which require an active target
4060 (such as kill) won't work. This variable serves (at least)
4061 double duty as both the pid of the target process (if it has
4062 such), and as a flag indicating that a target is active. */
4063 curr_ptid = magic_null_ptid;
4064 fake_pid_p = 1;
4065 }
4066
4067 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
4068
4069 /* Add the main thread and switch to it. Don't try reading
4070 registers yet, since we haven't fetched the target description
4071 yet. */
4072 thread_info *tp = add_thread_silent (curr_ptid);
4073 switch_to_thread_no_regs (tp);
4074 }
4075
4076 /* Print info about a thread that was found already stopped on
4077 connection. */
4078
4079 static void
4080 print_one_stopped_thread (struct thread_info *thread)
4081 {
4082 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4083
4084 switch_to_thread (thread->ptid);
4085 stop_pc = get_frame_pc (get_current_frame ());
4086 set_current_sal_from_frame (get_current_frame ());
4087
4088 thread->suspend.waitstatus_pending_p = 0;
4089
4090 if (ws->kind == TARGET_WAITKIND_STOPPED)
4091 {
4092 enum gdb_signal sig = ws->value.sig;
4093
4094 if (signal_print_state (sig))
4095 gdb::observers::signal_received.notify (sig);
4096 }
4097 gdb::observers::normal_stop.notify (NULL, 1);
4098 }
4099
4100 /* Process all initial stop replies the remote side sent in response
4101 to the ? packet. These indicate threads that were already stopped
4102 on initial connection. We mark these threads as stopped and print
4103 their current frame before giving the user the prompt. */
4104
4105 static void
4106 process_initial_stop_replies (int from_tty)
4107 {
4108 int pending_stop_replies = stop_reply_queue_length ();
4109 struct inferior *inf;
4110 struct thread_info *thread;
4111 struct thread_info *selected = NULL;
4112 struct thread_info *lowest_stopped = NULL;
4113 struct thread_info *first = NULL;
4114
4115 /* Consume the initial pending events. */
4116 while (pending_stop_replies-- > 0)
4117 {
4118 ptid_t waiton_ptid = minus_one_ptid;
4119 ptid_t event_ptid;
4120 struct target_waitstatus ws;
4121 int ignore_event = 0;
4122 struct thread_info *thread;
4123
4124 memset (&ws, 0, sizeof (ws));
4125 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4126 if (remote_debug)
4127 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4128
4129 switch (ws.kind)
4130 {
4131 case TARGET_WAITKIND_IGNORE:
4132 case TARGET_WAITKIND_NO_RESUMED:
4133 case TARGET_WAITKIND_SIGNALLED:
4134 case TARGET_WAITKIND_EXITED:
4135 /* We shouldn't see these, but if we do, just ignore. */
4136 if (remote_debug)
4137 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4138 ignore_event = 1;
4139 break;
4140
4141 case TARGET_WAITKIND_EXECD:
4142 xfree (ws.value.execd_pathname);
4143 break;
4144 default:
4145 break;
4146 }
4147
4148 if (ignore_event)
4149 continue;
4150
4151 thread = find_thread_ptid (event_ptid);
4152
4153 if (ws.kind == TARGET_WAITKIND_STOPPED)
4154 {
4155 enum gdb_signal sig = ws.value.sig;
4156
4157 /* Stubs traditionally report SIGTRAP as initial signal,
4158 instead of signal 0. Suppress it. */
4159 if (sig == GDB_SIGNAL_TRAP)
4160 sig = GDB_SIGNAL_0;
4161 thread->suspend.stop_signal = sig;
4162 ws.value.sig = sig;
4163 }
4164
4165 thread->suspend.waitstatus = ws;
4166
4167 if (ws.kind != TARGET_WAITKIND_STOPPED
4168 || ws.value.sig != GDB_SIGNAL_0)
4169 thread->suspend.waitstatus_pending_p = 1;
4170
4171 set_executing (event_ptid, 0);
4172 set_running (event_ptid, 0);
4173 get_remote_thread_info (thread)->vcont_resumed = 0;
4174 }
4175
4176 /* "Notice" the new inferiors before anything related to
4177 registers/memory. */
4178 ALL_INFERIORS (inf)
4179 {
4180 if (inf->pid == 0)
4181 continue;
4182
4183 inf->needs_setup = 1;
4184
4185 if (non_stop)
4186 {
4187 thread = any_live_thread_of_process (inf->pid);
4188 notice_new_inferior (thread->ptid,
4189 thread->state == THREAD_RUNNING,
4190 from_tty);
4191 }
4192 }
4193
4194 /* If all-stop on top of non-stop, pause all threads. Note this
4195 records the threads' stop pc, so must be done after "noticing"
4196 the inferiors. */
4197 if (!non_stop)
4198 {
4199 stop_all_threads ();
4200
4201 /* If all threads of an inferior were already stopped, we
4202 haven't setup the inferior yet. */
4203 ALL_INFERIORS (inf)
4204 {
4205 if (inf->pid == 0)
4206 continue;
4207
4208 if (inf->needs_setup)
4209 {
4210 thread = any_live_thread_of_process (inf->pid);
4211 switch_to_thread_no_regs (thread);
4212 setup_inferior (0);
4213 }
4214 }
4215 }
4216
4217 /* Now go over all threads that are stopped, and print their current
4218 frame. If all-stop, then if there's a signalled thread, pick
4219 that as current. */
4220 ALL_NON_EXITED_THREADS (thread)
4221 {
4222 if (first == NULL)
4223 first = thread;
4224
4225 if (!non_stop)
4226 set_running (thread->ptid, 0);
4227 else if (thread->state != THREAD_STOPPED)
4228 continue;
4229
4230 if (selected == NULL
4231 && thread->suspend.waitstatus_pending_p)
4232 selected = thread;
4233
4234 if (lowest_stopped == NULL
4235 || thread->inf->num < lowest_stopped->inf->num
4236 || thread->per_inf_num < lowest_stopped->per_inf_num)
4237 lowest_stopped = thread;
4238
4239 if (non_stop)
4240 print_one_stopped_thread (thread);
4241 }
4242
4243 /* In all-stop, we only print the status of one thread, and leave
4244 others with their status pending. */
4245 if (!non_stop)
4246 {
4247 thread = selected;
4248 if (thread == NULL)
4249 thread = lowest_stopped;
4250 if (thread == NULL)
4251 thread = first;
4252
4253 print_one_stopped_thread (thread);
4254 }
4255
4256 /* For "info program". */
4257 thread = inferior_thread ();
4258 if (thread->state == THREAD_STOPPED)
4259 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4260 }
4261
4262 /* Start the remote connection and sync state. */
4263
4264 void
4265 remote_target::start_remote (int from_tty, int extended_p)
4266 {
4267 struct remote_state *rs = get_remote_state ();
4268 struct packet_config *noack_config;
4269 char *wait_status = NULL;
4270
4271 /* Signal other parts that we're going through the initial setup,
4272 and so things may not be stable yet. E.g., we don't try to
4273 install tracepoints until we've relocated symbols. Also, a
4274 Ctrl-C before we're connected and synced up can't interrupt the
4275 target. Instead, it offers to drop the (potentially wedged)
4276 connection. */
4277 rs->starting_up = 1;
4278
4279 QUIT;
4280
4281 if (interrupt_on_connect)
4282 send_interrupt_sequence ();
4283
4284 /* Ack any packet which the remote side has already sent. */
4285 remote_serial_write ("+", 1);
4286
4287 /* The first packet we send to the target is the optional "supported
4288 packets" request. If the target can answer this, it will tell us
4289 which later probes to skip. */
4290 remote_query_supported ();
4291
4292 /* If the stub wants to get a QAllow, compose one and send it. */
4293 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4294 set_permissions ();
4295
4296 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4297 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4298 as a reply to known packet. For packet "vFile:setfs:" it is an
4299 invalid reply and GDB would return error in
4300 remote_hostio_set_filesystem, making remote files access impossible.
4301 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4302 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4303 {
4304 const char v_mustreplyempty[] = "vMustReplyEmpty";
4305
4306 putpkt (v_mustreplyempty);
4307 getpkt (&rs->buf, &rs->buf_size, 0);
4308 if (strcmp (rs->buf, "OK") == 0)
4309 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4310 else if (strcmp (rs->buf, "") != 0)
4311 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4312 rs->buf);
4313 }
4314
4315 /* Next, we possibly activate noack mode.
4316
4317 If the QStartNoAckMode packet configuration is set to AUTO,
4318 enable noack mode if the stub reported a wish for it with
4319 qSupported.
4320
4321 If set to TRUE, then enable noack mode even if the stub didn't
4322 report it in qSupported. If the stub doesn't reply OK, the
4323 session ends with an error.
4324
4325 If FALSE, then don't activate noack mode, regardless of what the
4326 stub claimed should be the default with qSupported. */
4327
4328 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4329 if (packet_config_support (noack_config) != PACKET_DISABLE)
4330 {
4331 putpkt ("QStartNoAckMode");
4332 getpkt (&rs->buf, &rs->buf_size, 0);
4333 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4334 rs->noack_mode = 1;
4335 }
4336
4337 if (extended_p)
4338 {
4339 /* Tell the remote that we are using the extended protocol. */
4340 putpkt ("!");
4341 getpkt (&rs->buf, &rs->buf_size, 0);
4342 }
4343
4344 /* Let the target know which signals it is allowed to pass down to
4345 the program. */
4346 update_signals_program_target ();
4347
4348 /* Next, if the target can specify a description, read it. We do
4349 this before anything involving memory or registers. */
4350 target_find_description ();
4351
4352 /* Next, now that we know something about the target, update the
4353 address spaces in the program spaces. */
4354 update_address_spaces ();
4355
4356 /* On OSs where the list of libraries is global to all
4357 processes, we fetch them early. */
4358 if (gdbarch_has_global_solist (target_gdbarch ()))
4359 solib_add (NULL, from_tty, auto_solib_add);
4360
4361 if (target_is_non_stop_p ())
4362 {
4363 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4364 error (_("Non-stop mode requested, but remote "
4365 "does not support non-stop"));
4366
4367 putpkt ("QNonStop:1");
4368 getpkt (&rs->buf, &rs->buf_size, 0);
4369
4370 if (strcmp (rs->buf, "OK") != 0)
4371 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4372
4373 /* Find about threads and processes the stub is already
4374 controlling. We default to adding them in the running state.
4375 The '?' query below will then tell us about which threads are
4376 stopped. */
4377 this->update_thread_list ();
4378 }
4379 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4380 {
4381 /* Don't assume that the stub can operate in all-stop mode.
4382 Request it explicitly. */
4383 putpkt ("QNonStop:0");
4384 getpkt (&rs->buf, &rs->buf_size, 0);
4385
4386 if (strcmp (rs->buf, "OK") != 0)
4387 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4388 }
4389
4390 /* Upload TSVs regardless of whether the target is running or not. The
4391 remote stub, such as GDBserver, may have some predefined or builtin
4392 TSVs, even if the target is not running. */
4393 if (get_trace_status (current_trace_status ()) != -1)
4394 {
4395 struct uploaded_tsv *uploaded_tsvs = NULL;
4396
4397 upload_trace_state_variables (&uploaded_tsvs);
4398 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4399 }
4400
4401 /* Check whether the target is running now. */
4402 putpkt ("?");
4403 getpkt (&rs->buf, &rs->buf_size, 0);
4404
4405 if (!target_is_non_stop_p ())
4406 {
4407 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4408 {
4409 if (!extended_p)
4410 error (_("The target is not running (try extended-remote?)"));
4411
4412 /* We're connected, but not running. Drop out before we
4413 call start_remote. */
4414 rs->starting_up = 0;
4415 return;
4416 }
4417 else
4418 {
4419 /* Save the reply for later. */
4420 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4421 strcpy (wait_status, rs->buf);
4422 }
4423
4424 /* Fetch thread list. */
4425 target_update_thread_list ();
4426
4427 /* Let the stub know that we want it to return the thread. */
4428 set_continue_thread (minus_one_ptid);
4429
4430 if (thread_count () == 0)
4431 {
4432 /* Target has no concept of threads at all. GDB treats
4433 non-threaded target as single-threaded; add a main
4434 thread. */
4435 add_current_inferior_and_thread (wait_status);
4436 }
4437 else
4438 {
4439 /* We have thread information; select the thread the target
4440 says should be current. If we're reconnecting to a
4441 multi-threaded program, this will ideally be the thread
4442 that last reported an event before GDB disconnected. */
4443 inferior_ptid = get_current_thread (wait_status);
4444 if (ptid_equal (inferior_ptid, null_ptid))
4445 {
4446 /* Odd... The target was able to list threads, but not
4447 tell us which thread was current (no "thread"
4448 register in T stop reply?). Just pick the first
4449 thread in the thread list then. */
4450
4451 if (remote_debug)
4452 fprintf_unfiltered (gdb_stdlog,
4453 "warning: couldn't determine remote "
4454 "current thread; picking first in list.\n");
4455
4456 inferior_ptid = thread_list->ptid;
4457 }
4458 }
4459
4460 /* init_wait_for_inferior should be called before get_offsets in order
4461 to manage `inserted' flag in bp loc in a correct state.
4462 breakpoint_init_inferior, called from init_wait_for_inferior, set
4463 `inserted' flag to 0, while before breakpoint_re_set, called from
4464 start_remote, set `inserted' flag to 1. In the initialization of
4465 inferior, breakpoint_init_inferior should be called first, and then
4466 breakpoint_re_set can be called. If this order is broken, state of
4467 `inserted' flag is wrong, and cause some problems on breakpoint
4468 manipulation. */
4469 init_wait_for_inferior ();
4470
4471 get_offsets (); /* Get text, data & bss offsets. */
4472
4473 /* If we could not find a description using qXfer, and we know
4474 how to do it some other way, try again. This is not
4475 supported for non-stop; it could be, but it is tricky if
4476 there are no stopped threads when we connect. */
4477 if (remote_read_description_p (this)
4478 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4479 {
4480 target_clear_description ();
4481 target_find_description ();
4482 }
4483
4484 /* Use the previously fetched status. */
4485 gdb_assert (wait_status != NULL);
4486 strcpy (rs->buf, wait_status);
4487 rs->cached_wait_status = 1;
4488
4489 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4490 }
4491 else
4492 {
4493 /* Clear WFI global state. Do this before finding about new
4494 threads and inferiors, and setting the current inferior.
4495 Otherwise we would clear the proceed status of the current
4496 inferior when we want its stop_soon state to be preserved
4497 (see notice_new_inferior). */
4498 init_wait_for_inferior ();
4499
4500 /* In non-stop, we will either get an "OK", meaning that there
4501 are no stopped threads at this time; or, a regular stop
4502 reply. In the latter case, there may be more than one thread
4503 stopped --- we pull them all out using the vStopped
4504 mechanism. */
4505 if (strcmp (rs->buf, "OK") != 0)
4506 {
4507 struct notif_client *notif = &notif_client_stop;
4508
4509 /* remote_notif_get_pending_replies acks this one, and gets
4510 the rest out. */
4511 rs->notif_state->pending_event[notif_client_stop.id]
4512 = remote_notif_parse (notif, rs->buf);
4513 remote_notif_get_pending_events (notif);
4514 }
4515
4516 if (thread_count () == 0)
4517 {
4518 if (!extended_p)
4519 error (_("The target is not running (try extended-remote?)"));
4520
4521 /* We're connected, but not running. Drop out before we
4522 call start_remote. */
4523 rs->starting_up = 0;
4524 return;
4525 }
4526
4527 /* In non-stop mode, any cached wait status will be stored in
4528 the stop reply queue. */
4529 gdb_assert (wait_status == NULL);
4530
4531 /* Report all signals during attach/startup. */
4532 pass_signals (0, NULL);
4533
4534 /* If there are already stopped threads, mark them stopped and
4535 report their stops before giving the prompt to the user. */
4536 process_initial_stop_replies (from_tty);
4537
4538 if (target_can_async_p ())
4539 target_async (1);
4540 }
4541
4542 /* If we connected to a live target, do some additional setup. */
4543 if (target_has_execution)
4544 {
4545 if (symfile_objfile) /* No use without a symbol-file. */
4546 remote_check_symbols ();
4547 }
4548
4549 /* Possibly the target has been engaged in a trace run started
4550 previously; find out where things are at. */
4551 if (get_trace_status (current_trace_status ()) != -1)
4552 {
4553 struct uploaded_tp *uploaded_tps = NULL;
4554
4555 if (current_trace_status ()->running)
4556 printf_filtered (_("Trace is already running on the target.\n"));
4557
4558 upload_tracepoints (&uploaded_tps);
4559
4560 merge_uploaded_tracepoints (&uploaded_tps);
4561 }
4562
4563 /* Possibly the target has been engaged in a btrace record started
4564 previously; find out where things are at. */
4565 remote_btrace_maybe_reopen ();
4566
4567 /* The thread and inferior lists are now synchronized with the
4568 target, our symbols have been relocated, and we're merged the
4569 target's tracepoints with ours. We're done with basic start
4570 up. */
4571 rs->starting_up = 0;
4572
4573 /* Maybe breakpoints are global and need to be inserted now. */
4574 if (breakpoints_should_be_inserted_now ())
4575 insert_breakpoints ();
4576 }
4577
4578 /* Open a connection to a remote debugger.
4579 NAME is the filename used for communication. */
4580
4581 void
4582 remote_target::open (const char *name, int from_tty)
4583 {
4584 open_1 (name, from_tty, 0);
4585 }
4586
4587 /* Open a connection to a remote debugger using the extended
4588 remote gdb protocol. NAME is the filename used for communication. */
4589
4590 void
4591 extended_remote_target::open (const char *name, int from_tty)
4592 {
4593 open_1 (name, from_tty, 1 /*extended_p */);
4594 }
4595
4596 /* Reset all packets back to "unknown support". Called when opening a
4597 new connection to a remote target. */
4598
4599 static void
4600 reset_all_packet_configs_support (void)
4601 {
4602 int i;
4603
4604 for (i = 0; i < PACKET_MAX; i++)
4605 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4606 }
4607
4608 /* Initialize all packet configs. */
4609
4610 static void
4611 init_all_packet_configs (void)
4612 {
4613 int i;
4614
4615 for (i = 0; i < PACKET_MAX; i++)
4616 {
4617 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4618 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4619 }
4620 }
4621
4622 /* Symbol look-up. */
4623
4624 static void
4625 remote_check_symbols (void)
4626 {
4627 char *msg, *reply, *tmp;
4628 int end;
4629 long reply_size;
4630 struct cleanup *old_chain;
4631
4632 /* The remote side has no concept of inferiors that aren't running
4633 yet, it only knows about running processes. If we're connected
4634 but our current inferior is not running, we should not invite the
4635 remote target to request symbol lookups related to its
4636 (unrelated) current process. */
4637 if (!target_has_execution)
4638 return;
4639
4640 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4641 return;
4642
4643 /* Make sure the remote is pointing at the right process. Note
4644 there's no way to select "no process". */
4645 set_general_process ();
4646
4647 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4648 because we need both at the same time. */
4649 msg = (char *) xmalloc (get_remote_packet_size ());
4650 old_chain = make_cleanup (xfree, msg);
4651 reply = (char *) xmalloc (get_remote_packet_size ());
4652 make_cleanup (free_current_contents, &reply);
4653 reply_size = get_remote_packet_size ();
4654
4655 /* Invite target to request symbol lookups. */
4656
4657 putpkt ("qSymbol::");
4658 getpkt (&reply, &reply_size, 0);
4659 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4660
4661 while (startswith (reply, "qSymbol:"))
4662 {
4663 struct bound_minimal_symbol sym;
4664
4665 tmp = &reply[8];
4666 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4667 msg[end] = '\0';
4668 sym = lookup_minimal_symbol (msg, NULL, NULL);
4669 if (sym.minsym == NULL)
4670 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4671 else
4672 {
4673 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4674 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4675
4676 /* If this is a function address, return the start of code
4677 instead of any data function descriptor. */
4678 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4679 sym_addr,
4680 target_stack);
4681
4682 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4683 phex_nz (sym_addr, addr_size), &reply[8]);
4684 }
4685
4686 putpkt (msg);
4687 getpkt (&reply, &reply_size, 0);
4688 }
4689
4690 do_cleanups (old_chain);
4691 }
4692
4693 static struct serial *
4694 remote_serial_open (const char *name)
4695 {
4696 static int udp_warning = 0;
4697
4698 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4699 of in ser-tcp.c, because it is the remote protocol assuming that the
4700 serial connection is reliable and not the serial connection promising
4701 to be. */
4702 if (!udp_warning && startswith (name, "udp:"))
4703 {
4704 warning (_("The remote protocol may be unreliable over UDP.\n"
4705 "Some events may be lost, rendering further debugging "
4706 "impossible."));
4707 udp_warning = 1;
4708 }
4709
4710 return serial_open (name);
4711 }
4712
4713 /* Inform the target of our permission settings. The permission flags
4714 work without this, but if the target knows the settings, it can do
4715 a couple things. First, it can add its own check, to catch cases
4716 that somehow manage to get by the permissions checks in target
4717 methods. Second, if the target is wired to disallow particular
4718 settings (for instance, a system in the field that is not set up to
4719 be able to stop at a breakpoint), it can object to any unavailable
4720 permissions. */
4721
4722 void
4723 remote_target::set_permissions ()
4724 {
4725 struct remote_state *rs = get_remote_state ();
4726
4727 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4728 "WriteReg:%x;WriteMem:%x;"
4729 "InsertBreak:%x;InsertTrace:%x;"
4730 "InsertFastTrace:%x;Stop:%x",
4731 may_write_registers, may_write_memory,
4732 may_insert_breakpoints, may_insert_tracepoints,
4733 may_insert_fast_tracepoints, may_stop);
4734 putpkt (rs->buf);
4735 getpkt (&rs->buf, &rs->buf_size, 0);
4736
4737 /* If the target didn't like the packet, warn the user. Do not try
4738 to undo the user's settings, that would just be maddening. */
4739 if (strcmp (rs->buf, "OK") != 0)
4740 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4741 }
4742
4743 /* This type describes each known response to the qSupported
4744 packet. */
4745 struct protocol_feature
4746 {
4747 /* The name of this protocol feature. */
4748 const char *name;
4749
4750 /* The default for this protocol feature. */
4751 enum packet_support default_support;
4752
4753 /* The function to call when this feature is reported, or after
4754 qSupported processing if the feature is not supported.
4755 The first argument points to this structure. The second
4756 argument indicates whether the packet requested support be
4757 enabled, disabled, or probed (or the default, if this function
4758 is being called at the end of processing and this feature was
4759 not reported). The third argument may be NULL; if not NULL, it
4760 is a NUL-terminated string taken from the packet following
4761 this feature's name and an equals sign. */
4762 void (*func) (const struct protocol_feature *, enum packet_support,
4763 const char *);
4764
4765 /* The corresponding packet for this feature. Only used if
4766 FUNC is remote_supported_packet. */
4767 int packet;
4768 };
4769
4770 static void
4771 remote_supported_packet (const struct protocol_feature *feature,
4772 enum packet_support support,
4773 const char *argument)
4774 {
4775 if (argument)
4776 {
4777 warning (_("Remote qSupported response supplied an unexpected value for"
4778 " \"%s\"."), feature->name);
4779 return;
4780 }
4781
4782 remote_protocol_packets[feature->packet].support = support;
4783 }
4784
4785 static void
4786 remote_packet_size (const struct protocol_feature *feature,
4787 enum packet_support support, const char *value)
4788 {
4789 struct remote_state *rs = get_remote_state ();
4790
4791 int packet_size;
4792 char *value_end;
4793
4794 if (support != PACKET_ENABLE)
4795 return;
4796
4797 if (value == NULL || *value == '\0')
4798 {
4799 warning (_("Remote target reported \"%s\" without a size."),
4800 feature->name);
4801 return;
4802 }
4803
4804 errno = 0;
4805 packet_size = strtol (value, &value_end, 16);
4806 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4807 {
4808 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4809 feature->name, value);
4810 return;
4811 }
4812
4813 /* Record the new maximum packet size. */
4814 rs->explicit_packet_size = packet_size;
4815 }
4816
4817 static const struct protocol_feature remote_protocol_features[] = {
4818 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4819 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4820 PACKET_qXfer_auxv },
4821 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4822 PACKET_qXfer_exec_file },
4823 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4824 PACKET_qXfer_features },
4825 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4826 PACKET_qXfer_libraries },
4827 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4828 PACKET_qXfer_libraries_svr4 },
4829 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4830 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4831 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4832 PACKET_qXfer_memory_map },
4833 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4834 PACKET_qXfer_spu_read },
4835 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4836 PACKET_qXfer_spu_write },
4837 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4838 PACKET_qXfer_osdata },
4839 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4840 PACKET_qXfer_threads },
4841 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4842 PACKET_qXfer_traceframe_info },
4843 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4844 PACKET_QPassSignals },
4845 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4846 PACKET_QCatchSyscalls },
4847 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4848 PACKET_QProgramSignals },
4849 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4850 PACKET_QSetWorkingDir },
4851 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4852 PACKET_QStartupWithShell },
4853 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4854 PACKET_QEnvironmentHexEncoded },
4855 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4856 PACKET_QEnvironmentReset },
4857 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4858 PACKET_QEnvironmentUnset },
4859 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4860 PACKET_QStartNoAckMode },
4861 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4862 PACKET_multiprocess_feature },
4863 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4864 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4865 PACKET_qXfer_siginfo_read },
4866 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4867 PACKET_qXfer_siginfo_write },
4868 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4869 PACKET_ConditionalTracepoints },
4870 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4871 PACKET_ConditionalBreakpoints },
4872 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4873 PACKET_BreakpointCommands },
4874 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4875 PACKET_FastTracepoints },
4876 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4877 PACKET_StaticTracepoints },
4878 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4879 PACKET_InstallInTrace},
4880 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4881 PACKET_DisconnectedTracing_feature },
4882 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4883 PACKET_bc },
4884 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4885 PACKET_bs },
4886 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4887 PACKET_TracepointSource },
4888 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4889 PACKET_QAllow },
4890 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4891 PACKET_EnableDisableTracepoints_feature },
4892 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4893 PACKET_qXfer_fdpic },
4894 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4895 PACKET_qXfer_uib },
4896 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4897 PACKET_QDisableRandomization },
4898 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4899 { "QTBuffer:size", PACKET_DISABLE,
4900 remote_supported_packet, PACKET_QTBuffer_size},
4901 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4902 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4903 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4904 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4905 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4906 PACKET_qXfer_btrace },
4907 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4908 PACKET_qXfer_btrace_conf },
4909 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4910 PACKET_Qbtrace_conf_bts_size },
4911 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4912 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4913 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4914 PACKET_fork_event_feature },
4915 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4916 PACKET_vfork_event_feature },
4917 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4918 PACKET_exec_event_feature },
4919 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4920 PACKET_Qbtrace_conf_pt_size },
4921 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4922 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4923 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4924 };
4925
4926 static char *remote_support_xml;
4927
4928 /* Register string appended to "xmlRegisters=" in qSupported query. */
4929
4930 void
4931 register_remote_support_xml (const char *xml)
4932 {
4933 #if defined(HAVE_LIBEXPAT)
4934 if (remote_support_xml == NULL)
4935 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4936 else
4937 {
4938 char *copy = xstrdup (remote_support_xml + 13);
4939 char *p = strtok (copy, ",");
4940
4941 do
4942 {
4943 if (strcmp (p, xml) == 0)
4944 {
4945 /* already there */
4946 xfree (copy);
4947 return;
4948 }
4949 }
4950 while ((p = strtok (NULL, ",")) != NULL);
4951 xfree (copy);
4952
4953 remote_support_xml = reconcat (remote_support_xml,
4954 remote_support_xml, ",", xml,
4955 (char *) NULL);
4956 }
4957 #endif
4958 }
4959
4960 static char *
4961 remote_query_supported_append (char *msg, const char *append)
4962 {
4963 if (msg)
4964 return reconcat (msg, msg, ";", append, (char *) NULL);
4965 else
4966 return xstrdup (append);
4967 }
4968
4969 static void
4970 remote_query_supported (void)
4971 {
4972 struct remote_state *rs = get_remote_state ();
4973 char *next;
4974 int i;
4975 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4976
4977 /* The packet support flags are handled differently for this packet
4978 than for most others. We treat an error, a disabled packet, and
4979 an empty response identically: any features which must be reported
4980 to be used will be automatically disabled. An empty buffer
4981 accomplishes this, since that is also the representation for a list
4982 containing no features. */
4983
4984 rs->buf[0] = 0;
4985 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4986 {
4987 char *q = NULL;
4988 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4989
4990 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4991 q = remote_query_supported_append (q, "multiprocess+");
4992
4993 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4994 q = remote_query_supported_append (q, "swbreak+");
4995 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4996 q = remote_query_supported_append (q, "hwbreak+");
4997
4998 q = remote_query_supported_append (q, "qRelocInsn+");
4999
5000 if (packet_set_cmd_state (PACKET_fork_event_feature)
5001 != AUTO_BOOLEAN_FALSE)
5002 q = remote_query_supported_append (q, "fork-events+");
5003 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5004 != AUTO_BOOLEAN_FALSE)
5005 q = remote_query_supported_append (q, "vfork-events+");
5006 if (packet_set_cmd_state (PACKET_exec_event_feature)
5007 != AUTO_BOOLEAN_FALSE)
5008 q = remote_query_supported_append (q, "exec-events+");
5009
5010 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5011 q = remote_query_supported_append (q, "vContSupported+");
5012
5013 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5014 q = remote_query_supported_append (q, "QThreadEvents+");
5015
5016 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5017 q = remote_query_supported_append (q, "no-resumed+");
5018
5019 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5020 the qSupported:xmlRegisters=i386 handling. */
5021 if (remote_support_xml != NULL
5022 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5023 q = remote_query_supported_append (q, remote_support_xml);
5024
5025 q = reconcat (q, "qSupported:", q, (char *) NULL);
5026 putpkt (q);
5027
5028 do_cleanups (old_chain);
5029
5030 getpkt (&rs->buf, &rs->buf_size, 0);
5031
5032 /* If an error occured, warn, but do not return - just reset the
5033 buffer to empty and go on to disable features. */
5034 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5035 == PACKET_ERROR)
5036 {
5037 warning (_("Remote failure reply: %s"), rs->buf);
5038 rs->buf[0] = 0;
5039 }
5040 }
5041
5042 memset (seen, 0, sizeof (seen));
5043
5044 next = rs->buf;
5045 while (*next)
5046 {
5047 enum packet_support is_supported;
5048 char *p, *end, *name_end, *value;
5049
5050 /* First separate out this item from the rest of the packet. If
5051 there's another item after this, we overwrite the separator
5052 (terminated strings are much easier to work with). */
5053 p = next;
5054 end = strchr (p, ';');
5055 if (end == NULL)
5056 {
5057 end = p + strlen (p);
5058 next = end;
5059 }
5060 else
5061 {
5062 *end = '\0';
5063 next = end + 1;
5064
5065 if (end == p)
5066 {
5067 warning (_("empty item in \"qSupported\" response"));
5068 continue;
5069 }
5070 }
5071
5072 name_end = strchr (p, '=');
5073 if (name_end)
5074 {
5075 /* This is a name=value entry. */
5076 is_supported = PACKET_ENABLE;
5077 value = name_end + 1;
5078 *name_end = '\0';
5079 }
5080 else
5081 {
5082 value = NULL;
5083 switch (end[-1])
5084 {
5085 case '+':
5086 is_supported = PACKET_ENABLE;
5087 break;
5088
5089 case '-':
5090 is_supported = PACKET_DISABLE;
5091 break;
5092
5093 case '?':
5094 is_supported = PACKET_SUPPORT_UNKNOWN;
5095 break;
5096
5097 default:
5098 warning (_("unrecognized item \"%s\" "
5099 "in \"qSupported\" response"), p);
5100 continue;
5101 }
5102 end[-1] = '\0';
5103 }
5104
5105 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5106 if (strcmp (remote_protocol_features[i].name, p) == 0)
5107 {
5108 const struct protocol_feature *feature;
5109
5110 seen[i] = 1;
5111 feature = &remote_protocol_features[i];
5112 feature->func (feature, is_supported, value);
5113 break;
5114 }
5115 }
5116
5117 /* If we increased the packet size, make sure to increase the global
5118 buffer size also. We delay this until after parsing the entire
5119 qSupported packet, because this is the same buffer we were
5120 parsing. */
5121 if (rs->buf_size < rs->explicit_packet_size)
5122 {
5123 rs->buf_size = rs->explicit_packet_size;
5124 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5125 }
5126
5127 /* Handle the defaults for unmentioned features. */
5128 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5129 if (!seen[i])
5130 {
5131 const struct protocol_feature *feature;
5132
5133 feature = &remote_protocol_features[i];
5134 feature->func (feature, feature->default_support, NULL);
5135 }
5136 }
5137
5138 /* Serial QUIT handler for the remote serial descriptor.
5139
5140 Defers handling a Ctrl-C until we're done with the current
5141 command/response packet sequence, unless:
5142
5143 - We're setting up the connection. Don't send a remote interrupt
5144 request, as we're not fully synced yet. Quit immediately
5145 instead.
5146
5147 - The target has been resumed in the foreground
5148 (target_terminal::is_ours is false) with a synchronous resume
5149 packet, and we're blocked waiting for the stop reply, thus a
5150 Ctrl-C should be immediately sent to the target.
5151
5152 - We get a second Ctrl-C while still within the same serial read or
5153 write. In that case the serial is seemingly wedged --- offer to
5154 quit/disconnect.
5155
5156 - We see a second Ctrl-C without target response, after having
5157 previously interrupted the target. In that case the target/stub
5158 is probably wedged --- offer to quit/disconnect.
5159 */
5160
5161 static void
5162 remote_serial_quit_handler (void)
5163 {
5164 struct remote_state *rs = get_remote_state ();
5165
5166 if (check_quit_flag ())
5167 {
5168 /* If we're starting up, we're not fully synced yet. Quit
5169 immediately. */
5170 if (rs->starting_up)
5171 quit ();
5172 else if (rs->got_ctrlc_during_io)
5173 {
5174 if (query (_("The target is not responding to GDB commands.\n"
5175 "Stop debugging it? ")))
5176 remote_unpush_and_throw ();
5177 }
5178 /* If ^C has already been sent once, offer to disconnect. */
5179 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5180 interrupt_query ();
5181 /* All-stop protocol, and blocked waiting for stop reply. Send
5182 an interrupt request. */
5183 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5184 target_interrupt ();
5185 else
5186 rs->got_ctrlc_during_io = 1;
5187 }
5188 }
5189
5190 /* Remove any of the remote.c targets from target stack. Upper targets depend
5191 on it so remove them first. */
5192
5193 static void
5194 remote_unpush_target (void)
5195 {
5196 pop_all_targets_at_and_above (process_stratum);
5197 }
5198
5199 static void
5200 remote_unpush_and_throw (void)
5201 {
5202 remote_unpush_target ();
5203 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5204 }
5205
5206 void
5207 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5208 {
5209 struct remote_state *rs = get_remote_state ();
5210
5211 if (name == 0)
5212 error (_("To open a remote debug connection, you need to specify what\n"
5213 "serial device is attached to the remote system\n"
5214 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5215
5216 /* See FIXME above. */
5217 if (!target_async_permitted)
5218 wait_forever_enabled_p = 1;
5219
5220 /* If we're connected to a running target, target_preopen will kill it.
5221 Ask this question first, before target_preopen has a chance to kill
5222 anything. */
5223 if (rs->remote_desc != NULL && !have_inferiors ())
5224 {
5225 if (from_tty
5226 && !query (_("Already connected to a remote target. Disconnect? ")))
5227 error (_("Still connected."));
5228 }
5229
5230 /* Here the possibly existing remote target gets unpushed. */
5231 target_preopen (from_tty);
5232
5233 /* Make sure we send the passed signals list the next time we resume. */
5234 xfree (rs->last_pass_packet);
5235 rs->last_pass_packet = NULL;
5236
5237 /* Make sure we send the program signals list the next time we
5238 resume. */
5239 xfree (rs->last_program_signals_packet);
5240 rs->last_program_signals_packet = NULL;
5241
5242 remote_fileio_reset ();
5243 reopen_exec_file ();
5244 reread_symbols ();
5245
5246 rs->remote_desc = remote_serial_open (name);
5247 if (!rs->remote_desc)
5248 perror_with_name (name);
5249
5250 if (baud_rate != -1)
5251 {
5252 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5253 {
5254 /* The requested speed could not be set. Error out to
5255 top level after closing remote_desc. Take care to
5256 set remote_desc to NULL to avoid closing remote_desc
5257 more than once. */
5258 serial_close (rs->remote_desc);
5259 rs->remote_desc = NULL;
5260 perror_with_name (name);
5261 }
5262 }
5263
5264 serial_setparity (rs->remote_desc, serial_parity);
5265 serial_raw (rs->remote_desc);
5266
5267 /* If there is something sitting in the buffer we might take it as a
5268 response to a command, which would be bad. */
5269 serial_flush_input (rs->remote_desc);
5270
5271 if (from_tty)
5272 {
5273 puts_filtered ("Remote debugging using ");
5274 puts_filtered (name);
5275 puts_filtered ("\n");
5276 }
5277
5278 remote_target *target
5279 = extended_p ? &extended_remote_ops : &remote_ops;
5280 push_target (target); /* Switch to using remote target now. */
5281
5282 /* Register extra event sources in the event loop. */
5283 remote_async_inferior_event_token
5284 = create_async_event_handler (remote_async_inferior_event_handler,
5285 NULL);
5286 rs->notif_state = remote_notif_state_allocate ();
5287
5288 /* Reset the target state; these things will be queried either by
5289 remote_query_supported or as they are needed. */
5290 reset_all_packet_configs_support ();
5291 rs->cached_wait_status = 0;
5292 rs->explicit_packet_size = 0;
5293 rs->noack_mode = 0;
5294 rs->extended = extended_p;
5295 rs->waiting_for_stop_reply = 0;
5296 rs->ctrlc_pending_p = 0;
5297 rs->got_ctrlc_during_io = 0;
5298
5299 rs->general_thread = not_sent_ptid;
5300 rs->continue_thread = not_sent_ptid;
5301 rs->remote_traceframe_number = -1;
5302
5303 rs->last_resume_exec_dir = EXEC_FORWARD;
5304
5305 /* Probe for ability to use "ThreadInfo" query, as required. */
5306 rs->use_threadinfo_query = 1;
5307 rs->use_threadextra_query = 1;
5308
5309 readahead_cache_invalidate ();
5310
5311 if (target_async_permitted)
5312 {
5313 /* FIXME: cagney/1999-09-23: During the initial connection it is
5314 assumed that the target is already ready and able to respond to
5315 requests. Unfortunately remote_start_remote() eventually calls
5316 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5317 around this. Eventually a mechanism that allows
5318 wait_for_inferior() to expect/get timeouts will be
5319 implemented. */
5320 wait_forever_enabled_p = 0;
5321 }
5322
5323 /* First delete any symbols previously loaded from shared libraries. */
5324 no_shared_libraries (NULL, 0);
5325
5326 /* Start afresh. */
5327 init_thread_list ();
5328
5329 /* Start the remote connection. If error() or QUIT, discard this
5330 target (we'd otherwise be in an inconsistent state) and then
5331 propogate the error on up the exception chain. This ensures that
5332 the caller doesn't stumble along blindly assuming that the
5333 function succeeded. The CLI doesn't have this problem but other
5334 UI's, such as MI do.
5335
5336 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5337 this function should return an error indication letting the
5338 caller restore the previous state. Unfortunately the command
5339 ``target remote'' is directly wired to this function making that
5340 impossible. On a positive note, the CLI side of this problem has
5341 been fixed - the function set_cmd_context() makes it possible for
5342 all the ``target ....'' commands to share a common callback
5343 function. See cli-dump.c. */
5344 {
5345
5346 TRY
5347 {
5348 target->start_remote (from_tty, extended_p);
5349 }
5350 CATCH (ex, RETURN_MASK_ALL)
5351 {
5352 /* Pop the partially set up target - unless something else did
5353 already before throwing the exception. */
5354 if (rs->remote_desc != NULL)
5355 remote_unpush_target ();
5356 if (target_async_permitted)
5357 wait_forever_enabled_p = 1;
5358 throw_exception (ex);
5359 }
5360 END_CATCH
5361 }
5362
5363 remote_btrace_reset ();
5364
5365 if (target_async_permitted)
5366 wait_forever_enabled_p = 1;
5367 }
5368
5369 /* Detach the specified process. */
5370
5371 static void
5372 remote_detach_pid (int pid)
5373 {
5374 struct remote_state *rs = get_remote_state ();
5375
5376 if (remote_multi_process_p (rs))
5377 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5378 else
5379 strcpy (rs->buf, "D");
5380
5381 putpkt (rs->buf);
5382 getpkt (&rs->buf, &rs->buf_size, 0);
5383
5384 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5385 ;
5386 else if (rs->buf[0] == '\0')
5387 error (_("Remote doesn't know how to detach"));
5388 else
5389 error (_("Can't detach process."));
5390 }
5391
5392 /* This detaches a program to which we previously attached, using
5393 inferior_ptid to identify the process. After this is done, GDB
5394 can be used to debug some other program. We better not have left
5395 any breakpoints in the target program or it'll die when it hits
5396 one. */
5397
5398 static void
5399 remote_detach_1 (int from_tty, inferior *inf)
5400 {
5401 int pid = ptid_get_pid (inferior_ptid);
5402 struct remote_state *rs = get_remote_state ();
5403 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5404 int is_fork_parent;
5405
5406 if (!target_has_execution)
5407 error (_("No process to detach from."));
5408
5409 target_announce_detach (from_tty);
5410
5411 /* Tell the remote target to detach. */
5412 remote_detach_pid (pid);
5413
5414 /* Exit only if this is the only active inferior. */
5415 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5416 puts_filtered (_("Ending remote debugging.\n"));
5417
5418 /* Check to see if we are detaching a fork parent. Note that if we
5419 are detaching a fork child, tp == NULL. */
5420 is_fork_parent = (tp != NULL
5421 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5422
5423 /* If doing detach-on-fork, we don't mourn, because that will delete
5424 breakpoints that should be available for the followed inferior. */
5425 if (!is_fork_parent)
5426 {
5427 /* Save the pid as a string before mourning, since that will
5428 unpush the remote target, and we need the string after. */
5429 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5430
5431 target_mourn_inferior (inferior_ptid);
5432 if (print_inferior_events)
5433 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5434 inf->num, infpid.c_str ());
5435 }
5436 else
5437 {
5438 inferior_ptid = null_ptid;
5439 detach_inferior (pid);
5440 }
5441 }
5442
5443 void
5444 remote_target::detach (inferior *inf, int from_tty)
5445 {
5446 remote_detach_1 (from_tty, inf);
5447 }
5448
5449 void
5450 extended_remote_target::detach (inferior *inf, int from_tty)
5451 {
5452 remote_detach_1 (from_tty, inf);
5453 }
5454
5455 /* Target follow-fork function for remote targets. On entry, and
5456 at return, the current inferior is the fork parent.
5457
5458 Note that although this is currently only used for extended-remote,
5459 it is named remote_follow_fork in anticipation of using it for the
5460 remote target as well. */
5461
5462 int
5463 remote_target::follow_fork (int follow_child, int detach_fork)
5464 {
5465 struct remote_state *rs = get_remote_state ();
5466 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5467
5468 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5469 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5470 {
5471 /* When following the parent and detaching the child, we detach
5472 the child here. For the case of following the child and
5473 detaching the parent, the detach is done in the target-
5474 independent follow fork code in infrun.c. We can't use
5475 target_detach when detaching an unfollowed child because
5476 the client side doesn't know anything about the child. */
5477 if (detach_fork && !follow_child)
5478 {
5479 /* Detach the fork child. */
5480 ptid_t child_ptid;
5481 pid_t child_pid;
5482
5483 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5484 child_pid = ptid_get_pid (child_ptid);
5485
5486 remote_detach_pid (child_pid);
5487 }
5488 }
5489 return 0;
5490 }
5491
5492 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5493 in the program space of the new inferior. On entry and at return the
5494 current inferior is the exec'ing inferior. INF is the new exec'd
5495 inferior, which may be the same as the exec'ing inferior unless
5496 follow-exec-mode is "new". */
5497
5498 void
5499 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5500 {
5501 /* We know that this is a target file name, so if it has the "target:"
5502 prefix we strip it off before saving it in the program space. */
5503 if (is_target_filename (execd_pathname))
5504 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5505
5506 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5507 }
5508
5509 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5510
5511 void
5512 remote_target::disconnect (const char *args, int from_tty)
5513 {
5514 if (args)
5515 error (_("Argument given to \"disconnect\" when remotely debugging."));
5516
5517 /* Make sure we unpush even the extended remote targets. Calling
5518 target_mourn_inferior won't unpush, and remote_mourn won't
5519 unpush if there is more than one inferior left. */
5520 unpush_target (this);
5521 generic_mourn_inferior ();
5522
5523 if (from_tty)
5524 puts_filtered ("Ending remote debugging.\n");
5525 }
5526
5527 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5528 be chatty about it. */
5529
5530 void
5531 extended_remote_target::attach (const char *args, int from_tty)
5532 {
5533 struct remote_state *rs = get_remote_state ();
5534 int pid;
5535 char *wait_status = NULL;
5536
5537 pid = parse_pid_to_attach (args);
5538
5539 /* Remote PID can be freely equal to getpid, do not check it here the same
5540 way as in other targets. */
5541
5542 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5543 error (_("This target does not support attaching to a process"));
5544
5545 if (from_tty)
5546 {
5547 char *exec_file = get_exec_file (0);
5548
5549 if (exec_file)
5550 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5551 target_pid_to_str (pid_to_ptid (pid)));
5552 else
5553 printf_unfiltered (_("Attaching to %s\n"),
5554 target_pid_to_str (pid_to_ptid (pid)));
5555
5556 gdb_flush (gdb_stdout);
5557 }
5558
5559 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5560 putpkt (rs->buf);
5561 getpkt (&rs->buf, &rs->buf_size, 0);
5562
5563 switch (packet_ok (rs->buf,
5564 &remote_protocol_packets[PACKET_vAttach]))
5565 {
5566 case PACKET_OK:
5567 if (!target_is_non_stop_p ())
5568 {
5569 /* Save the reply for later. */
5570 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5571 strcpy (wait_status, rs->buf);
5572 }
5573 else if (strcmp (rs->buf, "OK") != 0)
5574 error (_("Attaching to %s failed with: %s"),
5575 target_pid_to_str (pid_to_ptid (pid)),
5576 rs->buf);
5577 break;
5578 case PACKET_UNKNOWN:
5579 error (_("This target does not support attaching to a process"));
5580 default:
5581 error (_("Attaching to %s failed"),
5582 target_pid_to_str (pid_to_ptid (pid)));
5583 }
5584
5585 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5586
5587 inferior_ptid = pid_to_ptid (pid);
5588
5589 if (target_is_non_stop_p ())
5590 {
5591 struct thread_info *thread;
5592
5593 /* Get list of threads. */
5594 update_thread_list ();
5595
5596 thread = first_thread_of_process (pid);
5597 if (thread)
5598 inferior_ptid = thread->ptid;
5599 else
5600 inferior_ptid = pid_to_ptid (pid);
5601
5602 /* Invalidate our notion of the remote current thread. */
5603 record_currthread (rs, minus_one_ptid);
5604 }
5605 else
5606 {
5607 /* Now, if we have thread information, update inferior_ptid. */
5608 inferior_ptid = remote_current_thread (inferior_ptid);
5609
5610 /* Add the main thread to the thread list. */
5611 thread_info *thr = add_thread_silent (inferior_ptid);
5612 /* Don't consider the thread stopped until we've processed the
5613 saved stop reply. */
5614 set_executing (thr->ptid, true);
5615 }
5616
5617 /* Next, if the target can specify a description, read it. We do
5618 this before anything involving memory or registers. */
5619 target_find_description ();
5620
5621 if (!target_is_non_stop_p ())
5622 {
5623 /* Use the previously fetched status. */
5624 gdb_assert (wait_status != NULL);
5625
5626 if (target_can_async_p ())
5627 {
5628 struct notif_event *reply
5629 = remote_notif_parse (&notif_client_stop, wait_status);
5630
5631 push_stop_reply ((struct stop_reply *) reply);
5632
5633 target_async (1);
5634 }
5635 else
5636 {
5637 gdb_assert (wait_status != NULL);
5638 strcpy (rs->buf, wait_status);
5639 rs->cached_wait_status = 1;
5640 }
5641 }
5642 else
5643 gdb_assert (wait_status == NULL);
5644 }
5645
5646 /* Implementation of the to_post_attach method. */
5647
5648 void
5649 extended_remote_target::post_attach (int pid)
5650 {
5651 /* Get text, data & bss offsets. */
5652 get_offsets ();
5653
5654 /* In certain cases GDB might not have had the chance to start
5655 symbol lookup up until now. This could happen if the debugged
5656 binary is not using shared libraries, the vsyscall page is not
5657 present (on Linux) and the binary itself hadn't changed since the
5658 debugging process was started. */
5659 if (symfile_objfile != NULL)
5660 remote_check_symbols();
5661 }
5662
5663 \f
5664 /* Check for the availability of vCont. This function should also check
5665 the response. */
5666
5667 static void
5668 remote_vcont_probe (struct remote_state *rs)
5669 {
5670 char *buf;
5671
5672 strcpy (rs->buf, "vCont?");
5673 putpkt (rs->buf);
5674 getpkt (&rs->buf, &rs->buf_size, 0);
5675 buf = rs->buf;
5676
5677 /* Make sure that the features we assume are supported. */
5678 if (startswith (buf, "vCont"))
5679 {
5680 char *p = &buf[5];
5681 int support_c, support_C;
5682
5683 rs->supports_vCont.s = 0;
5684 rs->supports_vCont.S = 0;
5685 support_c = 0;
5686 support_C = 0;
5687 rs->supports_vCont.t = 0;
5688 rs->supports_vCont.r = 0;
5689 while (p && *p == ';')
5690 {
5691 p++;
5692 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5693 rs->supports_vCont.s = 1;
5694 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5695 rs->supports_vCont.S = 1;
5696 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5697 support_c = 1;
5698 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5699 support_C = 1;
5700 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5701 rs->supports_vCont.t = 1;
5702 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5703 rs->supports_vCont.r = 1;
5704
5705 p = strchr (p, ';');
5706 }
5707
5708 /* If c, and C are not all supported, we can't use vCont. Clearing
5709 BUF will make packet_ok disable the packet. */
5710 if (!support_c || !support_C)
5711 buf[0] = 0;
5712 }
5713
5714 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5715 }
5716
5717 /* Helper function for building "vCont" resumptions. Write a
5718 resumption to P. ENDP points to one-passed-the-end of the buffer
5719 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5720 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5721 resumed thread should be single-stepped and/or signalled. If PTID
5722 equals minus_one_ptid, then all threads are resumed; if PTID
5723 represents a process, then all threads of the process are resumed;
5724 the thread to be stepped and/or signalled is given in the global
5725 INFERIOR_PTID. */
5726
5727 static char *
5728 append_resumption (char *p, char *endp,
5729 ptid_t ptid, int step, enum gdb_signal siggnal)
5730 {
5731 struct remote_state *rs = get_remote_state ();
5732
5733 if (step && siggnal != GDB_SIGNAL_0)
5734 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5735 else if (step
5736 /* GDB is willing to range step. */
5737 && use_range_stepping
5738 /* Target supports range stepping. */
5739 && rs->supports_vCont.r
5740 /* We don't currently support range stepping multiple
5741 threads with a wildcard (though the protocol allows it,
5742 so stubs shouldn't make an active effort to forbid
5743 it). */
5744 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5745 {
5746 struct thread_info *tp;
5747
5748 if (ptid_equal (ptid, minus_one_ptid))
5749 {
5750 /* If we don't know about the target thread's tid, then
5751 we're resuming magic_null_ptid (see caller). */
5752 tp = find_thread_ptid (magic_null_ptid);
5753 }
5754 else
5755 tp = find_thread_ptid (ptid);
5756 gdb_assert (tp != NULL);
5757
5758 if (tp->control.may_range_step)
5759 {
5760 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5761
5762 p += xsnprintf (p, endp - p, ";r%s,%s",
5763 phex_nz (tp->control.step_range_start,
5764 addr_size),
5765 phex_nz (tp->control.step_range_end,
5766 addr_size));
5767 }
5768 else
5769 p += xsnprintf (p, endp - p, ";s");
5770 }
5771 else if (step)
5772 p += xsnprintf (p, endp - p, ";s");
5773 else if (siggnal != GDB_SIGNAL_0)
5774 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5775 else
5776 p += xsnprintf (p, endp - p, ";c");
5777
5778 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5779 {
5780 ptid_t nptid;
5781
5782 /* All (-1) threads of process. */
5783 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5784
5785 p += xsnprintf (p, endp - p, ":");
5786 p = write_ptid (p, endp, nptid);
5787 }
5788 else if (!ptid_equal (ptid, minus_one_ptid))
5789 {
5790 p += xsnprintf (p, endp - p, ":");
5791 p = write_ptid (p, endp, ptid);
5792 }
5793
5794 return p;
5795 }
5796
5797 /* Clear the thread's private info on resume. */
5798
5799 static void
5800 resume_clear_thread_private_info (struct thread_info *thread)
5801 {
5802 if (thread->priv != NULL)
5803 {
5804 remote_thread_info *priv = get_remote_thread_info (thread);
5805
5806 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5807 priv->watch_data_address = 0;
5808 }
5809 }
5810
5811 /* Append a vCont continue-with-signal action for threads that have a
5812 non-zero stop signal. */
5813
5814 static char *
5815 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5816 {
5817 struct thread_info *thread;
5818
5819 ALL_NON_EXITED_THREADS (thread)
5820 if (ptid_match (thread->ptid, ptid)
5821 && !ptid_equal (inferior_ptid, thread->ptid)
5822 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5823 {
5824 p = append_resumption (p, endp, thread->ptid,
5825 0, thread->suspend.stop_signal);
5826 thread->suspend.stop_signal = GDB_SIGNAL_0;
5827 resume_clear_thread_private_info (thread);
5828 }
5829
5830 return p;
5831 }
5832
5833 /* Set the target running, using the packets that use Hc
5834 (c/s/C/S). */
5835
5836 static void
5837 remote_resume_with_hc (struct target_ops *ops,
5838 ptid_t ptid, int step, enum gdb_signal siggnal)
5839 {
5840 struct remote_state *rs = get_remote_state ();
5841 struct thread_info *thread;
5842 char *buf;
5843
5844 rs->last_sent_signal = siggnal;
5845 rs->last_sent_step = step;
5846
5847 /* The c/s/C/S resume packets use Hc, so set the continue
5848 thread. */
5849 if (ptid_equal (ptid, minus_one_ptid))
5850 set_continue_thread (any_thread_ptid);
5851 else
5852 set_continue_thread (ptid);
5853
5854 ALL_NON_EXITED_THREADS (thread)
5855 resume_clear_thread_private_info (thread);
5856
5857 buf = rs->buf;
5858 if (execution_direction == EXEC_REVERSE)
5859 {
5860 /* We don't pass signals to the target in reverse exec mode. */
5861 if (info_verbose && siggnal != GDB_SIGNAL_0)
5862 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5863 siggnal);
5864
5865 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5866 error (_("Remote reverse-step not supported."));
5867 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5868 error (_("Remote reverse-continue not supported."));
5869
5870 strcpy (buf, step ? "bs" : "bc");
5871 }
5872 else if (siggnal != GDB_SIGNAL_0)
5873 {
5874 buf[0] = step ? 'S' : 'C';
5875 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5876 buf[2] = tohex (((int) siggnal) & 0xf);
5877 buf[3] = '\0';
5878 }
5879 else
5880 strcpy (buf, step ? "s" : "c");
5881
5882 putpkt (buf);
5883 }
5884
5885 /* Resume the remote inferior by using a "vCont" packet. The thread
5886 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5887 resumed thread should be single-stepped and/or signalled. If PTID
5888 equals minus_one_ptid, then all threads are resumed; the thread to
5889 be stepped and/or signalled is given in the global INFERIOR_PTID.
5890 This function returns non-zero iff it resumes the inferior.
5891
5892 This function issues a strict subset of all possible vCont commands
5893 at the moment. */
5894
5895 static int
5896 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5897 {
5898 struct remote_state *rs = get_remote_state ();
5899 char *p;
5900 char *endp;
5901
5902 /* No reverse execution actions defined for vCont. */
5903 if (execution_direction == EXEC_REVERSE)
5904 return 0;
5905
5906 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5907 remote_vcont_probe (rs);
5908
5909 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5910 return 0;
5911
5912 p = rs->buf;
5913 endp = rs->buf + get_remote_packet_size ();
5914
5915 /* If we could generate a wider range of packets, we'd have to worry
5916 about overflowing BUF. Should there be a generic
5917 "multi-part-packet" packet? */
5918
5919 p += xsnprintf (p, endp - p, "vCont");
5920
5921 if (ptid_equal (ptid, magic_null_ptid))
5922 {
5923 /* MAGIC_NULL_PTID means that we don't have any active threads,
5924 so we don't have any TID numbers the inferior will
5925 understand. Make sure to only send forms that do not specify
5926 a TID. */
5927 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5928 }
5929 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5930 {
5931 /* Resume all threads (of all processes, or of a single
5932 process), with preference for INFERIOR_PTID. This assumes
5933 inferior_ptid belongs to the set of all threads we are about
5934 to resume. */
5935 if (step || siggnal != GDB_SIGNAL_0)
5936 {
5937 /* Step inferior_ptid, with or without signal. */
5938 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5939 }
5940
5941 /* Also pass down any pending signaled resumption for other
5942 threads not the current. */
5943 p = append_pending_thread_resumptions (p, endp, ptid);
5944
5945 /* And continue others without a signal. */
5946 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5947 }
5948 else
5949 {
5950 /* Scheduler locking; resume only PTID. */
5951 append_resumption (p, endp, ptid, step, siggnal);
5952 }
5953
5954 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5955 putpkt (rs->buf);
5956
5957 if (target_is_non_stop_p ())
5958 {
5959 /* In non-stop, the stub replies to vCont with "OK". The stop
5960 reply will be reported asynchronously by means of a `%Stop'
5961 notification. */
5962 getpkt (&rs->buf, &rs->buf_size, 0);
5963 if (strcmp (rs->buf, "OK") != 0)
5964 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5965 }
5966
5967 return 1;
5968 }
5969
5970 /* Tell the remote machine to resume. */
5971
5972 void
5973 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5974 {
5975 struct remote_state *rs = get_remote_state ();
5976
5977 /* When connected in non-stop mode, the core resumes threads
5978 individually. Resuming remote threads directly in target_resume
5979 would thus result in sending one packet per thread. Instead, to
5980 minimize roundtrip latency, here we just store the resume
5981 request; the actual remote resumption will be done in
5982 target_commit_resume / remote_commit_resume, where we'll be able
5983 to do vCont action coalescing. */
5984 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
5985 {
5986 remote_thread_info *remote_thr;
5987
5988 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5989 remote_thr = get_remote_thread_info (inferior_ptid);
5990 else
5991 remote_thr = get_remote_thread_info (ptid);
5992
5993 remote_thr->last_resume_step = step;
5994 remote_thr->last_resume_sig = siggnal;
5995 return;
5996 }
5997
5998 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5999 (explained in remote-notif.c:handle_notification) so
6000 remote_notif_process is not called. We need find a place where
6001 it is safe to start a 'vNotif' sequence. It is good to do it
6002 before resuming inferior, because inferior was stopped and no RSP
6003 traffic at that moment. */
6004 if (!target_is_non_stop_p ())
6005 remote_notif_process (rs->notif_state, &notif_client_stop);
6006
6007 rs->last_resume_exec_dir = ::execution_direction;
6008
6009 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6010 if (!remote_resume_with_vcont (ptid, step, siggnal))
6011 remote_resume_with_hc (this, ptid, step, siggnal);
6012
6013 /* We are about to start executing the inferior, let's register it
6014 with the event loop. NOTE: this is the one place where all the
6015 execution commands end up. We could alternatively do this in each
6016 of the execution commands in infcmd.c. */
6017 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6018 into infcmd.c in order to allow inferior function calls to work
6019 NOT asynchronously. */
6020 if (target_can_async_p ())
6021 target_async (1);
6022
6023 /* We've just told the target to resume. The remote server will
6024 wait for the inferior to stop, and then send a stop reply. In
6025 the mean time, we can't start another command/query ourselves
6026 because the stub wouldn't be ready to process it. This applies
6027 only to the base all-stop protocol, however. In non-stop (which
6028 only supports vCont), the stub replies with an "OK", and is
6029 immediate able to process further serial input. */
6030 if (!target_is_non_stop_p ())
6031 rs->waiting_for_stop_reply = 1;
6032 }
6033
6034 static void check_pending_events_prevent_wildcard_vcont
6035 (int *may_global_wildcard_vcont);
6036 static int is_pending_fork_parent_thread (struct thread_info *thread);
6037
6038 /* Private per-inferior info for target remote processes. */
6039
6040 struct remote_inferior : public private_inferior
6041 {
6042 /* Whether we can send a wildcard vCont for this process. */
6043 bool may_wildcard_vcont = true;
6044 };
6045
6046 /* Get the remote private inferior data associated to INF. */
6047
6048 static remote_inferior *
6049 get_remote_inferior (inferior *inf)
6050 {
6051 if (inf->priv == NULL)
6052 inf->priv.reset (new remote_inferior);
6053
6054 return static_cast<remote_inferior *> (inf->priv.get ());
6055 }
6056
6057 /* Structure used to track the construction of a vCont packet in the
6058 outgoing packet buffer. This is used to send multiple vCont
6059 packets if we have more actions than would fit a single packet. */
6060
6061 struct vcont_builder
6062 {
6063 /* Pointer to the first action. P points here if no action has been
6064 appended yet. */
6065 char *first_action;
6066
6067 /* Where the next action will be appended. */
6068 char *p;
6069
6070 /* The end of the buffer. Must never write past this. */
6071 char *endp;
6072 };
6073
6074 /* Prepare the outgoing buffer for a new vCont packet. */
6075
6076 static void
6077 vcont_builder_restart (struct vcont_builder *builder)
6078 {
6079 struct remote_state *rs = get_remote_state ();
6080
6081 builder->p = rs->buf;
6082 builder->endp = rs->buf + get_remote_packet_size ();
6083 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
6084 builder->first_action = builder->p;
6085 }
6086
6087 /* If the vCont packet being built has any action, send it to the
6088 remote end. */
6089
6090 static void
6091 vcont_builder_flush (struct vcont_builder *builder)
6092 {
6093 struct remote_state *rs;
6094
6095 if (builder->p == builder->first_action)
6096 return;
6097
6098 rs = get_remote_state ();
6099 putpkt (rs->buf);
6100 getpkt (&rs->buf, &rs->buf_size, 0);
6101 if (strcmp (rs->buf, "OK") != 0)
6102 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6103 }
6104
6105 /* The largest action is range-stepping, with its two addresses. This
6106 is more than sufficient. If a new, bigger action is created, it'll
6107 quickly trigger a failed assertion in append_resumption (and we'll
6108 just bump this). */
6109 #define MAX_ACTION_SIZE 200
6110
6111 /* Append a new vCont action in the outgoing packet being built. If
6112 the action doesn't fit the packet along with previous actions, push
6113 what we've got so far to the remote end and start over a new vCont
6114 packet (with the new action). */
6115
6116 static void
6117 vcont_builder_push_action (struct vcont_builder *builder,
6118 ptid_t ptid, int step, enum gdb_signal siggnal)
6119 {
6120 char buf[MAX_ACTION_SIZE + 1];
6121 char *endp;
6122 size_t rsize;
6123
6124 endp = append_resumption (buf, buf + sizeof (buf),
6125 ptid, step, siggnal);
6126
6127 /* Check whether this new action would fit in the vCont packet along
6128 with previous actions. If not, send what we've got so far and
6129 start a new vCont packet. */
6130 rsize = endp - buf;
6131 if (rsize > builder->endp - builder->p)
6132 {
6133 vcont_builder_flush (builder);
6134 vcont_builder_restart (builder);
6135
6136 /* Should now fit. */
6137 gdb_assert (rsize <= builder->endp - builder->p);
6138 }
6139
6140 memcpy (builder->p, buf, rsize);
6141 builder->p += rsize;
6142 *builder->p = '\0';
6143 }
6144
6145 /* to_commit_resume implementation. */
6146
6147 void
6148 remote_target::commit_resume ()
6149 {
6150 struct inferior *inf;
6151 struct thread_info *tp;
6152 int any_process_wildcard;
6153 int may_global_wildcard_vcont;
6154 struct vcont_builder vcont_builder;
6155
6156 /* If connected in all-stop mode, we'd send the remote resume
6157 request directly from remote_resume. Likewise if
6158 reverse-debugging, as there are no defined vCont actions for
6159 reverse execution. */
6160 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6161 return;
6162
6163 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6164 instead of resuming all threads of each process individually.
6165 However, if any thread of a process must remain halted, we can't
6166 send wildcard resumes and must send one action per thread.
6167
6168 Care must be taken to not resume threads/processes the server
6169 side already told us are stopped, but the core doesn't know about
6170 yet, because the events are still in the vStopped notification
6171 queue. For example:
6172
6173 #1 => vCont s:p1.1;c
6174 #2 <= OK
6175 #3 <= %Stopped T05 p1.1
6176 #4 => vStopped
6177 #5 <= T05 p1.2
6178 #6 => vStopped
6179 #7 <= OK
6180 #8 (infrun handles the stop for p1.1 and continues stepping)
6181 #9 => vCont s:p1.1;c
6182
6183 The last vCont above would resume thread p1.2 by mistake, because
6184 the server has no idea that the event for p1.2 had not been
6185 handled yet.
6186
6187 The server side must similarly ignore resume actions for the
6188 thread that has a pending %Stopped notification (and any other
6189 threads with events pending), until GDB acks the notification
6190 with vStopped. Otherwise, e.g., the following case is
6191 mishandled:
6192
6193 #1 => g (or any other packet)
6194 #2 <= [registers]
6195 #3 <= %Stopped T05 p1.2
6196 #4 => vCont s:p1.1;c
6197 #5 <= OK
6198
6199 Above, the server must not resume thread p1.2. GDB can't know
6200 that p1.2 stopped until it acks the %Stopped notification, and
6201 since from GDB's perspective all threads should be running, it
6202 sends a "c" action.
6203
6204 Finally, special care must also be given to handling fork/vfork
6205 events. A (v)fork event actually tells us that two processes
6206 stopped -- the parent and the child. Until we follow the fork,
6207 we must not resume the child. Therefore, if we have a pending
6208 fork follow, we must not send a global wildcard resume action
6209 (vCont;c). We can still send process-wide wildcards though. */
6210
6211 /* Start by assuming a global wildcard (vCont;c) is possible. */
6212 may_global_wildcard_vcont = 1;
6213
6214 /* And assume every process is individually wildcard-able too. */
6215 ALL_NON_EXITED_INFERIORS (inf)
6216 {
6217 remote_inferior *priv = get_remote_inferior (inf);
6218
6219 priv->may_wildcard_vcont = true;
6220 }
6221
6222 /* Check for any pending events (not reported or processed yet) and
6223 disable process and global wildcard resumes appropriately. */
6224 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6225
6226 ALL_NON_EXITED_THREADS (tp)
6227 {
6228 /* If a thread of a process is not meant to be resumed, then we
6229 can't wildcard that process. */
6230 if (!tp->executing)
6231 {
6232 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6233
6234 /* And if we can't wildcard a process, we can't wildcard
6235 everything either. */
6236 may_global_wildcard_vcont = 0;
6237 continue;
6238 }
6239
6240 /* If a thread is the parent of an unfollowed fork, then we
6241 can't do a global wildcard, as that would resume the fork
6242 child. */
6243 if (is_pending_fork_parent_thread (tp))
6244 may_global_wildcard_vcont = 0;
6245 }
6246
6247 /* Now let's build the vCont packet(s). Actions must be appended
6248 from narrower to wider scopes (thread -> process -> global). If
6249 we end up with too many actions for a single packet vcont_builder
6250 flushes the current vCont packet to the remote side and starts a
6251 new one. */
6252 vcont_builder_restart (&vcont_builder);
6253
6254 /* Threads first. */
6255 ALL_NON_EXITED_THREADS (tp)
6256 {
6257 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6258
6259 if (!tp->executing || remote_thr->vcont_resumed)
6260 continue;
6261
6262 gdb_assert (!thread_is_in_step_over_chain (tp));
6263
6264 if (!remote_thr->last_resume_step
6265 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6266 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6267 {
6268 /* We'll send a wildcard resume instead. */
6269 remote_thr->vcont_resumed = 1;
6270 continue;
6271 }
6272
6273 vcont_builder_push_action (&vcont_builder, tp->ptid,
6274 remote_thr->last_resume_step,
6275 remote_thr->last_resume_sig);
6276 remote_thr->vcont_resumed = 1;
6277 }
6278
6279 /* Now check whether we can send any process-wide wildcard. This is
6280 to avoid sending a global wildcard in the case nothing is
6281 supposed to be resumed. */
6282 any_process_wildcard = 0;
6283
6284 ALL_NON_EXITED_INFERIORS (inf)
6285 {
6286 if (get_remote_inferior (inf)->may_wildcard_vcont)
6287 {
6288 any_process_wildcard = 1;
6289 break;
6290 }
6291 }
6292
6293 if (any_process_wildcard)
6294 {
6295 /* If all processes are wildcard-able, then send a single "c"
6296 action, otherwise, send an "all (-1) threads of process"
6297 continue action for each running process, if any. */
6298 if (may_global_wildcard_vcont)
6299 {
6300 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6301 0, GDB_SIGNAL_0);
6302 }
6303 else
6304 {
6305 ALL_NON_EXITED_INFERIORS (inf)
6306 {
6307 if (get_remote_inferior (inf)->may_wildcard_vcont)
6308 {
6309 vcont_builder_push_action (&vcont_builder,
6310 pid_to_ptid (inf->pid),
6311 0, GDB_SIGNAL_0);
6312 }
6313 }
6314 }
6315 }
6316
6317 vcont_builder_flush (&vcont_builder);
6318 }
6319
6320 \f
6321
6322 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6323 thread, all threads of a remote process, or all threads of all
6324 processes. */
6325
6326 static void
6327 remote_stop_ns (ptid_t ptid)
6328 {
6329 struct remote_state *rs = get_remote_state ();
6330 char *p = rs->buf;
6331 char *endp = rs->buf + get_remote_packet_size ();
6332
6333 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6334 remote_vcont_probe (rs);
6335
6336 if (!rs->supports_vCont.t)
6337 error (_("Remote server does not support stopping threads"));
6338
6339 if (ptid_equal (ptid, minus_one_ptid)
6340 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6341 p += xsnprintf (p, endp - p, "vCont;t");
6342 else
6343 {
6344 ptid_t nptid;
6345
6346 p += xsnprintf (p, endp - p, "vCont;t:");
6347
6348 if (ptid_is_pid (ptid))
6349 /* All (-1) threads of process. */
6350 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6351 else
6352 {
6353 /* Small optimization: if we already have a stop reply for
6354 this thread, no use in telling the stub we want this
6355 stopped. */
6356 if (peek_stop_reply (ptid))
6357 return;
6358
6359 nptid = ptid;
6360 }
6361
6362 write_ptid (p, endp, nptid);
6363 }
6364
6365 /* In non-stop, we get an immediate OK reply. The stop reply will
6366 come in asynchronously by notification. */
6367 putpkt (rs->buf);
6368 getpkt (&rs->buf, &rs->buf_size, 0);
6369 if (strcmp (rs->buf, "OK") != 0)
6370 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6371 }
6372
6373 /* All-stop version of target_interrupt. Sends a break or a ^C to
6374 interrupt the remote target. It is undefined which thread of which
6375 process reports the interrupt. */
6376
6377 static void
6378 remote_interrupt_as (void)
6379 {
6380 struct remote_state *rs = get_remote_state ();
6381
6382 rs->ctrlc_pending_p = 1;
6383
6384 /* If the inferior is stopped already, but the core didn't know
6385 about it yet, just ignore the request. The cached wait status
6386 will be collected in remote_wait. */
6387 if (rs->cached_wait_status)
6388 return;
6389
6390 /* Send interrupt_sequence to remote target. */
6391 send_interrupt_sequence ();
6392 }
6393
6394 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6395 the remote target. It is undefined which thread of which process
6396 reports the interrupt. Throws an error if the packet is not
6397 supported by the server. */
6398
6399 static void
6400 remote_interrupt_ns (void)
6401 {
6402 struct remote_state *rs = get_remote_state ();
6403 char *p = rs->buf;
6404 char *endp = rs->buf + get_remote_packet_size ();
6405
6406 xsnprintf (p, endp - p, "vCtrlC");
6407
6408 /* In non-stop, we get an immediate OK reply. The stop reply will
6409 come in asynchronously by notification. */
6410 putpkt (rs->buf);
6411 getpkt (&rs->buf, &rs->buf_size, 0);
6412
6413 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6414 {
6415 case PACKET_OK:
6416 break;
6417 case PACKET_UNKNOWN:
6418 error (_("No support for interrupting the remote target."));
6419 case PACKET_ERROR:
6420 error (_("Interrupting target failed: %s"), rs->buf);
6421 }
6422 }
6423
6424 /* Implement the to_stop function for the remote targets. */
6425
6426 void
6427 remote_target::stop (ptid_t ptid)
6428 {
6429 if (remote_debug)
6430 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6431
6432 if (target_is_non_stop_p ())
6433 remote_stop_ns (ptid);
6434 else
6435 {
6436 /* We don't currently have a way to transparently pause the
6437 remote target in all-stop mode. Interrupt it instead. */
6438 remote_interrupt_as ();
6439 }
6440 }
6441
6442 /* Implement the to_interrupt function for the remote targets. */
6443
6444 void
6445 remote_target::interrupt ()
6446 {
6447 if (remote_debug)
6448 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6449
6450 if (target_is_non_stop_p ())
6451 remote_interrupt_ns ();
6452 else
6453 remote_interrupt_as ();
6454 }
6455
6456 /* Implement the to_pass_ctrlc function for the remote targets. */
6457
6458 void
6459 remote_target::pass_ctrlc ()
6460 {
6461 struct remote_state *rs = get_remote_state ();
6462
6463 if (remote_debug)
6464 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6465
6466 /* If we're starting up, we're not fully synced yet. Quit
6467 immediately. */
6468 if (rs->starting_up)
6469 quit ();
6470 /* If ^C has already been sent once, offer to disconnect. */
6471 else if (rs->ctrlc_pending_p)
6472 interrupt_query ();
6473 else
6474 target_interrupt ();
6475 }
6476
6477 /* Ask the user what to do when an interrupt is received. */
6478
6479 static void
6480 interrupt_query (void)
6481 {
6482 struct remote_state *rs = get_remote_state ();
6483
6484 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6485 {
6486 if (query (_("The target is not responding to interrupt requests.\n"
6487 "Stop debugging it? ")))
6488 {
6489 remote_unpush_target ();
6490 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6491 }
6492 }
6493 else
6494 {
6495 if (query (_("Interrupted while waiting for the program.\n"
6496 "Give up waiting? ")))
6497 quit ();
6498 }
6499 }
6500
6501 /* Enable/disable target terminal ownership. Most targets can use
6502 terminal groups to control terminal ownership. Remote targets are
6503 different in that explicit transfer of ownership to/from GDB/target
6504 is required. */
6505
6506 void
6507 remote_target::terminal_inferior ()
6508 {
6509 /* NOTE: At this point we could also register our selves as the
6510 recipient of all input. Any characters typed could then be
6511 passed on down to the target. */
6512 }
6513
6514 void
6515 remote_target::terminal_ours ()
6516 {
6517 }
6518
6519 static void
6520 remote_console_output (char *msg)
6521 {
6522 char *p;
6523
6524 for (p = msg; p[0] && p[1]; p += 2)
6525 {
6526 char tb[2];
6527 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6528
6529 tb[0] = c;
6530 tb[1] = 0;
6531 fputs_unfiltered (tb, gdb_stdtarg);
6532 }
6533 gdb_flush (gdb_stdtarg);
6534 }
6535
6536 DEF_VEC_O(cached_reg_t);
6537
6538 typedef struct stop_reply
6539 {
6540 struct notif_event base;
6541
6542 /* The identifier of the thread about this event */
6543 ptid_t ptid;
6544
6545 /* The remote state this event is associated with. When the remote
6546 connection, represented by a remote_state object, is closed,
6547 all the associated stop_reply events should be released. */
6548 struct remote_state *rs;
6549
6550 struct target_waitstatus ws;
6551
6552 /* The architecture associated with the expedited registers. */
6553 gdbarch *arch;
6554
6555 /* Expedited registers. This makes remote debugging a bit more
6556 efficient for those targets that provide critical registers as
6557 part of their normal status mechanism (as another roundtrip to
6558 fetch them is avoided). */
6559 VEC(cached_reg_t) *regcache;
6560
6561 enum target_stop_reason stop_reason;
6562
6563 CORE_ADDR watch_data_address;
6564
6565 int core;
6566 } *stop_reply_p;
6567
6568 DECLARE_QUEUE_P (stop_reply_p);
6569 DEFINE_QUEUE_P (stop_reply_p);
6570 /* The list of already fetched and acknowledged stop events. This
6571 queue is used for notification Stop, and other notifications
6572 don't need queue for their events, because the notification events
6573 of Stop can't be consumed immediately, so that events should be
6574 queued first, and be consumed by remote_wait_{ns,as} one per
6575 time. Other notifications can consume their events immediately,
6576 so queue is not needed for them. */
6577 static QUEUE (stop_reply_p) *stop_reply_queue;
6578
6579 static void
6580 stop_reply_xfree (struct stop_reply *r)
6581 {
6582 notif_event_xfree ((struct notif_event *) r);
6583 }
6584
6585 /* Return the length of the stop reply queue. */
6586
6587 static int
6588 stop_reply_queue_length (void)
6589 {
6590 return QUEUE_length (stop_reply_p, stop_reply_queue);
6591 }
6592
6593 static void
6594 remote_notif_stop_parse (struct notif_client *self, char *buf,
6595 struct notif_event *event)
6596 {
6597 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6598 }
6599
6600 static void
6601 remote_notif_stop_ack (struct notif_client *self, char *buf,
6602 struct notif_event *event)
6603 {
6604 struct stop_reply *stop_reply = (struct stop_reply *) event;
6605
6606 /* acknowledge */
6607 putpkt (self->ack_command);
6608
6609 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6610 /* We got an unknown stop reply. */
6611 error (_("Unknown stop reply"));
6612
6613 push_stop_reply (stop_reply);
6614 }
6615
6616 static int
6617 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6618 {
6619 /* We can't get pending events in remote_notif_process for
6620 notification stop, and we have to do this in remote_wait_ns
6621 instead. If we fetch all queued events from stub, remote stub
6622 may exit and we have no chance to process them back in
6623 remote_wait_ns. */
6624 mark_async_event_handler (remote_async_inferior_event_token);
6625 return 0;
6626 }
6627
6628 static void
6629 stop_reply_dtr (struct notif_event *event)
6630 {
6631 struct stop_reply *r = (struct stop_reply *) event;
6632 cached_reg_t *reg;
6633 int ix;
6634
6635 for (ix = 0;
6636 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6637 ix++)
6638 xfree (reg->data);
6639
6640 VEC_free (cached_reg_t, r->regcache);
6641 }
6642
6643 static struct notif_event *
6644 remote_notif_stop_alloc_reply (void)
6645 {
6646 /* We cast to a pointer to the "base class". */
6647 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6648
6649 r->dtr = stop_reply_dtr;
6650
6651 return r;
6652 }
6653
6654 /* A client of notification Stop. */
6655
6656 struct notif_client notif_client_stop =
6657 {
6658 "Stop",
6659 "vStopped",
6660 remote_notif_stop_parse,
6661 remote_notif_stop_ack,
6662 remote_notif_stop_can_get_pending_events,
6663 remote_notif_stop_alloc_reply,
6664 REMOTE_NOTIF_STOP,
6665 };
6666
6667 /* A parameter to pass data in and out. */
6668
6669 struct queue_iter_param
6670 {
6671 void *input;
6672 struct stop_reply *output;
6673 };
6674
6675 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6676 the pid of the process that owns the threads we want to check, or
6677 -1 if we want to check all threads. */
6678
6679 static int
6680 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6681 ptid_t thread_ptid)
6682 {
6683 if (ws->kind == TARGET_WAITKIND_FORKED
6684 || ws->kind == TARGET_WAITKIND_VFORKED)
6685 {
6686 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6687 return 1;
6688 }
6689
6690 return 0;
6691 }
6692
6693 /* Return the thread's pending status used to determine whether the
6694 thread is a fork parent stopped at a fork event. */
6695
6696 static struct target_waitstatus *
6697 thread_pending_fork_status (struct thread_info *thread)
6698 {
6699 if (thread->suspend.waitstatus_pending_p)
6700 return &thread->suspend.waitstatus;
6701 else
6702 return &thread->pending_follow;
6703 }
6704
6705 /* Determine if THREAD is a pending fork parent thread. */
6706
6707 static int
6708 is_pending_fork_parent_thread (struct thread_info *thread)
6709 {
6710 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6711 int pid = -1;
6712
6713 return is_pending_fork_parent (ws, pid, thread->ptid);
6714 }
6715
6716 /* Check whether EVENT is a fork event, and if it is, remove the
6717 fork child from the context list passed in DATA. */
6718
6719 static int
6720 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6721 QUEUE_ITER (stop_reply_p) *iter,
6722 stop_reply_p event,
6723 void *data)
6724 {
6725 struct queue_iter_param *param = (struct queue_iter_param *) data;
6726 struct threads_listing_context *context
6727 = (struct threads_listing_context *) param->input;
6728
6729 if (event->ws.kind == TARGET_WAITKIND_FORKED
6730 || event->ws.kind == TARGET_WAITKIND_VFORKED
6731 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6732 context->remove_thread (event->ws.value.related_pid);
6733
6734 return 1;
6735 }
6736
6737 /* If CONTEXT contains any fork child threads that have not been
6738 reported yet, remove them from the CONTEXT list. If such a
6739 thread exists it is because we are stopped at a fork catchpoint
6740 and have not yet called follow_fork, which will set up the
6741 host-side data structures for the new process. */
6742
6743 static void
6744 remove_new_fork_children (struct threads_listing_context *context)
6745 {
6746 struct thread_info * thread;
6747 int pid = -1;
6748 struct notif_client *notif = &notif_client_stop;
6749 struct queue_iter_param param;
6750
6751 /* For any threads stopped at a fork event, remove the corresponding
6752 fork child threads from the CONTEXT list. */
6753 ALL_NON_EXITED_THREADS (thread)
6754 {
6755 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6756
6757 if (is_pending_fork_parent (ws, pid, thread->ptid))
6758 context->remove_thread (ws->value.related_pid);
6759 }
6760
6761 /* Check for any pending fork events (not reported or processed yet)
6762 in process PID and remove those fork child threads from the
6763 CONTEXT list as well. */
6764 remote_notif_get_pending_events (notif);
6765 param.input = context;
6766 param.output = NULL;
6767 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6768 remove_child_of_pending_fork, &param);
6769 }
6770
6771 /* Check whether EVENT would prevent a global or process wildcard
6772 vCont action. */
6773
6774 static int
6775 check_pending_event_prevents_wildcard_vcont_callback
6776 (QUEUE (stop_reply_p) *q,
6777 QUEUE_ITER (stop_reply_p) *iter,
6778 stop_reply_p event,
6779 void *data)
6780 {
6781 struct inferior *inf;
6782 int *may_global_wildcard_vcont = (int *) data;
6783
6784 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6785 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6786 return 1;
6787
6788 if (event->ws.kind == TARGET_WAITKIND_FORKED
6789 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6790 *may_global_wildcard_vcont = 0;
6791
6792 inf = find_inferior_ptid (event->ptid);
6793
6794 /* This may be the first time we heard about this process.
6795 Regardless, we must not do a global wildcard resume, otherwise
6796 we'd resume this process too. */
6797 *may_global_wildcard_vcont = 0;
6798 if (inf != NULL)
6799 get_remote_inferior (inf)->may_wildcard_vcont = false;
6800
6801 return 1;
6802 }
6803
6804 /* Check whether any event pending in the vStopped queue would prevent
6805 a global or process wildcard vCont action. Clear
6806 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6807 and clear the event inferior's may_wildcard_vcont flag if we can't
6808 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6809
6810 static void
6811 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6812 {
6813 struct notif_client *notif = &notif_client_stop;
6814
6815 remote_notif_get_pending_events (notif);
6816 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6817 check_pending_event_prevents_wildcard_vcont_callback,
6818 may_global_wildcard);
6819 }
6820
6821 /* Remove stop replies in the queue if its pid is equal to the given
6822 inferior's pid. */
6823
6824 static int
6825 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6826 QUEUE_ITER (stop_reply_p) *iter,
6827 stop_reply_p event,
6828 void *data)
6829 {
6830 struct queue_iter_param *param = (struct queue_iter_param *) data;
6831 struct inferior *inf = (struct inferior *) param->input;
6832
6833 if (ptid_get_pid (event->ptid) == inf->pid)
6834 {
6835 stop_reply_xfree (event);
6836 QUEUE_remove_elem (stop_reply_p, q, iter);
6837 }
6838
6839 return 1;
6840 }
6841
6842 /* Discard all pending stop replies of inferior INF. */
6843
6844 static void
6845 discard_pending_stop_replies (struct inferior *inf)
6846 {
6847 struct queue_iter_param param;
6848 struct stop_reply *reply;
6849 struct remote_state *rs = get_remote_state ();
6850 struct remote_notif_state *rns = rs->notif_state;
6851
6852 /* This function can be notified when an inferior exists. When the
6853 target is not remote, the notification state is NULL. */
6854 if (rs->remote_desc == NULL)
6855 return;
6856
6857 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6858
6859 /* Discard the in-flight notification. */
6860 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6861 {
6862 stop_reply_xfree (reply);
6863 rns->pending_event[notif_client_stop.id] = NULL;
6864 }
6865
6866 param.input = inf;
6867 param.output = NULL;
6868 /* Discard the stop replies we have already pulled with
6869 vStopped. */
6870 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6871 remove_stop_reply_for_inferior, &param);
6872 }
6873
6874 /* If its remote state is equal to the given remote state,
6875 remove EVENT from the stop reply queue. */
6876
6877 static int
6878 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6879 QUEUE_ITER (stop_reply_p) *iter,
6880 stop_reply_p event,
6881 void *data)
6882 {
6883 struct queue_iter_param *param = (struct queue_iter_param *) data;
6884 struct remote_state *rs = (struct remote_state *) param->input;
6885
6886 if (event->rs == rs)
6887 {
6888 stop_reply_xfree (event);
6889 QUEUE_remove_elem (stop_reply_p, q, iter);
6890 }
6891
6892 return 1;
6893 }
6894
6895 /* Discard the stop replies for RS in stop_reply_queue. */
6896
6897 static void
6898 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6899 {
6900 struct queue_iter_param param;
6901
6902 param.input = rs;
6903 param.output = NULL;
6904 /* Discard the stop replies we have already pulled with
6905 vStopped. */
6906 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6907 remove_stop_reply_of_remote_state, &param);
6908 }
6909
6910 /* A parameter to pass data in and out. */
6911
6912 static int
6913 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6914 QUEUE_ITER (stop_reply_p) *iter,
6915 stop_reply_p event,
6916 void *data)
6917 {
6918 struct queue_iter_param *param = (struct queue_iter_param *) data;
6919 ptid_t *ptid = (ptid_t *) param->input;
6920
6921 if (ptid_match (event->ptid, *ptid))
6922 {
6923 param->output = event;
6924 QUEUE_remove_elem (stop_reply_p, q, iter);
6925 return 0;
6926 }
6927
6928 return 1;
6929 }
6930
6931 /* Remove the first reply in 'stop_reply_queue' which matches
6932 PTID. */
6933
6934 static struct stop_reply *
6935 remote_notif_remove_queued_reply (ptid_t ptid)
6936 {
6937 struct queue_iter_param param;
6938
6939 param.input = &ptid;
6940 param.output = NULL;
6941
6942 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6943 remote_notif_remove_once_on_match, &param);
6944 if (notif_debug)
6945 fprintf_unfiltered (gdb_stdlog,
6946 "notif: discard queued event: 'Stop' in %s\n",
6947 target_pid_to_str (ptid));
6948
6949 return param.output;
6950 }
6951
6952 /* Look for a queued stop reply belonging to PTID. If one is found,
6953 remove it from the queue, and return it. Returns NULL if none is
6954 found. If there are still queued events left to process, tell the
6955 event loop to get back to target_wait soon. */
6956
6957 static struct stop_reply *
6958 queued_stop_reply (ptid_t ptid)
6959 {
6960 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6961
6962 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6963 /* There's still at least an event left. */
6964 mark_async_event_handler (remote_async_inferior_event_token);
6965
6966 return r;
6967 }
6968
6969 /* Push a fully parsed stop reply in the stop reply queue. Since we
6970 know that we now have at least one queued event left to pass to the
6971 core side, tell the event loop to get back to target_wait soon. */
6972
6973 static void
6974 push_stop_reply (struct stop_reply *new_event)
6975 {
6976 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6977
6978 if (notif_debug)
6979 fprintf_unfiltered (gdb_stdlog,
6980 "notif: push 'Stop' %s to queue %d\n",
6981 target_pid_to_str (new_event->ptid),
6982 QUEUE_length (stop_reply_p,
6983 stop_reply_queue));
6984
6985 mark_async_event_handler (remote_async_inferior_event_token);
6986 }
6987
6988 static int
6989 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6990 QUEUE_ITER (stop_reply_p) *iter,
6991 struct stop_reply *event,
6992 void *data)
6993 {
6994 ptid_t *ptid = (ptid_t *) data;
6995
6996 return !(ptid_equal (*ptid, event->ptid)
6997 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6998 }
6999
7000 /* Returns true if we have a stop reply for PTID. */
7001
7002 static int
7003 peek_stop_reply (ptid_t ptid)
7004 {
7005 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
7006 stop_reply_match_ptid_and_ws, &ptid);
7007 }
7008
7009 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7010 starting with P and ending with PEND matches PREFIX. */
7011
7012 static int
7013 strprefix (const char *p, const char *pend, const char *prefix)
7014 {
7015 for ( ; p < pend; p++, prefix++)
7016 if (*p != *prefix)
7017 return 0;
7018 return *prefix == '\0';
7019 }
7020
7021 /* Parse the stop reply in BUF. Either the function succeeds, and the
7022 result is stored in EVENT, or throws an error. */
7023
7024 static void
7025 remote_parse_stop_reply (char *buf, struct stop_reply *event)
7026 {
7027 remote_arch_state *rsa = NULL;
7028 ULONGEST addr;
7029 const char *p;
7030 int skipregs = 0;
7031
7032 event->ptid = null_ptid;
7033 event->rs = get_remote_state ();
7034 event->ws.kind = TARGET_WAITKIND_IGNORE;
7035 event->ws.value.integer = 0;
7036 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7037 event->regcache = NULL;
7038 event->core = -1;
7039
7040 switch (buf[0])
7041 {
7042 case 'T': /* Status with PC, SP, FP, ... */
7043 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7044 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7045 ss = signal number
7046 n... = register number
7047 r... = register contents
7048 */
7049
7050 p = &buf[3]; /* after Txx */
7051 while (*p)
7052 {
7053 const char *p1;
7054 int fieldsize;
7055
7056 p1 = strchr (p, ':');
7057 if (p1 == NULL)
7058 error (_("Malformed packet(a) (missing colon): %s\n\
7059 Packet: '%s'\n"),
7060 p, buf);
7061 if (p == p1)
7062 error (_("Malformed packet(a) (missing register number): %s\n\
7063 Packet: '%s'\n"),
7064 p, buf);
7065
7066 /* Some "registers" are actually extended stop information.
7067 Note if you're adding a new entry here: GDB 7.9 and
7068 earlier assume that all register "numbers" that start
7069 with an hex digit are real register numbers. Make sure
7070 the server only sends such a packet if it knows the
7071 client understands it. */
7072
7073 if (strprefix (p, p1, "thread"))
7074 event->ptid = read_ptid (++p1, &p);
7075 else if (strprefix (p, p1, "syscall_entry"))
7076 {
7077 ULONGEST sysno;
7078
7079 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7080 p = unpack_varlen_hex (++p1, &sysno);
7081 event->ws.value.syscall_number = (int) sysno;
7082 }
7083 else if (strprefix (p, p1, "syscall_return"))
7084 {
7085 ULONGEST sysno;
7086
7087 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7088 p = unpack_varlen_hex (++p1, &sysno);
7089 event->ws.value.syscall_number = (int) sysno;
7090 }
7091 else if (strprefix (p, p1, "watch")
7092 || strprefix (p, p1, "rwatch")
7093 || strprefix (p, p1, "awatch"))
7094 {
7095 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7096 p = unpack_varlen_hex (++p1, &addr);
7097 event->watch_data_address = (CORE_ADDR) addr;
7098 }
7099 else if (strprefix (p, p1, "swbreak"))
7100 {
7101 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7102
7103 /* Make sure the stub doesn't forget to indicate support
7104 with qSupported. */
7105 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7106 error (_("Unexpected swbreak stop reason"));
7107
7108 /* The value part is documented as "must be empty",
7109 though we ignore it, in case we ever decide to make
7110 use of it in a backward compatible way. */
7111 p = strchrnul (p1 + 1, ';');
7112 }
7113 else if (strprefix (p, p1, "hwbreak"))
7114 {
7115 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7116
7117 /* Make sure the stub doesn't forget to indicate support
7118 with qSupported. */
7119 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7120 error (_("Unexpected hwbreak stop reason"));
7121
7122 /* See above. */
7123 p = strchrnul (p1 + 1, ';');
7124 }
7125 else if (strprefix (p, p1, "library"))
7126 {
7127 event->ws.kind = TARGET_WAITKIND_LOADED;
7128 p = strchrnul (p1 + 1, ';');
7129 }
7130 else if (strprefix (p, p1, "replaylog"))
7131 {
7132 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7133 /* p1 will indicate "begin" or "end", but it makes
7134 no difference for now, so ignore it. */
7135 p = strchrnul (p1 + 1, ';');
7136 }
7137 else if (strprefix (p, p1, "core"))
7138 {
7139 ULONGEST c;
7140
7141 p = unpack_varlen_hex (++p1, &c);
7142 event->core = c;
7143 }
7144 else if (strprefix (p, p1, "fork"))
7145 {
7146 event->ws.value.related_pid = read_ptid (++p1, &p);
7147 event->ws.kind = TARGET_WAITKIND_FORKED;
7148 }
7149 else if (strprefix (p, p1, "vfork"))
7150 {
7151 event->ws.value.related_pid = read_ptid (++p1, &p);
7152 event->ws.kind = TARGET_WAITKIND_VFORKED;
7153 }
7154 else if (strprefix (p, p1, "vforkdone"))
7155 {
7156 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7157 p = strchrnul (p1 + 1, ';');
7158 }
7159 else if (strprefix (p, p1, "exec"))
7160 {
7161 ULONGEST ignored;
7162 char pathname[PATH_MAX];
7163 int pathlen;
7164
7165 /* Determine the length of the execd pathname. */
7166 p = unpack_varlen_hex (++p1, &ignored);
7167 pathlen = (p - p1) / 2;
7168
7169 /* Save the pathname for event reporting and for
7170 the next run command. */
7171 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7172 pathname[pathlen] = '\0';
7173
7174 /* This is freed during event handling. */
7175 event->ws.value.execd_pathname = xstrdup (pathname);
7176 event->ws.kind = TARGET_WAITKIND_EXECD;
7177
7178 /* Skip the registers included in this packet, since
7179 they may be for an architecture different from the
7180 one used by the original program. */
7181 skipregs = 1;
7182 }
7183 else if (strprefix (p, p1, "create"))
7184 {
7185 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7186 p = strchrnul (p1 + 1, ';');
7187 }
7188 else
7189 {
7190 ULONGEST pnum;
7191 const char *p_temp;
7192
7193 if (skipregs)
7194 {
7195 p = strchrnul (p1 + 1, ';');
7196 p++;
7197 continue;
7198 }
7199
7200 /* Maybe a real ``P'' register number. */
7201 p_temp = unpack_varlen_hex (p, &pnum);
7202 /* If the first invalid character is the colon, we got a
7203 register number. Otherwise, it's an unknown stop
7204 reason. */
7205 if (p_temp == p1)
7206 {
7207 /* If we haven't parsed the event's thread yet, find
7208 it now, in order to find the architecture of the
7209 reported expedited registers. */
7210 if (event->ptid == null_ptid)
7211 {
7212 const char *thr = strstr (p1 + 1, ";thread:");
7213 if (thr != NULL)
7214 event->ptid = read_ptid (thr + strlen (";thread:"),
7215 NULL);
7216 else
7217 {
7218 /* Either the current thread hasn't changed,
7219 or the inferior is not multi-threaded.
7220 The event must be for the thread we last
7221 set as (or learned as being) current. */
7222 event->ptid = event->rs->general_thread;
7223 }
7224 }
7225
7226 if (rsa == NULL)
7227 {
7228 inferior *inf = (event->ptid == null_ptid
7229 ? NULL
7230 : find_inferior_ptid (event->ptid));
7231 /* If this is the first time we learn anything
7232 about this process, skip the registers
7233 included in this packet, since we don't yet
7234 know which architecture to use to parse them.
7235 We'll determine the architecture later when
7236 we process the stop reply and retrieve the
7237 target description, via
7238 remote_notice_new_inferior ->
7239 post_create_inferior. */
7240 if (inf == NULL)
7241 {
7242 p = strchrnul (p1 + 1, ';');
7243 p++;
7244 continue;
7245 }
7246
7247 event->arch = inf->gdbarch;
7248 rsa = get_remote_arch_state (event->arch);
7249 }
7250
7251 packet_reg *reg
7252 = packet_reg_from_pnum (event->arch, rsa, pnum);
7253 cached_reg_t cached_reg;
7254
7255 if (reg == NULL)
7256 error (_("Remote sent bad register number %s: %s\n\
7257 Packet: '%s'\n"),
7258 hex_string (pnum), p, buf);
7259
7260 cached_reg.num = reg->regnum;
7261 cached_reg.data = (gdb_byte *)
7262 xmalloc (register_size (event->arch, reg->regnum));
7263
7264 p = p1 + 1;
7265 fieldsize = hex2bin (p, cached_reg.data,
7266 register_size (event->arch, reg->regnum));
7267 p += 2 * fieldsize;
7268 if (fieldsize < register_size (event->arch, reg->regnum))
7269 warning (_("Remote reply is too short: %s"), buf);
7270
7271 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7272 }
7273 else
7274 {
7275 /* Not a number. Silently skip unknown optional
7276 info. */
7277 p = strchrnul (p1 + 1, ';');
7278 }
7279 }
7280
7281 if (*p != ';')
7282 error (_("Remote register badly formatted: %s\nhere: %s"),
7283 buf, p);
7284 ++p;
7285 }
7286
7287 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7288 break;
7289
7290 /* fall through */
7291 case 'S': /* Old style status, just signal only. */
7292 {
7293 int sig;
7294
7295 event->ws.kind = TARGET_WAITKIND_STOPPED;
7296 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7297 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7298 event->ws.value.sig = (enum gdb_signal) sig;
7299 else
7300 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7301 }
7302 break;
7303 case 'w': /* Thread exited. */
7304 {
7305 const char *p;
7306 ULONGEST value;
7307
7308 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7309 p = unpack_varlen_hex (&buf[1], &value);
7310 event->ws.value.integer = value;
7311 if (*p != ';')
7312 error (_("stop reply packet badly formatted: %s"), buf);
7313 event->ptid = read_ptid (++p, NULL);
7314 break;
7315 }
7316 case 'W': /* Target exited. */
7317 case 'X':
7318 {
7319 const char *p;
7320 int pid;
7321 ULONGEST value;
7322
7323 /* GDB used to accept only 2 hex chars here. Stubs should
7324 only send more if they detect GDB supports multi-process
7325 support. */
7326 p = unpack_varlen_hex (&buf[1], &value);
7327
7328 if (buf[0] == 'W')
7329 {
7330 /* The remote process exited. */
7331 event->ws.kind = TARGET_WAITKIND_EXITED;
7332 event->ws.value.integer = value;
7333 }
7334 else
7335 {
7336 /* The remote process exited with a signal. */
7337 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7338 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7339 event->ws.value.sig = (enum gdb_signal) value;
7340 else
7341 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7342 }
7343
7344 /* If no process is specified, assume inferior_ptid. */
7345 pid = ptid_get_pid (inferior_ptid);
7346 if (*p == '\0')
7347 ;
7348 else if (*p == ';')
7349 {
7350 p++;
7351
7352 if (*p == '\0')
7353 ;
7354 else if (startswith (p, "process:"))
7355 {
7356 ULONGEST upid;
7357
7358 p += sizeof ("process:") - 1;
7359 unpack_varlen_hex (p, &upid);
7360 pid = upid;
7361 }
7362 else
7363 error (_("unknown stop reply packet: %s"), buf);
7364 }
7365 else
7366 error (_("unknown stop reply packet: %s"), buf);
7367 event->ptid = pid_to_ptid (pid);
7368 }
7369 break;
7370 case 'N':
7371 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7372 event->ptid = minus_one_ptid;
7373 break;
7374 }
7375
7376 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7377 error (_("No process or thread specified in stop reply: %s"), buf);
7378 }
7379
7380 /* When the stub wants to tell GDB about a new notification reply, it
7381 sends a notification (%Stop, for example). Those can come it at
7382 any time, hence, we have to make sure that any pending
7383 putpkt/getpkt sequence we're making is finished, before querying
7384 the stub for more events with the corresponding ack command
7385 (vStopped, for example). E.g., if we started a vStopped sequence
7386 immediately upon receiving the notification, something like this
7387 could happen:
7388
7389 1.1) --> Hg 1
7390 1.2) <-- OK
7391 1.3) --> g
7392 1.4) <-- %Stop
7393 1.5) --> vStopped
7394 1.6) <-- (registers reply to step #1.3)
7395
7396 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7397 query.
7398
7399 To solve this, whenever we parse a %Stop notification successfully,
7400 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7401 doing whatever we were doing:
7402
7403 2.1) --> Hg 1
7404 2.2) <-- OK
7405 2.3) --> g
7406 2.4) <-- %Stop
7407 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7408 2.5) <-- (registers reply to step #2.3)
7409
7410 Eventualy after step #2.5, we return to the event loop, which
7411 notices there's an event on the
7412 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7413 associated callback --- the function below. At this point, we're
7414 always safe to start a vStopped sequence. :
7415
7416 2.6) --> vStopped
7417 2.7) <-- T05 thread:2
7418 2.8) --> vStopped
7419 2.9) --> OK
7420 */
7421
7422 void
7423 remote_notif_get_pending_events (struct notif_client *nc)
7424 {
7425 struct remote_state *rs = get_remote_state ();
7426
7427 if (rs->notif_state->pending_event[nc->id] != NULL)
7428 {
7429 if (notif_debug)
7430 fprintf_unfiltered (gdb_stdlog,
7431 "notif: process: '%s' ack pending event\n",
7432 nc->name);
7433
7434 /* acknowledge */
7435 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7436 rs->notif_state->pending_event[nc->id] = NULL;
7437
7438 while (1)
7439 {
7440 getpkt (&rs->buf, &rs->buf_size, 0);
7441 if (strcmp (rs->buf, "OK") == 0)
7442 break;
7443 else
7444 remote_notif_ack (nc, rs->buf);
7445 }
7446 }
7447 else
7448 {
7449 if (notif_debug)
7450 fprintf_unfiltered (gdb_stdlog,
7451 "notif: process: '%s' no pending reply\n",
7452 nc->name);
7453 }
7454 }
7455
7456 /* Called when it is decided that STOP_REPLY holds the info of the
7457 event that is to be returned to the core. This function always
7458 destroys STOP_REPLY. */
7459
7460 static ptid_t
7461 process_stop_reply (struct stop_reply *stop_reply,
7462 struct target_waitstatus *status)
7463 {
7464 ptid_t ptid;
7465
7466 *status = stop_reply->ws;
7467 ptid = stop_reply->ptid;
7468
7469 /* If no thread/process was reported by the stub, assume the current
7470 inferior. */
7471 if (ptid_equal (ptid, null_ptid))
7472 ptid = inferior_ptid;
7473
7474 if (status->kind != TARGET_WAITKIND_EXITED
7475 && status->kind != TARGET_WAITKIND_SIGNALLED
7476 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7477 {
7478 /* Expedited registers. */
7479 if (stop_reply->regcache)
7480 {
7481 struct regcache *regcache
7482 = get_thread_arch_regcache (ptid, stop_reply->arch);
7483 cached_reg_t *reg;
7484 int ix;
7485
7486 for (ix = 0;
7487 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7488 ix++)
7489 {
7490 regcache_raw_supply (regcache, reg->num, reg->data);
7491 xfree (reg->data);
7492 }
7493
7494 VEC_free (cached_reg_t, stop_reply->regcache);
7495 }
7496
7497 remote_notice_new_inferior (ptid, 0);
7498 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7499 remote_thr->core = stop_reply->core;
7500 remote_thr->stop_reason = stop_reply->stop_reason;
7501 remote_thr->watch_data_address = stop_reply->watch_data_address;
7502 remote_thr->vcont_resumed = 0;
7503 }
7504
7505 stop_reply_xfree (stop_reply);
7506 return ptid;
7507 }
7508
7509 /* The non-stop mode version of target_wait. */
7510
7511 static ptid_t
7512 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7513 {
7514 struct remote_state *rs = get_remote_state ();
7515 struct stop_reply *stop_reply;
7516 int ret;
7517 int is_notif = 0;
7518
7519 /* If in non-stop mode, get out of getpkt even if a
7520 notification is received. */
7521
7522 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7523 0 /* forever */, &is_notif);
7524 while (1)
7525 {
7526 if (ret != -1 && !is_notif)
7527 switch (rs->buf[0])
7528 {
7529 case 'E': /* Error of some sort. */
7530 /* We're out of sync with the target now. Did it continue
7531 or not? We can't tell which thread it was in non-stop,
7532 so just ignore this. */
7533 warning (_("Remote failure reply: %s"), rs->buf);
7534 break;
7535 case 'O': /* Console output. */
7536 remote_console_output (rs->buf + 1);
7537 break;
7538 default:
7539 warning (_("Invalid remote reply: %s"), rs->buf);
7540 break;
7541 }
7542
7543 /* Acknowledge a pending stop reply that may have arrived in the
7544 mean time. */
7545 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7546 remote_notif_get_pending_events (&notif_client_stop);
7547
7548 /* If indeed we noticed a stop reply, we're done. */
7549 stop_reply = queued_stop_reply (ptid);
7550 if (stop_reply != NULL)
7551 return process_stop_reply (stop_reply, status);
7552
7553 /* Still no event. If we're just polling for an event, then
7554 return to the event loop. */
7555 if (options & TARGET_WNOHANG)
7556 {
7557 status->kind = TARGET_WAITKIND_IGNORE;
7558 return minus_one_ptid;
7559 }
7560
7561 /* Otherwise do a blocking wait. */
7562 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7563 1 /* forever */, &is_notif);
7564 }
7565 }
7566
7567 /* Wait until the remote machine stops, then return, storing status in
7568 STATUS just as `wait' would. */
7569
7570 static ptid_t
7571 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7572 {
7573 struct remote_state *rs = get_remote_state ();
7574 ptid_t event_ptid = null_ptid;
7575 char *buf;
7576 struct stop_reply *stop_reply;
7577
7578 again:
7579
7580 status->kind = TARGET_WAITKIND_IGNORE;
7581 status->value.integer = 0;
7582
7583 stop_reply = queued_stop_reply (ptid);
7584 if (stop_reply != NULL)
7585 return process_stop_reply (stop_reply, status);
7586
7587 if (rs->cached_wait_status)
7588 /* Use the cached wait status, but only once. */
7589 rs->cached_wait_status = 0;
7590 else
7591 {
7592 int ret;
7593 int is_notif;
7594 int forever = ((options & TARGET_WNOHANG) == 0
7595 && wait_forever_enabled_p);
7596
7597 if (!rs->waiting_for_stop_reply)
7598 {
7599 status->kind = TARGET_WAITKIND_NO_RESUMED;
7600 return minus_one_ptid;
7601 }
7602
7603 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7604 _never_ wait for ever -> test on target_is_async_p().
7605 However, before we do that we need to ensure that the caller
7606 knows how to take the target into/out of async mode. */
7607 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7608 forever, &is_notif);
7609
7610 /* GDB gets a notification. Return to core as this event is
7611 not interesting. */
7612 if (ret != -1 && is_notif)
7613 return minus_one_ptid;
7614
7615 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7616 return minus_one_ptid;
7617 }
7618
7619 buf = rs->buf;
7620
7621 /* Assume that the target has acknowledged Ctrl-C unless we receive
7622 an 'F' or 'O' packet. */
7623 if (buf[0] != 'F' && buf[0] != 'O')
7624 rs->ctrlc_pending_p = 0;
7625
7626 switch (buf[0])
7627 {
7628 case 'E': /* Error of some sort. */
7629 /* We're out of sync with the target now. Did it continue or
7630 not? Not is more likely, so report a stop. */
7631 rs->waiting_for_stop_reply = 0;
7632
7633 warning (_("Remote failure reply: %s"), buf);
7634 status->kind = TARGET_WAITKIND_STOPPED;
7635 status->value.sig = GDB_SIGNAL_0;
7636 break;
7637 case 'F': /* File-I/O request. */
7638 /* GDB may access the inferior memory while handling the File-I/O
7639 request, but we don't want GDB accessing memory while waiting
7640 for a stop reply. See the comments in putpkt_binary. Set
7641 waiting_for_stop_reply to 0 temporarily. */
7642 rs->waiting_for_stop_reply = 0;
7643 remote_fileio_request (buf, rs->ctrlc_pending_p);
7644 rs->ctrlc_pending_p = 0;
7645 /* GDB handled the File-I/O request, and the target is running
7646 again. Keep waiting for events. */
7647 rs->waiting_for_stop_reply = 1;
7648 break;
7649 case 'N': case 'T': case 'S': case 'X': case 'W':
7650 {
7651 struct stop_reply *stop_reply;
7652
7653 /* There is a stop reply to handle. */
7654 rs->waiting_for_stop_reply = 0;
7655
7656 stop_reply
7657 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7658 rs->buf);
7659
7660 event_ptid = process_stop_reply (stop_reply, status);
7661 break;
7662 }
7663 case 'O': /* Console output. */
7664 remote_console_output (buf + 1);
7665 break;
7666 case '\0':
7667 if (rs->last_sent_signal != GDB_SIGNAL_0)
7668 {
7669 /* Zero length reply means that we tried 'S' or 'C' and the
7670 remote system doesn't support it. */
7671 target_terminal::ours_for_output ();
7672 printf_filtered
7673 ("Can't send signals to this remote system. %s not sent.\n",
7674 gdb_signal_to_name (rs->last_sent_signal));
7675 rs->last_sent_signal = GDB_SIGNAL_0;
7676 target_terminal::inferior ();
7677
7678 strcpy (buf, rs->last_sent_step ? "s" : "c");
7679 putpkt (buf);
7680 break;
7681 }
7682 /* else fallthrough */
7683 default:
7684 warning (_("Invalid remote reply: %s"), buf);
7685 break;
7686 }
7687
7688 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7689 return minus_one_ptid;
7690 else if (status->kind == TARGET_WAITKIND_IGNORE)
7691 {
7692 /* Nothing interesting happened. If we're doing a non-blocking
7693 poll, we're done. Otherwise, go back to waiting. */
7694 if (options & TARGET_WNOHANG)
7695 return minus_one_ptid;
7696 else
7697 goto again;
7698 }
7699 else if (status->kind != TARGET_WAITKIND_EXITED
7700 && status->kind != TARGET_WAITKIND_SIGNALLED)
7701 {
7702 if (!ptid_equal (event_ptid, null_ptid))
7703 record_currthread (rs, event_ptid);
7704 else
7705 event_ptid = inferior_ptid;
7706 }
7707 else
7708 /* A process exit. Invalidate our notion of current thread. */
7709 record_currthread (rs, minus_one_ptid);
7710
7711 return event_ptid;
7712 }
7713
7714 /* Wait until the remote machine stops, then return, storing status in
7715 STATUS just as `wait' would. */
7716
7717 ptid_t
7718 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7719 {
7720 ptid_t event_ptid;
7721
7722 if (target_is_non_stop_p ())
7723 event_ptid = remote_wait_ns (ptid, status, options);
7724 else
7725 event_ptid = remote_wait_as (ptid, status, options);
7726
7727 if (target_is_async_p ())
7728 {
7729 /* If there are are events left in the queue tell the event loop
7730 to return here. */
7731 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7732 mark_async_event_handler (remote_async_inferior_event_token);
7733 }
7734
7735 return event_ptid;
7736 }
7737
7738 /* Fetch a single register using a 'p' packet. */
7739
7740 static int
7741 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7742 {
7743 struct gdbarch *gdbarch = regcache->arch ();
7744 struct remote_state *rs = get_remote_state ();
7745 char *buf, *p;
7746 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7747 int i;
7748
7749 if (packet_support (PACKET_p) == PACKET_DISABLE)
7750 return 0;
7751
7752 if (reg->pnum == -1)
7753 return 0;
7754
7755 p = rs->buf;
7756 *p++ = 'p';
7757 p += hexnumstr (p, reg->pnum);
7758 *p++ = '\0';
7759 putpkt (rs->buf);
7760 getpkt (&rs->buf, &rs->buf_size, 0);
7761
7762 buf = rs->buf;
7763
7764 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7765 {
7766 case PACKET_OK:
7767 break;
7768 case PACKET_UNKNOWN:
7769 return 0;
7770 case PACKET_ERROR:
7771 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7772 gdbarch_register_name (regcache->arch (),
7773 reg->regnum),
7774 buf);
7775 }
7776
7777 /* If this register is unfetchable, tell the regcache. */
7778 if (buf[0] == 'x')
7779 {
7780 regcache_raw_supply (regcache, reg->regnum, NULL);
7781 return 1;
7782 }
7783
7784 /* Otherwise, parse and supply the value. */
7785 p = buf;
7786 i = 0;
7787 while (p[0] != 0)
7788 {
7789 if (p[1] == 0)
7790 error (_("fetch_register_using_p: early buf termination"));
7791
7792 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7793 p += 2;
7794 }
7795 regcache_raw_supply (regcache, reg->regnum, regp);
7796 return 1;
7797 }
7798
7799 /* Fetch the registers included in the target's 'g' packet. */
7800
7801 static int
7802 send_g_packet (void)
7803 {
7804 struct remote_state *rs = get_remote_state ();
7805 int buf_len;
7806
7807 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7808 putpkt (rs->buf);
7809 getpkt (&rs->buf, &rs->buf_size, 0);
7810 if (packet_check_result (rs->buf) == PACKET_ERROR)
7811 error (_("Could not read registers; remote failure reply '%s'"),
7812 rs->buf);
7813
7814 /* We can get out of synch in various cases. If the first character
7815 in the buffer is not a hex character, assume that has happened
7816 and try to fetch another packet to read. */
7817 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7818 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7819 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7820 && rs->buf[0] != 'x') /* New: unavailable register value. */
7821 {
7822 if (remote_debug)
7823 fprintf_unfiltered (gdb_stdlog,
7824 "Bad register packet; fetching a new packet\n");
7825 getpkt (&rs->buf, &rs->buf_size, 0);
7826 }
7827
7828 buf_len = strlen (rs->buf);
7829
7830 /* Sanity check the received packet. */
7831 if (buf_len % 2 != 0)
7832 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7833
7834 return buf_len / 2;
7835 }
7836
7837 static void
7838 process_g_packet (struct regcache *regcache)
7839 {
7840 struct gdbarch *gdbarch = regcache->arch ();
7841 struct remote_state *rs = get_remote_state ();
7842 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7843 int i, buf_len;
7844 char *p;
7845 char *regs;
7846
7847 buf_len = strlen (rs->buf);
7848
7849 /* Further sanity checks, with knowledge of the architecture. */
7850 if (buf_len > 2 * rsa->sizeof_g_packet)
7851 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7852 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7853
7854 /* Save the size of the packet sent to us by the target. It is used
7855 as a heuristic when determining the max size of packets that the
7856 target can safely receive. */
7857 if (rsa->actual_register_packet_size == 0)
7858 rsa->actual_register_packet_size = buf_len;
7859
7860 /* If this is smaller than we guessed the 'g' packet would be,
7861 update our records. A 'g' reply that doesn't include a register's
7862 value implies either that the register is not available, or that
7863 the 'p' packet must be used. */
7864 if (buf_len < 2 * rsa->sizeof_g_packet)
7865 {
7866 long sizeof_g_packet = buf_len / 2;
7867
7868 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7869 {
7870 long offset = rsa->regs[i].offset;
7871 long reg_size = register_size (gdbarch, i);
7872
7873 if (rsa->regs[i].pnum == -1)
7874 continue;
7875
7876 if (offset >= sizeof_g_packet)
7877 rsa->regs[i].in_g_packet = 0;
7878 else if (offset + reg_size > sizeof_g_packet)
7879 error (_("Truncated register %d in remote 'g' packet"), i);
7880 else
7881 rsa->regs[i].in_g_packet = 1;
7882 }
7883
7884 /* Looks valid enough, we can assume this is the correct length
7885 for a 'g' packet. It's important not to adjust
7886 rsa->sizeof_g_packet if we have truncated registers otherwise
7887 this "if" won't be run the next time the method is called
7888 with a packet of the same size and one of the internal errors
7889 below will trigger instead. */
7890 rsa->sizeof_g_packet = sizeof_g_packet;
7891 }
7892
7893 regs = (char *) alloca (rsa->sizeof_g_packet);
7894
7895 /* Unimplemented registers read as all bits zero. */
7896 memset (regs, 0, rsa->sizeof_g_packet);
7897
7898 /* Reply describes registers byte by byte, each byte encoded as two
7899 hex characters. Suck them all up, then supply them to the
7900 register cacheing/storage mechanism. */
7901
7902 p = rs->buf;
7903 for (i = 0; i < rsa->sizeof_g_packet; i++)
7904 {
7905 if (p[0] == 0 || p[1] == 0)
7906 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7907 internal_error (__FILE__, __LINE__,
7908 _("unexpected end of 'g' packet reply"));
7909
7910 if (p[0] == 'x' && p[1] == 'x')
7911 regs[i] = 0; /* 'x' */
7912 else
7913 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7914 p += 2;
7915 }
7916
7917 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7918 {
7919 struct packet_reg *r = &rsa->regs[i];
7920 long reg_size = register_size (gdbarch, i);
7921
7922 if (r->in_g_packet)
7923 {
7924 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7925 /* This shouldn't happen - we adjusted in_g_packet above. */
7926 internal_error (__FILE__, __LINE__,
7927 _("unexpected end of 'g' packet reply"));
7928 else if (rs->buf[r->offset * 2] == 'x')
7929 {
7930 gdb_assert (r->offset * 2 < strlen (rs->buf));
7931 /* The register isn't available, mark it as such (at
7932 the same time setting the value to zero). */
7933 regcache_raw_supply (regcache, r->regnum, NULL);
7934 }
7935 else
7936 regcache_raw_supply (regcache, r->regnum,
7937 regs + r->offset);
7938 }
7939 }
7940 }
7941
7942 static void
7943 fetch_registers_using_g (struct regcache *regcache)
7944 {
7945 send_g_packet ();
7946 process_g_packet (regcache);
7947 }
7948
7949 /* Make the remote selected traceframe match GDB's selected
7950 traceframe. */
7951
7952 static void
7953 set_remote_traceframe (void)
7954 {
7955 int newnum;
7956 struct remote_state *rs = get_remote_state ();
7957
7958 if (rs->remote_traceframe_number == get_traceframe_number ())
7959 return;
7960
7961 /* Avoid recursion, remote_trace_find calls us again. */
7962 rs->remote_traceframe_number = get_traceframe_number ();
7963
7964 newnum = target_trace_find (tfind_number,
7965 get_traceframe_number (), 0, 0, NULL);
7966
7967 /* Should not happen. If it does, all bets are off. */
7968 if (newnum != get_traceframe_number ())
7969 warning (_("could not set remote traceframe"));
7970 }
7971
7972 void
7973 remote_target::fetch_registers (struct regcache *regcache, int regnum)
7974 {
7975 struct gdbarch *gdbarch = regcache->arch ();
7976 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7977 int i;
7978
7979 set_remote_traceframe ();
7980 set_general_thread (regcache_get_ptid (regcache));
7981
7982 if (regnum >= 0)
7983 {
7984 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
7985
7986 gdb_assert (reg != NULL);
7987
7988 /* If this register might be in the 'g' packet, try that first -
7989 we are likely to read more than one register. If this is the
7990 first 'g' packet, we might be overly optimistic about its
7991 contents, so fall back to 'p'. */
7992 if (reg->in_g_packet)
7993 {
7994 fetch_registers_using_g (regcache);
7995 if (reg->in_g_packet)
7996 return;
7997 }
7998
7999 if (fetch_register_using_p (regcache, reg))
8000 return;
8001
8002 /* This register is not available. */
8003 regcache_raw_supply (regcache, reg->regnum, NULL);
8004
8005 return;
8006 }
8007
8008 fetch_registers_using_g (regcache);
8009
8010 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8011 if (!rsa->regs[i].in_g_packet)
8012 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8013 {
8014 /* This register is not available. */
8015 regcache_raw_supply (regcache, i, NULL);
8016 }
8017 }
8018
8019 /* Prepare to store registers. Since we may send them all (using a
8020 'G' request), we have to read out the ones we don't want to change
8021 first. */
8022
8023 void
8024 remote_target::prepare_to_store (struct regcache *regcache)
8025 {
8026 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8027 int i;
8028
8029 /* Make sure the entire registers array is valid. */
8030 switch (packet_support (PACKET_P))
8031 {
8032 case PACKET_DISABLE:
8033 case PACKET_SUPPORT_UNKNOWN:
8034 /* Make sure all the necessary registers are cached. */
8035 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8036 if (rsa->regs[i].in_g_packet)
8037 regcache_raw_update (regcache, rsa->regs[i].regnum);
8038 break;
8039 case PACKET_ENABLE:
8040 break;
8041 }
8042 }
8043
8044 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8045 packet was not recognized. */
8046
8047 static int
8048 store_register_using_P (const struct regcache *regcache,
8049 struct packet_reg *reg)
8050 {
8051 struct gdbarch *gdbarch = regcache->arch ();
8052 struct remote_state *rs = get_remote_state ();
8053 /* Try storing a single register. */
8054 char *buf = rs->buf;
8055 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8056 char *p;
8057
8058 if (packet_support (PACKET_P) == PACKET_DISABLE)
8059 return 0;
8060
8061 if (reg->pnum == -1)
8062 return 0;
8063
8064 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8065 p = buf + strlen (buf);
8066 regcache_raw_collect (regcache, reg->regnum, regp);
8067 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8068 putpkt (rs->buf);
8069 getpkt (&rs->buf, &rs->buf_size, 0);
8070
8071 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8072 {
8073 case PACKET_OK:
8074 return 1;
8075 case PACKET_ERROR:
8076 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8077 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8078 case PACKET_UNKNOWN:
8079 return 0;
8080 default:
8081 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8082 }
8083 }
8084
8085 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8086 contents of the register cache buffer. FIXME: ignores errors. */
8087
8088 static void
8089 store_registers_using_G (const struct regcache *regcache)
8090 {
8091 struct remote_state *rs = get_remote_state ();
8092 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8093 gdb_byte *regs;
8094 char *p;
8095
8096 /* Extract all the registers in the regcache copying them into a
8097 local buffer. */
8098 {
8099 int i;
8100
8101 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8102 memset (regs, 0, rsa->sizeof_g_packet);
8103 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8104 {
8105 struct packet_reg *r = &rsa->regs[i];
8106
8107 if (r->in_g_packet)
8108 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
8109 }
8110 }
8111
8112 /* Command describes registers byte by byte,
8113 each byte encoded as two hex characters. */
8114 p = rs->buf;
8115 *p++ = 'G';
8116 bin2hex (regs, p, rsa->sizeof_g_packet);
8117 putpkt (rs->buf);
8118 getpkt (&rs->buf, &rs->buf_size, 0);
8119 if (packet_check_result (rs->buf) == PACKET_ERROR)
8120 error (_("Could not write registers; remote failure reply '%s'"),
8121 rs->buf);
8122 }
8123
8124 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8125 of the register cache buffer. FIXME: ignores errors. */
8126
8127 void
8128 remote_target::store_registers (struct regcache *regcache, int regnum)
8129 {
8130 struct gdbarch *gdbarch = regcache->arch ();
8131 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
8132 int i;
8133
8134 set_remote_traceframe ();
8135 set_general_thread (regcache_get_ptid (regcache));
8136
8137 if (regnum >= 0)
8138 {
8139 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8140
8141 gdb_assert (reg != NULL);
8142
8143 /* Always prefer to store registers using the 'P' packet if
8144 possible; we often change only a small number of registers.
8145 Sometimes we change a larger number; we'd need help from a
8146 higher layer to know to use 'G'. */
8147 if (store_register_using_P (regcache, reg))
8148 return;
8149
8150 /* For now, don't complain if we have no way to write the
8151 register. GDB loses track of unavailable registers too
8152 easily. Some day, this may be an error. We don't have
8153 any way to read the register, either... */
8154 if (!reg->in_g_packet)
8155 return;
8156
8157 store_registers_using_G (regcache);
8158 return;
8159 }
8160
8161 store_registers_using_G (regcache);
8162
8163 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8164 if (!rsa->regs[i].in_g_packet)
8165 if (!store_register_using_P (regcache, &rsa->regs[i]))
8166 /* See above for why we do not issue an error here. */
8167 continue;
8168 }
8169 \f
8170
8171 /* Return the number of hex digits in num. */
8172
8173 static int
8174 hexnumlen (ULONGEST num)
8175 {
8176 int i;
8177
8178 for (i = 0; num != 0; i++)
8179 num >>= 4;
8180
8181 return std::max (i, 1);
8182 }
8183
8184 /* Set BUF to the minimum number of hex digits representing NUM. */
8185
8186 static int
8187 hexnumstr (char *buf, ULONGEST num)
8188 {
8189 int len = hexnumlen (num);
8190
8191 return hexnumnstr (buf, num, len);
8192 }
8193
8194
8195 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8196
8197 static int
8198 hexnumnstr (char *buf, ULONGEST num, int width)
8199 {
8200 int i;
8201
8202 buf[width] = '\0';
8203
8204 for (i = width - 1; i >= 0; i--)
8205 {
8206 buf[i] = "0123456789abcdef"[(num & 0xf)];
8207 num >>= 4;
8208 }
8209
8210 return width;
8211 }
8212
8213 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8214
8215 static CORE_ADDR
8216 remote_address_masked (CORE_ADDR addr)
8217 {
8218 unsigned int address_size = remote_address_size;
8219
8220 /* If "remoteaddresssize" was not set, default to target address size. */
8221 if (!address_size)
8222 address_size = gdbarch_addr_bit (target_gdbarch ());
8223
8224 if (address_size > 0
8225 && address_size < (sizeof (ULONGEST) * 8))
8226 {
8227 /* Only create a mask when that mask can safely be constructed
8228 in a ULONGEST variable. */
8229 ULONGEST mask = 1;
8230
8231 mask = (mask << address_size) - 1;
8232 addr &= mask;
8233 }
8234 return addr;
8235 }
8236
8237 /* Determine whether the remote target supports binary downloading.
8238 This is accomplished by sending a no-op memory write of zero length
8239 to the target at the specified address. It does not suffice to send
8240 the whole packet, since many stubs strip the eighth bit and
8241 subsequently compute a wrong checksum, which causes real havoc with
8242 remote_write_bytes.
8243
8244 NOTE: This can still lose if the serial line is not eight-bit
8245 clean. In cases like this, the user should clear "remote
8246 X-packet". */
8247
8248 static void
8249 check_binary_download (CORE_ADDR addr)
8250 {
8251 struct remote_state *rs = get_remote_state ();
8252
8253 switch (packet_support (PACKET_X))
8254 {
8255 case PACKET_DISABLE:
8256 break;
8257 case PACKET_ENABLE:
8258 break;
8259 case PACKET_SUPPORT_UNKNOWN:
8260 {
8261 char *p;
8262
8263 p = rs->buf;
8264 *p++ = 'X';
8265 p += hexnumstr (p, (ULONGEST) addr);
8266 *p++ = ',';
8267 p += hexnumstr (p, (ULONGEST) 0);
8268 *p++ = ':';
8269 *p = '\0';
8270
8271 putpkt_binary (rs->buf, (int) (p - rs->buf));
8272 getpkt (&rs->buf, &rs->buf_size, 0);
8273
8274 if (rs->buf[0] == '\0')
8275 {
8276 if (remote_debug)
8277 fprintf_unfiltered (gdb_stdlog,
8278 "binary downloading NOT "
8279 "supported by target\n");
8280 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8281 }
8282 else
8283 {
8284 if (remote_debug)
8285 fprintf_unfiltered (gdb_stdlog,
8286 "binary downloading supported by target\n");
8287 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8288 }
8289 break;
8290 }
8291 }
8292 }
8293
8294 /* Helper function to resize the payload in order to try to get a good
8295 alignment. We try to write an amount of data such that the next write will
8296 start on an address aligned on REMOTE_ALIGN_WRITES. */
8297
8298 static int
8299 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8300 {
8301 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8302 }
8303
8304 /* Write memory data directly to the remote machine.
8305 This does not inform the data cache; the data cache uses this.
8306 HEADER is the starting part of the packet.
8307 MEMADDR is the address in the remote memory space.
8308 MYADDR is the address of the buffer in our space.
8309 LEN_UNITS is the number of addressable units to write.
8310 UNIT_SIZE is the length in bytes of an addressable unit.
8311 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8312 should send data as binary ('X'), or hex-encoded ('M').
8313
8314 The function creates packet of the form
8315 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8316
8317 where encoding of <DATA> is terminated by PACKET_FORMAT.
8318
8319 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8320 are omitted.
8321
8322 Return the transferred status, error or OK (an
8323 'enum target_xfer_status' value). Save the number of addressable units
8324 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8325
8326 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8327 exchange between gdb and the stub could look like (?? in place of the
8328 checksum):
8329
8330 -> $m1000,4#??
8331 <- aaaabbbbccccdddd
8332
8333 -> $M1000,3:eeeeffffeeee#??
8334 <- OK
8335
8336 -> $m1000,4#??
8337 <- eeeeffffeeeedddd */
8338
8339 static enum target_xfer_status
8340 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8341 const gdb_byte *myaddr, ULONGEST len_units,
8342 int unit_size, ULONGEST *xfered_len_units,
8343 char packet_format, int use_length)
8344 {
8345 struct remote_state *rs = get_remote_state ();
8346 char *p;
8347 char *plen = NULL;
8348 int plenlen = 0;
8349 int todo_units;
8350 int units_written;
8351 int payload_capacity_bytes;
8352 int payload_length_bytes;
8353
8354 if (packet_format != 'X' && packet_format != 'M')
8355 internal_error (__FILE__, __LINE__,
8356 _("remote_write_bytes_aux: bad packet format"));
8357
8358 if (len_units == 0)
8359 return TARGET_XFER_EOF;
8360
8361 payload_capacity_bytes = get_memory_write_packet_size ();
8362
8363 /* The packet buffer will be large enough for the payload;
8364 get_memory_packet_size ensures this. */
8365 rs->buf[0] = '\0';
8366
8367 /* Compute the size of the actual payload by subtracting out the
8368 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8369
8370 payload_capacity_bytes -= strlen ("$,:#NN");
8371 if (!use_length)
8372 /* The comma won't be used. */
8373 payload_capacity_bytes += 1;
8374 payload_capacity_bytes -= strlen (header);
8375 payload_capacity_bytes -= hexnumlen (memaddr);
8376
8377 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8378
8379 strcat (rs->buf, header);
8380 p = rs->buf + strlen (header);
8381
8382 /* Compute a best guess of the number of bytes actually transfered. */
8383 if (packet_format == 'X')
8384 {
8385 /* Best guess at number of bytes that will fit. */
8386 todo_units = std::min (len_units,
8387 (ULONGEST) payload_capacity_bytes / unit_size);
8388 if (use_length)
8389 payload_capacity_bytes -= hexnumlen (todo_units);
8390 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8391 }
8392 else
8393 {
8394 /* Number of bytes that will fit. */
8395 todo_units
8396 = std::min (len_units,
8397 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8398 if (use_length)
8399 payload_capacity_bytes -= hexnumlen (todo_units);
8400 todo_units = std::min (todo_units,
8401 (payload_capacity_bytes / unit_size) / 2);
8402 }
8403
8404 if (todo_units <= 0)
8405 internal_error (__FILE__, __LINE__,
8406 _("minimum packet size too small to write data"));
8407
8408 /* If we already need another packet, then try to align the end
8409 of this packet to a useful boundary. */
8410 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8411 todo_units = align_for_efficient_write (todo_units, memaddr);
8412
8413 /* Append "<memaddr>". */
8414 memaddr = remote_address_masked (memaddr);
8415 p += hexnumstr (p, (ULONGEST) memaddr);
8416
8417 if (use_length)
8418 {
8419 /* Append ",". */
8420 *p++ = ',';
8421
8422 /* Append the length and retain its location and size. It may need to be
8423 adjusted once the packet body has been created. */
8424 plen = p;
8425 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8426 p += plenlen;
8427 }
8428
8429 /* Append ":". */
8430 *p++ = ':';
8431 *p = '\0';
8432
8433 /* Append the packet body. */
8434 if (packet_format == 'X')
8435 {
8436 /* Binary mode. Send target system values byte by byte, in
8437 increasing byte addresses. Only escape certain critical
8438 characters. */
8439 payload_length_bytes =
8440 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8441 &units_written, payload_capacity_bytes);
8442
8443 /* If not all TODO units fit, then we'll need another packet. Make
8444 a second try to keep the end of the packet aligned. Don't do
8445 this if the packet is tiny. */
8446 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8447 {
8448 int new_todo_units;
8449
8450 new_todo_units = align_for_efficient_write (units_written, memaddr);
8451
8452 if (new_todo_units != units_written)
8453 payload_length_bytes =
8454 remote_escape_output (myaddr, new_todo_units, unit_size,
8455 (gdb_byte *) p, &units_written,
8456 payload_capacity_bytes);
8457 }
8458
8459 p += payload_length_bytes;
8460 if (use_length && units_written < todo_units)
8461 {
8462 /* Escape chars have filled up the buffer prematurely,
8463 and we have actually sent fewer units than planned.
8464 Fix-up the length field of the packet. Use the same
8465 number of characters as before. */
8466 plen += hexnumnstr (plen, (ULONGEST) units_written,
8467 plenlen);
8468 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8469 }
8470 }
8471 else
8472 {
8473 /* Normal mode: Send target system values byte by byte, in
8474 increasing byte addresses. Each byte is encoded as a two hex
8475 value. */
8476 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8477 units_written = todo_units;
8478 }
8479
8480 putpkt_binary (rs->buf, (int) (p - rs->buf));
8481 getpkt (&rs->buf, &rs->buf_size, 0);
8482
8483 if (rs->buf[0] == 'E')
8484 return TARGET_XFER_E_IO;
8485
8486 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8487 send fewer units than we'd planned. */
8488 *xfered_len_units = (ULONGEST) units_written;
8489 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8490 }
8491
8492 /* Write memory data directly to the remote machine.
8493 This does not inform the data cache; the data cache uses this.
8494 MEMADDR is the address in the remote memory space.
8495 MYADDR is the address of the buffer in our space.
8496 LEN is the number of bytes.
8497
8498 Return the transferred status, error or OK (an
8499 'enum target_xfer_status' value). Save the number of bytes
8500 transferred in *XFERED_LEN. Only transfer a single packet. */
8501
8502 static enum target_xfer_status
8503 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8504 int unit_size, ULONGEST *xfered_len)
8505 {
8506 const char *packet_format = NULL;
8507
8508 /* Check whether the target supports binary download. */
8509 check_binary_download (memaddr);
8510
8511 switch (packet_support (PACKET_X))
8512 {
8513 case PACKET_ENABLE:
8514 packet_format = "X";
8515 break;
8516 case PACKET_DISABLE:
8517 packet_format = "M";
8518 break;
8519 case PACKET_SUPPORT_UNKNOWN:
8520 internal_error (__FILE__, __LINE__,
8521 _("remote_write_bytes: bad internal state"));
8522 default:
8523 internal_error (__FILE__, __LINE__, _("bad switch"));
8524 }
8525
8526 return remote_write_bytes_aux (packet_format,
8527 memaddr, myaddr, len, unit_size, xfered_len,
8528 packet_format[0], 1);
8529 }
8530
8531 /* Read memory data directly from the remote machine.
8532 This does not use the data cache; the data cache uses this.
8533 MEMADDR is the address in the remote memory space.
8534 MYADDR is the address of the buffer in our space.
8535 LEN_UNITS is the number of addressable memory units to read..
8536 UNIT_SIZE is the length in bytes of an addressable unit.
8537
8538 Return the transferred status, error or OK (an
8539 'enum target_xfer_status' value). Save the number of bytes
8540 transferred in *XFERED_LEN_UNITS.
8541
8542 See the comment of remote_write_bytes_aux for an example of
8543 memory read/write exchange between gdb and the stub. */
8544
8545 static enum target_xfer_status
8546 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8547 int unit_size, ULONGEST *xfered_len_units)
8548 {
8549 struct remote_state *rs = get_remote_state ();
8550 int buf_size_bytes; /* Max size of packet output buffer. */
8551 char *p;
8552 int todo_units;
8553 int decoded_bytes;
8554
8555 buf_size_bytes = get_memory_read_packet_size ();
8556 /* The packet buffer will be large enough for the payload;
8557 get_memory_packet_size ensures this. */
8558
8559 /* Number of units that will fit. */
8560 todo_units = std::min (len_units,
8561 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8562
8563 /* Construct "m"<memaddr>","<len>". */
8564 memaddr = remote_address_masked (memaddr);
8565 p = rs->buf;
8566 *p++ = 'm';
8567 p += hexnumstr (p, (ULONGEST) memaddr);
8568 *p++ = ',';
8569 p += hexnumstr (p, (ULONGEST) todo_units);
8570 *p = '\0';
8571 putpkt (rs->buf);
8572 getpkt (&rs->buf, &rs->buf_size, 0);
8573 if (rs->buf[0] == 'E'
8574 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8575 && rs->buf[3] == '\0')
8576 return TARGET_XFER_E_IO;
8577 /* Reply describes memory byte by byte, each byte encoded as two hex
8578 characters. */
8579 p = rs->buf;
8580 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8581 /* Return what we have. Let higher layers handle partial reads. */
8582 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8583 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8584 }
8585
8586 /* Using the set of read-only target sections of remote, read live
8587 read-only memory.
8588
8589 For interface/parameters/return description see target.h,
8590 to_xfer_partial. */
8591
8592 static enum target_xfer_status
8593 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8594 ULONGEST memaddr, ULONGEST len,
8595 int unit_size, ULONGEST *xfered_len)
8596 {
8597 struct target_section *secp;
8598 struct target_section_table *table;
8599
8600 secp = target_section_by_addr (ops, memaddr);
8601 if (secp != NULL
8602 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8603 secp->the_bfd_section)
8604 & SEC_READONLY))
8605 {
8606 struct target_section *p;
8607 ULONGEST memend = memaddr + len;
8608
8609 table = target_get_section_table (ops);
8610
8611 for (p = table->sections; p < table->sections_end; p++)
8612 {
8613 if (memaddr >= p->addr)
8614 {
8615 if (memend <= p->endaddr)
8616 {
8617 /* Entire transfer is within this section. */
8618 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8619 xfered_len);
8620 }
8621 else if (memaddr >= p->endaddr)
8622 {
8623 /* This section ends before the transfer starts. */
8624 continue;
8625 }
8626 else
8627 {
8628 /* This section overlaps the transfer. Just do half. */
8629 len = p->endaddr - memaddr;
8630 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8631 xfered_len);
8632 }
8633 }
8634 }
8635 }
8636
8637 return TARGET_XFER_EOF;
8638 }
8639
8640 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8641 first if the requested memory is unavailable in traceframe.
8642 Otherwise, fall back to remote_read_bytes_1. */
8643
8644 static enum target_xfer_status
8645 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8646 gdb_byte *myaddr, ULONGEST len, int unit_size,
8647 ULONGEST *xfered_len)
8648 {
8649 if (len == 0)
8650 return TARGET_XFER_EOF;
8651
8652 if (get_traceframe_number () != -1)
8653 {
8654 std::vector<mem_range> available;
8655
8656 /* If we fail to get the set of available memory, then the
8657 target does not support querying traceframe info, and so we
8658 attempt reading from the traceframe anyway (assuming the
8659 target implements the old QTro packet then). */
8660 if (traceframe_available_memory (&available, memaddr, len))
8661 {
8662 if (available.empty () || available[0].start != memaddr)
8663 {
8664 enum target_xfer_status res;
8665
8666 /* Don't read into the traceframe's available
8667 memory. */
8668 if (!available.empty ())
8669 {
8670 LONGEST oldlen = len;
8671
8672 len = available[0].start - memaddr;
8673 gdb_assert (len <= oldlen);
8674 }
8675
8676 /* This goes through the topmost target again. */
8677 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8678 len, unit_size, xfered_len);
8679 if (res == TARGET_XFER_OK)
8680 return TARGET_XFER_OK;
8681 else
8682 {
8683 /* No use trying further, we know some memory starting
8684 at MEMADDR isn't available. */
8685 *xfered_len = len;
8686 return (*xfered_len != 0) ?
8687 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8688 }
8689 }
8690
8691 /* Don't try to read more than how much is available, in
8692 case the target implements the deprecated QTro packet to
8693 cater for older GDBs (the target's knowledge of read-only
8694 sections may be outdated by now). */
8695 len = available[0].length;
8696 }
8697 }
8698
8699 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8700 }
8701
8702 \f
8703
8704 /* Sends a packet with content determined by the printf format string
8705 FORMAT and the remaining arguments, then gets the reply. Returns
8706 whether the packet was a success, a failure, or unknown. */
8707
8708 static enum packet_result remote_send_printf (const char *format, ...)
8709 ATTRIBUTE_PRINTF (1, 2);
8710
8711 static enum packet_result
8712 remote_send_printf (const char *format, ...)
8713 {
8714 struct remote_state *rs = get_remote_state ();
8715 int max_size = get_remote_packet_size ();
8716 va_list ap;
8717
8718 va_start (ap, format);
8719
8720 rs->buf[0] = '\0';
8721 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8722 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8723
8724 if (putpkt (rs->buf) < 0)
8725 error (_("Communication problem with target."));
8726
8727 rs->buf[0] = '\0';
8728 getpkt (&rs->buf, &rs->buf_size, 0);
8729
8730 return packet_check_result (rs->buf);
8731 }
8732
8733 /* Flash writing can take quite some time. We'll set
8734 effectively infinite timeout for flash operations.
8735 In future, we'll need to decide on a better approach. */
8736 static const int remote_flash_timeout = 1000;
8737
8738 void
8739 remote_target::flash_erase (ULONGEST address, LONGEST length)
8740 {
8741 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8742 enum packet_result ret;
8743 scoped_restore restore_timeout
8744 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8745
8746 ret = remote_send_printf ("vFlashErase:%s,%s",
8747 phex (address, addr_size),
8748 phex (length, 4));
8749 switch (ret)
8750 {
8751 case PACKET_UNKNOWN:
8752 error (_("Remote target does not support flash erase"));
8753 case PACKET_ERROR:
8754 error (_("Error erasing flash with vFlashErase packet"));
8755 default:
8756 break;
8757 }
8758 }
8759
8760 static enum target_xfer_status
8761 remote_flash_write (struct target_ops *ops, ULONGEST address,
8762 ULONGEST length, ULONGEST *xfered_len,
8763 const gdb_byte *data)
8764 {
8765 scoped_restore restore_timeout
8766 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8767 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8768 xfered_len,'X', 0);
8769 }
8770
8771 void
8772 remote_target::flash_done ()
8773 {
8774 int ret;
8775
8776 scoped_restore restore_timeout
8777 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8778
8779 ret = remote_send_printf ("vFlashDone");
8780
8781 switch (ret)
8782 {
8783 case PACKET_UNKNOWN:
8784 error (_("Remote target does not support vFlashDone"));
8785 case PACKET_ERROR:
8786 error (_("Error finishing flash operation"));
8787 default:
8788 break;
8789 }
8790 }
8791
8792 void
8793 remote_target::files_info ()
8794 {
8795 puts_filtered ("Debugging a target over a serial line.\n");
8796 }
8797 \f
8798 /* Stuff for dealing with the packets which are part of this protocol.
8799 See comment at top of file for details. */
8800
8801 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8802 error to higher layers. Called when a serial error is detected.
8803 The exception message is STRING, followed by a colon and a blank,
8804 the system error message for errno at function entry and final dot
8805 for output compatibility with throw_perror_with_name. */
8806
8807 static void
8808 unpush_and_perror (const char *string)
8809 {
8810 int saved_errno = errno;
8811
8812 remote_unpush_target ();
8813 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8814 safe_strerror (saved_errno));
8815 }
8816
8817 /* Read a single character from the remote end. The current quit
8818 handler is overridden to avoid quitting in the middle of packet
8819 sequence, as that would break communication with the remote server.
8820 See remote_serial_quit_handler for more detail. */
8821
8822 static int
8823 readchar (int timeout)
8824 {
8825 int ch;
8826 struct remote_state *rs = get_remote_state ();
8827
8828 {
8829 scoped_restore restore_quit
8830 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8831
8832 rs->got_ctrlc_during_io = 0;
8833
8834 ch = serial_readchar (rs->remote_desc, timeout);
8835
8836 if (rs->got_ctrlc_during_io)
8837 set_quit_flag ();
8838 }
8839
8840 if (ch >= 0)
8841 return ch;
8842
8843 switch ((enum serial_rc) ch)
8844 {
8845 case SERIAL_EOF:
8846 remote_unpush_target ();
8847 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8848 /* no return */
8849 case SERIAL_ERROR:
8850 unpush_and_perror (_("Remote communication error. "
8851 "Target disconnected."));
8852 /* no return */
8853 case SERIAL_TIMEOUT:
8854 break;
8855 }
8856 return ch;
8857 }
8858
8859 /* Wrapper for serial_write that closes the target and throws if
8860 writing fails. The current quit handler is overridden to avoid
8861 quitting in the middle of packet sequence, as that would break
8862 communication with the remote server. See
8863 remote_serial_quit_handler for more detail. */
8864
8865 static void
8866 remote_serial_write (const char *str, int len)
8867 {
8868 struct remote_state *rs = get_remote_state ();
8869
8870 scoped_restore restore_quit
8871 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8872
8873 rs->got_ctrlc_during_io = 0;
8874
8875 if (serial_write (rs->remote_desc, str, len))
8876 {
8877 unpush_and_perror (_("Remote communication error. "
8878 "Target disconnected."));
8879 }
8880
8881 if (rs->got_ctrlc_during_io)
8882 set_quit_flag ();
8883 }
8884
8885 /* Return a string representing an escaped version of BUF, of len N.
8886 E.g. \n is converted to \\n, \t to \\t, etc. */
8887
8888 static std::string
8889 escape_buffer (const char *buf, int n)
8890 {
8891 string_file stb;
8892
8893 stb.putstrn (buf, n, '\\');
8894 return std::move (stb.string ());
8895 }
8896
8897 /* Display a null-terminated packet on stdout, for debugging, using C
8898 string notation. */
8899
8900 static void
8901 print_packet (const char *buf)
8902 {
8903 puts_filtered ("\"");
8904 fputstr_filtered (buf, '"', gdb_stdout);
8905 puts_filtered ("\"");
8906 }
8907
8908 int
8909 putpkt (const char *buf)
8910 {
8911 return putpkt_binary (buf, strlen (buf));
8912 }
8913
8914 /* Send a packet to the remote machine, with error checking. The data
8915 of the packet is in BUF. The string in BUF can be at most
8916 get_remote_packet_size () - 5 to account for the $, # and checksum,
8917 and for a possible /0 if we are debugging (remote_debug) and want
8918 to print the sent packet as a string. */
8919
8920 static int
8921 putpkt_binary (const char *buf, int cnt)
8922 {
8923 struct remote_state *rs = get_remote_state ();
8924 int i;
8925 unsigned char csum = 0;
8926 gdb::def_vector<char> data (cnt + 6);
8927 char *buf2 = data.data ();
8928
8929 int ch;
8930 int tcount = 0;
8931 char *p;
8932
8933 /* Catch cases like trying to read memory or listing threads while
8934 we're waiting for a stop reply. The remote server wouldn't be
8935 ready to handle this request, so we'd hang and timeout. We don't
8936 have to worry about this in synchronous mode, because in that
8937 case it's not possible to issue a command while the target is
8938 running. This is not a problem in non-stop mode, because in that
8939 case, the stub is always ready to process serial input. */
8940 if (!target_is_non_stop_p ()
8941 && target_is_async_p ()
8942 && rs->waiting_for_stop_reply)
8943 {
8944 error (_("Cannot execute this command while the target is running.\n"
8945 "Use the \"interrupt\" command to stop the target\n"
8946 "and then try again."));
8947 }
8948
8949 /* We're sending out a new packet. Make sure we don't look at a
8950 stale cached response. */
8951 rs->cached_wait_status = 0;
8952
8953 /* Copy the packet into buffer BUF2, encapsulating it
8954 and giving it a checksum. */
8955
8956 p = buf2;
8957 *p++ = '$';
8958
8959 for (i = 0; i < cnt; i++)
8960 {
8961 csum += buf[i];
8962 *p++ = buf[i];
8963 }
8964 *p++ = '#';
8965 *p++ = tohex ((csum >> 4) & 0xf);
8966 *p++ = tohex (csum & 0xf);
8967
8968 /* Send it over and over until we get a positive ack. */
8969
8970 while (1)
8971 {
8972 int started_error_output = 0;
8973
8974 if (remote_debug)
8975 {
8976 *p = '\0';
8977
8978 int len = (int) (p - buf2);
8979
8980 std::string str
8981 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8982
8983 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8984
8985 if (len > REMOTE_DEBUG_MAX_CHAR)
8986 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
8987 len - REMOTE_DEBUG_MAX_CHAR);
8988
8989 fprintf_unfiltered (gdb_stdlog, "...");
8990
8991 gdb_flush (gdb_stdlog);
8992 }
8993 remote_serial_write (buf2, p - buf2);
8994
8995 /* If this is a no acks version of the remote protocol, send the
8996 packet and move on. */
8997 if (rs->noack_mode)
8998 break;
8999
9000 /* Read until either a timeout occurs (-2) or '+' is read.
9001 Handle any notification that arrives in the mean time. */
9002 while (1)
9003 {
9004 ch = readchar (remote_timeout);
9005
9006 if (remote_debug)
9007 {
9008 switch (ch)
9009 {
9010 case '+':
9011 case '-':
9012 case SERIAL_TIMEOUT:
9013 case '$':
9014 case '%':
9015 if (started_error_output)
9016 {
9017 putchar_unfiltered ('\n');
9018 started_error_output = 0;
9019 }
9020 }
9021 }
9022
9023 switch (ch)
9024 {
9025 case '+':
9026 if (remote_debug)
9027 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9028 return 1;
9029 case '-':
9030 if (remote_debug)
9031 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9032 /* FALLTHROUGH */
9033 case SERIAL_TIMEOUT:
9034 tcount++;
9035 if (tcount > 3)
9036 return 0;
9037 break; /* Retransmit buffer. */
9038 case '$':
9039 {
9040 if (remote_debug)
9041 fprintf_unfiltered (gdb_stdlog,
9042 "Packet instead of Ack, ignoring it\n");
9043 /* It's probably an old response sent because an ACK
9044 was lost. Gobble up the packet and ack it so it
9045 doesn't get retransmitted when we resend this
9046 packet. */
9047 skip_frame ();
9048 remote_serial_write ("+", 1);
9049 continue; /* Now, go look for +. */
9050 }
9051
9052 case '%':
9053 {
9054 int val;
9055
9056 /* If we got a notification, handle it, and go back to looking
9057 for an ack. */
9058 /* We've found the start of a notification. Now
9059 collect the data. */
9060 val = read_frame (&rs->buf, &rs->buf_size);
9061 if (val >= 0)
9062 {
9063 if (remote_debug)
9064 {
9065 std::string str = escape_buffer (rs->buf, val);
9066
9067 fprintf_unfiltered (gdb_stdlog,
9068 " Notification received: %s\n",
9069 str.c_str ());
9070 }
9071 handle_notification (rs->notif_state, rs->buf);
9072 /* We're in sync now, rewait for the ack. */
9073 tcount = 0;
9074 }
9075 else
9076 {
9077 if (remote_debug)
9078 {
9079 if (!started_error_output)
9080 {
9081 started_error_output = 1;
9082 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9083 }
9084 fputc_unfiltered (ch & 0177, gdb_stdlog);
9085 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9086 }
9087 }
9088 continue;
9089 }
9090 /* fall-through */
9091 default:
9092 if (remote_debug)
9093 {
9094 if (!started_error_output)
9095 {
9096 started_error_output = 1;
9097 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9098 }
9099 fputc_unfiltered (ch & 0177, gdb_stdlog);
9100 }
9101 continue;
9102 }
9103 break; /* Here to retransmit. */
9104 }
9105
9106 #if 0
9107 /* This is wrong. If doing a long backtrace, the user should be
9108 able to get out next time we call QUIT, without anything as
9109 violent as interrupt_query. If we want to provide a way out of
9110 here without getting to the next QUIT, it should be based on
9111 hitting ^C twice as in remote_wait. */
9112 if (quit_flag)
9113 {
9114 quit_flag = 0;
9115 interrupt_query ();
9116 }
9117 #endif
9118 }
9119
9120 return 0;
9121 }
9122
9123 /* Come here after finding the start of a frame when we expected an
9124 ack. Do our best to discard the rest of this packet. */
9125
9126 static void
9127 skip_frame (void)
9128 {
9129 int c;
9130
9131 while (1)
9132 {
9133 c = readchar (remote_timeout);
9134 switch (c)
9135 {
9136 case SERIAL_TIMEOUT:
9137 /* Nothing we can do. */
9138 return;
9139 case '#':
9140 /* Discard the two bytes of checksum and stop. */
9141 c = readchar (remote_timeout);
9142 if (c >= 0)
9143 c = readchar (remote_timeout);
9144
9145 return;
9146 case '*': /* Run length encoding. */
9147 /* Discard the repeat count. */
9148 c = readchar (remote_timeout);
9149 if (c < 0)
9150 return;
9151 break;
9152 default:
9153 /* A regular character. */
9154 break;
9155 }
9156 }
9157 }
9158
9159 /* Come here after finding the start of the frame. Collect the rest
9160 into *BUF, verifying the checksum, length, and handling run-length
9161 compression. NUL terminate the buffer. If there is not enough room,
9162 expand *BUF using xrealloc.
9163
9164 Returns -1 on error, number of characters in buffer (ignoring the
9165 trailing NULL) on success. (could be extended to return one of the
9166 SERIAL status indications). */
9167
9168 static long
9169 read_frame (char **buf_p,
9170 long *sizeof_buf)
9171 {
9172 unsigned char csum;
9173 long bc;
9174 int c;
9175 char *buf = *buf_p;
9176 struct remote_state *rs = get_remote_state ();
9177
9178 csum = 0;
9179 bc = 0;
9180
9181 while (1)
9182 {
9183 c = readchar (remote_timeout);
9184 switch (c)
9185 {
9186 case SERIAL_TIMEOUT:
9187 if (remote_debug)
9188 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9189 return -1;
9190 case '$':
9191 if (remote_debug)
9192 fputs_filtered ("Saw new packet start in middle of old one\n",
9193 gdb_stdlog);
9194 return -1; /* Start a new packet, count retries. */
9195 case '#':
9196 {
9197 unsigned char pktcsum;
9198 int check_0 = 0;
9199 int check_1 = 0;
9200
9201 buf[bc] = '\0';
9202
9203 check_0 = readchar (remote_timeout);
9204 if (check_0 >= 0)
9205 check_1 = readchar (remote_timeout);
9206
9207 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9208 {
9209 if (remote_debug)
9210 fputs_filtered ("Timeout in checksum, retrying\n",
9211 gdb_stdlog);
9212 return -1;
9213 }
9214 else if (check_0 < 0 || check_1 < 0)
9215 {
9216 if (remote_debug)
9217 fputs_filtered ("Communication error in checksum\n",
9218 gdb_stdlog);
9219 return -1;
9220 }
9221
9222 /* Don't recompute the checksum; with no ack packets we
9223 don't have any way to indicate a packet retransmission
9224 is necessary. */
9225 if (rs->noack_mode)
9226 return bc;
9227
9228 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9229 if (csum == pktcsum)
9230 return bc;
9231
9232 if (remote_debug)
9233 {
9234 std::string str = escape_buffer (buf, bc);
9235
9236 fprintf_unfiltered (gdb_stdlog,
9237 "Bad checksum, sentsum=0x%x, "
9238 "csum=0x%x, buf=%s\n",
9239 pktcsum, csum, str.c_str ());
9240 }
9241 /* Number of characters in buffer ignoring trailing
9242 NULL. */
9243 return -1;
9244 }
9245 case '*': /* Run length encoding. */
9246 {
9247 int repeat;
9248
9249 csum += c;
9250 c = readchar (remote_timeout);
9251 csum += c;
9252 repeat = c - ' ' + 3; /* Compute repeat count. */
9253
9254 /* The character before ``*'' is repeated. */
9255
9256 if (repeat > 0 && repeat <= 255 && bc > 0)
9257 {
9258 if (bc + repeat - 1 >= *sizeof_buf - 1)
9259 {
9260 /* Make some more room in the buffer. */
9261 *sizeof_buf += repeat;
9262 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9263 buf = *buf_p;
9264 }
9265
9266 memset (&buf[bc], buf[bc - 1], repeat);
9267 bc += repeat;
9268 continue;
9269 }
9270
9271 buf[bc] = '\0';
9272 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9273 return -1;
9274 }
9275 default:
9276 if (bc >= *sizeof_buf - 1)
9277 {
9278 /* Make some more room in the buffer. */
9279 *sizeof_buf *= 2;
9280 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9281 buf = *buf_p;
9282 }
9283
9284 buf[bc++] = c;
9285 csum += c;
9286 continue;
9287 }
9288 }
9289 }
9290
9291 /* Read a packet from the remote machine, with error checking, and
9292 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9293 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9294 rather than timing out; this is used (in synchronous mode) to wait
9295 for a target that is is executing user code to stop. */
9296 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9297 don't have to change all the calls to getpkt to deal with the
9298 return value, because at the moment I don't know what the right
9299 thing to do it for those. */
9300 void
9301 getpkt (char **buf,
9302 long *sizeof_buf,
9303 int forever)
9304 {
9305 getpkt_sane (buf, sizeof_buf, forever);
9306 }
9307
9308
9309 /* Read a packet from the remote machine, with error checking, and
9310 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9311 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9312 rather than timing out; this is used (in synchronous mode) to wait
9313 for a target that is is executing user code to stop. If FOREVER ==
9314 0, this function is allowed to time out gracefully and return an
9315 indication of this to the caller. Otherwise return the number of
9316 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9317 enough reason to return to the caller. *IS_NOTIF is an output
9318 boolean that indicates whether *BUF holds a notification or not
9319 (a regular packet). */
9320
9321 static int
9322 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9323 int expecting_notif, int *is_notif)
9324 {
9325 struct remote_state *rs = get_remote_state ();
9326 int c;
9327 int tries;
9328 int timeout;
9329 int val = -1;
9330
9331 /* We're reading a new response. Make sure we don't look at a
9332 previously cached response. */
9333 rs->cached_wait_status = 0;
9334
9335 strcpy (*buf, "timeout");
9336
9337 if (forever)
9338 timeout = watchdog > 0 ? watchdog : -1;
9339 else if (expecting_notif)
9340 timeout = 0; /* There should already be a char in the buffer. If
9341 not, bail out. */
9342 else
9343 timeout = remote_timeout;
9344
9345 #define MAX_TRIES 3
9346
9347 /* Process any number of notifications, and then return when
9348 we get a packet. */
9349 for (;;)
9350 {
9351 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9352 times. */
9353 for (tries = 1; tries <= MAX_TRIES; tries++)
9354 {
9355 /* This can loop forever if the remote side sends us
9356 characters continuously, but if it pauses, we'll get
9357 SERIAL_TIMEOUT from readchar because of timeout. Then
9358 we'll count that as a retry.
9359
9360 Note that even when forever is set, we will only wait
9361 forever prior to the start of a packet. After that, we
9362 expect characters to arrive at a brisk pace. They should
9363 show up within remote_timeout intervals. */
9364 do
9365 c = readchar (timeout);
9366 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9367
9368 if (c == SERIAL_TIMEOUT)
9369 {
9370 if (expecting_notif)
9371 return -1; /* Don't complain, it's normal to not get
9372 anything in this case. */
9373
9374 if (forever) /* Watchdog went off? Kill the target. */
9375 {
9376 remote_unpush_target ();
9377 throw_error (TARGET_CLOSE_ERROR,
9378 _("Watchdog timeout has expired. "
9379 "Target detached."));
9380 }
9381 if (remote_debug)
9382 fputs_filtered ("Timed out.\n", gdb_stdlog);
9383 }
9384 else
9385 {
9386 /* We've found the start of a packet or notification.
9387 Now collect the data. */
9388 val = read_frame (buf, sizeof_buf);
9389 if (val >= 0)
9390 break;
9391 }
9392
9393 remote_serial_write ("-", 1);
9394 }
9395
9396 if (tries > MAX_TRIES)
9397 {
9398 /* We have tried hard enough, and just can't receive the
9399 packet/notification. Give up. */
9400 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9401
9402 /* Skip the ack char if we're in no-ack mode. */
9403 if (!rs->noack_mode)
9404 remote_serial_write ("+", 1);
9405 return -1;
9406 }
9407
9408 /* If we got an ordinary packet, return that to our caller. */
9409 if (c == '$')
9410 {
9411 if (remote_debug)
9412 {
9413 std::string str
9414 = escape_buffer (*buf,
9415 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9416
9417 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9418 str.c_str ());
9419
9420 if (val > REMOTE_DEBUG_MAX_CHAR)
9421 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9422 val - REMOTE_DEBUG_MAX_CHAR);
9423
9424 fprintf_unfiltered (gdb_stdlog, "\n");
9425 }
9426
9427 /* Skip the ack char if we're in no-ack mode. */
9428 if (!rs->noack_mode)
9429 remote_serial_write ("+", 1);
9430 if (is_notif != NULL)
9431 *is_notif = 0;
9432 return val;
9433 }
9434
9435 /* If we got a notification, handle it, and go back to looking
9436 for a packet. */
9437 else
9438 {
9439 gdb_assert (c == '%');
9440
9441 if (remote_debug)
9442 {
9443 std::string str = escape_buffer (*buf, val);
9444
9445 fprintf_unfiltered (gdb_stdlog,
9446 " Notification received: %s\n",
9447 str.c_str ());
9448 }
9449 if (is_notif != NULL)
9450 *is_notif = 1;
9451
9452 handle_notification (rs->notif_state, *buf);
9453
9454 /* Notifications require no acknowledgement. */
9455
9456 if (expecting_notif)
9457 return val;
9458 }
9459 }
9460 }
9461
9462 static int
9463 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9464 {
9465 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9466 }
9467
9468 static int
9469 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9470 int *is_notif)
9471 {
9472 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9473 is_notif);
9474 }
9475
9476 /* Check whether EVENT is a fork event for the process specified
9477 by the pid passed in DATA, and if it is, kill the fork child. */
9478
9479 static int
9480 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9481 QUEUE_ITER (stop_reply_p) *iter,
9482 stop_reply_p event,
9483 void *data)
9484 {
9485 struct queue_iter_param *param = (struct queue_iter_param *) data;
9486 int parent_pid = *(int *) param->input;
9487
9488 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9489 {
9490 struct remote_state *rs = get_remote_state ();
9491 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9492 int res;
9493
9494 res = remote_vkill (child_pid, rs);
9495 if (res != 0)
9496 error (_("Can't kill fork child process %d"), child_pid);
9497 }
9498
9499 return 1;
9500 }
9501
9502 /* Kill any new fork children of process PID that haven't been
9503 processed by follow_fork. */
9504
9505 static void
9506 kill_new_fork_children (int pid, struct remote_state *rs)
9507 {
9508 struct thread_info *thread;
9509 struct notif_client *notif = &notif_client_stop;
9510 struct queue_iter_param param;
9511
9512 /* Kill the fork child threads of any threads in process PID
9513 that are stopped at a fork event. */
9514 ALL_NON_EXITED_THREADS (thread)
9515 {
9516 struct target_waitstatus *ws = &thread->pending_follow;
9517
9518 if (is_pending_fork_parent (ws, pid, thread->ptid))
9519 {
9520 struct remote_state *rs = get_remote_state ();
9521 int child_pid = ptid_get_pid (ws->value.related_pid);
9522 int res;
9523
9524 res = remote_vkill (child_pid, rs);
9525 if (res != 0)
9526 error (_("Can't kill fork child process %d"), child_pid);
9527 }
9528 }
9529
9530 /* Check for any pending fork events (not reported or processed yet)
9531 in process PID and kill those fork child threads as well. */
9532 remote_notif_get_pending_events (notif);
9533 param.input = &pid;
9534 param.output = NULL;
9535 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9536 kill_child_of_pending_fork, &param);
9537 }
9538
9539 \f
9540 /* Target hook to kill the current inferior. */
9541
9542 void
9543 remote_target::kill ()
9544 {
9545 int res = -1;
9546 int pid = ptid_get_pid (inferior_ptid);
9547 struct remote_state *rs = get_remote_state ();
9548
9549 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9550 {
9551 /* If we're stopped while forking and we haven't followed yet,
9552 kill the child task. We need to do this before killing the
9553 parent task because if this is a vfork then the parent will
9554 be sleeping. */
9555 kill_new_fork_children (pid, rs);
9556
9557 res = remote_vkill (pid, rs);
9558 if (res == 0)
9559 {
9560 target_mourn_inferior (inferior_ptid);
9561 return;
9562 }
9563 }
9564
9565 /* If we are in 'target remote' mode and we are killing the only
9566 inferior, then we will tell gdbserver to exit and unpush the
9567 target. */
9568 if (res == -1 && !remote_multi_process_p (rs)
9569 && number_of_live_inferiors () == 1)
9570 {
9571 remote_kill_k ();
9572
9573 /* We've killed the remote end, we get to mourn it. If we are
9574 not in extended mode, mourning the inferior also unpushes
9575 remote_ops from the target stack, which closes the remote
9576 connection. */
9577 target_mourn_inferior (inferior_ptid);
9578
9579 return;
9580 }
9581
9582 error (_("Can't kill process"));
9583 }
9584
9585 /* Send a kill request to the target using the 'vKill' packet. */
9586
9587 static int
9588 remote_vkill (int pid, struct remote_state *rs)
9589 {
9590 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9591 return -1;
9592
9593 /* Tell the remote target to detach. */
9594 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9595 putpkt (rs->buf);
9596 getpkt (&rs->buf, &rs->buf_size, 0);
9597
9598 switch (packet_ok (rs->buf,
9599 &remote_protocol_packets[PACKET_vKill]))
9600 {
9601 case PACKET_OK:
9602 return 0;
9603 case PACKET_ERROR:
9604 return 1;
9605 case PACKET_UNKNOWN:
9606 return -1;
9607 default:
9608 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9609 }
9610 }
9611
9612 /* Send a kill request to the target using the 'k' packet. */
9613
9614 static void
9615 remote_kill_k (void)
9616 {
9617 /* Catch errors so the user can quit from gdb even when we
9618 aren't on speaking terms with the remote system. */
9619 TRY
9620 {
9621 putpkt ("k");
9622 }
9623 CATCH (ex, RETURN_MASK_ERROR)
9624 {
9625 if (ex.error == TARGET_CLOSE_ERROR)
9626 {
9627 /* If we got an (EOF) error that caused the target
9628 to go away, then we're done, that's what we wanted.
9629 "k" is susceptible to cause a premature EOF, given
9630 that the remote server isn't actually required to
9631 reply to "k", and it can happen that it doesn't
9632 even get to reply ACK to the "k". */
9633 return;
9634 }
9635
9636 /* Otherwise, something went wrong. We didn't actually kill
9637 the target. Just propagate the exception, and let the
9638 user or higher layers decide what to do. */
9639 throw_exception (ex);
9640 }
9641 END_CATCH
9642 }
9643
9644 void
9645 remote_target::mourn_inferior ()
9646 {
9647 struct remote_state *rs = get_remote_state ();
9648
9649 /* In 'target remote' mode with one inferior, we close the connection. */
9650 if (!rs->extended && number_of_live_inferiors () <= 1)
9651 {
9652 unpush_target (this);
9653
9654 /* remote_close takes care of doing most of the clean up. */
9655 generic_mourn_inferior ();
9656 return;
9657 }
9658
9659 /* In case we got here due to an error, but we're going to stay
9660 connected. */
9661 rs->waiting_for_stop_reply = 0;
9662
9663 /* If the current general thread belonged to the process we just
9664 detached from or has exited, the remote side current general
9665 thread becomes undefined. Considering a case like this:
9666
9667 - We just got here due to a detach.
9668 - The process that we're detaching from happens to immediately
9669 report a global breakpoint being hit in non-stop mode, in the
9670 same thread we had selected before.
9671 - GDB attaches to this process again.
9672 - This event happens to be the next event we handle.
9673
9674 GDB would consider that the current general thread didn't need to
9675 be set on the stub side (with Hg), since for all it knew,
9676 GENERAL_THREAD hadn't changed.
9677
9678 Notice that although in all-stop mode, the remote server always
9679 sets the current thread to the thread reporting the stop event,
9680 that doesn't happen in non-stop mode; in non-stop, the stub *must
9681 not* change the current thread when reporting a breakpoint hit,
9682 due to the decoupling of event reporting and event handling.
9683
9684 To keep things simple, we always invalidate our notion of the
9685 current thread. */
9686 record_currthread (rs, minus_one_ptid);
9687
9688 /* Call common code to mark the inferior as not running. */
9689 generic_mourn_inferior ();
9690
9691 if (!have_inferiors ())
9692 {
9693 if (!remote_multi_process_p (rs))
9694 {
9695 /* Check whether the target is running now - some remote stubs
9696 automatically restart after kill. */
9697 putpkt ("?");
9698 getpkt (&rs->buf, &rs->buf_size, 0);
9699
9700 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9701 {
9702 /* Assume that the target has been restarted. Set
9703 inferior_ptid so that bits of core GDB realizes
9704 there's something here, e.g., so that the user can
9705 say "kill" again. */
9706 inferior_ptid = magic_null_ptid;
9707 }
9708 }
9709 }
9710 }
9711
9712 bool
9713 extended_remote_target::supports_disable_randomization ()
9714 {
9715 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9716 }
9717
9718 static void
9719 extended_remote_disable_randomization (int val)
9720 {
9721 struct remote_state *rs = get_remote_state ();
9722 char *reply;
9723
9724 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9725 val);
9726 putpkt (rs->buf);
9727 reply = remote_get_noisy_reply ();
9728 if (*reply == '\0')
9729 error (_("Target does not support QDisableRandomization."));
9730 if (strcmp (reply, "OK") != 0)
9731 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9732 }
9733
9734 static int
9735 extended_remote_run (const std::string &args)
9736 {
9737 struct remote_state *rs = get_remote_state ();
9738 int len;
9739 const char *remote_exec_file = get_remote_exec_file ();
9740
9741 /* If the user has disabled vRun support, or we have detected that
9742 support is not available, do not try it. */
9743 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9744 return -1;
9745
9746 strcpy (rs->buf, "vRun;");
9747 len = strlen (rs->buf);
9748
9749 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9750 error (_("Remote file name too long for run packet"));
9751 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9752 strlen (remote_exec_file));
9753
9754 if (!args.empty ())
9755 {
9756 int i;
9757
9758 gdb_argv argv (args.c_str ());
9759 for (i = 0; argv[i] != NULL; i++)
9760 {
9761 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9762 error (_("Argument list too long for run packet"));
9763 rs->buf[len++] = ';';
9764 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9765 strlen (argv[i]));
9766 }
9767 }
9768
9769 rs->buf[len++] = '\0';
9770
9771 putpkt (rs->buf);
9772 getpkt (&rs->buf, &rs->buf_size, 0);
9773
9774 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9775 {
9776 case PACKET_OK:
9777 /* We have a wait response. All is well. */
9778 return 0;
9779 case PACKET_UNKNOWN:
9780 return -1;
9781 case PACKET_ERROR:
9782 if (remote_exec_file[0] == '\0')
9783 error (_("Running the default executable on the remote target failed; "
9784 "try \"set remote exec-file\"?"));
9785 else
9786 error (_("Running \"%s\" on the remote target failed"),
9787 remote_exec_file);
9788 default:
9789 gdb_assert_not_reached (_("bad switch"));
9790 }
9791 }
9792
9793 /* Helper function to send set/unset environment packets. ACTION is
9794 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9795 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9796 sent. */
9797
9798 static void
9799 send_environment_packet (struct remote_state *rs,
9800 const char *action,
9801 const char *packet,
9802 const char *value)
9803 {
9804 /* Convert the environment variable to an hex string, which
9805 is the best format to be transmitted over the wire. */
9806 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9807 strlen (value));
9808
9809 xsnprintf (rs->buf, get_remote_packet_size (),
9810 "%s:%s", packet, encoded_value.c_str ());
9811
9812 putpkt (rs->buf);
9813 getpkt (&rs->buf, &rs->buf_size, 0);
9814 if (strcmp (rs->buf, "OK") != 0)
9815 warning (_("Unable to %s environment variable '%s' on remote."),
9816 action, value);
9817 }
9818
9819 /* Helper function to handle the QEnvironment* packets. */
9820
9821 static void
9822 extended_remote_environment_support (struct remote_state *rs)
9823 {
9824 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9825 {
9826 putpkt ("QEnvironmentReset");
9827 getpkt (&rs->buf, &rs->buf_size, 0);
9828 if (strcmp (rs->buf, "OK") != 0)
9829 warning (_("Unable to reset environment on remote."));
9830 }
9831
9832 gdb_environ *e = &current_inferior ()->environment;
9833
9834 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9835 for (const std::string &el : e->user_set_env ())
9836 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9837 el.c_str ());
9838
9839 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9840 for (const std::string &el : e->user_unset_env ())
9841 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9842 }
9843
9844 /* Helper function to set the current working directory for the
9845 inferior in the remote target. */
9846
9847 static void
9848 extended_remote_set_inferior_cwd (struct remote_state *rs)
9849 {
9850 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9851 {
9852 const char *inferior_cwd = get_inferior_cwd ();
9853
9854 if (inferior_cwd != NULL)
9855 {
9856 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9857 strlen (inferior_cwd));
9858
9859 xsnprintf (rs->buf, get_remote_packet_size (),
9860 "QSetWorkingDir:%s", hexpath.c_str ());
9861 }
9862 else
9863 {
9864 /* An empty inferior_cwd means that the user wants us to
9865 reset the remote server's inferior's cwd. */
9866 xsnprintf (rs->buf, get_remote_packet_size (),
9867 "QSetWorkingDir:");
9868 }
9869
9870 putpkt (rs->buf);
9871 getpkt (&rs->buf, &rs->buf_size, 0);
9872 if (packet_ok (rs->buf,
9873 &remote_protocol_packets[PACKET_QSetWorkingDir])
9874 != PACKET_OK)
9875 error (_("\
9876 Remote replied unexpectedly while setting the inferior's working\n\
9877 directory: %s"),
9878 rs->buf);
9879
9880 }
9881 }
9882
9883 /* In the extended protocol we want to be able to do things like
9884 "run" and have them basically work as expected. So we need
9885 a special create_inferior function. We support changing the
9886 executable file and the command line arguments, but not the
9887 environment. */
9888
9889 void
9890 extended_remote_target::create_inferior (const char *exec_file,
9891 const std::string &args,
9892 char **env, int from_tty)
9893 {
9894 int run_worked;
9895 char *stop_reply;
9896 struct remote_state *rs = get_remote_state ();
9897 const char *remote_exec_file = get_remote_exec_file ();
9898
9899 /* If running asynchronously, register the target file descriptor
9900 with the event loop. */
9901 if (target_can_async_p ())
9902 target_async (1);
9903
9904 /* Disable address space randomization if requested (and supported). */
9905 if (supports_disable_randomization ())
9906 extended_remote_disable_randomization (disable_randomization);
9907
9908 /* If startup-with-shell is on, we inform gdbserver to start the
9909 remote inferior using a shell. */
9910 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9911 {
9912 xsnprintf (rs->buf, get_remote_packet_size (),
9913 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9914 putpkt (rs->buf);
9915 getpkt (&rs->buf, &rs->buf_size, 0);
9916 if (strcmp (rs->buf, "OK") != 0)
9917 error (_("\
9918 Remote replied unexpectedly while setting startup-with-shell: %s"),
9919 rs->buf);
9920 }
9921
9922 extended_remote_environment_support (rs);
9923
9924 extended_remote_set_inferior_cwd (rs);
9925
9926 /* Now restart the remote server. */
9927 run_worked = extended_remote_run (args) != -1;
9928 if (!run_worked)
9929 {
9930 /* vRun was not supported. Fail if we need it to do what the
9931 user requested. */
9932 if (remote_exec_file[0])
9933 error (_("Remote target does not support \"set remote exec-file\""));
9934 if (!args.empty ())
9935 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9936
9937 /* Fall back to "R". */
9938 extended_remote_restart ();
9939 }
9940
9941 if (!have_inferiors ())
9942 {
9943 /* Clean up from the last time we ran, before we mark the target
9944 running again. This will mark breakpoints uninserted, and
9945 get_offsets may insert breakpoints. */
9946 init_thread_list ();
9947 init_wait_for_inferior ();
9948 }
9949
9950 /* vRun's success return is a stop reply. */
9951 stop_reply = run_worked ? rs->buf : NULL;
9952 add_current_inferior_and_thread (stop_reply);
9953
9954 /* Get updated offsets, if the stub uses qOffsets. */
9955 get_offsets ();
9956 }
9957 \f
9958
9959 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9960 the list of conditions (in agent expression bytecode format), if any, the
9961 target needs to evaluate. The output is placed into the packet buffer
9962 started from BUF and ended at BUF_END. */
9963
9964 static int
9965 remote_add_target_side_condition (struct gdbarch *gdbarch,
9966 struct bp_target_info *bp_tgt, char *buf,
9967 char *buf_end)
9968 {
9969 if (bp_tgt->conditions.empty ())
9970 return 0;
9971
9972 buf += strlen (buf);
9973 xsnprintf (buf, buf_end - buf, "%s", ";");
9974 buf++;
9975
9976 /* Send conditions to the target. */
9977 for (agent_expr *aexpr : bp_tgt->conditions)
9978 {
9979 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9980 buf += strlen (buf);
9981 for (int i = 0; i < aexpr->len; ++i)
9982 buf = pack_hex_byte (buf, aexpr->buf[i]);
9983 *buf = '\0';
9984 }
9985 return 0;
9986 }
9987
9988 static void
9989 remote_add_target_side_commands (struct gdbarch *gdbarch,
9990 struct bp_target_info *bp_tgt, char *buf)
9991 {
9992 if (bp_tgt->tcommands.empty ())
9993 return;
9994
9995 buf += strlen (buf);
9996
9997 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9998 buf += strlen (buf);
9999
10000 /* Concatenate all the agent expressions that are commands into the
10001 cmds parameter. */
10002 for (agent_expr *aexpr : bp_tgt->tcommands)
10003 {
10004 sprintf (buf, "X%x,", aexpr->len);
10005 buf += strlen (buf);
10006 for (int i = 0; i < aexpr->len; ++i)
10007 buf = pack_hex_byte (buf, aexpr->buf[i]);
10008 *buf = '\0';
10009 }
10010 }
10011
10012 /* Insert a breakpoint. On targets that have software breakpoint
10013 support, we ask the remote target to do the work; on targets
10014 which don't, we insert a traditional memory breakpoint. */
10015
10016 int
10017 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10018 struct bp_target_info *bp_tgt)
10019 {
10020 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10021 If it succeeds, then set the support to PACKET_ENABLE. If it
10022 fails, and the user has explicitly requested the Z support then
10023 report an error, otherwise, mark it disabled and go on. */
10024
10025 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10026 {
10027 CORE_ADDR addr = bp_tgt->reqstd_address;
10028 struct remote_state *rs;
10029 char *p, *endbuf;
10030
10031 /* Make sure the remote is pointing at the right process, if
10032 necessary. */
10033 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10034 set_general_process ();
10035
10036 rs = get_remote_state ();
10037 p = rs->buf;
10038 endbuf = rs->buf + get_remote_packet_size ();
10039
10040 *(p++) = 'Z';
10041 *(p++) = '0';
10042 *(p++) = ',';
10043 addr = (ULONGEST) remote_address_masked (addr);
10044 p += hexnumstr (p, addr);
10045 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10046
10047 if (supports_evaluation_of_breakpoint_conditions ())
10048 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10049
10050 if (can_run_breakpoint_commands ())
10051 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10052
10053 putpkt (rs->buf);
10054 getpkt (&rs->buf, &rs->buf_size, 0);
10055
10056 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10057 {
10058 case PACKET_ERROR:
10059 return -1;
10060 case PACKET_OK:
10061 return 0;
10062 case PACKET_UNKNOWN:
10063 break;
10064 }
10065 }
10066
10067 /* If this breakpoint has target-side commands but this stub doesn't
10068 support Z0 packets, throw error. */
10069 if (!bp_tgt->tcommands.empty ())
10070 throw_error (NOT_SUPPORTED_ERROR, _("\
10071 Target doesn't support breakpoints that have target side commands."));
10072
10073 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10074 }
10075
10076 int
10077 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10078 struct bp_target_info *bp_tgt,
10079 enum remove_bp_reason reason)
10080 {
10081 CORE_ADDR addr = bp_tgt->placed_address;
10082 struct remote_state *rs = get_remote_state ();
10083
10084 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10085 {
10086 char *p = rs->buf;
10087 char *endbuf = rs->buf + get_remote_packet_size ();
10088
10089 /* Make sure the remote is pointing at the right process, if
10090 necessary. */
10091 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10092 set_general_process ();
10093
10094 *(p++) = 'z';
10095 *(p++) = '0';
10096 *(p++) = ',';
10097
10098 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10099 p += hexnumstr (p, addr);
10100 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10101
10102 putpkt (rs->buf);
10103 getpkt (&rs->buf, &rs->buf_size, 0);
10104
10105 return (rs->buf[0] == 'E');
10106 }
10107
10108 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10109 }
10110
10111 static enum Z_packet_type
10112 watchpoint_to_Z_packet (int type)
10113 {
10114 switch (type)
10115 {
10116 case hw_write:
10117 return Z_PACKET_WRITE_WP;
10118 break;
10119 case hw_read:
10120 return Z_PACKET_READ_WP;
10121 break;
10122 case hw_access:
10123 return Z_PACKET_ACCESS_WP;
10124 break;
10125 default:
10126 internal_error (__FILE__, __LINE__,
10127 _("hw_bp_to_z: bad watchpoint type %d"), type);
10128 }
10129 }
10130
10131 int
10132 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10133 enum target_hw_bp_type type, struct expression *cond)
10134 {
10135 struct remote_state *rs = get_remote_state ();
10136 char *endbuf = rs->buf + get_remote_packet_size ();
10137 char *p;
10138 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10139
10140 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10141 return 1;
10142
10143 /* Make sure the remote is pointing at the right process, if
10144 necessary. */
10145 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10146 set_general_process ();
10147
10148 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10149 p = strchr (rs->buf, '\0');
10150 addr = remote_address_masked (addr);
10151 p += hexnumstr (p, (ULONGEST) addr);
10152 xsnprintf (p, endbuf - p, ",%x", len);
10153
10154 putpkt (rs->buf);
10155 getpkt (&rs->buf, &rs->buf_size, 0);
10156
10157 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10158 {
10159 case PACKET_ERROR:
10160 return -1;
10161 case PACKET_UNKNOWN:
10162 return 1;
10163 case PACKET_OK:
10164 return 0;
10165 }
10166 internal_error (__FILE__, __LINE__,
10167 _("remote_insert_watchpoint: reached end of function"));
10168 }
10169
10170 bool
10171 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10172 CORE_ADDR start, int length)
10173 {
10174 CORE_ADDR diff = remote_address_masked (addr - start);
10175
10176 return diff < length;
10177 }
10178
10179
10180 int
10181 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10182 enum target_hw_bp_type type, struct expression *cond)
10183 {
10184 struct remote_state *rs = get_remote_state ();
10185 char *endbuf = rs->buf + get_remote_packet_size ();
10186 char *p;
10187 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10188
10189 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10190 return -1;
10191
10192 /* Make sure the remote is pointing at the right process, if
10193 necessary. */
10194 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10195 set_general_process ();
10196
10197 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10198 p = strchr (rs->buf, '\0');
10199 addr = remote_address_masked (addr);
10200 p += hexnumstr (p, (ULONGEST) addr);
10201 xsnprintf (p, endbuf - p, ",%x", len);
10202 putpkt (rs->buf);
10203 getpkt (&rs->buf, &rs->buf_size, 0);
10204
10205 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10206 {
10207 case PACKET_ERROR:
10208 case PACKET_UNKNOWN:
10209 return -1;
10210 case PACKET_OK:
10211 return 0;
10212 }
10213 internal_error (__FILE__, __LINE__,
10214 _("remote_remove_watchpoint: reached end of function"));
10215 }
10216
10217
10218 int remote_hw_watchpoint_limit = -1;
10219 int remote_hw_watchpoint_length_limit = -1;
10220 int remote_hw_breakpoint_limit = -1;
10221
10222 int
10223 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10224 {
10225 if (remote_hw_watchpoint_length_limit == 0)
10226 return 0;
10227 else if (remote_hw_watchpoint_length_limit < 0)
10228 return 1;
10229 else if (len <= remote_hw_watchpoint_length_limit)
10230 return 1;
10231 else
10232 return 0;
10233 }
10234
10235 int
10236 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10237 {
10238 if (type == bp_hardware_breakpoint)
10239 {
10240 if (remote_hw_breakpoint_limit == 0)
10241 return 0;
10242 else if (remote_hw_breakpoint_limit < 0)
10243 return 1;
10244 else if (cnt <= remote_hw_breakpoint_limit)
10245 return 1;
10246 }
10247 else
10248 {
10249 if (remote_hw_watchpoint_limit == 0)
10250 return 0;
10251 else if (remote_hw_watchpoint_limit < 0)
10252 return 1;
10253 else if (ot)
10254 return -1;
10255 else if (cnt <= remote_hw_watchpoint_limit)
10256 return 1;
10257 }
10258 return -1;
10259 }
10260
10261 /* The to_stopped_by_sw_breakpoint method of target remote. */
10262
10263 bool
10264 remote_target::stopped_by_sw_breakpoint ()
10265 {
10266 struct thread_info *thread = inferior_thread ();
10267
10268 return (thread->priv != NULL
10269 && (get_remote_thread_info (thread)->stop_reason
10270 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10271 }
10272
10273 /* The to_supports_stopped_by_sw_breakpoint method of target
10274 remote. */
10275
10276 bool
10277 remote_target::supports_stopped_by_sw_breakpoint ()
10278 {
10279 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10280 }
10281
10282 /* The to_stopped_by_hw_breakpoint method of target remote. */
10283
10284 bool
10285 remote_target::stopped_by_hw_breakpoint ()
10286 {
10287 struct thread_info *thread = inferior_thread ();
10288
10289 return (thread->priv != NULL
10290 && (get_remote_thread_info (thread)->stop_reason
10291 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10292 }
10293
10294 /* The to_supports_stopped_by_hw_breakpoint method of target
10295 remote. */
10296
10297 bool
10298 remote_target::supports_stopped_by_hw_breakpoint ()
10299 {
10300 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10301 }
10302
10303 bool
10304 remote_target::stopped_by_watchpoint ()
10305 {
10306 struct thread_info *thread = inferior_thread ();
10307
10308 return (thread->priv != NULL
10309 && (get_remote_thread_info (thread)->stop_reason
10310 == TARGET_STOPPED_BY_WATCHPOINT));
10311 }
10312
10313 bool
10314 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10315 {
10316 struct thread_info *thread = inferior_thread ();
10317
10318 if (thread->priv != NULL
10319 && (get_remote_thread_info (thread)->stop_reason
10320 == TARGET_STOPPED_BY_WATCHPOINT))
10321 {
10322 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10323 return true;
10324 }
10325
10326 return false;
10327 }
10328
10329
10330 int
10331 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10332 struct bp_target_info *bp_tgt)
10333 {
10334 CORE_ADDR addr = bp_tgt->reqstd_address;
10335 struct remote_state *rs;
10336 char *p, *endbuf;
10337 char *message;
10338
10339 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10340 return -1;
10341
10342 /* Make sure the remote is pointing at the right process, if
10343 necessary. */
10344 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10345 set_general_process ();
10346
10347 rs = get_remote_state ();
10348 p = rs->buf;
10349 endbuf = rs->buf + get_remote_packet_size ();
10350
10351 *(p++) = 'Z';
10352 *(p++) = '1';
10353 *(p++) = ',';
10354
10355 addr = remote_address_masked (addr);
10356 p += hexnumstr (p, (ULONGEST) addr);
10357 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10358
10359 if (supports_evaluation_of_breakpoint_conditions ())
10360 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10361
10362 if (can_run_breakpoint_commands ())
10363 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10364
10365 putpkt (rs->buf);
10366 getpkt (&rs->buf, &rs->buf_size, 0);
10367
10368 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10369 {
10370 case PACKET_ERROR:
10371 if (rs->buf[1] == '.')
10372 {
10373 message = strchr (rs->buf + 2, '.');
10374 if (message)
10375 error (_("Remote failure reply: %s"), message + 1);
10376 }
10377 return -1;
10378 case PACKET_UNKNOWN:
10379 return -1;
10380 case PACKET_OK:
10381 return 0;
10382 }
10383 internal_error (__FILE__, __LINE__,
10384 _("remote_insert_hw_breakpoint: reached end of function"));
10385 }
10386
10387
10388 int
10389 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10390 struct bp_target_info *bp_tgt)
10391 {
10392 CORE_ADDR addr;
10393 struct remote_state *rs = get_remote_state ();
10394 char *p = rs->buf;
10395 char *endbuf = rs->buf + get_remote_packet_size ();
10396
10397 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10398 return -1;
10399
10400 /* Make sure the remote is pointing at the right process, if
10401 necessary. */
10402 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10403 set_general_process ();
10404
10405 *(p++) = 'z';
10406 *(p++) = '1';
10407 *(p++) = ',';
10408
10409 addr = remote_address_masked (bp_tgt->placed_address);
10410 p += hexnumstr (p, (ULONGEST) addr);
10411 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10412
10413 putpkt (rs->buf);
10414 getpkt (&rs->buf, &rs->buf_size, 0);
10415
10416 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10417 {
10418 case PACKET_ERROR:
10419 case PACKET_UNKNOWN:
10420 return -1;
10421 case PACKET_OK:
10422 return 0;
10423 }
10424 internal_error (__FILE__, __LINE__,
10425 _("remote_remove_hw_breakpoint: reached end of function"));
10426 }
10427
10428 /* Verify memory using the "qCRC:" request. */
10429
10430 int
10431 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10432 {
10433 struct remote_state *rs = get_remote_state ();
10434 unsigned long host_crc, target_crc;
10435 char *tmp;
10436
10437 /* It doesn't make sense to use qCRC if the remote target is
10438 connected but not running. */
10439 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10440 {
10441 enum packet_result result;
10442
10443 /* Make sure the remote is pointing at the right process. */
10444 set_general_process ();
10445
10446 /* FIXME: assumes lma can fit into long. */
10447 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10448 (long) lma, (long) size);
10449 putpkt (rs->buf);
10450
10451 /* Be clever; compute the host_crc before waiting for target
10452 reply. */
10453 host_crc = xcrc32 (data, size, 0xffffffff);
10454
10455 getpkt (&rs->buf, &rs->buf_size, 0);
10456
10457 result = packet_ok (rs->buf,
10458 &remote_protocol_packets[PACKET_qCRC]);
10459 if (result == PACKET_ERROR)
10460 return -1;
10461 else if (result == PACKET_OK)
10462 {
10463 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10464 target_crc = target_crc * 16 + fromhex (*tmp);
10465
10466 return (host_crc == target_crc);
10467 }
10468 }
10469
10470 return simple_verify_memory (this, data, lma, size);
10471 }
10472
10473 /* compare-sections command
10474
10475 With no arguments, compares each loadable section in the exec bfd
10476 with the same memory range on the target, and reports mismatches.
10477 Useful for verifying the image on the target against the exec file. */
10478
10479 static void
10480 compare_sections_command (const char *args, int from_tty)
10481 {
10482 asection *s;
10483 const char *sectname;
10484 bfd_size_type size;
10485 bfd_vma lma;
10486 int matched = 0;
10487 int mismatched = 0;
10488 int res;
10489 int read_only = 0;
10490
10491 if (!exec_bfd)
10492 error (_("command cannot be used without an exec file"));
10493
10494 /* Make sure the remote is pointing at the right process. */
10495 set_general_process ();
10496
10497 if (args != NULL && strcmp (args, "-r") == 0)
10498 {
10499 read_only = 1;
10500 args = NULL;
10501 }
10502
10503 for (s = exec_bfd->sections; s; s = s->next)
10504 {
10505 if (!(s->flags & SEC_LOAD))
10506 continue; /* Skip non-loadable section. */
10507
10508 if (read_only && (s->flags & SEC_READONLY) == 0)
10509 continue; /* Skip writeable sections */
10510
10511 size = bfd_get_section_size (s);
10512 if (size == 0)
10513 continue; /* Skip zero-length section. */
10514
10515 sectname = bfd_get_section_name (exec_bfd, s);
10516 if (args && strcmp (args, sectname) != 0)
10517 continue; /* Not the section selected by user. */
10518
10519 matched = 1; /* Do this section. */
10520 lma = s->lma;
10521
10522 gdb::byte_vector sectdata (size);
10523 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10524
10525 res = target_verify_memory (sectdata.data (), lma, size);
10526
10527 if (res == -1)
10528 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10529 paddress (target_gdbarch (), lma),
10530 paddress (target_gdbarch (), lma + size));
10531
10532 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10533 paddress (target_gdbarch (), lma),
10534 paddress (target_gdbarch (), lma + size));
10535 if (res)
10536 printf_filtered ("matched.\n");
10537 else
10538 {
10539 printf_filtered ("MIS-MATCHED!\n");
10540 mismatched++;
10541 }
10542 }
10543 if (mismatched > 0)
10544 warning (_("One or more sections of the target image does not match\n\
10545 the loaded file\n"));
10546 if (args && !matched)
10547 printf_filtered (_("No loaded section named '%s'.\n"), args);
10548 }
10549
10550 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10551 into remote target. The number of bytes written to the remote
10552 target is returned, or -1 for error. */
10553
10554 static enum target_xfer_status
10555 remote_write_qxfer (const char *object_name,
10556 const char *annex, const gdb_byte *writebuf,
10557 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10558 struct packet_config *packet)
10559 {
10560 int i, buf_len;
10561 ULONGEST n;
10562 struct remote_state *rs = get_remote_state ();
10563 int max_size = get_memory_write_packet_size ();
10564
10565 if (packet_config_support (packet) == PACKET_DISABLE)
10566 return TARGET_XFER_E_IO;
10567
10568 /* Insert header. */
10569 i = snprintf (rs->buf, max_size,
10570 "qXfer:%s:write:%s:%s:",
10571 object_name, annex ? annex : "",
10572 phex_nz (offset, sizeof offset));
10573 max_size -= (i + 1);
10574
10575 /* Escape as much data as fits into rs->buf. */
10576 buf_len = remote_escape_output
10577 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10578
10579 if (putpkt_binary (rs->buf, i + buf_len) < 0
10580 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10581 || packet_ok (rs->buf, packet) != PACKET_OK)
10582 return TARGET_XFER_E_IO;
10583
10584 unpack_varlen_hex (rs->buf, &n);
10585
10586 *xfered_len = n;
10587 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10588 }
10589
10590 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10591 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10592 number of bytes read is returned, or 0 for EOF, or -1 for error.
10593 The number of bytes read may be less than LEN without indicating an
10594 EOF. PACKET is checked and updated to indicate whether the remote
10595 target supports this object. */
10596
10597 static enum target_xfer_status
10598 remote_read_qxfer (const char *object_name,
10599 const char *annex,
10600 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10601 ULONGEST *xfered_len,
10602 struct packet_config *packet)
10603 {
10604 struct remote_state *rs = get_remote_state ();
10605 LONGEST i, n, packet_len;
10606
10607 if (packet_config_support (packet) == PACKET_DISABLE)
10608 return TARGET_XFER_E_IO;
10609
10610 /* Check whether we've cached an end-of-object packet that matches
10611 this request. */
10612 if (rs->finished_object)
10613 {
10614 if (strcmp (object_name, rs->finished_object) == 0
10615 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10616 && offset == rs->finished_offset)
10617 return TARGET_XFER_EOF;
10618
10619
10620 /* Otherwise, we're now reading something different. Discard
10621 the cache. */
10622 xfree (rs->finished_object);
10623 xfree (rs->finished_annex);
10624 rs->finished_object = NULL;
10625 rs->finished_annex = NULL;
10626 }
10627
10628 /* Request only enough to fit in a single packet. The actual data
10629 may not, since we don't know how much of it will need to be escaped;
10630 the target is free to respond with slightly less data. We subtract
10631 five to account for the response type and the protocol frame. */
10632 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10633 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10634 object_name, annex ? annex : "",
10635 phex_nz (offset, sizeof offset),
10636 phex_nz (n, sizeof n));
10637 i = putpkt (rs->buf);
10638 if (i < 0)
10639 return TARGET_XFER_E_IO;
10640
10641 rs->buf[0] = '\0';
10642 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10643 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10644 return TARGET_XFER_E_IO;
10645
10646 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10647 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10648
10649 /* 'm' means there is (or at least might be) more data after this
10650 batch. That does not make sense unless there's at least one byte
10651 of data in this reply. */
10652 if (rs->buf[0] == 'm' && packet_len == 1)
10653 error (_("Remote qXfer reply contained no data."));
10654
10655 /* Got some data. */
10656 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10657 packet_len - 1, readbuf, n);
10658
10659 /* 'l' is an EOF marker, possibly including a final block of data,
10660 or possibly empty. If we have the final block of a non-empty
10661 object, record this fact to bypass a subsequent partial read. */
10662 if (rs->buf[0] == 'l' && offset + i > 0)
10663 {
10664 rs->finished_object = xstrdup (object_name);
10665 rs->finished_annex = xstrdup (annex ? annex : "");
10666 rs->finished_offset = offset + i;
10667 }
10668
10669 if (i == 0)
10670 return TARGET_XFER_EOF;
10671 else
10672 {
10673 *xfered_len = i;
10674 return TARGET_XFER_OK;
10675 }
10676 }
10677
10678 enum target_xfer_status
10679 remote_target::xfer_partial (enum target_object object,
10680 const char *annex, gdb_byte *readbuf,
10681 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10682 ULONGEST *xfered_len)
10683 {
10684 struct remote_state *rs;
10685 int i;
10686 char *p2;
10687 char query_type;
10688 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10689
10690 set_remote_traceframe ();
10691 set_general_thread (inferior_ptid);
10692
10693 rs = get_remote_state ();
10694
10695 /* Handle memory using the standard memory routines. */
10696 if (object == TARGET_OBJECT_MEMORY)
10697 {
10698 /* If the remote target is connected but not running, we should
10699 pass this request down to a lower stratum (e.g. the executable
10700 file). */
10701 if (!target_has_execution)
10702 return TARGET_XFER_EOF;
10703
10704 if (writebuf != NULL)
10705 return remote_write_bytes (offset, writebuf, len, unit_size,
10706 xfered_len);
10707 else
10708 return remote_read_bytes (this, offset, readbuf, len, unit_size,
10709 xfered_len);
10710 }
10711
10712 /* Handle SPU memory using qxfer packets. */
10713 if (object == TARGET_OBJECT_SPU)
10714 {
10715 if (readbuf)
10716 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10717 xfered_len, &remote_protocol_packets
10718 [PACKET_qXfer_spu_read]);
10719 else
10720 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10721 xfered_len, &remote_protocol_packets
10722 [PACKET_qXfer_spu_write]);
10723 }
10724
10725 /* Handle extra signal info using qxfer packets. */
10726 if (object == TARGET_OBJECT_SIGNAL_INFO)
10727 {
10728 if (readbuf)
10729 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10730 xfered_len, &remote_protocol_packets
10731 [PACKET_qXfer_siginfo_read]);
10732 else
10733 return remote_write_qxfer ("siginfo", annex,
10734 writebuf, offset, len, xfered_len,
10735 &remote_protocol_packets
10736 [PACKET_qXfer_siginfo_write]);
10737 }
10738
10739 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10740 {
10741 if (readbuf)
10742 return remote_read_qxfer ("statictrace", annex,
10743 readbuf, offset, len, xfered_len,
10744 &remote_protocol_packets
10745 [PACKET_qXfer_statictrace_read]);
10746 else
10747 return TARGET_XFER_E_IO;
10748 }
10749
10750 /* Only handle flash writes. */
10751 if (writebuf != NULL)
10752 {
10753 switch (object)
10754 {
10755 case TARGET_OBJECT_FLASH:
10756 return remote_flash_write (this, offset, len, xfered_len,
10757 writebuf);
10758
10759 default:
10760 return TARGET_XFER_E_IO;
10761 }
10762 }
10763
10764 /* Map pre-existing objects onto letters. DO NOT do this for new
10765 objects!!! Instead specify new query packets. */
10766 switch (object)
10767 {
10768 case TARGET_OBJECT_AVR:
10769 query_type = 'R';
10770 break;
10771
10772 case TARGET_OBJECT_AUXV:
10773 gdb_assert (annex == NULL);
10774 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10775 xfered_len,
10776 &remote_protocol_packets[PACKET_qXfer_auxv]);
10777
10778 case TARGET_OBJECT_AVAILABLE_FEATURES:
10779 return remote_read_qxfer
10780 ("features", annex, readbuf, offset, len, xfered_len,
10781 &remote_protocol_packets[PACKET_qXfer_features]);
10782
10783 case TARGET_OBJECT_LIBRARIES:
10784 return remote_read_qxfer
10785 ("libraries", annex, readbuf, offset, len, xfered_len,
10786 &remote_protocol_packets[PACKET_qXfer_libraries]);
10787
10788 case TARGET_OBJECT_LIBRARIES_SVR4:
10789 return remote_read_qxfer
10790 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10791 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10792
10793 case TARGET_OBJECT_MEMORY_MAP:
10794 gdb_assert (annex == NULL);
10795 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10796 xfered_len,
10797 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10798
10799 case TARGET_OBJECT_OSDATA:
10800 /* Should only get here if we're connected. */
10801 gdb_assert (rs->remote_desc);
10802 return remote_read_qxfer
10803 ("osdata", annex, readbuf, offset, len, xfered_len,
10804 &remote_protocol_packets[PACKET_qXfer_osdata]);
10805
10806 case TARGET_OBJECT_THREADS:
10807 gdb_assert (annex == NULL);
10808 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10809 xfered_len,
10810 &remote_protocol_packets[PACKET_qXfer_threads]);
10811
10812 case TARGET_OBJECT_TRACEFRAME_INFO:
10813 gdb_assert (annex == NULL);
10814 return remote_read_qxfer
10815 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
10816 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10817
10818 case TARGET_OBJECT_FDPIC:
10819 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
10820 xfered_len,
10821 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10822
10823 case TARGET_OBJECT_OPENVMS_UIB:
10824 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
10825 xfered_len,
10826 &remote_protocol_packets[PACKET_qXfer_uib]);
10827
10828 case TARGET_OBJECT_BTRACE:
10829 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
10830 xfered_len,
10831 &remote_protocol_packets[PACKET_qXfer_btrace]);
10832
10833 case TARGET_OBJECT_BTRACE_CONF:
10834 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
10835 len, xfered_len,
10836 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10837
10838 case TARGET_OBJECT_EXEC_FILE:
10839 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
10840 len, xfered_len,
10841 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10842
10843 default:
10844 return TARGET_XFER_E_IO;
10845 }
10846
10847 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10848 large enough let the caller deal with it. */
10849 if (len < get_remote_packet_size ())
10850 return TARGET_XFER_E_IO;
10851 len = get_remote_packet_size ();
10852
10853 /* Except for querying the minimum buffer size, target must be open. */
10854 if (!rs->remote_desc)
10855 error (_("remote query is only available after target open"));
10856
10857 gdb_assert (annex != NULL);
10858 gdb_assert (readbuf != NULL);
10859
10860 p2 = rs->buf;
10861 *p2++ = 'q';
10862 *p2++ = query_type;
10863
10864 /* We used one buffer char for the remote protocol q command and
10865 another for the query type. As the remote protocol encapsulation
10866 uses 4 chars plus one extra in case we are debugging
10867 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10868 string. */
10869 i = 0;
10870 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10871 {
10872 /* Bad caller may have sent forbidden characters. */
10873 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10874 *p2++ = annex[i];
10875 i++;
10876 }
10877 *p2 = '\0';
10878 gdb_assert (annex[i] == '\0');
10879
10880 i = putpkt (rs->buf);
10881 if (i < 0)
10882 return TARGET_XFER_E_IO;
10883
10884 getpkt (&rs->buf, &rs->buf_size, 0);
10885 strcpy ((char *) readbuf, rs->buf);
10886
10887 *xfered_len = strlen ((char *) readbuf);
10888 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10889 }
10890
10891 /* Implementation of to_get_memory_xfer_limit. */
10892
10893 ULONGEST
10894 remote_target::get_memory_xfer_limit ()
10895 {
10896 return get_memory_write_packet_size ();
10897 }
10898
10899 int
10900 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
10901 const gdb_byte *pattern, ULONGEST pattern_len,
10902 CORE_ADDR *found_addrp)
10903 {
10904 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10905 struct remote_state *rs = get_remote_state ();
10906 int max_size = get_memory_write_packet_size ();
10907 struct packet_config *packet =
10908 &remote_protocol_packets[PACKET_qSearch_memory];
10909 /* Number of packet bytes used to encode the pattern;
10910 this could be more than PATTERN_LEN due to escape characters. */
10911 int escaped_pattern_len;
10912 /* Amount of pattern that was encodable in the packet. */
10913 int used_pattern_len;
10914 int i;
10915 int found;
10916 ULONGEST found_addr;
10917
10918 /* Don't go to the target if we don't have to. This is done before
10919 checking packet_config_support to avoid the possibility that a
10920 success for this edge case means the facility works in
10921 general. */
10922 if (pattern_len > search_space_len)
10923 return 0;
10924 if (pattern_len == 0)
10925 {
10926 *found_addrp = start_addr;
10927 return 1;
10928 }
10929
10930 /* If we already know the packet isn't supported, fall back to the simple
10931 way of searching memory. */
10932
10933 if (packet_config_support (packet) == PACKET_DISABLE)
10934 {
10935 /* Target doesn't provided special support, fall back and use the
10936 standard support (copy memory and do the search here). */
10937 return simple_search_memory (this, start_addr, search_space_len,
10938 pattern, pattern_len, found_addrp);
10939 }
10940
10941 /* Make sure the remote is pointing at the right process. */
10942 set_general_process ();
10943
10944 /* Insert header. */
10945 i = snprintf (rs->buf, max_size,
10946 "qSearch:memory:%s;%s;",
10947 phex_nz (start_addr, addr_size),
10948 phex_nz (search_space_len, sizeof (search_space_len)));
10949 max_size -= (i + 1);
10950
10951 /* Escape as much data as fits into rs->buf. */
10952 escaped_pattern_len =
10953 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10954 &used_pattern_len, max_size);
10955
10956 /* Bail if the pattern is too large. */
10957 if (used_pattern_len != pattern_len)
10958 error (_("Pattern is too large to transmit to remote target."));
10959
10960 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10961 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10962 || packet_ok (rs->buf, packet) != PACKET_OK)
10963 {
10964 /* The request may not have worked because the command is not
10965 supported. If so, fall back to the simple way. */
10966 if (packet_config_support (packet) == PACKET_DISABLE)
10967 {
10968 return simple_search_memory (this, start_addr, search_space_len,
10969 pattern, pattern_len, found_addrp);
10970 }
10971 return -1;
10972 }
10973
10974 if (rs->buf[0] == '0')
10975 found = 0;
10976 else if (rs->buf[0] == '1')
10977 {
10978 found = 1;
10979 if (rs->buf[1] != ',')
10980 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10981 unpack_varlen_hex (rs->buf + 2, &found_addr);
10982 *found_addrp = found_addr;
10983 }
10984 else
10985 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10986
10987 return found;
10988 }
10989
10990 void
10991 remote_target::rcmd (const char *command, struct ui_file *outbuf)
10992 {
10993 struct remote_state *rs = get_remote_state ();
10994 char *p = rs->buf;
10995
10996 if (!rs->remote_desc)
10997 error (_("remote rcmd is only available after target open"));
10998
10999 /* Send a NULL command across as an empty command. */
11000 if (command == NULL)
11001 command = "";
11002
11003 /* The query prefix. */
11004 strcpy (rs->buf, "qRcmd,");
11005 p = strchr (rs->buf, '\0');
11006
11007 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11008 > get_remote_packet_size ())
11009 error (_("\"monitor\" command ``%s'' is too long."), command);
11010
11011 /* Encode the actual command. */
11012 bin2hex ((const gdb_byte *) command, p, strlen (command));
11013
11014 if (putpkt (rs->buf) < 0)
11015 error (_("Communication problem with target."));
11016
11017 /* get/display the response */
11018 while (1)
11019 {
11020 char *buf;
11021
11022 /* XXX - see also remote_get_noisy_reply(). */
11023 QUIT; /* Allow user to bail out with ^C. */
11024 rs->buf[0] = '\0';
11025 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11026 {
11027 /* Timeout. Continue to (try to) read responses.
11028 This is better than stopping with an error, assuming the stub
11029 is still executing the (long) monitor command.
11030 If needed, the user can interrupt gdb using C-c, obtaining
11031 an effect similar to stop on timeout. */
11032 continue;
11033 }
11034 buf = rs->buf;
11035 if (buf[0] == '\0')
11036 error (_("Target does not support this command."));
11037 if (buf[0] == 'O' && buf[1] != 'K')
11038 {
11039 remote_console_output (buf + 1); /* 'O' message from stub. */
11040 continue;
11041 }
11042 if (strcmp (buf, "OK") == 0)
11043 break;
11044 if (strlen (buf) == 3 && buf[0] == 'E'
11045 && isdigit (buf[1]) && isdigit (buf[2]))
11046 {
11047 error (_("Protocol error with Rcmd"));
11048 }
11049 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11050 {
11051 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11052
11053 fputc_unfiltered (c, outbuf);
11054 }
11055 break;
11056 }
11057 }
11058
11059 std::vector<mem_region>
11060 remote_target::memory_map ()
11061 {
11062 std::vector<mem_region> result;
11063 gdb::optional<gdb::char_vector> text
11064 = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
11065
11066 if (text)
11067 result = parse_memory_map (text->data ());
11068
11069 return result;
11070 }
11071
11072 static void
11073 packet_command (const char *args, int from_tty)
11074 {
11075 struct remote_state *rs = get_remote_state ();
11076
11077 if (!rs->remote_desc)
11078 error (_("command can only be used with remote target"));
11079
11080 if (!args)
11081 error (_("remote-packet command requires packet text as argument"));
11082
11083 puts_filtered ("sending: ");
11084 print_packet (args);
11085 puts_filtered ("\n");
11086 putpkt (args);
11087
11088 getpkt (&rs->buf, &rs->buf_size, 0);
11089 puts_filtered ("received: ");
11090 print_packet (rs->buf);
11091 puts_filtered ("\n");
11092 }
11093
11094 #if 0
11095 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11096
11097 static void display_thread_info (struct gdb_ext_thread_info *info);
11098
11099 static void threadset_test_cmd (char *cmd, int tty);
11100
11101 static void threadalive_test (char *cmd, int tty);
11102
11103 static void threadlist_test_cmd (char *cmd, int tty);
11104
11105 int get_and_display_threadinfo (threadref *ref);
11106
11107 static void threadinfo_test_cmd (char *cmd, int tty);
11108
11109 static int thread_display_step (threadref *ref, void *context);
11110
11111 static void threadlist_update_test_cmd (char *cmd, int tty);
11112
11113 static void init_remote_threadtests (void);
11114
11115 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11116
11117 static void
11118 threadset_test_cmd (const char *cmd, int tty)
11119 {
11120 int sample_thread = SAMPLE_THREAD;
11121
11122 printf_filtered (_("Remote threadset test\n"));
11123 set_general_thread (sample_thread);
11124 }
11125
11126
11127 static void
11128 threadalive_test (const char *cmd, int tty)
11129 {
11130 int sample_thread = SAMPLE_THREAD;
11131 int pid = ptid_get_pid (inferior_ptid);
11132 ptid_t ptid = ptid_build (pid, sample_thread, 0);
11133
11134 if (remote_thread_alive (ptid))
11135 printf_filtered ("PASS: Thread alive test\n");
11136 else
11137 printf_filtered ("FAIL: Thread alive test\n");
11138 }
11139
11140 void output_threadid (char *title, threadref *ref);
11141
11142 void
11143 output_threadid (char *title, threadref *ref)
11144 {
11145 char hexid[20];
11146
11147 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
11148 hexid[16] = 0;
11149 printf_filtered ("%s %s\n", title, (&hexid[0]));
11150 }
11151
11152 static void
11153 threadlist_test_cmd (const char *cmd, int tty)
11154 {
11155 int startflag = 1;
11156 threadref nextthread;
11157 int done, result_count;
11158 threadref threadlist[3];
11159
11160 printf_filtered ("Remote Threadlist test\n");
11161 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11162 &result_count, &threadlist[0]))
11163 printf_filtered ("FAIL: threadlist test\n");
11164 else
11165 {
11166 threadref *scan = threadlist;
11167 threadref *limit = scan + result_count;
11168
11169 while (scan < limit)
11170 output_threadid (" thread ", scan++);
11171 }
11172 }
11173
11174 void
11175 display_thread_info (struct gdb_ext_thread_info *info)
11176 {
11177 output_threadid ("Threadid: ", &info->threadid);
11178 printf_filtered ("Name: %s\n ", info->shortname);
11179 printf_filtered ("State: %s\n", info->display);
11180 printf_filtered ("other: %s\n\n", info->more_display);
11181 }
11182
11183 int
11184 get_and_display_threadinfo (threadref *ref)
11185 {
11186 int result;
11187 int set;
11188 struct gdb_ext_thread_info threadinfo;
11189
11190 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11191 | TAG_MOREDISPLAY | TAG_DISPLAY;
11192 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11193 display_thread_info (&threadinfo);
11194 return result;
11195 }
11196
11197 static void
11198 threadinfo_test_cmd (const char *cmd, int tty)
11199 {
11200 int athread = SAMPLE_THREAD;
11201 threadref thread;
11202 int set;
11203
11204 int_to_threadref (&thread, athread);
11205 printf_filtered ("Remote Threadinfo test\n");
11206 if (!get_and_display_threadinfo (&thread))
11207 printf_filtered ("FAIL cannot get thread info\n");
11208 }
11209
11210 static int
11211 thread_display_step (threadref *ref, void *context)
11212 {
11213 /* output_threadid(" threadstep ",ref); *//* simple test */
11214 return get_and_display_threadinfo (ref);
11215 }
11216
11217 static void
11218 threadlist_update_test_cmd (const char *cmd, int tty)
11219 {
11220 printf_filtered ("Remote Threadlist update test\n");
11221 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11222 }
11223
11224 static void
11225 init_remote_threadtests (void)
11226 {
11227 add_com ("tlist", class_obscure, threadlist_test_cmd,
11228 _("Fetch and print the remote list of "
11229 "thread identifiers, one pkt only"));
11230 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11231 _("Fetch and display info about one thread"));
11232 add_com ("tset", class_obscure, threadset_test_cmd,
11233 _("Test setting to a different thread"));
11234 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11235 _("Iterate through updating all remote thread info"));
11236 add_com ("talive", class_obscure, threadalive_test,
11237 _(" Remote thread alive test "));
11238 }
11239
11240 #endif /* 0 */
11241
11242 /* Convert a thread ID to a string. Returns the string in a static
11243 buffer. */
11244
11245 const char *
11246 remote_target::pid_to_str (ptid_t ptid)
11247 {
11248 static char buf[64];
11249 struct remote_state *rs = get_remote_state ();
11250
11251 if (ptid_equal (ptid, null_ptid))
11252 return normal_pid_to_str (ptid);
11253 else if (ptid_is_pid (ptid))
11254 {
11255 /* Printing an inferior target id. */
11256
11257 /* When multi-process extensions are off, there's no way in the
11258 remote protocol to know the remote process id, if there's any
11259 at all. There's one exception --- when we're connected with
11260 target extended-remote, and we manually attached to a process
11261 with "attach PID". We don't record anywhere a flag that
11262 allows us to distinguish that case from the case of
11263 connecting with extended-remote and the stub already being
11264 attached to a process, and reporting yes to qAttached, hence
11265 no smart special casing here. */
11266 if (!remote_multi_process_p (rs))
11267 {
11268 xsnprintf (buf, sizeof buf, "Remote target");
11269 return buf;
11270 }
11271
11272 return normal_pid_to_str (ptid);
11273 }
11274 else
11275 {
11276 if (ptid_equal (magic_null_ptid, ptid))
11277 xsnprintf (buf, sizeof buf, "Thread <main>");
11278 else if (remote_multi_process_p (rs))
11279 if (ptid_get_lwp (ptid) == 0)
11280 return normal_pid_to_str (ptid);
11281 else
11282 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11283 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11284 else
11285 xsnprintf (buf, sizeof buf, "Thread %ld",
11286 ptid_get_lwp (ptid));
11287 return buf;
11288 }
11289 }
11290
11291 /* Get the address of the thread local variable in OBJFILE which is
11292 stored at OFFSET within the thread local storage for thread PTID. */
11293
11294 CORE_ADDR
11295 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11296 CORE_ADDR offset)
11297 {
11298 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11299 {
11300 struct remote_state *rs = get_remote_state ();
11301 char *p = rs->buf;
11302 char *endp = rs->buf + get_remote_packet_size ();
11303 enum packet_result result;
11304
11305 strcpy (p, "qGetTLSAddr:");
11306 p += strlen (p);
11307 p = write_ptid (p, endp, ptid);
11308 *p++ = ',';
11309 p += hexnumstr (p, offset);
11310 *p++ = ',';
11311 p += hexnumstr (p, lm);
11312 *p++ = '\0';
11313
11314 putpkt (rs->buf);
11315 getpkt (&rs->buf, &rs->buf_size, 0);
11316 result = packet_ok (rs->buf,
11317 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11318 if (result == PACKET_OK)
11319 {
11320 ULONGEST result;
11321
11322 unpack_varlen_hex (rs->buf, &result);
11323 return result;
11324 }
11325 else if (result == PACKET_UNKNOWN)
11326 throw_error (TLS_GENERIC_ERROR,
11327 _("Remote target doesn't support qGetTLSAddr packet"));
11328 else
11329 throw_error (TLS_GENERIC_ERROR,
11330 _("Remote target failed to process qGetTLSAddr request"));
11331 }
11332 else
11333 throw_error (TLS_GENERIC_ERROR,
11334 _("TLS not supported or disabled on this target"));
11335 /* Not reached. */
11336 return 0;
11337 }
11338
11339 /* Provide thread local base, i.e. Thread Information Block address.
11340 Returns 1 if ptid is found and thread_local_base is non zero. */
11341
11342 bool
11343 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11344 {
11345 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11346 {
11347 struct remote_state *rs = get_remote_state ();
11348 char *p = rs->buf;
11349 char *endp = rs->buf + get_remote_packet_size ();
11350 enum packet_result result;
11351
11352 strcpy (p, "qGetTIBAddr:");
11353 p += strlen (p);
11354 p = write_ptid (p, endp, ptid);
11355 *p++ = '\0';
11356
11357 putpkt (rs->buf);
11358 getpkt (&rs->buf, &rs->buf_size, 0);
11359 result = packet_ok (rs->buf,
11360 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11361 if (result == PACKET_OK)
11362 {
11363 ULONGEST result;
11364
11365 unpack_varlen_hex (rs->buf, &result);
11366 if (addr)
11367 *addr = (CORE_ADDR) result;
11368 return true;
11369 }
11370 else if (result == PACKET_UNKNOWN)
11371 error (_("Remote target doesn't support qGetTIBAddr packet"));
11372 else
11373 error (_("Remote target failed to process qGetTIBAddr request"));
11374 }
11375 else
11376 error (_("qGetTIBAddr not supported or disabled on this target"));
11377 /* Not reached. */
11378 return false;
11379 }
11380
11381 /* Support for inferring a target description based on the current
11382 architecture and the size of a 'g' packet. While the 'g' packet
11383 can have any size (since optional registers can be left off the
11384 end), some sizes are easily recognizable given knowledge of the
11385 approximate architecture. */
11386
11387 struct remote_g_packet_guess
11388 {
11389 int bytes;
11390 const struct target_desc *tdesc;
11391 };
11392 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11393 DEF_VEC_O(remote_g_packet_guess_s);
11394
11395 struct remote_g_packet_data
11396 {
11397 VEC(remote_g_packet_guess_s) *guesses;
11398 };
11399
11400 static struct gdbarch_data *remote_g_packet_data_handle;
11401
11402 static void *
11403 remote_g_packet_data_init (struct obstack *obstack)
11404 {
11405 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11406 }
11407
11408 void
11409 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11410 const struct target_desc *tdesc)
11411 {
11412 struct remote_g_packet_data *data
11413 = ((struct remote_g_packet_data *)
11414 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11415 struct remote_g_packet_guess new_guess, *guess;
11416 int ix;
11417
11418 gdb_assert (tdesc != NULL);
11419
11420 for (ix = 0;
11421 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11422 ix++)
11423 if (guess->bytes == bytes)
11424 internal_error (__FILE__, __LINE__,
11425 _("Duplicate g packet description added for size %d"),
11426 bytes);
11427
11428 new_guess.bytes = bytes;
11429 new_guess.tdesc = tdesc;
11430 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11431 }
11432
11433 /* Return 1 if remote_read_description would do anything on this target
11434 and architecture, 0 otherwise. */
11435
11436 static int
11437 remote_read_description_p (struct target_ops *target)
11438 {
11439 struct remote_g_packet_data *data
11440 = ((struct remote_g_packet_data *)
11441 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11442
11443 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11444 return 1;
11445
11446 return 0;
11447 }
11448
11449 const struct target_desc *
11450 remote_target::read_description ()
11451 {
11452 struct remote_g_packet_data *data
11453 = ((struct remote_g_packet_data *)
11454 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11455
11456 /* Do not try this during initial connection, when we do not know
11457 whether there is a running but stopped thread. */
11458 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11459 return beneath->read_description ();
11460
11461 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11462 {
11463 struct remote_g_packet_guess *guess;
11464 int ix;
11465 int bytes = send_g_packet ();
11466
11467 for (ix = 0;
11468 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11469 ix++)
11470 if (guess->bytes == bytes)
11471 return guess->tdesc;
11472
11473 /* We discard the g packet. A minor optimization would be to
11474 hold on to it, and fill the register cache once we have selected
11475 an architecture, but it's too tricky to do safely. */
11476 }
11477
11478 return beneath->read_description ();
11479 }
11480
11481 /* Remote file transfer support. This is host-initiated I/O, not
11482 target-initiated; for target-initiated, see remote-fileio.c. */
11483
11484 /* If *LEFT is at least the length of STRING, copy STRING to
11485 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11486 decrease *LEFT. Otherwise raise an error. */
11487
11488 static void
11489 remote_buffer_add_string (char **buffer, int *left, const char *string)
11490 {
11491 int len = strlen (string);
11492
11493 if (len > *left)
11494 error (_("Packet too long for target."));
11495
11496 memcpy (*buffer, string, len);
11497 *buffer += len;
11498 *left -= len;
11499
11500 /* NUL-terminate the buffer as a convenience, if there is
11501 room. */
11502 if (*left)
11503 **buffer = '\0';
11504 }
11505
11506 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11507 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11508 decrease *LEFT. Otherwise raise an error. */
11509
11510 static void
11511 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11512 int len)
11513 {
11514 if (2 * len > *left)
11515 error (_("Packet too long for target."));
11516
11517 bin2hex (bytes, *buffer, len);
11518 *buffer += 2 * len;
11519 *left -= 2 * len;
11520
11521 /* NUL-terminate the buffer as a convenience, if there is
11522 room. */
11523 if (*left)
11524 **buffer = '\0';
11525 }
11526
11527 /* If *LEFT is large enough, convert VALUE to hex and add it to
11528 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11529 decrease *LEFT. Otherwise raise an error. */
11530
11531 static void
11532 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11533 {
11534 int len = hexnumlen (value);
11535
11536 if (len > *left)
11537 error (_("Packet too long for target."));
11538
11539 hexnumstr (*buffer, value);
11540 *buffer += len;
11541 *left -= len;
11542
11543 /* NUL-terminate the buffer as a convenience, if there is
11544 room. */
11545 if (*left)
11546 **buffer = '\0';
11547 }
11548
11549 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11550 value, *REMOTE_ERRNO to the remote error number or zero if none
11551 was included, and *ATTACHMENT to point to the start of the annex
11552 if any. The length of the packet isn't needed here; there may
11553 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11554
11555 Return 0 if the packet could be parsed, -1 if it could not. If
11556 -1 is returned, the other variables may not be initialized. */
11557
11558 static int
11559 remote_hostio_parse_result (char *buffer, int *retcode,
11560 int *remote_errno, char **attachment)
11561 {
11562 char *p, *p2;
11563
11564 *remote_errno = 0;
11565 *attachment = NULL;
11566
11567 if (buffer[0] != 'F')
11568 return -1;
11569
11570 errno = 0;
11571 *retcode = strtol (&buffer[1], &p, 16);
11572 if (errno != 0 || p == &buffer[1])
11573 return -1;
11574
11575 /* Check for ",errno". */
11576 if (*p == ',')
11577 {
11578 errno = 0;
11579 *remote_errno = strtol (p + 1, &p2, 16);
11580 if (errno != 0 || p + 1 == p2)
11581 return -1;
11582 p = p2;
11583 }
11584
11585 /* Check for ";attachment". If there is no attachment, the
11586 packet should end here. */
11587 if (*p == ';')
11588 {
11589 *attachment = p + 1;
11590 return 0;
11591 }
11592 else if (*p == '\0')
11593 return 0;
11594 else
11595 return -1;
11596 }
11597
11598 /* Send a prepared I/O packet to the target and read its response.
11599 The prepared packet is in the global RS->BUF before this function
11600 is called, and the answer is there when we return.
11601
11602 COMMAND_BYTES is the length of the request to send, which may include
11603 binary data. WHICH_PACKET is the packet configuration to check
11604 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11605 is set to the error number and -1 is returned. Otherwise the value
11606 returned by the function is returned.
11607
11608 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11609 attachment is expected; an error will be reported if there's a
11610 mismatch. If one is found, *ATTACHMENT will be set to point into
11611 the packet buffer and *ATTACHMENT_LEN will be set to the
11612 attachment's length. */
11613
11614 static int
11615 remote_hostio_send_command (int command_bytes, int which_packet,
11616 int *remote_errno, char **attachment,
11617 int *attachment_len)
11618 {
11619 struct remote_state *rs = get_remote_state ();
11620 int ret, bytes_read;
11621 char *attachment_tmp;
11622
11623 if (packet_support (which_packet) == PACKET_DISABLE)
11624 {
11625 *remote_errno = FILEIO_ENOSYS;
11626 return -1;
11627 }
11628
11629 putpkt_binary (rs->buf, command_bytes);
11630 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11631
11632 /* If it timed out, something is wrong. Don't try to parse the
11633 buffer. */
11634 if (bytes_read < 0)
11635 {
11636 *remote_errno = FILEIO_EINVAL;
11637 return -1;
11638 }
11639
11640 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11641 {
11642 case PACKET_ERROR:
11643 *remote_errno = FILEIO_EINVAL;
11644 return -1;
11645 case PACKET_UNKNOWN:
11646 *remote_errno = FILEIO_ENOSYS;
11647 return -1;
11648 case PACKET_OK:
11649 break;
11650 }
11651
11652 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11653 &attachment_tmp))
11654 {
11655 *remote_errno = FILEIO_EINVAL;
11656 return -1;
11657 }
11658
11659 /* Make sure we saw an attachment if and only if we expected one. */
11660 if ((attachment_tmp == NULL && attachment != NULL)
11661 || (attachment_tmp != NULL && attachment == NULL))
11662 {
11663 *remote_errno = FILEIO_EINVAL;
11664 return -1;
11665 }
11666
11667 /* If an attachment was found, it must point into the packet buffer;
11668 work out how many bytes there were. */
11669 if (attachment_tmp != NULL)
11670 {
11671 *attachment = attachment_tmp;
11672 *attachment_len = bytes_read - (*attachment - rs->buf);
11673 }
11674
11675 return ret;
11676 }
11677
11678 /* Invalidate the readahead cache. */
11679
11680 static void
11681 readahead_cache_invalidate (void)
11682 {
11683 struct remote_state *rs = get_remote_state ();
11684
11685 rs->readahead_cache.fd = -1;
11686 }
11687
11688 /* Invalidate the readahead cache if it is holding data for FD. */
11689
11690 static void
11691 readahead_cache_invalidate_fd (int fd)
11692 {
11693 struct remote_state *rs = get_remote_state ();
11694
11695 if (rs->readahead_cache.fd == fd)
11696 rs->readahead_cache.fd = -1;
11697 }
11698
11699 /* Set the filesystem remote_hostio functions that take FILENAME
11700 arguments will use. Return 0 on success, or -1 if an error
11701 occurs (and set *REMOTE_ERRNO). */
11702
11703 static int
11704 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11705 {
11706 struct remote_state *rs = get_remote_state ();
11707 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11708 char *p = rs->buf;
11709 int left = get_remote_packet_size () - 1;
11710 char arg[9];
11711 int ret;
11712
11713 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11714 return 0;
11715
11716 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11717 return 0;
11718
11719 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11720
11721 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11722 remote_buffer_add_string (&p, &left, arg);
11723
11724 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11725 remote_errno, NULL, NULL);
11726
11727 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11728 return 0;
11729
11730 if (ret == 0)
11731 rs->fs_pid = required_pid;
11732
11733 return ret;
11734 }
11735
11736 /* Implementation of to_fileio_open. */
11737
11738 static int
11739 remote_hostio_open (struct target_ops *self,
11740 struct inferior *inf, const char *filename,
11741 int flags, int mode, int warn_if_slow,
11742 int *remote_errno)
11743 {
11744 struct remote_state *rs = get_remote_state ();
11745 char *p = rs->buf;
11746 int left = get_remote_packet_size () - 1;
11747
11748 if (warn_if_slow)
11749 {
11750 static int warning_issued = 0;
11751
11752 printf_unfiltered (_("Reading %s from remote target...\n"),
11753 filename);
11754
11755 if (!warning_issued)
11756 {
11757 warning (_("File transfers from remote targets can be slow."
11758 " Use \"set sysroot\" to access files locally"
11759 " instead."));
11760 warning_issued = 1;
11761 }
11762 }
11763
11764 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11765 return -1;
11766
11767 remote_buffer_add_string (&p, &left, "vFile:open:");
11768
11769 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11770 strlen (filename));
11771 remote_buffer_add_string (&p, &left, ",");
11772
11773 remote_buffer_add_int (&p, &left, flags);
11774 remote_buffer_add_string (&p, &left, ",");
11775
11776 remote_buffer_add_int (&p, &left, mode);
11777
11778 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11779 remote_errno, NULL, NULL);
11780 }
11781
11782 int
11783 remote_target::fileio_open (struct inferior *inf, const char *filename,
11784 int flags, int mode, int warn_if_slow,
11785 int *remote_errno)
11786 {
11787 return remote_hostio_open (this, inf, filename, flags, mode, warn_if_slow,
11788 remote_errno);
11789 }
11790
11791 /* Implementation of to_fileio_pwrite. */
11792
11793 static int
11794 remote_hostio_pwrite (struct target_ops *self,
11795 int fd, const gdb_byte *write_buf, int len,
11796 ULONGEST offset, int *remote_errno)
11797 {
11798 struct remote_state *rs = get_remote_state ();
11799 char *p = rs->buf;
11800 int left = get_remote_packet_size ();
11801 int out_len;
11802
11803 readahead_cache_invalidate_fd (fd);
11804
11805 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11806
11807 remote_buffer_add_int (&p, &left, fd);
11808 remote_buffer_add_string (&p, &left, ",");
11809
11810 remote_buffer_add_int (&p, &left, offset);
11811 remote_buffer_add_string (&p, &left, ",");
11812
11813 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11814 get_remote_packet_size () - (p - rs->buf));
11815
11816 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11817 remote_errno, NULL, NULL);
11818 }
11819
11820 int
11821 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
11822 ULONGEST offset, int *remote_errno)
11823 {
11824 return remote_hostio_pwrite (this, fd, write_buf, len, offset, remote_errno);
11825 }
11826
11827 /* Helper for the implementation of to_fileio_pread. Read the file
11828 from the remote side with vFile:pread. */
11829
11830 static int
11831 remote_hostio_pread_vFile (struct target_ops *self,
11832 int fd, gdb_byte *read_buf, int len,
11833 ULONGEST offset, int *remote_errno)
11834 {
11835 struct remote_state *rs = get_remote_state ();
11836 char *p = rs->buf;
11837 char *attachment;
11838 int left = get_remote_packet_size ();
11839 int ret, attachment_len;
11840 int read_len;
11841
11842 remote_buffer_add_string (&p, &left, "vFile:pread:");
11843
11844 remote_buffer_add_int (&p, &left, fd);
11845 remote_buffer_add_string (&p, &left, ",");
11846
11847 remote_buffer_add_int (&p, &left, len);
11848 remote_buffer_add_string (&p, &left, ",");
11849
11850 remote_buffer_add_int (&p, &left, offset);
11851
11852 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11853 remote_errno, &attachment,
11854 &attachment_len);
11855
11856 if (ret < 0)
11857 return ret;
11858
11859 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11860 read_buf, len);
11861 if (read_len != ret)
11862 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11863
11864 return ret;
11865 }
11866
11867 /* Serve pread from the readahead cache. Returns number of bytes
11868 read, or 0 if the request can't be served from the cache. */
11869
11870 static int
11871 remote_hostio_pread_from_cache (struct remote_state *rs,
11872 int fd, gdb_byte *read_buf, size_t len,
11873 ULONGEST offset)
11874 {
11875 struct readahead_cache *cache = &rs->readahead_cache;
11876
11877 if (cache->fd == fd
11878 && cache->offset <= offset
11879 && offset < cache->offset + cache->bufsize)
11880 {
11881 ULONGEST max = cache->offset + cache->bufsize;
11882
11883 if (offset + len > max)
11884 len = max - offset;
11885
11886 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11887 return len;
11888 }
11889
11890 return 0;
11891 }
11892
11893 /* Implementation of to_fileio_pread. */
11894
11895 static int
11896 remote_hostio_pread (struct target_ops *self,
11897 int fd, gdb_byte *read_buf, int len,
11898 ULONGEST offset, int *remote_errno)
11899 {
11900 int ret;
11901 struct remote_state *rs = get_remote_state ();
11902 struct readahead_cache *cache = &rs->readahead_cache;
11903
11904 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11905 if (ret > 0)
11906 {
11907 cache->hit_count++;
11908
11909 if (remote_debug)
11910 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11911 pulongest (cache->hit_count));
11912 return ret;
11913 }
11914
11915 cache->miss_count++;
11916 if (remote_debug)
11917 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11918 pulongest (cache->miss_count));
11919
11920 cache->fd = fd;
11921 cache->offset = offset;
11922 cache->bufsize = get_remote_packet_size ();
11923 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11924
11925 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11926 cache->offset, remote_errno);
11927 if (ret <= 0)
11928 {
11929 readahead_cache_invalidate_fd (fd);
11930 return ret;
11931 }
11932
11933 cache->bufsize = ret;
11934 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11935 }
11936
11937 int
11938 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
11939 ULONGEST offset, int *remote_errno)
11940 {
11941 return remote_hostio_pread (this, fd, read_buf, len, offset, remote_errno);
11942 }
11943
11944 /* Implementation of to_fileio_close. */
11945
11946 static int
11947 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11948 {
11949 struct remote_state *rs = get_remote_state ();
11950 char *p = rs->buf;
11951 int left = get_remote_packet_size () - 1;
11952
11953 readahead_cache_invalidate_fd (fd);
11954
11955 remote_buffer_add_string (&p, &left, "vFile:close:");
11956
11957 remote_buffer_add_int (&p, &left, fd);
11958
11959 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11960 remote_errno, NULL, NULL);
11961 }
11962
11963 int
11964 remote_target::fileio_close (int fd, int *remote_errno)
11965 {
11966 return remote_hostio_close (this, fd, remote_errno);
11967 }
11968
11969 /* Implementation of to_fileio_unlink. */
11970
11971 static int
11972 remote_hostio_unlink (struct target_ops *self,
11973 struct inferior *inf, const char *filename,
11974 int *remote_errno)
11975 {
11976 struct remote_state *rs = get_remote_state ();
11977 char *p = rs->buf;
11978 int left = get_remote_packet_size () - 1;
11979
11980 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11981 return -1;
11982
11983 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11984
11985 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11986 strlen (filename));
11987
11988 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11989 remote_errno, NULL, NULL);
11990 }
11991
11992 int
11993 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
11994 int *remote_errno)
11995 {
11996 return remote_hostio_unlink (this, inf, filename, remote_errno);
11997 }
11998
11999 /* Implementation of to_fileio_readlink. */
12000
12001 gdb::optional<std::string>
12002 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12003 int *remote_errno)
12004 {
12005 struct remote_state *rs = get_remote_state ();
12006 char *p = rs->buf;
12007 char *attachment;
12008 int left = get_remote_packet_size ();
12009 int len, attachment_len;
12010 int read_len;
12011
12012 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12013 return {};
12014
12015 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12016
12017 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12018 strlen (filename));
12019
12020 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12021 remote_errno, &attachment,
12022 &attachment_len);
12023
12024 if (len < 0)
12025 return {};
12026
12027 std::string ret (len, '\0');
12028
12029 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12030 (gdb_byte *) &ret[0], len);
12031 if (read_len != len)
12032 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12033
12034 return ret;
12035 }
12036
12037 /* Implementation of to_fileio_fstat. */
12038
12039 int
12040 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12041 {
12042 struct remote_state *rs = get_remote_state ();
12043 char *p = rs->buf;
12044 int left = get_remote_packet_size ();
12045 int attachment_len, ret;
12046 char *attachment;
12047 struct fio_stat fst;
12048 int read_len;
12049
12050 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12051
12052 remote_buffer_add_int (&p, &left, fd);
12053
12054 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12055 remote_errno, &attachment,
12056 &attachment_len);
12057 if (ret < 0)
12058 {
12059 if (*remote_errno != FILEIO_ENOSYS)
12060 return ret;
12061
12062 /* Strictly we should return -1, ENOSYS here, but when
12063 "set sysroot remote:" was implemented in August 2008
12064 BFD's need for a stat function was sidestepped with
12065 this hack. This was not remedied until March 2015
12066 so we retain the previous behavior to avoid breaking
12067 compatibility.
12068
12069 Note that the memset is a March 2015 addition; older
12070 GDBs set st_size *and nothing else* so the structure
12071 would have garbage in all other fields. This might
12072 break something but retaining the previous behavior
12073 here would be just too wrong. */
12074
12075 memset (st, 0, sizeof (struct stat));
12076 st->st_size = INT_MAX;
12077 return 0;
12078 }
12079
12080 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12081 (gdb_byte *) &fst, sizeof (fst));
12082
12083 if (read_len != ret)
12084 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12085
12086 if (read_len != sizeof (fst))
12087 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12088 read_len, (int) sizeof (fst));
12089
12090 remote_fileio_to_host_stat (&fst, st);
12091
12092 return 0;
12093 }
12094
12095 /* Implementation of to_filesystem_is_local. */
12096
12097 bool
12098 remote_target::filesystem_is_local ()
12099 {
12100 /* Valgrind GDB presents itself as a remote target but works
12101 on the local filesystem: it does not implement remote get
12102 and users are not expected to set a sysroot. To handle
12103 this case we treat the remote filesystem as local if the
12104 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12105 does not support vFile:open. */
12106 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12107 {
12108 enum packet_support ps = packet_support (PACKET_vFile_open);
12109
12110 if (ps == PACKET_SUPPORT_UNKNOWN)
12111 {
12112 int fd, remote_errno;
12113
12114 /* Try opening a file to probe support. The supplied
12115 filename is irrelevant, we only care about whether
12116 the stub recognizes the packet or not. */
12117 fd = remote_hostio_open (this, NULL, "just probing",
12118 FILEIO_O_RDONLY, 0700, 0,
12119 &remote_errno);
12120
12121 if (fd >= 0)
12122 remote_hostio_close (this, fd, &remote_errno);
12123
12124 ps = packet_support (PACKET_vFile_open);
12125 }
12126
12127 if (ps == PACKET_DISABLE)
12128 {
12129 static int warning_issued = 0;
12130
12131 if (!warning_issued)
12132 {
12133 warning (_("remote target does not support file"
12134 " transfer, attempting to access files"
12135 " from local filesystem."));
12136 warning_issued = 1;
12137 }
12138
12139 return true;
12140 }
12141 }
12142
12143 return false;
12144 }
12145
12146 static int
12147 remote_fileio_errno_to_host (int errnum)
12148 {
12149 switch (errnum)
12150 {
12151 case FILEIO_EPERM:
12152 return EPERM;
12153 case FILEIO_ENOENT:
12154 return ENOENT;
12155 case FILEIO_EINTR:
12156 return EINTR;
12157 case FILEIO_EIO:
12158 return EIO;
12159 case FILEIO_EBADF:
12160 return EBADF;
12161 case FILEIO_EACCES:
12162 return EACCES;
12163 case FILEIO_EFAULT:
12164 return EFAULT;
12165 case FILEIO_EBUSY:
12166 return EBUSY;
12167 case FILEIO_EEXIST:
12168 return EEXIST;
12169 case FILEIO_ENODEV:
12170 return ENODEV;
12171 case FILEIO_ENOTDIR:
12172 return ENOTDIR;
12173 case FILEIO_EISDIR:
12174 return EISDIR;
12175 case FILEIO_EINVAL:
12176 return EINVAL;
12177 case FILEIO_ENFILE:
12178 return ENFILE;
12179 case FILEIO_EMFILE:
12180 return EMFILE;
12181 case FILEIO_EFBIG:
12182 return EFBIG;
12183 case FILEIO_ENOSPC:
12184 return ENOSPC;
12185 case FILEIO_ESPIPE:
12186 return ESPIPE;
12187 case FILEIO_EROFS:
12188 return EROFS;
12189 case FILEIO_ENOSYS:
12190 return ENOSYS;
12191 case FILEIO_ENAMETOOLONG:
12192 return ENAMETOOLONG;
12193 }
12194 return -1;
12195 }
12196
12197 static char *
12198 remote_hostio_error (int errnum)
12199 {
12200 int host_error = remote_fileio_errno_to_host (errnum);
12201
12202 if (host_error == -1)
12203 error (_("Unknown remote I/O error %d"), errnum);
12204 else
12205 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12206 }
12207
12208 static void
12209 remote_hostio_close_cleanup (void *opaque)
12210 {
12211 int fd = *(int *) opaque;
12212 int remote_errno;
12213
12214 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
12215 }
12216
12217 void
12218 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12219 {
12220 struct cleanup *back_to, *close_cleanup;
12221 int retcode, fd, remote_errno, bytes, io_size;
12222 gdb_byte *buffer;
12223 int bytes_in_buffer;
12224 int saw_eof;
12225 ULONGEST offset;
12226 struct remote_state *rs = get_remote_state ();
12227
12228 if (!rs->remote_desc)
12229 error (_("command can only be used with remote target"));
12230
12231 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12232 if (file == NULL)
12233 perror_with_name (local_file);
12234
12235 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12236 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12237 | FILEIO_O_TRUNC),
12238 0700, 0, &remote_errno);
12239 if (fd == -1)
12240 remote_hostio_error (remote_errno);
12241
12242 /* Send up to this many bytes at once. They won't all fit in the
12243 remote packet limit, so we'll transfer slightly fewer. */
12244 io_size = get_remote_packet_size ();
12245 buffer = (gdb_byte *) xmalloc (io_size);
12246 back_to = make_cleanup (xfree, buffer);
12247
12248 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12249
12250 bytes_in_buffer = 0;
12251 saw_eof = 0;
12252 offset = 0;
12253 while (bytes_in_buffer || !saw_eof)
12254 {
12255 if (!saw_eof)
12256 {
12257 bytes = fread (buffer + bytes_in_buffer, 1,
12258 io_size - bytes_in_buffer,
12259 file.get ());
12260 if (bytes == 0)
12261 {
12262 if (ferror (file.get ()))
12263 error (_("Error reading %s."), local_file);
12264 else
12265 {
12266 /* EOF. Unless there is something still in the
12267 buffer from the last iteration, we are done. */
12268 saw_eof = 1;
12269 if (bytes_in_buffer == 0)
12270 break;
12271 }
12272 }
12273 }
12274 else
12275 bytes = 0;
12276
12277 bytes += bytes_in_buffer;
12278 bytes_in_buffer = 0;
12279
12280 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12281 fd, buffer, bytes,
12282 offset, &remote_errno);
12283
12284 if (retcode < 0)
12285 remote_hostio_error (remote_errno);
12286 else if (retcode == 0)
12287 error (_("Remote write of %d bytes returned 0!"), bytes);
12288 else if (retcode < bytes)
12289 {
12290 /* Short write. Save the rest of the read data for the next
12291 write. */
12292 bytes_in_buffer = bytes - retcode;
12293 memmove (buffer, buffer + retcode, bytes_in_buffer);
12294 }
12295
12296 offset += retcode;
12297 }
12298
12299 discard_cleanups (close_cleanup);
12300 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12301 remote_hostio_error (remote_errno);
12302
12303 if (from_tty)
12304 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12305 do_cleanups (back_to);
12306 }
12307
12308 void
12309 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12310 {
12311 struct cleanup *back_to, *close_cleanup;
12312 int fd, remote_errno, bytes, io_size;
12313 gdb_byte *buffer;
12314 ULONGEST offset;
12315 struct remote_state *rs = get_remote_state ();
12316
12317 if (!rs->remote_desc)
12318 error (_("command can only be used with remote target"));
12319
12320 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12321 remote_file, FILEIO_O_RDONLY, 0, 0,
12322 &remote_errno);
12323 if (fd == -1)
12324 remote_hostio_error (remote_errno);
12325
12326 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12327 if (file == NULL)
12328 perror_with_name (local_file);
12329
12330 /* Send up to this many bytes at once. They won't all fit in the
12331 remote packet limit, so we'll transfer slightly fewer. */
12332 io_size = get_remote_packet_size ();
12333 buffer = (gdb_byte *) xmalloc (io_size);
12334 back_to = make_cleanup (xfree, buffer);
12335
12336 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12337
12338 offset = 0;
12339 while (1)
12340 {
12341 bytes = remote_hostio_pread (find_target_at (process_stratum),
12342 fd, buffer, io_size, offset, &remote_errno);
12343 if (bytes == 0)
12344 /* Success, but no bytes, means end-of-file. */
12345 break;
12346 if (bytes == -1)
12347 remote_hostio_error (remote_errno);
12348
12349 offset += bytes;
12350
12351 bytes = fwrite (buffer, 1, bytes, file.get ());
12352 if (bytes == 0)
12353 perror_with_name (local_file);
12354 }
12355
12356 discard_cleanups (close_cleanup);
12357 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12358 remote_hostio_error (remote_errno);
12359
12360 if (from_tty)
12361 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12362 do_cleanups (back_to);
12363 }
12364
12365 void
12366 remote_file_delete (const char *remote_file, int from_tty)
12367 {
12368 int retcode, remote_errno;
12369 struct remote_state *rs = get_remote_state ();
12370
12371 if (!rs->remote_desc)
12372 error (_("command can only be used with remote target"));
12373
12374 retcode = remote_hostio_unlink (find_target_at (process_stratum),
12375 NULL, remote_file, &remote_errno);
12376 if (retcode == -1)
12377 remote_hostio_error (remote_errno);
12378
12379 if (from_tty)
12380 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12381 }
12382
12383 static void
12384 remote_put_command (const char *args, int from_tty)
12385 {
12386 if (args == NULL)
12387 error_no_arg (_("file to put"));
12388
12389 gdb_argv argv (args);
12390 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12391 error (_("Invalid parameters to remote put"));
12392
12393 remote_file_put (argv[0], argv[1], from_tty);
12394 }
12395
12396 static void
12397 remote_get_command (const char *args, int from_tty)
12398 {
12399 if (args == NULL)
12400 error_no_arg (_("file to get"));
12401
12402 gdb_argv argv (args);
12403 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12404 error (_("Invalid parameters to remote get"));
12405
12406 remote_file_get (argv[0], argv[1], from_tty);
12407 }
12408
12409 static void
12410 remote_delete_command (const char *args, int from_tty)
12411 {
12412 if (args == NULL)
12413 error_no_arg (_("file to delete"));
12414
12415 gdb_argv argv (args);
12416 if (argv[0] == NULL || argv[1] != NULL)
12417 error (_("Invalid parameters to remote delete"));
12418
12419 remote_file_delete (argv[0], from_tty);
12420 }
12421
12422 static void
12423 remote_command (const char *args, int from_tty)
12424 {
12425 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12426 }
12427
12428 bool
12429 remote_target::can_execute_reverse ()
12430 {
12431 if (packet_support (PACKET_bs) == PACKET_ENABLE
12432 || packet_support (PACKET_bc) == PACKET_ENABLE)
12433 return true;
12434 else
12435 return false;
12436 }
12437
12438 bool
12439 remote_target::supports_non_stop ()
12440 {
12441 return true;
12442 }
12443
12444 bool
12445 remote_target::supports_disable_randomization ()
12446 {
12447 /* Only supported in extended mode. */
12448 return false;
12449 }
12450
12451 bool
12452 remote_target::supports_multi_process ()
12453 {
12454 struct remote_state *rs = get_remote_state ();
12455
12456 return remote_multi_process_p (rs);
12457 }
12458
12459 static int
12460 remote_supports_cond_tracepoints ()
12461 {
12462 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12463 }
12464
12465 bool
12466 remote_target::supports_evaluation_of_breakpoint_conditions ()
12467 {
12468 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12469 }
12470
12471 static int
12472 remote_supports_fast_tracepoints ()
12473 {
12474 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12475 }
12476
12477 static int
12478 remote_supports_static_tracepoints ()
12479 {
12480 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12481 }
12482
12483 static int
12484 remote_supports_install_in_trace ()
12485 {
12486 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12487 }
12488
12489 bool
12490 remote_target::supports_enable_disable_tracepoint ()
12491 {
12492 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12493 == PACKET_ENABLE);
12494 }
12495
12496 bool
12497 remote_target::supports_string_tracing ()
12498 {
12499 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12500 }
12501
12502 bool
12503 remote_target::can_run_breakpoint_commands ()
12504 {
12505 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12506 }
12507
12508 void
12509 remote_target::trace_init ()
12510 {
12511 struct remote_state *rs = get_remote_state ();
12512
12513 putpkt ("QTinit");
12514 remote_get_noisy_reply ();
12515 if (strcmp (rs->buf, "OK") != 0)
12516 error (_("Target does not support this command."));
12517 }
12518
12519 /* Recursive routine to walk through command list including loops, and
12520 download packets for each command. */
12521
12522 static void
12523 remote_download_command_source (int num, ULONGEST addr,
12524 struct command_line *cmds)
12525 {
12526 struct remote_state *rs = get_remote_state ();
12527 struct command_line *cmd;
12528
12529 for (cmd = cmds; cmd; cmd = cmd->next)
12530 {
12531 QUIT; /* Allow user to bail out with ^C. */
12532 strcpy (rs->buf, "QTDPsrc:");
12533 encode_source_string (num, addr, "cmd", cmd->line,
12534 rs->buf + strlen (rs->buf),
12535 rs->buf_size - strlen (rs->buf));
12536 putpkt (rs->buf);
12537 remote_get_noisy_reply ();
12538 if (strcmp (rs->buf, "OK"))
12539 warning (_("Target does not support source download."));
12540
12541 if (cmd->control_type == while_control
12542 || cmd->control_type == while_stepping_control)
12543 {
12544 remote_download_command_source (num, addr, *cmd->body_list);
12545
12546 QUIT; /* Allow user to bail out with ^C. */
12547 strcpy (rs->buf, "QTDPsrc:");
12548 encode_source_string (num, addr, "cmd", "end",
12549 rs->buf + strlen (rs->buf),
12550 rs->buf_size - strlen (rs->buf));
12551 putpkt (rs->buf);
12552 remote_get_noisy_reply ();
12553 if (strcmp (rs->buf, "OK"))
12554 warning (_("Target does not support source download."));
12555 }
12556 }
12557 }
12558
12559 void
12560 remote_target::download_tracepoint (struct bp_location *loc)
12561 {
12562 #define BUF_SIZE 2048
12563
12564 CORE_ADDR tpaddr;
12565 char addrbuf[40];
12566 char buf[BUF_SIZE];
12567 std::vector<std::string> tdp_actions;
12568 std::vector<std::string> stepping_actions;
12569 char *pkt;
12570 struct breakpoint *b = loc->owner;
12571 struct tracepoint *t = (struct tracepoint *) b;
12572 struct remote_state *rs = get_remote_state ();
12573
12574 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12575
12576 tpaddr = loc->address;
12577 sprintf_vma (addrbuf, tpaddr);
12578 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12579 addrbuf, /* address */
12580 (b->enable_state == bp_enabled ? 'E' : 'D'),
12581 t->step_count, t->pass_count);
12582 /* Fast tracepoints are mostly handled by the target, but we can
12583 tell the target how big of an instruction block should be moved
12584 around. */
12585 if (b->type == bp_fast_tracepoint)
12586 {
12587 /* Only test for support at download time; we may not know
12588 target capabilities at definition time. */
12589 if (remote_supports_fast_tracepoints ())
12590 {
12591 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12592 NULL))
12593 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12594 gdb_insn_length (loc->gdbarch, tpaddr));
12595 else
12596 /* If it passed validation at definition but fails now,
12597 something is very wrong. */
12598 internal_error (__FILE__, __LINE__,
12599 _("Fast tracepoint not "
12600 "valid during download"));
12601 }
12602 else
12603 /* Fast tracepoints are functionally identical to regular
12604 tracepoints, so don't take lack of support as a reason to
12605 give up on the trace run. */
12606 warning (_("Target does not support fast tracepoints, "
12607 "downloading %d as regular tracepoint"), b->number);
12608 }
12609 else if (b->type == bp_static_tracepoint)
12610 {
12611 /* Only test for support at download time; we may not know
12612 target capabilities at definition time. */
12613 if (remote_supports_static_tracepoints ())
12614 {
12615 struct static_tracepoint_marker marker;
12616
12617 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12618 strcat (buf, ":S");
12619 else
12620 error (_("Static tracepoint not valid during download"));
12621 }
12622 else
12623 /* Fast tracepoints are functionally identical to regular
12624 tracepoints, so don't take lack of support as a reason
12625 to give up on the trace run. */
12626 error (_("Target does not support static tracepoints"));
12627 }
12628 /* If the tracepoint has a conditional, make it into an agent
12629 expression and append to the definition. */
12630 if (loc->cond)
12631 {
12632 /* Only test support at download time, we may not know target
12633 capabilities at definition time. */
12634 if (remote_supports_cond_tracepoints ())
12635 {
12636 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12637 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12638 aexpr->len);
12639 pkt = buf + strlen (buf);
12640 for (int ndx = 0; ndx < aexpr->len; ++ndx)
12641 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12642 *pkt = '\0';
12643 }
12644 else
12645 warning (_("Target does not support conditional tracepoints, "
12646 "ignoring tp %d cond"), b->number);
12647 }
12648
12649 if (b->commands || *default_collect)
12650 strcat (buf, "-");
12651 putpkt (buf);
12652 remote_get_noisy_reply ();
12653 if (strcmp (rs->buf, "OK"))
12654 error (_("Target does not support tracepoints."));
12655
12656 /* do_single_steps (t); */
12657 for (auto action_it = tdp_actions.begin ();
12658 action_it != tdp_actions.end (); action_it++)
12659 {
12660 QUIT; /* Allow user to bail out with ^C. */
12661
12662 bool has_more = (action_it != tdp_actions.end ()
12663 || !stepping_actions.empty ());
12664
12665 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12666 b->number, addrbuf, /* address */
12667 action_it->c_str (),
12668 has_more ? '-' : 0);
12669 putpkt (buf);
12670 remote_get_noisy_reply ();
12671 if (strcmp (rs->buf, "OK"))
12672 error (_("Error on target while setting tracepoints."));
12673 }
12674
12675 for (auto action_it = stepping_actions.begin ();
12676 action_it != stepping_actions.end (); action_it++)
12677 {
12678 QUIT; /* Allow user to bail out with ^C. */
12679
12680 bool is_first = action_it == stepping_actions.begin ();
12681 bool has_more = action_it != stepping_actions.end ();
12682
12683 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12684 b->number, addrbuf, /* address */
12685 is_first ? "S" : "",
12686 action_it->c_str (),
12687 has_more ? "-" : "");
12688 putpkt (buf);
12689 remote_get_noisy_reply ();
12690 if (strcmp (rs->buf, "OK"))
12691 error (_("Error on target while setting tracepoints."));
12692 }
12693
12694 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12695 {
12696 if (b->location != NULL)
12697 {
12698 strcpy (buf, "QTDPsrc:");
12699 encode_source_string (b->number, loc->address, "at",
12700 event_location_to_string (b->location.get ()),
12701 buf + strlen (buf), 2048 - strlen (buf));
12702 putpkt (buf);
12703 remote_get_noisy_reply ();
12704 if (strcmp (rs->buf, "OK"))
12705 warning (_("Target does not support source download."));
12706 }
12707 if (b->cond_string)
12708 {
12709 strcpy (buf, "QTDPsrc:");
12710 encode_source_string (b->number, loc->address,
12711 "cond", b->cond_string, buf + strlen (buf),
12712 2048 - strlen (buf));
12713 putpkt (buf);
12714 remote_get_noisy_reply ();
12715 if (strcmp (rs->buf, "OK"))
12716 warning (_("Target does not support source download."));
12717 }
12718 remote_download_command_source (b->number, loc->address,
12719 breakpoint_commands (b));
12720 }
12721 }
12722
12723 bool
12724 remote_target::can_download_tracepoint ()
12725 {
12726 struct remote_state *rs = get_remote_state ();
12727 struct trace_status *ts;
12728 int status;
12729
12730 /* Don't try to install tracepoints until we've relocated our
12731 symbols, and fetched and merged the target's tracepoint list with
12732 ours. */
12733 if (rs->starting_up)
12734 return false;
12735
12736 ts = current_trace_status ();
12737 status = get_trace_status (ts);
12738
12739 if (status == -1 || !ts->running_known || !ts->running)
12740 return false;
12741
12742 /* If we are in a tracing experiment, but remote stub doesn't support
12743 installing tracepoint in trace, we have to return. */
12744 if (!remote_supports_install_in_trace ())
12745 return false;
12746
12747 return true;
12748 }
12749
12750
12751 void
12752 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12753 {
12754 struct remote_state *rs = get_remote_state ();
12755 char *p;
12756
12757 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12758 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12759 tsv.builtin);
12760 p = rs->buf + strlen (rs->buf);
12761 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12762 error (_("Trace state variable name too long for tsv definition packet"));
12763 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12764 *p++ = '\0';
12765 putpkt (rs->buf);
12766 remote_get_noisy_reply ();
12767 if (*rs->buf == '\0')
12768 error (_("Target does not support this command."));
12769 if (strcmp (rs->buf, "OK") != 0)
12770 error (_("Error on target while downloading trace state variable."));
12771 }
12772
12773 void
12774 remote_target::enable_tracepoint (struct bp_location *location)
12775 {
12776 struct remote_state *rs = get_remote_state ();
12777 char addr_buf[40];
12778
12779 sprintf_vma (addr_buf, location->address);
12780 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12781 location->owner->number, addr_buf);
12782 putpkt (rs->buf);
12783 remote_get_noisy_reply ();
12784 if (*rs->buf == '\0')
12785 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12786 if (strcmp (rs->buf, "OK") != 0)
12787 error (_("Error on target while enabling tracepoint."));
12788 }
12789
12790 void
12791 remote_target::disable_tracepoint (struct bp_location *location)
12792 {
12793 struct remote_state *rs = get_remote_state ();
12794 char addr_buf[40];
12795
12796 sprintf_vma (addr_buf, location->address);
12797 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12798 location->owner->number, addr_buf);
12799 putpkt (rs->buf);
12800 remote_get_noisy_reply ();
12801 if (*rs->buf == '\0')
12802 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12803 if (strcmp (rs->buf, "OK") != 0)
12804 error (_("Error on target while disabling tracepoint."));
12805 }
12806
12807 void
12808 remote_target::trace_set_readonly_regions ()
12809 {
12810 asection *s;
12811 bfd *abfd = NULL;
12812 bfd_size_type size;
12813 bfd_vma vma;
12814 int anysecs = 0;
12815 int offset = 0;
12816
12817 if (!exec_bfd)
12818 return; /* No information to give. */
12819
12820 struct remote_state *rs = get_remote_state ();
12821
12822 strcpy (rs->buf, "QTro");
12823 offset = strlen (rs->buf);
12824 for (s = exec_bfd->sections; s; s = s->next)
12825 {
12826 char tmp1[40], tmp2[40];
12827 int sec_length;
12828
12829 if ((s->flags & SEC_LOAD) == 0 ||
12830 /* (s->flags & SEC_CODE) == 0 || */
12831 (s->flags & SEC_READONLY) == 0)
12832 continue;
12833
12834 anysecs = 1;
12835 vma = bfd_get_section_vma (abfd, s);
12836 size = bfd_get_section_size (s);
12837 sprintf_vma (tmp1, vma);
12838 sprintf_vma (tmp2, vma + size);
12839 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12840 if (offset + sec_length + 1 > rs->buf_size)
12841 {
12842 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12843 warning (_("\
12844 Too many sections for read-only sections definition packet."));
12845 break;
12846 }
12847 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
12848 tmp1, tmp2);
12849 offset += sec_length;
12850 }
12851 if (anysecs)
12852 {
12853 putpkt (rs->buf);
12854 getpkt (&rs->buf, &rs->buf_size, 0);
12855 }
12856 }
12857
12858 void
12859 remote_target::trace_start ()
12860 {
12861 struct remote_state *rs = get_remote_state ();
12862
12863 putpkt ("QTStart");
12864 remote_get_noisy_reply ();
12865 if (*rs->buf == '\0')
12866 error (_("Target does not support this command."));
12867 if (strcmp (rs->buf, "OK") != 0)
12868 error (_("Bogus reply from target: %s"), rs->buf);
12869 }
12870
12871 int
12872 remote_target::get_trace_status (struct trace_status *ts)
12873 {
12874 /* Initialize it just to avoid a GCC false warning. */
12875 char *p = NULL;
12876 /* FIXME we need to get register block size some other way. */
12877 extern int trace_regblock_size;
12878 enum packet_result result;
12879 struct remote_state *rs = get_remote_state ();
12880
12881 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12882 return -1;
12883
12884 trace_regblock_size
12885 = get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
12886
12887 putpkt ("qTStatus");
12888
12889 TRY
12890 {
12891 p = remote_get_noisy_reply ();
12892 }
12893 CATCH (ex, RETURN_MASK_ERROR)
12894 {
12895 if (ex.error != TARGET_CLOSE_ERROR)
12896 {
12897 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12898 return -1;
12899 }
12900 throw_exception (ex);
12901 }
12902 END_CATCH
12903
12904 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12905
12906 /* If the remote target doesn't do tracing, flag it. */
12907 if (result == PACKET_UNKNOWN)
12908 return -1;
12909
12910 /* We're working with a live target. */
12911 ts->filename = NULL;
12912
12913 if (*p++ != 'T')
12914 error (_("Bogus trace status reply from target: %s"), rs->buf);
12915
12916 /* Function 'parse_trace_status' sets default value of each field of
12917 'ts' at first, so we don't have to do it here. */
12918 parse_trace_status (p, ts);
12919
12920 return ts->running;
12921 }
12922
12923 void
12924 remote_target::get_tracepoint_status (struct breakpoint *bp,
12925 struct uploaded_tp *utp)
12926 {
12927 struct remote_state *rs = get_remote_state ();
12928 char *reply;
12929 struct bp_location *loc;
12930 struct tracepoint *tp = (struct tracepoint *) bp;
12931 size_t size = get_remote_packet_size ();
12932
12933 if (tp)
12934 {
12935 tp->hit_count = 0;
12936 tp->traceframe_usage = 0;
12937 for (loc = tp->loc; loc; loc = loc->next)
12938 {
12939 /* If the tracepoint was never downloaded, don't go asking for
12940 any status. */
12941 if (tp->number_on_target == 0)
12942 continue;
12943 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12944 phex_nz (loc->address, 0));
12945 putpkt (rs->buf);
12946 reply = remote_get_noisy_reply ();
12947 if (reply && *reply)
12948 {
12949 if (*reply == 'V')
12950 parse_tracepoint_status (reply + 1, bp, utp);
12951 }
12952 }
12953 }
12954 else if (utp)
12955 {
12956 utp->hit_count = 0;
12957 utp->traceframe_usage = 0;
12958 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12959 phex_nz (utp->addr, 0));
12960 putpkt (rs->buf);
12961 reply = remote_get_noisy_reply ();
12962 if (reply && *reply)
12963 {
12964 if (*reply == 'V')
12965 parse_tracepoint_status (reply + 1, bp, utp);
12966 }
12967 }
12968 }
12969
12970 void
12971 remote_target::trace_stop ()
12972 {
12973 struct remote_state *rs = get_remote_state ();
12974
12975 putpkt ("QTStop");
12976 remote_get_noisy_reply ();
12977 if (*rs->buf == '\0')
12978 error (_("Target does not support this command."));
12979 if (strcmp (rs->buf, "OK") != 0)
12980 error (_("Bogus reply from target: %s"), rs->buf);
12981 }
12982
12983 int
12984 remote_target::trace_find (enum trace_find_type type, int num,
12985 CORE_ADDR addr1, CORE_ADDR addr2,
12986 int *tpp)
12987 {
12988 struct remote_state *rs = get_remote_state ();
12989 char *endbuf = rs->buf + get_remote_packet_size ();
12990 char *p, *reply;
12991 int target_frameno = -1, target_tracept = -1;
12992
12993 /* Lookups other than by absolute frame number depend on the current
12994 trace selected, so make sure it is correct on the remote end
12995 first. */
12996 if (type != tfind_number)
12997 set_remote_traceframe ();
12998
12999 p = rs->buf;
13000 strcpy (p, "QTFrame:");
13001 p = strchr (p, '\0');
13002 switch (type)
13003 {
13004 case tfind_number:
13005 xsnprintf (p, endbuf - p, "%x", num);
13006 break;
13007 case tfind_pc:
13008 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13009 break;
13010 case tfind_tp:
13011 xsnprintf (p, endbuf - p, "tdp:%x", num);
13012 break;
13013 case tfind_range:
13014 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13015 phex_nz (addr2, 0));
13016 break;
13017 case tfind_outside:
13018 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13019 phex_nz (addr2, 0));
13020 break;
13021 default:
13022 error (_("Unknown trace find type %d"), type);
13023 }
13024
13025 putpkt (rs->buf);
13026 reply = remote_get_noisy_reply ();
13027 if (*reply == '\0')
13028 error (_("Target does not support this command."));
13029
13030 while (reply && *reply)
13031 switch (*reply)
13032 {
13033 case 'F':
13034 p = ++reply;
13035 target_frameno = (int) strtol (p, &reply, 16);
13036 if (reply == p)
13037 error (_("Unable to parse trace frame number"));
13038 /* Don't update our remote traceframe number cache on failure
13039 to select a remote traceframe. */
13040 if (target_frameno == -1)
13041 return -1;
13042 break;
13043 case 'T':
13044 p = ++reply;
13045 target_tracept = (int) strtol (p, &reply, 16);
13046 if (reply == p)
13047 error (_("Unable to parse tracepoint number"));
13048 break;
13049 case 'O': /* "OK"? */
13050 if (reply[1] == 'K' && reply[2] == '\0')
13051 reply += 2;
13052 else
13053 error (_("Bogus reply from target: %s"), reply);
13054 break;
13055 default:
13056 error (_("Bogus reply from target: %s"), reply);
13057 }
13058 if (tpp)
13059 *tpp = target_tracept;
13060
13061 rs->remote_traceframe_number = target_frameno;
13062 return target_frameno;
13063 }
13064
13065 bool
13066 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13067 {
13068 struct remote_state *rs = get_remote_state ();
13069 char *reply;
13070 ULONGEST uval;
13071
13072 set_remote_traceframe ();
13073
13074 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13075 putpkt (rs->buf);
13076 reply = remote_get_noisy_reply ();
13077 if (reply && *reply)
13078 {
13079 if (*reply == 'V')
13080 {
13081 unpack_varlen_hex (reply + 1, &uval);
13082 *val = (LONGEST) uval;
13083 return true;
13084 }
13085 }
13086 return false;
13087 }
13088
13089 int
13090 remote_target::save_trace_data (const char *filename)
13091 {
13092 struct remote_state *rs = get_remote_state ();
13093 char *p, *reply;
13094
13095 p = rs->buf;
13096 strcpy (p, "QTSave:");
13097 p += strlen (p);
13098 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13099 error (_("Remote file name too long for trace save packet"));
13100 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13101 *p++ = '\0';
13102 putpkt (rs->buf);
13103 reply = remote_get_noisy_reply ();
13104 if (*reply == '\0')
13105 error (_("Target does not support this command."));
13106 if (strcmp (reply, "OK") != 0)
13107 error (_("Bogus reply from target: %s"), reply);
13108 return 0;
13109 }
13110
13111 /* This is basically a memory transfer, but needs to be its own packet
13112 because we don't know how the target actually organizes its trace
13113 memory, plus we want to be able to ask for as much as possible, but
13114 not be unhappy if we don't get as much as we ask for. */
13115
13116 LONGEST
13117 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13118 {
13119 struct remote_state *rs = get_remote_state ();
13120 char *reply;
13121 char *p;
13122 int rslt;
13123
13124 p = rs->buf;
13125 strcpy (p, "qTBuffer:");
13126 p += strlen (p);
13127 p += hexnumstr (p, offset);
13128 *p++ = ',';
13129 p += hexnumstr (p, len);
13130 *p++ = '\0';
13131
13132 putpkt (rs->buf);
13133 reply = remote_get_noisy_reply ();
13134 if (reply && *reply)
13135 {
13136 /* 'l' by itself means we're at the end of the buffer and
13137 there is nothing more to get. */
13138 if (*reply == 'l')
13139 return 0;
13140
13141 /* Convert the reply into binary. Limit the number of bytes to
13142 convert according to our passed-in buffer size, rather than
13143 what was returned in the packet; if the target is
13144 unexpectedly generous and gives us a bigger reply than we
13145 asked for, we don't want to crash. */
13146 rslt = hex2bin (reply, buf, len);
13147 return rslt;
13148 }
13149
13150 /* Something went wrong, flag as an error. */
13151 return -1;
13152 }
13153
13154 void
13155 remote_target::set_disconnected_tracing (int val)
13156 {
13157 struct remote_state *rs = get_remote_state ();
13158
13159 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13160 {
13161 char *reply;
13162
13163 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13164 putpkt (rs->buf);
13165 reply = remote_get_noisy_reply ();
13166 if (*reply == '\0')
13167 error (_("Target does not support this command."));
13168 if (strcmp (reply, "OK") != 0)
13169 error (_("Bogus reply from target: %s"), reply);
13170 }
13171 else if (val)
13172 warning (_("Target does not support disconnected tracing."));
13173 }
13174
13175 int
13176 remote_target::core_of_thread (ptid_t ptid)
13177 {
13178 struct thread_info *info = find_thread_ptid (ptid);
13179
13180 if (info != NULL && info->priv != NULL)
13181 return get_remote_thread_info (info)->core;
13182
13183 return -1;
13184 }
13185
13186 void
13187 remote_target::set_circular_trace_buffer (int val)
13188 {
13189 struct remote_state *rs = get_remote_state ();
13190 char *reply;
13191
13192 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13193 putpkt (rs->buf);
13194 reply = remote_get_noisy_reply ();
13195 if (*reply == '\0')
13196 error (_("Target does not support this command."));
13197 if (strcmp (reply, "OK") != 0)
13198 error (_("Bogus reply from target: %s"), reply);
13199 }
13200
13201 traceframe_info_up
13202 remote_target::traceframe_info ()
13203 {
13204 gdb::optional<gdb::char_vector> text
13205 = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
13206 NULL);
13207 if (text)
13208 return parse_traceframe_info (text->data ());
13209
13210 return NULL;
13211 }
13212
13213 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13214 instruction on which a fast tracepoint may be placed. Returns -1
13215 if the packet is not supported, and 0 if the minimum instruction
13216 length is unknown. */
13217
13218 int
13219 remote_target::get_min_fast_tracepoint_insn_len ()
13220 {
13221 struct remote_state *rs = get_remote_state ();
13222 char *reply;
13223
13224 /* If we're not debugging a process yet, the IPA can't be
13225 loaded. */
13226 if (!target_has_execution)
13227 return 0;
13228
13229 /* Make sure the remote is pointing at the right process. */
13230 set_general_process ();
13231
13232 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13233 putpkt (rs->buf);
13234 reply = remote_get_noisy_reply ();
13235 if (*reply == '\0')
13236 return -1;
13237 else
13238 {
13239 ULONGEST min_insn_len;
13240
13241 unpack_varlen_hex (reply, &min_insn_len);
13242
13243 return (int) min_insn_len;
13244 }
13245 }
13246
13247 void
13248 remote_target::set_trace_buffer_size (LONGEST val)
13249 {
13250 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13251 {
13252 struct remote_state *rs = get_remote_state ();
13253 char *buf = rs->buf;
13254 char *endbuf = rs->buf + get_remote_packet_size ();
13255 enum packet_result result;
13256
13257 gdb_assert (val >= 0 || val == -1);
13258 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13259 /* Send -1 as literal "-1" to avoid host size dependency. */
13260 if (val < 0)
13261 {
13262 *buf++ = '-';
13263 buf += hexnumstr (buf, (ULONGEST) -val);
13264 }
13265 else
13266 buf += hexnumstr (buf, (ULONGEST) val);
13267
13268 putpkt (rs->buf);
13269 remote_get_noisy_reply ();
13270 result = packet_ok (rs->buf,
13271 &remote_protocol_packets[PACKET_QTBuffer_size]);
13272
13273 if (result != PACKET_OK)
13274 warning (_("Bogus reply from target: %s"), rs->buf);
13275 }
13276 }
13277
13278 bool
13279 remote_target::set_trace_notes (const char *user, const char *notes,
13280 const char *stop_notes)
13281 {
13282 struct remote_state *rs = get_remote_state ();
13283 char *reply;
13284 char *buf = rs->buf;
13285 char *endbuf = rs->buf + get_remote_packet_size ();
13286 int nbytes;
13287
13288 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13289 if (user)
13290 {
13291 buf += xsnprintf (buf, endbuf - buf, "user:");
13292 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13293 buf += 2 * nbytes;
13294 *buf++ = ';';
13295 }
13296 if (notes)
13297 {
13298 buf += xsnprintf (buf, endbuf - buf, "notes:");
13299 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13300 buf += 2 * nbytes;
13301 *buf++ = ';';
13302 }
13303 if (stop_notes)
13304 {
13305 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13306 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13307 buf += 2 * nbytes;
13308 *buf++ = ';';
13309 }
13310 /* Ensure the buffer is terminated. */
13311 *buf = '\0';
13312
13313 putpkt (rs->buf);
13314 reply = remote_get_noisy_reply ();
13315 if (*reply == '\0')
13316 return false;
13317
13318 if (strcmp (reply, "OK") != 0)
13319 error (_("Bogus reply from target: %s"), reply);
13320
13321 return true;
13322 }
13323
13324 bool
13325 remote_target::use_agent (bool use)
13326 {
13327 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13328 {
13329 struct remote_state *rs = get_remote_state ();
13330
13331 /* If the stub supports QAgent. */
13332 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13333 putpkt (rs->buf);
13334 getpkt (&rs->buf, &rs->buf_size, 0);
13335
13336 if (strcmp (rs->buf, "OK") == 0)
13337 {
13338 ::use_agent = use;
13339 return true;
13340 }
13341 }
13342
13343 return false;
13344 }
13345
13346 bool
13347 remote_target::can_use_agent ()
13348 {
13349 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13350 }
13351
13352 struct btrace_target_info
13353 {
13354 /* The ptid of the traced thread. */
13355 ptid_t ptid;
13356
13357 /* The obtained branch trace configuration. */
13358 struct btrace_config conf;
13359 };
13360
13361 /* Reset our idea of our target's btrace configuration. */
13362
13363 static void
13364 remote_btrace_reset (void)
13365 {
13366 struct remote_state *rs = get_remote_state ();
13367
13368 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13369 }
13370
13371 /* Synchronize the configuration with the target. */
13372
13373 static void
13374 btrace_sync_conf (const struct btrace_config *conf)
13375 {
13376 struct packet_config *packet;
13377 struct remote_state *rs;
13378 char *buf, *pos, *endbuf;
13379
13380 rs = get_remote_state ();
13381 buf = rs->buf;
13382 endbuf = buf + get_remote_packet_size ();
13383
13384 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13385 if (packet_config_support (packet) == PACKET_ENABLE
13386 && conf->bts.size != rs->btrace_config.bts.size)
13387 {
13388 pos = buf;
13389 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13390 conf->bts.size);
13391
13392 putpkt (buf);
13393 getpkt (&buf, &rs->buf_size, 0);
13394
13395 if (packet_ok (buf, packet) == PACKET_ERROR)
13396 {
13397 if (buf[0] == 'E' && buf[1] == '.')
13398 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13399 else
13400 error (_("Failed to configure the BTS buffer size."));
13401 }
13402
13403 rs->btrace_config.bts.size = conf->bts.size;
13404 }
13405
13406 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13407 if (packet_config_support (packet) == PACKET_ENABLE
13408 && conf->pt.size != rs->btrace_config.pt.size)
13409 {
13410 pos = buf;
13411 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13412 conf->pt.size);
13413
13414 putpkt (buf);
13415 getpkt (&buf, &rs->buf_size, 0);
13416
13417 if (packet_ok (buf, packet) == PACKET_ERROR)
13418 {
13419 if (buf[0] == 'E' && buf[1] == '.')
13420 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13421 else
13422 error (_("Failed to configure the trace buffer size."));
13423 }
13424
13425 rs->btrace_config.pt.size = conf->pt.size;
13426 }
13427 }
13428
13429 /* Read the current thread's btrace configuration from the target and
13430 store it into CONF. */
13431
13432 static void
13433 btrace_read_config (struct btrace_config *conf)
13434 {
13435 gdb::optional<gdb::char_vector> xml
13436 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
13437 if (xml)
13438 parse_xml_btrace_conf (conf, xml->data ());
13439 }
13440
13441 /* Maybe reopen target btrace. */
13442
13443 static void
13444 remote_btrace_maybe_reopen (void)
13445 {
13446 struct remote_state *rs = get_remote_state ();
13447 struct thread_info *tp;
13448 int btrace_target_pushed = 0;
13449 int warned = 0;
13450
13451 scoped_restore_current_thread restore_thread;
13452
13453 ALL_NON_EXITED_THREADS (tp)
13454 {
13455 set_general_thread (tp->ptid);
13456
13457 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13458 btrace_read_config (&rs->btrace_config);
13459
13460 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13461 continue;
13462
13463 #if !defined (HAVE_LIBIPT)
13464 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13465 {
13466 if (!warned)
13467 {
13468 warned = 1;
13469 warning (_("Target is recording using Intel Processor Trace "
13470 "but support was disabled at compile time."));
13471 }
13472
13473 continue;
13474 }
13475 #endif /* !defined (HAVE_LIBIPT) */
13476
13477 /* Push target, once, but before anything else happens. This way our
13478 changes to the threads will be cleaned up by unpushing the target
13479 in case btrace_read_config () throws. */
13480 if (!btrace_target_pushed)
13481 {
13482 btrace_target_pushed = 1;
13483 record_btrace_push_target ();
13484 printf_filtered (_("Target is recording using %s.\n"),
13485 btrace_format_string (rs->btrace_config.format));
13486 }
13487
13488 tp->btrace.target = XCNEW (struct btrace_target_info);
13489 tp->btrace.target->ptid = tp->ptid;
13490 tp->btrace.target->conf = rs->btrace_config;
13491 }
13492 }
13493
13494 /* Enable branch tracing. */
13495
13496 struct btrace_target_info *
13497 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13498 {
13499 struct btrace_target_info *tinfo = NULL;
13500 struct packet_config *packet = NULL;
13501 struct remote_state *rs = get_remote_state ();
13502 char *buf = rs->buf;
13503 char *endbuf = rs->buf + get_remote_packet_size ();
13504
13505 switch (conf->format)
13506 {
13507 case BTRACE_FORMAT_BTS:
13508 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13509 break;
13510
13511 case BTRACE_FORMAT_PT:
13512 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13513 break;
13514 }
13515
13516 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13517 error (_("Target does not support branch tracing."));
13518
13519 btrace_sync_conf (conf);
13520
13521 set_general_thread (ptid);
13522
13523 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13524 putpkt (rs->buf);
13525 getpkt (&rs->buf, &rs->buf_size, 0);
13526
13527 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13528 {
13529 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13530 error (_("Could not enable branch tracing for %s: %s"),
13531 target_pid_to_str (ptid), rs->buf + 2);
13532 else
13533 error (_("Could not enable branch tracing for %s."),
13534 target_pid_to_str (ptid));
13535 }
13536
13537 tinfo = XCNEW (struct btrace_target_info);
13538 tinfo->ptid = ptid;
13539
13540 /* If we fail to read the configuration, we lose some information, but the
13541 tracing itself is not impacted. */
13542 TRY
13543 {
13544 btrace_read_config (&tinfo->conf);
13545 }
13546 CATCH (err, RETURN_MASK_ERROR)
13547 {
13548 if (err.message != NULL)
13549 warning ("%s", err.message);
13550 }
13551 END_CATCH
13552
13553 return tinfo;
13554 }
13555
13556 /* Disable branch tracing. */
13557
13558 void
13559 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13560 {
13561 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13562 struct remote_state *rs = get_remote_state ();
13563 char *buf = rs->buf;
13564 char *endbuf = rs->buf + get_remote_packet_size ();
13565
13566 if (packet_config_support (packet) != PACKET_ENABLE)
13567 error (_("Target does not support branch tracing."));
13568
13569 set_general_thread (tinfo->ptid);
13570
13571 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13572 putpkt (rs->buf);
13573 getpkt (&rs->buf, &rs->buf_size, 0);
13574
13575 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13576 {
13577 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13578 error (_("Could not disable branch tracing for %s: %s"),
13579 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13580 else
13581 error (_("Could not disable branch tracing for %s."),
13582 target_pid_to_str (tinfo->ptid));
13583 }
13584
13585 xfree (tinfo);
13586 }
13587
13588 /* Teardown branch tracing. */
13589
13590 void
13591 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13592 {
13593 /* We must not talk to the target during teardown. */
13594 xfree (tinfo);
13595 }
13596
13597 /* Read the branch trace. */
13598
13599 enum btrace_error
13600 remote_target::read_btrace (struct btrace_data *btrace,
13601 struct btrace_target_info *tinfo,
13602 enum btrace_read_type type)
13603 {
13604 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13605 const char *annex;
13606
13607 if (packet_config_support (packet) != PACKET_ENABLE)
13608 error (_("Target does not support branch tracing."));
13609
13610 #if !defined(HAVE_LIBEXPAT)
13611 error (_("Cannot process branch tracing result. XML parsing not supported."));
13612 #endif
13613
13614 switch (type)
13615 {
13616 case BTRACE_READ_ALL:
13617 annex = "all";
13618 break;
13619 case BTRACE_READ_NEW:
13620 annex = "new";
13621 break;
13622 case BTRACE_READ_DELTA:
13623 annex = "delta";
13624 break;
13625 default:
13626 internal_error (__FILE__, __LINE__,
13627 _("Bad branch tracing read type: %u."),
13628 (unsigned int) type);
13629 }
13630
13631 gdb::optional<gdb::char_vector> xml
13632 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
13633 if (!xml)
13634 return BTRACE_ERR_UNKNOWN;
13635
13636 parse_xml_btrace (btrace, xml->data ());
13637
13638 return BTRACE_ERR_NONE;
13639 }
13640
13641 const struct btrace_config *
13642 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13643 {
13644 return &tinfo->conf;
13645 }
13646
13647 bool
13648 remote_target::augmented_libraries_svr4_read ()
13649 {
13650 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13651 == PACKET_ENABLE);
13652 }
13653
13654 /* Implementation of to_load. */
13655
13656 void
13657 remote_target::load (const char *name, int from_tty)
13658 {
13659 generic_load (name, from_tty);
13660 }
13661
13662 /* Accepts an integer PID; returns a string representing a file that
13663 can be opened on the remote side to get the symbols for the child
13664 process. Returns NULL if the operation is not supported. */
13665
13666 char *
13667 remote_target::pid_to_exec_file (int pid)
13668 {
13669 static gdb::optional<gdb::char_vector> filename;
13670 struct inferior *inf;
13671 char *annex = NULL;
13672
13673 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13674 return NULL;
13675
13676 inf = find_inferior_pid (pid);
13677 if (inf == NULL)
13678 internal_error (__FILE__, __LINE__,
13679 _("not currently attached to process %d"), pid);
13680
13681 if (!inf->fake_pid_p)
13682 {
13683 const int annex_size = 9;
13684
13685 annex = (char *) alloca (annex_size);
13686 xsnprintf (annex, annex_size, "%x", pid);
13687 }
13688
13689 filename = target_read_stralloc (target_stack,
13690 TARGET_OBJECT_EXEC_FILE, annex);
13691
13692 return filename ? filename->data () : nullptr;
13693 }
13694
13695 /* Implement the to_can_do_single_step target_ops method. */
13696
13697 int
13698 remote_target::can_do_single_step ()
13699 {
13700 /* We can only tell whether target supports single step or not by
13701 supported s and S vCont actions if the stub supports vContSupported
13702 feature. If the stub doesn't support vContSupported feature,
13703 we have conservatively to think target doesn't supports single
13704 step. */
13705 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13706 {
13707 struct remote_state *rs = get_remote_state ();
13708
13709 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13710 remote_vcont_probe (rs);
13711
13712 return rs->supports_vCont.s && rs->supports_vCont.S;
13713 }
13714 else
13715 return 0;
13716 }
13717
13718 /* Implementation of the to_execution_direction method for the remote
13719 target. */
13720
13721 enum exec_direction_kind
13722 remote_target::execution_direction ()
13723 {
13724 struct remote_state *rs = get_remote_state ();
13725
13726 return rs->last_resume_exec_dir;
13727 }
13728
13729 /* Return pointer to the thread_info struct which corresponds to
13730 THREAD_HANDLE (having length HANDLE_LEN). */
13731
13732 thread_info *
13733 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13734 int handle_len,
13735 inferior *inf)
13736 {
13737 struct thread_info *tp;
13738
13739 ALL_NON_EXITED_THREADS (tp)
13740 {
13741 remote_thread_info *priv = get_remote_thread_info (tp);
13742
13743 if (tp->inf == inf && priv != NULL)
13744 {
13745 if (handle_len != priv->thread_handle.size ())
13746 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13747 handle_len, priv->thread_handle.size ());
13748 if (memcmp (thread_handle, priv->thread_handle.data (),
13749 handle_len) == 0)
13750 return tp;
13751 }
13752 }
13753
13754 return NULL;
13755 }
13756
13757 bool
13758 remote_target::can_async_p ()
13759 {
13760 struct remote_state *rs = get_remote_state ();
13761
13762 /* We don't go async if the user has explicitly prevented it with the
13763 "maint set target-async" command. */
13764 if (!target_async_permitted)
13765 return false;
13766
13767 /* We're async whenever the serial device is. */
13768 return serial_can_async_p (rs->remote_desc);
13769 }
13770
13771 bool
13772 remote_target::is_async_p ()
13773 {
13774 struct remote_state *rs = get_remote_state ();
13775
13776 if (!target_async_permitted)
13777 /* We only enable async when the user specifically asks for it. */
13778 return false;
13779
13780 /* We're async whenever the serial device is. */
13781 return serial_is_async_p (rs->remote_desc);
13782 }
13783
13784 /* Pass the SERIAL event on and up to the client. One day this code
13785 will be able to delay notifying the client of an event until the
13786 point where an entire packet has been received. */
13787
13788 static serial_event_ftype remote_async_serial_handler;
13789
13790 static void
13791 remote_async_serial_handler (struct serial *scb, void *context)
13792 {
13793 /* Don't propogate error information up to the client. Instead let
13794 the client find out about the error by querying the target. */
13795 inferior_event_handler (INF_REG_EVENT, NULL);
13796 }
13797
13798 static void
13799 remote_async_inferior_event_handler (gdb_client_data data)
13800 {
13801 inferior_event_handler (INF_REG_EVENT, NULL);
13802 }
13803
13804 void
13805 remote_target::async (int enable)
13806 {
13807 struct remote_state *rs = get_remote_state ();
13808
13809 if (enable)
13810 {
13811 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13812
13813 /* If there are pending events in the stop reply queue tell the
13814 event loop to process them. */
13815 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13816 mark_async_event_handler (remote_async_inferior_event_token);
13817 /* For simplicity, below we clear the pending events token
13818 without remembering whether it is marked, so here we always
13819 mark it. If there's actually no pending notification to
13820 process, this ends up being a no-op (other than a spurious
13821 event-loop wakeup). */
13822 if (target_is_non_stop_p ())
13823 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13824 }
13825 else
13826 {
13827 serial_async (rs->remote_desc, NULL, NULL);
13828 /* If the core is disabling async, it doesn't want to be
13829 disturbed with target events. Clear all async event sources
13830 too. */
13831 clear_async_event_handler (remote_async_inferior_event_token);
13832 if (target_is_non_stop_p ())
13833 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13834 }
13835 }
13836
13837 /* Implementation of the to_thread_events method. */
13838
13839 void
13840 remote_target::thread_events (int enable)
13841 {
13842 struct remote_state *rs = get_remote_state ();
13843 size_t size = get_remote_packet_size ();
13844
13845 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13846 return;
13847
13848 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13849 putpkt (rs->buf);
13850 getpkt (&rs->buf, &rs->buf_size, 0);
13851
13852 switch (packet_ok (rs->buf,
13853 &remote_protocol_packets[PACKET_QThreadEvents]))
13854 {
13855 case PACKET_OK:
13856 if (strcmp (rs->buf, "OK") != 0)
13857 error (_("Remote refused setting thread events: %s"), rs->buf);
13858 break;
13859 case PACKET_ERROR:
13860 warning (_("Remote failure reply: %s"), rs->buf);
13861 break;
13862 case PACKET_UNKNOWN:
13863 break;
13864 }
13865 }
13866
13867 static void
13868 set_remote_cmd (const char *args, int from_tty)
13869 {
13870 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13871 }
13872
13873 static void
13874 show_remote_cmd (const char *args, int from_tty)
13875 {
13876 /* We can't just use cmd_show_list here, because we want to skip
13877 the redundant "show remote Z-packet" and the legacy aliases. */
13878 struct cmd_list_element *list = remote_show_cmdlist;
13879 struct ui_out *uiout = current_uiout;
13880
13881 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13882 for (; list != NULL; list = list->next)
13883 if (strcmp (list->name, "Z-packet") == 0)
13884 continue;
13885 else if (list->type == not_set_cmd)
13886 /* Alias commands are exactly like the original, except they
13887 don't have the normal type. */
13888 continue;
13889 else
13890 {
13891 ui_out_emit_tuple option_emitter (uiout, "option");
13892
13893 uiout->field_string ("name", list->name);
13894 uiout->text (": ");
13895 if (list->type == show_cmd)
13896 do_show_command (NULL, from_tty, list);
13897 else
13898 cmd_func (list, NULL, from_tty);
13899 }
13900 }
13901
13902
13903 /* Function to be called whenever a new objfile (shlib) is detected. */
13904 static void
13905 remote_new_objfile (struct objfile *objfile)
13906 {
13907 struct remote_state *rs = get_remote_state ();
13908
13909 if (rs->remote_desc != 0) /* Have a remote connection. */
13910 remote_check_symbols ();
13911 }
13912
13913 /* Pull all the tracepoints defined on the target and create local
13914 data structures representing them. We don't want to create real
13915 tracepoints yet, we don't want to mess up the user's existing
13916 collection. */
13917
13918 int
13919 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
13920 {
13921 struct remote_state *rs = get_remote_state ();
13922 char *p;
13923
13924 /* Ask for a first packet of tracepoint definition. */
13925 putpkt ("qTfP");
13926 getpkt (&rs->buf, &rs->buf_size, 0);
13927 p = rs->buf;
13928 while (*p && *p != 'l')
13929 {
13930 parse_tracepoint_definition (p, utpp);
13931 /* Ask for another packet of tracepoint definition. */
13932 putpkt ("qTsP");
13933 getpkt (&rs->buf, &rs->buf_size, 0);
13934 p = rs->buf;
13935 }
13936 return 0;
13937 }
13938
13939 int
13940 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
13941 {
13942 struct remote_state *rs = get_remote_state ();
13943 char *p;
13944
13945 /* Ask for a first packet of variable definition. */
13946 putpkt ("qTfV");
13947 getpkt (&rs->buf, &rs->buf_size, 0);
13948 p = rs->buf;
13949 while (*p && *p != 'l')
13950 {
13951 parse_tsv_definition (p, utsvp);
13952 /* Ask for another packet of variable definition. */
13953 putpkt ("qTsV");
13954 getpkt (&rs->buf, &rs->buf_size, 0);
13955 p = rs->buf;
13956 }
13957 return 0;
13958 }
13959
13960 /* The "set/show range-stepping" show hook. */
13961
13962 static void
13963 show_range_stepping (struct ui_file *file, int from_tty,
13964 struct cmd_list_element *c,
13965 const char *value)
13966 {
13967 fprintf_filtered (file,
13968 _("Debugger's willingness to use range stepping "
13969 "is %s.\n"), value);
13970 }
13971
13972 /* The "set/show range-stepping" set hook. */
13973
13974 static void
13975 set_range_stepping (const char *ignore_args, int from_tty,
13976 struct cmd_list_element *c)
13977 {
13978 struct remote_state *rs = get_remote_state ();
13979
13980 /* Whene enabling, check whether range stepping is actually
13981 supported by the target, and warn if not. */
13982 if (use_range_stepping)
13983 {
13984 if (rs->remote_desc != NULL)
13985 {
13986 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13987 remote_vcont_probe (rs);
13988
13989 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13990 && rs->supports_vCont.r)
13991 return;
13992 }
13993
13994 warning (_("Range stepping is not supported by the current target"));
13995 }
13996 }
13997
13998 void
13999 _initialize_remote (void)
14000 {
14001 struct cmd_list_element *cmd;
14002 const char *cmd_name;
14003
14004 /* architecture specific data */
14005 remote_gdbarch_data_handle =
14006 gdbarch_data_register_post_init (init_remote_state);
14007 remote_g_packet_data_handle =
14008 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14009
14010 remote_pspace_data
14011 = register_program_space_data_with_cleanup (NULL,
14012 remote_pspace_data_cleanup);
14013
14014 /* Initialize the per-target state. At the moment there is only one
14015 of these, not one per target. Only one target is active at a
14016 time. */
14017 remote_state = new_remote_state ();
14018
14019 add_target (remote_target_info, remote_target::open);
14020 add_target (extended_remote_target_info, extended_remote_target::open);
14021
14022 /* Hook into new objfile notification. */
14023 gdb::observers::new_objfile.attach (remote_new_objfile);
14024 /* We're no longer interested in notification events of an inferior
14025 when it exits. */
14026 gdb::observers::inferior_exit.attach (discard_pending_stop_replies);
14027
14028 #if 0
14029 init_remote_threadtests ();
14030 #endif
14031
14032 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14033 /* set/show remote ... */
14034
14035 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14036 Remote protocol specific variables\n\
14037 Configure various remote-protocol specific variables such as\n\
14038 the packets being used"),
14039 &remote_set_cmdlist, "set remote ",
14040 0 /* allow-unknown */, &setlist);
14041 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14042 Remote protocol specific variables\n\
14043 Configure various remote-protocol specific variables such as\n\
14044 the packets being used"),
14045 &remote_show_cmdlist, "show remote ",
14046 0 /* allow-unknown */, &showlist);
14047
14048 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14049 Compare section data on target to the exec file.\n\
14050 Argument is a single section name (default: all loaded sections).\n\
14051 To compare only read-only loaded sections, specify the -r option."),
14052 &cmdlist);
14053
14054 add_cmd ("packet", class_maintenance, packet_command, _("\
14055 Send an arbitrary packet to a remote target.\n\
14056 maintenance packet TEXT\n\
14057 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14058 this command sends the string TEXT to the inferior, and displays the\n\
14059 response packet. GDB supplies the initial `$' character, and the\n\
14060 terminating `#' character and checksum."),
14061 &maintenancelist);
14062
14063 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14064 Set whether to send break if interrupted."), _("\
14065 Show whether to send break if interrupted."), _("\
14066 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14067 set_remotebreak, show_remotebreak,
14068 &setlist, &showlist);
14069 cmd_name = "remotebreak";
14070 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14071 deprecate_cmd (cmd, "set remote interrupt-sequence");
14072 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14073 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14074 deprecate_cmd (cmd, "show remote interrupt-sequence");
14075
14076 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14077 interrupt_sequence_modes, &interrupt_sequence_mode,
14078 _("\
14079 Set interrupt sequence to remote target."), _("\
14080 Show interrupt sequence to remote target."), _("\
14081 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14082 NULL, show_interrupt_sequence,
14083 &remote_set_cmdlist,
14084 &remote_show_cmdlist);
14085
14086 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14087 &interrupt_on_connect, _("\
14088 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14089 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14090 If set, interrupt sequence is sent to remote target."),
14091 NULL, NULL,
14092 &remote_set_cmdlist, &remote_show_cmdlist);
14093
14094 /* Install commands for configuring memory read/write packets. */
14095
14096 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14097 Set the maximum number of bytes per memory write packet (deprecated)."),
14098 &setlist);
14099 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14100 Show the maximum number of bytes per memory write packet (deprecated)."),
14101 &showlist);
14102 add_cmd ("memory-write-packet-size", no_class,
14103 set_memory_write_packet_size, _("\
14104 Set the maximum number of bytes per memory-write packet.\n\
14105 Specify the number of bytes in a packet or 0 (zero) for the\n\
14106 default packet size. The actual limit is further reduced\n\
14107 dependent on the target. Specify ``fixed'' to disable the\n\
14108 further restriction and ``limit'' to enable that restriction."),
14109 &remote_set_cmdlist);
14110 add_cmd ("memory-read-packet-size", no_class,
14111 set_memory_read_packet_size, _("\
14112 Set the maximum number of bytes per memory-read packet.\n\
14113 Specify the number of bytes in a packet or 0 (zero) for the\n\
14114 default packet size. The actual limit is further reduced\n\
14115 dependent on the target. Specify ``fixed'' to disable the\n\
14116 further restriction and ``limit'' to enable that restriction."),
14117 &remote_set_cmdlist);
14118 add_cmd ("memory-write-packet-size", no_class,
14119 show_memory_write_packet_size,
14120 _("Show the maximum number of bytes per memory-write packet."),
14121 &remote_show_cmdlist);
14122 add_cmd ("memory-read-packet-size", no_class,
14123 show_memory_read_packet_size,
14124 _("Show the maximum number of bytes per memory-read packet."),
14125 &remote_show_cmdlist);
14126
14127 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14128 &remote_hw_watchpoint_limit, _("\
14129 Set the maximum number of target hardware watchpoints."), _("\
14130 Show the maximum number of target hardware watchpoints."), _("\
14131 Specify a negative limit for unlimited."),
14132 NULL, NULL, /* FIXME: i18n: The maximum
14133 number of target hardware
14134 watchpoints is %s. */
14135 &remote_set_cmdlist, &remote_show_cmdlist);
14136 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14137 &remote_hw_watchpoint_length_limit, _("\
14138 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14139 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14140 Specify a negative limit for unlimited."),
14141 NULL, NULL, /* FIXME: i18n: The maximum
14142 length (in bytes) of a target
14143 hardware watchpoint is %s. */
14144 &remote_set_cmdlist, &remote_show_cmdlist);
14145 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14146 &remote_hw_breakpoint_limit, _("\
14147 Set the maximum number of target hardware breakpoints."), _("\
14148 Show the maximum number of target hardware breakpoints."), _("\
14149 Specify a negative limit for unlimited."),
14150 NULL, NULL, /* FIXME: i18n: The maximum
14151 number of target hardware
14152 breakpoints is %s. */
14153 &remote_set_cmdlist, &remote_show_cmdlist);
14154
14155 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14156 &remote_address_size, _("\
14157 Set the maximum size of the address (in bits) in a memory packet."), _("\
14158 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14159 NULL,
14160 NULL, /* FIXME: i18n: */
14161 &setlist, &showlist);
14162
14163 init_all_packet_configs ();
14164
14165 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14166 "X", "binary-download", 1);
14167
14168 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14169 "vCont", "verbose-resume", 0);
14170
14171 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14172 "QPassSignals", "pass-signals", 0);
14173
14174 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14175 "QCatchSyscalls", "catch-syscalls", 0);
14176
14177 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14178 "QProgramSignals", "program-signals", 0);
14179
14180 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14181 "QSetWorkingDir", "set-working-dir", 0);
14182
14183 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14184 "QStartupWithShell", "startup-with-shell", 0);
14185
14186 add_packet_config_cmd (&remote_protocol_packets
14187 [PACKET_QEnvironmentHexEncoded],
14188 "QEnvironmentHexEncoded", "environment-hex-encoded",
14189 0);
14190
14191 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14192 "QEnvironmentReset", "environment-reset",
14193 0);
14194
14195 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14196 "QEnvironmentUnset", "environment-unset",
14197 0);
14198
14199 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14200 "qSymbol", "symbol-lookup", 0);
14201
14202 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14203 "P", "set-register", 1);
14204
14205 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14206 "p", "fetch-register", 1);
14207
14208 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14209 "Z0", "software-breakpoint", 0);
14210
14211 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14212 "Z1", "hardware-breakpoint", 0);
14213
14214 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14215 "Z2", "write-watchpoint", 0);
14216
14217 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14218 "Z3", "read-watchpoint", 0);
14219
14220 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14221 "Z4", "access-watchpoint", 0);
14222
14223 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14224 "qXfer:auxv:read", "read-aux-vector", 0);
14225
14226 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14227 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14228
14229 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14230 "qXfer:features:read", "target-features", 0);
14231
14232 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14233 "qXfer:libraries:read", "library-info", 0);
14234
14235 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14236 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14237
14238 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14239 "qXfer:memory-map:read", "memory-map", 0);
14240
14241 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14242 "qXfer:spu:read", "read-spu-object", 0);
14243
14244 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14245 "qXfer:spu:write", "write-spu-object", 0);
14246
14247 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14248 "qXfer:osdata:read", "osdata", 0);
14249
14250 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14251 "qXfer:threads:read", "threads", 0);
14252
14253 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14254 "qXfer:siginfo:read", "read-siginfo-object", 0);
14255
14256 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14257 "qXfer:siginfo:write", "write-siginfo-object", 0);
14258
14259 add_packet_config_cmd
14260 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14261 "qXfer:traceframe-info:read", "traceframe-info", 0);
14262
14263 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14264 "qXfer:uib:read", "unwind-info-block", 0);
14265
14266 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14267 "qGetTLSAddr", "get-thread-local-storage-address",
14268 0);
14269
14270 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14271 "qGetTIBAddr", "get-thread-information-block-address",
14272 0);
14273
14274 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14275 "bc", "reverse-continue", 0);
14276
14277 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14278 "bs", "reverse-step", 0);
14279
14280 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14281 "qSupported", "supported-packets", 0);
14282
14283 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14284 "qSearch:memory", "search-memory", 0);
14285
14286 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14287 "qTStatus", "trace-status", 0);
14288
14289 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14290 "vFile:setfs", "hostio-setfs", 0);
14291
14292 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14293 "vFile:open", "hostio-open", 0);
14294
14295 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14296 "vFile:pread", "hostio-pread", 0);
14297
14298 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14299 "vFile:pwrite", "hostio-pwrite", 0);
14300
14301 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14302 "vFile:close", "hostio-close", 0);
14303
14304 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14305 "vFile:unlink", "hostio-unlink", 0);
14306
14307 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14308 "vFile:readlink", "hostio-readlink", 0);
14309
14310 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14311 "vFile:fstat", "hostio-fstat", 0);
14312
14313 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14314 "vAttach", "attach", 0);
14315
14316 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14317 "vRun", "run", 0);
14318
14319 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14320 "QStartNoAckMode", "noack", 0);
14321
14322 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14323 "vKill", "kill", 0);
14324
14325 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14326 "qAttached", "query-attached", 0);
14327
14328 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14329 "ConditionalTracepoints",
14330 "conditional-tracepoints", 0);
14331
14332 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14333 "ConditionalBreakpoints",
14334 "conditional-breakpoints", 0);
14335
14336 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14337 "BreakpointCommands",
14338 "breakpoint-commands", 0);
14339
14340 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14341 "FastTracepoints", "fast-tracepoints", 0);
14342
14343 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14344 "TracepointSource", "TracepointSource", 0);
14345
14346 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14347 "QAllow", "allow", 0);
14348
14349 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14350 "StaticTracepoints", "static-tracepoints", 0);
14351
14352 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14353 "InstallInTrace", "install-in-trace", 0);
14354
14355 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14356 "qXfer:statictrace:read", "read-sdata-object", 0);
14357
14358 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14359 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14360
14361 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14362 "QDisableRandomization", "disable-randomization", 0);
14363
14364 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14365 "QAgent", "agent", 0);
14366
14367 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14368 "QTBuffer:size", "trace-buffer-size", 0);
14369
14370 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14371 "Qbtrace:off", "disable-btrace", 0);
14372
14373 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14374 "Qbtrace:bts", "enable-btrace-bts", 0);
14375
14376 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14377 "Qbtrace:pt", "enable-btrace-pt", 0);
14378
14379 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14380 "qXfer:btrace", "read-btrace", 0);
14381
14382 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14383 "qXfer:btrace-conf", "read-btrace-conf", 0);
14384
14385 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14386 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14387
14388 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14389 "multiprocess-feature", "multiprocess-feature", 0);
14390
14391 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14392 "swbreak-feature", "swbreak-feature", 0);
14393
14394 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14395 "hwbreak-feature", "hwbreak-feature", 0);
14396
14397 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14398 "fork-event-feature", "fork-event-feature", 0);
14399
14400 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14401 "vfork-event-feature", "vfork-event-feature", 0);
14402
14403 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14404 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14405
14406 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14407 "vContSupported", "verbose-resume-supported", 0);
14408
14409 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14410 "exec-event-feature", "exec-event-feature", 0);
14411
14412 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14413 "vCtrlC", "ctrl-c", 0);
14414
14415 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14416 "QThreadEvents", "thread-events", 0);
14417
14418 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14419 "N stop reply", "no-resumed-stop-reply", 0);
14420
14421 /* Assert that we've registered "set remote foo-packet" commands
14422 for all packet configs. */
14423 {
14424 int i;
14425
14426 for (i = 0; i < PACKET_MAX; i++)
14427 {
14428 /* Ideally all configs would have a command associated. Some
14429 still don't though. */
14430 int excepted;
14431
14432 switch (i)
14433 {
14434 case PACKET_QNonStop:
14435 case PACKET_EnableDisableTracepoints_feature:
14436 case PACKET_tracenz_feature:
14437 case PACKET_DisconnectedTracing_feature:
14438 case PACKET_augmented_libraries_svr4_read_feature:
14439 case PACKET_qCRC:
14440 /* Additions to this list need to be well justified:
14441 pre-existing packets are OK; new packets are not. */
14442 excepted = 1;
14443 break;
14444 default:
14445 excepted = 0;
14446 break;
14447 }
14448
14449 /* This catches both forgetting to add a config command, and
14450 forgetting to remove a packet from the exception list. */
14451 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14452 }
14453 }
14454
14455 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14456 Z sub-packet has its own set and show commands, but users may
14457 have sets to this variable in their .gdbinit files (or in their
14458 documentation). */
14459 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14460 &remote_Z_packet_detect, _("\
14461 Set use of remote protocol `Z' packets"), _("\
14462 Show use of remote protocol `Z' packets "), _("\
14463 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14464 packets."),
14465 set_remote_protocol_Z_packet_cmd,
14466 show_remote_protocol_Z_packet_cmd,
14467 /* FIXME: i18n: Use of remote protocol
14468 `Z' packets is %s. */
14469 &remote_set_cmdlist, &remote_show_cmdlist);
14470
14471 add_prefix_cmd ("remote", class_files, remote_command, _("\
14472 Manipulate files on the remote system\n\
14473 Transfer files to and from the remote target system."),
14474 &remote_cmdlist, "remote ",
14475 0 /* allow-unknown */, &cmdlist);
14476
14477 add_cmd ("put", class_files, remote_put_command,
14478 _("Copy a local file to the remote system."),
14479 &remote_cmdlist);
14480
14481 add_cmd ("get", class_files, remote_get_command,
14482 _("Copy a remote file to the local system."),
14483 &remote_cmdlist);
14484
14485 add_cmd ("delete", class_files, remote_delete_command,
14486 _("Delete a remote file."),
14487 &remote_cmdlist);
14488
14489 add_setshow_string_noescape_cmd ("exec-file", class_files,
14490 &remote_exec_file_var, _("\
14491 Set the remote pathname for \"run\""), _("\
14492 Show the remote pathname for \"run\""), NULL,
14493 set_remote_exec_file,
14494 show_remote_exec_file,
14495 &remote_set_cmdlist,
14496 &remote_show_cmdlist);
14497
14498 add_setshow_boolean_cmd ("range-stepping", class_run,
14499 &use_range_stepping, _("\
14500 Enable or disable range stepping."), _("\
14501 Show whether target-assisted range stepping is enabled."), _("\
14502 If on, and the target supports it, when stepping a source line, GDB\n\
14503 tells the target to step the corresponding range of addresses itself instead\n\
14504 of issuing multiple single-steps. This speeds up source level\n\
14505 stepping. If off, GDB always issues single-steps, even if range\n\
14506 stepping is supported by the target. The default is on."),
14507 set_range_stepping,
14508 show_range_stepping,
14509 &setlist,
14510 &showlist);
14511
14512 /* Eventually initialize fileio. See fileio.c */
14513 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14514
14515 /* Take advantage of the fact that the TID field is not used, to tag
14516 special ptids with it set to != 0. */
14517 magic_null_ptid = ptid_build (42000, -1, 1);
14518 not_sent_ptid = ptid_build (42000, -2, 1);
14519 any_thread_ptid = ptid_build (42000, 0, 1);
14520 }
This page took 0.307538 seconds and 5 git commands to generate.