Use counted_command_line everywhere
[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 void
4961 remote_query_supported_append (std::string *msg, const char *append)
4962 {
4963 if (!msg->empty ())
4964 msg->append (";");
4965 msg->append (append);
4966 }
4967
4968 static void
4969 remote_query_supported (void)
4970 {
4971 struct remote_state *rs = get_remote_state ();
4972 char *next;
4973 int i;
4974 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4975
4976 /* The packet support flags are handled differently for this packet
4977 than for most others. We treat an error, a disabled packet, and
4978 an empty response identically: any features which must be reported
4979 to be used will be automatically disabled. An empty buffer
4980 accomplishes this, since that is also the representation for a list
4981 containing no features. */
4982
4983 rs->buf[0] = 0;
4984 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4985 {
4986 std::string q;
4987
4988 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4989 remote_query_supported_append (&q, "multiprocess+");
4990
4991 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4992 remote_query_supported_append (&q, "swbreak+");
4993 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4994 remote_query_supported_append (&q, "hwbreak+");
4995
4996 remote_query_supported_append (&q, "qRelocInsn+");
4997
4998 if (packet_set_cmd_state (PACKET_fork_event_feature)
4999 != AUTO_BOOLEAN_FALSE)
5000 remote_query_supported_append (&q, "fork-events+");
5001 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5002 != AUTO_BOOLEAN_FALSE)
5003 remote_query_supported_append (&q, "vfork-events+");
5004 if (packet_set_cmd_state (PACKET_exec_event_feature)
5005 != AUTO_BOOLEAN_FALSE)
5006 remote_query_supported_append (&q, "exec-events+");
5007
5008 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5009 remote_query_supported_append (&q, "vContSupported+");
5010
5011 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5012 remote_query_supported_append (&q, "QThreadEvents+");
5013
5014 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5015 remote_query_supported_append (&q, "no-resumed+");
5016
5017 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5018 the qSupported:xmlRegisters=i386 handling. */
5019 if (remote_support_xml != NULL
5020 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5021 remote_query_supported_append (&q, remote_support_xml);
5022
5023 q = "qSupported:" + q;
5024 putpkt (q.c_str ());
5025
5026 getpkt (&rs->buf, &rs->buf_size, 0);
5027
5028 /* If an error occured, warn, but do not return - just reset the
5029 buffer to empty and go on to disable features. */
5030 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5031 == PACKET_ERROR)
5032 {
5033 warning (_("Remote failure reply: %s"), rs->buf);
5034 rs->buf[0] = 0;
5035 }
5036 }
5037
5038 memset (seen, 0, sizeof (seen));
5039
5040 next = rs->buf;
5041 while (*next)
5042 {
5043 enum packet_support is_supported;
5044 char *p, *end, *name_end, *value;
5045
5046 /* First separate out this item from the rest of the packet. If
5047 there's another item after this, we overwrite the separator
5048 (terminated strings are much easier to work with). */
5049 p = next;
5050 end = strchr (p, ';');
5051 if (end == NULL)
5052 {
5053 end = p + strlen (p);
5054 next = end;
5055 }
5056 else
5057 {
5058 *end = '\0';
5059 next = end + 1;
5060
5061 if (end == p)
5062 {
5063 warning (_("empty item in \"qSupported\" response"));
5064 continue;
5065 }
5066 }
5067
5068 name_end = strchr (p, '=');
5069 if (name_end)
5070 {
5071 /* This is a name=value entry. */
5072 is_supported = PACKET_ENABLE;
5073 value = name_end + 1;
5074 *name_end = '\0';
5075 }
5076 else
5077 {
5078 value = NULL;
5079 switch (end[-1])
5080 {
5081 case '+':
5082 is_supported = PACKET_ENABLE;
5083 break;
5084
5085 case '-':
5086 is_supported = PACKET_DISABLE;
5087 break;
5088
5089 case '?':
5090 is_supported = PACKET_SUPPORT_UNKNOWN;
5091 break;
5092
5093 default:
5094 warning (_("unrecognized item \"%s\" "
5095 "in \"qSupported\" response"), p);
5096 continue;
5097 }
5098 end[-1] = '\0';
5099 }
5100
5101 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5102 if (strcmp (remote_protocol_features[i].name, p) == 0)
5103 {
5104 const struct protocol_feature *feature;
5105
5106 seen[i] = 1;
5107 feature = &remote_protocol_features[i];
5108 feature->func (feature, is_supported, value);
5109 break;
5110 }
5111 }
5112
5113 /* If we increased the packet size, make sure to increase the global
5114 buffer size also. We delay this until after parsing the entire
5115 qSupported packet, because this is the same buffer we were
5116 parsing. */
5117 if (rs->buf_size < rs->explicit_packet_size)
5118 {
5119 rs->buf_size = rs->explicit_packet_size;
5120 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5121 }
5122
5123 /* Handle the defaults for unmentioned features. */
5124 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5125 if (!seen[i])
5126 {
5127 const struct protocol_feature *feature;
5128
5129 feature = &remote_protocol_features[i];
5130 feature->func (feature, feature->default_support, NULL);
5131 }
5132 }
5133
5134 /* Serial QUIT handler for the remote serial descriptor.
5135
5136 Defers handling a Ctrl-C until we're done with the current
5137 command/response packet sequence, unless:
5138
5139 - We're setting up the connection. Don't send a remote interrupt
5140 request, as we're not fully synced yet. Quit immediately
5141 instead.
5142
5143 - The target has been resumed in the foreground
5144 (target_terminal::is_ours is false) with a synchronous resume
5145 packet, and we're blocked waiting for the stop reply, thus a
5146 Ctrl-C should be immediately sent to the target.
5147
5148 - We get a second Ctrl-C while still within the same serial read or
5149 write. In that case the serial is seemingly wedged --- offer to
5150 quit/disconnect.
5151
5152 - We see a second Ctrl-C without target response, after having
5153 previously interrupted the target. In that case the target/stub
5154 is probably wedged --- offer to quit/disconnect.
5155 */
5156
5157 static void
5158 remote_serial_quit_handler (void)
5159 {
5160 struct remote_state *rs = get_remote_state ();
5161
5162 if (check_quit_flag ())
5163 {
5164 /* If we're starting up, we're not fully synced yet. Quit
5165 immediately. */
5166 if (rs->starting_up)
5167 quit ();
5168 else if (rs->got_ctrlc_during_io)
5169 {
5170 if (query (_("The target is not responding to GDB commands.\n"
5171 "Stop debugging it? ")))
5172 remote_unpush_and_throw ();
5173 }
5174 /* If ^C has already been sent once, offer to disconnect. */
5175 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5176 interrupt_query ();
5177 /* All-stop protocol, and blocked waiting for stop reply. Send
5178 an interrupt request. */
5179 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5180 target_interrupt ();
5181 else
5182 rs->got_ctrlc_during_io = 1;
5183 }
5184 }
5185
5186 /* Remove any of the remote.c targets from target stack. Upper targets depend
5187 on it so remove them first. */
5188
5189 static void
5190 remote_unpush_target (void)
5191 {
5192 pop_all_targets_at_and_above (process_stratum);
5193 }
5194
5195 static void
5196 remote_unpush_and_throw (void)
5197 {
5198 remote_unpush_target ();
5199 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5200 }
5201
5202 void
5203 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5204 {
5205 struct remote_state *rs = get_remote_state ();
5206
5207 if (name == 0)
5208 error (_("To open a remote debug connection, you need to specify what\n"
5209 "serial device is attached to the remote system\n"
5210 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5211
5212 /* See FIXME above. */
5213 if (!target_async_permitted)
5214 wait_forever_enabled_p = 1;
5215
5216 /* If we're connected to a running target, target_preopen will kill it.
5217 Ask this question first, before target_preopen has a chance to kill
5218 anything. */
5219 if (rs->remote_desc != NULL && !have_inferiors ())
5220 {
5221 if (from_tty
5222 && !query (_("Already connected to a remote target. Disconnect? ")))
5223 error (_("Still connected."));
5224 }
5225
5226 /* Here the possibly existing remote target gets unpushed. */
5227 target_preopen (from_tty);
5228
5229 /* Make sure we send the passed signals list the next time we resume. */
5230 xfree (rs->last_pass_packet);
5231 rs->last_pass_packet = NULL;
5232
5233 /* Make sure we send the program signals list the next time we
5234 resume. */
5235 xfree (rs->last_program_signals_packet);
5236 rs->last_program_signals_packet = NULL;
5237
5238 remote_fileio_reset ();
5239 reopen_exec_file ();
5240 reread_symbols ();
5241
5242 rs->remote_desc = remote_serial_open (name);
5243 if (!rs->remote_desc)
5244 perror_with_name (name);
5245
5246 if (baud_rate != -1)
5247 {
5248 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5249 {
5250 /* The requested speed could not be set. Error out to
5251 top level after closing remote_desc. Take care to
5252 set remote_desc to NULL to avoid closing remote_desc
5253 more than once. */
5254 serial_close (rs->remote_desc);
5255 rs->remote_desc = NULL;
5256 perror_with_name (name);
5257 }
5258 }
5259
5260 serial_setparity (rs->remote_desc, serial_parity);
5261 serial_raw (rs->remote_desc);
5262
5263 /* If there is something sitting in the buffer we might take it as a
5264 response to a command, which would be bad. */
5265 serial_flush_input (rs->remote_desc);
5266
5267 if (from_tty)
5268 {
5269 puts_filtered ("Remote debugging using ");
5270 puts_filtered (name);
5271 puts_filtered ("\n");
5272 }
5273
5274 remote_target *target
5275 = extended_p ? &extended_remote_ops : &remote_ops;
5276 push_target (target); /* Switch to using remote target now. */
5277
5278 /* Register extra event sources in the event loop. */
5279 remote_async_inferior_event_token
5280 = create_async_event_handler (remote_async_inferior_event_handler,
5281 NULL);
5282 rs->notif_state = remote_notif_state_allocate ();
5283
5284 /* Reset the target state; these things will be queried either by
5285 remote_query_supported or as they are needed. */
5286 reset_all_packet_configs_support ();
5287 rs->cached_wait_status = 0;
5288 rs->explicit_packet_size = 0;
5289 rs->noack_mode = 0;
5290 rs->extended = extended_p;
5291 rs->waiting_for_stop_reply = 0;
5292 rs->ctrlc_pending_p = 0;
5293 rs->got_ctrlc_during_io = 0;
5294
5295 rs->general_thread = not_sent_ptid;
5296 rs->continue_thread = not_sent_ptid;
5297 rs->remote_traceframe_number = -1;
5298
5299 rs->last_resume_exec_dir = EXEC_FORWARD;
5300
5301 /* Probe for ability to use "ThreadInfo" query, as required. */
5302 rs->use_threadinfo_query = 1;
5303 rs->use_threadextra_query = 1;
5304
5305 readahead_cache_invalidate ();
5306
5307 if (target_async_permitted)
5308 {
5309 /* FIXME: cagney/1999-09-23: During the initial connection it is
5310 assumed that the target is already ready and able to respond to
5311 requests. Unfortunately remote_start_remote() eventually calls
5312 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5313 around this. Eventually a mechanism that allows
5314 wait_for_inferior() to expect/get timeouts will be
5315 implemented. */
5316 wait_forever_enabled_p = 0;
5317 }
5318
5319 /* First delete any symbols previously loaded from shared libraries. */
5320 no_shared_libraries (NULL, 0);
5321
5322 /* Start afresh. */
5323 init_thread_list ();
5324
5325 /* Start the remote connection. If error() or QUIT, discard this
5326 target (we'd otherwise be in an inconsistent state) and then
5327 propogate the error on up the exception chain. This ensures that
5328 the caller doesn't stumble along blindly assuming that the
5329 function succeeded. The CLI doesn't have this problem but other
5330 UI's, such as MI do.
5331
5332 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5333 this function should return an error indication letting the
5334 caller restore the previous state. Unfortunately the command
5335 ``target remote'' is directly wired to this function making that
5336 impossible. On a positive note, the CLI side of this problem has
5337 been fixed - the function set_cmd_context() makes it possible for
5338 all the ``target ....'' commands to share a common callback
5339 function. See cli-dump.c. */
5340 {
5341
5342 TRY
5343 {
5344 target->start_remote (from_tty, extended_p);
5345 }
5346 CATCH (ex, RETURN_MASK_ALL)
5347 {
5348 /* Pop the partially set up target - unless something else did
5349 already before throwing the exception. */
5350 if (rs->remote_desc != NULL)
5351 remote_unpush_target ();
5352 if (target_async_permitted)
5353 wait_forever_enabled_p = 1;
5354 throw_exception (ex);
5355 }
5356 END_CATCH
5357 }
5358
5359 remote_btrace_reset ();
5360
5361 if (target_async_permitted)
5362 wait_forever_enabled_p = 1;
5363 }
5364
5365 /* Detach the specified process. */
5366
5367 static void
5368 remote_detach_pid (int pid)
5369 {
5370 struct remote_state *rs = get_remote_state ();
5371
5372 if (remote_multi_process_p (rs))
5373 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5374 else
5375 strcpy (rs->buf, "D");
5376
5377 putpkt (rs->buf);
5378 getpkt (&rs->buf, &rs->buf_size, 0);
5379
5380 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5381 ;
5382 else if (rs->buf[0] == '\0')
5383 error (_("Remote doesn't know how to detach"));
5384 else
5385 error (_("Can't detach process."));
5386 }
5387
5388 /* This detaches a program to which we previously attached, using
5389 inferior_ptid to identify the process. After this is done, GDB
5390 can be used to debug some other program. We better not have left
5391 any breakpoints in the target program or it'll die when it hits
5392 one. */
5393
5394 static void
5395 remote_detach_1 (int from_tty, inferior *inf)
5396 {
5397 int pid = ptid_get_pid (inferior_ptid);
5398 struct remote_state *rs = get_remote_state ();
5399 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5400 int is_fork_parent;
5401
5402 if (!target_has_execution)
5403 error (_("No process to detach from."));
5404
5405 target_announce_detach (from_tty);
5406
5407 /* Tell the remote target to detach. */
5408 remote_detach_pid (pid);
5409
5410 /* Exit only if this is the only active inferior. */
5411 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5412 puts_filtered (_("Ending remote debugging.\n"));
5413
5414 /* Check to see if we are detaching a fork parent. Note that if we
5415 are detaching a fork child, tp == NULL. */
5416 is_fork_parent = (tp != NULL
5417 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5418
5419 /* If doing detach-on-fork, we don't mourn, because that will delete
5420 breakpoints that should be available for the followed inferior. */
5421 if (!is_fork_parent)
5422 {
5423 /* Save the pid as a string before mourning, since that will
5424 unpush the remote target, and we need the string after. */
5425 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5426
5427 target_mourn_inferior (inferior_ptid);
5428 if (print_inferior_events)
5429 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5430 inf->num, infpid.c_str ());
5431 }
5432 else
5433 {
5434 inferior_ptid = null_ptid;
5435 detach_inferior (pid);
5436 }
5437 }
5438
5439 void
5440 remote_target::detach (inferior *inf, int from_tty)
5441 {
5442 remote_detach_1 (from_tty, inf);
5443 }
5444
5445 void
5446 extended_remote_target::detach (inferior *inf, int from_tty)
5447 {
5448 remote_detach_1 (from_tty, inf);
5449 }
5450
5451 /* Target follow-fork function for remote targets. On entry, and
5452 at return, the current inferior is the fork parent.
5453
5454 Note that although this is currently only used for extended-remote,
5455 it is named remote_follow_fork in anticipation of using it for the
5456 remote target as well. */
5457
5458 int
5459 remote_target::follow_fork (int follow_child, int detach_fork)
5460 {
5461 struct remote_state *rs = get_remote_state ();
5462 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5463
5464 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5465 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5466 {
5467 /* When following the parent and detaching the child, we detach
5468 the child here. For the case of following the child and
5469 detaching the parent, the detach is done in the target-
5470 independent follow fork code in infrun.c. We can't use
5471 target_detach when detaching an unfollowed child because
5472 the client side doesn't know anything about the child. */
5473 if (detach_fork && !follow_child)
5474 {
5475 /* Detach the fork child. */
5476 ptid_t child_ptid;
5477 pid_t child_pid;
5478
5479 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5480 child_pid = ptid_get_pid (child_ptid);
5481
5482 remote_detach_pid (child_pid);
5483 }
5484 }
5485 return 0;
5486 }
5487
5488 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5489 in the program space of the new inferior. On entry and at return the
5490 current inferior is the exec'ing inferior. INF is the new exec'd
5491 inferior, which may be the same as the exec'ing inferior unless
5492 follow-exec-mode is "new". */
5493
5494 void
5495 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5496 {
5497 /* We know that this is a target file name, so if it has the "target:"
5498 prefix we strip it off before saving it in the program space. */
5499 if (is_target_filename (execd_pathname))
5500 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5501
5502 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5503 }
5504
5505 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5506
5507 void
5508 remote_target::disconnect (const char *args, int from_tty)
5509 {
5510 if (args)
5511 error (_("Argument given to \"disconnect\" when remotely debugging."));
5512
5513 /* Make sure we unpush even the extended remote targets. Calling
5514 target_mourn_inferior won't unpush, and remote_mourn won't
5515 unpush if there is more than one inferior left. */
5516 unpush_target (this);
5517 generic_mourn_inferior ();
5518
5519 if (from_tty)
5520 puts_filtered ("Ending remote debugging.\n");
5521 }
5522
5523 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5524 be chatty about it. */
5525
5526 void
5527 extended_remote_target::attach (const char *args, int from_tty)
5528 {
5529 struct remote_state *rs = get_remote_state ();
5530 int pid;
5531 char *wait_status = NULL;
5532
5533 pid = parse_pid_to_attach (args);
5534
5535 /* Remote PID can be freely equal to getpid, do not check it here the same
5536 way as in other targets. */
5537
5538 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5539 error (_("This target does not support attaching to a process"));
5540
5541 if (from_tty)
5542 {
5543 char *exec_file = get_exec_file (0);
5544
5545 if (exec_file)
5546 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5547 target_pid_to_str (pid_to_ptid (pid)));
5548 else
5549 printf_unfiltered (_("Attaching to %s\n"),
5550 target_pid_to_str (pid_to_ptid (pid)));
5551
5552 gdb_flush (gdb_stdout);
5553 }
5554
5555 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5556 putpkt (rs->buf);
5557 getpkt (&rs->buf, &rs->buf_size, 0);
5558
5559 switch (packet_ok (rs->buf,
5560 &remote_protocol_packets[PACKET_vAttach]))
5561 {
5562 case PACKET_OK:
5563 if (!target_is_non_stop_p ())
5564 {
5565 /* Save the reply for later. */
5566 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5567 strcpy (wait_status, rs->buf);
5568 }
5569 else if (strcmp (rs->buf, "OK") != 0)
5570 error (_("Attaching to %s failed with: %s"),
5571 target_pid_to_str (pid_to_ptid (pid)),
5572 rs->buf);
5573 break;
5574 case PACKET_UNKNOWN:
5575 error (_("This target does not support attaching to a process"));
5576 default:
5577 error (_("Attaching to %s failed"),
5578 target_pid_to_str (pid_to_ptid (pid)));
5579 }
5580
5581 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5582
5583 inferior_ptid = pid_to_ptid (pid);
5584
5585 if (target_is_non_stop_p ())
5586 {
5587 struct thread_info *thread;
5588
5589 /* Get list of threads. */
5590 update_thread_list ();
5591
5592 thread = first_thread_of_process (pid);
5593 if (thread)
5594 inferior_ptid = thread->ptid;
5595 else
5596 inferior_ptid = pid_to_ptid (pid);
5597
5598 /* Invalidate our notion of the remote current thread. */
5599 record_currthread (rs, minus_one_ptid);
5600 }
5601 else
5602 {
5603 /* Now, if we have thread information, update inferior_ptid. */
5604 inferior_ptid = remote_current_thread (inferior_ptid);
5605
5606 /* Add the main thread to the thread list. */
5607 thread_info *thr = add_thread_silent (inferior_ptid);
5608 /* Don't consider the thread stopped until we've processed the
5609 saved stop reply. */
5610 set_executing (thr->ptid, true);
5611 }
5612
5613 /* Next, if the target can specify a description, read it. We do
5614 this before anything involving memory or registers. */
5615 target_find_description ();
5616
5617 if (!target_is_non_stop_p ())
5618 {
5619 /* Use the previously fetched status. */
5620 gdb_assert (wait_status != NULL);
5621
5622 if (target_can_async_p ())
5623 {
5624 struct notif_event *reply
5625 = remote_notif_parse (&notif_client_stop, wait_status);
5626
5627 push_stop_reply ((struct stop_reply *) reply);
5628
5629 target_async (1);
5630 }
5631 else
5632 {
5633 gdb_assert (wait_status != NULL);
5634 strcpy (rs->buf, wait_status);
5635 rs->cached_wait_status = 1;
5636 }
5637 }
5638 else
5639 gdb_assert (wait_status == NULL);
5640 }
5641
5642 /* Implementation of the to_post_attach method. */
5643
5644 void
5645 extended_remote_target::post_attach (int pid)
5646 {
5647 /* Get text, data & bss offsets. */
5648 get_offsets ();
5649
5650 /* In certain cases GDB might not have had the chance to start
5651 symbol lookup up until now. This could happen if the debugged
5652 binary is not using shared libraries, the vsyscall page is not
5653 present (on Linux) and the binary itself hadn't changed since the
5654 debugging process was started. */
5655 if (symfile_objfile != NULL)
5656 remote_check_symbols();
5657 }
5658
5659 \f
5660 /* Check for the availability of vCont. This function should also check
5661 the response. */
5662
5663 static void
5664 remote_vcont_probe (struct remote_state *rs)
5665 {
5666 char *buf;
5667
5668 strcpy (rs->buf, "vCont?");
5669 putpkt (rs->buf);
5670 getpkt (&rs->buf, &rs->buf_size, 0);
5671 buf = rs->buf;
5672
5673 /* Make sure that the features we assume are supported. */
5674 if (startswith (buf, "vCont"))
5675 {
5676 char *p = &buf[5];
5677 int support_c, support_C;
5678
5679 rs->supports_vCont.s = 0;
5680 rs->supports_vCont.S = 0;
5681 support_c = 0;
5682 support_C = 0;
5683 rs->supports_vCont.t = 0;
5684 rs->supports_vCont.r = 0;
5685 while (p && *p == ';')
5686 {
5687 p++;
5688 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5689 rs->supports_vCont.s = 1;
5690 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5691 rs->supports_vCont.S = 1;
5692 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5693 support_c = 1;
5694 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5695 support_C = 1;
5696 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5697 rs->supports_vCont.t = 1;
5698 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5699 rs->supports_vCont.r = 1;
5700
5701 p = strchr (p, ';');
5702 }
5703
5704 /* If c, and C are not all supported, we can't use vCont. Clearing
5705 BUF will make packet_ok disable the packet. */
5706 if (!support_c || !support_C)
5707 buf[0] = 0;
5708 }
5709
5710 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5711 }
5712
5713 /* Helper function for building "vCont" resumptions. Write a
5714 resumption to P. ENDP points to one-passed-the-end of the buffer
5715 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5716 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5717 resumed thread should be single-stepped and/or signalled. If PTID
5718 equals minus_one_ptid, then all threads are resumed; if PTID
5719 represents a process, then all threads of the process are resumed;
5720 the thread to be stepped and/or signalled is given in the global
5721 INFERIOR_PTID. */
5722
5723 static char *
5724 append_resumption (char *p, char *endp,
5725 ptid_t ptid, int step, enum gdb_signal siggnal)
5726 {
5727 struct remote_state *rs = get_remote_state ();
5728
5729 if (step && siggnal != GDB_SIGNAL_0)
5730 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5731 else if (step
5732 /* GDB is willing to range step. */
5733 && use_range_stepping
5734 /* Target supports range stepping. */
5735 && rs->supports_vCont.r
5736 /* We don't currently support range stepping multiple
5737 threads with a wildcard (though the protocol allows it,
5738 so stubs shouldn't make an active effort to forbid
5739 it). */
5740 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5741 {
5742 struct thread_info *tp;
5743
5744 if (ptid_equal (ptid, minus_one_ptid))
5745 {
5746 /* If we don't know about the target thread's tid, then
5747 we're resuming magic_null_ptid (see caller). */
5748 tp = find_thread_ptid (magic_null_ptid);
5749 }
5750 else
5751 tp = find_thread_ptid (ptid);
5752 gdb_assert (tp != NULL);
5753
5754 if (tp->control.may_range_step)
5755 {
5756 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5757
5758 p += xsnprintf (p, endp - p, ";r%s,%s",
5759 phex_nz (tp->control.step_range_start,
5760 addr_size),
5761 phex_nz (tp->control.step_range_end,
5762 addr_size));
5763 }
5764 else
5765 p += xsnprintf (p, endp - p, ";s");
5766 }
5767 else if (step)
5768 p += xsnprintf (p, endp - p, ";s");
5769 else if (siggnal != GDB_SIGNAL_0)
5770 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5771 else
5772 p += xsnprintf (p, endp - p, ";c");
5773
5774 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5775 {
5776 ptid_t nptid;
5777
5778 /* All (-1) threads of process. */
5779 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5780
5781 p += xsnprintf (p, endp - p, ":");
5782 p = write_ptid (p, endp, nptid);
5783 }
5784 else if (!ptid_equal (ptid, minus_one_ptid))
5785 {
5786 p += xsnprintf (p, endp - p, ":");
5787 p = write_ptid (p, endp, ptid);
5788 }
5789
5790 return p;
5791 }
5792
5793 /* Clear the thread's private info on resume. */
5794
5795 static void
5796 resume_clear_thread_private_info (struct thread_info *thread)
5797 {
5798 if (thread->priv != NULL)
5799 {
5800 remote_thread_info *priv = get_remote_thread_info (thread);
5801
5802 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5803 priv->watch_data_address = 0;
5804 }
5805 }
5806
5807 /* Append a vCont continue-with-signal action for threads that have a
5808 non-zero stop signal. */
5809
5810 static char *
5811 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5812 {
5813 struct thread_info *thread;
5814
5815 ALL_NON_EXITED_THREADS (thread)
5816 if (ptid_match (thread->ptid, ptid)
5817 && !ptid_equal (inferior_ptid, thread->ptid)
5818 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5819 {
5820 p = append_resumption (p, endp, thread->ptid,
5821 0, thread->suspend.stop_signal);
5822 thread->suspend.stop_signal = GDB_SIGNAL_0;
5823 resume_clear_thread_private_info (thread);
5824 }
5825
5826 return p;
5827 }
5828
5829 /* Set the target running, using the packets that use Hc
5830 (c/s/C/S). */
5831
5832 static void
5833 remote_resume_with_hc (struct target_ops *ops,
5834 ptid_t ptid, int step, enum gdb_signal siggnal)
5835 {
5836 struct remote_state *rs = get_remote_state ();
5837 struct thread_info *thread;
5838 char *buf;
5839
5840 rs->last_sent_signal = siggnal;
5841 rs->last_sent_step = step;
5842
5843 /* The c/s/C/S resume packets use Hc, so set the continue
5844 thread. */
5845 if (ptid_equal (ptid, minus_one_ptid))
5846 set_continue_thread (any_thread_ptid);
5847 else
5848 set_continue_thread (ptid);
5849
5850 ALL_NON_EXITED_THREADS (thread)
5851 resume_clear_thread_private_info (thread);
5852
5853 buf = rs->buf;
5854 if (execution_direction == EXEC_REVERSE)
5855 {
5856 /* We don't pass signals to the target in reverse exec mode. */
5857 if (info_verbose && siggnal != GDB_SIGNAL_0)
5858 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5859 siggnal);
5860
5861 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5862 error (_("Remote reverse-step not supported."));
5863 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5864 error (_("Remote reverse-continue not supported."));
5865
5866 strcpy (buf, step ? "bs" : "bc");
5867 }
5868 else if (siggnal != GDB_SIGNAL_0)
5869 {
5870 buf[0] = step ? 'S' : 'C';
5871 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5872 buf[2] = tohex (((int) siggnal) & 0xf);
5873 buf[3] = '\0';
5874 }
5875 else
5876 strcpy (buf, step ? "s" : "c");
5877
5878 putpkt (buf);
5879 }
5880
5881 /* Resume the remote inferior by using a "vCont" packet. The thread
5882 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5883 resumed thread should be single-stepped and/or signalled. If PTID
5884 equals minus_one_ptid, then all threads are resumed; the thread to
5885 be stepped and/or signalled is given in the global INFERIOR_PTID.
5886 This function returns non-zero iff it resumes the inferior.
5887
5888 This function issues a strict subset of all possible vCont commands
5889 at the moment. */
5890
5891 static int
5892 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5893 {
5894 struct remote_state *rs = get_remote_state ();
5895 char *p;
5896 char *endp;
5897
5898 /* No reverse execution actions defined for vCont. */
5899 if (execution_direction == EXEC_REVERSE)
5900 return 0;
5901
5902 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5903 remote_vcont_probe (rs);
5904
5905 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5906 return 0;
5907
5908 p = rs->buf;
5909 endp = rs->buf + get_remote_packet_size ();
5910
5911 /* If we could generate a wider range of packets, we'd have to worry
5912 about overflowing BUF. Should there be a generic
5913 "multi-part-packet" packet? */
5914
5915 p += xsnprintf (p, endp - p, "vCont");
5916
5917 if (ptid_equal (ptid, magic_null_ptid))
5918 {
5919 /* MAGIC_NULL_PTID means that we don't have any active threads,
5920 so we don't have any TID numbers the inferior will
5921 understand. Make sure to only send forms that do not specify
5922 a TID. */
5923 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5924 }
5925 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5926 {
5927 /* Resume all threads (of all processes, or of a single
5928 process), with preference for INFERIOR_PTID. This assumes
5929 inferior_ptid belongs to the set of all threads we are about
5930 to resume. */
5931 if (step || siggnal != GDB_SIGNAL_0)
5932 {
5933 /* Step inferior_ptid, with or without signal. */
5934 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5935 }
5936
5937 /* Also pass down any pending signaled resumption for other
5938 threads not the current. */
5939 p = append_pending_thread_resumptions (p, endp, ptid);
5940
5941 /* And continue others without a signal. */
5942 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5943 }
5944 else
5945 {
5946 /* Scheduler locking; resume only PTID. */
5947 append_resumption (p, endp, ptid, step, siggnal);
5948 }
5949
5950 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5951 putpkt (rs->buf);
5952
5953 if (target_is_non_stop_p ())
5954 {
5955 /* In non-stop, the stub replies to vCont with "OK". The stop
5956 reply will be reported asynchronously by means of a `%Stop'
5957 notification. */
5958 getpkt (&rs->buf, &rs->buf_size, 0);
5959 if (strcmp (rs->buf, "OK") != 0)
5960 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5961 }
5962
5963 return 1;
5964 }
5965
5966 /* Tell the remote machine to resume. */
5967
5968 void
5969 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5970 {
5971 struct remote_state *rs = get_remote_state ();
5972
5973 /* When connected in non-stop mode, the core resumes threads
5974 individually. Resuming remote threads directly in target_resume
5975 would thus result in sending one packet per thread. Instead, to
5976 minimize roundtrip latency, here we just store the resume
5977 request; the actual remote resumption will be done in
5978 target_commit_resume / remote_commit_resume, where we'll be able
5979 to do vCont action coalescing. */
5980 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
5981 {
5982 remote_thread_info *remote_thr;
5983
5984 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5985 remote_thr = get_remote_thread_info (inferior_ptid);
5986 else
5987 remote_thr = get_remote_thread_info (ptid);
5988
5989 remote_thr->last_resume_step = step;
5990 remote_thr->last_resume_sig = siggnal;
5991 return;
5992 }
5993
5994 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5995 (explained in remote-notif.c:handle_notification) so
5996 remote_notif_process is not called. We need find a place where
5997 it is safe to start a 'vNotif' sequence. It is good to do it
5998 before resuming inferior, because inferior was stopped and no RSP
5999 traffic at that moment. */
6000 if (!target_is_non_stop_p ())
6001 remote_notif_process (rs->notif_state, &notif_client_stop);
6002
6003 rs->last_resume_exec_dir = ::execution_direction;
6004
6005 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6006 if (!remote_resume_with_vcont (ptid, step, siggnal))
6007 remote_resume_with_hc (this, ptid, step, siggnal);
6008
6009 /* We are about to start executing the inferior, let's register it
6010 with the event loop. NOTE: this is the one place where all the
6011 execution commands end up. We could alternatively do this in each
6012 of the execution commands in infcmd.c. */
6013 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6014 into infcmd.c in order to allow inferior function calls to work
6015 NOT asynchronously. */
6016 if (target_can_async_p ())
6017 target_async (1);
6018
6019 /* We've just told the target to resume. The remote server will
6020 wait for the inferior to stop, and then send a stop reply. In
6021 the mean time, we can't start another command/query ourselves
6022 because the stub wouldn't be ready to process it. This applies
6023 only to the base all-stop protocol, however. In non-stop (which
6024 only supports vCont), the stub replies with an "OK", and is
6025 immediate able to process further serial input. */
6026 if (!target_is_non_stop_p ())
6027 rs->waiting_for_stop_reply = 1;
6028 }
6029
6030 static void check_pending_events_prevent_wildcard_vcont
6031 (int *may_global_wildcard_vcont);
6032 static int is_pending_fork_parent_thread (struct thread_info *thread);
6033
6034 /* Private per-inferior info for target remote processes. */
6035
6036 struct remote_inferior : public private_inferior
6037 {
6038 /* Whether we can send a wildcard vCont for this process. */
6039 bool may_wildcard_vcont = true;
6040 };
6041
6042 /* Get the remote private inferior data associated to INF. */
6043
6044 static remote_inferior *
6045 get_remote_inferior (inferior *inf)
6046 {
6047 if (inf->priv == NULL)
6048 inf->priv.reset (new remote_inferior);
6049
6050 return static_cast<remote_inferior *> (inf->priv.get ());
6051 }
6052
6053 /* Structure used to track the construction of a vCont packet in the
6054 outgoing packet buffer. This is used to send multiple vCont
6055 packets if we have more actions than would fit a single packet. */
6056
6057 struct vcont_builder
6058 {
6059 /* Pointer to the first action. P points here if no action has been
6060 appended yet. */
6061 char *first_action;
6062
6063 /* Where the next action will be appended. */
6064 char *p;
6065
6066 /* The end of the buffer. Must never write past this. */
6067 char *endp;
6068 };
6069
6070 /* Prepare the outgoing buffer for a new vCont packet. */
6071
6072 static void
6073 vcont_builder_restart (struct vcont_builder *builder)
6074 {
6075 struct remote_state *rs = get_remote_state ();
6076
6077 builder->p = rs->buf;
6078 builder->endp = rs->buf + get_remote_packet_size ();
6079 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
6080 builder->first_action = builder->p;
6081 }
6082
6083 /* If the vCont packet being built has any action, send it to the
6084 remote end. */
6085
6086 static void
6087 vcont_builder_flush (struct vcont_builder *builder)
6088 {
6089 struct remote_state *rs;
6090
6091 if (builder->p == builder->first_action)
6092 return;
6093
6094 rs = get_remote_state ();
6095 putpkt (rs->buf);
6096 getpkt (&rs->buf, &rs->buf_size, 0);
6097 if (strcmp (rs->buf, "OK") != 0)
6098 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6099 }
6100
6101 /* The largest action is range-stepping, with its two addresses. This
6102 is more than sufficient. If a new, bigger action is created, it'll
6103 quickly trigger a failed assertion in append_resumption (and we'll
6104 just bump this). */
6105 #define MAX_ACTION_SIZE 200
6106
6107 /* Append a new vCont action in the outgoing packet being built. If
6108 the action doesn't fit the packet along with previous actions, push
6109 what we've got so far to the remote end and start over a new vCont
6110 packet (with the new action). */
6111
6112 static void
6113 vcont_builder_push_action (struct vcont_builder *builder,
6114 ptid_t ptid, int step, enum gdb_signal siggnal)
6115 {
6116 char buf[MAX_ACTION_SIZE + 1];
6117 char *endp;
6118 size_t rsize;
6119
6120 endp = append_resumption (buf, buf + sizeof (buf),
6121 ptid, step, siggnal);
6122
6123 /* Check whether this new action would fit in the vCont packet along
6124 with previous actions. If not, send what we've got so far and
6125 start a new vCont packet. */
6126 rsize = endp - buf;
6127 if (rsize > builder->endp - builder->p)
6128 {
6129 vcont_builder_flush (builder);
6130 vcont_builder_restart (builder);
6131
6132 /* Should now fit. */
6133 gdb_assert (rsize <= builder->endp - builder->p);
6134 }
6135
6136 memcpy (builder->p, buf, rsize);
6137 builder->p += rsize;
6138 *builder->p = '\0';
6139 }
6140
6141 /* to_commit_resume implementation. */
6142
6143 void
6144 remote_target::commit_resume ()
6145 {
6146 struct inferior *inf;
6147 struct thread_info *tp;
6148 int any_process_wildcard;
6149 int may_global_wildcard_vcont;
6150 struct vcont_builder vcont_builder;
6151
6152 /* If connected in all-stop mode, we'd send the remote resume
6153 request directly from remote_resume. Likewise if
6154 reverse-debugging, as there are no defined vCont actions for
6155 reverse execution. */
6156 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6157 return;
6158
6159 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6160 instead of resuming all threads of each process individually.
6161 However, if any thread of a process must remain halted, we can't
6162 send wildcard resumes and must send one action per thread.
6163
6164 Care must be taken to not resume threads/processes the server
6165 side already told us are stopped, but the core doesn't know about
6166 yet, because the events are still in the vStopped notification
6167 queue. For example:
6168
6169 #1 => vCont s:p1.1;c
6170 #2 <= OK
6171 #3 <= %Stopped T05 p1.1
6172 #4 => vStopped
6173 #5 <= T05 p1.2
6174 #6 => vStopped
6175 #7 <= OK
6176 #8 (infrun handles the stop for p1.1 and continues stepping)
6177 #9 => vCont s:p1.1;c
6178
6179 The last vCont above would resume thread p1.2 by mistake, because
6180 the server has no idea that the event for p1.2 had not been
6181 handled yet.
6182
6183 The server side must similarly ignore resume actions for the
6184 thread that has a pending %Stopped notification (and any other
6185 threads with events pending), until GDB acks the notification
6186 with vStopped. Otherwise, e.g., the following case is
6187 mishandled:
6188
6189 #1 => g (or any other packet)
6190 #2 <= [registers]
6191 #3 <= %Stopped T05 p1.2
6192 #4 => vCont s:p1.1;c
6193 #5 <= OK
6194
6195 Above, the server must not resume thread p1.2. GDB can't know
6196 that p1.2 stopped until it acks the %Stopped notification, and
6197 since from GDB's perspective all threads should be running, it
6198 sends a "c" action.
6199
6200 Finally, special care must also be given to handling fork/vfork
6201 events. A (v)fork event actually tells us that two processes
6202 stopped -- the parent and the child. Until we follow the fork,
6203 we must not resume the child. Therefore, if we have a pending
6204 fork follow, we must not send a global wildcard resume action
6205 (vCont;c). We can still send process-wide wildcards though. */
6206
6207 /* Start by assuming a global wildcard (vCont;c) is possible. */
6208 may_global_wildcard_vcont = 1;
6209
6210 /* And assume every process is individually wildcard-able too. */
6211 ALL_NON_EXITED_INFERIORS (inf)
6212 {
6213 remote_inferior *priv = get_remote_inferior (inf);
6214
6215 priv->may_wildcard_vcont = true;
6216 }
6217
6218 /* Check for any pending events (not reported or processed yet) and
6219 disable process and global wildcard resumes appropriately. */
6220 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6221
6222 ALL_NON_EXITED_THREADS (tp)
6223 {
6224 /* If a thread of a process is not meant to be resumed, then we
6225 can't wildcard that process. */
6226 if (!tp->executing)
6227 {
6228 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6229
6230 /* And if we can't wildcard a process, we can't wildcard
6231 everything either. */
6232 may_global_wildcard_vcont = 0;
6233 continue;
6234 }
6235
6236 /* If a thread is the parent of an unfollowed fork, then we
6237 can't do a global wildcard, as that would resume the fork
6238 child. */
6239 if (is_pending_fork_parent_thread (tp))
6240 may_global_wildcard_vcont = 0;
6241 }
6242
6243 /* Now let's build the vCont packet(s). Actions must be appended
6244 from narrower to wider scopes (thread -> process -> global). If
6245 we end up with too many actions for a single packet vcont_builder
6246 flushes the current vCont packet to the remote side and starts a
6247 new one. */
6248 vcont_builder_restart (&vcont_builder);
6249
6250 /* Threads first. */
6251 ALL_NON_EXITED_THREADS (tp)
6252 {
6253 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6254
6255 if (!tp->executing || remote_thr->vcont_resumed)
6256 continue;
6257
6258 gdb_assert (!thread_is_in_step_over_chain (tp));
6259
6260 if (!remote_thr->last_resume_step
6261 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6262 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6263 {
6264 /* We'll send a wildcard resume instead. */
6265 remote_thr->vcont_resumed = 1;
6266 continue;
6267 }
6268
6269 vcont_builder_push_action (&vcont_builder, tp->ptid,
6270 remote_thr->last_resume_step,
6271 remote_thr->last_resume_sig);
6272 remote_thr->vcont_resumed = 1;
6273 }
6274
6275 /* Now check whether we can send any process-wide wildcard. This is
6276 to avoid sending a global wildcard in the case nothing is
6277 supposed to be resumed. */
6278 any_process_wildcard = 0;
6279
6280 ALL_NON_EXITED_INFERIORS (inf)
6281 {
6282 if (get_remote_inferior (inf)->may_wildcard_vcont)
6283 {
6284 any_process_wildcard = 1;
6285 break;
6286 }
6287 }
6288
6289 if (any_process_wildcard)
6290 {
6291 /* If all processes are wildcard-able, then send a single "c"
6292 action, otherwise, send an "all (-1) threads of process"
6293 continue action for each running process, if any. */
6294 if (may_global_wildcard_vcont)
6295 {
6296 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6297 0, GDB_SIGNAL_0);
6298 }
6299 else
6300 {
6301 ALL_NON_EXITED_INFERIORS (inf)
6302 {
6303 if (get_remote_inferior (inf)->may_wildcard_vcont)
6304 {
6305 vcont_builder_push_action (&vcont_builder,
6306 pid_to_ptid (inf->pid),
6307 0, GDB_SIGNAL_0);
6308 }
6309 }
6310 }
6311 }
6312
6313 vcont_builder_flush (&vcont_builder);
6314 }
6315
6316 \f
6317
6318 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6319 thread, all threads of a remote process, or all threads of all
6320 processes. */
6321
6322 static void
6323 remote_stop_ns (ptid_t ptid)
6324 {
6325 struct remote_state *rs = get_remote_state ();
6326 char *p = rs->buf;
6327 char *endp = rs->buf + get_remote_packet_size ();
6328
6329 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6330 remote_vcont_probe (rs);
6331
6332 if (!rs->supports_vCont.t)
6333 error (_("Remote server does not support stopping threads"));
6334
6335 if (ptid_equal (ptid, minus_one_ptid)
6336 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6337 p += xsnprintf (p, endp - p, "vCont;t");
6338 else
6339 {
6340 ptid_t nptid;
6341
6342 p += xsnprintf (p, endp - p, "vCont;t:");
6343
6344 if (ptid_is_pid (ptid))
6345 /* All (-1) threads of process. */
6346 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6347 else
6348 {
6349 /* Small optimization: if we already have a stop reply for
6350 this thread, no use in telling the stub we want this
6351 stopped. */
6352 if (peek_stop_reply (ptid))
6353 return;
6354
6355 nptid = ptid;
6356 }
6357
6358 write_ptid (p, endp, nptid);
6359 }
6360
6361 /* In non-stop, we get an immediate OK reply. The stop reply will
6362 come in asynchronously by notification. */
6363 putpkt (rs->buf);
6364 getpkt (&rs->buf, &rs->buf_size, 0);
6365 if (strcmp (rs->buf, "OK") != 0)
6366 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6367 }
6368
6369 /* All-stop version of target_interrupt. Sends a break or a ^C to
6370 interrupt the remote target. It is undefined which thread of which
6371 process reports the interrupt. */
6372
6373 static void
6374 remote_interrupt_as (void)
6375 {
6376 struct remote_state *rs = get_remote_state ();
6377
6378 rs->ctrlc_pending_p = 1;
6379
6380 /* If the inferior is stopped already, but the core didn't know
6381 about it yet, just ignore the request. The cached wait status
6382 will be collected in remote_wait. */
6383 if (rs->cached_wait_status)
6384 return;
6385
6386 /* Send interrupt_sequence to remote target. */
6387 send_interrupt_sequence ();
6388 }
6389
6390 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6391 the remote target. It is undefined which thread of which process
6392 reports the interrupt. Throws an error if the packet is not
6393 supported by the server. */
6394
6395 static void
6396 remote_interrupt_ns (void)
6397 {
6398 struct remote_state *rs = get_remote_state ();
6399 char *p = rs->buf;
6400 char *endp = rs->buf + get_remote_packet_size ();
6401
6402 xsnprintf (p, endp - p, "vCtrlC");
6403
6404 /* In non-stop, we get an immediate OK reply. The stop reply will
6405 come in asynchronously by notification. */
6406 putpkt (rs->buf);
6407 getpkt (&rs->buf, &rs->buf_size, 0);
6408
6409 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6410 {
6411 case PACKET_OK:
6412 break;
6413 case PACKET_UNKNOWN:
6414 error (_("No support for interrupting the remote target."));
6415 case PACKET_ERROR:
6416 error (_("Interrupting target failed: %s"), rs->buf);
6417 }
6418 }
6419
6420 /* Implement the to_stop function for the remote targets. */
6421
6422 void
6423 remote_target::stop (ptid_t ptid)
6424 {
6425 if (remote_debug)
6426 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6427
6428 if (target_is_non_stop_p ())
6429 remote_stop_ns (ptid);
6430 else
6431 {
6432 /* We don't currently have a way to transparently pause the
6433 remote target in all-stop mode. Interrupt it instead. */
6434 remote_interrupt_as ();
6435 }
6436 }
6437
6438 /* Implement the to_interrupt function for the remote targets. */
6439
6440 void
6441 remote_target::interrupt ()
6442 {
6443 if (remote_debug)
6444 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6445
6446 if (target_is_non_stop_p ())
6447 remote_interrupt_ns ();
6448 else
6449 remote_interrupt_as ();
6450 }
6451
6452 /* Implement the to_pass_ctrlc function for the remote targets. */
6453
6454 void
6455 remote_target::pass_ctrlc ()
6456 {
6457 struct remote_state *rs = get_remote_state ();
6458
6459 if (remote_debug)
6460 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6461
6462 /* If we're starting up, we're not fully synced yet. Quit
6463 immediately. */
6464 if (rs->starting_up)
6465 quit ();
6466 /* If ^C has already been sent once, offer to disconnect. */
6467 else if (rs->ctrlc_pending_p)
6468 interrupt_query ();
6469 else
6470 target_interrupt ();
6471 }
6472
6473 /* Ask the user what to do when an interrupt is received. */
6474
6475 static void
6476 interrupt_query (void)
6477 {
6478 struct remote_state *rs = get_remote_state ();
6479
6480 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6481 {
6482 if (query (_("The target is not responding to interrupt requests.\n"
6483 "Stop debugging it? ")))
6484 {
6485 remote_unpush_target ();
6486 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6487 }
6488 }
6489 else
6490 {
6491 if (query (_("Interrupted while waiting for the program.\n"
6492 "Give up waiting? ")))
6493 quit ();
6494 }
6495 }
6496
6497 /* Enable/disable target terminal ownership. Most targets can use
6498 terminal groups to control terminal ownership. Remote targets are
6499 different in that explicit transfer of ownership to/from GDB/target
6500 is required. */
6501
6502 void
6503 remote_target::terminal_inferior ()
6504 {
6505 /* NOTE: At this point we could also register our selves as the
6506 recipient of all input. Any characters typed could then be
6507 passed on down to the target. */
6508 }
6509
6510 void
6511 remote_target::terminal_ours ()
6512 {
6513 }
6514
6515 static void
6516 remote_console_output (char *msg)
6517 {
6518 char *p;
6519
6520 for (p = msg; p[0] && p[1]; p += 2)
6521 {
6522 char tb[2];
6523 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6524
6525 tb[0] = c;
6526 tb[1] = 0;
6527 fputs_unfiltered (tb, gdb_stdtarg);
6528 }
6529 gdb_flush (gdb_stdtarg);
6530 }
6531
6532 DEF_VEC_O(cached_reg_t);
6533
6534 typedef struct stop_reply
6535 {
6536 struct notif_event base;
6537
6538 /* The identifier of the thread about this event */
6539 ptid_t ptid;
6540
6541 /* The remote state this event is associated with. When the remote
6542 connection, represented by a remote_state object, is closed,
6543 all the associated stop_reply events should be released. */
6544 struct remote_state *rs;
6545
6546 struct target_waitstatus ws;
6547
6548 /* The architecture associated with the expedited registers. */
6549 gdbarch *arch;
6550
6551 /* Expedited registers. This makes remote debugging a bit more
6552 efficient for those targets that provide critical registers as
6553 part of their normal status mechanism (as another roundtrip to
6554 fetch them is avoided). */
6555 VEC(cached_reg_t) *regcache;
6556
6557 enum target_stop_reason stop_reason;
6558
6559 CORE_ADDR watch_data_address;
6560
6561 int core;
6562 } *stop_reply_p;
6563
6564 DECLARE_QUEUE_P (stop_reply_p);
6565 DEFINE_QUEUE_P (stop_reply_p);
6566 /* The list of already fetched and acknowledged stop events. This
6567 queue is used for notification Stop, and other notifications
6568 don't need queue for their events, because the notification events
6569 of Stop can't be consumed immediately, so that events should be
6570 queued first, and be consumed by remote_wait_{ns,as} one per
6571 time. Other notifications can consume their events immediately,
6572 so queue is not needed for them. */
6573 static QUEUE (stop_reply_p) *stop_reply_queue;
6574
6575 static void
6576 stop_reply_xfree (struct stop_reply *r)
6577 {
6578 notif_event_xfree ((struct notif_event *) r);
6579 }
6580
6581 /* Return the length of the stop reply queue. */
6582
6583 static int
6584 stop_reply_queue_length (void)
6585 {
6586 return QUEUE_length (stop_reply_p, stop_reply_queue);
6587 }
6588
6589 static void
6590 remote_notif_stop_parse (struct notif_client *self, char *buf,
6591 struct notif_event *event)
6592 {
6593 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6594 }
6595
6596 static void
6597 remote_notif_stop_ack (struct notif_client *self, char *buf,
6598 struct notif_event *event)
6599 {
6600 struct stop_reply *stop_reply = (struct stop_reply *) event;
6601
6602 /* acknowledge */
6603 putpkt (self->ack_command);
6604
6605 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6606 /* We got an unknown stop reply. */
6607 error (_("Unknown stop reply"));
6608
6609 push_stop_reply (stop_reply);
6610 }
6611
6612 static int
6613 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6614 {
6615 /* We can't get pending events in remote_notif_process for
6616 notification stop, and we have to do this in remote_wait_ns
6617 instead. If we fetch all queued events from stub, remote stub
6618 may exit and we have no chance to process them back in
6619 remote_wait_ns. */
6620 mark_async_event_handler (remote_async_inferior_event_token);
6621 return 0;
6622 }
6623
6624 static void
6625 stop_reply_dtr (struct notif_event *event)
6626 {
6627 struct stop_reply *r = (struct stop_reply *) event;
6628 cached_reg_t *reg;
6629 int ix;
6630
6631 for (ix = 0;
6632 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6633 ix++)
6634 xfree (reg->data);
6635
6636 VEC_free (cached_reg_t, r->regcache);
6637 }
6638
6639 static struct notif_event *
6640 remote_notif_stop_alloc_reply (void)
6641 {
6642 /* We cast to a pointer to the "base class". */
6643 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6644
6645 r->dtr = stop_reply_dtr;
6646
6647 return r;
6648 }
6649
6650 /* A client of notification Stop. */
6651
6652 struct notif_client notif_client_stop =
6653 {
6654 "Stop",
6655 "vStopped",
6656 remote_notif_stop_parse,
6657 remote_notif_stop_ack,
6658 remote_notif_stop_can_get_pending_events,
6659 remote_notif_stop_alloc_reply,
6660 REMOTE_NOTIF_STOP,
6661 };
6662
6663 /* A parameter to pass data in and out. */
6664
6665 struct queue_iter_param
6666 {
6667 void *input;
6668 struct stop_reply *output;
6669 };
6670
6671 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6672 the pid of the process that owns the threads we want to check, or
6673 -1 if we want to check all threads. */
6674
6675 static int
6676 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6677 ptid_t thread_ptid)
6678 {
6679 if (ws->kind == TARGET_WAITKIND_FORKED
6680 || ws->kind == TARGET_WAITKIND_VFORKED)
6681 {
6682 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6683 return 1;
6684 }
6685
6686 return 0;
6687 }
6688
6689 /* Return the thread's pending status used to determine whether the
6690 thread is a fork parent stopped at a fork event. */
6691
6692 static struct target_waitstatus *
6693 thread_pending_fork_status (struct thread_info *thread)
6694 {
6695 if (thread->suspend.waitstatus_pending_p)
6696 return &thread->suspend.waitstatus;
6697 else
6698 return &thread->pending_follow;
6699 }
6700
6701 /* Determine if THREAD is a pending fork parent thread. */
6702
6703 static int
6704 is_pending_fork_parent_thread (struct thread_info *thread)
6705 {
6706 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6707 int pid = -1;
6708
6709 return is_pending_fork_parent (ws, pid, thread->ptid);
6710 }
6711
6712 /* Check whether EVENT is a fork event, and if it is, remove the
6713 fork child from the context list passed in DATA. */
6714
6715 static int
6716 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6717 QUEUE_ITER (stop_reply_p) *iter,
6718 stop_reply_p event,
6719 void *data)
6720 {
6721 struct queue_iter_param *param = (struct queue_iter_param *) data;
6722 struct threads_listing_context *context
6723 = (struct threads_listing_context *) param->input;
6724
6725 if (event->ws.kind == TARGET_WAITKIND_FORKED
6726 || event->ws.kind == TARGET_WAITKIND_VFORKED
6727 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6728 context->remove_thread (event->ws.value.related_pid);
6729
6730 return 1;
6731 }
6732
6733 /* If CONTEXT contains any fork child threads that have not been
6734 reported yet, remove them from the CONTEXT list. If such a
6735 thread exists it is because we are stopped at a fork catchpoint
6736 and have not yet called follow_fork, which will set up the
6737 host-side data structures for the new process. */
6738
6739 static void
6740 remove_new_fork_children (struct threads_listing_context *context)
6741 {
6742 struct thread_info * thread;
6743 int pid = -1;
6744 struct notif_client *notif = &notif_client_stop;
6745 struct queue_iter_param param;
6746
6747 /* For any threads stopped at a fork event, remove the corresponding
6748 fork child threads from the CONTEXT list. */
6749 ALL_NON_EXITED_THREADS (thread)
6750 {
6751 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6752
6753 if (is_pending_fork_parent (ws, pid, thread->ptid))
6754 context->remove_thread (ws->value.related_pid);
6755 }
6756
6757 /* Check for any pending fork events (not reported or processed yet)
6758 in process PID and remove those fork child threads from the
6759 CONTEXT list as well. */
6760 remote_notif_get_pending_events (notif);
6761 param.input = context;
6762 param.output = NULL;
6763 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6764 remove_child_of_pending_fork, &param);
6765 }
6766
6767 /* Check whether EVENT would prevent a global or process wildcard
6768 vCont action. */
6769
6770 static int
6771 check_pending_event_prevents_wildcard_vcont_callback
6772 (QUEUE (stop_reply_p) *q,
6773 QUEUE_ITER (stop_reply_p) *iter,
6774 stop_reply_p event,
6775 void *data)
6776 {
6777 struct inferior *inf;
6778 int *may_global_wildcard_vcont = (int *) data;
6779
6780 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6781 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6782 return 1;
6783
6784 if (event->ws.kind == TARGET_WAITKIND_FORKED
6785 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6786 *may_global_wildcard_vcont = 0;
6787
6788 inf = find_inferior_ptid (event->ptid);
6789
6790 /* This may be the first time we heard about this process.
6791 Regardless, we must not do a global wildcard resume, otherwise
6792 we'd resume this process too. */
6793 *may_global_wildcard_vcont = 0;
6794 if (inf != NULL)
6795 get_remote_inferior (inf)->may_wildcard_vcont = false;
6796
6797 return 1;
6798 }
6799
6800 /* Check whether any event pending in the vStopped queue would prevent
6801 a global or process wildcard vCont action. Clear
6802 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6803 and clear the event inferior's may_wildcard_vcont flag if we can't
6804 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6805
6806 static void
6807 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6808 {
6809 struct notif_client *notif = &notif_client_stop;
6810
6811 remote_notif_get_pending_events (notif);
6812 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6813 check_pending_event_prevents_wildcard_vcont_callback,
6814 may_global_wildcard);
6815 }
6816
6817 /* Remove stop replies in the queue if its pid is equal to the given
6818 inferior's pid. */
6819
6820 static int
6821 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6822 QUEUE_ITER (stop_reply_p) *iter,
6823 stop_reply_p event,
6824 void *data)
6825 {
6826 struct queue_iter_param *param = (struct queue_iter_param *) data;
6827 struct inferior *inf = (struct inferior *) param->input;
6828
6829 if (ptid_get_pid (event->ptid) == inf->pid)
6830 {
6831 stop_reply_xfree (event);
6832 QUEUE_remove_elem (stop_reply_p, q, iter);
6833 }
6834
6835 return 1;
6836 }
6837
6838 /* Discard all pending stop replies of inferior INF. */
6839
6840 static void
6841 discard_pending_stop_replies (struct inferior *inf)
6842 {
6843 struct queue_iter_param param;
6844 struct stop_reply *reply;
6845 struct remote_state *rs = get_remote_state ();
6846 struct remote_notif_state *rns = rs->notif_state;
6847
6848 /* This function can be notified when an inferior exists. When the
6849 target is not remote, the notification state is NULL. */
6850 if (rs->remote_desc == NULL)
6851 return;
6852
6853 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6854
6855 /* Discard the in-flight notification. */
6856 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6857 {
6858 stop_reply_xfree (reply);
6859 rns->pending_event[notif_client_stop.id] = NULL;
6860 }
6861
6862 param.input = inf;
6863 param.output = NULL;
6864 /* Discard the stop replies we have already pulled with
6865 vStopped. */
6866 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6867 remove_stop_reply_for_inferior, &param);
6868 }
6869
6870 /* If its remote state is equal to the given remote state,
6871 remove EVENT from the stop reply queue. */
6872
6873 static int
6874 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6875 QUEUE_ITER (stop_reply_p) *iter,
6876 stop_reply_p event,
6877 void *data)
6878 {
6879 struct queue_iter_param *param = (struct queue_iter_param *) data;
6880 struct remote_state *rs = (struct remote_state *) param->input;
6881
6882 if (event->rs == rs)
6883 {
6884 stop_reply_xfree (event);
6885 QUEUE_remove_elem (stop_reply_p, q, iter);
6886 }
6887
6888 return 1;
6889 }
6890
6891 /* Discard the stop replies for RS in stop_reply_queue. */
6892
6893 static void
6894 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6895 {
6896 struct queue_iter_param param;
6897
6898 param.input = rs;
6899 param.output = NULL;
6900 /* Discard the stop replies we have already pulled with
6901 vStopped. */
6902 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6903 remove_stop_reply_of_remote_state, &param);
6904 }
6905
6906 /* A parameter to pass data in and out. */
6907
6908 static int
6909 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6910 QUEUE_ITER (stop_reply_p) *iter,
6911 stop_reply_p event,
6912 void *data)
6913 {
6914 struct queue_iter_param *param = (struct queue_iter_param *) data;
6915 ptid_t *ptid = (ptid_t *) param->input;
6916
6917 if (ptid_match (event->ptid, *ptid))
6918 {
6919 param->output = event;
6920 QUEUE_remove_elem (stop_reply_p, q, iter);
6921 return 0;
6922 }
6923
6924 return 1;
6925 }
6926
6927 /* Remove the first reply in 'stop_reply_queue' which matches
6928 PTID. */
6929
6930 static struct stop_reply *
6931 remote_notif_remove_queued_reply (ptid_t ptid)
6932 {
6933 struct queue_iter_param param;
6934
6935 param.input = &ptid;
6936 param.output = NULL;
6937
6938 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6939 remote_notif_remove_once_on_match, &param);
6940 if (notif_debug)
6941 fprintf_unfiltered (gdb_stdlog,
6942 "notif: discard queued event: 'Stop' in %s\n",
6943 target_pid_to_str (ptid));
6944
6945 return param.output;
6946 }
6947
6948 /* Look for a queued stop reply belonging to PTID. If one is found,
6949 remove it from the queue, and return it. Returns NULL if none is
6950 found. If there are still queued events left to process, tell the
6951 event loop to get back to target_wait soon. */
6952
6953 static struct stop_reply *
6954 queued_stop_reply (ptid_t ptid)
6955 {
6956 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6957
6958 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6959 /* There's still at least an event left. */
6960 mark_async_event_handler (remote_async_inferior_event_token);
6961
6962 return r;
6963 }
6964
6965 /* Push a fully parsed stop reply in the stop reply queue. Since we
6966 know that we now have at least one queued event left to pass to the
6967 core side, tell the event loop to get back to target_wait soon. */
6968
6969 static void
6970 push_stop_reply (struct stop_reply *new_event)
6971 {
6972 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6973
6974 if (notif_debug)
6975 fprintf_unfiltered (gdb_stdlog,
6976 "notif: push 'Stop' %s to queue %d\n",
6977 target_pid_to_str (new_event->ptid),
6978 QUEUE_length (stop_reply_p,
6979 stop_reply_queue));
6980
6981 mark_async_event_handler (remote_async_inferior_event_token);
6982 }
6983
6984 static int
6985 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6986 QUEUE_ITER (stop_reply_p) *iter,
6987 struct stop_reply *event,
6988 void *data)
6989 {
6990 ptid_t *ptid = (ptid_t *) data;
6991
6992 return !(ptid_equal (*ptid, event->ptid)
6993 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6994 }
6995
6996 /* Returns true if we have a stop reply for PTID. */
6997
6998 static int
6999 peek_stop_reply (ptid_t ptid)
7000 {
7001 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
7002 stop_reply_match_ptid_and_ws, &ptid);
7003 }
7004
7005 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7006 starting with P and ending with PEND matches PREFIX. */
7007
7008 static int
7009 strprefix (const char *p, const char *pend, const char *prefix)
7010 {
7011 for ( ; p < pend; p++, prefix++)
7012 if (*p != *prefix)
7013 return 0;
7014 return *prefix == '\0';
7015 }
7016
7017 /* Parse the stop reply in BUF. Either the function succeeds, and the
7018 result is stored in EVENT, or throws an error. */
7019
7020 static void
7021 remote_parse_stop_reply (char *buf, struct stop_reply *event)
7022 {
7023 remote_arch_state *rsa = NULL;
7024 ULONGEST addr;
7025 const char *p;
7026 int skipregs = 0;
7027
7028 event->ptid = null_ptid;
7029 event->rs = get_remote_state ();
7030 event->ws.kind = TARGET_WAITKIND_IGNORE;
7031 event->ws.value.integer = 0;
7032 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7033 event->regcache = NULL;
7034 event->core = -1;
7035
7036 switch (buf[0])
7037 {
7038 case 'T': /* Status with PC, SP, FP, ... */
7039 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7040 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7041 ss = signal number
7042 n... = register number
7043 r... = register contents
7044 */
7045
7046 p = &buf[3]; /* after Txx */
7047 while (*p)
7048 {
7049 const char *p1;
7050 int fieldsize;
7051
7052 p1 = strchr (p, ':');
7053 if (p1 == NULL)
7054 error (_("Malformed packet(a) (missing colon): %s\n\
7055 Packet: '%s'\n"),
7056 p, buf);
7057 if (p == p1)
7058 error (_("Malformed packet(a) (missing register number): %s\n\
7059 Packet: '%s'\n"),
7060 p, buf);
7061
7062 /* Some "registers" are actually extended stop information.
7063 Note if you're adding a new entry here: GDB 7.9 and
7064 earlier assume that all register "numbers" that start
7065 with an hex digit are real register numbers. Make sure
7066 the server only sends such a packet if it knows the
7067 client understands it. */
7068
7069 if (strprefix (p, p1, "thread"))
7070 event->ptid = read_ptid (++p1, &p);
7071 else if (strprefix (p, p1, "syscall_entry"))
7072 {
7073 ULONGEST sysno;
7074
7075 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7076 p = unpack_varlen_hex (++p1, &sysno);
7077 event->ws.value.syscall_number = (int) sysno;
7078 }
7079 else if (strprefix (p, p1, "syscall_return"))
7080 {
7081 ULONGEST sysno;
7082
7083 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7084 p = unpack_varlen_hex (++p1, &sysno);
7085 event->ws.value.syscall_number = (int) sysno;
7086 }
7087 else if (strprefix (p, p1, "watch")
7088 || strprefix (p, p1, "rwatch")
7089 || strprefix (p, p1, "awatch"))
7090 {
7091 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7092 p = unpack_varlen_hex (++p1, &addr);
7093 event->watch_data_address = (CORE_ADDR) addr;
7094 }
7095 else if (strprefix (p, p1, "swbreak"))
7096 {
7097 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7098
7099 /* Make sure the stub doesn't forget to indicate support
7100 with qSupported. */
7101 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7102 error (_("Unexpected swbreak stop reason"));
7103
7104 /* The value part is documented as "must be empty",
7105 though we ignore it, in case we ever decide to make
7106 use of it in a backward compatible way. */
7107 p = strchrnul (p1 + 1, ';');
7108 }
7109 else if (strprefix (p, p1, "hwbreak"))
7110 {
7111 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7112
7113 /* Make sure the stub doesn't forget to indicate support
7114 with qSupported. */
7115 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7116 error (_("Unexpected hwbreak stop reason"));
7117
7118 /* See above. */
7119 p = strchrnul (p1 + 1, ';');
7120 }
7121 else if (strprefix (p, p1, "library"))
7122 {
7123 event->ws.kind = TARGET_WAITKIND_LOADED;
7124 p = strchrnul (p1 + 1, ';');
7125 }
7126 else if (strprefix (p, p1, "replaylog"))
7127 {
7128 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7129 /* p1 will indicate "begin" or "end", but it makes
7130 no difference for now, so ignore it. */
7131 p = strchrnul (p1 + 1, ';');
7132 }
7133 else if (strprefix (p, p1, "core"))
7134 {
7135 ULONGEST c;
7136
7137 p = unpack_varlen_hex (++p1, &c);
7138 event->core = c;
7139 }
7140 else if (strprefix (p, p1, "fork"))
7141 {
7142 event->ws.value.related_pid = read_ptid (++p1, &p);
7143 event->ws.kind = TARGET_WAITKIND_FORKED;
7144 }
7145 else if (strprefix (p, p1, "vfork"))
7146 {
7147 event->ws.value.related_pid = read_ptid (++p1, &p);
7148 event->ws.kind = TARGET_WAITKIND_VFORKED;
7149 }
7150 else if (strprefix (p, p1, "vforkdone"))
7151 {
7152 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7153 p = strchrnul (p1 + 1, ';');
7154 }
7155 else if (strprefix (p, p1, "exec"))
7156 {
7157 ULONGEST ignored;
7158 char pathname[PATH_MAX];
7159 int pathlen;
7160
7161 /* Determine the length of the execd pathname. */
7162 p = unpack_varlen_hex (++p1, &ignored);
7163 pathlen = (p - p1) / 2;
7164
7165 /* Save the pathname for event reporting and for
7166 the next run command. */
7167 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7168 pathname[pathlen] = '\0';
7169
7170 /* This is freed during event handling. */
7171 event->ws.value.execd_pathname = xstrdup (pathname);
7172 event->ws.kind = TARGET_WAITKIND_EXECD;
7173
7174 /* Skip the registers included in this packet, since
7175 they may be for an architecture different from the
7176 one used by the original program. */
7177 skipregs = 1;
7178 }
7179 else if (strprefix (p, p1, "create"))
7180 {
7181 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7182 p = strchrnul (p1 + 1, ';');
7183 }
7184 else
7185 {
7186 ULONGEST pnum;
7187 const char *p_temp;
7188
7189 if (skipregs)
7190 {
7191 p = strchrnul (p1 + 1, ';');
7192 p++;
7193 continue;
7194 }
7195
7196 /* Maybe a real ``P'' register number. */
7197 p_temp = unpack_varlen_hex (p, &pnum);
7198 /* If the first invalid character is the colon, we got a
7199 register number. Otherwise, it's an unknown stop
7200 reason. */
7201 if (p_temp == p1)
7202 {
7203 /* If we haven't parsed the event's thread yet, find
7204 it now, in order to find the architecture of the
7205 reported expedited registers. */
7206 if (event->ptid == null_ptid)
7207 {
7208 const char *thr = strstr (p1 + 1, ";thread:");
7209 if (thr != NULL)
7210 event->ptid = read_ptid (thr + strlen (";thread:"),
7211 NULL);
7212 else
7213 {
7214 /* Either the current thread hasn't changed,
7215 or the inferior is not multi-threaded.
7216 The event must be for the thread we last
7217 set as (or learned as being) current. */
7218 event->ptid = event->rs->general_thread;
7219 }
7220 }
7221
7222 if (rsa == NULL)
7223 {
7224 inferior *inf = (event->ptid == null_ptid
7225 ? NULL
7226 : find_inferior_ptid (event->ptid));
7227 /* If this is the first time we learn anything
7228 about this process, skip the registers
7229 included in this packet, since we don't yet
7230 know which architecture to use to parse them.
7231 We'll determine the architecture later when
7232 we process the stop reply and retrieve the
7233 target description, via
7234 remote_notice_new_inferior ->
7235 post_create_inferior. */
7236 if (inf == NULL)
7237 {
7238 p = strchrnul (p1 + 1, ';');
7239 p++;
7240 continue;
7241 }
7242
7243 event->arch = inf->gdbarch;
7244 rsa = get_remote_arch_state (event->arch);
7245 }
7246
7247 packet_reg *reg
7248 = packet_reg_from_pnum (event->arch, rsa, pnum);
7249 cached_reg_t cached_reg;
7250
7251 if (reg == NULL)
7252 error (_("Remote sent bad register number %s: %s\n\
7253 Packet: '%s'\n"),
7254 hex_string (pnum), p, buf);
7255
7256 cached_reg.num = reg->regnum;
7257 cached_reg.data = (gdb_byte *)
7258 xmalloc (register_size (event->arch, reg->regnum));
7259
7260 p = p1 + 1;
7261 fieldsize = hex2bin (p, cached_reg.data,
7262 register_size (event->arch, reg->regnum));
7263 p += 2 * fieldsize;
7264 if (fieldsize < register_size (event->arch, reg->regnum))
7265 warning (_("Remote reply is too short: %s"), buf);
7266
7267 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7268 }
7269 else
7270 {
7271 /* Not a number. Silently skip unknown optional
7272 info. */
7273 p = strchrnul (p1 + 1, ';');
7274 }
7275 }
7276
7277 if (*p != ';')
7278 error (_("Remote register badly formatted: %s\nhere: %s"),
7279 buf, p);
7280 ++p;
7281 }
7282
7283 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7284 break;
7285
7286 /* fall through */
7287 case 'S': /* Old style status, just signal only. */
7288 {
7289 int sig;
7290
7291 event->ws.kind = TARGET_WAITKIND_STOPPED;
7292 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7293 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7294 event->ws.value.sig = (enum gdb_signal) sig;
7295 else
7296 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7297 }
7298 break;
7299 case 'w': /* Thread exited. */
7300 {
7301 const char *p;
7302 ULONGEST value;
7303
7304 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7305 p = unpack_varlen_hex (&buf[1], &value);
7306 event->ws.value.integer = value;
7307 if (*p != ';')
7308 error (_("stop reply packet badly formatted: %s"), buf);
7309 event->ptid = read_ptid (++p, NULL);
7310 break;
7311 }
7312 case 'W': /* Target exited. */
7313 case 'X':
7314 {
7315 const char *p;
7316 int pid;
7317 ULONGEST value;
7318
7319 /* GDB used to accept only 2 hex chars here. Stubs should
7320 only send more if they detect GDB supports multi-process
7321 support. */
7322 p = unpack_varlen_hex (&buf[1], &value);
7323
7324 if (buf[0] == 'W')
7325 {
7326 /* The remote process exited. */
7327 event->ws.kind = TARGET_WAITKIND_EXITED;
7328 event->ws.value.integer = value;
7329 }
7330 else
7331 {
7332 /* The remote process exited with a signal. */
7333 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7334 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7335 event->ws.value.sig = (enum gdb_signal) value;
7336 else
7337 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7338 }
7339
7340 /* If no process is specified, assume inferior_ptid. */
7341 pid = ptid_get_pid (inferior_ptid);
7342 if (*p == '\0')
7343 ;
7344 else if (*p == ';')
7345 {
7346 p++;
7347
7348 if (*p == '\0')
7349 ;
7350 else if (startswith (p, "process:"))
7351 {
7352 ULONGEST upid;
7353
7354 p += sizeof ("process:") - 1;
7355 unpack_varlen_hex (p, &upid);
7356 pid = upid;
7357 }
7358 else
7359 error (_("unknown stop reply packet: %s"), buf);
7360 }
7361 else
7362 error (_("unknown stop reply packet: %s"), buf);
7363 event->ptid = pid_to_ptid (pid);
7364 }
7365 break;
7366 case 'N':
7367 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7368 event->ptid = minus_one_ptid;
7369 break;
7370 }
7371
7372 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7373 error (_("No process or thread specified in stop reply: %s"), buf);
7374 }
7375
7376 /* When the stub wants to tell GDB about a new notification reply, it
7377 sends a notification (%Stop, for example). Those can come it at
7378 any time, hence, we have to make sure that any pending
7379 putpkt/getpkt sequence we're making is finished, before querying
7380 the stub for more events with the corresponding ack command
7381 (vStopped, for example). E.g., if we started a vStopped sequence
7382 immediately upon receiving the notification, something like this
7383 could happen:
7384
7385 1.1) --> Hg 1
7386 1.2) <-- OK
7387 1.3) --> g
7388 1.4) <-- %Stop
7389 1.5) --> vStopped
7390 1.6) <-- (registers reply to step #1.3)
7391
7392 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7393 query.
7394
7395 To solve this, whenever we parse a %Stop notification successfully,
7396 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7397 doing whatever we were doing:
7398
7399 2.1) --> Hg 1
7400 2.2) <-- OK
7401 2.3) --> g
7402 2.4) <-- %Stop
7403 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7404 2.5) <-- (registers reply to step #2.3)
7405
7406 Eventualy after step #2.5, we return to the event loop, which
7407 notices there's an event on the
7408 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7409 associated callback --- the function below. At this point, we're
7410 always safe to start a vStopped sequence. :
7411
7412 2.6) --> vStopped
7413 2.7) <-- T05 thread:2
7414 2.8) --> vStopped
7415 2.9) --> OK
7416 */
7417
7418 void
7419 remote_notif_get_pending_events (struct notif_client *nc)
7420 {
7421 struct remote_state *rs = get_remote_state ();
7422
7423 if (rs->notif_state->pending_event[nc->id] != NULL)
7424 {
7425 if (notif_debug)
7426 fprintf_unfiltered (gdb_stdlog,
7427 "notif: process: '%s' ack pending event\n",
7428 nc->name);
7429
7430 /* acknowledge */
7431 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7432 rs->notif_state->pending_event[nc->id] = NULL;
7433
7434 while (1)
7435 {
7436 getpkt (&rs->buf, &rs->buf_size, 0);
7437 if (strcmp (rs->buf, "OK") == 0)
7438 break;
7439 else
7440 remote_notif_ack (nc, rs->buf);
7441 }
7442 }
7443 else
7444 {
7445 if (notif_debug)
7446 fprintf_unfiltered (gdb_stdlog,
7447 "notif: process: '%s' no pending reply\n",
7448 nc->name);
7449 }
7450 }
7451
7452 /* Called when it is decided that STOP_REPLY holds the info of the
7453 event that is to be returned to the core. This function always
7454 destroys STOP_REPLY. */
7455
7456 static ptid_t
7457 process_stop_reply (struct stop_reply *stop_reply,
7458 struct target_waitstatus *status)
7459 {
7460 ptid_t ptid;
7461
7462 *status = stop_reply->ws;
7463 ptid = stop_reply->ptid;
7464
7465 /* If no thread/process was reported by the stub, assume the current
7466 inferior. */
7467 if (ptid_equal (ptid, null_ptid))
7468 ptid = inferior_ptid;
7469
7470 if (status->kind != TARGET_WAITKIND_EXITED
7471 && status->kind != TARGET_WAITKIND_SIGNALLED
7472 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7473 {
7474 /* Expedited registers. */
7475 if (stop_reply->regcache)
7476 {
7477 struct regcache *regcache
7478 = get_thread_arch_regcache (ptid, stop_reply->arch);
7479 cached_reg_t *reg;
7480 int ix;
7481
7482 for (ix = 0;
7483 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7484 ix++)
7485 {
7486 regcache_raw_supply (regcache, reg->num, reg->data);
7487 xfree (reg->data);
7488 }
7489
7490 VEC_free (cached_reg_t, stop_reply->regcache);
7491 }
7492
7493 remote_notice_new_inferior (ptid, 0);
7494 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7495 remote_thr->core = stop_reply->core;
7496 remote_thr->stop_reason = stop_reply->stop_reason;
7497 remote_thr->watch_data_address = stop_reply->watch_data_address;
7498 remote_thr->vcont_resumed = 0;
7499 }
7500
7501 stop_reply_xfree (stop_reply);
7502 return ptid;
7503 }
7504
7505 /* The non-stop mode version of target_wait. */
7506
7507 static ptid_t
7508 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7509 {
7510 struct remote_state *rs = get_remote_state ();
7511 struct stop_reply *stop_reply;
7512 int ret;
7513 int is_notif = 0;
7514
7515 /* If in non-stop mode, get out of getpkt even if a
7516 notification is received. */
7517
7518 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7519 0 /* forever */, &is_notif);
7520 while (1)
7521 {
7522 if (ret != -1 && !is_notif)
7523 switch (rs->buf[0])
7524 {
7525 case 'E': /* Error of some sort. */
7526 /* We're out of sync with the target now. Did it continue
7527 or not? We can't tell which thread it was in non-stop,
7528 so just ignore this. */
7529 warning (_("Remote failure reply: %s"), rs->buf);
7530 break;
7531 case 'O': /* Console output. */
7532 remote_console_output (rs->buf + 1);
7533 break;
7534 default:
7535 warning (_("Invalid remote reply: %s"), rs->buf);
7536 break;
7537 }
7538
7539 /* Acknowledge a pending stop reply that may have arrived in the
7540 mean time. */
7541 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7542 remote_notif_get_pending_events (&notif_client_stop);
7543
7544 /* If indeed we noticed a stop reply, we're done. */
7545 stop_reply = queued_stop_reply (ptid);
7546 if (stop_reply != NULL)
7547 return process_stop_reply (stop_reply, status);
7548
7549 /* Still no event. If we're just polling for an event, then
7550 return to the event loop. */
7551 if (options & TARGET_WNOHANG)
7552 {
7553 status->kind = TARGET_WAITKIND_IGNORE;
7554 return minus_one_ptid;
7555 }
7556
7557 /* Otherwise do a blocking wait. */
7558 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7559 1 /* forever */, &is_notif);
7560 }
7561 }
7562
7563 /* Wait until the remote machine stops, then return, storing status in
7564 STATUS just as `wait' would. */
7565
7566 static ptid_t
7567 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7568 {
7569 struct remote_state *rs = get_remote_state ();
7570 ptid_t event_ptid = null_ptid;
7571 char *buf;
7572 struct stop_reply *stop_reply;
7573
7574 again:
7575
7576 status->kind = TARGET_WAITKIND_IGNORE;
7577 status->value.integer = 0;
7578
7579 stop_reply = queued_stop_reply (ptid);
7580 if (stop_reply != NULL)
7581 return process_stop_reply (stop_reply, status);
7582
7583 if (rs->cached_wait_status)
7584 /* Use the cached wait status, but only once. */
7585 rs->cached_wait_status = 0;
7586 else
7587 {
7588 int ret;
7589 int is_notif;
7590 int forever = ((options & TARGET_WNOHANG) == 0
7591 && wait_forever_enabled_p);
7592
7593 if (!rs->waiting_for_stop_reply)
7594 {
7595 status->kind = TARGET_WAITKIND_NO_RESUMED;
7596 return minus_one_ptid;
7597 }
7598
7599 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7600 _never_ wait for ever -> test on target_is_async_p().
7601 However, before we do that we need to ensure that the caller
7602 knows how to take the target into/out of async mode. */
7603 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7604 forever, &is_notif);
7605
7606 /* GDB gets a notification. Return to core as this event is
7607 not interesting. */
7608 if (ret != -1 && is_notif)
7609 return minus_one_ptid;
7610
7611 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7612 return minus_one_ptid;
7613 }
7614
7615 buf = rs->buf;
7616
7617 /* Assume that the target has acknowledged Ctrl-C unless we receive
7618 an 'F' or 'O' packet. */
7619 if (buf[0] != 'F' && buf[0] != 'O')
7620 rs->ctrlc_pending_p = 0;
7621
7622 switch (buf[0])
7623 {
7624 case 'E': /* Error of some sort. */
7625 /* We're out of sync with the target now. Did it continue or
7626 not? Not is more likely, so report a stop. */
7627 rs->waiting_for_stop_reply = 0;
7628
7629 warning (_("Remote failure reply: %s"), buf);
7630 status->kind = TARGET_WAITKIND_STOPPED;
7631 status->value.sig = GDB_SIGNAL_0;
7632 break;
7633 case 'F': /* File-I/O request. */
7634 /* GDB may access the inferior memory while handling the File-I/O
7635 request, but we don't want GDB accessing memory while waiting
7636 for a stop reply. See the comments in putpkt_binary. Set
7637 waiting_for_stop_reply to 0 temporarily. */
7638 rs->waiting_for_stop_reply = 0;
7639 remote_fileio_request (buf, rs->ctrlc_pending_p);
7640 rs->ctrlc_pending_p = 0;
7641 /* GDB handled the File-I/O request, and the target is running
7642 again. Keep waiting for events. */
7643 rs->waiting_for_stop_reply = 1;
7644 break;
7645 case 'N': case 'T': case 'S': case 'X': case 'W':
7646 {
7647 struct stop_reply *stop_reply;
7648
7649 /* There is a stop reply to handle. */
7650 rs->waiting_for_stop_reply = 0;
7651
7652 stop_reply
7653 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7654 rs->buf);
7655
7656 event_ptid = process_stop_reply (stop_reply, status);
7657 break;
7658 }
7659 case 'O': /* Console output. */
7660 remote_console_output (buf + 1);
7661 break;
7662 case '\0':
7663 if (rs->last_sent_signal != GDB_SIGNAL_0)
7664 {
7665 /* Zero length reply means that we tried 'S' or 'C' and the
7666 remote system doesn't support it. */
7667 target_terminal::ours_for_output ();
7668 printf_filtered
7669 ("Can't send signals to this remote system. %s not sent.\n",
7670 gdb_signal_to_name (rs->last_sent_signal));
7671 rs->last_sent_signal = GDB_SIGNAL_0;
7672 target_terminal::inferior ();
7673
7674 strcpy (buf, rs->last_sent_step ? "s" : "c");
7675 putpkt (buf);
7676 break;
7677 }
7678 /* else fallthrough */
7679 default:
7680 warning (_("Invalid remote reply: %s"), buf);
7681 break;
7682 }
7683
7684 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7685 return minus_one_ptid;
7686 else if (status->kind == TARGET_WAITKIND_IGNORE)
7687 {
7688 /* Nothing interesting happened. If we're doing a non-blocking
7689 poll, we're done. Otherwise, go back to waiting. */
7690 if (options & TARGET_WNOHANG)
7691 return minus_one_ptid;
7692 else
7693 goto again;
7694 }
7695 else if (status->kind != TARGET_WAITKIND_EXITED
7696 && status->kind != TARGET_WAITKIND_SIGNALLED)
7697 {
7698 if (!ptid_equal (event_ptid, null_ptid))
7699 record_currthread (rs, event_ptid);
7700 else
7701 event_ptid = inferior_ptid;
7702 }
7703 else
7704 /* A process exit. Invalidate our notion of current thread. */
7705 record_currthread (rs, minus_one_ptid);
7706
7707 return event_ptid;
7708 }
7709
7710 /* Wait until the remote machine stops, then return, storing status in
7711 STATUS just as `wait' would. */
7712
7713 ptid_t
7714 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7715 {
7716 ptid_t event_ptid;
7717
7718 if (target_is_non_stop_p ())
7719 event_ptid = remote_wait_ns (ptid, status, options);
7720 else
7721 event_ptid = remote_wait_as (ptid, status, options);
7722
7723 if (target_is_async_p ())
7724 {
7725 /* If there are are events left in the queue tell the event loop
7726 to return here. */
7727 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7728 mark_async_event_handler (remote_async_inferior_event_token);
7729 }
7730
7731 return event_ptid;
7732 }
7733
7734 /* Fetch a single register using a 'p' packet. */
7735
7736 static int
7737 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7738 {
7739 struct gdbarch *gdbarch = regcache->arch ();
7740 struct remote_state *rs = get_remote_state ();
7741 char *buf, *p;
7742 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7743 int i;
7744
7745 if (packet_support (PACKET_p) == PACKET_DISABLE)
7746 return 0;
7747
7748 if (reg->pnum == -1)
7749 return 0;
7750
7751 p = rs->buf;
7752 *p++ = 'p';
7753 p += hexnumstr (p, reg->pnum);
7754 *p++ = '\0';
7755 putpkt (rs->buf);
7756 getpkt (&rs->buf, &rs->buf_size, 0);
7757
7758 buf = rs->buf;
7759
7760 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7761 {
7762 case PACKET_OK:
7763 break;
7764 case PACKET_UNKNOWN:
7765 return 0;
7766 case PACKET_ERROR:
7767 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7768 gdbarch_register_name (regcache->arch (),
7769 reg->regnum),
7770 buf);
7771 }
7772
7773 /* If this register is unfetchable, tell the regcache. */
7774 if (buf[0] == 'x')
7775 {
7776 regcache_raw_supply (regcache, reg->regnum, NULL);
7777 return 1;
7778 }
7779
7780 /* Otherwise, parse and supply the value. */
7781 p = buf;
7782 i = 0;
7783 while (p[0] != 0)
7784 {
7785 if (p[1] == 0)
7786 error (_("fetch_register_using_p: early buf termination"));
7787
7788 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7789 p += 2;
7790 }
7791 regcache_raw_supply (regcache, reg->regnum, regp);
7792 return 1;
7793 }
7794
7795 /* Fetch the registers included in the target's 'g' packet. */
7796
7797 static int
7798 send_g_packet (void)
7799 {
7800 struct remote_state *rs = get_remote_state ();
7801 int buf_len;
7802
7803 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7804 putpkt (rs->buf);
7805 getpkt (&rs->buf, &rs->buf_size, 0);
7806 if (packet_check_result (rs->buf) == PACKET_ERROR)
7807 error (_("Could not read registers; remote failure reply '%s'"),
7808 rs->buf);
7809
7810 /* We can get out of synch in various cases. If the first character
7811 in the buffer is not a hex character, assume that has happened
7812 and try to fetch another packet to read. */
7813 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7814 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7815 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7816 && rs->buf[0] != 'x') /* New: unavailable register value. */
7817 {
7818 if (remote_debug)
7819 fprintf_unfiltered (gdb_stdlog,
7820 "Bad register packet; fetching a new packet\n");
7821 getpkt (&rs->buf, &rs->buf_size, 0);
7822 }
7823
7824 buf_len = strlen (rs->buf);
7825
7826 /* Sanity check the received packet. */
7827 if (buf_len % 2 != 0)
7828 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7829
7830 return buf_len / 2;
7831 }
7832
7833 static void
7834 process_g_packet (struct regcache *regcache)
7835 {
7836 struct gdbarch *gdbarch = regcache->arch ();
7837 struct remote_state *rs = get_remote_state ();
7838 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7839 int i, buf_len;
7840 char *p;
7841 char *regs;
7842
7843 buf_len = strlen (rs->buf);
7844
7845 /* Further sanity checks, with knowledge of the architecture. */
7846 if (buf_len > 2 * rsa->sizeof_g_packet)
7847 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7848 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7849
7850 /* Save the size of the packet sent to us by the target. It is used
7851 as a heuristic when determining the max size of packets that the
7852 target can safely receive. */
7853 if (rsa->actual_register_packet_size == 0)
7854 rsa->actual_register_packet_size = buf_len;
7855
7856 /* If this is smaller than we guessed the 'g' packet would be,
7857 update our records. A 'g' reply that doesn't include a register's
7858 value implies either that the register is not available, or that
7859 the 'p' packet must be used. */
7860 if (buf_len < 2 * rsa->sizeof_g_packet)
7861 {
7862 long sizeof_g_packet = buf_len / 2;
7863
7864 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7865 {
7866 long offset = rsa->regs[i].offset;
7867 long reg_size = register_size (gdbarch, i);
7868
7869 if (rsa->regs[i].pnum == -1)
7870 continue;
7871
7872 if (offset >= sizeof_g_packet)
7873 rsa->regs[i].in_g_packet = 0;
7874 else if (offset + reg_size > sizeof_g_packet)
7875 error (_("Truncated register %d in remote 'g' packet"), i);
7876 else
7877 rsa->regs[i].in_g_packet = 1;
7878 }
7879
7880 /* Looks valid enough, we can assume this is the correct length
7881 for a 'g' packet. It's important not to adjust
7882 rsa->sizeof_g_packet if we have truncated registers otherwise
7883 this "if" won't be run the next time the method is called
7884 with a packet of the same size and one of the internal errors
7885 below will trigger instead. */
7886 rsa->sizeof_g_packet = sizeof_g_packet;
7887 }
7888
7889 regs = (char *) alloca (rsa->sizeof_g_packet);
7890
7891 /* Unimplemented registers read as all bits zero. */
7892 memset (regs, 0, rsa->sizeof_g_packet);
7893
7894 /* Reply describes registers byte by byte, each byte encoded as two
7895 hex characters. Suck them all up, then supply them to the
7896 register cacheing/storage mechanism. */
7897
7898 p = rs->buf;
7899 for (i = 0; i < rsa->sizeof_g_packet; i++)
7900 {
7901 if (p[0] == 0 || p[1] == 0)
7902 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7903 internal_error (__FILE__, __LINE__,
7904 _("unexpected end of 'g' packet reply"));
7905
7906 if (p[0] == 'x' && p[1] == 'x')
7907 regs[i] = 0; /* 'x' */
7908 else
7909 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7910 p += 2;
7911 }
7912
7913 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7914 {
7915 struct packet_reg *r = &rsa->regs[i];
7916 long reg_size = register_size (gdbarch, i);
7917
7918 if (r->in_g_packet)
7919 {
7920 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7921 /* This shouldn't happen - we adjusted in_g_packet above. */
7922 internal_error (__FILE__, __LINE__,
7923 _("unexpected end of 'g' packet reply"));
7924 else if (rs->buf[r->offset * 2] == 'x')
7925 {
7926 gdb_assert (r->offset * 2 < strlen (rs->buf));
7927 /* The register isn't available, mark it as such (at
7928 the same time setting the value to zero). */
7929 regcache_raw_supply (regcache, r->regnum, NULL);
7930 }
7931 else
7932 regcache_raw_supply (regcache, r->regnum,
7933 regs + r->offset);
7934 }
7935 }
7936 }
7937
7938 static void
7939 fetch_registers_using_g (struct regcache *regcache)
7940 {
7941 send_g_packet ();
7942 process_g_packet (regcache);
7943 }
7944
7945 /* Make the remote selected traceframe match GDB's selected
7946 traceframe. */
7947
7948 static void
7949 set_remote_traceframe (void)
7950 {
7951 int newnum;
7952 struct remote_state *rs = get_remote_state ();
7953
7954 if (rs->remote_traceframe_number == get_traceframe_number ())
7955 return;
7956
7957 /* Avoid recursion, remote_trace_find calls us again. */
7958 rs->remote_traceframe_number = get_traceframe_number ();
7959
7960 newnum = target_trace_find (tfind_number,
7961 get_traceframe_number (), 0, 0, NULL);
7962
7963 /* Should not happen. If it does, all bets are off. */
7964 if (newnum != get_traceframe_number ())
7965 warning (_("could not set remote traceframe"));
7966 }
7967
7968 void
7969 remote_target::fetch_registers (struct regcache *regcache, int regnum)
7970 {
7971 struct gdbarch *gdbarch = regcache->arch ();
7972 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7973 int i;
7974
7975 set_remote_traceframe ();
7976 set_general_thread (regcache_get_ptid (regcache));
7977
7978 if (regnum >= 0)
7979 {
7980 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
7981
7982 gdb_assert (reg != NULL);
7983
7984 /* If this register might be in the 'g' packet, try that first -
7985 we are likely to read more than one register. If this is the
7986 first 'g' packet, we might be overly optimistic about its
7987 contents, so fall back to 'p'. */
7988 if (reg->in_g_packet)
7989 {
7990 fetch_registers_using_g (regcache);
7991 if (reg->in_g_packet)
7992 return;
7993 }
7994
7995 if (fetch_register_using_p (regcache, reg))
7996 return;
7997
7998 /* This register is not available. */
7999 regcache_raw_supply (regcache, reg->regnum, NULL);
8000
8001 return;
8002 }
8003
8004 fetch_registers_using_g (regcache);
8005
8006 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8007 if (!rsa->regs[i].in_g_packet)
8008 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8009 {
8010 /* This register is not available. */
8011 regcache_raw_supply (regcache, i, NULL);
8012 }
8013 }
8014
8015 /* Prepare to store registers. Since we may send them all (using a
8016 'G' request), we have to read out the ones we don't want to change
8017 first. */
8018
8019 void
8020 remote_target::prepare_to_store (struct regcache *regcache)
8021 {
8022 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8023 int i;
8024
8025 /* Make sure the entire registers array is valid. */
8026 switch (packet_support (PACKET_P))
8027 {
8028 case PACKET_DISABLE:
8029 case PACKET_SUPPORT_UNKNOWN:
8030 /* Make sure all the necessary registers are cached. */
8031 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8032 if (rsa->regs[i].in_g_packet)
8033 regcache_raw_update (regcache, rsa->regs[i].regnum);
8034 break;
8035 case PACKET_ENABLE:
8036 break;
8037 }
8038 }
8039
8040 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8041 packet was not recognized. */
8042
8043 static int
8044 store_register_using_P (const struct regcache *regcache,
8045 struct packet_reg *reg)
8046 {
8047 struct gdbarch *gdbarch = regcache->arch ();
8048 struct remote_state *rs = get_remote_state ();
8049 /* Try storing a single register. */
8050 char *buf = rs->buf;
8051 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8052 char *p;
8053
8054 if (packet_support (PACKET_P) == PACKET_DISABLE)
8055 return 0;
8056
8057 if (reg->pnum == -1)
8058 return 0;
8059
8060 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8061 p = buf + strlen (buf);
8062 regcache_raw_collect (regcache, reg->regnum, regp);
8063 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8064 putpkt (rs->buf);
8065 getpkt (&rs->buf, &rs->buf_size, 0);
8066
8067 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8068 {
8069 case PACKET_OK:
8070 return 1;
8071 case PACKET_ERROR:
8072 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8073 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8074 case PACKET_UNKNOWN:
8075 return 0;
8076 default:
8077 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8078 }
8079 }
8080
8081 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8082 contents of the register cache buffer. FIXME: ignores errors. */
8083
8084 static void
8085 store_registers_using_G (const struct regcache *regcache)
8086 {
8087 struct remote_state *rs = get_remote_state ();
8088 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8089 gdb_byte *regs;
8090 char *p;
8091
8092 /* Extract all the registers in the regcache copying them into a
8093 local buffer. */
8094 {
8095 int i;
8096
8097 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8098 memset (regs, 0, rsa->sizeof_g_packet);
8099 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8100 {
8101 struct packet_reg *r = &rsa->regs[i];
8102
8103 if (r->in_g_packet)
8104 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
8105 }
8106 }
8107
8108 /* Command describes registers byte by byte,
8109 each byte encoded as two hex characters. */
8110 p = rs->buf;
8111 *p++ = 'G';
8112 bin2hex (regs, p, rsa->sizeof_g_packet);
8113 putpkt (rs->buf);
8114 getpkt (&rs->buf, &rs->buf_size, 0);
8115 if (packet_check_result (rs->buf) == PACKET_ERROR)
8116 error (_("Could not write registers; remote failure reply '%s'"),
8117 rs->buf);
8118 }
8119
8120 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8121 of the register cache buffer. FIXME: ignores errors. */
8122
8123 void
8124 remote_target::store_registers (struct regcache *regcache, int regnum)
8125 {
8126 struct gdbarch *gdbarch = regcache->arch ();
8127 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
8128 int i;
8129
8130 set_remote_traceframe ();
8131 set_general_thread (regcache_get_ptid (regcache));
8132
8133 if (regnum >= 0)
8134 {
8135 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8136
8137 gdb_assert (reg != NULL);
8138
8139 /* Always prefer to store registers using the 'P' packet if
8140 possible; we often change only a small number of registers.
8141 Sometimes we change a larger number; we'd need help from a
8142 higher layer to know to use 'G'. */
8143 if (store_register_using_P (regcache, reg))
8144 return;
8145
8146 /* For now, don't complain if we have no way to write the
8147 register. GDB loses track of unavailable registers too
8148 easily. Some day, this may be an error. We don't have
8149 any way to read the register, either... */
8150 if (!reg->in_g_packet)
8151 return;
8152
8153 store_registers_using_G (regcache);
8154 return;
8155 }
8156
8157 store_registers_using_G (regcache);
8158
8159 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8160 if (!rsa->regs[i].in_g_packet)
8161 if (!store_register_using_P (regcache, &rsa->regs[i]))
8162 /* See above for why we do not issue an error here. */
8163 continue;
8164 }
8165 \f
8166
8167 /* Return the number of hex digits in num. */
8168
8169 static int
8170 hexnumlen (ULONGEST num)
8171 {
8172 int i;
8173
8174 for (i = 0; num != 0; i++)
8175 num >>= 4;
8176
8177 return std::max (i, 1);
8178 }
8179
8180 /* Set BUF to the minimum number of hex digits representing NUM. */
8181
8182 static int
8183 hexnumstr (char *buf, ULONGEST num)
8184 {
8185 int len = hexnumlen (num);
8186
8187 return hexnumnstr (buf, num, len);
8188 }
8189
8190
8191 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8192
8193 static int
8194 hexnumnstr (char *buf, ULONGEST num, int width)
8195 {
8196 int i;
8197
8198 buf[width] = '\0';
8199
8200 for (i = width - 1; i >= 0; i--)
8201 {
8202 buf[i] = "0123456789abcdef"[(num & 0xf)];
8203 num >>= 4;
8204 }
8205
8206 return width;
8207 }
8208
8209 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8210
8211 static CORE_ADDR
8212 remote_address_masked (CORE_ADDR addr)
8213 {
8214 unsigned int address_size = remote_address_size;
8215
8216 /* If "remoteaddresssize" was not set, default to target address size. */
8217 if (!address_size)
8218 address_size = gdbarch_addr_bit (target_gdbarch ());
8219
8220 if (address_size > 0
8221 && address_size < (sizeof (ULONGEST) * 8))
8222 {
8223 /* Only create a mask when that mask can safely be constructed
8224 in a ULONGEST variable. */
8225 ULONGEST mask = 1;
8226
8227 mask = (mask << address_size) - 1;
8228 addr &= mask;
8229 }
8230 return addr;
8231 }
8232
8233 /* Determine whether the remote target supports binary downloading.
8234 This is accomplished by sending a no-op memory write of zero length
8235 to the target at the specified address. It does not suffice to send
8236 the whole packet, since many stubs strip the eighth bit and
8237 subsequently compute a wrong checksum, which causes real havoc with
8238 remote_write_bytes.
8239
8240 NOTE: This can still lose if the serial line is not eight-bit
8241 clean. In cases like this, the user should clear "remote
8242 X-packet". */
8243
8244 static void
8245 check_binary_download (CORE_ADDR addr)
8246 {
8247 struct remote_state *rs = get_remote_state ();
8248
8249 switch (packet_support (PACKET_X))
8250 {
8251 case PACKET_DISABLE:
8252 break;
8253 case PACKET_ENABLE:
8254 break;
8255 case PACKET_SUPPORT_UNKNOWN:
8256 {
8257 char *p;
8258
8259 p = rs->buf;
8260 *p++ = 'X';
8261 p += hexnumstr (p, (ULONGEST) addr);
8262 *p++ = ',';
8263 p += hexnumstr (p, (ULONGEST) 0);
8264 *p++ = ':';
8265 *p = '\0';
8266
8267 putpkt_binary (rs->buf, (int) (p - rs->buf));
8268 getpkt (&rs->buf, &rs->buf_size, 0);
8269
8270 if (rs->buf[0] == '\0')
8271 {
8272 if (remote_debug)
8273 fprintf_unfiltered (gdb_stdlog,
8274 "binary downloading NOT "
8275 "supported by target\n");
8276 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8277 }
8278 else
8279 {
8280 if (remote_debug)
8281 fprintf_unfiltered (gdb_stdlog,
8282 "binary downloading supported by target\n");
8283 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8284 }
8285 break;
8286 }
8287 }
8288 }
8289
8290 /* Helper function to resize the payload in order to try to get a good
8291 alignment. We try to write an amount of data such that the next write will
8292 start on an address aligned on REMOTE_ALIGN_WRITES. */
8293
8294 static int
8295 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8296 {
8297 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8298 }
8299
8300 /* Write memory data directly to the remote machine.
8301 This does not inform the data cache; the data cache uses this.
8302 HEADER is the starting part of the packet.
8303 MEMADDR is the address in the remote memory space.
8304 MYADDR is the address of the buffer in our space.
8305 LEN_UNITS is the number of addressable units to write.
8306 UNIT_SIZE is the length in bytes of an addressable unit.
8307 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8308 should send data as binary ('X'), or hex-encoded ('M').
8309
8310 The function creates packet of the form
8311 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8312
8313 where encoding of <DATA> is terminated by PACKET_FORMAT.
8314
8315 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8316 are omitted.
8317
8318 Return the transferred status, error or OK (an
8319 'enum target_xfer_status' value). Save the number of addressable units
8320 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8321
8322 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8323 exchange between gdb and the stub could look like (?? in place of the
8324 checksum):
8325
8326 -> $m1000,4#??
8327 <- aaaabbbbccccdddd
8328
8329 -> $M1000,3:eeeeffffeeee#??
8330 <- OK
8331
8332 -> $m1000,4#??
8333 <- eeeeffffeeeedddd */
8334
8335 static enum target_xfer_status
8336 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8337 const gdb_byte *myaddr, ULONGEST len_units,
8338 int unit_size, ULONGEST *xfered_len_units,
8339 char packet_format, int use_length)
8340 {
8341 struct remote_state *rs = get_remote_state ();
8342 char *p;
8343 char *plen = NULL;
8344 int plenlen = 0;
8345 int todo_units;
8346 int units_written;
8347 int payload_capacity_bytes;
8348 int payload_length_bytes;
8349
8350 if (packet_format != 'X' && packet_format != 'M')
8351 internal_error (__FILE__, __LINE__,
8352 _("remote_write_bytes_aux: bad packet format"));
8353
8354 if (len_units == 0)
8355 return TARGET_XFER_EOF;
8356
8357 payload_capacity_bytes = get_memory_write_packet_size ();
8358
8359 /* The packet buffer will be large enough for the payload;
8360 get_memory_packet_size ensures this. */
8361 rs->buf[0] = '\0';
8362
8363 /* Compute the size of the actual payload by subtracting out the
8364 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8365
8366 payload_capacity_bytes -= strlen ("$,:#NN");
8367 if (!use_length)
8368 /* The comma won't be used. */
8369 payload_capacity_bytes += 1;
8370 payload_capacity_bytes -= strlen (header);
8371 payload_capacity_bytes -= hexnumlen (memaddr);
8372
8373 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8374
8375 strcat (rs->buf, header);
8376 p = rs->buf + strlen (header);
8377
8378 /* Compute a best guess of the number of bytes actually transfered. */
8379 if (packet_format == 'X')
8380 {
8381 /* Best guess at number of bytes that will fit. */
8382 todo_units = std::min (len_units,
8383 (ULONGEST) payload_capacity_bytes / unit_size);
8384 if (use_length)
8385 payload_capacity_bytes -= hexnumlen (todo_units);
8386 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8387 }
8388 else
8389 {
8390 /* Number of bytes that will fit. */
8391 todo_units
8392 = std::min (len_units,
8393 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8394 if (use_length)
8395 payload_capacity_bytes -= hexnumlen (todo_units);
8396 todo_units = std::min (todo_units,
8397 (payload_capacity_bytes / unit_size) / 2);
8398 }
8399
8400 if (todo_units <= 0)
8401 internal_error (__FILE__, __LINE__,
8402 _("minimum packet size too small to write data"));
8403
8404 /* If we already need another packet, then try to align the end
8405 of this packet to a useful boundary. */
8406 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8407 todo_units = align_for_efficient_write (todo_units, memaddr);
8408
8409 /* Append "<memaddr>". */
8410 memaddr = remote_address_masked (memaddr);
8411 p += hexnumstr (p, (ULONGEST) memaddr);
8412
8413 if (use_length)
8414 {
8415 /* Append ",". */
8416 *p++ = ',';
8417
8418 /* Append the length and retain its location and size. It may need to be
8419 adjusted once the packet body has been created. */
8420 plen = p;
8421 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8422 p += plenlen;
8423 }
8424
8425 /* Append ":". */
8426 *p++ = ':';
8427 *p = '\0';
8428
8429 /* Append the packet body. */
8430 if (packet_format == 'X')
8431 {
8432 /* Binary mode. Send target system values byte by byte, in
8433 increasing byte addresses. Only escape certain critical
8434 characters. */
8435 payload_length_bytes =
8436 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8437 &units_written, payload_capacity_bytes);
8438
8439 /* If not all TODO units fit, then we'll need another packet. Make
8440 a second try to keep the end of the packet aligned. Don't do
8441 this if the packet is tiny. */
8442 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8443 {
8444 int new_todo_units;
8445
8446 new_todo_units = align_for_efficient_write (units_written, memaddr);
8447
8448 if (new_todo_units != units_written)
8449 payload_length_bytes =
8450 remote_escape_output (myaddr, new_todo_units, unit_size,
8451 (gdb_byte *) p, &units_written,
8452 payload_capacity_bytes);
8453 }
8454
8455 p += payload_length_bytes;
8456 if (use_length && units_written < todo_units)
8457 {
8458 /* Escape chars have filled up the buffer prematurely,
8459 and we have actually sent fewer units than planned.
8460 Fix-up the length field of the packet. Use the same
8461 number of characters as before. */
8462 plen += hexnumnstr (plen, (ULONGEST) units_written,
8463 plenlen);
8464 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8465 }
8466 }
8467 else
8468 {
8469 /* Normal mode: Send target system values byte by byte, in
8470 increasing byte addresses. Each byte is encoded as a two hex
8471 value. */
8472 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8473 units_written = todo_units;
8474 }
8475
8476 putpkt_binary (rs->buf, (int) (p - rs->buf));
8477 getpkt (&rs->buf, &rs->buf_size, 0);
8478
8479 if (rs->buf[0] == 'E')
8480 return TARGET_XFER_E_IO;
8481
8482 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8483 send fewer units than we'd planned. */
8484 *xfered_len_units = (ULONGEST) units_written;
8485 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8486 }
8487
8488 /* Write memory data directly to the remote machine.
8489 This does not inform the data cache; the data cache uses this.
8490 MEMADDR is the address in the remote memory space.
8491 MYADDR is the address of the buffer in our space.
8492 LEN is the number of bytes.
8493
8494 Return the transferred status, error or OK (an
8495 'enum target_xfer_status' value). Save the number of bytes
8496 transferred in *XFERED_LEN. Only transfer a single packet. */
8497
8498 static enum target_xfer_status
8499 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8500 int unit_size, ULONGEST *xfered_len)
8501 {
8502 const char *packet_format = NULL;
8503
8504 /* Check whether the target supports binary download. */
8505 check_binary_download (memaddr);
8506
8507 switch (packet_support (PACKET_X))
8508 {
8509 case PACKET_ENABLE:
8510 packet_format = "X";
8511 break;
8512 case PACKET_DISABLE:
8513 packet_format = "M";
8514 break;
8515 case PACKET_SUPPORT_UNKNOWN:
8516 internal_error (__FILE__, __LINE__,
8517 _("remote_write_bytes: bad internal state"));
8518 default:
8519 internal_error (__FILE__, __LINE__, _("bad switch"));
8520 }
8521
8522 return remote_write_bytes_aux (packet_format,
8523 memaddr, myaddr, len, unit_size, xfered_len,
8524 packet_format[0], 1);
8525 }
8526
8527 /* Read memory data directly from the remote machine.
8528 This does not use the data cache; the data cache uses this.
8529 MEMADDR is the address in the remote memory space.
8530 MYADDR is the address of the buffer in our space.
8531 LEN_UNITS is the number of addressable memory units to read..
8532 UNIT_SIZE is the length in bytes of an addressable unit.
8533
8534 Return the transferred status, error or OK (an
8535 'enum target_xfer_status' value). Save the number of bytes
8536 transferred in *XFERED_LEN_UNITS.
8537
8538 See the comment of remote_write_bytes_aux for an example of
8539 memory read/write exchange between gdb and the stub. */
8540
8541 static enum target_xfer_status
8542 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8543 int unit_size, ULONGEST *xfered_len_units)
8544 {
8545 struct remote_state *rs = get_remote_state ();
8546 int buf_size_bytes; /* Max size of packet output buffer. */
8547 char *p;
8548 int todo_units;
8549 int decoded_bytes;
8550
8551 buf_size_bytes = get_memory_read_packet_size ();
8552 /* The packet buffer will be large enough for the payload;
8553 get_memory_packet_size ensures this. */
8554
8555 /* Number of units that will fit. */
8556 todo_units = std::min (len_units,
8557 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8558
8559 /* Construct "m"<memaddr>","<len>". */
8560 memaddr = remote_address_masked (memaddr);
8561 p = rs->buf;
8562 *p++ = 'm';
8563 p += hexnumstr (p, (ULONGEST) memaddr);
8564 *p++ = ',';
8565 p += hexnumstr (p, (ULONGEST) todo_units);
8566 *p = '\0';
8567 putpkt (rs->buf);
8568 getpkt (&rs->buf, &rs->buf_size, 0);
8569 if (rs->buf[0] == 'E'
8570 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8571 && rs->buf[3] == '\0')
8572 return TARGET_XFER_E_IO;
8573 /* Reply describes memory byte by byte, each byte encoded as two hex
8574 characters. */
8575 p = rs->buf;
8576 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8577 /* Return what we have. Let higher layers handle partial reads. */
8578 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8579 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8580 }
8581
8582 /* Using the set of read-only target sections of remote, read live
8583 read-only memory.
8584
8585 For interface/parameters/return description see target.h,
8586 to_xfer_partial. */
8587
8588 static enum target_xfer_status
8589 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8590 ULONGEST memaddr, ULONGEST len,
8591 int unit_size, ULONGEST *xfered_len)
8592 {
8593 struct target_section *secp;
8594 struct target_section_table *table;
8595
8596 secp = target_section_by_addr (ops, memaddr);
8597 if (secp != NULL
8598 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8599 secp->the_bfd_section)
8600 & SEC_READONLY))
8601 {
8602 struct target_section *p;
8603 ULONGEST memend = memaddr + len;
8604
8605 table = target_get_section_table (ops);
8606
8607 for (p = table->sections; p < table->sections_end; p++)
8608 {
8609 if (memaddr >= p->addr)
8610 {
8611 if (memend <= p->endaddr)
8612 {
8613 /* Entire transfer is within this section. */
8614 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8615 xfered_len);
8616 }
8617 else if (memaddr >= p->endaddr)
8618 {
8619 /* This section ends before the transfer starts. */
8620 continue;
8621 }
8622 else
8623 {
8624 /* This section overlaps the transfer. Just do half. */
8625 len = p->endaddr - memaddr;
8626 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8627 xfered_len);
8628 }
8629 }
8630 }
8631 }
8632
8633 return TARGET_XFER_EOF;
8634 }
8635
8636 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8637 first if the requested memory is unavailable in traceframe.
8638 Otherwise, fall back to remote_read_bytes_1. */
8639
8640 static enum target_xfer_status
8641 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8642 gdb_byte *myaddr, ULONGEST len, int unit_size,
8643 ULONGEST *xfered_len)
8644 {
8645 if (len == 0)
8646 return TARGET_XFER_EOF;
8647
8648 if (get_traceframe_number () != -1)
8649 {
8650 std::vector<mem_range> available;
8651
8652 /* If we fail to get the set of available memory, then the
8653 target does not support querying traceframe info, and so we
8654 attempt reading from the traceframe anyway (assuming the
8655 target implements the old QTro packet then). */
8656 if (traceframe_available_memory (&available, memaddr, len))
8657 {
8658 if (available.empty () || available[0].start != memaddr)
8659 {
8660 enum target_xfer_status res;
8661
8662 /* Don't read into the traceframe's available
8663 memory. */
8664 if (!available.empty ())
8665 {
8666 LONGEST oldlen = len;
8667
8668 len = available[0].start - memaddr;
8669 gdb_assert (len <= oldlen);
8670 }
8671
8672 /* This goes through the topmost target again. */
8673 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8674 len, unit_size, xfered_len);
8675 if (res == TARGET_XFER_OK)
8676 return TARGET_XFER_OK;
8677 else
8678 {
8679 /* No use trying further, we know some memory starting
8680 at MEMADDR isn't available. */
8681 *xfered_len = len;
8682 return (*xfered_len != 0) ?
8683 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8684 }
8685 }
8686
8687 /* Don't try to read more than how much is available, in
8688 case the target implements the deprecated QTro packet to
8689 cater for older GDBs (the target's knowledge of read-only
8690 sections may be outdated by now). */
8691 len = available[0].length;
8692 }
8693 }
8694
8695 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8696 }
8697
8698 \f
8699
8700 /* Sends a packet with content determined by the printf format string
8701 FORMAT and the remaining arguments, then gets the reply. Returns
8702 whether the packet was a success, a failure, or unknown. */
8703
8704 static enum packet_result remote_send_printf (const char *format, ...)
8705 ATTRIBUTE_PRINTF (1, 2);
8706
8707 static enum packet_result
8708 remote_send_printf (const char *format, ...)
8709 {
8710 struct remote_state *rs = get_remote_state ();
8711 int max_size = get_remote_packet_size ();
8712 va_list ap;
8713
8714 va_start (ap, format);
8715
8716 rs->buf[0] = '\0';
8717 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8718 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8719
8720 if (putpkt (rs->buf) < 0)
8721 error (_("Communication problem with target."));
8722
8723 rs->buf[0] = '\0';
8724 getpkt (&rs->buf, &rs->buf_size, 0);
8725
8726 return packet_check_result (rs->buf);
8727 }
8728
8729 /* Flash writing can take quite some time. We'll set
8730 effectively infinite timeout for flash operations.
8731 In future, we'll need to decide on a better approach. */
8732 static const int remote_flash_timeout = 1000;
8733
8734 void
8735 remote_target::flash_erase (ULONGEST address, LONGEST length)
8736 {
8737 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8738 enum packet_result ret;
8739 scoped_restore restore_timeout
8740 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8741
8742 ret = remote_send_printf ("vFlashErase:%s,%s",
8743 phex (address, addr_size),
8744 phex (length, 4));
8745 switch (ret)
8746 {
8747 case PACKET_UNKNOWN:
8748 error (_("Remote target does not support flash erase"));
8749 case PACKET_ERROR:
8750 error (_("Error erasing flash with vFlashErase packet"));
8751 default:
8752 break;
8753 }
8754 }
8755
8756 static enum target_xfer_status
8757 remote_flash_write (struct target_ops *ops, ULONGEST address,
8758 ULONGEST length, ULONGEST *xfered_len,
8759 const gdb_byte *data)
8760 {
8761 scoped_restore restore_timeout
8762 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8763 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8764 xfered_len,'X', 0);
8765 }
8766
8767 void
8768 remote_target::flash_done ()
8769 {
8770 int ret;
8771
8772 scoped_restore restore_timeout
8773 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8774
8775 ret = remote_send_printf ("vFlashDone");
8776
8777 switch (ret)
8778 {
8779 case PACKET_UNKNOWN:
8780 error (_("Remote target does not support vFlashDone"));
8781 case PACKET_ERROR:
8782 error (_("Error finishing flash operation"));
8783 default:
8784 break;
8785 }
8786 }
8787
8788 void
8789 remote_target::files_info ()
8790 {
8791 puts_filtered ("Debugging a target over a serial line.\n");
8792 }
8793 \f
8794 /* Stuff for dealing with the packets which are part of this protocol.
8795 See comment at top of file for details. */
8796
8797 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8798 error to higher layers. Called when a serial error is detected.
8799 The exception message is STRING, followed by a colon and a blank,
8800 the system error message for errno at function entry and final dot
8801 for output compatibility with throw_perror_with_name. */
8802
8803 static void
8804 unpush_and_perror (const char *string)
8805 {
8806 int saved_errno = errno;
8807
8808 remote_unpush_target ();
8809 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8810 safe_strerror (saved_errno));
8811 }
8812
8813 /* Read a single character from the remote end. The current quit
8814 handler is overridden to avoid quitting in the middle of packet
8815 sequence, as that would break communication with the remote server.
8816 See remote_serial_quit_handler for more detail. */
8817
8818 static int
8819 readchar (int timeout)
8820 {
8821 int ch;
8822 struct remote_state *rs = get_remote_state ();
8823
8824 {
8825 scoped_restore restore_quit
8826 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8827
8828 rs->got_ctrlc_during_io = 0;
8829
8830 ch = serial_readchar (rs->remote_desc, timeout);
8831
8832 if (rs->got_ctrlc_during_io)
8833 set_quit_flag ();
8834 }
8835
8836 if (ch >= 0)
8837 return ch;
8838
8839 switch ((enum serial_rc) ch)
8840 {
8841 case SERIAL_EOF:
8842 remote_unpush_target ();
8843 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8844 /* no return */
8845 case SERIAL_ERROR:
8846 unpush_and_perror (_("Remote communication error. "
8847 "Target disconnected."));
8848 /* no return */
8849 case SERIAL_TIMEOUT:
8850 break;
8851 }
8852 return ch;
8853 }
8854
8855 /* Wrapper for serial_write that closes the target and throws if
8856 writing fails. The current quit handler is overridden to avoid
8857 quitting in the middle of packet sequence, as that would break
8858 communication with the remote server. See
8859 remote_serial_quit_handler for more detail. */
8860
8861 static void
8862 remote_serial_write (const char *str, int len)
8863 {
8864 struct remote_state *rs = get_remote_state ();
8865
8866 scoped_restore restore_quit
8867 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8868
8869 rs->got_ctrlc_during_io = 0;
8870
8871 if (serial_write (rs->remote_desc, str, len))
8872 {
8873 unpush_and_perror (_("Remote communication error. "
8874 "Target disconnected."));
8875 }
8876
8877 if (rs->got_ctrlc_during_io)
8878 set_quit_flag ();
8879 }
8880
8881 /* Return a string representing an escaped version of BUF, of len N.
8882 E.g. \n is converted to \\n, \t to \\t, etc. */
8883
8884 static std::string
8885 escape_buffer (const char *buf, int n)
8886 {
8887 string_file stb;
8888
8889 stb.putstrn (buf, n, '\\');
8890 return std::move (stb.string ());
8891 }
8892
8893 /* Display a null-terminated packet on stdout, for debugging, using C
8894 string notation. */
8895
8896 static void
8897 print_packet (const char *buf)
8898 {
8899 puts_filtered ("\"");
8900 fputstr_filtered (buf, '"', gdb_stdout);
8901 puts_filtered ("\"");
8902 }
8903
8904 int
8905 putpkt (const char *buf)
8906 {
8907 return putpkt_binary (buf, strlen (buf));
8908 }
8909
8910 /* Send a packet to the remote machine, with error checking. The data
8911 of the packet is in BUF. The string in BUF can be at most
8912 get_remote_packet_size () - 5 to account for the $, # and checksum,
8913 and for a possible /0 if we are debugging (remote_debug) and want
8914 to print the sent packet as a string. */
8915
8916 static int
8917 putpkt_binary (const char *buf, int cnt)
8918 {
8919 struct remote_state *rs = get_remote_state ();
8920 int i;
8921 unsigned char csum = 0;
8922 gdb::def_vector<char> data (cnt + 6);
8923 char *buf2 = data.data ();
8924
8925 int ch;
8926 int tcount = 0;
8927 char *p;
8928
8929 /* Catch cases like trying to read memory or listing threads while
8930 we're waiting for a stop reply. The remote server wouldn't be
8931 ready to handle this request, so we'd hang and timeout. We don't
8932 have to worry about this in synchronous mode, because in that
8933 case it's not possible to issue a command while the target is
8934 running. This is not a problem in non-stop mode, because in that
8935 case, the stub is always ready to process serial input. */
8936 if (!target_is_non_stop_p ()
8937 && target_is_async_p ()
8938 && rs->waiting_for_stop_reply)
8939 {
8940 error (_("Cannot execute this command while the target is running.\n"
8941 "Use the \"interrupt\" command to stop the target\n"
8942 "and then try again."));
8943 }
8944
8945 /* We're sending out a new packet. Make sure we don't look at a
8946 stale cached response. */
8947 rs->cached_wait_status = 0;
8948
8949 /* Copy the packet into buffer BUF2, encapsulating it
8950 and giving it a checksum. */
8951
8952 p = buf2;
8953 *p++ = '$';
8954
8955 for (i = 0; i < cnt; i++)
8956 {
8957 csum += buf[i];
8958 *p++ = buf[i];
8959 }
8960 *p++ = '#';
8961 *p++ = tohex ((csum >> 4) & 0xf);
8962 *p++ = tohex (csum & 0xf);
8963
8964 /* Send it over and over until we get a positive ack. */
8965
8966 while (1)
8967 {
8968 int started_error_output = 0;
8969
8970 if (remote_debug)
8971 {
8972 *p = '\0';
8973
8974 int len = (int) (p - buf2);
8975
8976 std::string str
8977 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8978
8979 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8980
8981 if (len > REMOTE_DEBUG_MAX_CHAR)
8982 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
8983 len - REMOTE_DEBUG_MAX_CHAR);
8984
8985 fprintf_unfiltered (gdb_stdlog, "...");
8986
8987 gdb_flush (gdb_stdlog);
8988 }
8989 remote_serial_write (buf2, p - buf2);
8990
8991 /* If this is a no acks version of the remote protocol, send the
8992 packet and move on. */
8993 if (rs->noack_mode)
8994 break;
8995
8996 /* Read until either a timeout occurs (-2) or '+' is read.
8997 Handle any notification that arrives in the mean time. */
8998 while (1)
8999 {
9000 ch = readchar (remote_timeout);
9001
9002 if (remote_debug)
9003 {
9004 switch (ch)
9005 {
9006 case '+':
9007 case '-':
9008 case SERIAL_TIMEOUT:
9009 case '$':
9010 case '%':
9011 if (started_error_output)
9012 {
9013 putchar_unfiltered ('\n');
9014 started_error_output = 0;
9015 }
9016 }
9017 }
9018
9019 switch (ch)
9020 {
9021 case '+':
9022 if (remote_debug)
9023 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9024 return 1;
9025 case '-':
9026 if (remote_debug)
9027 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9028 /* FALLTHROUGH */
9029 case SERIAL_TIMEOUT:
9030 tcount++;
9031 if (tcount > 3)
9032 return 0;
9033 break; /* Retransmit buffer. */
9034 case '$':
9035 {
9036 if (remote_debug)
9037 fprintf_unfiltered (gdb_stdlog,
9038 "Packet instead of Ack, ignoring it\n");
9039 /* It's probably an old response sent because an ACK
9040 was lost. Gobble up the packet and ack it so it
9041 doesn't get retransmitted when we resend this
9042 packet. */
9043 skip_frame ();
9044 remote_serial_write ("+", 1);
9045 continue; /* Now, go look for +. */
9046 }
9047
9048 case '%':
9049 {
9050 int val;
9051
9052 /* If we got a notification, handle it, and go back to looking
9053 for an ack. */
9054 /* We've found the start of a notification. Now
9055 collect the data. */
9056 val = read_frame (&rs->buf, &rs->buf_size);
9057 if (val >= 0)
9058 {
9059 if (remote_debug)
9060 {
9061 std::string str = escape_buffer (rs->buf, val);
9062
9063 fprintf_unfiltered (gdb_stdlog,
9064 " Notification received: %s\n",
9065 str.c_str ());
9066 }
9067 handle_notification (rs->notif_state, rs->buf);
9068 /* We're in sync now, rewait for the ack. */
9069 tcount = 0;
9070 }
9071 else
9072 {
9073 if (remote_debug)
9074 {
9075 if (!started_error_output)
9076 {
9077 started_error_output = 1;
9078 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9079 }
9080 fputc_unfiltered (ch & 0177, gdb_stdlog);
9081 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9082 }
9083 }
9084 continue;
9085 }
9086 /* fall-through */
9087 default:
9088 if (remote_debug)
9089 {
9090 if (!started_error_output)
9091 {
9092 started_error_output = 1;
9093 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9094 }
9095 fputc_unfiltered (ch & 0177, gdb_stdlog);
9096 }
9097 continue;
9098 }
9099 break; /* Here to retransmit. */
9100 }
9101
9102 #if 0
9103 /* This is wrong. If doing a long backtrace, the user should be
9104 able to get out next time we call QUIT, without anything as
9105 violent as interrupt_query. If we want to provide a way out of
9106 here without getting to the next QUIT, it should be based on
9107 hitting ^C twice as in remote_wait. */
9108 if (quit_flag)
9109 {
9110 quit_flag = 0;
9111 interrupt_query ();
9112 }
9113 #endif
9114 }
9115
9116 return 0;
9117 }
9118
9119 /* Come here after finding the start of a frame when we expected an
9120 ack. Do our best to discard the rest of this packet. */
9121
9122 static void
9123 skip_frame (void)
9124 {
9125 int c;
9126
9127 while (1)
9128 {
9129 c = readchar (remote_timeout);
9130 switch (c)
9131 {
9132 case SERIAL_TIMEOUT:
9133 /* Nothing we can do. */
9134 return;
9135 case '#':
9136 /* Discard the two bytes of checksum and stop. */
9137 c = readchar (remote_timeout);
9138 if (c >= 0)
9139 c = readchar (remote_timeout);
9140
9141 return;
9142 case '*': /* Run length encoding. */
9143 /* Discard the repeat count. */
9144 c = readchar (remote_timeout);
9145 if (c < 0)
9146 return;
9147 break;
9148 default:
9149 /* A regular character. */
9150 break;
9151 }
9152 }
9153 }
9154
9155 /* Come here after finding the start of the frame. Collect the rest
9156 into *BUF, verifying the checksum, length, and handling run-length
9157 compression. NUL terminate the buffer. If there is not enough room,
9158 expand *BUF using xrealloc.
9159
9160 Returns -1 on error, number of characters in buffer (ignoring the
9161 trailing NULL) on success. (could be extended to return one of the
9162 SERIAL status indications). */
9163
9164 static long
9165 read_frame (char **buf_p,
9166 long *sizeof_buf)
9167 {
9168 unsigned char csum;
9169 long bc;
9170 int c;
9171 char *buf = *buf_p;
9172 struct remote_state *rs = get_remote_state ();
9173
9174 csum = 0;
9175 bc = 0;
9176
9177 while (1)
9178 {
9179 c = readchar (remote_timeout);
9180 switch (c)
9181 {
9182 case SERIAL_TIMEOUT:
9183 if (remote_debug)
9184 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9185 return -1;
9186 case '$':
9187 if (remote_debug)
9188 fputs_filtered ("Saw new packet start in middle of old one\n",
9189 gdb_stdlog);
9190 return -1; /* Start a new packet, count retries. */
9191 case '#':
9192 {
9193 unsigned char pktcsum;
9194 int check_0 = 0;
9195 int check_1 = 0;
9196
9197 buf[bc] = '\0';
9198
9199 check_0 = readchar (remote_timeout);
9200 if (check_0 >= 0)
9201 check_1 = readchar (remote_timeout);
9202
9203 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9204 {
9205 if (remote_debug)
9206 fputs_filtered ("Timeout in checksum, retrying\n",
9207 gdb_stdlog);
9208 return -1;
9209 }
9210 else if (check_0 < 0 || check_1 < 0)
9211 {
9212 if (remote_debug)
9213 fputs_filtered ("Communication error in checksum\n",
9214 gdb_stdlog);
9215 return -1;
9216 }
9217
9218 /* Don't recompute the checksum; with no ack packets we
9219 don't have any way to indicate a packet retransmission
9220 is necessary. */
9221 if (rs->noack_mode)
9222 return bc;
9223
9224 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9225 if (csum == pktcsum)
9226 return bc;
9227
9228 if (remote_debug)
9229 {
9230 std::string str = escape_buffer (buf, bc);
9231
9232 fprintf_unfiltered (gdb_stdlog,
9233 "Bad checksum, sentsum=0x%x, "
9234 "csum=0x%x, buf=%s\n",
9235 pktcsum, csum, str.c_str ());
9236 }
9237 /* Number of characters in buffer ignoring trailing
9238 NULL. */
9239 return -1;
9240 }
9241 case '*': /* Run length encoding. */
9242 {
9243 int repeat;
9244
9245 csum += c;
9246 c = readchar (remote_timeout);
9247 csum += c;
9248 repeat = c - ' ' + 3; /* Compute repeat count. */
9249
9250 /* The character before ``*'' is repeated. */
9251
9252 if (repeat > 0 && repeat <= 255 && bc > 0)
9253 {
9254 if (bc + repeat - 1 >= *sizeof_buf - 1)
9255 {
9256 /* Make some more room in the buffer. */
9257 *sizeof_buf += repeat;
9258 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9259 buf = *buf_p;
9260 }
9261
9262 memset (&buf[bc], buf[bc - 1], repeat);
9263 bc += repeat;
9264 continue;
9265 }
9266
9267 buf[bc] = '\0';
9268 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9269 return -1;
9270 }
9271 default:
9272 if (bc >= *sizeof_buf - 1)
9273 {
9274 /* Make some more room in the buffer. */
9275 *sizeof_buf *= 2;
9276 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9277 buf = *buf_p;
9278 }
9279
9280 buf[bc++] = c;
9281 csum += c;
9282 continue;
9283 }
9284 }
9285 }
9286
9287 /* Read a packet from the remote machine, with error checking, and
9288 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9289 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9290 rather than timing out; this is used (in synchronous mode) to wait
9291 for a target that is is executing user code to stop. */
9292 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9293 don't have to change all the calls to getpkt to deal with the
9294 return value, because at the moment I don't know what the right
9295 thing to do it for those. */
9296 void
9297 getpkt (char **buf,
9298 long *sizeof_buf,
9299 int forever)
9300 {
9301 getpkt_sane (buf, sizeof_buf, forever);
9302 }
9303
9304
9305 /* Read a packet from the remote machine, with error checking, and
9306 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9307 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9308 rather than timing out; this is used (in synchronous mode) to wait
9309 for a target that is is executing user code to stop. If FOREVER ==
9310 0, this function is allowed to time out gracefully and return an
9311 indication of this to the caller. Otherwise return the number of
9312 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9313 enough reason to return to the caller. *IS_NOTIF is an output
9314 boolean that indicates whether *BUF holds a notification or not
9315 (a regular packet). */
9316
9317 static int
9318 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9319 int expecting_notif, int *is_notif)
9320 {
9321 struct remote_state *rs = get_remote_state ();
9322 int c;
9323 int tries;
9324 int timeout;
9325 int val = -1;
9326
9327 /* We're reading a new response. Make sure we don't look at a
9328 previously cached response. */
9329 rs->cached_wait_status = 0;
9330
9331 strcpy (*buf, "timeout");
9332
9333 if (forever)
9334 timeout = watchdog > 0 ? watchdog : -1;
9335 else if (expecting_notif)
9336 timeout = 0; /* There should already be a char in the buffer. If
9337 not, bail out. */
9338 else
9339 timeout = remote_timeout;
9340
9341 #define MAX_TRIES 3
9342
9343 /* Process any number of notifications, and then return when
9344 we get a packet. */
9345 for (;;)
9346 {
9347 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9348 times. */
9349 for (tries = 1; tries <= MAX_TRIES; tries++)
9350 {
9351 /* This can loop forever if the remote side sends us
9352 characters continuously, but if it pauses, we'll get
9353 SERIAL_TIMEOUT from readchar because of timeout. Then
9354 we'll count that as a retry.
9355
9356 Note that even when forever is set, we will only wait
9357 forever prior to the start of a packet. After that, we
9358 expect characters to arrive at a brisk pace. They should
9359 show up within remote_timeout intervals. */
9360 do
9361 c = readchar (timeout);
9362 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9363
9364 if (c == SERIAL_TIMEOUT)
9365 {
9366 if (expecting_notif)
9367 return -1; /* Don't complain, it's normal to not get
9368 anything in this case. */
9369
9370 if (forever) /* Watchdog went off? Kill the target. */
9371 {
9372 remote_unpush_target ();
9373 throw_error (TARGET_CLOSE_ERROR,
9374 _("Watchdog timeout has expired. "
9375 "Target detached."));
9376 }
9377 if (remote_debug)
9378 fputs_filtered ("Timed out.\n", gdb_stdlog);
9379 }
9380 else
9381 {
9382 /* We've found the start of a packet or notification.
9383 Now collect the data. */
9384 val = read_frame (buf, sizeof_buf);
9385 if (val >= 0)
9386 break;
9387 }
9388
9389 remote_serial_write ("-", 1);
9390 }
9391
9392 if (tries > MAX_TRIES)
9393 {
9394 /* We have tried hard enough, and just can't receive the
9395 packet/notification. Give up. */
9396 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9397
9398 /* Skip the ack char if we're in no-ack mode. */
9399 if (!rs->noack_mode)
9400 remote_serial_write ("+", 1);
9401 return -1;
9402 }
9403
9404 /* If we got an ordinary packet, return that to our caller. */
9405 if (c == '$')
9406 {
9407 if (remote_debug)
9408 {
9409 std::string str
9410 = escape_buffer (*buf,
9411 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9412
9413 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9414 str.c_str ());
9415
9416 if (val > REMOTE_DEBUG_MAX_CHAR)
9417 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9418 val - REMOTE_DEBUG_MAX_CHAR);
9419
9420 fprintf_unfiltered (gdb_stdlog, "\n");
9421 }
9422
9423 /* Skip the ack char if we're in no-ack mode. */
9424 if (!rs->noack_mode)
9425 remote_serial_write ("+", 1);
9426 if (is_notif != NULL)
9427 *is_notif = 0;
9428 return val;
9429 }
9430
9431 /* If we got a notification, handle it, and go back to looking
9432 for a packet. */
9433 else
9434 {
9435 gdb_assert (c == '%');
9436
9437 if (remote_debug)
9438 {
9439 std::string str = escape_buffer (*buf, val);
9440
9441 fprintf_unfiltered (gdb_stdlog,
9442 " Notification received: %s\n",
9443 str.c_str ());
9444 }
9445 if (is_notif != NULL)
9446 *is_notif = 1;
9447
9448 handle_notification (rs->notif_state, *buf);
9449
9450 /* Notifications require no acknowledgement. */
9451
9452 if (expecting_notif)
9453 return val;
9454 }
9455 }
9456 }
9457
9458 static int
9459 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9460 {
9461 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9462 }
9463
9464 static int
9465 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9466 int *is_notif)
9467 {
9468 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9469 is_notif);
9470 }
9471
9472 /* Check whether EVENT is a fork event for the process specified
9473 by the pid passed in DATA, and if it is, kill the fork child. */
9474
9475 static int
9476 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9477 QUEUE_ITER (stop_reply_p) *iter,
9478 stop_reply_p event,
9479 void *data)
9480 {
9481 struct queue_iter_param *param = (struct queue_iter_param *) data;
9482 int parent_pid = *(int *) param->input;
9483
9484 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9485 {
9486 struct remote_state *rs = get_remote_state ();
9487 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9488 int res;
9489
9490 res = remote_vkill (child_pid, rs);
9491 if (res != 0)
9492 error (_("Can't kill fork child process %d"), child_pid);
9493 }
9494
9495 return 1;
9496 }
9497
9498 /* Kill any new fork children of process PID that haven't been
9499 processed by follow_fork. */
9500
9501 static void
9502 kill_new_fork_children (int pid, struct remote_state *rs)
9503 {
9504 struct thread_info *thread;
9505 struct notif_client *notif = &notif_client_stop;
9506 struct queue_iter_param param;
9507
9508 /* Kill the fork child threads of any threads in process PID
9509 that are stopped at a fork event. */
9510 ALL_NON_EXITED_THREADS (thread)
9511 {
9512 struct target_waitstatus *ws = &thread->pending_follow;
9513
9514 if (is_pending_fork_parent (ws, pid, thread->ptid))
9515 {
9516 struct remote_state *rs = get_remote_state ();
9517 int child_pid = ptid_get_pid (ws->value.related_pid);
9518 int res;
9519
9520 res = remote_vkill (child_pid, rs);
9521 if (res != 0)
9522 error (_("Can't kill fork child process %d"), child_pid);
9523 }
9524 }
9525
9526 /* Check for any pending fork events (not reported or processed yet)
9527 in process PID and kill those fork child threads as well. */
9528 remote_notif_get_pending_events (notif);
9529 param.input = &pid;
9530 param.output = NULL;
9531 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9532 kill_child_of_pending_fork, &param);
9533 }
9534
9535 \f
9536 /* Target hook to kill the current inferior. */
9537
9538 void
9539 remote_target::kill ()
9540 {
9541 int res = -1;
9542 int pid = ptid_get_pid (inferior_ptid);
9543 struct remote_state *rs = get_remote_state ();
9544
9545 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9546 {
9547 /* If we're stopped while forking and we haven't followed yet,
9548 kill the child task. We need to do this before killing the
9549 parent task because if this is a vfork then the parent will
9550 be sleeping. */
9551 kill_new_fork_children (pid, rs);
9552
9553 res = remote_vkill (pid, rs);
9554 if (res == 0)
9555 {
9556 target_mourn_inferior (inferior_ptid);
9557 return;
9558 }
9559 }
9560
9561 /* If we are in 'target remote' mode and we are killing the only
9562 inferior, then we will tell gdbserver to exit and unpush the
9563 target. */
9564 if (res == -1 && !remote_multi_process_p (rs)
9565 && number_of_live_inferiors () == 1)
9566 {
9567 remote_kill_k ();
9568
9569 /* We've killed the remote end, we get to mourn it. If we are
9570 not in extended mode, mourning the inferior also unpushes
9571 remote_ops from the target stack, which closes the remote
9572 connection. */
9573 target_mourn_inferior (inferior_ptid);
9574
9575 return;
9576 }
9577
9578 error (_("Can't kill process"));
9579 }
9580
9581 /* Send a kill request to the target using the 'vKill' packet. */
9582
9583 static int
9584 remote_vkill (int pid, struct remote_state *rs)
9585 {
9586 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9587 return -1;
9588
9589 /* Tell the remote target to detach. */
9590 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9591 putpkt (rs->buf);
9592 getpkt (&rs->buf, &rs->buf_size, 0);
9593
9594 switch (packet_ok (rs->buf,
9595 &remote_protocol_packets[PACKET_vKill]))
9596 {
9597 case PACKET_OK:
9598 return 0;
9599 case PACKET_ERROR:
9600 return 1;
9601 case PACKET_UNKNOWN:
9602 return -1;
9603 default:
9604 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9605 }
9606 }
9607
9608 /* Send a kill request to the target using the 'k' packet. */
9609
9610 static void
9611 remote_kill_k (void)
9612 {
9613 /* Catch errors so the user can quit from gdb even when we
9614 aren't on speaking terms with the remote system. */
9615 TRY
9616 {
9617 putpkt ("k");
9618 }
9619 CATCH (ex, RETURN_MASK_ERROR)
9620 {
9621 if (ex.error == TARGET_CLOSE_ERROR)
9622 {
9623 /* If we got an (EOF) error that caused the target
9624 to go away, then we're done, that's what we wanted.
9625 "k" is susceptible to cause a premature EOF, given
9626 that the remote server isn't actually required to
9627 reply to "k", and it can happen that it doesn't
9628 even get to reply ACK to the "k". */
9629 return;
9630 }
9631
9632 /* Otherwise, something went wrong. We didn't actually kill
9633 the target. Just propagate the exception, and let the
9634 user or higher layers decide what to do. */
9635 throw_exception (ex);
9636 }
9637 END_CATCH
9638 }
9639
9640 void
9641 remote_target::mourn_inferior ()
9642 {
9643 struct remote_state *rs = get_remote_state ();
9644
9645 /* In 'target remote' mode with one inferior, we close the connection. */
9646 if (!rs->extended && number_of_live_inferiors () <= 1)
9647 {
9648 unpush_target (this);
9649
9650 /* remote_close takes care of doing most of the clean up. */
9651 generic_mourn_inferior ();
9652 return;
9653 }
9654
9655 /* In case we got here due to an error, but we're going to stay
9656 connected. */
9657 rs->waiting_for_stop_reply = 0;
9658
9659 /* If the current general thread belonged to the process we just
9660 detached from or has exited, the remote side current general
9661 thread becomes undefined. Considering a case like this:
9662
9663 - We just got here due to a detach.
9664 - The process that we're detaching from happens to immediately
9665 report a global breakpoint being hit in non-stop mode, in the
9666 same thread we had selected before.
9667 - GDB attaches to this process again.
9668 - This event happens to be the next event we handle.
9669
9670 GDB would consider that the current general thread didn't need to
9671 be set on the stub side (with Hg), since for all it knew,
9672 GENERAL_THREAD hadn't changed.
9673
9674 Notice that although in all-stop mode, the remote server always
9675 sets the current thread to the thread reporting the stop event,
9676 that doesn't happen in non-stop mode; in non-stop, the stub *must
9677 not* change the current thread when reporting a breakpoint hit,
9678 due to the decoupling of event reporting and event handling.
9679
9680 To keep things simple, we always invalidate our notion of the
9681 current thread. */
9682 record_currthread (rs, minus_one_ptid);
9683
9684 /* Call common code to mark the inferior as not running. */
9685 generic_mourn_inferior ();
9686
9687 if (!have_inferiors ())
9688 {
9689 if (!remote_multi_process_p (rs))
9690 {
9691 /* Check whether the target is running now - some remote stubs
9692 automatically restart after kill. */
9693 putpkt ("?");
9694 getpkt (&rs->buf, &rs->buf_size, 0);
9695
9696 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9697 {
9698 /* Assume that the target has been restarted. Set
9699 inferior_ptid so that bits of core GDB realizes
9700 there's something here, e.g., so that the user can
9701 say "kill" again. */
9702 inferior_ptid = magic_null_ptid;
9703 }
9704 }
9705 }
9706 }
9707
9708 bool
9709 extended_remote_target::supports_disable_randomization ()
9710 {
9711 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9712 }
9713
9714 static void
9715 extended_remote_disable_randomization (int val)
9716 {
9717 struct remote_state *rs = get_remote_state ();
9718 char *reply;
9719
9720 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9721 val);
9722 putpkt (rs->buf);
9723 reply = remote_get_noisy_reply ();
9724 if (*reply == '\0')
9725 error (_("Target does not support QDisableRandomization."));
9726 if (strcmp (reply, "OK") != 0)
9727 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9728 }
9729
9730 static int
9731 extended_remote_run (const std::string &args)
9732 {
9733 struct remote_state *rs = get_remote_state ();
9734 int len;
9735 const char *remote_exec_file = get_remote_exec_file ();
9736
9737 /* If the user has disabled vRun support, or we have detected that
9738 support is not available, do not try it. */
9739 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9740 return -1;
9741
9742 strcpy (rs->buf, "vRun;");
9743 len = strlen (rs->buf);
9744
9745 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9746 error (_("Remote file name too long for run packet"));
9747 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9748 strlen (remote_exec_file));
9749
9750 if (!args.empty ())
9751 {
9752 int i;
9753
9754 gdb_argv argv (args.c_str ());
9755 for (i = 0; argv[i] != NULL; i++)
9756 {
9757 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9758 error (_("Argument list too long for run packet"));
9759 rs->buf[len++] = ';';
9760 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9761 strlen (argv[i]));
9762 }
9763 }
9764
9765 rs->buf[len++] = '\0';
9766
9767 putpkt (rs->buf);
9768 getpkt (&rs->buf, &rs->buf_size, 0);
9769
9770 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9771 {
9772 case PACKET_OK:
9773 /* We have a wait response. All is well. */
9774 return 0;
9775 case PACKET_UNKNOWN:
9776 return -1;
9777 case PACKET_ERROR:
9778 if (remote_exec_file[0] == '\0')
9779 error (_("Running the default executable on the remote target failed; "
9780 "try \"set remote exec-file\"?"));
9781 else
9782 error (_("Running \"%s\" on the remote target failed"),
9783 remote_exec_file);
9784 default:
9785 gdb_assert_not_reached (_("bad switch"));
9786 }
9787 }
9788
9789 /* Helper function to send set/unset environment packets. ACTION is
9790 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9791 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9792 sent. */
9793
9794 static void
9795 send_environment_packet (struct remote_state *rs,
9796 const char *action,
9797 const char *packet,
9798 const char *value)
9799 {
9800 /* Convert the environment variable to an hex string, which
9801 is the best format to be transmitted over the wire. */
9802 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9803 strlen (value));
9804
9805 xsnprintf (rs->buf, get_remote_packet_size (),
9806 "%s:%s", packet, encoded_value.c_str ());
9807
9808 putpkt (rs->buf);
9809 getpkt (&rs->buf, &rs->buf_size, 0);
9810 if (strcmp (rs->buf, "OK") != 0)
9811 warning (_("Unable to %s environment variable '%s' on remote."),
9812 action, value);
9813 }
9814
9815 /* Helper function to handle the QEnvironment* packets. */
9816
9817 static void
9818 extended_remote_environment_support (struct remote_state *rs)
9819 {
9820 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9821 {
9822 putpkt ("QEnvironmentReset");
9823 getpkt (&rs->buf, &rs->buf_size, 0);
9824 if (strcmp (rs->buf, "OK") != 0)
9825 warning (_("Unable to reset environment on remote."));
9826 }
9827
9828 gdb_environ *e = &current_inferior ()->environment;
9829
9830 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9831 for (const std::string &el : e->user_set_env ())
9832 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9833 el.c_str ());
9834
9835 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9836 for (const std::string &el : e->user_unset_env ())
9837 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9838 }
9839
9840 /* Helper function to set the current working directory for the
9841 inferior in the remote target. */
9842
9843 static void
9844 extended_remote_set_inferior_cwd (struct remote_state *rs)
9845 {
9846 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9847 {
9848 const char *inferior_cwd = get_inferior_cwd ();
9849
9850 if (inferior_cwd != NULL)
9851 {
9852 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9853 strlen (inferior_cwd));
9854
9855 xsnprintf (rs->buf, get_remote_packet_size (),
9856 "QSetWorkingDir:%s", hexpath.c_str ());
9857 }
9858 else
9859 {
9860 /* An empty inferior_cwd means that the user wants us to
9861 reset the remote server's inferior's cwd. */
9862 xsnprintf (rs->buf, get_remote_packet_size (),
9863 "QSetWorkingDir:");
9864 }
9865
9866 putpkt (rs->buf);
9867 getpkt (&rs->buf, &rs->buf_size, 0);
9868 if (packet_ok (rs->buf,
9869 &remote_protocol_packets[PACKET_QSetWorkingDir])
9870 != PACKET_OK)
9871 error (_("\
9872 Remote replied unexpectedly while setting the inferior's working\n\
9873 directory: %s"),
9874 rs->buf);
9875
9876 }
9877 }
9878
9879 /* In the extended protocol we want to be able to do things like
9880 "run" and have them basically work as expected. So we need
9881 a special create_inferior function. We support changing the
9882 executable file and the command line arguments, but not the
9883 environment. */
9884
9885 void
9886 extended_remote_target::create_inferior (const char *exec_file,
9887 const std::string &args,
9888 char **env, int from_tty)
9889 {
9890 int run_worked;
9891 char *stop_reply;
9892 struct remote_state *rs = get_remote_state ();
9893 const char *remote_exec_file = get_remote_exec_file ();
9894
9895 /* If running asynchronously, register the target file descriptor
9896 with the event loop. */
9897 if (target_can_async_p ())
9898 target_async (1);
9899
9900 /* Disable address space randomization if requested (and supported). */
9901 if (supports_disable_randomization ())
9902 extended_remote_disable_randomization (disable_randomization);
9903
9904 /* If startup-with-shell is on, we inform gdbserver to start the
9905 remote inferior using a shell. */
9906 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9907 {
9908 xsnprintf (rs->buf, get_remote_packet_size (),
9909 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9910 putpkt (rs->buf);
9911 getpkt (&rs->buf, &rs->buf_size, 0);
9912 if (strcmp (rs->buf, "OK") != 0)
9913 error (_("\
9914 Remote replied unexpectedly while setting startup-with-shell: %s"),
9915 rs->buf);
9916 }
9917
9918 extended_remote_environment_support (rs);
9919
9920 extended_remote_set_inferior_cwd (rs);
9921
9922 /* Now restart the remote server. */
9923 run_worked = extended_remote_run (args) != -1;
9924 if (!run_worked)
9925 {
9926 /* vRun was not supported. Fail if we need it to do what the
9927 user requested. */
9928 if (remote_exec_file[0])
9929 error (_("Remote target does not support \"set remote exec-file\""));
9930 if (!args.empty ())
9931 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9932
9933 /* Fall back to "R". */
9934 extended_remote_restart ();
9935 }
9936
9937 if (!have_inferiors ())
9938 {
9939 /* Clean up from the last time we ran, before we mark the target
9940 running again. This will mark breakpoints uninserted, and
9941 get_offsets may insert breakpoints. */
9942 init_thread_list ();
9943 init_wait_for_inferior ();
9944 }
9945
9946 /* vRun's success return is a stop reply. */
9947 stop_reply = run_worked ? rs->buf : NULL;
9948 add_current_inferior_and_thread (stop_reply);
9949
9950 /* Get updated offsets, if the stub uses qOffsets. */
9951 get_offsets ();
9952 }
9953 \f
9954
9955 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9956 the list of conditions (in agent expression bytecode format), if any, the
9957 target needs to evaluate. The output is placed into the packet buffer
9958 started from BUF and ended at BUF_END. */
9959
9960 static int
9961 remote_add_target_side_condition (struct gdbarch *gdbarch,
9962 struct bp_target_info *bp_tgt, char *buf,
9963 char *buf_end)
9964 {
9965 if (bp_tgt->conditions.empty ())
9966 return 0;
9967
9968 buf += strlen (buf);
9969 xsnprintf (buf, buf_end - buf, "%s", ";");
9970 buf++;
9971
9972 /* Send conditions to the target. */
9973 for (agent_expr *aexpr : bp_tgt->conditions)
9974 {
9975 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9976 buf += strlen (buf);
9977 for (int i = 0; i < aexpr->len; ++i)
9978 buf = pack_hex_byte (buf, aexpr->buf[i]);
9979 *buf = '\0';
9980 }
9981 return 0;
9982 }
9983
9984 static void
9985 remote_add_target_side_commands (struct gdbarch *gdbarch,
9986 struct bp_target_info *bp_tgt, char *buf)
9987 {
9988 if (bp_tgt->tcommands.empty ())
9989 return;
9990
9991 buf += strlen (buf);
9992
9993 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9994 buf += strlen (buf);
9995
9996 /* Concatenate all the agent expressions that are commands into the
9997 cmds parameter. */
9998 for (agent_expr *aexpr : bp_tgt->tcommands)
9999 {
10000 sprintf (buf, "X%x,", aexpr->len);
10001 buf += strlen (buf);
10002 for (int i = 0; i < aexpr->len; ++i)
10003 buf = pack_hex_byte (buf, aexpr->buf[i]);
10004 *buf = '\0';
10005 }
10006 }
10007
10008 /* Insert a breakpoint. On targets that have software breakpoint
10009 support, we ask the remote target to do the work; on targets
10010 which don't, we insert a traditional memory breakpoint. */
10011
10012 int
10013 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10014 struct bp_target_info *bp_tgt)
10015 {
10016 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10017 If it succeeds, then set the support to PACKET_ENABLE. If it
10018 fails, and the user has explicitly requested the Z support then
10019 report an error, otherwise, mark it disabled and go on. */
10020
10021 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10022 {
10023 CORE_ADDR addr = bp_tgt->reqstd_address;
10024 struct remote_state *rs;
10025 char *p, *endbuf;
10026
10027 /* Make sure the remote is pointing at the right process, if
10028 necessary. */
10029 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10030 set_general_process ();
10031
10032 rs = get_remote_state ();
10033 p = rs->buf;
10034 endbuf = rs->buf + get_remote_packet_size ();
10035
10036 *(p++) = 'Z';
10037 *(p++) = '0';
10038 *(p++) = ',';
10039 addr = (ULONGEST) remote_address_masked (addr);
10040 p += hexnumstr (p, addr);
10041 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10042
10043 if (supports_evaluation_of_breakpoint_conditions ())
10044 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10045
10046 if (can_run_breakpoint_commands ())
10047 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10048
10049 putpkt (rs->buf);
10050 getpkt (&rs->buf, &rs->buf_size, 0);
10051
10052 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10053 {
10054 case PACKET_ERROR:
10055 return -1;
10056 case PACKET_OK:
10057 return 0;
10058 case PACKET_UNKNOWN:
10059 break;
10060 }
10061 }
10062
10063 /* If this breakpoint has target-side commands but this stub doesn't
10064 support Z0 packets, throw error. */
10065 if (!bp_tgt->tcommands.empty ())
10066 throw_error (NOT_SUPPORTED_ERROR, _("\
10067 Target doesn't support breakpoints that have target side commands."));
10068
10069 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10070 }
10071
10072 int
10073 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10074 struct bp_target_info *bp_tgt,
10075 enum remove_bp_reason reason)
10076 {
10077 CORE_ADDR addr = bp_tgt->placed_address;
10078 struct remote_state *rs = get_remote_state ();
10079
10080 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10081 {
10082 char *p = rs->buf;
10083 char *endbuf = rs->buf + get_remote_packet_size ();
10084
10085 /* Make sure the remote is pointing at the right process, if
10086 necessary. */
10087 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10088 set_general_process ();
10089
10090 *(p++) = 'z';
10091 *(p++) = '0';
10092 *(p++) = ',';
10093
10094 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10095 p += hexnumstr (p, addr);
10096 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10097
10098 putpkt (rs->buf);
10099 getpkt (&rs->buf, &rs->buf_size, 0);
10100
10101 return (rs->buf[0] == 'E');
10102 }
10103
10104 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10105 }
10106
10107 static enum Z_packet_type
10108 watchpoint_to_Z_packet (int type)
10109 {
10110 switch (type)
10111 {
10112 case hw_write:
10113 return Z_PACKET_WRITE_WP;
10114 break;
10115 case hw_read:
10116 return Z_PACKET_READ_WP;
10117 break;
10118 case hw_access:
10119 return Z_PACKET_ACCESS_WP;
10120 break;
10121 default:
10122 internal_error (__FILE__, __LINE__,
10123 _("hw_bp_to_z: bad watchpoint type %d"), type);
10124 }
10125 }
10126
10127 int
10128 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10129 enum target_hw_bp_type type, struct expression *cond)
10130 {
10131 struct remote_state *rs = get_remote_state ();
10132 char *endbuf = rs->buf + get_remote_packet_size ();
10133 char *p;
10134 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10135
10136 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10137 return 1;
10138
10139 /* Make sure the remote is pointing at the right process, if
10140 necessary. */
10141 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10142 set_general_process ();
10143
10144 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10145 p = strchr (rs->buf, '\0');
10146 addr = remote_address_masked (addr);
10147 p += hexnumstr (p, (ULONGEST) addr);
10148 xsnprintf (p, endbuf - p, ",%x", len);
10149
10150 putpkt (rs->buf);
10151 getpkt (&rs->buf, &rs->buf_size, 0);
10152
10153 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10154 {
10155 case PACKET_ERROR:
10156 return -1;
10157 case PACKET_UNKNOWN:
10158 return 1;
10159 case PACKET_OK:
10160 return 0;
10161 }
10162 internal_error (__FILE__, __LINE__,
10163 _("remote_insert_watchpoint: reached end of function"));
10164 }
10165
10166 bool
10167 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10168 CORE_ADDR start, int length)
10169 {
10170 CORE_ADDR diff = remote_address_masked (addr - start);
10171
10172 return diff < length;
10173 }
10174
10175
10176 int
10177 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10178 enum target_hw_bp_type type, struct expression *cond)
10179 {
10180 struct remote_state *rs = get_remote_state ();
10181 char *endbuf = rs->buf + get_remote_packet_size ();
10182 char *p;
10183 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10184
10185 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10186 return -1;
10187
10188 /* Make sure the remote is pointing at the right process, if
10189 necessary. */
10190 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10191 set_general_process ();
10192
10193 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10194 p = strchr (rs->buf, '\0');
10195 addr = remote_address_masked (addr);
10196 p += hexnumstr (p, (ULONGEST) addr);
10197 xsnprintf (p, endbuf - p, ",%x", len);
10198 putpkt (rs->buf);
10199 getpkt (&rs->buf, &rs->buf_size, 0);
10200
10201 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10202 {
10203 case PACKET_ERROR:
10204 case PACKET_UNKNOWN:
10205 return -1;
10206 case PACKET_OK:
10207 return 0;
10208 }
10209 internal_error (__FILE__, __LINE__,
10210 _("remote_remove_watchpoint: reached end of function"));
10211 }
10212
10213
10214 int remote_hw_watchpoint_limit = -1;
10215 int remote_hw_watchpoint_length_limit = -1;
10216 int remote_hw_breakpoint_limit = -1;
10217
10218 int
10219 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10220 {
10221 if (remote_hw_watchpoint_length_limit == 0)
10222 return 0;
10223 else if (remote_hw_watchpoint_length_limit < 0)
10224 return 1;
10225 else if (len <= remote_hw_watchpoint_length_limit)
10226 return 1;
10227 else
10228 return 0;
10229 }
10230
10231 int
10232 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10233 {
10234 if (type == bp_hardware_breakpoint)
10235 {
10236 if (remote_hw_breakpoint_limit == 0)
10237 return 0;
10238 else if (remote_hw_breakpoint_limit < 0)
10239 return 1;
10240 else if (cnt <= remote_hw_breakpoint_limit)
10241 return 1;
10242 }
10243 else
10244 {
10245 if (remote_hw_watchpoint_limit == 0)
10246 return 0;
10247 else if (remote_hw_watchpoint_limit < 0)
10248 return 1;
10249 else if (ot)
10250 return -1;
10251 else if (cnt <= remote_hw_watchpoint_limit)
10252 return 1;
10253 }
10254 return -1;
10255 }
10256
10257 /* The to_stopped_by_sw_breakpoint method of target remote. */
10258
10259 bool
10260 remote_target::stopped_by_sw_breakpoint ()
10261 {
10262 struct thread_info *thread = inferior_thread ();
10263
10264 return (thread->priv != NULL
10265 && (get_remote_thread_info (thread)->stop_reason
10266 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10267 }
10268
10269 /* The to_supports_stopped_by_sw_breakpoint method of target
10270 remote. */
10271
10272 bool
10273 remote_target::supports_stopped_by_sw_breakpoint ()
10274 {
10275 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10276 }
10277
10278 /* The to_stopped_by_hw_breakpoint method of target remote. */
10279
10280 bool
10281 remote_target::stopped_by_hw_breakpoint ()
10282 {
10283 struct thread_info *thread = inferior_thread ();
10284
10285 return (thread->priv != NULL
10286 && (get_remote_thread_info (thread)->stop_reason
10287 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10288 }
10289
10290 /* The to_supports_stopped_by_hw_breakpoint method of target
10291 remote. */
10292
10293 bool
10294 remote_target::supports_stopped_by_hw_breakpoint ()
10295 {
10296 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10297 }
10298
10299 bool
10300 remote_target::stopped_by_watchpoint ()
10301 {
10302 struct thread_info *thread = inferior_thread ();
10303
10304 return (thread->priv != NULL
10305 && (get_remote_thread_info (thread)->stop_reason
10306 == TARGET_STOPPED_BY_WATCHPOINT));
10307 }
10308
10309 bool
10310 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10311 {
10312 struct thread_info *thread = inferior_thread ();
10313
10314 if (thread->priv != NULL
10315 && (get_remote_thread_info (thread)->stop_reason
10316 == TARGET_STOPPED_BY_WATCHPOINT))
10317 {
10318 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10319 return true;
10320 }
10321
10322 return false;
10323 }
10324
10325
10326 int
10327 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10328 struct bp_target_info *bp_tgt)
10329 {
10330 CORE_ADDR addr = bp_tgt->reqstd_address;
10331 struct remote_state *rs;
10332 char *p, *endbuf;
10333 char *message;
10334
10335 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10336 return -1;
10337
10338 /* Make sure the remote is pointing at the right process, if
10339 necessary. */
10340 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10341 set_general_process ();
10342
10343 rs = get_remote_state ();
10344 p = rs->buf;
10345 endbuf = rs->buf + get_remote_packet_size ();
10346
10347 *(p++) = 'Z';
10348 *(p++) = '1';
10349 *(p++) = ',';
10350
10351 addr = remote_address_masked (addr);
10352 p += hexnumstr (p, (ULONGEST) addr);
10353 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10354
10355 if (supports_evaluation_of_breakpoint_conditions ())
10356 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10357
10358 if (can_run_breakpoint_commands ())
10359 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10360
10361 putpkt (rs->buf);
10362 getpkt (&rs->buf, &rs->buf_size, 0);
10363
10364 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10365 {
10366 case PACKET_ERROR:
10367 if (rs->buf[1] == '.')
10368 {
10369 message = strchr (rs->buf + 2, '.');
10370 if (message)
10371 error (_("Remote failure reply: %s"), message + 1);
10372 }
10373 return -1;
10374 case PACKET_UNKNOWN:
10375 return -1;
10376 case PACKET_OK:
10377 return 0;
10378 }
10379 internal_error (__FILE__, __LINE__,
10380 _("remote_insert_hw_breakpoint: reached end of function"));
10381 }
10382
10383
10384 int
10385 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10386 struct bp_target_info *bp_tgt)
10387 {
10388 CORE_ADDR addr;
10389 struct remote_state *rs = get_remote_state ();
10390 char *p = rs->buf;
10391 char *endbuf = rs->buf + get_remote_packet_size ();
10392
10393 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10394 return -1;
10395
10396 /* Make sure the remote is pointing at the right process, if
10397 necessary. */
10398 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10399 set_general_process ();
10400
10401 *(p++) = 'z';
10402 *(p++) = '1';
10403 *(p++) = ',';
10404
10405 addr = remote_address_masked (bp_tgt->placed_address);
10406 p += hexnumstr (p, (ULONGEST) addr);
10407 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10408
10409 putpkt (rs->buf);
10410 getpkt (&rs->buf, &rs->buf_size, 0);
10411
10412 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10413 {
10414 case PACKET_ERROR:
10415 case PACKET_UNKNOWN:
10416 return -1;
10417 case PACKET_OK:
10418 return 0;
10419 }
10420 internal_error (__FILE__, __LINE__,
10421 _("remote_remove_hw_breakpoint: reached end of function"));
10422 }
10423
10424 /* Verify memory using the "qCRC:" request. */
10425
10426 int
10427 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10428 {
10429 struct remote_state *rs = get_remote_state ();
10430 unsigned long host_crc, target_crc;
10431 char *tmp;
10432
10433 /* It doesn't make sense to use qCRC if the remote target is
10434 connected but not running. */
10435 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10436 {
10437 enum packet_result result;
10438
10439 /* Make sure the remote is pointing at the right process. */
10440 set_general_process ();
10441
10442 /* FIXME: assumes lma can fit into long. */
10443 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10444 (long) lma, (long) size);
10445 putpkt (rs->buf);
10446
10447 /* Be clever; compute the host_crc before waiting for target
10448 reply. */
10449 host_crc = xcrc32 (data, size, 0xffffffff);
10450
10451 getpkt (&rs->buf, &rs->buf_size, 0);
10452
10453 result = packet_ok (rs->buf,
10454 &remote_protocol_packets[PACKET_qCRC]);
10455 if (result == PACKET_ERROR)
10456 return -1;
10457 else if (result == PACKET_OK)
10458 {
10459 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10460 target_crc = target_crc * 16 + fromhex (*tmp);
10461
10462 return (host_crc == target_crc);
10463 }
10464 }
10465
10466 return simple_verify_memory (this, data, lma, size);
10467 }
10468
10469 /* compare-sections command
10470
10471 With no arguments, compares each loadable section in the exec bfd
10472 with the same memory range on the target, and reports mismatches.
10473 Useful for verifying the image on the target against the exec file. */
10474
10475 static void
10476 compare_sections_command (const char *args, int from_tty)
10477 {
10478 asection *s;
10479 const char *sectname;
10480 bfd_size_type size;
10481 bfd_vma lma;
10482 int matched = 0;
10483 int mismatched = 0;
10484 int res;
10485 int read_only = 0;
10486
10487 if (!exec_bfd)
10488 error (_("command cannot be used without an exec file"));
10489
10490 /* Make sure the remote is pointing at the right process. */
10491 set_general_process ();
10492
10493 if (args != NULL && strcmp (args, "-r") == 0)
10494 {
10495 read_only = 1;
10496 args = NULL;
10497 }
10498
10499 for (s = exec_bfd->sections; s; s = s->next)
10500 {
10501 if (!(s->flags & SEC_LOAD))
10502 continue; /* Skip non-loadable section. */
10503
10504 if (read_only && (s->flags & SEC_READONLY) == 0)
10505 continue; /* Skip writeable sections */
10506
10507 size = bfd_get_section_size (s);
10508 if (size == 0)
10509 continue; /* Skip zero-length section. */
10510
10511 sectname = bfd_get_section_name (exec_bfd, s);
10512 if (args && strcmp (args, sectname) != 0)
10513 continue; /* Not the section selected by user. */
10514
10515 matched = 1; /* Do this section. */
10516 lma = s->lma;
10517
10518 gdb::byte_vector sectdata (size);
10519 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10520
10521 res = target_verify_memory (sectdata.data (), lma, size);
10522
10523 if (res == -1)
10524 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10525 paddress (target_gdbarch (), lma),
10526 paddress (target_gdbarch (), lma + size));
10527
10528 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10529 paddress (target_gdbarch (), lma),
10530 paddress (target_gdbarch (), lma + size));
10531 if (res)
10532 printf_filtered ("matched.\n");
10533 else
10534 {
10535 printf_filtered ("MIS-MATCHED!\n");
10536 mismatched++;
10537 }
10538 }
10539 if (mismatched > 0)
10540 warning (_("One or more sections of the target image does not match\n\
10541 the loaded file\n"));
10542 if (args && !matched)
10543 printf_filtered (_("No loaded section named '%s'.\n"), args);
10544 }
10545
10546 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10547 into remote target. The number of bytes written to the remote
10548 target is returned, or -1 for error. */
10549
10550 static enum target_xfer_status
10551 remote_write_qxfer (const char *object_name,
10552 const char *annex, const gdb_byte *writebuf,
10553 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10554 struct packet_config *packet)
10555 {
10556 int i, buf_len;
10557 ULONGEST n;
10558 struct remote_state *rs = get_remote_state ();
10559 int max_size = get_memory_write_packet_size ();
10560
10561 if (packet_config_support (packet) == PACKET_DISABLE)
10562 return TARGET_XFER_E_IO;
10563
10564 /* Insert header. */
10565 i = snprintf (rs->buf, max_size,
10566 "qXfer:%s:write:%s:%s:",
10567 object_name, annex ? annex : "",
10568 phex_nz (offset, sizeof offset));
10569 max_size -= (i + 1);
10570
10571 /* Escape as much data as fits into rs->buf. */
10572 buf_len = remote_escape_output
10573 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10574
10575 if (putpkt_binary (rs->buf, i + buf_len) < 0
10576 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10577 || packet_ok (rs->buf, packet) != PACKET_OK)
10578 return TARGET_XFER_E_IO;
10579
10580 unpack_varlen_hex (rs->buf, &n);
10581
10582 *xfered_len = n;
10583 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10584 }
10585
10586 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10587 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10588 number of bytes read is returned, or 0 for EOF, or -1 for error.
10589 The number of bytes read may be less than LEN without indicating an
10590 EOF. PACKET is checked and updated to indicate whether the remote
10591 target supports this object. */
10592
10593 static enum target_xfer_status
10594 remote_read_qxfer (const char *object_name,
10595 const char *annex,
10596 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10597 ULONGEST *xfered_len,
10598 struct packet_config *packet)
10599 {
10600 struct remote_state *rs = get_remote_state ();
10601 LONGEST i, n, packet_len;
10602
10603 if (packet_config_support (packet) == PACKET_DISABLE)
10604 return TARGET_XFER_E_IO;
10605
10606 /* Check whether we've cached an end-of-object packet that matches
10607 this request. */
10608 if (rs->finished_object)
10609 {
10610 if (strcmp (object_name, rs->finished_object) == 0
10611 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10612 && offset == rs->finished_offset)
10613 return TARGET_XFER_EOF;
10614
10615
10616 /* Otherwise, we're now reading something different. Discard
10617 the cache. */
10618 xfree (rs->finished_object);
10619 xfree (rs->finished_annex);
10620 rs->finished_object = NULL;
10621 rs->finished_annex = NULL;
10622 }
10623
10624 /* Request only enough to fit in a single packet. The actual data
10625 may not, since we don't know how much of it will need to be escaped;
10626 the target is free to respond with slightly less data. We subtract
10627 five to account for the response type and the protocol frame. */
10628 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10629 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10630 object_name, annex ? annex : "",
10631 phex_nz (offset, sizeof offset),
10632 phex_nz (n, sizeof n));
10633 i = putpkt (rs->buf);
10634 if (i < 0)
10635 return TARGET_XFER_E_IO;
10636
10637 rs->buf[0] = '\0';
10638 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10639 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10640 return TARGET_XFER_E_IO;
10641
10642 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10643 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10644
10645 /* 'm' means there is (or at least might be) more data after this
10646 batch. That does not make sense unless there's at least one byte
10647 of data in this reply. */
10648 if (rs->buf[0] == 'm' && packet_len == 1)
10649 error (_("Remote qXfer reply contained no data."));
10650
10651 /* Got some data. */
10652 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10653 packet_len - 1, readbuf, n);
10654
10655 /* 'l' is an EOF marker, possibly including a final block of data,
10656 or possibly empty. If we have the final block of a non-empty
10657 object, record this fact to bypass a subsequent partial read. */
10658 if (rs->buf[0] == 'l' && offset + i > 0)
10659 {
10660 rs->finished_object = xstrdup (object_name);
10661 rs->finished_annex = xstrdup (annex ? annex : "");
10662 rs->finished_offset = offset + i;
10663 }
10664
10665 if (i == 0)
10666 return TARGET_XFER_EOF;
10667 else
10668 {
10669 *xfered_len = i;
10670 return TARGET_XFER_OK;
10671 }
10672 }
10673
10674 enum target_xfer_status
10675 remote_target::xfer_partial (enum target_object object,
10676 const char *annex, gdb_byte *readbuf,
10677 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10678 ULONGEST *xfered_len)
10679 {
10680 struct remote_state *rs;
10681 int i;
10682 char *p2;
10683 char query_type;
10684 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10685
10686 set_remote_traceframe ();
10687 set_general_thread (inferior_ptid);
10688
10689 rs = get_remote_state ();
10690
10691 /* Handle memory using the standard memory routines. */
10692 if (object == TARGET_OBJECT_MEMORY)
10693 {
10694 /* If the remote target is connected but not running, we should
10695 pass this request down to a lower stratum (e.g. the executable
10696 file). */
10697 if (!target_has_execution)
10698 return TARGET_XFER_EOF;
10699
10700 if (writebuf != NULL)
10701 return remote_write_bytes (offset, writebuf, len, unit_size,
10702 xfered_len);
10703 else
10704 return remote_read_bytes (this, offset, readbuf, len, unit_size,
10705 xfered_len);
10706 }
10707
10708 /* Handle SPU memory using qxfer packets. */
10709 if (object == TARGET_OBJECT_SPU)
10710 {
10711 if (readbuf)
10712 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10713 xfered_len, &remote_protocol_packets
10714 [PACKET_qXfer_spu_read]);
10715 else
10716 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10717 xfered_len, &remote_protocol_packets
10718 [PACKET_qXfer_spu_write]);
10719 }
10720
10721 /* Handle extra signal info using qxfer packets. */
10722 if (object == TARGET_OBJECT_SIGNAL_INFO)
10723 {
10724 if (readbuf)
10725 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10726 xfered_len, &remote_protocol_packets
10727 [PACKET_qXfer_siginfo_read]);
10728 else
10729 return remote_write_qxfer ("siginfo", annex,
10730 writebuf, offset, len, xfered_len,
10731 &remote_protocol_packets
10732 [PACKET_qXfer_siginfo_write]);
10733 }
10734
10735 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10736 {
10737 if (readbuf)
10738 return remote_read_qxfer ("statictrace", annex,
10739 readbuf, offset, len, xfered_len,
10740 &remote_protocol_packets
10741 [PACKET_qXfer_statictrace_read]);
10742 else
10743 return TARGET_XFER_E_IO;
10744 }
10745
10746 /* Only handle flash writes. */
10747 if (writebuf != NULL)
10748 {
10749 switch (object)
10750 {
10751 case TARGET_OBJECT_FLASH:
10752 return remote_flash_write (this, offset, len, xfered_len,
10753 writebuf);
10754
10755 default:
10756 return TARGET_XFER_E_IO;
10757 }
10758 }
10759
10760 /* Map pre-existing objects onto letters. DO NOT do this for new
10761 objects!!! Instead specify new query packets. */
10762 switch (object)
10763 {
10764 case TARGET_OBJECT_AVR:
10765 query_type = 'R';
10766 break;
10767
10768 case TARGET_OBJECT_AUXV:
10769 gdb_assert (annex == NULL);
10770 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10771 xfered_len,
10772 &remote_protocol_packets[PACKET_qXfer_auxv]);
10773
10774 case TARGET_OBJECT_AVAILABLE_FEATURES:
10775 return remote_read_qxfer
10776 ("features", annex, readbuf, offset, len, xfered_len,
10777 &remote_protocol_packets[PACKET_qXfer_features]);
10778
10779 case TARGET_OBJECT_LIBRARIES:
10780 return remote_read_qxfer
10781 ("libraries", annex, readbuf, offset, len, xfered_len,
10782 &remote_protocol_packets[PACKET_qXfer_libraries]);
10783
10784 case TARGET_OBJECT_LIBRARIES_SVR4:
10785 return remote_read_qxfer
10786 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10787 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10788
10789 case TARGET_OBJECT_MEMORY_MAP:
10790 gdb_assert (annex == NULL);
10791 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10792 xfered_len,
10793 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10794
10795 case TARGET_OBJECT_OSDATA:
10796 /* Should only get here if we're connected. */
10797 gdb_assert (rs->remote_desc);
10798 return remote_read_qxfer
10799 ("osdata", annex, readbuf, offset, len, xfered_len,
10800 &remote_protocol_packets[PACKET_qXfer_osdata]);
10801
10802 case TARGET_OBJECT_THREADS:
10803 gdb_assert (annex == NULL);
10804 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10805 xfered_len,
10806 &remote_protocol_packets[PACKET_qXfer_threads]);
10807
10808 case TARGET_OBJECT_TRACEFRAME_INFO:
10809 gdb_assert (annex == NULL);
10810 return remote_read_qxfer
10811 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
10812 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10813
10814 case TARGET_OBJECT_FDPIC:
10815 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
10816 xfered_len,
10817 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10818
10819 case TARGET_OBJECT_OPENVMS_UIB:
10820 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
10821 xfered_len,
10822 &remote_protocol_packets[PACKET_qXfer_uib]);
10823
10824 case TARGET_OBJECT_BTRACE:
10825 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
10826 xfered_len,
10827 &remote_protocol_packets[PACKET_qXfer_btrace]);
10828
10829 case TARGET_OBJECT_BTRACE_CONF:
10830 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
10831 len, xfered_len,
10832 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10833
10834 case TARGET_OBJECT_EXEC_FILE:
10835 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
10836 len, xfered_len,
10837 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10838
10839 default:
10840 return TARGET_XFER_E_IO;
10841 }
10842
10843 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10844 large enough let the caller deal with it. */
10845 if (len < get_remote_packet_size ())
10846 return TARGET_XFER_E_IO;
10847 len = get_remote_packet_size ();
10848
10849 /* Except for querying the minimum buffer size, target must be open. */
10850 if (!rs->remote_desc)
10851 error (_("remote query is only available after target open"));
10852
10853 gdb_assert (annex != NULL);
10854 gdb_assert (readbuf != NULL);
10855
10856 p2 = rs->buf;
10857 *p2++ = 'q';
10858 *p2++ = query_type;
10859
10860 /* We used one buffer char for the remote protocol q command and
10861 another for the query type. As the remote protocol encapsulation
10862 uses 4 chars plus one extra in case we are debugging
10863 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10864 string. */
10865 i = 0;
10866 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10867 {
10868 /* Bad caller may have sent forbidden characters. */
10869 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10870 *p2++ = annex[i];
10871 i++;
10872 }
10873 *p2 = '\0';
10874 gdb_assert (annex[i] == '\0');
10875
10876 i = putpkt (rs->buf);
10877 if (i < 0)
10878 return TARGET_XFER_E_IO;
10879
10880 getpkt (&rs->buf, &rs->buf_size, 0);
10881 strcpy ((char *) readbuf, rs->buf);
10882
10883 *xfered_len = strlen ((char *) readbuf);
10884 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10885 }
10886
10887 /* Implementation of to_get_memory_xfer_limit. */
10888
10889 ULONGEST
10890 remote_target::get_memory_xfer_limit ()
10891 {
10892 return get_memory_write_packet_size ();
10893 }
10894
10895 int
10896 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
10897 const gdb_byte *pattern, ULONGEST pattern_len,
10898 CORE_ADDR *found_addrp)
10899 {
10900 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10901 struct remote_state *rs = get_remote_state ();
10902 int max_size = get_memory_write_packet_size ();
10903 struct packet_config *packet =
10904 &remote_protocol_packets[PACKET_qSearch_memory];
10905 /* Number of packet bytes used to encode the pattern;
10906 this could be more than PATTERN_LEN due to escape characters. */
10907 int escaped_pattern_len;
10908 /* Amount of pattern that was encodable in the packet. */
10909 int used_pattern_len;
10910 int i;
10911 int found;
10912 ULONGEST found_addr;
10913
10914 /* Don't go to the target if we don't have to. This is done before
10915 checking packet_config_support to avoid the possibility that a
10916 success for this edge case means the facility works in
10917 general. */
10918 if (pattern_len > search_space_len)
10919 return 0;
10920 if (pattern_len == 0)
10921 {
10922 *found_addrp = start_addr;
10923 return 1;
10924 }
10925
10926 /* If we already know the packet isn't supported, fall back to the simple
10927 way of searching memory. */
10928
10929 if (packet_config_support (packet) == PACKET_DISABLE)
10930 {
10931 /* Target doesn't provided special support, fall back and use the
10932 standard support (copy memory and do the search here). */
10933 return simple_search_memory (this, start_addr, search_space_len,
10934 pattern, pattern_len, found_addrp);
10935 }
10936
10937 /* Make sure the remote is pointing at the right process. */
10938 set_general_process ();
10939
10940 /* Insert header. */
10941 i = snprintf (rs->buf, max_size,
10942 "qSearch:memory:%s;%s;",
10943 phex_nz (start_addr, addr_size),
10944 phex_nz (search_space_len, sizeof (search_space_len)));
10945 max_size -= (i + 1);
10946
10947 /* Escape as much data as fits into rs->buf. */
10948 escaped_pattern_len =
10949 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10950 &used_pattern_len, max_size);
10951
10952 /* Bail if the pattern is too large. */
10953 if (used_pattern_len != pattern_len)
10954 error (_("Pattern is too large to transmit to remote target."));
10955
10956 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10957 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10958 || packet_ok (rs->buf, packet) != PACKET_OK)
10959 {
10960 /* The request may not have worked because the command is not
10961 supported. If so, fall back to the simple way. */
10962 if (packet_config_support (packet) == PACKET_DISABLE)
10963 {
10964 return simple_search_memory (this, start_addr, search_space_len,
10965 pattern, pattern_len, found_addrp);
10966 }
10967 return -1;
10968 }
10969
10970 if (rs->buf[0] == '0')
10971 found = 0;
10972 else if (rs->buf[0] == '1')
10973 {
10974 found = 1;
10975 if (rs->buf[1] != ',')
10976 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10977 unpack_varlen_hex (rs->buf + 2, &found_addr);
10978 *found_addrp = found_addr;
10979 }
10980 else
10981 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10982
10983 return found;
10984 }
10985
10986 void
10987 remote_target::rcmd (const char *command, struct ui_file *outbuf)
10988 {
10989 struct remote_state *rs = get_remote_state ();
10990 char *p = rs->buf;
10991
10992 if (!rs->remote_desc)
10993 error (_("remote rcmd is only available after target open"));
10994
10995 /* Send a NULL command across as an empty command. */
10996 if (command == NULL)
10997 command = "";
10998
10999 /* The query prefix. */
11000 strcpy (rs->buf, "qRcmd,");
11001 p = strchr (rs->buf, '\0');
11002
11003 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11004 > get_remote_packet_size ())
11005 error (_("\"monitor\" command ``%s'' is too long."), command);
11006
11007 /* Encode the actual command. */
11008 bin2hex ((const gdb_byte *) command, p, strlen (command));
11009
11010 if (putpkt (rs->buf) < 0)
11011 error (_("Communication problem with target."));
11012
11013 /* get/display the response */
11014 while (1)
11015 {
11016 char *buf;
11017
11018 /* XXX - see also remote_get_noisy_reply(). */
11019 QUIT; /* Allow user to bail out with ^C. */
11020 rs->buf[0] = '\0';
11021 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11022 {
11023 /* Timeout. Continue to (try to) read responses.
11024 This is better than stopping with an error, assuming the stub
11025 is still executing the (long) monitor command.
11026 If needed, the user can interrupt gdb using C-c, obtaining
11027 an effect similar to stop on timeout. */
11028 continue;
11029 }
11030 buf = rs->buf;
11031 if (buf[0] == '\0')
11032 error (_("Target does not support this command."));
11033 if (buf[0] == 'O' && buf[1] != 'K')
11034 {
11035 remote_console_output (buf + 1); /* 'O' message from stub. */
11036 continue;
11037 }
11038 if (strcmp (buf, "OK") == 0)
11039 break;
11040 if (strlen (buf) == 3 && buf[0] == 'E'
11041 && isdigit (buf[1]) && isdigit (buf[2]))
11042 {
11043 error (_("Protocol error with Rcmd"));
11044 }
11045 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11046 {
11047 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11048
11049 fputc_unfiltered (c, outbuf);
11050 }
11051 break;
11052 }
11053 }
11054
11055 std::vector<mem_region>
11056 remote_target::memory_map ()
11057 {
11058 std::vector<mem_region> result;
11059 gdb::optional<gdb::char_vector> text
11060 = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
11061
11062 if (text)
11063 result = parse_memory_map (text->data ());
11064
11065 return result;
11066 }
11067
11068 static void
11069 packet_command (const char *args, int from_tty)
11070 {
11071 struct remote_state *rs = get_remote_state ();
11072
11073 if (!rs->remote_desc)
11074 error (_("command can only be used with remote target"));
11075
11076 if (!args)
11077 error (_("remote-packet command requires packet text as argument"));
11078
11079 puts_filtered ("sending: ");
11080 print_packet (args);
11081 puts_filtered ("\n");
11082 putpkt (args);
11083
11084 getpkt (&rs->buf, &rs->buf_size, 0);
11085 puts_filtered ("received: ");
11086 print_packet (rs->buf);
11087 puts_filtered ("\n");
11088 }
11089
11090 #if 0
11091 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11092
11093 static void display_thread_info (struct gdb_ext_thread_info *info);
11094
11095 static void threadset_test_cmd (char *cmd, int tty);
11096
11097 static void threadalive_test (char *cmd, int tty);
11098
11099 static void threadlist_test_cmd (char *cmd, int tty);
11100
11101 int get_and_display_threadinfo (threadref *ref);
11102
11103 static void threadinfo_test_cmd (char *cmd, int tty);
11104
11105 static int thread_display_step (threadref *ref, void *context);
11106
11107 static void threadlist_update_test_cmd (char *cmd, int tty);
11108
11109 static void init_remote_threadtests (void);
11110
11111 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11112
11113 static void
11114 threadset_test_cmd (const char *cmd, int tty)
11115 {
11116 int sample_thread = SAMPLE_THREAD;
11117
11118 printf_filtered (_("Remote threadset test\n"));
11119 set_general_thread (sample_thread);
11120 }
11121
11122
11123 static void
11124 threadalive_test (const char *cmd, int tty)
11125 {
11126 int sample_thread = SAMPLE_THREAD;
11127 int pid = ptid_get_pid (inferior_ptid);
11128 ptid_t ptid = ptid_build (pid, sample_thread, 0);
11129
11130 if (remote_thread_alive (ptid))
11131 printf_filtered ("PASS: Thread alive test\n");
11132 else
11133 printf_filtered ("FAIL: Thread alive test\n");
11134 }
11135
11136 void output_threadid (char *title, threadref *ref);
11137
11138 void
11139 output_threadid (char *title, threadref *ref)
11140 {
11141 char hexid[20];
11142
11143 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
11144 hexid[16] = 0;
11145 printf_filtered ("%s %s\n", title, (&hexid[0]));
11146 }
11147
11148 static void
11149 threadlist_test_cmd (const char *cmd, int tty)
11150 {
11151 int startflag = 1;
11152 threadref nextthread;
11153 int done, result_count;
11154 threadref threadlist[3];
11155
11156 printf_filtered ("Remote Threadlist test\n");
11157 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11158 &result_count, &threadlist[0]))
11159 printf_filtered ("FAIL: threadlist test\n");
11160 else
11161 {
11162 threadref *scan = threadlist;
11163 threadref *limit = scan + result_count;
11164
11165 while (scan < limit)
11166 output_threadid (" thread ", scan++);
11167 }
11168 }
11169
11170 void
11171 display_thread_info (struct gdb_ext_thread_info *info)
11172 {
11173 output_threadid ("Threadid: ", &info->threadid);
11174 printf_filtered ("Name: %s\n ", info->shortname);
11175 printf_filtered ("State: %s\n", info->display);
11176 printf_filtered ("other: %s\n\n", info->more_display);
11177 }
11178
11179 int
11180 get_and_display_threadinfo (threadref *ref)
11181 {
11182 int result;
11183 int set;
11184 struct gdb_ext_thread_info threadinfo;
11185
11186 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11187 | TAG_MOREDISPLAY | TAG_DISPLAY;
11188 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11189 display_thread_info (&threadinfo);
11190 return result;
11191 }
11192
11193 static void
11194 threadinfo_test_cmd (const char *cmd, int tty)
11195 {
11196 int athread = SAMPLE_THREAD;
11197 threadref thread;
11198 int set;
11199
11200 int_to_threadref (&thread, athread);
11201 printf_filtered ("Remote Threadinfo test\n");
11202 if (!get_and_display_threadinfo (&thread))
11203 printf_filtered ("FAIL cannot get thread info\n");
11204 }
11205
11206 static int
11207 thread_display_step (threadref *ref, void *context)
11208 {
11209 /* output_threadid(" threadstep ",ref); *//* simple test */
11210 return get_and_display_threadinfo (ref);
11211 }
11212
11213 static void
11214 threadlist_update_test_cmd (const char *cmd, int tty)
11215 {
11216 printf_filtered ("Remote Threadlist update test\n");
11217 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11218 }
11219
11220 static void
11221 init_remote_threadtests (void)
11222 {
11223 add_com ("tlist", class_obscure, threadlist_test_cmd,
11224 _("Fetch and print the remote list of "
11225 "thread identifiers, one pkt only"));
11226 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11227 _("Fetch and display info about one thread"));
11228 add_com ("tset", class_obscure, threadset_test_cmd,
11229 _("Test setting to a different thread"));
11230 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11231 _("Iterate through updating all remote thread info"));
11232 add_com ("talive", class_obscure, threadalive_test,
11233 _(" Remote thread alive test "));
11234 }
11235
11236 #endif /* 0 */
11237
11238 /* Convert a thread ID to a string. Returns the string in a static
11239 buffer. */
11240
11241 const char *
11242 remote_target::pid_to_str (ptid_t ptid)
11243 {
11244 static char buf[64];
11245 struct remote_state *rs = get_remote_state ();
11246
11247 if (ptid_equal (ptid, null_ptid))
11248 return normal_pid_to_str (ptid);
11249 else if (ptid_is_pid (ptid))
11250 {
11251 /* Printing an inferior target id. */
11252
11253 /* When multi-process extensions are off, there's no way in the
11254 remote protocol to know the remote process id, if there's any
11255 at all. There's one exception --- when we're connected with
11256 target extended-remote, and we manually attached to a process
11257 with "attach PID". We don't record anywhere a flag that
11258 allows us to distinguish that case from the case of
11259 connecting with extended-remote and the stub already being
11260 attached to a process, and reporting yes to qAttached, hence
11261 no smart special casing here. */
11262 if (!remote_multi_process_p (rs))
11263 {
11264 xsnprintf (buf, sizeof buf, "Remote target");
11265 return buf;
11266 }
11267
11268 return normal_pid_to_str (ptid);
11269 }
11270 else
11271 {
11272 if (ptid_equal (magic_null_ptid, ptid))
11273 xsnprintf (buf, sizeof buf, "Thread <main>");
11274 else if (remote_multi_process_p (rs))
11275 if (ptid_get_lwp (ptid) == 0)
11276 return normal_pid_to_str (ptid);
11277 else
11278 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11279 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11280 else
11281 xsnprintf (buf, sizeof buf, "Thread %ld",
11282 ptid_get_lwp (ptid));
11283 return buf;
11284 }
11285 }
11286
11287 /* Get the address of the thread local variable in OBJFILE which is
11288 stored at OFFSET within the thread local storage for thread PTID. */
11289
11290 CORE_ADDR
11291 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11292 CORE_ADDR offset)
11293 {
11294 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11295 {
11296 struct remote_state *rs = get_remote_state ();
11297 char *p = rs->buf;
11298 char *endp = rs->buf + get_remote_packet_size ();
11299 enum packet_result result;
11300
11301 strcpy (p, "qGetTLSAddr:");
11302 p += strlen (p);
11303 p = write_ptid (p, endp, ptid);
11304 *p++ = ',';
11305 p += hexnumstr (p, offset);
11306 *p++ = ',';
11307 p += hexnumstr (p, lm);
11308 *p++ = '\0';
11309
11310 putpkt (rs->buf);
11311 getpkt (&rs->buf, &rs->buf_size, 0);
11312 result = packet_ok (rs->buf,
11313 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11314 if (result == PACKET_OK)
11315 {
11316 ULONGEST result;
11317
11318 unpack_varlen_hex (rs->buf, &result);
11319 return result;
11320 }
11321 else if (result == PACKET_UNKNOWN)
11322 throw_error (TLS_GENERIC_ERROR,
11323 _("Remote target doesn't support qGetTLSAddr packet"));
11324 else
11325 throw_error (TLS_GENERIC_ERROR,
11326 _("Remote target failed to process qGetTLSAddr request"));
11327 }
11328 else
11329 throw_error (TLS_GENERIC_ERROR,
11330 _("TLS not supported or disabled on this target"));
11331 /* Not reached. */
11332 return 0;
11333 }
11334
11335 /* Provide thread local base, i.e. Thread Information Block address.
11336 Returns 1 if ptid is found and thread_local_base is non zero. */
11337
11338 bool
11339 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11340 {
11341 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11342 {
11343 struct remote_state *rs = get_remote_state ();
11344 char *p = rs->buf;
11345 char *endp = rs->buf + get_remote_packet_size ();
11346 enum packet_result result;
11347
11348 strcpy (p, "qGetTIBAddr:");
11349 p += strlen (p);
11350 p = write_ptid (p, endp, ptid);
11351 *p++ = '\0';
11352
11353 putpkt (rs->buf);
11354 getpkt (&rs->buf, &rs->buf_size, 0);
11355 result = packet_ok (rs->buf,
11356 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11357 if (result == PACKET_OK)
11358 {
11359 ULONGEST result;
11360
11361 unpack_varlen_hex (rs->buf, &result);
11362 if (addr)
11363 *addr = (CORE_ADDR) result;
11364 return true;
11365 }
11366 else if (result == PACKET_UNKNOWN)
11367 error (_("Remote target doesn't support qGetTIBAddr packet"));
11368 else
11369 error (_("Remote target failed to process qGetTIBAddr request"));
11370 }
11371 else
11372 error (_("qGetTIBAddr not supported or disabled on this target"));
11373 /* Not reached. */
11374 return false;
11375 }
11376
11377 /* Support for inferring a target description based on the current
11378 architecture and the size of a 'g' packet. While the 'g' packet
11379 can have any size (since optional registers can be left off the
11380 end), some sizes are easily recognizable given knowledge of the
11381 approximate architecture. */
11382
11383 struct remote_g_packet_guess
11384 {
11385 int bytes;
11386 const struct target_desc *tdesc;
11387 };
11388 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11389 DEF_VEC_O(remote_g_packet_guess_s);
11390
11391 struct remote_g_packet_data
11392 {
11393 VEC(remote_g_packet_guess_s) *guesses;
11394 };
11395
11396 static struct gdbarch_data *remote_g_packet_data_handle;
11397
11398 static void *
11399 remote_g_packet_data_init (struct obstack *obstack)
11400 {
11401 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11402 }
11403
11404 void
11405 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11406 const struct target_desc *tdesc)
11407 {
11408 struct remote_g_packet_data *data
11409 = ((struct remote_g_packet_data *)
11410 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11411 struct remote_g_packet_guess new_guess, *guess;
11412 int ix;
11413
11414 gdb_assert (tdesc != NULL);
11415
11416 for (ix = 0;
11417 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11418 ix++)
11419 if (guess->bytes == bytes)
11420 internal_error (__FILE__, __LINE__,
11421 _("Duplicate g packet description added for size %d"),
11422 bytes);
11423
11424 new_guess.bytes = bytes;
11425 new_guess.tdesc = tdesc;
11426 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11427 }
11428
11429 /* Return 1 if remote_read_description would do anything on this target
11430 and architecture, 0 otherwise. */
11431
11432 static int
11433 remote_read_description_p (struct target_ops *target)
11434 {
11435 struct remote_g_packet_data *data
11436 = ((struct remote_g_packet_data *)
11437 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11438
11439 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11440 return 1;
11441
11442 return 0;
11443 }
11444
11445 const struct target_desc *
11446 remote_target::read_description ()
11447 {
11448 struct remote_g_packet_data *data
11449 = ((struct remote_g_packet_data *)
11450 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11451
11452 /* Do not try this during initial connection, when we do not know
11453 whether there is a running but stopped thread. */
11454 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11455 return beneath->read_description ();
11456
11457 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11458 {
11459 struct remote_g_packet_guess *guess;
11460 int ix;
11461 int bytes = send_g_packet ();
11462
11463 for (ix = 0;
11464 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11465 ix++)
11466 if (guess->bytes == bytes)
11467 return guess->tdesc;
11468
11469 /* We discard the g packet. A minor optimization would be to
11470 hold on to it, and fill the register cache once we have selected
11471 an architecture, but it's too tricky to do safely. */
11472 }
11473
11474 return beneath->read_description ();
11475 }
11476
11477 /* Remote file transfer support. This is host-initiated I/O, not
11478 target-initiated; for target-initiated, see remote-fileio.c. */
11479
11480 /* If *LEFT is at least the length of STRING, copy STRING to
11481 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11482 decrease *LEFT. Otherwise raise an error. */
11483
11484 static void
11485 remote_buffer_add_string (char **buffer, int *left, const char *string)
11486 {
11487 int len = strlen (string);
11488
11489 if (len > *left)
11490 error (_("Packet too long for target."));
11491
11492 memcpy (*buffer, string, len);
11493 *buffer += len;
11494 *left -= len;
11495
11496 /* NUL-terminate the buffer as a convenience, if there is
11497 room. */
11498 if (*left)
11499 **buffer = '\0';
11500 }
11501
11502 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11503 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11504 decrease *LEFT. Otherwise raise an error. */
11505
11506 static void
11507 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11508 int len)
11509 {
11510 if (2 * len > *left)
11511 error (_("Packet too long for target."));
11512
11513 bin2hex (bytes, *buffer, len);
11514 *buffer += 2 * len;
11515 *left -= 2 * len;
11516
11517 /* NUL-terminate the buffer as a convenience, if there is
11518 room. */
11519 if (*left)
11520 **buffer = '\0';
11521 }
11522
11523 /* If *LEFT is large enough, convert VALUE to hex and add it to
11524 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11525 decrease *LEFT. Otherwise raise an error. */
11526
11527 static void
11528 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11529 {
11530 int len = hexnumlen (value);
11531
11532 if (len > *left)
11533 error (_("Packet too long for target."));
11534
11535 hexnumstr (*buffer, value);
11536 *buffer += len;
11537 *left -= len;
11538
11539 /* NUL-terminate the buffer as a convenience, if there is
11540 room. */
11541 if (*left)
11542 **buffer = '\0';
11543 }
11544
11545 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11546 value, *REMOTE_ERRNO to the remote error number or zero if none
11547 was included, and *ATTACHMENT to point to the start of the annex
11548 if any. The length of the packet isn't needed here; there may
11549 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11550
11551 Return 0 if the packet could be parsed, -1 if it could not. If
11552 -1 is returned, the other variables may not be initialized. */
11553
11554 static int
11555 remote_hostio_parse_result (char *buffer, int *retcode,
11556 int *remote_errno, char **attachment)
11557 {
11558 char *p, *p2;
11559
11560 *remote_errno = 0;
11561 *attachment = NULL;
11562
11563 if (buffer[0] != 'F')
11564 return -1;
11565
11566 errno = 0;
11567 *retcode = strtol (&buffer[1], &p, 16);
11568 if (errno != 0 || p == &buffer[1])
11569 return -1;
11570
11571 /* Check for ",errno". */
11572 if (*p == ',')
11573 {
11574 errno = 0;
11575 *remote_errno = strtol (p + 1, &p2, 16);
11576 if (errno != 0 || p + 1 == p2)
11577 return -1;
11578 p = p2;
11579 }
11580
11581 /* Check for ";attachment". If there is no attachment, the
11582 packet should end here. */
11583 if (*p == ';')
11584 {
11585 *attachment = p + 1;
11586 return 0;
11587 }
11588 else if (*p == '\0')
11589 return 0;
11590 else
11591 return -1;
11592 }
11593
11594 /* Send a prepared I/O packet to the target and read its response.
11595 The prepared packet is in the global RS->BUF before this function
11596 is called, and the answer is there when we return.
11597
11598 COMMAND_BYTES is the length of the request to send, which may include
11599 binary data. WHICH_PACKET is the packet configuration to check
11600 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11601 is set to the error number and -1 is returned. Otherwise the value
11602 returned by the function is returned.
11603
11604 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11605 attachment is expected; an error will be reported if there's a
11606 mismatch. If one is found, *ATTACHMENT will be set to point into
11607 the packet buffer and *ATTACHMENT_LEN will be set to the
11608 attachment's length. */
11609
11610 static int
11611 remote_hostio_send_command (int command_bytes, int which_packet,
11612 int *remote_errno, char **attachment,
11613 int *attachment_len)
11614 {
11615 struct remote_state *rs = get_remote_state ();
11616 int ret, bytes_read;
11617 char *attachment_tmp;
11618
11619 if (packet_support (which_packet) == PACKET_DISABLE)
11620 {
11621 *remote_errno = FILEIO_ENOSYS;
11622 return -1;
11623 }
11624
11625 putpkt_binary (rs->buf, command_bytes);
11626 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11627
11628 /* If it timed out, something is wrong. Don't try to parse the
11629 buffer. */
11630 if (bytes_read < 0)
11631 {
11632 *remote_errno = FILEIO_EINVAL;
11633 return -1;
11634 }
11635
11636 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11637 {
11638 case PACKET_ERROR:
11639 *remote_errno = FILEIO_EINVAL;
11640 return -1;
11641 case PACKET_UNKNOWN:
11642 *remote_errno = FILEIO_ENOSYS;
11643 return -1;
11644 case PACKET_OK:
11645 break;
11646 }
11647
11648 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11649 &attachment_tmp))
11650 {
11651 *remote_errno = FILEIO_EINVAL;
11652 return -1;
11653 }
11654
11655 /* Make sure we saw an attachment if and only if we expected one. */
11656 if ((attachment_tmp == NULL && attachment != NULL)
11657 || (attachment_tmp != NULL && attachment == NULL))
11658 {
11659 *remote_errno = FILEIO_EINVAL;
11660 return -1;
11661 }
11662
11663 /* If an attachment was found, it must point into the packet buffer;
11664 work out how many bytes there were. */
11665 if (attachment_tmp != NULL)
11666 {
11667 *attachment = attachment_tmp;
11668 *attachment_len = bytes_read - (*attachment - rs->buf);
11669 }
11670
11671 return ret;
11672 }
11673
11674 /* Invalidate the readahead cache. */
11675
11676 static void
11677 readahead_cache_invalidate (void)
11678 {
11679 struct remote_state *rs = get_remote_state ();
11680
11681 rs->readahead_cache.fd = -1;
11682 }
11683
11684 /* Invalidate the readahead cache if it is holding data for FD. */
11685
11686 static void
11687 readahead_cache_invalidate_fd (int fd)
11688 {
11689 struct remote_state *rs = get_remote_state ();
11690
11691 if (rs->readahead_cache.fd == fd)
11692 rs->readahead_cache.fd = -1;
11693 }
11694
11695 /* Set the filesystem remote_hostio functions that take FILENAME
11696 arguments will use. Return 0 on success, or -1 if an error
11697 occurs (and set *REMOTE_ERRNO). */
11698
11699 static int
11700 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11701 {
11702 struct remote_state *rs = get_remote_state ();
11703 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11704 char *p = rs->buf;
11705 int left = get_remote_packet_size () - 1;
11706 char arg[9];
11707 int ret;
11708
11709 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11710 return 0;
11711
11712 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11713 return 0;
11714
11715 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11716
11717 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11718 remote_buffer_add_string (&p, &left, arg);
11719
11720 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11721 remote_errno, NULL, NULL);
11722
11723 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11724 return 0;
11725
11726 if (ret == 0)
11727 rs->fs_pid = required_pid;
11728
11729 return ret;
11730 }
11731
11732 /* Implementation of to_fileio_open. */
11733
11734 static int
11735 remote_hostio_open (struct target_ops *self,
11736 struct inferior *inf, const char *filename,
11737 int flags, int mode, int warn_if_slow,
11738 int *remote_errno)
11739 {
11740 struct remote_state *rs = get_remote_state ();
11741 char *p = rs->buf;
11742 int left = get_remote_packet_size () - 1;
11743
11744 if (warn_if_slow)
11745 {
11746 static int warning_issued = 0;
11747
11748 printf_unfiltered (_("Reading %s from remote target...\n"),
11749 filename);
11750
11751 if (!warning_issued)
11752 {
11753 warning (_("File transfers from remote targets can be slow."
11754 " Use \"set sysroot\" to access files locally"
11755 " instead."));
11756 warning_issued = 1;
11757 }
11758 }
11759
11760 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11761 return -1;
11762
11763 remote_buffer_add_string (&p, &left, "vFile:open:");
11764
11765 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11766 strlen (filename));
11767 remote_buffer_add_string (&p, &left, ",");
11768
11769 remote_buffer_add_int (&p, &left, flags);
11770 remote_buffer_add_string (&p, &left, ",");
11771
11772 remote_buffer_add_int (&p, &left, mode);
11773
11774 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11775 remote_errno, NULL, NULL);
11776 }
11777
11778 int
11779 remote_target::fileio_open (struct inferior *inf, const char *filename,
11780 int flags, int mode, int warn_if_slow,
11781 int *remote_errno)
11782 {
11783 return remote_hostio_open (this, inf, filename, flags, mode, warn_if_slow,
11784 remote_errno);
11785 }
11786
11787 /* Implementation of to_fileio_pwrite. */
11788
11789 static int
11790 remote_hostio_pwrite (struct target_ops *self,
11791 int fd, const gdb_byte *write_buf, int len,
11792 ULONGEST offset, int *remote_errno)
11793 {
11794 struct remote_state *rs = get_remote_state ();
11795 char *p = rs->buf;
11796 int left = get_remote_packet_size ();
11797 int out_len;
11798
11799 readahead_cache_invalidate_fd (fd);
11800
11801 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11802
11803 remote_buffer_add_int (&p, &left, fd);
11804 remote_buffer_add_string (&p, &left, ",");
11805
11806 remote_buffer_add_int (&p, &left, offset);
11807 remote_buffer_add_string (&p, &left, ",");
11808
11809 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11810 get_remote_packet_size () - (p - rs->buf));
11811
11812 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11813 remote_errno, NULL, NULL);
11814 }
11815
11816 int
11817 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
11818 ULONGEST offset, int *remote_errno)
11819 {
11820 return remote_hostio_pwrite (this, fd, write_buf, len, offset, remote_errno);
11821 }
11822
11823 /* Helper for the implementation of to_fileio_pread. Read the file
11824 from the remote side with vFile:pread. */
11825
11826 static int
11827 remote_hostio_pread_vFile (struct target_ops *self,
11828 int fd, gdb_byte *read_buf, int len,
11829 ULONGEST offset, int *remote_errno)
11830 {
11831 struct remote_state *rs = get_remote_state ();
11832 char *p = rs->buf;
11833 char *attachment;
11834 int left = get_remote_packet_size ();
11835 int ret, attachment_len;
11836 int read_len;
11837
11838 remote_buffer_add_string (&p, &left, "vFile:pread:");
11839
11840 remote_buffer_add_int (&p, &left, fd);
11841 remote_buffer_add_string (&p, &left, ",");
11842
11843 remote_buffer_add_int (&p, &left, len);
11844 remote_buffer_add_string (&p, &left, ",");
11845
11846 remote_buffer_add_int (&p, &left, offset);
11847
11848 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11849 remote_errno, &attachment,
11850 &attachment_len);
11851
11852 if (ret < 0)
11853 return ret;
11854
11855 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11856 read_buf, len);
11857 if (read_len != ret)
11858 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11859
11860 return ret;
11861 }
11862
11863 /* Serve pread from the readahead cache. Returns number of bytes
11864 read, or 0 if the request can't be served from the cache. */
11865
11866 static int
11867 remote_hostio_pread_from_cache (struct remote_state *rs,
11868 int fd, gdb_byte *read_buf, size_t len,
11869 ULONGEST offset)
11870 {
11871 struct readahead_cache *cache = &rs->readahead_cache;
11872
11873 if (cache->fd == fd
11874 && cache->offset <= offset
11875 && offset < cache->offset + cache->bufsize)
11876 {
11877 ULONGEST max = cache->offset + cache->bufsize;
11878
11879 if (offset + len > max)
11880 len = max - offset;
11881
11882 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11883 return len;
11884 }
11885
11886 return 0;
11887 }
11888
11889 /* Implementation of to_fileio_pread. */
11890
11891 static int
11892 remote_hostio_pread (struct target_ops *self,
11893 int fd, gdb_byte *read_buf, int len,
11894 ULONGEST offset, int *remote_errno)
11895 {
11896 int ret;
11897 struct remote_state *rs = get_remote_state ();
11898 struct readahead_cache *cache = &rs->readahead_cache;
11899
11900 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11901 if (ret > 0)
11902 {
11903 cache->hit_count++;
11904
11905 if (remote_debug)
11906 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11907 pulongest (cache->hit_count));
11908 return ret;
11909 }
11910
11911 cache->miss_count++;
11912 if (remote_debug)
11913 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11914 pulongest (cache->miss_count));
11915
11916 cache->fd = fd;
11917 cache->offset = offset;
11918 cache->bufsize = get_remote_packet_size ();
11919 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11920
11921 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11922 cache->offset, remote_errno);
11923 if (ret <= 0)
11924 {
11925 readahead_cache_invalidate_fd (fd);
11926 return ret;
11927 }
11928
11929 cache->bufsize = ret;
11930 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11931 }
11932
11933 int
11934 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
11935 ULONGEST offset, int *remote_errno)
11936 {
11937 return remote_hostio_pread (this, fd, read_buf, len, offset, remote_errno);
11938 }
11939
11940 /* Implementation of to_fileio_close. */
11941
11942 static int
11943 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11944 {
11945 struct remote_state *rs = get_remote_state ();
11946 char *p = rs->buf;
11947 int left = get_remote_packet_size () - 1;
11948
11949 readahead_cache_invalidate_fd (fd);
11950
11951 remote_buffer_add_string (&p, &left, "vFile:close:");
11952
11953 remote_buffer_add_int (&p, &left, fd);
11954
11955 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11956 remote_errno, NULL, NULL);
11957 }
11958
11959 int
11960 remote_target::fileio_close (int fd, int *remote_errno)
11961 {
11962 return remote_hostio_close (this, fd, remote_errno);
11963 }
11964
11965 /* Implementation of to_fileio_unlink. */
11966
11967 static int
11968 remote_hostio_unlink (struct target_ops *self,
11969 struct inferior *inf, const char *filename,
11970 int *remote_errno)
11971 {
11972 struct remote_state *rs = get_remote_state ();
11973 char *p = rs->buf;
11974 int left = get_remote_packet_size () - 1;
11975
11976 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11977 return -1;
11978
11979 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11980
11981 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11982 strlen (filename));
11983
11984 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11985 remote_errno, NULL, NULL);
11986 }
11987
11988 int
11989 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
11990 int *remote_errno)
11991 {
11992 return remote_hostio_unlink (this, inf, filename, remote_errno);
11993 }
11994
11995 /* Implementation of to_fileio_readlink. */
11996
11997 gdb::optional<std::string>
11998 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
11999 int *remote_errno)
12000 {
12001 struct remote_state *rs = get_remote_state ();
12002 char *p = rs->buf;
12003 char *attachment;
12004 int left = get_remote_packet_size ();
12005 int len, attachment_len;
12006 int read_len;
12007
12008 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12009 return {};
12010
12011 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12012
12013 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12014 strlen (filename));
12015
12016 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12017 remote_errno, &attachment,
12018 &attachment_len);
12019
12020 if (len < 0)
12021 return {};
12022
12023 std::string ret (len, '\0');
12024
12025 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12026 (gdb_byte *) &ret[0], len);
12027 if (read_len != len)
12028 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12029
12030 return ret;
12031 }
12032
12033 /* Implementation of to_fileio_fstat. */
12034
12035 int
12036 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12037 {
12038 struct remote_state *rs = get_remote_state ();
12039 char *p = rs->buf;
12040 int left = get_remote_packet_size ();
12041 int attachment_len, ret;
12042 char *attachment;
12043 struct fio_stat fst;
12044 int read_len;
12045
12046 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12047
12048 remote_buffer_add_int (&p, &left, fd);
12049
12050 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12051 remote_errno, &attachment,
12052 &attachment_len);
12053 if (ret < 0)
12054 {
12055 if (*remote_errno != FILEIO_ENOSYS)
12056 return ret;
12057
12058 /* Strictly we should return -1, ENOSYS here, but when
12059 "set sysroot remote:" was implemented in August 2008
12060 BFD's need for a stat function was sidestepped with
12061 this hack. This was not remedied until March 2015
12062 so we retain the previous behavior to avoid breaking
12063 compatibility.
12064
12065 Note that the memset is a March 2015 addition; older
12066 GDBs set st_size *and nothing else* so the structure
12067 would have garbage in all other fields. This might
12068 break something but retaining the previous behavior
12069 here would be just too wrong. */
12070
12071 memset (st, 0, sizeof (struct stat));
12072 st->st_size = INT_MAX;
12073 return 0;
12074 }
12075
12076 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12077 (gdb_byte *) &fst, sizeof (fst));
12078
12079 if (read_len != ret)
12080 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12081
12082 if (read_len != sizeof (fst))
12083 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12084 read_len, (int) sizeof (fst));
12085
12086 remote_fileio_to_host_stat (&fst, st);
12087
12088 return 0;
12089 }
12090
12091 /* Implementation of to_filesystem_is_local. */
12092
12093 bool
12094 remote_target::filesystem_is_local ()
12095 {
12096 /* Valgrind GDB presents itself as a remote target but works
12097 on the local filesystem: it does not implement remote get
12098 and users are not expected to set a sysroot. To handle
12099 this case we treat the remote filesystem as local if the
12100 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12101 does not support vFile:open. */
12102 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12103 {
12104 enum packet_support ps = packet_support (PACKET_vFile_open);
12105
12106 if (ps == PACKET_SUPPORT_UNKNOWN)
12107 {
12108 int fd, remote_errno;
12109
12110 /* Try opening a file to probe support. The supplied
12111 filename is irrelevant, we only care about whether
12112 the stub recognizes the packet or not. */
12113 fd = remote_hostio_open (this, NULL, "just probing",
12114 FILEIO_O_RDONLY, 0700, 0,
12115 &remote_errno);
12116
12117 if (fd >= 0)
12118 remote_hostio_close (this, fd, &remote_errno);
12119
12120 ps = packet_support (PACKET_vFile_open);
12121 }
12122
12123 if (ps == PACKET_DISABLE)
12124 {
12125 static int warning_issued = 0;
12126
12127 if (!warning_issued)
12128 {
12129 warning (_("remote target does not support file"
12130 " transfer, attempting to access files"
12131 " from local filesystem."));
12132 warning_issued = 1;
12133 }
12134
12135 return true;
12136 }
12137 }
12138
12139 return false;
12140 }
12141
12142 static int
12143 remote_fileio_errno_to_host (int errnum)
12144 {
12145 switch (errnum)
12146 {
12147 case FILEIO_EPERM:
12148 return EPERM;
12149 case FILEIO_ENOENT:
12150 return ENOENT;
12151 case FILEIO_EINTR:
12152 return EINTR;
12153 case FILEIO_EIO:
12154 return EIO;
12155 case FILEIO_EBADF:
12156 return EBADF;
12157 case FILEIO_EACCES:
12158 return EACCES;
12159 case FILEIO_EFAULT:
12160 return EFAULT;
12161 case FILEIO_EBUSY:
12162 return EBUSY;
12163 case FILEIO_EEXIST:
12164 return EEXIST;
12165 case FILEIO_ENODEV:
12166 return ENODEV;
12167 case FILEIO_ENOTDIR:
12168 return ENOTDIR;
12169 case FILEIO_EISDIR:
12170 return EISDIR;
12171 case FILEIO_EINVAL:
12172 return EINVAL;
12173 case FILEIO_ENFILE:
12174 return ENFILE;
12175 case FILEIO_EMFILE:
12176 return EMFILE;
12177 case FILEIO_EFBIG:
12178 return EFBIG;
12179 case FILEIO_ENOSPC:
12180 return ENOSPC;
12181 case FILEIO_ESPIPE:
12182 return ESPIPE;
12183 case FILEIO_EROFS:
12184 return EROFS;
12185 case FILEIO_ENOSYS:
12186 return ENOSYS;
12187 case FILEIO_ENAMETOOLONG:
12188 return ENAMETOOLONG;
12189 }
12190 return -1;
12191 }
12192
12193 static char *
12194 remote_hostio_error (int errnum)
12195 {
12196 int host_error = remote_fileio_errno_to_host (errnum);
12197
12198 if (host_error == -1)
12199 error (_("Unknown remote I/O error %d"), errnum);
12200 else
12201 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12202 }
12203
12204 static void
12205 remote_hostio_close_cleanup (void *opaque)
12206 {
12207 int fd = *(int *) opaque;
12208 int remote_errno;
12209
12210 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
12211 }
12212
12213 void
12214 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12215 {
12216 struct cleanup *back_to, *close_cleanup;
12217 int retcode, fd, remote_errno, bytes, io_size;
12218 gdb_byte *buffer;
12219 int bytes_in_buffer;
12220 int saw_eof;
12221 ULONGEST offset;
12222 struct remote_state *rs = get_remote_state ();
12223
12224 if (!rs->remote_desc)
12225 error (_("command can only be used with remote target"));
12226
12227 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12228 if (file == NULL)
12229 perror_with_name (local_file);
12230
12231 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12232 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12233 | FILEIO_O_TRUNC),
12234 0700, 0, &remote_errno);
12235 if (fd == -1)
12236 remote_hostio_error (remote_errno);
12237
12238 /* Send up to this many bytes at once. They won't all fit in the
12239 remote packet limit, so we'll transfer slightly fewer. */
12240 io_size = get_remote_packet_size ();
12241 buffer = (gdb_byte *) xmalloc (io_size);
12242 back_to = make_cleanup (xfree, buffer);
12243
12244 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12245
12246 bytes_in_buffer = 0;
12247 saw_eof = 0;
12248 offset = 0;
12249 while (bytes_in_buffer || !saw_eof)
12250 {
12251 if (!saw_eof)
12252 {
12253 bytes = fread (buffer + bytes_in_buffer, 1,
12254 io_size - bytes_in_buffer,
12255 file.get ());
12256 if (bytes == 0)
12257 {
12258 if (ferror (file.get ()))
12259 error (_("Error reading %s."), local_file);
12260 else
12261 {
12262 /* EOF. Unless there is something still in the
12263 buffer from the last iteration, we are done. */
12264 saw_eof = 1;
12265 if (bytes_in_buffer == 0)
12266 break;
12267 }
12268 }
12269 }
12270 else
12271 bytes = 0;
12272
12273 bytes += bytes_in_buffer;
12274 bytes_in_buffer = 0;
12275
12276 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12277 fd, buffer, bytes,
12278 offset, &remote_errno);
12279
12280 if (retcode < 0)
12281 remote_hostio_error (remote_errno);
12282 else if (retcode == 0)
12283 error (_("Remote write of %d bytes returned 0!"), bytes);
12284 else if (retcode < bytes)
12285 {
12286 /* Short write. Save the rest of the read data for the next
12287 write. */
12288 bytes_in_buffer = bytes - retcode;
12289 memmove (buffer, buffer + retcode, bytes_in_buffer);
12290 }
12291
12292 offset += retcode;
12293 }
12294
12295 discard_cleanups (close_cleanup);
12296 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12297 remote_hostio_error (remote_errno);
12298
12299 if (from_tty)
12300 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12301 do_cleanups (back_to);
12302 }
12303
12304 void
12305 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12306 {
12307 struct cleanup *back_to, *close_cleanup;
12308 int fd, remote_errno, bytes, io_size;
12309 gdb_byte *buffer;
12310 ULONGEST offset;
12311 struct remote_state *rs = get_remote_state ();
12312
12313 if (!rs->remote_desc)
12314 error (_("command can only be used with remote target"));
12315
12316 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12317 remote_file, FILEIO_O_RDONLY, 0, 0,
12318 &remote_errno);
12319 if (fd == -1)
12320 remote_hostio_error (remote_errno);
12321
12322 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12323 if (file == NULL)
12324 perror_with_name (local_file);
12325
12326 /* Send up to this many bytes at once. They won't all fit in the
12327 remote packet limit, so we'll transfer slightly fewer. */
12328 io_size = get_remote_packet_size ();
12329 buffer = (gdb_byte *) xmalloc (io_size);
12330 back_to = make_cleanup (xfree, buffer);
12331
12332 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12333
12334 offset = 0;
12335 while (1)
12336 {
12337 bytes = remote_hostio_pread (find_target_at (process_stratum),
12338 fd, buffer, io_size, offset, &remote_errno);
12339 if (bytes == 0)
12340 /* Success, but no bytes, means end-of-file. */
12341 break;
12342 if (bytes == -1)
12343 remote_hostio_error (remote_errno);
12344
12345 offset += bytes;
12346
12347 bytes = fwrite (buffer, 1, bytes, file.get ());
12348 if (bytes == 0)
12349 perror_with_name (local_file);
12350 }
12351
12352 discard_cleanups (close_cleanup);
12353 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12354 remote_hostio_error (remote_errno);
12355
12356 if (from_tty)
12357 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12358 do_cleanups (back_to);
12359 }
12360
12361 void
12362 remote_file_delete (const char *remote_file, int from_tty)
12363 {
12364 int retcode, remote_errno;
12365 struct remote_state *rs = get_remote_state ();
12366
12367 if (!rs->remote_desc)
12368 error (_("command can only be used with remote target"));
12369
12370 retcode = remote_hostio_unlink (find_target_at (process_stratum),
12371 NULL, remote_file, &remote_errno);
12372 if (retcode == -1)
12373 remote_hostio_error (remote_errno);
12374
12375 if (from_tty)
12376 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12377 }
12378
12379 static void
12380 remote_put_command (const char *args, int from_tty)
12381 {
12382 if (args == NULL)
12383 error_no_arg (_("file to put"));
12384
12385 gdb_argv argv (args);
12386 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12387 error (_("Invalid parameters to remote put"));
12388
12389 remote_file_put (argv[0], argv[1], from_tty);
12390 }
12391
12392 static void
12393 remote_get_command (const char *args, int from_tty)
12394 {
12395 if (args == NULL)
12396 error_no_arg (_("file to get"));
12397
12398 gdb_argv argv (args);
12399 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12400 error (_("Invalid parameters to remote get"));
12401
12402 remote_file_get (argv[0], argv[1], from_tty);
12403 }
12404
12405 static void
12406 remote_delete_command (const char *args, int from_tty)
12407 {
12408 if (args == NULL)
12409 error_no_arg (_("file to delete"));
12410
12411 gdb_argv argv (args);
12412 if (argv[0] == NULL || argv[1] != NULL)
12413 error (_("Invalid parameters to remote delete"));
12414
12415 remote_file_delete (argv[0], from_tty);
12416 }
12417
12418 static void
12419 remote_command (const char *args, int from_tty)
12420 {
12421 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12422 }
12423
12424 bool
12425 remote_target::can_execute_reverse ()
12426 {
12427 if (packet_support (PACKET_bs) == PACKET_ENABLE
12428 || packet_support (PACKET_bc) == PACKET_ENABLE)
12429 return true;
12430 else
12431 return false;
12432 }
12433
12434 bool
12435 remote_target::supports_non_stop ()
12436 {
12437 return true;
12438 }
12439
12440 bool
12441 remote_target::supports_disable_randomization ()
12442 {
12443 /* Only supported in extended mode. */
12444 return false;
12445 }
12446
12447 bool
12448 remote_target::supports_multi_process ()
12449 {
12450 struct remote_state *rs = get_remote_state ();
12451
12452 return remote_multi_process_p (rs);
12453 }
12454
12455 static int
12456 remote_supports_cond_tracepoints ()
12457 {
12458 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12459 }
12460
12461 bool
12462 remote_target::supports_evaluation_of_breakpoint_conditions ()
12463 {
12464 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12465 }
12466
12467 static int
12468 remote_supports_fast_tracepoints ()
12469 {
12470 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12471 }
12472
12473 static int
12474 remote_supports_static_tracepoints ()
12475 {
12476 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12477 }
12478
12479 static int
12480 remote_supports_install_in_trace ()
12481 {
12482 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12483 }
12484
12485 bool
12486 remote_target::supports_enable_disable_tracepoint ()
12487 {
12488 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12489 == PACKET_ENABLE);
12490 }
12491
12492 bool
12493 remote_target::supports_string_tracing ()
12494 {
12495 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12496 }
12497
12498 bool
12499 remote_target::can_run_breakpoint_commands ()
12500 {
12501 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12502 }
12503
12504 void
12505 remote_target::trace_init ()
12506 {
12507 struct remote_state *rs = get_remote_state ();
12508
12509 putpkt ("QTinit");
12510 remote_get_noisy_reply ();
12511 if (strcmp (rs->buf, "OK") != 0)
12512 error (_("Target does not support this command."));
12513 }
12514
12515 /* Recursive routine to walk through command list including loops, and
12516 download packets for each command. */
12517
12518 static void
12519 remote_download_command_source (int num, ULONGEST addr,
12520 struct command_line *cmds)
12521 {
12522 struct remote_state *rs = get_remote_state ();
12523 struct command_line *cmd;
12524
12525 for (cmd = cmds; cmd; cmd = cmd->next)
12526 {
12527 QUIT; /* Allow user to bail out with ^C. */
12528 strcpy (rs->buf, "QTDPsrc:");
12529 encode_source_string (num, addr, "cmd", cmd->line,
12530 rs->buf + strlen (rs->buf),
12531 rs->buf_size - strlen (rs->buf));
12532 putpkt (rs->buf);
12533 remote_get_noisy_reply ();
12534 if (strcmp (rs->buf, "OK"))
12535 warning (_("Target does not support source download."));
12536
12537 if (cmd->control_type == while_control
12538 || cmd->control_type == while_stepping_control)
12539 {
12540 remote_download_command_source (num, addr, cmd->body_list_0.get ());
12541
12542 QUIT; /* Allow user to bail out with ^C. */
12543 strcpy (rs->buf, "QTDPsrc:");
12544 encode_source_string (num, addr, "cmd", "end",
12545 rs->buf + strlen (rs->buf),
12546 rs->buf_size - strlen (rs->buf));
12547 putpkt (rs->buf);
12548 remote_get_noisy_reply ();
12549 if (strcmp (rs->buf, "OK"))
12550 warning (_("Target does not support source download."));
12551 }
12552 }
12553 }
12554
12555 void
12556 remote_target::download_tracepoint (struct bp_location *loc)
12557 {
12558 #define BUF_SIZE 2048
12559
12560 CORE_ADDR tpaddr;
12561 char addrbuf[40];
12562 char buf[BUF_SIZE];
12563 std::vector<std::string> tdp_actions;
12564 std::vector<std::string> stepping_actions;
12565 char *pkt;
12566 struct breakpoint *b = loc->owner;
12567 struct tracepoint *t = (struct tracepoint *) b;
12568 struct remote_state *rs = get_remote_state ();
12569
12570 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12571
12572 tpaddr = loc->address;
12573 sprintf_vma (addrbuf, tpaddr);
12574 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12575 addrbuf, /* address */
12576 (b->enable_state == bp_enabled ? 'E' : 'D'),
12577 t->step_count, t->pass_count);
12578 /* Fast tracepoints are mostly handled by the target, but we can
12579 tell the target how big of an instruction block should be moved
12580 around. */
12581 if (b->type == bp_fast_tracepoint)
12582 {
12583 /* Only test for support at download time; we may not know
12584 target capabilities at definition time. */
12585 if (remote_supports_fast_tracepoints ())
12586 {
12587 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12588 NULL))
12589 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12590 gdb_insn_length (loc->gdbarch, tpaddr));
12591 else
12592 /* If it passed validation at definition but fails now,
12593 something is very wrong. */
12594 internal_error (__FILE__, __LINE__,
12595 _("Fast tracepoint not "
12596 "valid during download"));
12597 }
12598 else
12599 /* Fast tracepoints are functionally identical to regular
12600 tracepoints, so don't take lack of support as a reason to
12601 give up on the trace run. */
12602 warning (_("Target does not support fast tracepoints, "
12603 "downloading %d as regular tracepoint"), b->number);
12604 }
12605 else if (b->type == bp_static_tracepoint)
12606 {
12607 /* Only test for support at download time; we may not know
12608 target capabilities at definition time. */
12609 if (remote_supports_static_tracepoints ())
12610 {
12611 struct static_tracepoint_marker marker;
12612
12613 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12614 strcat (buf, ":S");
12615 else
12616 error (_("Static tracepoint not valid during download"));
12617 }
12618 else
12619 /* Fast tracepoints are functionally identical to regular
12620 tracepoints, so don't take lack of support as a reason
12621 to give up on the trace run. */
12622 error (_("Target does not support static tracepoints"));
12623 }
12624 /* If the tracepoint has a conditional, make it into an agent
12625 expression and append to the definition. */
12626 if (loc->cond)
12627 {
12628 /* Only test support at download time, we may not know target
12629 capabilities at definition time. */
12630 if (remote_supports_cond_tracepoints ())
12631 {
12632 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12633 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12634 aexpr->len);
12635 pkt = buf + strlen (buf);
12636 for (int ndx = 0; ndx < aexpr->len; ++ndx)
12637 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12638 *pkt = '\0';
12639 }
12640 else
12641 warning (_("Target does not support conditional tracepoints, "
12642 "ignoring tp %d cond"), b->number);
12643 }
12644
12645 if (b->commands || *default_collect)
12646 strcat (buf, "-");
12647 putpkt (buf);
12648 remote_get_noisy_reply ();
12649 if (strcmp (rs->buf, "OK"))
12650 error (_("Target does not support tracepoints."));
12651
12652 /* do_single_steps (t); */
12653 for (auto action_it = tdp_actions.begin ();
12654 action_it != tdp_actions.end (); action_it++)
12655 {
12656 QUIT; /* Allow user to bail out with ^C. */
12657
12658 bool has_more = (action_it != tdp_actions.end ()
12659 || !stepping_actions.empty ());
12660
12661 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12662 b->number, addrbuf, /* address */
12663 action_it->c_str (),
12664 has_more ? '-' : 0);
12665 putpkt (buf);
12666 remote_get_noisy_reply ();
12667 if (strcmp (rs->buf, "OK"))
12668 error (_("Error on target while setting tracepoints."));
12669 }
12670
12671 for (auto action_it = stepping_actions.begin ();
12672 action_it != stepping_actions.end (); action_it++)
12673 {
12674 QUIT; /* Allow user to bail out with ^C. */
12675
12676 bool is_first = action_it == stepping_actions.begin ();
12677 bool has_more = action_it != stepping_actions.end ();
12678
12679 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12680 b->number, addrbuf, /* address */
12681 is_first ? "S" : "",
12682 action_it->c_str (),
12683 has_more ? "-" : "");
12684 putpkt (buf);
12685 remote_get_noisy_reply ();
12686 if (strcmp (rs->buf, "OK"))
12687 error (_("Error on target while setting tracepoints."));
12688 }
12689
12690 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12691 {
12692 if (b->location != NULL)
12693 {
12694 strcpy (buf, "QTDPsrc:");
12695 encode_source_string (b->number, loc->address, "at",
12696 event_location_to_string (b->location.get ()),
12697 buf + strlen (buf), 2048 - strlen (buf));
12698 putpkt (buf);
12699 remote_get_noisy_reply ();
12700 if (strcmp (rs->buf, "OK"))
12701 warning (_("Target does not support source download."));
12702 }
12703 if (b->cond_string)
12704 {
12705 strcpy (buf, "QTDPsrc:");
12706 encode_source_string (b->number, loc->address,
12707 "cond", b->cond_string, buf + strlen (buf),
12708 2048 - strlen (buf));
12709 putpkt (buf);
12710 remote_get_noisy_reply ();
12711 if (strcmp (rs->buf, "OK"))
12712 warning (_("Target does not support source download."));
12713 }
12714 remote_download_command_source (b->number, loc->address,
12715 breakpoint_commands (b));
12716 }
12717 }
12718
12719 bool
12720 remote_target::can_download_tracepoint ()
12721 {
12722 struct remote_state *rs = get_remote_state ();
12723 struct trace_status *ts;
12724 int status;
12725
12726 /* Don't try to install tracepoints until we've relocated our
12727 symbols, and fetched and merged the target's tracepoint list with
12728 ours. */
12729 if (rs->starting_up)
12730 return false;
12731
12732 ts = current_trace_status ();
12733 status = get_trace_status (ts);
12734
12735 if (status == -1 || !ts->running_known || !ts->running)
12736 return false;
12737
12738 /* If we are in a tracing experiment, but remote stub doesn't support
12739 installing tracepoint in trace, we have to return. */
12740 if (!remote_supports_install_in_trace ())
12741 return false;
12742
12743 return true;
12744 }
12745
12746
12747 void
12748 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12749 {
12750 struct remote_state *rs = get_remote_state ();
12751 char *p;
12752
12753 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12754 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12755 tsv.builtin);
12756 p = rs->buf + strlen (rs->buf);
12757 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12758 error (_("Trace state variable name too long for tsv definition packet"));
12759 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12760 *p++ = '\0';
12761 putpkt (rs->buf);
12762 remote_get_noisy_reply ();
12763 if (*rs->buf == '\0')
12764 error (_("Target does not support this command."));
12765 if (strcmp (rs->buf, "OK") != 0)
12766 error (_("Error on target while downloading trace state variable."));
12767 }
12768
12769 void
12770 remote_target::enable_tracepoint (struct bp_location *location)
12771 {
12772 struct remote_state *rs = get_remote_state ();
12773 char addr_buf[40];
12774
12775 sprintf_vma (addr_buf, location->address);
12776 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12777 location->owner->number, addr_buf);
12778 putpkt (rs->buf);
12779 remote_get_noisy_reply ();
12780 if (*rs->buf == '\0')
12781 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12782 if (strcmp (rs->buf, "OK") != 0)
12783 error (_("Error on target while enabling tracepoint."));
12784 }
12785
12786 void
12787 remote_target::disable_tracepoint (struct bp_location *location)
12788 {
12789 struct remote_state *rs = get_remote_state ();
12790 char addr_buf[40];
12791
12792 sprintf_vma (addr_buf, location->address);
12793 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12794 location->owner->number, addr_buf);
12795 putpkt (rs->buf);
12796 remote_get_noisy_reply ();
12797 if (*rs->buf == '\0')
12798 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12799 if (strcmp (rs->buf, "OK") != 0)
12800 error (_("Error on target while disabling tracepoint."));
12801 }
12802
12803 void
12804 remote_target::trace_set_readonly_regions ()
12805 {
12806 asection *s;
12807 bfd *abfd = NULL;
12808 bfd_size_type size;
12809 bfd_vma vma;
12810 int anysecs = 0;
12811 int offset = 0;
12812
12813 if (!exec_bfd)
12814 return; /* No information to give. */
12815
12816 struct remote_state *rs = get_remote_state ();
12817
12818 strcpy (rs->buf, "QTro");
12819 offset = strlen (rs->buf);
12820 for (s = exec_bfd->sections; s; s = s->next)
12821 {
12822 char tmp1[40], tmp2[40];
12823 int sec_length;
12824
12825 if ((s->flags & SEC_LOAD) == 0 ||
12826 /* (s->flags & SEC_CODE) == 0 || */
12827 (s->flags & SEC_READONLY) == 0)
12828 continue;
12829
12830 anysecs = 1;
12831 vma = bfd_get_section_vma (abfd, s);
12832 size = bfd_get_section_size (s);
12833 sprintf_vma (tmp1, vma);
12834 sprintf_vma (tmp2, vma + size);
12835 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12836 if (offset + sec_length + 1 > rs->buf_size)
12837 {
12838 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12839 warning (_("\
12840 Too many sections for read-only sections definition packet."));
12841 break;
12842 }
12843 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
12844 tmp1, tmp2);
12845 offset += sec_length;
12846 }
12847 if (anysecs)
12848 {
12849 putpkt (rs->buf);
12850 getpkt (&rs->buf, &rs->buf_size, 0);
12851 }
12852 }
12853
12854 void
12855 remote_target::trace_start ()
12856 {
12857 struct remote_state *rs = get_remote_state ();
12858
12859 putpkt ("QTStart");
12860 remote_get_noisy_reply ();
12861 if (*rs->buf == '\0')
12862 error (_("Target does not support this command."));
12863 if (strcmp (rs->buf, "OK") != 0)
12864 error (_("Bogus reply from target: %s"), rs->buf);
12865 }
12866
12867 int
12868 remote_target::get_trace_status (struct trace_status *ts)
12869 {
12870 /* Initialize it just to avoid a GCC false warning. */
12871 char *p = NULL;
12872 /* FIXME we need to get register block size some other way. */
12873 extern int trace_regblock_size;
12874 enum packet_result result;
12875 struct remote_state *rs = get_remote_state ();
12876
12877 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12878 return -1;
12879
12880 trace_regblock_size
12881 = get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
12882
12883 putpkt ("qTStatus");
12884
12885 TRY
12886 {
12887 p = remote_get_noisy_reply ();
12888 }
12889 CATCH (ex, RETURN_MASK_ERROR)
12890 {
12891 if (ex.error != TARGET_CLOSE_ERROR)
12892 {
12893 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12894 return -1;
12895 }
12896 throw_exception (ex);
12897 }
12898 END_CATCH
12899
12900 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12901
12902 /* If the remote target doesn't do tracing, flag it. */
12903 if (result == PACKET_UNKNOWN)
12904 return -1;
12905
12906 /* We're working with a live target. */
12907 ts->filename = NULL;
12908
12909 if (*p++ != 'T')
12910 error (_("Bogus trace status reply from target: %s"), rs->buf);
12911
12912 /* Function 'parse_trace_status' sets default value of each field of
12913 'ts' at first, so we don't have to do it here. */
12914 parse_trace_status (p, ts);
12915
12916 return ts->running;
12917 }
12918
12919 void
12920 remote_target::get_tracepoint_status (struct breakpoint *bp,
12921 struct uploaded_tp *utp)
12922 {
12923 struct remote_state *rs = get_remote_state ();
12924 char *reply;
12925 struct bp_location *loc;
12926 struct tracepoint *tp = (struct tracepoint *) bp;
12927 size_t size = get_remote_packet_size ();
12928
12929 if (tp)
12930 {
12931 tp->hit_count = 0;
12932 tp->traceframe_usage = 0;
12933 for (loc = tp->loc; loc; loc = loc->next)
12934 {
12935 /* If the tracepoint was never downloaded, don't go asking for
12936 any status. */
12937 if (tp->number_on_target == 0)
12938 continue;
12939 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12940 phex_nz (loc->address, 0));
12941 putpkt (rs->buf);
12942 reply = remote_get_noisy_reply ();
12943 if (reply && *reply)
12944 {
12945 if (*reply == 'V')
12946 parse_tracepoint_status (reply + 1, bp, utp);
12947 }
12948 }
12949 }
12950 else if (utp)
12951 {
12952 utp->hit_count = 0;
12953 utp->traceframe_usage = 0;
12954 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12955 phex_nz (utp->addr, 0));
12956 putpkt (rs->buf);
12957 reply = remote_get_noisy_reply ();
12958 if (reply && *reply)
12959 {
12960 if (*reply == 'V')
12961 parse_tracepoint_status (reply + 1, bp, utp);
12962 }
12963 }
12964 }
12965
12966 void
12967 remote_target::trace_stop ()
12968 {
12969 struct remote_state *rs = get_remote_state ();
12970
12971 putpkt ("QTStop");
12972 remote_get_noisy_reply ();
12973 if (*rs->buf == '\0')
12974 error (_("Target does not support this command."));
12975 if (strcmp (rs->buf, "OK") != 0)
12976 error (_("Bogus reply from target: %s"), rs->buf);
12977 }
12978
12979 int
12980 remote_target::trace_find (enum trace_find_type type, int num,
12981 CORE_ADDR addr1, CORE_ADDR addr2,
12982 int *tpp)
12983 {
12984 struct remote_state *rs = get_remote_state ();
12985 char *endbuf = rs->buf + get_remote_packet_size ();
12986 char *p, *reply;
12987 int target_frameno = -1, target_tracept = -1;
12988
12989 /* Lookups other than by absolute frame number depend on the current
12990 trace selected, so make sure it is correct on the remote end
12991 first. */
12992 if (type != tfind_number)
12993 set_remote_traceframe ();
12994
12995 p = rs->buf;
12996 strcpy (p, "QTFrame:");
12997 p = strchr (p, '\0');
12998 switch (type)
12999 {
13000 case tfind_number:
13001 xsnprintf (p, endbuf - p, "%x", num);
13002 break;
13003 case tfind_pc:
13004 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13005 break;
13006 case tfind_tp:
13007 xsnprintf (p, endbuf - p, "tdp:%x", num);
13008 break;
13009 case tfind_range:
13010 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13011 phex_nz (addr2, 0));
13012 break;
13013 case tfind_outside:
13014 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13015 phex_nz (addr2, 0));
13016 break;
13017 default:
13018 error (_("Unknown trace find type %d"), type);
13019 }
13020
13021 putpkt (rs->buf);
13022 reply = remote_get_noisy_reply ();
13023 if (*reply == '\0')
13024 error (_("Target does not support this command."));
13025
13026 while (reply && *reply)
13027 switch (*reply)
13028 {
13029 case 'F':
13030 p = ++reply;
13031 target_frameno = (int) strtol (p, &reply, 16);
13032 if (reply == p)
13033 error (_("Unable to parse trace frame number"));
13034 /* Don't update our remote traceframe number cache on failure
13035 to select a remote traceframe. */
13036 if (target_frameno == -1)
13037 return -1;
13038 break;
13039 case 'T':
13040 p = ++reply;
13041 target_tracept = (int) strtol (p, &reply, 16);
13042 if (reply == p)
13043 error (_("Unable to parse tracepoint number"));
13044 break;
13045 case 'O': /* "OK"? */
13046 if (reply[1] == 'K' && reply[2] == '\0')
13047 reply += 2;
13048 else
13049 error (_("Bogus reply from target: %s"), reply);
13050 break;
13051 default:
13052 error (_("Bogus reply from target: %s"), reply);
13053 }
13054 if (tpp)
13055 *tpp = target_tracept;
13056
13057 rs->remote_traceframe_number = target_frameno;
13058 return target_frameno;
13059 }
13060
13061 bool
13062 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13063 {
13064 struct remote_state *rs = get_remote_state ();
13065 char *reply;
13066 ULONGEST uval;
13067
13068 set_remote_traceframe ();
13069
13070 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13071 putpkt (rs->buf);
13072 reply = remote_get_noisy_reply ();
13073 if (reply && *reply)
13074 {
13075 if (*reply == 'V')
13076 {
13077 unpack_varlen_hex (reply + 1, &uval);
13078 *val = (LONGEST) uval;
13079 return true;
13080 }
13081 }
13082 return false;
13083 }
13084
13085 int
13086 remote_target::save_trace_data (const char *filename)
13087 {
13088 struct remote_state *rs = get_remote_state ();
13089 char *p, *reply;
13090
13091 p = rs->buf;
13092 strcpy (p, "QTSave:");
13093 p += strlen (p);
13094 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13095 error (_("Remote file name too long for trace save packet"));
13096 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13097 *p++ = '\0';
13098 putpkt (rs->buf);
13099 reply = remote_get_noisy_reply ();
13100 if (*reply == '\0')
13101 error (_("Target does not support this command."));
13102 if (strcmp (reply, "OK") != 0)
13103 error (_("Bogus reply from target: %s"), reply);
13104 return 0;
13105 }
13106
13107 /* This is basically a memory transfer, but needs to be its own packet
13108 because we don't know how the target actually organizes its trace
13109 memory, plus we want to be able to ask for as much as possible, but
13110 not be unhappy if we don't get as much as we ask for. */
13111
13112 LONGEST
13113 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13114 {
13115 struct remote_state *rs = get_remote_state ();
13116 char *reply;
13117 char *p;
13118 int rslt;
13119
13120 p = rs->buf;
13121 strcpy (p, "qTBuffer:");
13122 p += strlen (p);
13123 p += hexnumstr (p, offset);
13124 *p++ = ',';
13125 p += hexnumstr (p, len);
13126 *p++ = '\0';
13127
13128 putpkt (rs->buf);
13129 reply = remote_get_noisy_reply ();
13130 if (reply && *reply)
13131 {
13132 /* 'l' by itself means we're at the end of the buffer and
13133 there is nothing more to get. */
13134 if (*reply == 'l')
13135 return 0;
13136
13137 /* Convert the reply into binary. Limit the number of bytes to
13138 convert according to our passed-in buffer size, rather than
13139 what was returned in the packet; if the target is
13140 unexpectedly generous and gives us a bigger reply than we
13141 asked for, we don't want to crash. */
13142 rslt = hex2bin (reply, buf, len);
13143 return rslt;
13144 }
13145
13146 /* Something went wrong, flag as an error. */
13147 return -1;
13148 }
13149
13150 void
13151 remote_target::set_disconnected_tracing (int val)
13152 {
13153 struct remote_state *rs = get_remote_state ();
13154
13155 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13156 {
13157 char *reply;
13158
13159 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13160 putpkt (rs->buf);
13161 reply = remote_get_noisy_reply ();
13162 if (*reply == '\0')
13163 error (_("Target does not support this command."));
13164 if (strcmp (reply, "OK") != 0)
13165 error (_("Bogus reply from target: %s"), reply);
13166 }
13167 else if (val)
13168 warning (_("Target does not support disconnected tracing."));
13169 }
13170
13171 int
13172 remote_target::core_of_thread (ptid_t ptid)
13173 {
13174 struct thread_info *info = find_thread_ptid (ptid);
13175
13176 if (info != NULL && info->priv != NULL)
13177 return get_remote_thread_info (info)->core;
13178
13179 return -1;
13180 }
13181
13182 void
13183 remote_target::set_circular_trace_buffer (int val)
13184 {
13185 struct remote_state *rs = get_remote_state ();
13186 char *reply;
13187
13188 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13189 putpkt (rs->buf);
13190 reply = remote_get_noisy_reply ();
13191 if (*reply == '\0')
13192 error (_("Target does not support this command."));
13193 if (strcmp (reply, "OK") != 0)
13194 error (_("Bogus reply from target: %s"), reply);
13195 }
13196
13197 traceframe_info_up
13198 remote_target::traceframe_info ()
13199 {
13200 gdb::optional<gdb::char_vector> text
13201 = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
13202 NULL);
13203 if (text)
13204 return parse_traceframe_info (text->data ());
13205
13206 return NULL;
13207 }
13208
13209 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13210 instruction on which a fast tracepoint may be placed. Returns -1
13211 if the packet is not supported, and 0 if the minimum instruction
13212 length is unknown. */
13213
13214 int
13215 remote_target::get_min_fast_tracepoint_insn_len ()
13216 {
13217 struct remote_state *rs = get_remote_state ();
13218 char *reply;
13219
13220 /* If we're not debugging a process yet, the IPA can't be
13221 loaded. */
13222 if (!target_has_execution)
13223 return 0;
13224
13225 /* Make sure the remote is pointing at the right process. */
13226 set_general_process ();
13227
13228 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13229 putpkt (rs->buf);
13230 reply = remote_get_noisy_reply ();
13231 if (*reply == '\0')
13232 return -1;
13233 else
13234 {
13235 ULONGEST min_insn_len;
13236
13237 unpack_varlen_hex (reply, &min_insn_len);
13238
13239 return (int) min_insn_len;
13240 }
13241 }
13242
13243 void
13244 remote_target::set_trace_buffer_size (LONGEST val)
13245 {
13246 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13247 {
13248 struct remote_state *rs = get_remote_state ();
13249 char *buf = rs->buf;
13250 char *endbuf = rs->buf + get_remote_packet_size ();
13251 enum packet_result result;
13252
13253 gdb_assert (val >= 0 || val == -1);
13254 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13255 /* Send -1 as literal "-1" to avoid host size dependency. */
13256 if (val < 0)
13257 {
13258 *buf++ = '-';
13259 buf += hexnumstr (buf, (ULONGEST) -val);
13260 }
13261 else
13262 buf += hexnumstr (buf, (ULONGEST) val);
13263
13264 putpkt (rs->buf);
13265 remote_get_noisy_reply ();
13266 result = packet_ok (rs->buf,
13267 &remote_protocol_packets[PACKET_QTBuffer_size]);
13268
13269 if (result != PACKET_OK)
13270 warning (_("Bogus reply from target: %s"), rs->buf);
13271 }
13272 }
13273
13274 bool
13275 remote_target::set_trace_notes (const char *user, const char *notes,
13276 const char *stop_notes)
13277 {
13278 struct remote_state *rs = get_remote_state ();
13279 char *reply;
13280 char *buf = rs->buf;
13281 char *endbuf = rs->buf + get_remote_packet_size ();
13282 int nbytes;
13283
13284 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13285 if (user)
13286 {
13287 buf += xsnprintf (buf, endbuf - buf, "user:");
13288 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13289 buf += 2 * nbytes;
13290 *buf++ = ';';
13291 }
13292 if (notes)
13293 {
13294 buf += xsnprintf (buf, endbuf - buf, "notes:");
13295 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13296 buf += 2 * nbytes;
13297 *buf++ = ';';
13298 }
13299 if (stop_notes)
13300 {
13301 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13302 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13303 buf += 2 * nbytes;
13304 *buf++ = ';';
13305 }
13306 /* Ensure the buffer is terminated. */
13307 *buf = '\0';
13308
13309 putpkt (rs->buf);
13310 reply = remote_get_noisy_reply ();
13311 if (*reply == '\0')
13312 return false;
13313
13314 if (strcmp (reply, "OK") != 0)
13315 error (_("Bogus reply from target: %s"), reply);
13316
13317 return true;
13318 }
13319
13320 bool
13321 remote_target::use_agent (bool use)
13322 {
13323 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13324 {
13325 struct remote_state *rs = get_remote_state ();
13326
13327 /* If the stub supports QAgent. */
13328 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13329 putpkt (rs->buf);
13330 getpkt (&rs->buf, &rs->buf_size, 0);
13331
13332 if (strcmp (rs->buf, "OK") == 0)
13333 {
13334 ::use_agent = use;
13335 return true;
13336 }
13337 }
13338
13339 return false;
13340 }
13341
13342 bool
13343 remote_target::can_use_agent ()
13344 {
13345 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13346 }
13347
13348 struct btrace_target_info
13349 {
13350 /* The ptid of the traced thread. */
13351 ptid_t ptid;
13352
13353 /* The obtained branch trace configuration. */
13354 struct btrace_config conf;
13355 };
13356
13357 /* Reset our idea of our target's btrace configuration. */
13358
13359 static void
13360 remote_btrace_reset (void)
13361 {
13362 struct remote_state *rs = get_remote_state ();
13363
13364 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13365 }
13366
13367 /* Synchronize the configuration with the target. */
13368
13369 static void
13370 btrace_sync_conf (const struct btrace_config *conf)
13371 {
13372 struct packet_config *packet;
13373 struct remote_state *rs;
13374 char *buf, *pos, *endbuf;
13375
13376 rs = get_remote_state ();
13377 buf = rs->buf;
13378 endbuf = buf + get_remote_packet_size ();
13379
13380 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13381 if (packet_config_support (packet) == PACKET_ENABLE
13382 && conf->bts.size != rs->btrace_config.bts.size)
13383 {
13384 pos = buf;
13385 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13386 conf->bts.size);
13387
13388 putpkt (buf);
13389 getpkt (&buf, &rs->buf_size, 0);
13390
13391 if (packet_ok (buf, packet) == PACKET_ERROR)
13392 {
13393 if (buf[0] == 'E' && buf[1] == '.')
13394 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13395 else
13396 error (_("Failed to configure the BTS buffer size."));
13397 }
13398
13399 rs->btrace_config.bts.size = conf->bts.size;
13400 }
13401
13402 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13403 if (packet_config_support (packet) == PACKET_ENABLE
13404 && conf->pt.size != rs->btrace_config.pt.size)
13405 {
13406 pos = buf;
13407 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13408 conf->pt.size);
13409
13410 putpkt (buf);
13411 getpkt (&buf, &rs->buf_size, 0);
13412
13413 if (packet_ok (buf, packet) == PACKET_ERROR)
13414 {
13415 if (buf[0] == 'E' && buf[1] == '.')
13416 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13417 else
13418 error (_("Failed to configure the trace buffer size."));
13419 }
13420
13421 rs->btrace_config.pt.size = conf->pt.size;
13422 }
13423 }
13424
13425 /* Read the current thread's btrace configuration from the target and
13426 store it into CONF. */
13427
13428 static void
13429 btrace_read_config (struct btrace_config *conf)
13430 {
13431 gdb::optional<gdb::char_vector> xml
13432 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
13433 if (xml)
13434 parse_xml_btrace_conf (conf, xml->data ());
13435 }
13436
13437 /* Maybe reopen target btrace. */
13438
13439 static void
13440 remote_btrace_maybe_reopen (void)
13441 {
13442 struct remote_state *rs = get_remote_state ();
13443 struct thread_info *tp;
13444 int btrace_target_pushed = 0;
13445 int warned = 0;
13446
13447 scoped_restore_current_thread restore_thread;
13448
13449 ALL_NON_EXITED_THREADS (tp)
13450 {
13451 set_general_thread (tp->ptid);
13452
13453 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13454 btrace_read_config (&rs->btrace_config);
13455
13456 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13457 continue;
13458
13459 #if !defined (HAVE_LIBIPT)
13460 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13461 {
13462 if (!warned)
13463 {
13464 warned = 1;
13465 warning (_("Target is recording using Intel Processor Trace "
13466 "but support was disabled at compile time."));
13467 }
13468
13469 continue;
13470 }
13471 #endif /* !defined (HAVE_LIBIPT) */
13472
13473 /* Push target, once, but before anything else happens. This way our
13474 changes to the threads will be cleaned up by unpushing the target
13475 in case btrace_read_config () throws. */
13476 if (!btrace_target_pushed)
13477 {
13478 btrace_target_pushed = 1;
13479 record_btrace_push_target ();
13480 printf_filtered (_("Target is recording using %s.\n"),
13481 btrace_format_string (rs->btrace_config.format));
13482 }
13483
13484 tp->btrace.target = XCNEW (struct btrace_target_info);
13485 tp->btrace.target->ptid = tp->ptid;
13486 tp->btrace.target->conf = rs->btrace_config;
13487 }
13488 }
13489
13490 /* Enable branch tracing. */
13491
13492 struct btrace_target_info *
13493 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13494 {
13495 struct btrace_target_info *tinfo = NULL;
13496 struct packet_config *packet = NULL;
13497 struct remote_state *rs = get_remote_state ();
13498 char *buf = rs->buf;
13499 char *endbuf = rs->buf + get_remote_packet_size ();
13500
13501 switch (conf->format)
13502 {
13503 case BTRACE_FORMAT_BTS:
13504 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13505 break;
13506
13507 case BTRACE_FORMAT_PT:
13508 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13509 break;
13510 }
13511
13512 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13513 error (_("Target does not support branch tracing."));
13514
13515 btrace_sync_conf (conf);
13516
13517 set_general_thread (ptid);
13518
13519 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13520 putpkt (rs->buf);
13521 getpkt (&rs->buf, &rs->buf_size, 0);
13522
13523 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13524 {
13525 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13526 error (_("Could not enable branch tracing for %s: %s"),
13527 target_pid_to_str (ptid), rs->buf + 2);
13528 else
13529 error (_("Could not enable branch tracing for %s."),
13530 target_pid_to_str (ptid));
13531 }
13532
13533 tinfo = XCNEW (struct btrace_target_info);
13534 tinfo->ptid = ptid;
13535
13536 /* If we fail to read the configuration, we lose some information, but the
13537 tracing itself is not impacted. */
13538 TRY
13539 {
13540 btrace_read_config (&tinfo->conf);
13541 }
13542 CATCH (err, RETURN_MASK_ERROR)
13543 {
13544 if (err.message != NULL)
13545 warning ("%s", err.message);
13546 }
13547 END_CATCH
13548
13549 return tinfo;
13550 }
13551
13552 /* Disable branch tracing. */
13553
13554 void
13555 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13556 {
13557 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13558 struct remote_state *rs = get_remote_state ();
13559 char *buf = rs->buf;
13560 char *endbuf = rs->buf + get_remote_packet_size ();
13561
13562 if (packet_config_support (packet) != PACKET_ENABLE)
13563 error (_("Target does not support branch tracing."));
13564
13565 set_general_thread (tinfo->ptid);
13566
13567 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13568 putpkt (rs->buf);
13569 getpkt (&rs->buf, &rs->buf_size, 0);
13570
13571 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13572 {
13573 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13574 error (_("Could not disable branch tracing for %s: %s"),
13575 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13576 else
13577 error (_("Could not disable branch tracing for %s."),
13578 target_pid_to_str (tinfo->ptid));
13579 }
13580
13581 xfree (tinfo);
13582 }
13583
13584 /* Teardown branch tracing. */
13585
13586 void
13587 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13588 {
13589 /* We must not talk to the target during teardown. */
13590 xfree (tinfo);
13591 }
13592
13593 /* Read the branch trace. */
13594
13595 enum btrace_error
13596 remote_target::read_btrace (struct btrace_data *btrace,
13597 struct btrace_target_info *tinfo,
13598 enum btrace_read_type type)
13599 {
13600 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13601 const char *annex;
13602
13603 if (packet_config_support (packet) != PACKET_ENABLE)
13604 error (_("Target does not support branch tracing."));
13605
13606 #if !defined(HAVE_LIBEXPAT)
13607 error (_("Cannot process branch tracing result. XML parsing not supported."));
13608 #endif
13609
13610 switch (type)
13611 {
13612 case BTRACE_READ_ALL:
13613 annex = "all";
13614 break;
13615 case BTRACE_READ_NEW:
13616 annex = "new";
13617 break;
13618 case BTRACE_READ_DELTA:
13619 annex = "delta";
13620 break;
13621 default:
13622 internal_error (__FILE__, __LINE__,
13623 _("Bad branch tracing read type: %u."),
13624 (unsigned int) type);
13625 }
13626
13627 gdb::optional<gdb::char_vector> xml
13628 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
13629 if (!xml)
13630 return BTRACE_ERR_UNKNOWN;
13631
13632 parse_xml_btrace (btrace, xml->data ());
13633
13634 return BTRACE_ERR_NONE;
13635 }
13636
13637 const struct btrace_config *
13638 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13639 {
13640 return &tinfo->conf;
13641 }
13642
13643 bool
13644 remote_target::augmented_libraries_svr4_read ()
13645 {
13646 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13647 == PACKET_ENABLE);
13648 }
13649
13650 /* Implementation of to_load. */
13651
13652 void
13653 remote_target::load (const char *name, int from_tty)
13654 {
13655 generic_load (name, from_tty);
13656 }
13657
13658 /* Accepts an integer PID; returns a string representing a file that
13659 can be opened on the remote side to get the symbols for the child
13660 process. Returns NULL if the operation is not supported. */
13661
13662 char *
13663 remote_target::pid_to_exec_file (int pid)
13664 {
13665 static gdb::optional<gdb::char_vector> filename;
13666 struct inferior *inf;
13667 char *annex = NULL;
13668
13669 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13670 return NULL;
13671
13672 inf = find_inferior_pid (pid);
13673 if (inf == NULL)
13674 internal_error (__FILE__, __LINE__,
13675 _("not currently attached to process %d"), pid);
13676
13677 if (!inf->fake_pid_p)
13678 {
13679 const int annex_size = 9;
13680
13681 annex = (char *) alloca (annex_size);
13682 xsnprintf (annex, annex_size, "%x", pid);
13683 }
13684
13685 filename = target_read_stralloc (target_stack,
13686 TARGET_OBJECT_EXEC_FILE, annex);
13687
13688 return filename ? filename->data () : nullptr;
13689 }
13690
13691 /* Implement the to_can_do_single_step target_ops method. */
13692
13693 int
13694 remote_target::can_do_single_step ()
13695 {
13696 /* We can only tell whether target supports single step or not by
13697 supported s and S vCont actions if the stub supports vContSupported
13698 feature. If the stub doesn't support vContSupported feature,
13699 we have conservatively to think target doesn't supports single
13700 step. */
13701 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13702 {
13703 struct remote_state *rs = get_remote_state ();
13704
13705 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13706 remote_vcont_probe (rs);
13707
13708 return rs->supports_vCont.s && rs->supports_vCont.S;
13709 }
13710 else
13711 return 0;
13712 }
13713
13714 /* Implementation of the to_execution_direction method for the remote
13715 target. */
13716
13717 enum exec_direction_kind
13718 remote_target::execution_direction ()
13719 {
13720 struct remote_state *rs = get_remote_state ();
13721
13722 return rs->last_resume_exec_dir;
13723 }
13724
13725 /* Return pointer to the thread_info struct which corresponds to
13726 THREAD_HANDLE (having length HANDLE_LEN). */
13727
13728 thread_info *
13729 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13730 int handle_len,
13731 inferior *inf)
13732 {
13733 struct thread_info *tp;
13734
13735 ALL_NON_EXITED_THREADS (tp)
13736 {
13737 remote_thread_info *priv = get_remote_thread_info (tp);
13738
13739 if (tp->inf == inf && priv != NULL)
13740 {
13741 if (handle_len != priv->thread_handle.size ())
13742 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13743 handle_len, priv->thread_handle.size ());
13744 if (memcmp (thread_handle, priv->thread_handle.data (),
13745 handle_len) == 0)
13746 return tp;
13747 }
13748 }
13749
13750 return NULL;
13751 }
13752
13753 bool
13754 remote_target::can_async_p ()
13755 {
13756 struct remote_state *rs = get_remote_state ();
13757
13758 /* We don't go async if the user has explicitly prevented it with the
13759 "maint set target-async" command. */
13760 if (!target_async_permitted)
13761 return false;
13762
13763 /* We're async whenever the serial device is. */
13764 return serial_can_async_p (rs->remote_desc);
13765 }
13766
13767 bool
13768 remote_target::is_async_p ()
13769 {
13770 struct remote_state *rs = get_remote_state ();
13771
13772 if (!target_async_permitted)
13773 /* We only enable async when the user specifically asks for it. */
13774 return false;
13775
13776 /* We're async whenever the serial device is. */
13777 return serial_is_async_p (rs->remote_desc);
13778 }
13779
13780 /* Pass the SERIAL event on and up to the client. One day this code
13781 will be able to delay notifying the client of an event until the
13782 point where an entire packet has been received. */
13783
13784 static serial_event_ftype remote_async_serial_handler;
13785
13786 static void
13787 remote_async_serial_handler (struct serial *scb, void *context)
13788 {
13789 /* Don't propogate error information up to the client. Instead let
13790 the client find out about the error by querying the target. */
13791 inferior_event_handler (INF_REG_EVENT, NULL);
13792 }
13793
13794 static void
13795 remote_async_inferior_event_handler (gdb_client_data data)
13796 {
13797 inferior_event_handler (INF_REG_EVENT, NULL);
13798 }
13799
13800 void
13801 remote_target::async (int enable)
13802 {
13803 struct remote_state *rs = get_remote_state ();
13804
13805 if (enable)
13806 {
13807 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13808
13809 /* If there are pending events in the stop reply queue tell the
13810 event loop to process them. */
13811 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13812 mark_async_event_handler (remote_async_inferior_event_token);
13813 /* For simplicity, below we clear the pending events token
13814 without remembering whether it is marked, so here we always
13815 mark it. If there's actually no pending notification to
13816 process, this ends up being a no-op (other than a spurious
13817 event-loop wakeup). */
13818 if (target_is_non_stop_p ())
13819 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13820 }
13821 else
13822 {
13823 serial_async (rs->remote_desc, NULL, NULL);
13824 /* If the core is disabling async, it doesn't want to be
13825 disturbed with target events. Clear all async event sources
13826 too. */
13827 clear_async_event_handler (remote_async_inferior_event_token);
13828 if (target_is_non_stop_p ())
13829 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13830 }
13831 }
13832
13833 /* Implementation of the to_thread_events method. */
13834
13835 void
13836 remote_target::thread_events (int enable)
13837 {
13838 struct remote_state *rs = get_remote_state ();
13839 size_t size = get_remote_packet_size ();
13840
13841 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13842 return;
13843
13844 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13845 putpkt (rs->buf);
13846 getpkt (&rs->buf, &rs->buf_size, 0);
13847
13848 switch (packet_ok (rs->buf,
13849 &remote_protocol_packets[PACKET_QThreadEvents]))
13850 {
13851 case PACKET_OK:
13852 if (strcmp (rs->buf, "OK") != 0)
13853 error (_("Remote refused setting thread events: %s"), rs->buf);
13854 break;
13855 case PACKET_ERROR:
13856 warning (_("Remote failure reply: %s"), rs->buf);
13857 break;
13858 case PACKET_UNKNOWN:
13859 break;
13860 }
13861 }
13862
13863 static void
13864 set_remote_cmd (const char *args, int from_tty)
13865 {
13866 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13867 }
13868
13869 static void
13870 show_remote_cmd (const char *args, int from_tty)
13871 {
13872 /* We can't just use cmd_show_list here, because we want to skip
13873 the redundant "show remote Z-packet" and the legacy aliases. */
13874 struct cmd_list_element *list = remote_show_cmdlist;
13875 struct ui_out *uiout = current_uiout;
13876
13877 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13878 for (; list != NULL; list = list->next)
13879 if (strcmp (list->name, "Z-packet") == 0)
13880 continue;
13881 else if (list->type == not_set_cmd)
13882 /* Alias commands are exactly like the original, except they
13883 don't have the normal type. */
13884 continue;
13885 else
13886 {
13887 ui_out_emit_tuple option_emitter (uiout, "option");
13888
13889 uiout->field_string ("name", list->name);
13890 uiout->text (": ");
13891 if (list->type == show_cmd)
13892 do_show_command (NULL, from_tty, list);
13893 else
13894 cmd_func (list, NULL, from_tty);
13895 }
13896 }
13897
13898
13899 /* Function to be called whenever a new objfile (shlib) is detected. */
13900 static void
13901 remote_new_objfile (struct objfile *objfile)
13902 {
13903 struct remote_state *rs = get_remote_state ();
13904
13905 if (rs->remote_desc != 0) /* Have a remote connection. */
13906 remote_check_symbols ();
13907 }
13908
13909 /* Pull all the tracepoints defined on the target and create local
13910 data structures representing them. We don't want to create real
13911 tracepoints yet, we don't want to mess up the user's existing
13912 collection. */
13913
13914 int
13915 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
13916 {
13917 struct remote_state *rs = get_remote_state ();
13918 char *p;
13919
13920 /* Ask for a first packet of tracepoint definition. */
13921 putpkt ("qTfP");
13922 getpkt (&rs->buf, &rs->buf_size, 0);
13923 p = rs->buf;
13924 while (*p && *p != 'l')
13925 {
13926 parse_tracepoint_definition (p, utpp);
13927 /* Ask for another packet of tracepoint definition. */
13928 putpkt ("qTsP");
13929 getpkt (&rs->buf, &rs->buf_size, 0);
13930 p = rs->buf;
13931 }
13932 return 0;
13933 }
13934
13935 int
13936 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
13937 {
13938 struct remote_state *rs = get_remote_state ();
13939 char *p;
13940
13941 /* Ask for a first packet of variable definition. */
13942 putpkt ("qTfV");
13943 getpkt (&rs->buf, &rs->buf_size, 0);
13944 p = rs->buf;
13945 while (*p && *p != 'l')
13946 {
13947 parse_tsv_definition (p, utsvp);
13948 /* Ask for another packet of variable definition. */
13949 putpkt ("qTsV");
13950 getpkt (&rs->buf, &rs->buf_size, 0);
13951 p = rs->buf;
13952 }
13953 return 0;
13954 }
13955
13956 /* The "set/show range-stepping" show hook. */
13957
13958 static void
13959 show_range_stepping (struct ui_file *file, int from_tty,
13960 struct cmd_list_element *c,
13961 const char *value)
13962 {
13963 fprintf_filtered (file,
13964 _("Debugger's willingness to use range stepping "
13965 "is %s.\n"), value);
13966 }
13967
13968 /* The "set/show range-stepping" set hook. */
13969
13970 static void
13971 set_range_stepping (const char *ignore_args, int from_tty,
13972 struct cmd_list_element *c)
13973 {
13974 struct remote_state *rs = get_remote_state ();
13975
13976 /* Whene enabling, check whether range stepping is actually
13977 supported by the target, and warn if not. */
13978 if (use_range_stepping)
13979 {
13980 if (rs->remote_desc != NULL)
13981 {
13982 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13983 remote_vcont_probe (rs);
13984
13985 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13986 && rs->supports_vCont.r)
13987 return;
13988 }
13989
13990 warning (_("Range stepping is not supported by the current target"));
13991 }
13992 }
13993
13994 void
13995 _initialize_remote (void)
13996 {
13997 struct cmd_list_element *cmd;
13998 const char *cmd_name;
13999
14000 /* architecture specific data */
14001 remote_gdbarch_data_handle =
14002 gdbarch_data_register_post_init (init_remote_state);
14003 remote_g_packet_data_handle =
14004 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14005
14006 remote_pspace_data
14007 = register_program_space_data_with_cleanup (NULL,
14008 remote_pspace_data_cleanup);
14009
14010 /* Initialize the per-target state. At the moment there is only one
14011 of these, not one per target. Only one target is active at a
14012 time. */
14013 remote_state = new_remote_state ();
14014
14015 add_target (remote_target_info, remote_target::open);
14016 add_target (extended_remote_target_info, extended_remote_target::open);
14017
14018 /* Hook into new objfile notification. */
14019 gdb::observers::new_objfile.attach (remote_new_objfile);
14020 /* We're no longer interested in notification events of an inferior
14021 when it exits. */
14022 gdb::observers::inferior_exit.attach (discard_pending_stop_replies);
14023
14024 #if 0
14025 init_remote_threadtests ();
14026 #endif
14027
14028 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14029 /* set/show remote ... */
14030
14031 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14032 Remote protocol specific variables\n\
14033 Configure various remote-protocol specific variables such as\n\
14034 the packets being used"),
14035 &remote_set_cmdlist, "set remote ",
14036 0 /* allow-unknown */, &setlist);
14037 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14038 Remote protocol specific variables\n\
14039 Configure various remote-protocol specific variables such as\n\
14040 the packets being used"),
14041 &remote_show_cmdlist, "show remote ",
14042 0 /* allow-unknown */, &showlist);
14043
14044 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14045 Compare section data on target to the exec file.\n\
14046 Argument is a single section name (default: all loaded sections).\n\
14047 To compare only read-only loaded sections, specify the -r option."),
14048 &cmdlist);
14049
14050 add_cmd ("packet", class_maintenance, packet_command, _("\
14051 Send an arbitrary packet to a remote target.\n\
14052 maintenance packet TEXT\n\
14053 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14054 this command sends the string TEXT to the inferior, and displays the\n\
14055 response packet. GDB supplies the initial `$' character, and the\n\
14056 terminating `#' character and checksum."),
14057 &maintenancelist);
14058
14059 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14060 Set whether to send break if interrupted."), _("\
14061 Show whether to send break if interrupted."), _("\
14062 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14063 set_remotebreak, show_remotebreak,
14064 &setlist, &showlist);
14065 cmd_name = "remotebreak";
14066 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14067 deprecate_cmd (cmd, "set remote interrupt-sequence");
14068 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14069 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14070 deprecate_cmd (cmd, "show remote interrupt-sequence");
14071
14072 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14073 interrupt_sequence_modes, &interrupt_sequence_mode,
14074 _("\
14075 Set interrupt sequence to remote target."), _("\
14076 Show interrupt sequence to remote target."), _("\
14077 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14078 NULL, show_interrupt_sequence,
14079 &remote_set_cmdlist,
14080 &remote_show_cmdlist);
14081
14082 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14083 &interrupt_on_connect, _("\
14084 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14085 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14086 If set, interrupt sequence is sent to remote target."),
14087 NULL, NULL,
14088 &remote_set_cmdlist, &remote_show_cmdlist);
14089
14090 /* Install commands for configuring memory read/write packets. */
14091
14092 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14093 Set the maximum number of bytes per memory write packet (deprecated)."),
14094 &setlist);
14095 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14096 Show the maximum number of bytes per memory write packet (deprecated)."),
14097 &showlist);
14098 add_cmd ("memory-write-packet-size", no_class,
14099 set_memory_write_packet_size, _("\
14100 Set the maximum number of bytes per memory-write packet.\n\
14101 Specify the number of bytes in a packet or 0 (zero) for the\n\
14102 default packet size. The actual limit is further reduced\n\
14103 dependent on the target. Specify ``fixed'' to disable the\n\
14104 further restriction and ``limit'' to enable that restriction."),
14105 &remote_set_cmdlist);
14106 add_cmd ("memory-read-packet-size", no_class,
14107 set_memory_read_packet_size, _("\
14108 Set the maximum number of bytes per memory-read packet.\n\
14109 Specify the number of bytes in a packet or 0 (zero) for the\n\
14110 default packet size. The actual limit is further reduced\n\
14111 dependent on the target. Specify ``fixed'' to disable the\n\
14112 further restriction and ``limit'' to enable that restriction."),
14113 &remote_set_cmdlist);
14114 add_cmd ("memory-write-packet-size", no_class,
14115 show_memory_write_packet_size,
14116 _("Show the maximum number of bytes per memory-write packet."),
14117 &remote_show_cmdlist);
14118 add_cmd ("memory-read-packet-size", no_class,
14119 show_memory_read_packet_size,
14120 _("Show the maximum number of bytes per memory-read packet."),
14121 &remote_show_cmdlist);
14122
14123 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14124 &remote_hw_watchpoint_limit, _("\
14125 Set the maximum number of target hardware watchpoints."), _("\
14126 Show the maximum number of target hardware watchpoints."), _("\
14127 Specify a negative limit for unlimited."),
14128 NULL, NULL, /* FIXME: i18n: The maximum
14129 number of target hardware
14130 watchpoints is %s. */
14131 &remote_set_cmdlist, &remote_show_cmdlist);
14132 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14133 &remote_hw_watchpoint_length_limit, _("\
14134 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14135 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14136 Specify a negative limit for unlimited."),
14137 NULL, NULL, /* FIXME: i18n: The maximum
14138 length (in bytes) of a target
14139 hardware watchpoint is %s. */
14140 &remote_set_cmdlist, &remote_show_cmdlist);
14141 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14142 &remote_hw_breakpoint_limit, _("\
14143 Set the maximum number of target hardware breakpoints."), _("\
14144 Show the maximum number of target hardware breakpoints."), _("\
14145 Specify a negative limit for unlimited."),
14146 NULL, NULL, /* FIXME: i18n: The maximum
14147 number of target hardware
14148 breakpoints is %s. */
14149 &remote_set_cmdlist, &remote_show_cmdlist);
14150
14151 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14152 &remote_address_size, _("\
14153 Set the maximum size of the address (in bits) in a memory packet."), _("\
14154 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14155 NULL,
14156 NULL, /* FIXME: i18n: */
14157 &setlist, &showlist);
14158
14159 init_all_packet_configs ();
14160
14161 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14162 "X", "binary-download", 1);
14163
14164 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14165 "vCont", "verbose-resume", 0);
14166
14167 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14168 "QPassSignals", "pass-signals", 0);
14169
14170 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14171 "QCatchSyscalls", "catch-syscalls", 0);
14172
14173 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14174 "QProgramSignals", "program-signals", 0);
14175
14176 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14177 "QSetWorkingDir", "set-working-dir", 0);
14178
14179 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14180 "QStartupWithShell", "startup-with-shell", 0);
14181
14182 add_packet_config_cmd (&remote_protocol_packets
14183 [PACKET_QEnvironmentHexEncoded],
14184 "QEnvironmentHexEncoded", "environment-hex-encoded",
14185 0);
14186
14187 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14188 "QEnvironmentReset", "environment-reset",
14189 0);
14190
14191 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14192 "QEnvironmentUnset", "environment-unset",
14193 0);
14194
14195 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14196 "qSymbol", "symbol-lookup", 0);
14197
14198 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14199 "P", "set-register", 1);
14200
14201 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14202 "p", "fetch-register", 1);
14203
14204 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14205 "Z0", "software-breakpoint", 0);
14206
14207 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14208 "Z1", "hardware-breakpoint", 0);
14209
14210 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14211 "Z2", "write-watchpoint", 0);
14212
14213 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14214 "Z3", "read-watchpoint", 0);
14215
14216 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14217 "Z4", "access-watchpoint", 0);
14218
14219 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14220 "qXfer:auxv:read", "read-aux-vector", 0);
14221
14222 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14223 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14224
14225 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14226 "qXfer:features:read", "target-features", 0);
14227
14228 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14229 "qXfer:libraries:read", "library-info", 0);
14230
14231 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14232 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14233
14234 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14235 "qXfer:memory-map:read", "memory-map", 0);
14236
14237 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14238 "qXfer:spu:read", "read-spu-object", 0);
14239
14240 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14241 "qXfer:spu:write", "write-spu-object", 0);
14242
14243 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14244 "qXfer:osdata:read", "osdata", 0);
14245
14246 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14247 "qXfer:threads:read", "threads", 0);
14248
14249 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14250 "qXfer:siginfo:read", "read-siginfo-object", 0);
14251
14252 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14253 "qXfer:siginfo:write", "write-siginfo-object", 0);
14254
14255 add_packet_config_cmd
14256 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14257 "qXfer:traceframe-info:read", "traceframe-info", 0);
14258
14259 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14260 "qXfer:uib:read", "unwind-info-block", 0);
14261
14262 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14263 "qGetTLSAddr", "get-thread-local-storage-address",
14264 0);
14265
14266 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14267 "qGetTIBAddr", "get-thread-information-block-address",
14268 0);
14269
14270 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14271 "bc", "reverse-continue", 0);
14272
14273 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14274 "bs", "reverse-step", 0);
14275
14276 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14277 "qSupported", "supported-packets", 0);
14278
14279 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14280 "qSearch:memory", "search-memory", 0);
14281
14282 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14283 "qTStatus", "trace-status", 0);
14284
14285 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14286 "vFile:setfs", "hostio-setfs", 0);
14287
14288 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14289 "vFile:open", "hostio-open", 0);
14290
14291 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14292 "vFile:pread", "hostio-pread", 0);
14293
14294 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14295 "vFile:pwrite", "hostio-pwrite", 0);
14296
14297 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14298 "vFile:close", "hostio-close", 0);
14299
14300 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14301 "vFile:unlink", "hostio-unlink", 0);
14302
14303 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14304 "vFile:readlink", "hostio-readlink", 0);
14305
14306 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14307 "vFile:fstat", "hostio-fstat", 0);
14308
14309 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14310 "vAttach", "attach", 0);
14311
14312 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14313 "vRun", "run", 0);
14314
14315 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14316 "QStartNoAckMode", "noack", 0);
14317
14318 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14319 "vKill", "kill", 0);
14320
14321 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14322 "qAttached", "query-attached", 0);
14323
14324 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14325 "ConditionalTracepoints",
14326 "conditional-tracepoints", 0);
14327
14328 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14329 "ConditionalBreakpoints",
14330 "conditional-breakpoints", 0);
14331
14332 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14333 "BreakpointCommands",
14334 "breakpoint-commands", 0);
14335
14336 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14337 "FastTracepoints", "fast-tracepoints", 0);
14338
14339 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14340 "TracepointSource", "TracepointSource", 0);
14341
14342 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14343 "QAllow", "allow", 0);
14344
14345 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14346 "StaticTracepoints", "static-tracepoints", 0);
14347
14348 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14349 "InstallInTrace", "install-in-trace", 0);
14350
14351 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14352 "qXfer:statictrace:read", "read-sdata-object", 0);
14353
14354 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14355 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14356
14357 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14358 "QDisableRandomization", "disable-randomization", 0);
14359
14360 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14361 "QAgent", "agent", 0);
14362
14363 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14364 "QTBuffer:size", "trace-buffer-size", 0);
14365
14366 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14367 "Qbtrace:off", "disable-btrace", 0);
14368
14369 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14370 "Qbtrace:bts", "enable-btrace-bts", 0);
14371
14372 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14373 "Qbtrace:pt", "enable-btrace-pt", 0);
14374
14375 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14376 "qXfer:btrace", "read-btrace", 0);
14377
14378 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14379 "qXfer:btrace-conf", "read-btrace-conf", 0);
14380
14381 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14382 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14383
14384 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14385 "multiprocess-feature", "multiprocess-feature", 0);
14386
14387 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14388 "swbreak-feature", "swbreak-feature", 0);
14389
14390 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14391 "hwbreak-feature", "hwbreak-feature", 0);
14392
14393 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14394 "fork-event-feature", "fork-event-feature", 0);
14395
14396 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14397 "vfork-event-feature", "vfork-event-feature", 0);
14398
14399 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14400 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14401
14402 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14403 "vContSupported", "verbose-resume-supported", 0);
14404
14405 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14406 "exec-event-feature", "exec-event-feature", 0);
14407
14408 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14409 "vCtrlC", "ctrl-c", 0);
14410
14411 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14412 "QThreadEvents", "thread-events", 0);
14413
14414 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14415 "N stop reply", "no-resumed-stop-reply", 0);
14416
14417 /* Assert that we've registered "set remote foo-packet" commands
14418 for all packet configs. */
14419 {
14420 int i;
14421
14422 for (i = 0; i < PACKET_MAX; i++)
14423 {
14424 /* Ideally all configs would have a command associated. Some
14425 still don't though. */
14426 int excepted;
14427
14428 switch (i)
14429 {
14430 case PACKET_QNonStop:
14431 case PACKET_EnableDisableTracepoints_feature:
14432 case PACKET_tracenz_feature:
14433 case PACKET_DisconnectedTracing_feature:
14434 case PACKET_augmented_libraries_svr4_read_feature:
14435 case PACKET_qCRC:
14436 /* Additions to this list need to be well justified:
14437 pre-existing packets are OK; new packets are not. */
14438 excepted = 1;
14439 break;
14440 default:
14441 excepted = 0;
14442 break;
14443 }
14444
14445 /* This catches both forgetting to add a config command, and
14446 forgetting to remove a packet from the exception list. */
14447 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14448 }
14449 }
14450
14451 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14452 Z sub-packet has its own set and show commands, but users may
14453 have sets to this variable in their .gdbinit files (or in their
14454 documentation). */
14455 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14456 &remote_Z_packet_detect, _("\
14457 Set use of remote protocol `Z' packets"), _("\
14458 Show use of remote protocol `Z' packets "), _("\
14459 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14460 packets."),
14461 set_remote_protocol_Z_packet_cmd,
14462 show_remote_protocol_Z_packet_cmd,
14463 /* FIXME: i18n: Use of remote protocol
14464 `Z' packets is %s. */
14465 &remote_set_cmdlist, &remote_show_cmdlist);
14466
14467 add_prefix_cmd ("remote", class_files, remote_command, _("\
14468 Manipulate files on the remote system\n\
14469 Transfer files to and from the remote target system."),
14470 &remote_cmdlist, "remote ",
14471 0 /* allow-unknown */, &cmdlist);
14472
14473 add_cmd ("put", class_files, remote_put_command,
14474 _("Copy a local file to the remote system."),
14475 &remote_cmdlist);
14476
14477 add_cmd ("get", class_files, remote_get_command,
14478 _("Copy a remote file to the local system."),
14479 &remote_cmdlist);
14480
14481 add_cmd ("delete", class_files, remote_delete_command,
14482 _("Delete a remote file."),
14483 &remote_cmdlist);
14484
14485 add_setshow_string_noescape_cmd ("exec-file", class_files,
14486 &remote_exec_file_var, _("\
14487 Set the remote pathname for \"run\""), _("\
14488 Show the remote pathname for \"run\""), NULL,
14489 set_remote_exec_file,
14490 show_remote_exec_file,
14491 &remote_set_cmdlist,
14492 &remote_show_cmdlist);
14493
14494 add_setshow_boolean_cmd ("range-stepping", class_run,
14495 &use_range_stepping, _("\
14496 Enable or disable range stepping."), _("\
14497 Show whether target-assisted range stepping is enabled."), _("\
14498 If on, and the target supports it, when stepping a source line, GDB\n\
14499 tells the target to step the corresponding range of addresses itself instead\n\
14500 of issuing multiple single-steps. This speeds up source level\n\
14501 stepping. If off, GDB always issues single-steps, even if range\n\
14502 stepping is supported by the target. The default is on."),
14503 set_range_stepping,
14504 show_range_stepping,
14505 &setlist,
14506 &showlist);
14507
14508 /* Eventually initialize fileio. See fileio.c */
14509 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14510
14511 /* Take advantage of the fact that the TID field is not used, to tag
14512 special ptids with it set to != 0. */
14513 magic_null_ptid = ptid_build (42000, -1, 1);
14514 not_sent_ptid = ptid_build (42000, -2, 1);
14515 any_thread_ptid = ptid_build (42000, 0, 1);
14516 }
This page took 0.347428 seconds and 5 git commands to generate.