cf56a5636aa06b7cfefd01d08ebe2be34f0279d3
[deliverable/binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2018 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* See the GDB User Guide for details of the GDB remote protocol. */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 /*#include "terminal.h" */
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observable.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "filestuff.h"
46 #include "rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdb_sys_time.h"
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "common/scoped_restore.h"
76 #include "environ.h"
77 #include "common/byte-vector.h"
78 #include <unordered_map>
79
80 /* The remote target. */
81
82 static const char remote_doc[] = N_("\
83 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
84 Specify the serial device it is connected to\n\
85 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
86
87 #define OPAQUETHREADBYTES 8
88
89 /* a 64 bit opaque identifier */
90 typedef unsigned char threadref[OPAQUETHREADBYTES];
91
92 struct gdb_ext_thread_info;
93 struct threads_listing_context;
94 typedef int (*rmt_thread_action) (threadref *ref, void *context);
95 struct protocol_feature;
96 struct packet_reg;
97
98 struct stop_reply;
99 static void stop_reply_xfree (struct stop_reply *);
100
101 struct stop_reply_deleter
102 {
103 void operator() (stop_reply *r) const
104 {
105 stop_reply_xfree (r);
106 }
107 };
108
109 typedef std::unique_ptr<stop_reply, stop_reply_deleter> stop_reply_up;
110
111 /* Generic configuration support for packets the stub optionally
112 supports. Allows the user to specify the use of the packet as well
113 as allowing GDB to auto-detect support in the remote stub. */
114
115 enum packet_support
116 {
117 PACKET_SUPPORT_UNKNOWN = 0,
118 PACKET_ENABLE,
119 PACKET_DISABLE
120 };
121
122 /* Analyze a packet's return value and update the packet config
123 accordingly. */
124
125 enum packet_result
126 {
127 PACKET_ERROR,
128 PACKET_OK,
129 PACKET_UNKNOWN
130 };
131
132 struct threads_listing_context;
133
134 /* Stub vCont actions support.
135
136 Each field is a boolean flag indicating whether the stub reports
137 support for the corresponding action. */
138
139 struct vCont_action_support
140 {
141 /* vCont;t */
142 bool t = false;
143
144 /* vCont;r */
145 bool r = false;
146
147 /* vCont;s */
148 bool s = false;
149
150 /* vCont;S */
151 bool S = false;
152 };
153
154 /* About this many threadisds fit in a packet. */
155
156 #define MAXTHREADLISTRESULTS 32
157
158 /* Data for the vFile:pread readahead cache. */
159
160 struct readahead_cache
161 {
162 /* Invalidate the readahead cache. */
163 void invalidate ();
164
165 /* Invalidate the readahead cache if it is holding data for FD. */
166 void invalidate_fd (int fd);
167
168 /* Serve pread from the readahead cache. Returns number of bytes
169 read, or 0 if the request can't be served from the cache. */
170 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
171
172 /* The file descriptor for the file that is being cached. -1 if the
173 cache is invalid. */
174 int fd = -1;
175
176 /* The offset into the file that the cache buffer corresponds
177 to. */
178 ULONGEST offset = 0;
179
180 /* The buffer holding the cache contents. */
181 gdb_byte *buf = nullptr;
182 /* The buffer's size. We try to read as much as fits into a packet
183 at a time. */
184 size_t bufsize = 0;
185
186 /* Cache hit and miss counters. */
187 ULONGEST hit_count = 0;
188 ULONGEST miss_count = 0;
189 };
190
191 /* Description of the remote protocol for a given architecture. */
192
193 struct packet_reg
194 {
195 long offset; /* Offset into G packet. */
196 long regnum; /* GDB's internal register number. */
197 LONGEST pnum; /* Remote protocol register number. */
198 int in_g_packet; /* Always part of G packet. */
199 /* long size in bytes; == register_size (target_gdbarch (), regnum);
200 at present. */
201 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
202 at present. */
203 };
204
205 struct remote_arch_state
206 {
207 explicit remote_arch_state (struct gdbarch *gdbarch);
208
209 /* Description of the remote protocol registers. */
210 long sizeof_g_packet;
211
212 /* Description of the remote protocol registers indexed by REGNUM
213 (making an array gdbarch_num_regs in size). */
214 std::unique_ptr<packet_reg[]> regs;
215
216 /* This is the size (in chars) of the first response to the ``g''
217 packet. It is used as a heuristic when determining the maximum
218 size of memory-read and memory-write packets. A target will
219 typically only reserve a buffer large enough to hold the ``g''
220 packet. The size does not include packet overhead (headers and
221 trailers). */
222 long actual_register_packet_size;
223
224 /* This is the maximum size (in chars) of a non read/write packet.
225 It is also used as a cap on the size of read/write packets. */
226 long remote_packet_size;
227 };
228
229 /* Description of the remote protocol state for the currently
230 connected target. This is per-target state, and independent of the
231 selected architecture. */
232
233 class remote_state
234 {
235 public:
236
237 remote_state ();
238 ~remote_state ();
239
240 /* Get the remote arch state for GDBARCH. */
241 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
242
243 public: /* data */
244
245 /* A buffer to use for incoming packets, and its current size. The
246 buffer is grown dynamically for larger incoming packets.
247 Outgoing packets may also be constructed in this buffer.
248 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
249 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
250 packets. */
251 char *buf;
252 long buf_size;
253
254 /* True if we're going through initial connection setup (finding out
255 about the remote side's threads, relocating symbols, etc.). */
256 bool starting_up = false;
257
258 /* If we negotiated packet size explicitly (and thus can bypass
259 heuristics for the largest packet size that will not overflow
260 a buffer in the stub), this will be set to that packet size.
261 Otherwise zero, meaning to use the guessed size. */
262 long explicit_packet_size = 0;
263
264 /* remote_wait is normally called when the target is running and
265 waits for a stop reply packet. But sometimes we need to call it
266 when the target is already stopped. We can send a "?" packet
267 and have remote_wait read the response. Or, if we already have
268 the response, we can stash it in BUF and tell remote_wait to
269 skip calling getpkt. This flag is set when BUF contains a
270 stop reply packet and the target is not waiting. */
271 int cached_wait_status = 0;
272
273 /* True, if in no ack mode. That is, neither GDB nor the stub will
274 expect acks from each other. The connection is assumed to be
275 reliable. */
276 bool noack_mode = false;
277
278 /* True if we're connected in extended remote mode. */
279 bool extended = false;
280
281 /* True if we resumed the target and we're waiting for the target to
282 stop. In the mean time, we can't start another command/query.
283 The remote server wouldn't be ready to process it, so we'd
284 timeout waiting for a reply that would never come and eventually
285 we'd close the connection. This can happen in asynchronous mode
286 because we allow GDB commands while the target is running. */
287 bool waiting_for_stop_reply = false;
288
289 /* The status of the stub support for the various vCont actions. */
290 vCont_action_support supports_vCont;
291
292 /* True if the user has pressed Ctrl-C, but the target hasn't
293 responded to that. */
294 bool ctrlc_pending_p = false;
295
296 /* True if we saw a Ctrl-C while reading or writing from/to the
297 remote descriptor. At that point it is not safe to send a remote
298 interrupt packet, so we instead remember we saw the Ctrl-C and
299 process it once we're done with sending/receiving the current
300 packet, which should be shortly. If however that takes too long,
301 and the user presses Ctrl-C again, we offer to disconnect. */
302 bool got_ctrlc_during_io = false;
303
304 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
305 remote_open knows that we don't have a file open when the program
306 starts. */
307 struct serial *remote_desc = nullptr;
308
309 /* These are the threads which we last sent to the remote system. The
310 TID member will be -1 for all or -2 for not sent yet. */
311 ptid_t general_thread = null_ptid;
312 ptid_t continue_thread = null_ptid;
313
314 /* This is the traceframe which we last selected on the remote system.
315 It will be -1 if no traceframe is selected. */
316 int remote_traceframe_number = -1;
317
318 char *last_pass_packet = nullptr;
319
320 /* The last QProgramSignals packet sent to the target. We bypass
321 sending a new program signals list down to the target if the new
322 packet is exactly the same as the last we sent. IOW, we only let
323 the target know about program signals list changes. */
324 char *last_program_signals_packet = nullptr;
325
326 gdb_signal last_sent_signal = GDB_SIGNAL_0;
327
328 bool last_sent_step = false;
329
330 /* The execution direction of the last resume we got. */
331 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
332
333 char *finished_object = nullptr;
334 char *finished_annex = nullptr;
335 ULONGEST finished_offset = 0;
336
337 /* Should we try the 'ThreadInfo' query packet?
338
339 This variable (NOT available to the user: auto-detect only!)
340 determines whether GDB will use the new, simpler "ThreadInfo"
341 query or the older, more complex syntax for thread queries.
342 This is an auto-detect variable (set to true at each connect,
343 and set to false when the target fails to recognize it). */
344 bool use_threadinfo_query = false;
345 bool use_threadextra_query = false;
346
347 threadref echo_nextthread {};
348 threadref nextthread {};
349 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
350
351 /* The state of remote notification. */
352 struct remote_notif_state *notif_state = nullptr;
353
354 /* The branch trace configuration. */
355 struct btrace_config btrace_config {};
356
357 /* The argument to the last "vFile:setfs:" packet we sent, used
358 to avoid sending repeated unnecessary "vFile:setfs:" packets.
359 Initialized to -1 to indicate that no "vFile:setfs:" packet
360 has yet been sent. */
361 int fs_pid = -1;
362
363 /* A readahead cache for vFile:pread. Often, reading a binary
364 involves a sequence of small reads. E.g., when parsing an ELF
365 file. A readahead cache helps mostly the case of remote
366 debugging on a connection with higher latency, due to the
367 request/reply nature of the RSP. We only cache data for a single
368 file descriptor at a time. */
369 struct readahead_cache readahead_cache;
370
371 /* The list of already fetched and acknowledged stop events. This
372 queue is used for notification Stop, and other notifications
373 don't need queue for their events, because the notification
374 events of Stop can't be consumed immediately, so that events
375 should be queued first, and be consumed by remote_wait_{ns,as}
376 one per time. Other notifications can consume their events
377 immediately, so queue is not needed for them. */
378 std::vector<stop_reply_up> stop_reply_queue;
379
380 /* Asynchronous signal handle registered as event loop source for
381 when we have pending events ready to be passed to the core. */
382 struct async_event_handler *remote_async_inferior_event_token = nullptr;
383
384 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
385 ``forever'' still use the normal timeout mechanism. This is
386 currently used by the ASYNC code to guarentee that target reads
387 during the initial connect always time-out. Once getpkt has been
388 modified to return a timeout indication and, in turn
389 remote_wait()/wait_for_inferior() have gained a timeout parameter
390 this can go away. */
391 int wait_forever_enabled_p = 1;
392
393 private:
394 /* Mapping of remote protocol data for each gdbarch. Usually there
395 is only one entry here, though we may see more with stubs that
396 support multi-process. */
397 std::unordered_map<struct gdbarch *, remote_arch_state>
398 m_arch_states;
399 };
400
401 static const target_info remote_target_info = {
402 "remote",
403 N_("Remote serial target in gdb-specific protocol"),
404 remote_doc
405 };
406
407 class remote_target : public target_ops
408 {
409 public:
410 remote_target ()
411 {
412 to_stratum = process_stratum;
413 }
414 ~remote_target () override;
415
416 const target_info &info () const override
417 { return remote_target_info; }
418
419 thread_control_capabilities get_thread_control_capabilities () override
420 { return tc_schedlock; }
421
422 /* Open a remote connection. */
423 static void open (const char *, int);
424
425 void close () override;
426
427 void detach (inferior *, int) override;
428 void disconnect (const char *, int) override;
429
430 void commit_resume () override;
431 void resume (ptid_t, int, enum gdb_signal) override;
432 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
433
434 void fetch_registers (struct regcache *, int) override;
435 void store_registers (struct regcache *, int) override;
436 void prepare_to_store (struct regcache *) override;
437
438 void files_info () override;
439
440 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
441
442 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
443 enum remove_bp_reason) override;
444
445
446 bool stopped_by_sw_breakpoint () override;
447 bool supports_stopped_by_sw_breakpoint () override;
448
449 bool stopped_by_hw_breakpoint () override;
450
451 bool supports_stopped_by_hw_breakpoint () override;
452
453 bool stopped_by_watchpoint () override;
454
455 bool stopped_data_address (CORE_ADDR *) override;
456
457 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
458
459 int can_use_hw_breakpoint (enum bptype, int, int) override;
460
461 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
462
463 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
464
465 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
466
467 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
468 struct expression *) override;
469
470 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
471 struct expression *) override;
472
473 void kill () override;
474
475 void load (const char *, int) override;
476
477 void mourn_inferior () override;
478
479 void pass_signals (int, unsigned char *) override;
480
481 int set_syscall_catchpoint (int, bool, int,
482 gdb::array_view<const int>) override;
483
484 void program_signals (int, unsigned char *) override;
485
486 bool thread_alive (ptid_t ptid) override;
487
488 const char *thread_name (struct thread_info *) override;
489
490 void update_thread_list () override;
491
492 const char *pid_to_str (ptid_t) override;
493
494 const char *extra_thread_info (struct thread_info *) override;
495
496 ptid_t get_ada_task_ptid (long lwp, long thread) override;
497
498 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
499 int handle_len,
500 inferior *inf) override;
501
502 void stop (ptid_t) override;
503
504 void interrupt () override;
505
506 void pass_ctrlc () override;
507
508 enum target_xfer_status xfer_partial (enum target_object object,
509 const char *annex,
510 gdb_byte *readbuf,
511 const gdb_byte *writebuf,
512 ULONGEST offset, ULONGEST len,
513 ULONGEST *xfered_len) override;
514
515 ULONGEST get_memory_xfer_limit () override;
516
517 void rcmd (const char *command, struct ui_file *output) override;
518
519 char *pid_to_exec_file (int pid) override;
520
521 void log_command (const char *cmd) override
522 {
523 serial_log_command (this, cmd);
524 }
525
526 CORE_ADDR get_thread_local_address (ptid_t ptid,
527 CORE_ADDR load_module_addr,
528 CORE_ADDR offset) override;
529
530 bool has_all_memory () override { return default_child_has_all_memory (); }
531 bool has_memory () override { return default_child_has_memory (); }
532 bool has_stack () override { return default_child_has_stack (); }
533 bool has_registers () override { return default_child_has_registers (); }
534 bool has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
535
536 bool can_execute_reverse () override;
537
538 std::vector<mem_region> memory_map () override;
539
540 void flash_erase (ULONGEST address, LONGEST length) override;
541
542 void flash_done () override;
543
544 const struct target_desc *read_description () override;
545
546 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
547 const gdb_byte *pattern, ULONGEST pattern_len,
548 CORE_ADDR *found_addrp) override;
549
550 bool can_async_p () override;
551
552 bool is_async_p () override;
553
554 void async (int) override;
555
556 void thread_events (int) override;
557
558 int can_do_single_step () override;
559
560 void terminal_inferior () override;
561
562 void terminal_ours () override;
563
564 bool supports_non_stop () override;
565
566 bool supports_multi_process () override;
567
568 bool supports_disable_randomization () override;
569
570 bool filesystem_is_local () override;
571
572
573 int fileio_open (struct inferior *inf, const char *filename,
574 int flags, int mode, int warn_if_slow,
575 int *target_errno) override;
576
577 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
578 ULONGEST offset, int *target_errno) override;
579
580 int fileio_pread (int fd, gdb_byte *read_buf, int len,
581 ULONGEST offset, int *target_errno) override;
582
583 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
584
585 int fileio_close (int fd, int *target_errno) override;
586
587 int fileio_unlink (struct inferior *inf,
588 const char *filename,
589 int *target_errno) override;
590
591 gdb::optional<std::string>
592 fileio_readlink (struct inferior *inf,
593 const char *filename,
594 int *target_errno) override;
595
596 bool supports_enable_disable_tracepoint () override;
597
598 bool supports_string_tracing () override;
599
600 bool supports_evaluation_of_breakpoint_conditions () override;
601
602 bool can_run_breakpoint_commands () override;
603
604 void trace_init () override;
605
606 void download_tracepoint (struct bp_location *location) override;
607
608 bool can_download_tracepoint () override;
609
610 void download_trace_state_variable (const trace_state_variable &tsv) override;
611
612 void enable_tracepoint (struct bp_location *location) override;
613
614 void disable_tracepoint (struct bp_location *location) override;
615
616 void trace_set_readonly_regions () override;
617
618 void trace_start () override;
619
620 int get_trace_status (struct trace_status *ts) override;
621
622 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
623 override;
624
625 void trace_stop () override;
626
627 int trace_find (enum trace_find_type type, int num,
628 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
629
630 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
631
632 int save_trace_data (const char *filename) override;
633
634 int upload_tracepoints (struct uploaded_tp **utpp) override;
635
636 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
637
638 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
639
640 int get_min_fast_tracepoint_insn_len () override;
641
642 void set_disconnected_tracing (int val) override;
643
644 void set_circular_trace_buffer (int val) override;
645
646 void set_trace_buffer_size (LONGEST val) override;
647
648 bool set_trace_notes (const char *user, const char *notes,
649 const char *stopnotes) override;
650
651 int core_of_thread (ptid_t ptid) override;
652
653 int verify_memory (const gdb_byte *data,
654 CORE_ADDR memaddr, ULONGEST size) override;
655
656
657 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
658
659 void set_permissions () override;
660
661 bool static_tracepoint_marker_at (CORE_ADDR,
662 struct static_tracepoint_marker *marker)
663 override;
664
665 std::vector<static_tracepoint_marker>
666 static_tracepoint_markers_by_strid (const char *id) override;
667
668 traceframe_info_up traceframe_info () override;
669
670 bool use_agent (bool use) override;
671 bool can_use_agent () override;
672
673 struct btrace_target_info *enable_btrace (ptid_t ptid,
674 const struct btrace_config *conf) override;
675
676 void disable_btrace (struct btrace_target_info *tinfo) override;
677
678 void teardown_btrace (struct btrace_target_info *tinfo) override;
679
680 enum btrace_error read_btrace (struct btrace_data *data,
681 struct btrace_target_info *btinfo,
682 enum btrace_read_type type) override;
683
684 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
685 bool augmented_libraries_svr4_read () override;
686 int follow_fork (int, int) override;
687 void follow_exec (struct inferior *, char *) override;
688 int insert_fork_catchpoint (int) override;
689 int remove_fork_catchpoint (int) override;
690 int insert_vfork_catchpoint (int) override;
691 int remove_vfork_catchpoint (int) override;
692 int insert_exec_catchpoint (int) override;
693 int remove_exec_catchpoint (int) override;
694 enum exec_direction_kind execution_direction () override;
695
696 public: /* Remote specific methods. */
697
698 void remote_download_command_source (int num, ULONGEST addr,
699 struct command_line *cmds);
700
701 void remote_file_put (const char *local_file, const char *remote_file,
702 int from_tty);
703 void remote_file_get (const char *remote_file, const char *local_file,
704 int from_tty);
705 void remote_file_delete (const char *remote_file, int from_tty);
706
707 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, int *remote_errno);
709 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
710 ULONGEST offset, int *remote_errno);
711 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
712 ULONGEST offset, int *remote_errno);
713
714 int remote_hostio_send_command (int command_bytes, int which_packet,
715 int *remote_errno, char **attachment,
716 int *attachment_len);
717 int remote_hostio_set_filesystem (struct inferior *inf,
718 int *remote_errno);
719 /* We should get rid of this and use fileio_open directly. */
720 int remote_hostio_open (struct inferior *inf, const char *filename,
721 int flags, int mode, int warn_if_slow,
722 int *remote_errno);
723 int remote_hostio_close (int fd, int *remote_errno);
724
725 int remote_hostio_unlink (inferior *inf, const char *filename,
726 int *remote_errno);
727
728 struct remote_state *get_remote_state ();
729
730 long get_remote_packet_size (void);
731 long get_memory_packet_size (struct memory_packet_config *config);
732
733 long get_memory_write_packet_size ();
734 long get_memory_read_packet_size ();
735
736 char *append_pending_thread_resumptions (char *p, char *endp,
737 ptid_t ptid);
738 static void open_1 (const char *name, int from_tty, int extended_p);
739 void start_remote (int from_tty, int extended_p);
740 void remote_detach_1 (struct inferior *inf, int from_tty);
741
742 char *append_resumption (char *p, char *endp,
743 ptid_t ptid, int step, gdb_signal siggnal);
744 int remote_resume_with_vcont (ptid_t ptid, int step,
745 gdb_signal siggnal);
746
747 void add_current_inferior_and_thread (char *wait_status);
748
749 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
750 int options);
751 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
752 int options);
753
754 ptid_t process_stop_reply (struct stop_reply *stop_reply,
755 target_waitstatus *status);
756
757 void remote_notice_new_inferior (ptid_t currthread, int executing);
758
759 void process_initial_stop_replies (int from_tty);
760
761 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
762
763 void btrace_sync_conf (const btrace_config *conf);
764
765 void remote_btrace_maybe_reopen ();
766
767 void remove_new_fork_children (threads_listing_context *context);
768 void kill_new_fork_children (int pid);
769 void discard_pending_stop_replies (struct inferior *inf);
770 int stop_reply_queue_length ();
771
772 void check_pending_events_prevent_wildcard_vcont
773 (int *may_global_wildcard_vcont);
774
775 void discard_pending_stop_replies_in_queue ();
776 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
777 struct stop_reply *queued_stop_reply (ptid_t ptid);
778 int peek_stop_reply (ptid_t ptid);
779 void remote_parse_stop_reply (char *buf, stop_reply *event);
780
781 void remote_stop_ns (ptid_t ptid);
782 void remote_interrupt_as ();
783 void remote_interrupt_ns ();
784
785 char *remote_get_noisy_reply ();
786 int remote_query_attached (int pid);
787 inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
788 int try_open_exec);
789
790 ptid_t remote_current_thread (ptid_t oldpid);
791 ptid_t get_current_thread (char *wait_status);
792
793 void set_thread (ptid_t ptid, int gen);
794 void set_general_thread (ptid_t ptid);
795 void set_continue_thread (ptid_t ptid);
796 void set_general_process ();
797
798 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
799
800 int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
801 gdb_ext_thread_info *info);
802 int remote_get_threadinfo (threadref *threadid, int fieldset,
803 gdb_ext_thread_info *info);
804
805 int parse_threadlist_response (char *pkt, int result_limit,
806 threadref *original_echo,
807 threadref *resultlist,
808 int *doneflag);
809 int remote_get_threadlist (int startflag, threadref *nextthread,
810 int result_limit, int *done, int *result_count,
811 threadref *threadlist);
812
813 int remote_threadlist_iterator (rmt_thread_action stepfunction,
814 void *context, int looplimit);
815
816 int remote_get_threads_with_ql (threads_listing_context *context);
817 int remote_get_threads_with_qxfer (threads_listing_context *context);
818 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
819
820 void extended_remote_restart ();
821
822 void get_offsets ();
823
824 void remote_check_symbols ();
825
826 void remote_supported_packet (const struct protocol_feature *feature,
827 enum packet_support support,
828 const char *argument);
829
830 void remote_query_supported ();
831
832 void remote_packet_size (const protocol_feature *feature,
833 packet_support support, const char *value);
834
835 void remote_serial_quit_handler ();
836
837 void remote_detach_pid (int pid);
838
839 void remote_vcont_probe ();
840
841 void remote_resume_with_hc (ptid_t ptid, int step,
842 gdb_signal siggnal);
843
844 void send_interrupt_sequence ();
845 void interrupt_query ();
846
847 void remote_notif_get_pending_events (notif_client *nc);
848
849 int fetch_register_using_p (struct regcache *regcache,
850 packet_reg *reg);
851 int send_g_packet ();
852 void process_g_packet (struct regcache *regcache);
853 void fetch_registers_using_g (struct regcache *regcache);
854 int store_register_using_P (const struct regcache *regcache,
855 packet_reg *reg);
856 void store_registers_using_G (const struct regcache *regcache);
857
858 void set_remote_traceframe ();
859
860 void check_binary_download (CORE_ADDR addr);
861
862 target_xfer_status remote_write_bytes_aux (const char *header,
863 CORE_ADDR memaddr,
864 const gdb_byte *myaddr,
865 ULONGEST len_units,
866 int unit_size,
867 ULONGEST *xfered_len_units,
868 char packet_format,
869 int use_length);
870
871 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
872 const gdb_byte *myaddr, ULONGEST len,
873 int unit_size, ULONGEST *xfered_len);
874
875 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
876 ULONGEST len_units,
877 int unit_size, ULONGEST *xfered_len_units);
878
879 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
880 ULONGEST memaddr,
881 ULONGEST len,
882 int unit_size,
883 ULONGEST *xfered_len);
884
885 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
886 gdb_byte *myaddr, ULONGEST len,
887 int unit_size,
888 ULONGEST *xfered_len);
889
890 packet_result remote_send_printf (const char *format, ...)
891 ATTRIBUTE_PRINTF (2, 3);
892
893 target_xfer_status remote_flash_write (ULONGEST address,
894 ULONGEST length, ULONGEST *xfered_len,
895 const gdb_byte *data);
896
897 int readchar (int timeout);
898
899 void remote_serial_write (const char *str, int len);
900
901 int putpkt (const char *buf);
902 int putpkt_binary (const char *buf, int cnt);
903
904 void skip_frame ();
905 long read_frame (char **buf_p, long *sizeof_buf);
906 void getpkt (char **buf, long *sizeof_buf, int forever);
907 int getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
908 int expecting_notif, int *is_notif);
909 int getpkt_sane (char **buf, long *sizeof_buf, int forever);
910 int getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
911 int *is_notif);
912 int remote_vkill (int pid);
913 void remote_kill_k ();
914
915 void extended_remote_disable_randomization (int val);
916 int extended_remote_run (const std::string &args);
917
918 void send_environment_packet (const char *action,
919 const char *packet,
920 const char *value);
921
922 void extended_remote_environment_support ();
923 void extended_remote_set_inferior_cwd ();
924
925 target_xfer_status remote_write_qxfer (const char *object_name,
926 const char *annex,
927 const gdb_byte *writebuf,
928 ULONGEST offset, LONGEST len,
929 ULONGEST *xfered_len,
930 struct packet_config *packet);
931
932 target_xfer_status remote_read_qxfer (const char *object_name,
933 const char *annex,
934 gdb_byte *readbuf, ULONGEST offset,
935 LONGEST len,
936 ULONGEST *xfered_len,
937 struct packet_config *packet);
938
939 void push_stop_reply (struct stop_reply *new_event);
940
941 bool vcont_r_supported ();
942
943 void packet_command (const char *args, int from_tty);
944
945 private: /* data fields */
946
947 /* The remote state. Don't reference this directly. Use the
948 get_remote_state method instead. */
949 remote_state m_remote_state;
950 };
951
952 static const target_info extended_remote_target_info = {
953 "extended-remote",
954 N_("Extended remote serial target in gdb-specific protocol"),
955 remote_doc
956 };
957
958 /* Set up the extended remote target by extending the standard remote
959 target and adding to it. */
960
961 class extended_remote_target final : public remote_target
962 {
963 public:
964 const target_info &info () const override
965 { return extended_remote_target_info; }
966
967 /* Open an extended-remote connection. */
968 static void open (const char *, int);
969
970 bool can_create_inferior () override { return true; }
971 void create_inferior (const char *, const std::string &,
972 char **, int) override;
973
974 void detach (inferior *, int) override;
975
976 bool can_attach () override { return true; }
977 void attach (const char *, int) override;
978
979 void post_attach (int) override;
980 bool supports_disable_randomization () override;
981 };
982
983 /* Per-program-space data key. */
984 static const struct program_space_data *remote_pspace_data;
985
986 /* The variable registered as the control variable used by the
987 remote exec-file commands. While the remote exec-file setting is
988 per-program-space, the set/show machinery uses this as the
989 location of the remote exec-file value. */
990 static char *remote_exec_file_var;
991
992 /* The size to align memory write packets, when practical. The protocol
993 does not guarantee any alignment, and gdb will generate short
994 writes and unaligned writes, but even as a best-effort attempt this
995 can improve bulk transfers. For instance, if a write is misaligned
996 relative to the target's data bus, the stub may need to make an extra
997 round trip fetching data from the target. This doesn't make a
998 huge difference, but it's easy to do, so we try to be helpful.
999
1000 The alignment chosen is arbitrary; usually data bus width is
1001 important here, not the possibly larger cache line size. */
1002 enum { REMOTE_ALIGN_WRITES = 16 };
1003
1004 /* Prototypes for local functions. */
1005
1006 static int hexnumlen (ULONGEST num);
1007
1008 static int stubhex (int ch);
1009
1010 static int hexnumstr (char *, ULONGEST);
1011
1012 static int hexnumnstr (char *, ULONGEST, int);
1013
1014 static CORE_ADDR remote_address_masked (CORE_ADDR);
1015
1016 static void print_packet (const char *);
1017
1018 static int stub_unpack_int (char *buff, int fieldlength);
1019
1020 struct packet_config;
1021
1022 static void show_packet_config_cmd (struct packet_config *config);
1023
1024 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1025 int from_tty,
1026 struct cmd_list_element *c,
1027 const char *value);
1028
1029 static ptid_t read_ptid (const char *buf, const char **obuf);
1030
1031 static void remote_async_inferior_event_handler (gdb_client_data);
1032
1033 static int remote_read_description_p (struct target_ops *target);
1034
1035 static void remote_console_output (char *msg);
1036
1037 static void remote_btrace_reset (remote_state *rs);
1038
1039 static void remote_unpush_and_throw (void);
1040
1041 /* For "remote". */
1042
1043 static struct cmd_list_element *remote_cmdlist;
1044
1045 /* For "set remote" and "show remote". */
1046
1047 static struct cmd_list_element *remote_set_cmdlist;
1048 static struct cmd_list_element *remote_show_cmdlist;
1049
1050 /* Controls whether GDB is willing to use range stepping. */
1051
1052 static int use_range_stepping = 1;
1053
1054 /* The max number of chars in debug output. The rest of chars are
1055 omitted. */
1056
1057 #define REMOTE_DEBUG_MAX_CHAR 512
1058
1059 /* Private data that we'll store in (struct thread_info)->priv. */
1060 struct remote_thread_info : public private_thread_info
1061 {
1062 std::string extra;
1063 std::string name;
1064 int core = -1;
1065
1066 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1067 sequence of bytes. */
1068 gdb::byte_vector thread_handle;
1069
1070 /* Whether the target stopped for a breakpoint/watchpoint. */
1071 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1072
1073 /* This is set to the data address of the access causing the target
1074 to stop for a watchpoint. */
1075 CORE_ADDR watch_data_address = 0;
1076
1077 /* Fields used by the vCont action coalescing implemented in
1078 remote_resume / remote_commit_resume. remote_resume stores each
1079 thread's last resume request in these fields, so that a later
1080 remote_commit_resume knows which is the proper action for this
1081 thread to include in the vCont packet. */
1082
1083 /* True if the last target_resume call for this thread was a step
1084 request, false if a continue request. */
1085 int last_resume_step = 0;
1086
1087 /* The signal specified in the last target_resume call for this
1088 thread. */
1089 gdb_signal last_resume_sig = GDB_SIGNAL_0;
1090
1091 /* Whether this thread was already vCont-resumed on the remote
1092 side. */
1093 int vcont_resumed = 0;
1094 };
1095
1096 remote_state::remote_state ()
1097 {
1098 /* The default buffer size is unimportant; it will be expanded
1099 whenever a larger buffer is needed. */
1100 this->buf_size = 400;
1101 this->buf = (char *) xmalloc (this->buf_size);
1102 }
1103
1104 remote_state::~remote_state ()
1105 {
1106 xfree (this->last_pass_packet);
1107 xfree (this->last_program_signals_packet);
1108 xfree (this->buf);
1109 xfree (this->finished_object);
1110 xfree (this->finished_annex);
1111 }
1112
1113 /* Utility: generate error from an incoming stub packet. */
1114 static void
1115 trace_error (char *buf)
1116 {
1117 if (*buf++ != 'E')
1118 return; /* not an error msg */
1119 switch (*buf)
1120 {
1121 case '1': /* malformed packet error */
1122 if (*++buf == '0') /* general case: */
1123 error (_("remote.c: error in outgoing packet."));
1124 else
1125 error (_("remote.c: error in outgoing packet at field #%ld."),
1126 strtol (buf, NULL, 16));
1127 default:
1128 error (_("Target returns error code '%s'."), buf);
1129 }
1130 }
1131
1132 /* Utility: wait for reply from stub, while accepting "O" packets. */
1133
1134 char *
1135 remote_target::remote_get_noisy_reply ()
1136 {
1137 struct remote_state *rs = get_remote_state ();
1138
1139 do /* Loop on reply from remote stub. */
1140 {
1141 char *buf;
1142
1143 QUIT; /* Allow user to bail out with ^C. */
1144 getpkt (&rs->buf, &rs->buf_size, 0);
1145 buf = rs->buf;
1146 if (buf[0] == 'E')
1147 trace_error (buf);
1148 else if (startswith (buf, "qRelocInsn:"))
1149 {
1150 ULONGEST ul;
1151 CORE_ADDR from, to, org_to;
1152 const char *p, *pp;
1153 int adjusted_size = 0;
1154 int relocated = 0;
1155
1156 p = buf + strlen ("qRelocInsn:");
1157 pp = unpack_varlen_hex (p, &ul);
1158 if (*pp != ';')
1159 error (_("invalid qRelocInsn packet: %s"), buf);
1160 from = ul;
1161
1162 p = pp + 1;
1163 unpack_varlen_hex (p, &ul);
1164 to = ul;
1165
1166 org_to = to;
1167
1168 TRY
1169 {
1170 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1171 relocated = 1;
1172 }
1173 CATCH (ex, RETURN_MASK_ALL)
1174 {
1175 if (ex.error == MEMORY_ERROR)
1176 {
1177 /* Propagate memory errors silently back to the
1178 target. The stub may have limited the range of
1179 addresses we can write to, for example. */
1180 }
1181 else
1182 {
1183 /* Something unexpectedly bad happened. Be verbose
1184 so we can tell what, and propagate the error back
1185 to the stub, so it doesn't get stuck waiting for
1186 a response. */
1187 exception_fprintf (gdb_stderr, ex,
1188 _("warning: relocating instruction: "));
1189 }
1190 putpkt ("E01");
1191 }
1192 END_CATCH
1193
1194 if (relocated)
1195 {
1196 adjusted_size = to - org_to;
1197
1198 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
1199 putpkt (buf);
1200 }
1201 }
1202 else if (buf[0] == 'O' && buf[1] != 'K')
1203 remote_console_output (buf + 1); /* 'O' message from stub */
1204 else
1205 return buf; /* Here's the actual reply. */
1206 }
1207 while (1);
1208 }
1209
1210 struct remote_arch_state *
1211 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1212 {
1213 remote_arch_state *rsa;
1214
1215 auto it = this->m_arch_states.find (gdbarch);
1216 if (it == this->m_arch_states.end ())
1217 {
1218 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1219 std::forward_as_tuple (gdbarch),
1220 std::forward_as_tuple (gdbarch));
1221 rsa = &p.first->second;
1222
1223 /* Make sure that the packet buffer is plenty big enough for
1224 this architecture. */
1225 if (this->buf_size < rsa->remote_packet_size)
1226 {
1227 this->buf_size = 2 * rsa->remote_packet_size;
1228 this->buf = (char *) xrealloc (this->buf, this->buf_size);
1229 }
1230 }
1231 else
1232 rsa = &it->second;
1233
1234 return rsa;
1235 }
1236
1237 /* Fetch the global remote target state. */
1238
1239 remote_state *
1240 remote_target::get_remote_state ()
1241 {
1242 /* Make sure that the remote architecture state has been
1243 initialized, because doing so might reallocate rs->buf. Any
1244 function which calls getpkt also needs to be mindful of changes
1245 to rs->buf, but this call limits the number of places which run
1246 into trouble. */
1247 m_remote_state.get_remote_arch_state (target_gdbarch ());
1248
1249 return &m_remote_state;
1250 }
1251
1252 /* Cleanup routine for the remote module's pspace data. */
1253
1254 static void
1255 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1256 {
1257 char *remote_exec_file = (char *) arg;
1258
1259 xfree (remote_exec_file);
1260 }
1261
1262 /* Fetch the remote exec-file from the current program space. */
1263
1264 static const char *
1265 get_remote_exec_file (void)
1266 {
1267 char *remote_exec_file;
1268
1269 remote_exec_file
1270 = (char *) program_space_data (current_program_space,
1271 remote_pspace_data);
1272 if (remote_exec_file == NULL)
1273 return "";
1274
1275 return remote_exec_file;
1276 }
1277
1278 /* Set the remote exec file for PSPACE. */
1279
1280 static void
1281 set_pspace_remote_exec_file (struct program_space *pspace,
1282 char *remote_exec_file)
1283 {
1284 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
1285
1286 xfree (old_file);
1287 set_program_space_data (pspace, remote_pspace_data,
1288 xstrdup (remote_exec_file));
1289 }
1290
1291 /* The "set/show remote exec-file" set command hook. */
1292
1293 static void
1294 set_remote_exec_file (const char *ignored, int from_tty,
1295 struct cmd_list_element *c)
1296 {
1297 gdb_assert (remote_exec_file_var != NULL);
1298 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1299 }
1300
1301 /* The "set/show remote exec-file" show command hook. */
1302
1303 static void
1304 show_remote_exec_file (struct ui_file *file, int from_tty,
1305 struct cmd_list_element *cmd, const char *value)
1306 {
1307 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1308 }
1309
1310 static int
1311 compare_pnums (const void *lhs_, const void *rhs_)
1312 {
1313 const struct packet_reg * const *lhs
1314 = (const struct packet_reg * const *) lhs_;
1315 const struct packet_reg * const *rhs
1316 = (const struct packet_reg * const *) rhs_;
1317
1318 if ((*lhs)->pnum < (*rhs)->pnum)
1319 return -1;
1320 else if ((*lhs)->pnum == (*rhs)->pnum)
1321 return 0;
1322 else
1323 return 1;
1324 }
1325
1326 static int
1327 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1328 {
1329 int regnum, num_remote_regs, offset;
1330 struct packet_reg **remote_regs;
1331
1332 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1333 {
1334 struct packet_reg *r = &regs[regnum];
1335
1336 if (register_size (gdbarch, regnum) == 0)
1337 /* Do not try to fetch zero-sized (placeholder) registers. */
1338 r->pnum = -1;
1339 else
1340 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1341
1342 r->regnum = regnum;
1343 }
1344
1345 /* Define the g/G packet format as the contents of each register
1346 with a remote protocol number, in order of ascending protocol
1347 number. */
1348
1349 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1350 for (num_remote_regs = 0, regnum = 0;
1351 regnum < gdbarch_num_regs (gdbarch);
1352 regnum++)
1353 if (regs[regnum].pnum != -1)
1354 remote_regs[num_remote_regs++] = &regs[regnum];
1355
1356 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1357 compare_pnums);
1358
1359 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1360 {
1361 remote_regs[regnum]->in_g_packet = 1;
1362 remote_regs[regnum]->offset = offset;
1363 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1364 }
1365
1366 return offset;
1367 }
1368
1369 /* Given the architecture described by GDBARCH, return the remote
1370 protocol register's number and the register's offset in the g/G
1371 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1372 If the target does not have a mapping for REGNUM, return false,
1373 otherwise, return true. */
1374
1375 int
1376 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1377 int *pnum, int *poffset)
1378 {
1379 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1380
1381 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1382
1383 map_regcache_remote_table (gdbarch, regs.data ());
1384
1385 *pnum = regs[regnum].pnum;
1386 *poffset = regs[regnum].offset;
1387
1388 return *pnum != -1;
1389 }
1390
1391 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1392 {
1393 /* Use the architecture to build a regnum<->pnum table, which will be
1394 1:1 unless a feature set specifies otherwise. */
1395 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1396
1397 /* Record the maximum possible size of the g packet - it may turn out
1398 to be smaller. */
1399 this->sizeof_g_packet
1400 = map_regcache_remote_table (gdbarch, this->regs.get ());
1401
1402 /* Default maximum number of characters in a packet body. Many
1403 remote stubs have a hardwired buffer size of 400 bytes
1404 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1405 as the maximum packet-size to ensure that the packet and an extra
1406 NUL character can always fit in the buffer. This stops GDB
1407 trashing stubs that try to squeeze an extra NUL into what is
1408 already a full buffer (As of 1999-12-04 that was most stubs). */
1409 this->remote_packet_size = 400 - 1;
1410
1411 /* This one is filled in when a ``g'' packet is received. */
1412 this->actual_register_packet_size = 0;
1413
1414 /* Should rsa->sizeof_g_packet needs more space than the
1415 default, adjust the size accordingly. Remember that each byte is
1416 encoded as two characters. 32 is the overhead for the packet
1417 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1418 (``$NN:G...#NN'') is a better guess, the below has been padded a
1419 little. */
1420 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1421 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1422 }
1423
1424 /* Get a pointer to the current remote target. If not connected to a
1425 remote target, return NULL. */
1426
1427 static remote_target *
1428 get_current_remote_target ()
1429 {
1430 target_ops *proc_target = find_target_at (process_stratum);
1431 return dynamic_cast<remote_target *> (proc_target);
1432 }
1433
1434 /* Return the current allowed size of a remote packet. This is
1435 inferred from the current architecture, and should be used to
1436 limit the length of outgoing packets. */
1437 long
1438 remote_target::get_remote_packet_size ()
1439 {
1440 struct remote_state *rs = get_remote_state ();
1441 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1442
1443 if (rs->explicit_packet_size)
1444 return rs->explicit_packet_size;
1445
1446 return rsa->remote_packet_size;
1447 }
1448
1449 static struct packet_reg *
1450 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1451 long regnum)
1452 {
1453 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1454 return NULL;
1455 else
1456 {
1457 struct packet_reg *r = &rsa->regs[regnum];
1458
1459 gdb_assert (r->regnum == regnum);
1460 return r;
1461 }
1462 }
1463
1464 static struct packet_reg *
1465 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1466 LONGEST pnum)
1467 {
1468 int i;
1469
1470 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1471 {
1472 struct packet_reg *r = &rsa->regs[i];
1473
1474 if (r->pnum == pnum)
1475 return r;
1476 }
1477 return NULL;
1478 }
1479
1480 /* Allow the user to specify what sequence to send to the remote
1481 when he requests a program interruption: Although ^C is usually
1482 what remote systems expect (this is the default, here), it is
1483 sometimes preferable to send a break. On other systems such
1484 as the Linux kernel, a break followed by g, which is Magic SysRq g
1485 is required in order to interrupt the execution. */
1486 const char interrupt_sequence_control_c[] = "Ctrl-C";
1487 const char interrupt_sequence_break[] = "BREAK";
1488 const char interrupt_sequence_break_g[] = "BREAK-g";
1489 static const char *const interrupt_sequence_modes[] =
1490 {
1491 interrupt_sequence_control_c,
1492 interrupt_sequence_break,
1493 interrupt_sequence_break_g,
1494 NULL
1495 };
1496 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1497
1498 static void
1499 show_interrupt_sequence (struct ui_file *file, int from_tty,
1500 struct cmd_list_element *c,
1501 const char *value)
1502 {
1503 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1504 fprintf_filtered (file,
1505 _("Send the ASCII ETX character (Ctrl-c) "
1506 "to the remote target to interrupt the "
1507 "execution of the program.\n"));
1508 else if (interrupt_sequence_mode == interrupt_sequence_break)
1509 fprintf_filtered (file,
1510 _("send a break signal to the remote target "
1511 "to interrupt the execution of the program.\n"));
1512 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1513 fprintf_filtered (file,
1514 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1515 "the remote target to interrupt the execution "
1516 "of Linux kernel.\n"));
1517 else
1518 internal_error (__FILE__, __LINE__,
1519 _("Invalid value for interrupt_sequence_mode: %s."),
1520 interrupt_sequence_mode);
1521 }
1522
1523 /* This boolean variable specifies whether interrupt_sequence is sent
1524 to the remote target when gdb connects to it.
1525 This is mostly needed when you debug the Linux kernel: The Linux kernel
1526 expects BREAK g which is Magic SysRq g for connecting gdb. */
1527 static int interrupt_on_connect = 0;
1528
1529 /* This variable is used to implement the "set/show remotebreak" commands.
1530 Since these commands are now deprecated in favor of "set/show remote
1531 interrupt-sequence", it no longer has any effect on the code. */
1532 static int remote_break;
1533
1534 static void
1535 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1536 {
1537 if (remote_break)
1538 interrupt_sequence_mode = interrupt_sequence_break;
1539 else
1540 interrupt_sequence_mode = interrupt_sequence_control_c;
1541 }
1542
1543 static void
1544 show_remotebreak (struct ui_file *file, int from_tty,
1545 struct cmd_list_element *c,
1546 const char *value)
1547 {
1548 }
1549
1550 /* This variable sets the number of bits in an address that are to be
1551 sent in a memory ("M" or "m") packet. Normally, after stripping
1552 leading zeros, the entire address would be sent. This variable
1553 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1554 initial implementation of remote.c restricted the address sent in
1555 memory packets to ``host::sizeof long'' bytes - (typically 32
1556 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1557 address was never sent. Since fixing this bug may cause a break in
1558 some remote targets this variable is principly provided to
1559 facilitate backward compatibility. */
1560
1561 static unsigned int remote_address_size;
1562
1563 \f
1564 /* User configurable variables for the number of characters in a
1565 memory read/write packet. MIN (rsa->remote_packet_size,
1566 rsa->sizeof_g_packet) is the default. Some targets need smaller
1567 values (fifo overruns, et.al.) and some users need larger values
1568 (speed up transfers). The variables ``preferred_*'' (the user
1569 request), ``current_*'' (what was actually set) and ``forced_*''
1570 (Positive - a soft limit, negative - a hard limit). */
1571
1572 struct memory_packet_config
1573 {
1574 const char *name;
1575 long size;
1576 int fixed_p;
1577 };
1578
1579 /* The default max memory-write-packet-size, when the setting is
1580 "fixed". The 16k is historical. (It came from older GDB's using
1581 alloca for buffers and the knowledge (folklore?) that some hosts
1582 don't cope very well with large alloca calls.) */
1583 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1584
1585 /* The minimum remote packet size for memory transfers. Ensures we
1586 can write at least one byte. */
1587 #define MIN_MEMORY_PACKET_SIZE 20
1588
1589 /* Get the memory packet size, assuming it is fixed. */
1590
1591 static long
1592 get_fixed_memory_packet_size (struct memory_packet_config *config)
1593 {
1594 gdb_assert (config->fixed_p);
1595
1596 if (config->size <= 0)
1597 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1598 else
1599 return config->size;
1600 }
1601
1602 /* Compute the current size of a read/write packet. Since this makes
1603 use of ``actual_register_packet_size'' the computation is dynamic. */
1604
1605 long
1606 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1607 {
1608 struct remote_state *rs = get_remote_state ();
1609 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1610
1611 long what_they_get;
1612 if (config->fixed_p)
1613 what_they_get = get_fixed_memory_packet_size (config);
1614 else
1615 {
1616 what_they_get = get_remote_packet_size ();
1617 /* Limit the packet to the size specified by the user. */
1618 if (config->size > 0
1619 && what_they_get > config->size)
1620 what_they_get = config->size;
1621
1622 /* Limit it to the size of the targets ``g'' response unless we have
1623 permission from the stub to use a larger packet size. */
1624 if (rs->explicit_packet_size == 0
1625 && rsa->actual_register_packet_size > 0
1626 && what_they_get > rsa->actual_register_packet_size)
1627 what_they_get = rsa->actual_register_packet_size;
1628 }
1629 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1630 what_they_get = MIN_MEMORY_PACKET_SIZE;
1631
1632 /* Make sure there is room in the global buffer for this packet
1633 (including its trailing NUL byte). */
1634 if (rs->buf_size < what_they_get + 1)
1635 {
1636 rs->buf_size = 2 * what_they_get;
1637 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1638 }
1639
1640 return what_they_get;
1641 }
1642
1643 /* Update the size of a read/write packet. If they user wants
1644 something really big then do a sanity check. */
1645
1646 static void
1647 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1648 {
1649 int fixed_p = config->fixed_p;
1650 long size = config->size;
1651
1652 if (args == NULL)
1653 error (_("Argument required (integer, `fixed' or `limited')."));
1654 else if (strcmp (args, "hard") == 0
1655 || strcmp (args, "fixed") == 0)
1656 fixed_p = 1;
1657 else if (strcmp (args, "soft") == 0
1658 || strcmp (args, "limit") == 0)
1659 fixed_p = 0;
1660 else
1661 {
1662 char *end;
1663
1664 size = strtoul (args, &end, 0);
1665 if (args == end)
1666 error (_("Invalid %s (bad syntax)."), config->name);
1667
1668 /* Instead of explicitly capping the size of a packet to or
1669 disallowing it, the user is allowed to set the size to
1670 something arbitrarily large. */
1671 }
1672
1673 /* Extra checks? */
1674 if (fixed_p && !config->fixed_p)
1675 {
1676 /* So that the query shows the correct value. */
1677 long query_size = (size <= 0
1678 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1679 : size);
1680
1681 if (! query (_("The target may not be able to correctly handle a %s\n"
1682 "of %ld bytes. Change the packet size? "),
1683 config->name, query_size))
1684 error (_("Packet size not changed."));
1685 }
1686 /* Update the config. */
1687 config->fixed_p = fixed_p;
1688 config->size = size;
1689 }
1690
1691 static void
1692 show_memory_packet_size (struct memory_packet_config *config)
1693 {
1694 if (config->size == 0)
1695 printf_filtered (_("The %s is 0 (default). "), config->name);
1696 else
1697 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1698 if (config->fixed_p)
1699 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1700 get_fixed_memory_packet_size (config));
1701 else
1702 {
1703 remote_target *remote = get_current_remote_target ();
1704
1705 if (remote != NULL)
1706 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1707 remote->get_memory_packet_size (config));
1708 else
1709 puts_filtered ("The actual limit will be further reduced "
1710 "dependent on the target.\n");
1711 }
1712 }
1713
1714 static struct memory_packet_config memory_write_packet_config =
1715 {
1716 "memory-write-packet-size",
1717 };
1718
1719 static void
1720 set_memory_write_packet_size (const char *args, int from_tty)
1721 {
1722 set_memory_packet_size (args, &memory_write_packet_config);
1723 }
1724
1725 static void
1726 show_memory_write_packet_size (const char *args, int from_tty)
1727 {
1728 show_memory_packet_size (&memory_write_packet_config);
1729 }
1730
1731 long
1732 remote_target::get_memory_write_packet_size ()
1733 {
1734 return get_memory_packet_size (&memory_write_packet_config);
1735 }
1736
1737 static struct memory_packet_config memory_read_packet_config =
1738 {
1739 "memory-read-packet-size",
1740 };
1741
1742 static void
1743 set_memory_read_packet_size (const char *args, int from_tty)
1744 {
1745 set_memory_packet_size (args, &memory_read_packet_config);
1746 }
1747
1748 static void
1749 show_memory_read_packet_size (const char *args, int from_tty)
1750 {
1751 show_memory_packet_size (&memory_read_packet_config);
1752 }
1753
1754 long
1755 remote_target::get_memory_read_packet_size ()
1756 {
1757 long size = get_memory_packet_size (&memory_read_packet_config);
1758
1759 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1760 extra buffer size argument before the memory read size can be
1761 increased beyond this. */
1762 if (size > get_remote_packet_size ())
1763 size = get_remote_packet_size ();
1764 return size;
1765 }
1766
1767 \f
1768
1769 struct packet_config
1770 {
1771 const char *name;
1772 const char *title;
1773
1774 /* If auto, GDB auto-detects support for this packet or feature,
1775 either through qSupported, or by trying the packet and looking
1776 at the response. If true, GDB assumes the target supports this
1777 packet. If false, the packet is disabled. Configs that don't
1778 have an associated command always have this set to auto. */
1779 enum auto_boolean detect;
1780
1781 /* Does the target support this packet? */
1782 enum packet_support support;
1783 };
1784
1785 static enum packet_support packet_config_support (struct packet_config *config);
1786 static enum packet_support packet_support (int packet);
1787
1788 static void
1789 show_packet_config_cmd (struct packet_config *config)
1790 {
1791 const char *support = "internal-error";
1792
1793 switch (packet_config_support (config))
1794 {
1795 case PACKET_ENABLE:
1796 support = "enabled";
1797 break;
1798 case PACKET_DISABLE:
1799 support = "disabled";
1800 break;
1801 case PACKET_SUPPORT_UNKNOWN:
1802 support = "unknown";
1803 break;
1804 }
1805 switch (config->detect)
1806 {
1807 case AUTO_BOOLEAN_AUTO:
1808 printf_filtered (_("Support for the `%s' packet "
1809 "is auto-detected, currently %s.\n"),
1810 config->name, support);
1811 break;
1812 case AUTO_BOOLEAN_TRUE:
1813 case AUTO_BOOLEAN_FALSE:
1814 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1815 config->name, support);
1816 break;
1817 }
1818 }
1819
1820 static void
1821 add_packet_config_cmd (struct packet_config *config, const char *name,
1822 const char *title, int legacy)
1823 {
1824 char *set_doc;
1825 char *show_doc;
1826 char *cmd_name;
1827
1828 config->name = name;
1829 config->title = title;
1830 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1831 name, title);
1832 show_doc = xstrprintf ("Show current use of remote "
1833 "protocol `%s' (%s) packet",
1834 name, title);
1835 /* set/show TITLE-packet {auto,on,off} */
1836 cmd_name = xstrprintf ("%s-packet", title);
1837 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1838 &config->detect, set_doc,
1839 show_doc, NULL, /* help_doc */
1840 NULL,
1841 show_remote_protocol_packet_cmd,
1842 &remote_set_cmdlist, &remote_show_cmdlist);
1843 /* The command code copies the documentation strings. */
1844 xfree (set_doc);
1845 xfree (show_doc);
1846 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1847 if (legacy)
1848 {
1849 char *legacy_name;
1850
1851 legacy_name = xstrprintf ("%s-packet", name);
1852 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1853 &remote_set_cmdlist);
1854 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1855 &remote_show_cmdlist);
1856 }
1857 }
1858
1859 static enum packet_result
1860 packet_check_result (const char *buf)
1861 {
1862 if (buf[0] != '\0')
1863 {
1864 /* The stub recognized the packet request. Check that the
1865 operation succeeded. */
1866 if (buf[0] == 'E'
1867 && isxdigit (buf[1]) && isxdigit (buf[2])
1868 && buf[3] == '\0')
1869 /* "Enn" - definitly an error. */
1870 return PACKET_ERROR;
1871
1872 /* Always treat "E." as an error. This will be used for
1873 more verbose error messages, such as E.memtypes. */
1874 if (buf[0] == 'E' && buf[1] == '.')
1875 return PACKET_ERROR;
1876
1877 /* The packet may or may not be OK. Just assume it is. */
1878 return PACKET_OK;
1879 }
1880 else
1881 /* The stub does not support the packet. */
1882 return PACKET_UNKNOWN;
1883 }
1884
1885 static enum packet_result
1886 packet_ok (const char *buf, struct packet_config *config)
1887 {
1888 enum packet_result result;
1889
1890 if (config->detect != AUTO_BOOLEAN_TRUE
1891 && config->support == PACKET_DISABLE)
1892 internal_error (__FILE__, __LINE__,
1893 _("packet_ok: attempt to use a disabled packet"));
1894
1895 result = packet_check_result (buf);
1896 switch (result)
1897 {
1898 case PACKET_OK:
1899 case PACKET_ERROR:
1900 /* The stub recognized the packet request. */
1901 if (config->support == PACKET_SUPPORT_UNKNOWN)
1902 {
1903 if (remote_debug)
1904 fprintf_unfiltered (gdb_stdlog,
1905 "Packet %s (%s) is supported\n",
1906 config->name, config->title);
1907 config->support = PACKET_ENABLE;
1908 }
1909 break;
1910 case PACKET_UNKNOWN:
1911 /* The stub does not support the packet. */
1912 if (config->detect == AUTO_BOOLEAN_AUTO
1913 && config->support == PACKET_ENABLE)
1914 {
1915 /* If the stub previously indicated that the packet was
1916 supported then there is a protocol error. */
1917 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1918 config->name, config->title);
1919 }
1920 else if (config->detect == AUTO_BOOLEAN_TRUE)
1921 {
1922 /* The user set it wrong. */
1923 error (_("Enabled packet %s (%s) not recognized by stub"),
1924 config->name, config->title);
1925 }
1926
1927 if (remote_debug)
1928 fprintf_unfiltered (gdb_stdlog,
1929 "Packet %s (%s) is NOT supported\n",
1930 config->name, config->title);
1931 config->support = PACKET_DISABLE;
1932 break;
1933 }
1934
1935 return result;
1936 }
1937
1938 enum {
1939 PACKET_vCont = 0,
1940 PACKET_X,
1941 PACKET_qSymbol,
1942 PACKET_P,
1943 PACKET_p,
1944 PACKET_Z0,
1945 PACKET_Z1,
1946 PACKET_Z2,
1947 PACKET_Z3,
1948 PACKET_Z4,
1949 PACKET_vFile_setfs,
1950 PACKET_vFile_open,
1951 PACKET_vFile_pread,
1952 PACKET_vFile_pwrite,
1953 PACKET_vFile_close,
1954 PACKET_vFile_unlink,
1955 PACKET_vFile_readlink,
1956 PACKET_vFile_fstat,
1957 PACKET_qXfer_auxv,
1958 PACKET_qXfer_features,
1959 PACKET_qXfer_exec_file,
1960 PACKET_qXfer_libraries,
1961 PACKET_qXfer_libraries_svr4,
1962 PACKET_qXfer_memory_map,
1963 PACKET_qXfer_spu_read,
1964 PACKET_qXfer_spu_write,
1965 PACKET_qXfer_osdata,
1966 PACKET_qXfer_threads,
1967 PACKET_qXfer_statictrace_read,
1968 PACKET_qXfer_traceframe_info,
1969 PACKET_qXfer_uib,
1970 PACKET_qGetTIBAddr,
1971 PACKET_qGetTLSAddr,
1972 PACKET_qSupported,
1973 PACKET_qTStatus,
1974 PACKET_QPassSignals,
1975 PACKET_QCatchSyscalls,
1976 PACKET_QProgramSignals,
1977 PACKET_QSetWorkingDir,
1978 PACKET_QStartupWithShell,
1979 PACKET_QEnvironmentHexEncoded,
1980 PACKET_QEnvironmentReset,
1981 PACKET_QEnvironmentUnset,
1982 PACKET_qCRC,
1983 PACKET_qSearch_memory,
1984 PACKET_vAttach,
1985 PACKET_vRun,
1986 PACKET_QStartNoAckMode,
1987 PACKET_vKill,
1988 PACKET_qXfer_siginfo_read,
1989 PACKET_qXfer_siginfo_write,
1990 PACKET_qAttached,
1991
1992 /* Support for conditional tracepoints. */
1993 PACKET_ConditionalTracepoints,
1994
1995 /* Support for target-side breakpoint conditions. */
1996 PACKET_ConditionalBreakpoints,
1997
1998 /* Support for target-side breakpoint commands. */
1999 PACKET_BreakpointCommands,
2000
2001 /* Support for fast tracepoints. */
2002 PACKET_FastTracepoints,
2003
2004 /* Support for static tracepoints. */
2005 PACKET_StaticTracepoints,
2006
2007 /* Support for installing tracepoints while a trace experiment is
2008 running. */
2009 PACKET_InstallInTrace,
2010
2011 PACKET_bc,
2012 PACKET_bs,
2013 PACKET_TracepointSource,
2014 PACKET_QAllow,
2015 PACKET_qXfer_fdpic,
2016 PACKET_QDisableRandomization,
2017 PACKET_QAgent,
2018 PACKET_QTBuffer_size,
2019 PACKET_Qbtrace_off,
2020 PACKET_Qbtrace_bts,
2021 PACKET_Qbtrace_pt,
2022 PACKET_qXfer_btrace,
2023
2024 /* Support for the QNonStop packet. */
2025 PACKET_QNonStop,
2026
2027 /* Support for the QThreadEvents packet. */
2028 PACKET_QThreadEvents,
2029
2030 /* Support for multi-process extensions. */
2031 PACKET_multiprocess_feature,
2032
2033 /* Support for enabling and disabling tracepoints while a trace
2034 experiment is running. */
2035 PACKET_EnableDisableTracepoints_feature,
2036
2037 /* Support for collecting strings using the tracenz bytecode. */
2038 PACKET_tracenz_feature,
2039
2040 /* Support for continuing to run a trace experiment while GDB is
2041 disconnected. */
2042 PACKET_DisconnectedTracing_feature,
2043
2044 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2045 PACKET_augmented_libraries_svr4_read_feature,
2046
2047 /* Support for the qXfer:btrace-conf:read packet. */
2048 PACKET_qXfer_btrace_conf,
2049
2050 /* Support for the Qbtrace-conf:bts:size packet. */
2051 PACKET_Qbtrace_conf_bts_size,
2052
2053 /* Support for swbreak+ feature. */
2054 PACKET_swbreak_feature,
2055
2056 /* Support for hwbreak+ feature. */
2057 PACKET_hwbreak_feature,
2058
2059 /* Support for fork events. */
2060 PACKET_fork_event_feature,
2061
2062 /* Support for vfork events. */
2063 PACKET_vfork_event_feature,
2064
2065 /* Support for the Qbtrace-conf:pt:size packet. */
2066 PACKET_Qbtrace_conf_pt_size,
2067
2068 /* Support for exec events. */
2069 PACKET_exec_event_feature,
2070
2071 /* Support for query supported vCont actions. */
2072 PACKET_vContSupported,
2073
2074 /* Support remote CTRL-C. */
2075 PACKET_vCtrlC,
2076
2077 /* Support TARGET_WAITKIND_NO_RESUMED. */
2078 PACKET_no_resumed,
2079
2080 PACKET_MAX
2081 };
2082
2083 static struct packet_config remote_protocol_packets[PACKET_MAX];
2084
2085 /* Returns the packet's corresponding "set remote foo-packet" command
2086 state. See struct packet_config for more details. */
2087
2088 static enum auto_boolean
2089 packet_set_cmd_state (int packet)
2090 {
2091 return remote_protocol_packets[packet].detect;
2092 }
2093
2094 /* Returns whether a given packet or feature is supported. This takes
2095 into account the state of the corresponding "set remote foo-packet"
2096 command, which may be used to bypass auto-detection. */
2097
2098 static enum packet_support
2099 packet_config_support (struct packet_config *config)
2100 {
2101 switch (config->detect)
2102 {
2103 case AUTO_BOOLEAN_TRUE:
2104 return PACKET_ENABLE;
2105 case AUTO_BOOLEAN_FALSE:
2106 return PACKET_DISABLE;
2107 case AUTO_BOOLEAN_AUTO:
2108 return config->support;
2109 default:
2110 gdb_assert_not_reached (_("bad switch"));
2111 }
2112 }
2113
2114 /* Same as packet_config_support, but takes the packet's enum value as
2115 argument. */
2116
2117 static enum packet_support
2118 packet_support (int packet)
2119 {
2120 struct packet_config *config = &remote_protocol_packets[packet];
2121
2122 return packet_config_support (config);
2123 }
2124
2125 static void
2126 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2127 struct cmd_list_element *c,
2128 const char *value)
2129 {
2130 struct packet_config *packet;
2131
2132 for (packet = remote_protocol_packets;
2133 packet < &remote_protocol_packets[PACKET_MAX];
2134 packet++)
2135 {
2136 if (&packet->detect == c->var)
2137 {
2138 show_packet_config_cmd (packet);
2139 return;
2140 }
2141 }
2142 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2143 c->name);
2144 }
2145
2146 /* Should we try one of the 'Z' requests? */
2147
2148 enum Z_packet_type
2149 {
2150 Z_PACKET_SOFTWARE_BP,
2151 Z_PACKET_HARDWARE_BP,
2152 Z_PACKET_WRITE_WP,
2153 Z_PACKET_READ_WP,
2154 Z_PACKET_ACCESS_WP,
2155 NR_Z_PACKET_TYPES
2156 };
2157
2158 /* For compatibility with older distributions. Provide a ``set remote
2159 Z-packet ...'' command that updates all the Z packet types. */
2160
2161 static enum auto_boolean remote_Z_packet_detect;
2162
2163 static void
2164 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2165 struct cmd_list_element *c)
2166 {
2167 int i;
2168
2169 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2170 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2171 }
2172
2173 static void
2174 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2175 struct cmd_list_element *c,
2176 const char *value)
2177 {
2178 int i;
2179
2180 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2181 {
2182 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2183 }
2184 }
2185
2186 /* Returns true if the multi-process extensions are in effect. */
2187
2188 static int
2189 remote_multi_process_p (struct remote_state *rs)
2190 {
2191 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2192 }
2193
2194 /* Returns true if fork events are supported. */
2195
2196 static int
2197 remote_fork_event_p (struct remote_state *rs)
2198 {
2199 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2200 }
2201
2202 /* Returns true if vfork events are supported. */
2203
2204 static int
2205 remote_vfork_event_p (struct remote_state *rs)
2206 {
2207 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2208 }
2209
2210 /* Returns true if exec events are supported. */
2211
2212 static int
2213 remote_exec_event_p (struct remote_state *rs)
2214 {
2215 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2216 }
2217
2218 /* Insert fork catchpoint target routine. If fork events are enabled
2219 then return success, nothing more to do. */
2220
2221 int
2222 remote_target::insert_fork_catchpoint (int pid)
2223 {
2224 struct remote_state *rs = get_remote_state ();
2225
2226 return !remote_fork_event_p (rs);
2227 }
2228
2229 /* Remove fork catchpoint target routine. Nothing to do, just
2230 return success. */
2231
2232 int
2233 remote_target::remove_fork_catchpoint (int pid)
2234 {
2235 return 0;
2236 }
2237
2238 /* Insert vfork catchpoint target routine. If vfork events are enabled
2239 then return success, nothing more to do. */
2240
2241 int
2242 remote_target::insert_vfork_catchpoint (int pid)
2243 {
2244 struct remote_state *rs = get_remote_state ();
2245
2246 return !remote_vfork_event_p (rs);
2247 }
2248
2249 /* Remove vfork catchpoint target routine. Nothing to do, just
2250 return success. */
2251
2252 int
2253 remote_target::remove_vfork_catchpoint (int pid)
2254 {
2255 return 0;
2256 }
2257
2258 /* Insert exec catchpoint target routine. If exec events are
2259 enabled, just return success. */
2260
2261 int
2262 remote_target::insert_exec_catchpoint (int pid)
2263 {
2264 struct remote_state *rs = get_remote_state ();
2265
2266 return !remote_exec_event_p (rs);
2267 }
2268
2269 /* Remove exec catchpoint target routine. Nothing to do, just
2270 return success. */
2271
2272 int
2273 remote_target::remove_exec_catchpoint (int pid)
2274 {
2275 return 0;
2276 }
2277
2278 \f
2279
2280 static ptid_t magic_null_ptid;
2281 static ptid_t not_sent_ptid;
2282 static ptid_t any_thread_ptid;
2283
2284 /* Find out if the stub attached to PID (and hence GDB should offer to
2285 detach instead of killing it when bailing out). */
2286
2287 int
2288 remote_target::remote_query_attached (int pid)
2289 {
2290 struct remote_state *rs = get_remote_state ();
2291 size_t size = get_remote_packet_size ();
2292
2293 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2294 return 0;
2295
2296 if (remote_multi_process_p (rs))
2297 xsnprintf (rs->buf, size, "qAttached:%x", pid);
2298 else
2299 xsnprintf (rs->buf, size, "qAttached");
2300
2301 putpkt (rs->buf);
2302 getpkt (&rs->buf, &rs->buf_size, 0);
2303
2304 switch (packet_ok (rs->buf,
2305 &remote_protocol_packets[PACKET_qAttached]))
2306 {
2307 case PACKET_OK:
2308 if (strcmp (rs->buf, "1") == 0)
2309 return 1;
2310 break;
2311 case PACKET_ERROR:
2312 warning (_("Remote failure reply: %s"), rs->buf);
2313 break;
2314 case PACKET_UNKNOWN:
2315 break;
2316 }
2317
2318 return 0;
2319 }
2320
2321 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2322 has been invented by GDB, instead of reported by the target. Since
2323 we can be connected to a remote system before before knowing about
2324 any inferior, mark the target with execution when we find the first
2325 inferior. If ATTACHED is 1, then we had just attached to this
2326 inferior. If it is 0, then we just created this inferior. If it
2327 is -1, then try querying the remote stub to find out if it had
2328 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2329 attempt to open this inferior's executable as the main executable
2330 if no main executable is open already. */
2331
2332 inferior *
2333 remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2334 int try_open_exec)
2335 {
2336 struct inferior *inf;
2337
2338 /* Check whether this process we're learning about is to be
2339 considered attached, or if is to be considered to have been
2340 spawned by the stub. */
2341 if (attached == -1)
2342 attached = remote_query_attached (pid);
2343
2344 if (gdbarch_has_global_solist (target_gdbarch ()))
2345 {
2346 /* If the target shares code across all inferiors, then every
2347 attach adds a new inferior. */
2348 inf = add_inferior (pid);
2349
2350 /* ... and every inferior is bound to the same program space.
2351 However, each inferior may still have its own address
2352 space. */
2353 inf->aspace = maybe_new_address_space ();
2354 inf->pspace = current_program_space;
2355 }
2356 else
2357 {
2358 /* In the traditional debugging scenario, there's a 1-1 match
2359 between program/address spaces. We simply bind the inferior
2360 to the program space's address space. */
2361 inf = current_inferior ();
2362 inferior_appeared (inf, pid);
2363 }
2364
2365 inf->attach_flag = attached;
2366 inf->fake_pid_p = fake_pid_p;
2367
2368 /* If no main executable is currently open then attempt to
2369 open the file that was executed to create this inferior. */
2370 if (try_open_exec && get_exec_file (0) == NULL)
2371 exec_file_locate_attach (pid, 0, 1);
2372
2373 return inf;
2374 }
2375
2376 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2377 static remote_thread_info *get_remote_thread_info (ptid_t ptid);
2378
2379 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2380 according to RUNNING. */
2381
2382 thread_info *
2383 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2384 {
2385 struct remote_state *rs = get_remote_state ();
2386 struct thread_info *thread;
2387
2388 /* GDB historically didn't pull threads in the initial connection
2389 setup. If the remote target doesn't even have a concept of
2390 threads (e.g., a bare-metal target), even if internally we
2391 consider that a single-threaded target, mentioning a new thread
2392 might be confusing to the user. Be silent then, preserving the
2393 age old behavior. */
2394 if (rs->starting_up)
2395 thread = add_thread_silent (ptid);
2396 else
2397 thread = add_thread (ptid);
2398
2399 get_remote_thread_info (thread)->vcont_resumed = executing;
2400 set_executing (ptid, executing);
2401 set_running (ptid, running);
2402
2403 return thread;
2404 }
2405
2406 /* Come here when we learn about a thread id from the remote target.
2407 It may be the first time we hear about such thread, so take the
2408 opportunity to add it to GDB's thread list. In case this is the
2409 first time we're noticing its corresponding inferior, add it to
2410 GDB's inferior list as well. EXECUTING indicates whether the
2411 thread is (internally) executing or stopped. */
2412
2413 void
2414 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2415 {
2416 /* In non-stop mode, we assume new found threads are (externally)
2417 running until proven otherwise with a stop reply. In all-stop,
2418 we can only get here if all threads are stopped. */
2419 int running = target_is_non_stop_p () ? 1 : 0;
2420
2421 /* If this is a new thread, add it to GDB's thread list.
2422 If we leave it up to WFI to do this, bad things will happen. */
2423
2424 thread_info *tp = find_thread_ptid (currthread);
2425 if (tp != NULL && tp->state == THREAD_EXITED)
2426 {
2427 /* We're seeing an event on a thread id we knew had exited.
2428 This has to be a new thread reusing the old id. Add it. */
2429 remote_add_thread (currthread, running, executing);
2430 return;
2431 }
2432
2433 if (!in_thread_list (currthread))
2434 {
2435 struct inferior *inf = NULL;
2436 int pid = ptid_get_pid (currthread);
2437
2438 if (ptid_is_pid (inferior_ptid)
2439 && pid == ptid_get_pid (inferior_ptid))
2440 {
2441 /* inferior_ptid has no thread member yet. This can happen
2442 with the vAttach -> remote_wait,"TAAthread:" path if the
2443 stub doesn't support qC. This is the first stop reported
2444 after an attach, so this is the main thread. Update the
2445 ptid in the thread list. */
2446 if (in_thread_list (pid_to_ptid (pid)))
2447 thread_change_ptid (inferior_ptid, currthread);
2448 else
2449 {
2450 remote_add_thread (currthread, running, executing);
2451 inferior_ptid = currthread;
2452 }
2453 return;
2454 }
2455
2456 if (ptid_equal (magic_null_ptid, inferior_ptid))
2457 {
2458 /* inferior_ptid is not set yet. This can happen with the
2459 vRun -> remote_wait,"TAAthread:" path if the stub
2460 doesn't support qC. This is the first stop reported
2461 after an attach, so this is the main thread. Update the
2462 ptid in the thread list. */
2463 thread_change_ptid (inferior_ptid, currthread);
2464 return;
2465 }
2466
2467 /* When connecting to a target remote, or to a target
2468 extended-remote which already was debugging an inferior, we
2469 may not know about it yet. Add it before adding its child
2470 thread, so notifications are emitted in a sensible order. */
2471 if (find_inferior_pid (ptid_get_pid (currthread)) == NULL)
2472 {
2473 struct remote_state *rs = get_remote_state ();
2474 int fake_pid_p = !remote_multi_process_p (rs);
2475
2476 inf = remote_add_inferior (fake_pid_p,
2477 ptid_get_pid (currthread), -1, 1);
2478 }
2479
2480 /* This is really a new thread. Add it. */
2481 thread_info *new_thr
2482 = remote_add_thread (currthread, running, executing);
2483
2484 /* If we found a new inferior, let the common code do whatever
2485 it needs to with it (e.g., read shared libraries, insert
2486 breakpoints), unless we're just setting up an all-stop
2487 connection. */
2488 if (inf != NULL)
2489 {
2490 struct remote_state *rs = get_remote_state ();
2491
2492 if (!rs->starting_up)
2493 notice_new_inferior (new_thr, executing, 0);
2494 }
2495 }
2496 }
2497
2498 /* Return THREAD's private thread data, creating it if necessary. */
2499
2500 static remote_thread_info *
2501 get_remote_thread_info (thread_info *thread)
2502 {
2503 gdb_assert (thread != NULL);
2504
2505 if (thread->priv == NULL)
2506 thread->priv.reset (new remote_thread_info);
2507
2508 return static_cast<remote_thread_info *> (thread->priv.get ());
2509 }
2510
2511 static remote_thread_info *
2512 get_remote_thread_info (ptid_t ptid)
2513 {
2514 thread_info *thr = find_thread_ptid (ptid);
2515 return get_remote_thread_info (thr);
2516 }
2517
2518 /* Call this function as a result of
2519 1) A halt indication (T packet) containing a thread id
2520 2) A direct query of currthread
2521 3) Successful execution of set thread */
2522
2523 static void
2524 record_currthread (struct remote_state *rs, ptid_t currthread)
2525 {
2526 rs->general_thread = currthread;
2527 }
2528
2529 /* If 'QPassSignals' is supported, tell the remote stub what signals
2530 it can simply pass through to the inferior without reporting. */
2531
2532 void
2533 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2534 {
2535 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2536 {
2537 char *pass_packet, *p;
2538 int count = 0, i;
2539 struct remote_state *rs = get_remote_state ();
2540
2541 gdb_assert (numsigs < 256);
2542 for (i = 0; i < numsigs; i++)
2543 {
2544 if (pass_signals[i])
2545 count++;
2546 }
2547 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2548 strcpy (pass_packet, "QPassSignals:");
2549 p = pass_packet + strlen (pass_packet);
2550 for (i = 0; i < numsigs; i++)
2551 {
2552 if (pass_signals[i])
2553 {
2554 if (i >= 16)
2555 *p++ = tohex (i >> 4);
2556 *p++ = tohex (i & 15);
2557 if (count)
2558 *p++ = ';';
2559 else
2560 break;
2561 count--;
2562 }
2563 }
2564 *p = 0;
2565 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2566 {
2567 putpkt (pass_packet);
2568 getpkt (&rs->buf, &rs->buf_size, 0);
2569 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2570 if (rs->last_pass_packet)
2571 xfree (rs->last_pass_packet);
2572 rs->last_pass_packet = pass_packet;
2573 }
2574 else
2575 xfree (pass_packet);
2576 }
2577 }
2578
2579 /* If 'QCatchSyscalls' is supported, tell the remote stub
2580 to report syscalls to GDB. */
2581
2582 int
2583 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2584 gdb::array_view<const int> syscall_counts)
2585 {
2586 const char *catch_packet;
2587 enum packet_result result;
2588 int n_sysno = 0;
2589
2590 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2591 {
2592 /* Not supported. */
2593 return 1;
2594 }
2595
2596 if (needed && any_count == 0)
2597 {
2598 /* Count how many syscalls are to be caught. */
2599 for (size_t i = 0; i < syscall_counts.size (); i++)
2600 {
2601 if (syscall_counts[i] != 0)
2602 n_sysno++;
2603 }
2604 }
2605
2606 if (remote_debug)
2607 {
2608 fprintf_unfiltered (gdb_stdlog,
2609 "remote_set_syscall_catchpoint "
2610 "pid %d needed %d any_count %d n_sysno %d\n",
2611 pid, needed, any_count, n_sysno);
2612 }
2613
2614 std::string built_packet;
2615 if (needed)
2616 {
2617 /* Prepare a packet with the sysno list, assuming max 8+1
2618 characters for a sysno. If the resulting packet size is too
2619 big, fallback on the non-selective packet. */
2620 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2621 built_packet.reserve (maxpktsz);
2622 built_packet = "QCatchSyscalls:1";
2623 if (any_count == 0)
2624 {
2625 /* Add in each syscall to be caught. */
2626 for (size_t i = 0; i < syscall_counts.size (); i++)
2627 {
2628 if (syscall_counts[i] != 0)
2629 string_appendf (built_packet, ";%zx", i);
2630 }
2631 }
2632 if (built_packet.size () > get_remote_packet_size ())
2633 {
2634 /* catch_packet too big. Fallback to less efficient
2635 non selective mode, with GDB doing the filtering. */
2636 catch_packet = "QCatchSyscalls:1";
2637 }
2638 else
2639 catch_packet = built_packet.c_str ();
2640 }
2641 else
2642 catch_packet = "QCatchSyscalls:0";
2643
2644 struct remote_state *rs = get_remote_state ();
2645
2646 putpkt (catch_packet);
2647 getpkt (&rs->buf, &rs->buf_size, 0);
2648 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2649 if (result == PACKET_OK)
2650 return 0;
2651 else
2652 return -1;
2653 }
2654
2655 /* If 'QProgramSignals' is supported, tell the remote stub what
2656 signals it should pass through to the inferior when detaching. */
2657
2658 void
2659 remote_target::program_signals (int numsigs, unsigned char *signals)
2660 {
2661 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2662 {
2663 char *packet, *p;
2664 int count = 0, i;
2665 struct remote_state *rs = get_remote_state ();
2666
2667 gdb_assert (numsigs < 256);
2668 for (i = 0; i < numsigs; i++)
2669 {
2670 if (signals[i])
2671 count++;
2672 }
2673 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2674 strcpy (packet, "QProgramSignals:");
2675 p = packet + strlen (packet);
2676 for (i = 0; i < numsigs; i++)
2677 {
2678 if (signal_pass_state (i))
2679 {
2680 if (i >= 16)
2681 *p++ = tohex (i >> 4);
2682 *p++ = tohex (i & 15);
2683 if (count)
2684 *p++ = ';';
2685 else
2686 break;
2687 count--;
2688 }
2689 }
2690 *p = 0;
2691 if (!rs->last_program_signals_packet
2692 || strcmp (rs->last_program_signals_packet, packet) != 0)
2693 {
2694 putpkt (packet);
2695 getpkt (&rs->buf, &rs->buf_size, 0);
2696 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2697 xfree (rs->last_program_signals_packet);
2698 rs->last_program_signals_packet = packet;
2699 }
2700 else
2701 xfree (packet);
2702 }
2703 }
2704
2705 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2706 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2707 thread. If GEN is set, set the general thread, if not, then set
2708 the step/continue thread. */
2709 void
2710 remote_target::set_thread (ptid_t ptid, int gen)
2711 {
2712 struct remote_state *rs = get_remote_state ();
2713 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2714 char *buf = rs->buf;
2715 char *endbuf = rs->buf + get_remote_packet_size ();
2716
2717 if (ptid_equal (state, ptid))
2718 return;
2719
2720 *buf++ = 'H';
2721 *buf++ = gen ? 'g' : 'c';
2722 if (ptid_equal (ptid, magic_null_ptid))
2723 xsnprintf (buf, endbuf - buf, "0");
2724 else if (ptid_equal (ptid, any_thread_ptid))
2725 xsnprintf (buf, endbuf - buf, "0");
2726 else if (ptid_equal (ptid, minus_one_ptid))
2727 xsnprintf (buf, endbuf - buf, "-1");
2728 else
2729 write_ptid (buf, endbuf, ptid);
2730 putpkt (rs->buf);
2731 getpkt (&rs->buf, &rs->buf_size, 0);
2732 if (gen)
2733 rs->general_thread = ptid;
2734 else
2735 rs->continue_thread = ptid;
2736 }
2737
2738 void
2739 remote_target::set_general_thread (ptid_t ptid)
2740 {
2741 set_thread (ptid, 1);
2742 }
2743
2744 void
2745 remote_target::set_continue_thread (ptid_t ptid)
2746 {
2747 set_thread (ptid, 0);
2748 }
2749
2750 /* Change the remote current process. Which thread within the process
2751 ends up selected isn't important, as long as it is the same process
2752 as what INFERIOR_PTID points to.
2753
2754 This comes from that fact that there is no explicit notion of
2755 "selected process" in the protocol. The selected process for
2756 general operations is the process the selected general thread
2757 belongs to. */
2758
2759 void
2760 remote_target::set_general_process ()
2761 {
2762 struct remote_state *rs = get_remote_state ();
2763
2764 /* If the remote can't handle multiple processes, don't bother. */
2765 if (!remote_multi_process_p (rs))
2766 return;
2767
2768 /* We only need to change the remote current thread if it's pointing
2769 at some other process. */
2770 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2771 set_general_thread (inferior_ptid);
2772 }
2773
2774 \f
2775 /* Return nonzero if this is the main thread that we made up ourselves
2776 to model non-threaded targets as single-threaded. */
2777
2778 static int
2779 remote_thread_always_alive (ptid_t ptid)
2780 {
2781 if (ptid_equal (ptid, magic_null_ptid))
2782 /* The main thread is always alive. */
2783 return 1;
2784
2785 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2786 /* The main thread is always alive. This can happen after a
2787 vAttach, if the remote side doesn't support
2788 multi-threading. */
2789 return 1;
2790
2791 return 0;
2792 }
2793
2794 /* Return nonzero if the thread PTID is still alive on the remote
2795 system. */
2796
2797 bool
2798 remote_target::thread_alive (ptid_t ptid)
2799 {
2800 struct remote_state *rs = get_remote_state ();
2801 char *p, *endp;
2802
2803 /* Check if this is a thread that we made up ourselves to model
2804 non-threaded targets as single-threaded. */
2805 if (remote_thread_always_alive (ptid))
2806 return 1;
2807
2808 p = rs->buf;
2809 endp = rs->buf + get_remote_packet_size ();
2810
2811 *p++ = 'T';
2812 write_ptid (p, endp, ptid);
2813
2814 putpkt (rs->buf);
2815 getpkt (&rs->buf, &rs->buf_size, 0);
2816 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2817 }
2818
2819 /* Return a pointer to a thread name if we know it and NULL otherwise.
2820 The thread_info object owns the memory for the name. */
2821
2822 const char *
2823 remote_target::thread_name (struct thread_info *info)
2824 {
2825 if (info->priv != NULL)
2826 {
2827 const std::string &name = get_remote_thread_info (info)->name;
2828 return !name.empty () ? name.c_str () : NULL;
2829 }
2830
2831 return NULL;
2832 }
2833
2834 /* About these extended threadlist and threadinfo packets. They are
2835 variable length packets but, the fields within them are often fixed
2836 length. They are redundent enough to send over UDP as is the
2837 remote protocol in general. There is a matching unit test module
2838 in libstub. */
2839
2840 /* WARNING: This threadref data structure comes from the remote O.S.,
2841 libstub protocol encoding, and remote.c. It is not particularly
2842 changable. */
2843
2844 /* Right now, the internal structure is int. We want it to be bigger.
2845 Plan to fix this. */
2846
2847 typedef int gdb_threadref; /* Internal GDB thread reference. */
2848
2849 /* gdb_ext_thread_info is an internal GDB data structure which is
2850 equivalent to the reply of the remote threadinfo packet. */
2851
2852 struct gdb_ext_thread_info
2853 {
2854 threadref threadid; /* External form of thread reference. */
2855 int active; /* Has state interesting to GDB?
2856 regs, stack. */
2857 char display[256]; /* Brief state display, name,
2858 blocked/suspended. */
2859 char shortname[32]; /* To be used to name threads. */
2860 char more_display[256]; /* Long info, statistics, queue depth,
2861 whatever. */
2862 };
2863
2864 /* The volume of remote transfers can be limited by submitting
2865 a mask containing bits specifying the desired information.
2866 Use a union of these values as the 'selection' parameter to
2867 get_thread_info. FIXME: Make these TAG names more thread specific. */
2868
2869 #define TAG_THREADID 1
2870 #define TAG_EXISTS 2
2871 #define TAG_DISPLAY 4
2872 #define TAG_THREADNAME 8
2873 #define TAG_MOREDISPLAY 16
2874
2875 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2876
2877 static char *unpack_nibble (char *buf, int *val);
2878
2879 static char *unpack_byte (char *buf, int *value);
2880
2881 static char *pack_int (char *buf, int value);
2882
2883 static char *unpack_int (char *buf, int *value);
2884
2885 static char *unpack_string (char *src, char *dest, int length);
2886
2887 static char *pack_threadid (char *pkt, threadref *id);
2888
2889 static char *unpack_threadid (char *inbuf, threadref *id);
2890
2891 void int_to_threadref (threadref *id, int value);
2892
2893 static int threadref_to_int (threadref *ref);
2894
2895 static void copy_threadref (threadref *dest, threadref *src);
2896
2897 static int threadmatch (threadref *dest, threadref *src);
2898
2899 static char *pack_threadinfo_request (char *pkt, int mode,
2900 threadref *id);
2901
2902 static char *pack_threadlist_request (char *pkt, int startflag,
2903 int threadcount,
2904 threadref *nextthread);
2905
2906 static int remote_newthread_step (threadref *ref, void *context);
2907
2908
2909 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2910 buffer we're allowed to write to. Returns
2911 BUF+CHARACTERS_WRITTEN. */
2912
2913 char *
2914 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2915 {
2916 int pid, tid;
2917 struct remote_state *rs = get_remote_state ();
2918
2919 if (remote_multi_process_p (rs))
2920 {
2921 pid = ptid_get_pid (ptid);
2922 if (pid < 0)
2923 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2924 else
2925 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2926 }
2927 tid = ptid_get_lwp (ptid);
2928 if (tid < 0)
2929 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2930 else
2931 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2932
2933 return buf;
2934 }
2935
2936 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2937 last parsed char. Returns null_ptid if no thread id is found, and
2938 throws an error if the thread id has an invalid format. */
2939
2940 static ptid_t
2941 read_ptid (const char *buf, const char **obuf)
2942 {
2943 const char *p = buf;
2944 const char *pp;
2945 ULONGEST pid = 0, tid = 0;
2946
2947 if (*p == 'p')
2948 {
2949 /* Multi-process ptid. */
2950 pp = unpack_varlen_hex (p + 1, &pid);
2951 if (*pp != '.')
2952 error (_("invalid remote ptid: %s"), p);
2953
2954 p = pp;
2955 pp = unpack_varlen_hex (p + 1, &tid);
2956 if (obuf)
2957 *obuf = pp;
2958 return ptid_build (pid, tid, 0);
2959 }
2960
2961 /* No multi-process. Just a tid. */
2962 pp = unpack_varlen_hex (p, &tid);
2963
2964 /* Return null_ptid when no thread id is found. */
2965 if (p == pp)
2966 {
2967 if (obuf)
2968 *obuf = pp;
2969 return null_ptid;
2970 }
2971
2972 /* Since the stub is not sending a process id, then default to
2973 what's in inferior_ptid, unless it's null at this point. If so,
2974 then since there's no way to know the pid of the reported
2975 threads, use the magic number. */
2976 if (ptid_equal (inferior_ptid, null_ptid))
2977 pid = ptid_get_pid (magic_null_ptid);
2978 else
2979 pid = ptid_get_pid (inferior_ptid);
2980
2981 if (obuf)
2982 *obuf = pp;
2983 return ptid_build (pid, tid, 0);
2984 }
2985
2986 static int
2987 stubhex (int ch)
2988 {
2989 if (ch >= 'a' && ch <= 'f')
2990 return ch - 'a' + 10;
2991 if (ch >= '0' && ch <= '9')
2992 return ch - '0';
2993 if (ch >= 'A' && ch <= 'F')
2994 return ch - 'A' + 10;
2995 return -1;
2996 }
2997
2998 static int
2999 stub_unpack_int (char *buff, int fieldlength)
3000 {
3001 int nibble;
3002 int retval = 0;
3003
3004 while (fieldlength)
3005 {
3006 nibble = stubhex (*buff++);
3007 retval |= nibble;
3008 fieldlength--;
3009 if (fieldlength)
3010 retval = retval << 4;
3011 }
3012 return retval;
3013 }
3014
3015 static char *
3016 unpack_nibble (char *buf, int *val)
3017 {
3018 *val = fromhex (*buf++);
3019 return buf;
3020 }
3021
3022 static char *
3023 unpack_byte (char *buf, int *value)
3024 {
3025 *value = stub_unpack_int (buf, 2);
3026 return buf + 2;
3027 }
3028
3029 static char *
3030 pack_int (char *buf, int value)
3031 {
3032 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3033 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3034 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3035 buf = pack_hex_byte (buf, (value & 0xff));
3036 return buf;
3037 }
3038
3039 static char *
3040 unpack_int (char *buf, int *value)
3041 {
3042 *value = stub_unpack_int (buf, 8);
3043 return buf + 8;
3044 }
3045
3046 #if 0 /* Currently unused, uncomment when needed. */
3047 static char *pack_string (char *pkt, char *string);
3048
3049 static char *
3050 pack_string (char *pkt, char *string)
3051 {
3052 char ch;
3053 int len;
3054
3055 len = strlen (string);
3056 if (len > 200)
3057 len = 200; /* Bigger than most GDB packets, junk??? */
3058 pkt = pack_hex_byte (pkt, len);
3059 while (len-- > 0)
3060 {
3061 ch = *string++;
3062 if ((ch == '\0') || (ch == '#'))
3063 ch = '*'; /* Protect encapsulation. */
3064 *pkt++ = ch;
3065 }
3066 return pkt;
3067 }
3068 #endif /* 0 (unused) */
3069
3070 static char *
3071 unpack_string (char *src, char *dest, int length)
3072 {
3073 while (length--)
3074 *dest++ = *src++;
3075 *dest = '\0';
3076 return src;
3077 }
3078
3079 static char *
3080 pack_threadid (char *pkt, threadref *id)
3081 {
3082 char *limit;
3083 unsigned char *altid;
3084
3085 altid = (unsigned char *) id;
3086 limit = pkt + BUF_THREAD_ID_SIZE;
3087 while (pkt < limit)
3088 pkt = pack_hex_byte (pkt, *altid++);
3089 return pkt;
3090 }
3091
3092
3093 static char *
3094 unpack_threadid (char *inbuf, threadref *id)
3095 {
3096 char *altref;
3097 char *limit = inbuf + BUF_THREAD_ID_SIZE;
3098 int x, y;
3099
3100 altref = (char *) id;
3101
3102 while (inbuf < limit)
3103 {
3104 x = stubhex (*inbuf++);
3105 y = stubhex (*inbuf++);
3106 *altref++ = (x << 4) | y;
3107 }
3108 return inbuf;
3109 }
3110
3111 /* Externally, threadrefs are 64 bits but internally, they are still
3112 ints. This is due to a mismatch of specifications. We would like
3113 to use 64bit thread references internally. This is an adapter
3114 function. */
3115
3116 void
3117 int_to_threadref (threadref *id, int value)
3118 {
3119 unsigned char *scan;
3120
3121 scan = (unsigned char *) id;
3122 {
3123 int i = 4;
3124 while (i--)
3125 *scan++ = 0;
3126 }
3127 *scan++ = (value >> 24) & 0xff;
3128 *scan++ = (value >> 16) & 0xff;
3129 *scan++ = (value >> 8) & 0xff;
3130 *scan++ = (value & 0xff);
3131 }
3132
3133 static int
3134 threadref_to_int (threadref *ref)
3135 {
3136 int i, value = 0;
3137 unsigned char *scan;
3138
3139 scan = *ref;
3140 scan += 4;
3141 i = 4;
3142 while (i-- > 0)
3143 value = (value << 8) | ((*scan++) & 0xff);
3144 return value;
3145 }
3146
3147 static void
3148 copy_threadref (threadref *dest, threadref *src)
3149 {
3150 int i;
3151 unsigned char *csrc, *cdest;
3152
3153 csrc = (unsigned char *) src;
3154 cdest = (unsigned char *) dest;
3155 i = 8;
3156 while (i--)
3157 *cdest++ = *csrc++;
3158 }
3159
3160 static int
3161 threadmatch (threadref *dest, threadref *src)
3162 {
3163 /* Things are broken right now, so just assume we got a match. */
3164 #if 0
3165 unsigned char *srcp, *destp;
3166 int i, result;
3167 srcp = (char *) src;
3168 destp = (char *) dest;
3169
3170 result = 1;
3171 while (i-- > 0)
3172 result &= (*srcp++ == *destp++) ? 1 : 0;
3173 return result;
3174 #endif
3175 return 1;
3176 }
3177
3178 /*
3179 threadid:1, # always request threadid
3180 context_exists:2,
3181 display:4,
3182 unique_name:8,
3183 more_display:16
3184 */
3185
3186 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3187
3188 static char *
3189 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3190 {
3191 *pkt++ = 'q'; /* Info Query */
3192 *pkt++ = 'P'; /* process or thread info */
3193 pkt = pack_int (pkt, mode); /* mode */
3194 pkt = pack_threadid (pkt, id); /* threadid */
3195 *pkt = '\0'; /* terminate */
3196 return pkt;
3197 }
3198
3199 /* These values tag the fields in a thread info response packet. */
3200 /* Tagging the fields allows us to request specific fields and to
3201 add more fields as time goes by. */
3202
3203 #define TAG_THREADID 1 /* Echo the thread identifier. */
3204 #define TAG_EXISTS 2 /* Is this process defined enough to
3205 fetch registers and its stack? */
3206 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3207 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3208 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3209 the process. */
3210
3211 int
3212 remote_target::remote_unpack_thread_info_response (char *pkt,
3213 threadref *expectedref,
3214 gdb_ext_thread_info *info)
3215 {
3216 struct remote_state *rs = get_remote_state ();
3217 int mask, length;
3218 int tag;
3219 threadref ref;
3220 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
3221 int retval = 1;
3222
3223 /* info->threadid = 0; FIXME: implement zero_threadref. */
3224 info->active = 0;
3225 info->display[0] = '\0';
3226 info->shortname[0] = '\0';
3227 info->more_display[0] = '\0';
3228
3229 /* Assume the characters indicating the packet type have been
3230 stripped. */
3231 pkt = unpack_int (pkt, &mask); /* arg mask */
3232 pkt = unpack_threadid (pkt, &ref);
3233
3234 if (mask == 0)
3235 warning (_("Incomplete response to threadinfo request."));
3236 if (!threadmatch (&ref, expectedref))
3237 { /* This is an answer to a different request. */
3238 warning (_("ERROR RMT Thread info mismatch."));
3239 return 0;
3240 }
3241 copy_threadref (&info->threadid, &ref);
3242
3243 /* Loop on tagged fields , try to bail if somthing goes wrong. */
3244
3245 /* Packets are terminated with nulls. */
3246 while ((pkt < limit) && mask && *pkt)
3247 {
3248 pkt = unpack_int (pkt, &tag); /* tag */
3249 pkt = unpack_byte (pkt, &length); /* length */
3250 if (!(tag & mask)) /* Tags out of synch with mask. */
3251 {
3252 warning (_("ERROR RMT: threadinfo tag mismatch."));
3253 retval = 0;
3254 break;
3255 }
3256 if (tag == TAG_THREADID)
3257 {
3258 if (length != 16)
3259 {
3260 warning (_("ERROR RMT: length of threadid is not 16."));
3261 retval = 0;
3262 break;
3263 }
3264 pkt = unpack_threadid (pkt, &ref);
3265 mask = mask & ~TAG_THREADID;
3266 continue;
3267 }
3268 if (tag == TAG_EXISTS)
3269 {
3270 info->active = stub_unpack_int (pkt, length);
3271 pkt += length;
3272 mask = mask & ~(TAG_EXISTS);
3273 if (length > 8)
3274 {
3275 warning (_("ERROR RMT: 'exists' length too long."));
3276 retval = 0;
3277 break;
3278 }
3279 continue;
3280 }
3281 if (tag == TAG_THREADNAME)
3282 {
3283 pkt = unpack_string (pkt, &info->shortname[0], length);
3284 mask = mask & ~TAG_THREADNAME;
3285 continue;
3286 }
3287 if (tag == TAG_DISPLAY)
3288 {
3289 pkt = unpack_string (pkt, &info->display[0], length);
3290 mask = mask & ~TAG_DISPLAY;
3291 continue;
3292 }
3293 if (tag == TAG_MOREDISPLAY)
3294 {
3295 pkt = unpack_string (pkt, &info->more_display[0], length);
3296 mask = mask & ~TAG_MOREDISPLAY;
3297 continue;
3298 }
3299 warning (_("ERROR RMT: unknown thread info tag."));
3300 break; /* Not a tag we know about. */
3301 }
3302 return retval;
3303 }
3304
3305 int
3306 remote_target::remote_get_threadinfo (threadref *threadid,
3307 int fieldset,
3308 gdb_ext_thread_info *info)
3309 {
3310 struct remote_state *rs = get_remote_state ();
3311 int result;
3312
3313 pack_threadinfo_request (rs->buf, fieldset, threadid);
3314 putpkt (rs->buf);
3315 getpkt (&rs->buf, &rs->buf_size, 0);
3316
3317 if (rs->buf[0] == '\0')
3318 return 0;
3319
3320 result = remote_unpack_thread_info_response (rs->buf + 2,
3321 threadid, info);
3322 return result;
3323 }
3324
3325 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3326
3327 static char *
3328 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3329 threadref *nextthread)
3330 {
3331 *pkt++ = 'q'; /* info query packet */
3332 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3333 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3334 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3335 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3336 *pkt = '\0';
3337 return pkt;
3338 }
3339
3340 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3341
3342 int
3343 remote_target::parse_threadlist_response (char *pkt, int result_limit,
3344 threadref *original_echo,
3345 threadref *resultlist,
3346 int *doneflag)
3347 {
3348 struct remote_state *rs = get_remote_state ();
3349 char *limit;
3350 int count, resultcount, done;
3351
3352 resultcount = 0;
3353 /* Assume the 'q' and 'M chars have been stripped. */
3354 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3355 /* done parse past here */
3356 pkt = unpack_byte (pkt, &count); /* count field */
3357 pkt = unpack_nibble (pkt, &done);
3358 /* The first threadid is the argument threadid. */
3359 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3360 while ((count-- > 0) && (pkt < limit))
3361 {
3362 pkt = unpack_threadid (pkt, resultlist++);
3363 if (resultcount++ >= result_limit)
3364 break;
3365 }
3366 if (doneflag)
3367 *doneflag = done;
3368 return resultcount;
3369 }
3370
3371 /* Fetch the next batch of threads from the remote. Returns -1 if the
3372 qL packet is not supported, 0 on error and 1 on success. */
3373
3374 int
3375 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3376 int result_limit, int *done, int *result_count,
3377 threadref *threadlist)
3378 {
3379 struct remote_state *rs = get_remote_state ();
3380 int result = 1;
3381
3382 /* Trancate result limit to be smaller than the packet size. */
3383 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3384 >= get_remote_packet_size ())
3385 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3386
3387 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3388 putpkt (rs->buf);
3389 getpkt (&rs->buf, &rs->buf_size, 0);
3390 if (*rs->buf == '\0')
3391 {
3392 /* Packet not supported. */
3393 return -1;
3394 }
3395
3396 *result_count =
3397 parse_threadlist_response (rs->buf + 2, result_limit,
3398 &rs->echo_nextthread, threadlist, done);
3399
3400 if (!threadmatch (&rs->echo_nextthread, nextthread))
3401 {
3402 /* FIXME: This is a good reason to drop the packet. */
3403 /* Possably, there is a duplicate response. */
3404 /* Possabilities :
3405 retransmit immediatly - race conditions
3406 retransmit after timeout - yes
3407 exit
3408 wait for packet, then exit
3409 */
3410 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3411 return 0; /* I choose simply exiting. */
3412 }
3413 if (*result_count <= 0)
3414 {
3415 if (*done != 1)
3416 {
3417 warning (_("RMT ERROR : failed to get remote thread list."));
3418 result = 0;
3419 }
3420 return result; /* break; */
3421 }
3422 if (*result_count > result_limit)
3423 {
3424 *result_count = 0;
3425 warning (_("RMT ERROR: threadlist response longer than requested."));
3426 return 0;
3427 }
3428 return result;
3429 }
3430
3431 /* Fetch the list of remote threads, with the qL packet, and call
3432 STEPFUNCTION for each thread found. Stops iterating and returns 1
3433 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3434 STEPFUNCTION returns false. If the packet is not supported,
3435 returns -1. */
3436
3437 int
3438 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3439 void *context, int looplimit)
3440 {
3441 struct remote_state *rs = get_remote_state ();
3442 int done, i, result_count;
3443 int startflag = 1;
3444 int result = 1;
3445 int loopcount = 0;
3446
3447 done = 0;
3448 while (!done)
3449 {
3450 if (loopcount++ > looplimit)
3451 {
3452 result = 0;
3453 warning (_("Remote fetch threadlist -infinite loop-."));
3454 break;
3455 }
3456 result = remote_get_threadlist (startflag, &rs->nextthread,
3457 MAXTHREADLISTRESULTS,
3458 &done, &result_count,
3459 rs->resultthreadlist);
3460 if (result <= 0)
3461 break;
3462 /* Clear for later iterations. */
3463 startflag = 0;
3464 /* Setup to resume next batch of thread references, set nextthread. */
3465 if (result_count >= 1)
3466 copy_threadref (&rs->nextthread,
3467 &rs->resultthreadlist[result_count - 1]);
3468 i = 0;
3469 while (result_count--)
3470 {
3471 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3472 {
3473 result = 0;
3474 break;
3475 }
3476 }
3477 }
3478 return result;
3479 }
3480
3481 /* A thread found on the remote target. */
3482
3483 struct thread_item
3484 {
3485 explicit thread_item (ptid_t ptid_)
3486 : ptid (ptid_)
3487 {}
3488
3489 thread_item (thread_item &&other) = default;
3490 thread_item &operator= (thread_item &&other) = default;
3491
3492 DISABLE_COPY_AND_ASSIGN (thread_item);
3493
3494 /* The thread's PTID. */
3495 ptid_t ptid;
3496
3497 /* The thread's extra info. */
3498 std::string extra;
3499
3500 /* The thread's name. */
3501 std::string name;
3502
3503 /* The core the thread was running on. -1 if not known. */
3504 int core = -1;
3505
3506 /* The thread handle associated with the thread. */
3507 gdb::byte_vector thread_handle;
3508 };
3509
3510 /* Context passed around to the various methods listing remote
3511 threads. As new threads are found, they're added to the ITEMS
3512 vector. */
3513
3514 struct threads_listing_context
3515 {
3516 /* Return true if this object contains an entry for a thread with ptid
3517 PTID. */
3518
3519 bool contains_thread (ptid_t ptid) const
3520 {
3521 auto match_ptid = [&] (const thread_item &item)
3522 {
3523 return item.ptid == ptid;
3524 };
3525
3526 auto it = std::find_if (this->items.begin (),
3527 this->items.end (),
3528 match_ptid);
3529
3530 return it != this->items.end ();
3531 }
3532
3533 /* Remove the thread with ptid PTID. */
3534
3535 void remove_thread (ptid_t ptid)
3536 {
3537 auto match_ptid = [&] (const thread_item &item)
3538 {
3539 return item.ptid == ptid;
3540 };
3541
3542 auto it = std::remove_if (this->items.begin (),
3543 this->items.end (),
3544 match_ptid);
3545
3546 if (it != this->items.end ())
3547 this->items.erase (it);
3548 }
3549
3550 /* The threads found on the remote target. */
3551 std::vector<thread_item> items;
3552 };
3553
3554 static int
3555 remote_newthread_step (threadref *ref, void *data)
3556 {
3557 struct threads_listing_context *context
3558 = (struct threads_listing_context *) data;
3559 int pid = inferior_ptid.pid ();
3560 int lwp = threadref_to_int (ref);
3561 ptid_t ptid (pid, lwp);
3562
3563 context->items.emplace_back (ptid);
3564
3565 return 1; /* continue iterator */
3566 }
3567
3568 #define CRAZY_MAX_THREADS 1000
3569
3570 ptid_t
3571 remote_target::remote_current_thread (ptid_t oldpid)
3572 {
3573 struct remote_state *rs = get_remote_state ();
3574
3575 putpkt ("qC");
3576 getpkt (&rs->buf, &rs->buf_size, 0);
3577 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3578 {
3579 const char *obuf;
3580 ptid_t result;
3581
3582 result = read_ptid (&rs->buf[2], &obuf);
3583 if (*obuf != '\0' && remote_debug)
3584 fprintf_unfiltered (gdb_stdlog,
3585 "warning: garbage in qC reply\n");
3586
3587 return result;
3588 }
3589 else
3590 return oldpid;
3591 }
3592
3593 /* List remote threads using the deprecated qL packet. */
3594
3595 int
3596 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3597 {
3598 if (remote_threadlist_iterator (remote_newthread_step, context,
3599 CRAZY_MAX_THREADS) >= 0)
3600 return 1;
3601
3602 return 0;
3603 }
3604
3605 #if defined(HAVE_LIBEXPAT)
3606
3607 static void
3608 start_thread (struct gdb_xml_parser *parser,
3609 const struct gdb_xml_element *element,
3610 void *user_data,
3611 std::vector<gdb_xml_value> &attributes)
3612 {
3613 struct threads_listing_context *data
3614 = (struct threads_listing_context *) user_data;
3615 struct gdb_xml_value *attr;
3616
3617 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3618 ptid_t ptid = read_ptid (id, NULL);
3619
3620 data->items.emplace_back (ptid);
3621 thread_item &item = data->items.back ();
3622
3623 attr = xml_find_attribute (attributes, "core");
3624 if (attr != NULL)
3625 item.core = *(ULONGEST *) attr->value.get ();
3626
3627 attr = xml_find_attribute (attributes, "name");
3628 if (attr != NULL)
3629 item.name = (const char *) attr->value.get ();
3630
3631 attr = xml_find_attribute (attributes, "handle");
3632 if (attr != NULL)
3633 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3634 }
3635
3636 static void
3637 end_thread (struct gdb_xml_parser *parser,
3638 const struct gdb_xml_element *element,
3639 void *user_data, const char *body_text)
3640 {
3641 struct threads_listing_context *data
3642 = (struct threads_listing_context *) user_data;
3643
3644 if (body_text != NULL && *body_text != '\0')
3645 data->items.back ().extra = body_text;
3646 }
3647
3648 const struct gdb_xml_attribute thread_attributes[] = {
3649 { "id", GDB_XML_AF_NONE, NULL, NULL },
3650 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3651 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3652 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3653 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3654 };
3655
3656 const struct gdb_xml_element thread_children[] = {
3657 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3658 };
3659
3660 const struct gdb_xml_element threads_children[] = {
3661 { "thread", thread_attributes, thread_children,
3662 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3663 start_thread, end_thread },
3664 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3665 };
3666
3667 const struct gdb_xml_element threads_elements[] = {
3668 { "threads", NULL, threads_children,
3669 GDB_XML_EF_NONE, NULL, NULL },
3670 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3671 };
3672
3673 #endif
3674
3675 /* List remote threads using qXfer:threads:read. */
3676
3677 int
3678 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3679 {
3680 #if defined(HAVE_LIBEXPAT)
3681 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3682 {
3683 gdb::optional<gdb::char_vector> xml
3684 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3685
3686 if (xml && (*xml)[0] != '\0')
3687 {
3688 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3689 threads_elements, xml->data (), context);
3690 }
3691
3692 return 1;
3693 }
3694 #endif
3695
3696 return 0;
3697 }
3698
3699 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3700
3701 int
3702 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3703 {
3704 struct remote_state *rs = get_remote_state ();
3705
3706 if (rs->use_threadinfo_query)
3707 {
3708 const char *bufp;
3709
3710 putpkt ("qfThreadInfo");
3711 getpkt (&rs->buf, &rs->buf_size, 0);
3712 bufp = rs->buf;
3713 if (bufp[0] != '\0') /* q packet recognized */
3714 {
3715 while (*bufp++ == 'm') /* reply contains one or more TID */
3716 {
3717 do
3718 {
3719 ptid_t ptid = read_ptid (bufp, &bufp);
3720 context->items.emplace_back (ptid);
3721 }
3722 while (*bufp++ == ','); /* comma-separated list */
3723 putpkt ("qsThreadInfo");
3724 getpkt (&rs->buf, &rs->buf_size, 0);
3725 bufp = rs->buf;
3726 }
3727 return 1;
3728 }
3729 else
3730 {
3731 /* Packet not recognized. */
3732 rs->use_threadinfo_query = 0;
3733 }
3734 }
3735
3736 return 0;
3737 }
3738
3739 /* Implement the to_update_thread_list function for the remote
3740 targets. */
3741
3742 void
3743 remote_target::update_thread_list ()
3744 {
3745 struct threads_listing_context context;
3746 int got_list = 0;
3747
3748 /* We have a few different mechanisms to fetch the thread list. Try
3749 them all, starting with the most preferred one first, falling
3750 back to older methods. */
3751 if (remote_get_threads_with_qxfer (&context)
3752 || remote_get_threads_with_qthreadinfo (&context)
3753 || remote_get_threads_with_ql (&context))
3754 {
3755 struct thread_info *tp, *tmp;
3756
3757 got_list = 1;
3758
3759 if (context.items.empty ()
3760 && remote_thread_always_alive (inferior_ptid))
3761 {
3762 /* Some targets don't really support threads, but still
3763 reply an (empty) thread list in response to the thread
3764 listing packets, instead of replying "packet not
3765 supported". Exit early so we don't delete the main
3766 thread. */
3767 return;
3768 }
3769
3770 /* CONTEXT now holds the current thread list on the remote
3771 target end. Delete GDB-side threads no longer found on the
3772 target. */
3773 ALL_THREADS_SAFE (tp, tmp)
3774 {
3775 if (!context.contains_thread (tp->ptid))
3776 {
3777 /* Not found. */
3778 delete_thread (tp);
3779 }
3780 }
3781
3782 /* Remove any unreported fork child threads from CONTEXT so
3783 that we don't interfere with follow fork, which is where
3784 creation of such threads is handled. */
3785 remove_new_fork_children (&context);
3786
3787 /* And now add threads we don't know about yet to our list. */
3788 for (thread_item &item : context.items)
3789 {
3790 if (item.ptid != null_ptid)
3791 {
3792 /* In non-stop mode, we assume new found threads are
3793 executing until proven otherwise with a stop reply.
3794 In all-stop, we can only get here if all threads are
3795 stopped. */
3796 int executing = target_is_non_stop_p () ? 1 : 0;
3797
3798 remote_notice_new_inferior (item.ptid, executing);
3799
3800 thread_info *tp = find_thread_ptid (item.ptid);
3801 remote_thread_info *info = get_remote_thread_info (tp);
3802 info->core = item.core;
3803 info->extra = std::move (item.extra);
3804 info->name = std::move (item.name);
3805 info->thread_handle = std::move (item.thread_handle);
3806 }
3807 }
3808 }
3809
3810 if (!got_list)
3811 {
3812 /* If no thread listing method is supported, then query whether
3813 each known thread is alive, one by one, with the T packet.
3814 If the target doesn't support threads at all, then this is a
3815 no-op. See remote_thread_alive. */
3816 prune_threads ();
3817 }
3818 }
3819
3820 /*
3821 * Collect a descriptive string about the given thread.
3822 * The target may say anything it wants to about the thread
3823 * (typically info about its blocked / runnable state, name, etc.).
3824 * This string will appear in the info threads display.
3825 *
3826 * Optional: targets are not required to implement this function.
3827 */
3828
3829 const char *
3830 remote_target::extra_thread_info (thread_info *tp)
3831 {
3832 struct remote_state *rs = get_remote_state ();
3833 int result;
3834 int set;
3835 threadref id;
3836 struct gdb_ext_thread_info threadinfo;
3837 static char display_buf[100]; /* arbitrary... */
3838 int n = 0; /* position in display_buf */
3839
3840 if (rs->remote_desc == 0) /* paranoia */
3841 internal_error (__FILE__, __LINE__,
3842 _("remote_threads_extra_info"));
3843
3844 if (ptid_equal (tp->ptid, magic_null_ptid)
3845 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3846 /* This is the main thread which was added by GDB. The remote
3847 server doesn't know about it. */
3848 return NULL;
3849
3850 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3851 {
3852 if (tp->priv != NULL)
3853 {
3854 const std::string &extra = get_remote_thread_info (tp)->extra;
3855 return !extra.empty () ? extra.c_str () : NULL;
3856 }
3857 else
3858 return NULL;
3859 }
3860
3861 if (rs->use_threadextra_query)
3862 {
3863 char *b = rs->buf;
3864 char *endb = rs->buf + get_remote_packet_size ();
3865
3866 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3867 b += strlen (b);
3868 write_ptid (b, endb, tp->ptid);
3869
3870 putpkt (rs->buf);
3871 getpkt (&rs->buf, &rs->buf_size, 0);
3872 if (rs->buf[0] != 0)
3873 {
3874 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3875 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3876 display_buf [result] = '\0';
3877 return display_buf;
3878 }
3879 }
3880
3881 /* If the above query fails, fall back to the old method. */
3882 rs->use_threadextra_query = 0;
3883 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3884 | TAG_MOREDISPLAY | TAG_DISPLAY;
3885 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3886 if (remote_get_threadinfo (&id, set, &threadinfo))
3887 if (threadinfo.active)
3888 {
3889 if (*threadinfo.shortname)
3890 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3891 " Name: %s,", threadinfo.shortname);
3892 if (*threadinfo.display)
3893 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3894 " State: %s,", threadinfo.display);
3895 if (*threadinfo.more_display)
3896 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3897 " Priority: %s", threadinfo.more_display);
3898
3899 if (n > 0)
3900 {
3901 /* For purely cosmetic reasons, clear up trailing commas. */
3902 if (',' == display_buf[n-1])
3903 display_buf[n-1] = ' ';
3904 return display_buf;
3905 }
3906 }
3907 return NULL;
3908 }
3909 \f
3910
3911 bool
3912 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3913 struct static_tracepoint_marker *marker)
3914 {
3915 struct remote_state *rs = get_remote_state ();
3916 char *p = rs->buf;
3917
3918 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3919 p += strlen (p);
3920 p += hexnumstr (p, addr);
3921 putpkt (rs->buf);
3922 getpkt (&rs->buf, &rs->buf_size, 0);
3923 p = rs->buf;
3924
3925 if (*p == 'E')
3926 error (_("Remote failure reply: %s"), p);
3927
3928 if (*p++ == 'm')
3929 {
3930 parse_static_tracepoint_marker_definition (p, NULL, marker);
3931 return true;
3932 }
3933
3934 return false;
3935 }
3936
3937 std::vector<static_tracepoint_marker>
3938 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3939 {
3940 struct remote_state *rs = get_remote_state ();
3941 std::vector<static_tracepoint_marker> markers;
3942 const char *p;
3943 static_tracepoint_marker marker;
3944
3945 /* Ask for a first packet of static tracepoint marker
3946 definition. */
3947 putpkt ("qTfSTM");
3948 getpkt (&rs->buf, &rs->buf_size, 0);
3949 p = rs->buf;
3950 if (*p == 'E')
3951 error (_("Remote failure reply: %s"), p);
3952
3953 while (*p++ == 'm')
3954 {
3955 do
3956 {
3957 parse_static_tracepoint_marker_definition (p, &p, &marker);
3958
3959 if (strid == NULL || marker.str_id == strid)
3960 markers.push_back (std::move (marker));
3961 }
3962 while (*p++ == ','); /* comma-separated list */
3963 /* Ask for another packet of static tracepoint definition. */
3964 putpkt ("qTsSTM");
3965 getpkt (&rs->buf, &rs->buf_size, 0);
3966 p = rs->buf;
3967 }
3968
3969 return markers;
3970 }
3971
3972 \f
3973 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3974
3975 ptid_t
3976 remote_target::get_ada_task_ptid (long lwp, long thread)
3977 {
3978 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3979 }
3980 \f
3981
3982 /* Restart the remote side; this is an extended protocol operation. */
3983
3984 void
3985 remote_target::extended_remote_restart ()
3986 {
3987 struct remote_state *rs = get_remote_state ();
3988
3989 /* Send the restart command; for reasons I don't understand the
3990 remote side really expects a number after the "R". */
3991 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3992 putpkt (rs->buf);
3993
3994 remote_fileio_reset ();
3995 }
3996 \f
3997 /* Clean up connection to a remote debugger. */
3998
3999 void
4000 remote_target::close ()
4001 {
4002 /* Make sure we leave stdin registered in the event loop. */
4003 terminal_ours ();
4004
4005 /* We don't have a connection to the remote stub anymore. Get rid
4006 of all the inferiors and their threads we were controlling.
4007 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4008 will be unable to find the thread corresponding to (pid, 0, 0). */
4009 inferior_ptid = null_ptid;
4010 discard_all_inferiors ();
4011
4012 trace_reset_local_state ();
4013
4014 delete this;
4015 }
4016
4017 remote_target::~remote_target ()
4018 {
4019 struct remote_state *rs = get_remote_state ();
4020
4021 /* Check for NULL because we may get here with a partially
4022 constructed target/connection. */
4023 if (rs->remote_desc == nullptr)
4024 return;
4025
4026 serial_close (rs->remote_desc);
4027
4028 /* We are destroying the remote target, so we should discard
4029 everything of this target. */
4030 discard_pending_stop_replies_in_queue ();
4031
4032 if (rs->remote_async_inferior_event_token)
4033 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4034
4035 remote_notif_state_xfree (rs->notif_state);
4036 }
4037
4038 /* Query the remote side for the text, data and bss offsets. */
4039
4040 void
4041 remote_target::get_offsets ()
4042 {
4043 struct remote_state *rs = get_remote_state ();
4044 char *buf;
4045 char *ptr;
4046 int lose, num_segments = 0, do_sections, do_segments;
4047 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4048 struct section_offsets *offs;
4049 struct symfile_segment_data *data;
4050
4051 if (symfile_objfile == NULL)
4052 return;
4053
4054 putpkt ("qOffsets");
4055 getpkt (&rs->buf, &rs->buf_size, 0);
4056 buf = rs->buf;
4057
4058 if (buf[0] == '\000')
4059 return; /* Return silently. Stub doesn't support
4060 this command. */
4061 if (buf[0] == 'E')
4062 {
4063 warning (_("Remote failure reply: %s"), buf);
4064 return;
4065 }
4066
4067 /* Pick up each field in turn. This used to be done with scanf, but
4068 scanf will make trouble if CORE_ADDR size doesn't match
4069 conversion directives correctly. The following code will work
4070 with any size of CORE_ADDR. */
4071 text_addr = data_addr = bss_addr = 0;
4072 ptr = buf;
4073 lose = 0;
4074
4075 if (startswith (ptr, "Text="))
4076 {
4077 ptr += 5;
4078 /* Don't use strtol, could lose on big values. */
4079 while (*ptr && *ptr != ';')
4080 text_addr = (text_addr << 4) + fromhex (*ptr++);
4081
4082 if (startswith (ptr, ";Data="))
4083 {
4084 ptr += 6;
4085 while (*ptr && *ptr != ';')
4086 data_addr = (data_addr << 4) + fromhex (*ptr++);
4087 }
4088 else
4089 lose = 1;
4090
4091 if (!lose && startswith (ptr, ";Bss="))
4092 {
4093 ptr += 5;
4094 while (*ptr && *ptr != ';')
4095 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4096
4097 if (bss_addr != data_addr)
4098 warning (_("Target reported unsupported offsets: %s"), buf);
4099 }
4100 else
4101 lose = 1;
4102 }
4103 else if (startswith (ptr, "TextSeg="))
4104 {
4105 ptr += 8;
4106 /* Don't use strtol, could lose on big values. */
4107 while (*ptr && *ptr != ';')
4108 text_addr = (text_addr << 4) + fromhex (*ptr++);
4109 num_segments = 1;
4110
4111 if (startswith (ptr, ";DataSeg="))
4112 {
4113 ptr += 9;
4114 while (*ptr && *ptr != ';')
4115 data_addr = (data_addr << 4) + fromhex (*ptr++);
4116 num_segments++;
4117 }
4118 }
4119 else
4120 lose = 1;
4121
4122 if (lose)
4123 error (_("Malformed response to offset query, %s"), buf);
4124 else if (*ptr != '\0')
4125 warning (_("Target reported unsupported offsets: %s"), buf);
4126
4127 offs = ((struct section_offsets *)
4128 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
4129 memcpy (offs, symfile_objfile->section_offsets,
4130 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
4131
4132 data = get_symfile_segment_data (symfile_objfile->obfd);
4133 do_segments = (data != NULL);
4134 do_sections = num_segments == 0;
4135
4136 if (num_segments > 0)
4137 {
4138 segments[0] = text_addr;
4139 segments[1] = data_addr;
4140 }
4141 /* If we have two segments, we can still try to relocate everything
4142 by assuming that the .text and .data offsets apply to the whole
4143 text and data segments. Convert the offsets given in the packet
4144 to base addresses for symfile_map_offsets_to_segments. */
4145 else if (data && data->num_segments == 2)
4146 {
4147 segments[0] = data->segment_bases[0] + text_addr;
4148 segments[1] = data->segment_bases[1] + data_addr;
4149 num_segments = 2;
4150 }
4151 /* If the object file has only one segment, assume that it is text
4152 rather than data; main programs with no writable data are rare,
4153 but programs with no code are useless. Of course the code might
4154 have ended up in the data segment... to detect that we would need
4155 the permissions here. */
4156 else if (data && data->num_segments == 1)
4157 {
4158 segments[0] = data->segment_bases[0] + text_addr;
4159 num_segments = 1;
4160 }
4161 /* There's no way to relocate by segment. */
4162 else
4163 do_segments = 0;
4164
4165 if (do_segments)
4166 {
4167 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4168 offs, num_segments, segments);
4169
4170 if (ret == 0 && !do_sections)
4171 error (_("Can not handle qOffsets TextSeg "
4172 "response with this symbol file"));
4173
4174 if (ret > 0)
4175 do_sections = 0;
4176 }
4177
4178 if (data)
4179 free_symfile_segment_data (data);
4180
4181 if (do_sections)
4182 {
4183 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4184
4185 /* This is a temporary kludge to force data and bss to use the
4186 same offsets because that's what nlmconv does now. The real
4187 solution requires changes to the stub and remote.c that I
4188 don't have time to do right now. */
4189
4190 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4191 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4192 }
4193
4194 objfile_relocate (symfile_objfile, offs);
4195 }
4196
4197 /* Send interrupt_sequence to remote target. */
4198
4199 void
4200 remote_target::send_interrupt_sequence ()
4201 {
4202 struct remote_state *rs = get_remote_state ();
4203
4204 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4205 remote_serial_write ("\x03", 1);
4206 else if (interrupt_sequence_mode == interrupt_sequence_break)
4207 serial_send_break (rs->remote_desc);
4208 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4209 {
4210 serial_send_break (rs->remote_desc);
4211 remote_serial_write ("g", 1);
4212 }
4213 else
4214 internal_error (__FILE__, __LINE__,
4215 _("Invalid value for interrupt_sequence_mode: %s."),
4216 interrupt_sequence_mode);
4217 }
4218
4219
4220 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4221 and extract the PTID. Returns NULL_PTID if not found. */
4222
4223 static ptid_t
4224 stop_reply_extract_thread (char *stop_reply)
4225 {
4226 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4227 {
4228 const char *p;
4229
4230 /* Txx r:val ; r:val (...) */
4231 p = &stop_reply[3];
4232
4233 /* Look for "register" named "thread". */
4234 while (*p != '\0')
4235 {
4236 const char *p1;
4237
4238 p1 = strchr (p, ':');
4239 if (p1 == NULL)
4240 return null_ptid;
4241
4242 if (strncmp (p, "thread", p1 - p) == 0)
4243 return read_ptid (++p1, &p);
4244
4245 p1 = strchr (p, ';');
4246 if (p1 == NULL)
4247 return null_ptid;
4248 p1++;
4249
4250 p = p1;
4251 }
4252 }
4253
4254 return null_ptid;
4255 }
4256
4257 /* Determine the remote side's current thread. If we have a stop
4258 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4259 "thread" register we can extract the current thread from. If not,
4260 ask the remote which is the current thread with qC. The former
4261 method avoids a roundtrip. */
4262
4263 ptid_t
4264 remote_target::get_current_thread (char *wait_status)
4265 {
4266 ptid_t ptid = null_ptid;
4267
4268 /* Note we don't use remote_parse_stop_reply as that makes use of
4269 the target architecture, which we haven't yet fully determined at
4270 this point. */
4271 if (wait_status != NULL)
4272 ptid = stop_reply_extract_thread (wait_status);
4273 if (ptid_equal (ptid, null_ptid))
4274 ptid = remote_current_thread (inferior_ptid);
4275
4276 return ptid;
4277 }
4278
4279 /* Query the remote target for which is the current thread/process,
4280 add it to our tables, and update INFERIOR_PTID. The caller is
4281 responsible for setting the state such that the remote end is ready
4282 to return the current thread.
4283
4284 This function is called after handling the '?' or 'vRun' packets,
4285 whose response is a stop reply from which we can also try
4286 extracting the thread. If the target doesn't support the explicit
4287 qC query, we infer the current thread from that stop reply, passed
4288 in in WAIT_STATUS, which may be NULL. */
4289
4290 void
4291 remote_target::add_current_inferior_and_thread (char *wait_status)
4292 {
4293 struct remote_state *rs = get_remote_state ();
4294 int fake_pid_p = 0;
4295
4296 inferior_ptid = null_ptid;
4297
4298 /* Now, if we have thread information, update inferior_ptid. */
4299 ptid_t curr_ptid = get_current_thread (wait_status);
4300
4301 if (curr_ptid != null_ptid)
4302 {
4303 if (!remote_multi_process_p (rs))
4304 fake_pid_p = 1;
4305 }
4306 else
4307 {
4308 /* Without this, some commands which require an active target
4309 (such as kill) won't work. This variable serves (at least)
4310 double duty as both the pid of the target process (if it has
4311 such), and as a flag indicating that a target is active. */
4312 curr_ptid = magic_null_ptid;
4313 fake_pid_p = 1;
4314 }
4315
4316 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
4317
4318 /* Add the main thread and switch to it. Don't try reading
4319 registers yet, since we haven't fetched the target description
4320 yet. */
4321 thread_info *tp = add_thread_silent (curr_ptid);
4322 switch_to_thread_no_regs (tp);
4323 }
4324
4325 /* Print info about a thread that was found already stopped on
4326 connection. */
4327
4328 static void
4329 print_one_stopped_thread (struct thread_info *thread)
4330 {
4331 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4332
4333 switch_to_thread (thread);
4334 thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
4335 set_current_sal_from_frame (get_current_frame ());
4336
4337 thread->suspend.waitstatus_pending_p = 0;
4338
4339 if (ws->kind == TARGET_WAITKIND_STOPPED)
4340 {
4341 enum gdb_signal sig = ws->value.sig;
4342
4343 if (signal_print_state (sig))
4344 gdb::observers::signal_received.notify (sig);
4345 }
4346 gdb::observers::normal_stop.notify (NULL, 1);
4347 }
4348
4349 /* Process all initial stop replies the remote side sent in response
4350 to the ? packet. These indicate threads that were already stopped
4351 on initial connection. We mark these threads as stopped and print
4352 their current frame before giving the user the prompt. */
4353
4354 void
4355 remote_target::process_initial_stop_replies (int from_tty)
4356 {
4357 int pending_stop_replies = stop_reply_queue_length ();
4358 struct inferior *inf;
4359 struct thread_info *thread;
4360 struct thread_info *selected = NULL;
4361 struct thread_info *lowest_stopped = NULL;
4362 struct thread_info *first = NULL;
4363
4364 /* Consume the initial pending events. */
4365 while (pending_stop_replies-- > 0)
4366 {
4367 ptid_t waiton_ptid = minus_one_ptid;
4368 ptid_t event_ptid;
4369 struct target_waitstatus ws;
4370 int ignore_event = 0;
4371 struct thread_info *thread;
4372
4373 memset (&ws, 0, sizeof (ws));
4374 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4375 if (remote_debug)
4376 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4377
4378 switch (ws.kind)
4379 {
4380 case TARGET_WAITKIND_IGNORE:
4381 case TARGET_WAITKIND_NO_RESUMED:
4382 case TARGET_WAITKIND_SIGNALLED:
4383 case TARGET_WAITKIND_EXITED:
4384 /* We shouldn't see these, but if we do, just ignore. */
4385 if (remote_debug)
4386 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4387 ignore_event = 1;
4388 break;
4389
4390 case TARGET_WAITKIND_EXECD:
4391 xfree (ws.value.execd_pathname);
4392 break;
4393 default:
4394 break;
4395 }
4396
4397 if (ignore_event)
4398 continue;
4399
4400 thread = find_thread_ptid (event_ptid);
4401
4402 if (ws.kind == TARGET_WAITKIND_STOPPED)
4403 {
4404 enum gdb_signal sig = ws.value.sig;
4405
4406 /* Stubs traditionally report SIGTRAP as initial signal,
4407 instead of signal 0. Suppress it. */
4408 if (sig == GDB_SIGNAL_TRAP)
4409 sig = GDB_SIGNAL_0;
4410 thread->suspend.stop_signal = sig;
4411 ws.value.sig = sig;
4412 }
4413
4414 thread->suspend.waitstatus = ws;
4415
4416 if (ws.kind != TARGET_WAITKIND_STOPPED
4417 || ws.value.sig != GDB_SIGNAL_0)
4418 thread->suspend.waitstatus_pending_p = 1;
4419
4420 set_executing (event_ptid, 0);
4421 set_running (event_ptid, 0);
4422 get_remote_thread_info (thread)->vcont_resumed = 0;
4423 }
4424
4425 /* "Notice" the new inferiors before anything related to
4426 registers/memory. */
4427 ALL_INFERIORS (inf)
4428 {
4429 if (inf->pid == 0)
4430 continue;
4431
4432 inf->needs_setup = 1;
4433
4434 if (non_stop)
4435 {
4436 thread = any_live_thread_of_inferior (inf);
4437 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4438 from_tty);
4439 }
4440 }
4441
4442 /* If all-stop on top of non-stop, pause all threads. Note this
4443 records the threads' stop pc, so must be done after "noticing"
4444 the inferiors. */
4445 if (!non_stop)
4446 {
4447 stop_all_threads ();
4448
4449 /* If all threads of an inferior were already stopped, we
4450 haven't setup the inferior yet. */
4451 ALL_INFERIORS (inf)
4452 {
4453 if (inf->pid == 0)
4454 continue;
4455
4456 if (inf->needs_setup)
4457 {
4458 thread = any_live_thread_of_inferior (inf);
4459 switch_to_thread_no_regs (thread);
4460 setup_inferior (0);
4461 }
4462 }
4463 }
4464
4465 /* Now go over all threads that are stopped, and print their current
4466 frame. If all-stop, then if there's a signalled thread, pick
4467 that as current. */
4468 ALL_NON_EXITED_THREADS (thread)
4469 {
4470 if (first == NULL)
4471 first = thread;
4472
4473 if (!non_stop)
4474 thread->set_running (false);
4475 else if (thread->state != THREAD_STOPPED)
4476 continue;
4477
4478 if (selected == NULL
4479 && thread->suspend.waitstatus_pending_p)
4480 selected = thread;
4481
4482 if (lowest_stopped == NULL
4483 || thread->inf->num < lowest_stopped->inf->num
4484 || thread->per_inf_num < lowest_stopped->per_inf_num)
4485 lowest_stopped = thread;
4486
4487 if (non_stop)
4488 print_one_stopped_thread (thread);
4489 }
4490
4491 /* In all-stop, we only print the status of one thread, and leave
4492 others with their status pending. */
4493 if (!non_stop)
4494 {
4495 thread = selected;
4496 if (thread == NULL)
4497 thread = lowest_stopped;
4498 if (thread == NULL)
4499 thread = first;
4500
4501 print_one_stopped_thread (thread);
4502 }
4503
4504 /* For "info program". */
4505 thread = inferior_thread ();
4506 if (thread->state == THREAD_STOPPED)
4507 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4508 }
4509
4510 /* Start the remote connection and sync state. */
4511
4512 void
4513 remote_target::start_remote (int from_tty, int extended_p)
4514 {
4515 struct remote_state *rs = get_remote_state ();
4516 struct packet_config *noack_config;
4517 char *wait_status = NULL;
4518
4519 /* Signal other parts that we're going through the initial setup,
4520 and so things may not be stable yet. E.g., we don't try to
4521 install tracepoints until we've relocated symbols. Also, a
4522 Ctrl-C before we're connected and synced up can't interrupt the
4523 target. Instead, it offers to drop the (potentially wedged)
4524 connection. */
4525 rs->starting_up = 1;
4526
4527 QUIT;
4528
4529 if (interrupt_on_connect)
4530 send_interrupt_sequence ();
4531
4532 /* Ack any packet which the remote side has already sent. */
4533 remote_serial_write ("+", 1);
4534
4535 /* The first packet we send to the target is the optional "supported
4536 packets" request. If the target can answer this, it will tell us
4537 which later probes to skip. */
4538 remote_query_supported ();
4539
4540 /* If the stub wants to get a QAllow, compose one and send it. */
4541 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4542 set_permissions ();
4543
4544 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4545 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4546 as a reply to known packet. For packet "vFile:setfs:" it is an
4547 invalid reply and GDB would return error in
4548 remote_hostio_set_filesystem, making remote files access impossible.
4549 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4550 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4551 {
4552 const char v_mustreplyempty[] = "vMustReplyEmpty";
4553
4554 putpkt (v_mustreplyempty);
4555 getpkt (&rs->buf, &rs->buf_size, 0);
4556 if (strcmp (rs->buf, "OK") == 0)
4557 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4558 else if (strcmp (rs->buf, "") != 0)
4559 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4560 rs->buf);
4561 }
4562
4563 /* Next, we possibly activate noack mode.
4564
4565 If the QStartNoAckMode packet configuration is set to AUTO,
4566 enable noack mode if the stub reported a wish for it with
4567 qSupported.
4568
4569 If set to TRUE, then enable noack mode even if the stub didn't
4570 report it in qSupported. If the stub doesn't reply OK, the
4571 session ends with an error.
4572
4573 If FALSE, then don't activate noack mode, regardless of what the
4574 stub claimed should be the default with qSupported. */
4575
4576 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4577 if (packet_config_support (noack_config) != PACKET_DISABLE)
4578 {
4579 putpkt ("QStartNoAckMode");
4580 getpkt (&rs->buf, &rs->buf_size, 0);
4581 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4582 rs->noack_mode = 1;
4583 }
4584
4585 if (extended_p)
4586 {
4587 /* Tell the remote that we are using the extended protocol. */
4588 putpkt ("!");
4589 getpkt (&rs->buf, &rs->buf_size, 0);
4590 }
4591
4592 /* Let the target know which signals it is allowed to pass down to
4593 the program. */
4594 update_signals_program_target ();
4595
4596 /* Next, if the target can specify a description, read it. We do
4597 this before anything involving memory or registers. */
4598 target_find_description ();
4599
4600 /* Next, now that we know something about the target, update the
4601 address spaces in the program spaces. */
4602 update_address_spaces ();
4603
4604 /* On OSs where the list of libraries is global to all
4605 processes, we fetch them early. */
4606 if (gdbarch_has_global_solist (target_gdbarch ()))
4607 solib_add (NULL, from_tty, auto_solib_add);
4608
4609 if (target_is_non_stop_p ())
4610 {
4611 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4612 error (_("Non-stop mode requested, but remote "
4613 "does not support non-stop"));
4614
4615 putpkt ("QNonStop:1");
4616 getpkt (&rs->buf, &rs->buf_size, 0);
4617
4618 if (strcmp (rs->buf, "OK") != 0)
4619 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4620
4621 /* Find about threads and processes the stub is already
4622 controlling. We default to adding them in the running state.
4623 The '?' query below will then tell us about which threads are
4624 stopped. */
4625 this->update_thread_list ();
4626 }
4627 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4628 {
4629 /* Don't assume that the stub can operate in all-stop mode.
4630 Request it explicitly. */
4631 putpkt ("QNonStop:0");
4632 getpkt (&rs->buf, &rs->buf_size, 0);
4633
4634 if (strcmp (rs->buf, "OK") != 0)
4635 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4636 }
4637
4638 /* Upload TSVs regardless of whether the target is running or not. The
4639 remote stub, such as GDBserver, may have some predefined or builtin
4640 TSVs, even if the target is not running. */
4641 if (get_trace_status (current_trace_status ()) != -1)
4642 {
4643 struct uploaded_tsv *uploaded_tsvs = NULL;
4644
4645 upload_trace_state_variables (&uploaded_tsvs);
4646 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4647 }
4648
4649 /* Check whether the target is running now. */
4650 putpkt ("?");
4651 getpkt (&rs->buf, &rs->buf_size, 0);
4652
4653 if (!target_is_non_stop_p ())
4654 {
4655 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4656 {
4657 if (!extended_p)
4658 error (_("The target is not running (try extended-remote?)"));
4659
4660 /* We're connected, but not running. Drop out before we
4661 call start_remote. */
4662 rs->starting_up = 0;
4663 return;
4664 }
4665 else
4666 {
4667 /* Save the reply for later. */
4668 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4669 strcpy (wait_status, rs->buf);
4670 }
4671
4672 /* Fetch thread list. */
4673 target_update_thread_list ();
4674
4675 /* Let the stub know that we want it to return the thread. */
4676 set_continue_thread (minus_one_ptid);
4677
4678 if (thread_count () == 0)
4679 {
4680 /* Target has no concept of threads at all. GDB treats
4681 non-threaded target as single-threaded; add a main
4682 thread. */
4683 add_current_inferior_and_thread (wait_status);
4684 }
4685 else
4686 {
4687 /* We have thread information; select the thread the target
4688 says should be current. If we're reconnecting to a
4689 multi-threaded program, this will ideally be the thread
4690 that last reported an event before GDB disconnected. */
4691 inferior_ptid = get_current_thread (wait_status);
4692 if (ptid_equal (inferior_ptid, null_ptid))
4693 {
4694 /* Odd... The target was able to list threads, but not
4695 tell us which thread was current (no "thread"
4696 register in T stop reply?). Just pick the first
4697 thread in the thread list then. */
4698
4699 if (remote_debug)
4700 fprintf_unfiltered (gdb_stdlog,
4701 "warning: couldn't determine remote "
4702 "current thread; picking first in list.\n");
4703
4704 inferior_ptid = thread_list->ptid;
4705 }
4706 }
4707
4708 /* init_wait_for_inferior should be called before get_offsets in order
4709 to manage `inserted' flag in bp loc in a correct state.
4710 breakpoint_init_inferior, called from init_wait_for_inferior, set
4711 `inserted' flag to 0, while before breakpoint_re_set, called from
4712 start_remote, set `inserted' flag to 1. In the initialization of
4713 inferior, breakpoint_init_inferior should be called first, and then
4714 breakpoint_re_set can be called. If this order is broken, state of
4715 `inserted' flag is wrong, and cause some problems on breakpoint
4716 manipulation. */
4717 init_wait_for_inferior ();
4718
4719 get_offsets (); /* Get text, data & bss offsets. */
4720
4721 /* If we could not find a description using qXfer, and we know
4722 how to do it some other way, try again. This is not
4723 supported for non-stop; it could be, but it is tricky if
4724 there are no stopped threads when we connect. */
4725 if (remote_read_description_p (this)
4726 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4727 {
4728 target_clear_description ();
4729 target_find_description ();
4730 }
4731
4732 /* Use the previously fetched status. */
4733 gdb_assert (wait_status != NULL);
4734 strcpy (rs->buf, wait_status);
4735 rs->cached_wait_status = 1;
4736
4737 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4738 }
4739 else
4740 {
4741 /* Clear WFI global state. Do this before finding about new
4742 threads and inferiors, and setting the current inferior.
4743 Otherwise we would clear the proceed status of the current
4744 inferior when we want its stop_soon state to be preserved
4745 (see notice_new_inferior). */
4746 init_wait_for_inferior ();
4747
4748 /* In non-stop, we will either get an "OK", meaning that there
4749 are no stopped threads at this time; or, a regular stop
4750 reply. In the latter case, there may be more than one thread
4751 stopped --- we pull them all out using the vStopped
4752 mechanism. */
4753 if (strcmp (rs->buf, "OK") != 0)
4754 {
4755 struct notif_client *notif = &notif_client_stop;
4756
4757 /* remote_notif_get_pending_replies acks this one, and gets
4758 the rest out. */
4759 rs->notif_state->pending_event[notif_client_stop.id]
4760 = remote_notif_parse (this, notif, rs->buf);
4761 remote_notif_get_pending_events (notif);
4762 }
4763
4764 if (thread_count () == 0)
4765 {
4766 if (!extended_p)
4767 error (_("The target is not running (try extended-remote?)"));
4768
4769 /* We're connected, but not running. Drop out before we
4770 call start_remote. */
4771 rs->starting_up = 0;
4772 return;
4773 }
4774
4775 /* In non-stop mode, any cached wait status will be stored in
4776 the stop reply queue. */
4777 gdb_assert (wait_status == NULL);
4778
4779 /* Report all signals during attach/startup. */
4780 pass_signals (0, NULL);
4781
4782 /* If there are already stopped threads, mark them stopped and
4783 report their stops before giving the prompt to the user. */
4784 process_initial_stop_replies (from_tty);
4785
4786 if (target_can_async_p ())
4787 target_async (1);
4788 }
4789
4790 /* If we connected to a live target, do some additional setup. */
4791 if (target_has_execution)
4792 {
4793 if (symfile_objfile) /* No use without a symbol-file. */
4794 remote_check_symbols ();
4795 }
4796
4797 /* Possibly the target has been engaged in a trace run started
4798 previously; find out where things are at. */
4799 if (get_trace_status (current_trace_status ()) != -1)
4800 {
4801 struct uploaded_tp *uploaded_tps = NULL;
4802
4803 if (current_trace_status ()->running)
4804 printf_filtered (_("Trace is already running on the target.\n"));
4805
4806 upload_tracepoints (&uploaded_tps);
4807
4808 merge_uploaded_tracepoints (&uploaded_tps);
4809 }
4810
4811 /* Possibly the target has been engaged in a btrace record started
4812 previously; find out where things are at. */
4813 remote_btrace_maybe_reopen ();
4814
4815 /* The thread and inferior lists are now synchronized with the
4816 target, our symbols have been relocated, and we're merged the
4817 target's tracepoints with ours. We're done with basic start
4818 up. */
4819 rs->starting_up = 0;
4820
4821 /* Maybe breakpoints are global and need to be inserted now. */
4822 if (breakpoints_should_be_inserted_now ())
4823 insert_breakpoints ();
4824 }
4825
4826 /* Open a connection to a remote debugger.
4827 NAME is the filename used for communication. */
4828
4829 void
4830 remote_target::open (const char *name, int from_tty)
4831 {
4832 open_1 (name, from_tty, 0);
4833 }
4834
4835 /* Open a connection to a remote debugger using the extended
4836 remote gdb protocol. NAME is the filename used for communication. */
4837
4838 void
4839 extended_remote_target::open (const char *name, int from_tty)
4840 {
4841 open_1 (name, from_tty, 1 /*extended_p */);
4842 }
4843
4844 /* Reset all packets back to "unknown support". Called when opening a
4845 new connection to a remote target. */
4846
4847 static void
4848 reset_all_packet_configs_support (void)
4849 {
4850 int i;
4851
4852 for (i = 0; i < PACKET_MAX; i++)
4853 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4854 }
4855
4856 /* Initialize all packet configs. */
4857
4858 static void
4859 init_all_packet_configs (void)
4860 {
4861 int i;
4862
4863 for (i = 0; i < PACKET_MAX; i++)
4864 {
4865 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4866 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4867 }
4868 }
4869
4870 /* Symbol look-up. */
4871
4872 void
4873 remote_target::remote_check_symbols ()
4874 {
4875 char *msg, *reply, *tmp;
4876 int end;
4877 long reply_size;
4878 struct cleanup *old_chain;
4879
4880 /* The remote side has no concept of inferiors that aren't running
4881 yet, it only knows about running processes. If we're connected
4882 but our current inferior is not running, we should not invite the
4883 remote target to request symbol lookups related to its
4884 (unrelated) current process. */
4885 if (!target_has_execution)
4886 return;
4887
4888 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4889 return;
4890
4891 /* Make sure the remote is pointing at the right process. Note
4892 there's no way to select "no process". */
4893 set_general_process ();
4894
4895 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4896 because we need both at the same time. */
4897 msg = (char *) xmalloc (get_remote_packet_size ());
4898 old_chain = make_cleanup (xfree, msg);
4899 reply = (char *) xmalloc (get_remote_packet_size ());
4900 make_cleanup (free_current_contents, &reply);
4901 reply_size = get_remote_packet_size ();
4902
4903 /* Invite target to request symbol lookups. */
4904
4905 putpkt ("qSymbol::");
4906 getpkt (&reply, &reply_size, 0);
4907 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4908
4909 while (startswith (reply, "qSymbol:"))
4910 {
4911 struct bound_minimal_symbol sym;
4912
4913 tmp = &reply[8];
4914 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4915 msg[end] = '\0';
4916 sym = lookup_minimal_symbol (msg, NULL, NULL);
4917 if (sym.minsym == NULL)
4918 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4919 else
4920 {
4921 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4922 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4923
4924 /* If this is a function address, return the start of code
4925 instead of any data function descriptor. */
4926 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4927 sym_addr,
4928 current_top_target ());
4929
4930 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4931 phex_nz (sym_addr, addr_size), &reply[8]);
4932 }
4933
4934 putpkt (msg);
4935 getpkt (&reply, &reply_size, 0);
4936 }
4937
4938 do_cleanups (old_chain);
4939 }
4940
4941 static struct serial *
4942 remote_serial_open (const char *name)
4943 {
4944 static int udp_warning = 0;
4945
4946 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4947 of in ser-tcp.c, because it is the remote protocol assuming that the
4948 serial connection is reliable and not the serial connection promising
4949 to be. */
4950 if (!udp_warning && startswith (name, "udp:"))
4951 {
4952 warning (_("The remote protocol may be unreliable over UDP.\n"
4953 "Some events may be lost, rendering further debugging "
4954 "impossible."));
4955 udp_warning = 1;
4956 }
4957
4958 return serial_open (name);
4959 }
4960
4961 /* Inform the target of our permission settings. The permission flags
4962 work without this, but if the target knows the settings, it can do
4963 a couple things. First, it can add its own check, to catch cases
4964 that somehow manage to get by the permissions checks in target
4965 methods. Second, if the target is wired to disallow particular
4966 settings (for instance, a system in the field that is not set up to
4967 be able to stop at a breakpoint), it can object to any unavailable
4968 permissions. */
4969
4970 void
4971 remote_target::set_permissions ()
4972 {
4973 struct remote_state *rs = get_remote_state ();
4974
4975 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4976 "WriteReg:%x;WriteMem:%x;"
4977 "InsertBreak:%x;InsertTrace:%x;"
4978 "InsertFastTrace:%x;Stop:%x",
4979 may_write_registers, may_write_memory,
4980 may_insert_breakpoints, may_insert_tracepoints,
4981 may_insert_fast_tracepoints, may_stop);
4982 putpkt (rs->buf);
4983 getpkt (&rs->buf, &rs->buf_size, 0);
4984
4985 /* If the target didn't like the packet, warn the user. Do not try
4986 to undo the user's settings, that would just be maddening. */
4987 if (strcmp (rs->buf, "OK") != 0)
4988 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4989 }
4990
4991 /* This type describes each known response to the qSupported
4992 packet. */
4993 struct protocol_feature
4994 {
4995 /* The name of this protocol feature. */
4996 const char *name;
4997
4998 /* The default for this protocol feature. */
4999 enum packet_support default_support;
5000
5001 /* The function to call when this feature is reported, or after
5002 qSupported processing if the feature is not supported.
5003 The first argument points to this structure. The second
5004 argument indicates whether the packet requested support be
5005 enabled, disabled, or probed (or the default, if this function
5006 is being called at the end of processing and this feature was
5007 not reported). The third argument may be NULL; if not NULL, it
5008 is a NUL-terminated string taken from the packet following
5009 this feature's name and an equals sign. */
5010 void (*func) (remote_target *remote, const struct protocol_feature *,
5011 enum packet_support, const char *);
5012
5013 /* The corresponding packet for this feature. Only used if
5014 FUNC is remote_supported_packet. */
5015 int packet;
5016 };
5017
5018 static void
5019 remote_supported_packet (remote_target *remote,
5020 const struct protocol_feature *feature,
5021 enum packet_support support,
5022 const char *argument)
5023 {
5024 if (argument)
5025 {
5026 warning (_("Remote qSupported response supplied an unexpected value for"
5027 " \"%s\"."), feature->name);
5028 return;
5029 }
5030
5031 remote_protocol_packets[feature->packet].support = support;
5032 }
5033
5034 void
5035 remote_target::remote_packet_size (const protocol_feature *feature,
5036 enum packet_support support, const char *value)
5037 {
5038 struct remote_state *rs = get_remote_state ();
5039
5040 int packet_size;
5041 char *value_end;
5042
5043 if (support != PACKET_ENABLE)
5044 return;
5045
5046 if (value == NULL || *value == '\0')
5047 {
5048 warning (_("Remote target reported \"%s\" without a size."),
5049 feature->name);
5050 return;
5051 }
5052
5053 errno = 0;
5054 packet_size = strtol (value, &value_end, 16);
5055 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5056 {
5057 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5058 feature->name, value);
5059 return;
5060 }
5061
5062 /* Record the new maximum packet size. */
5063 rs->explicit_packet_size = packet_size;
5064 }
5065
5066 void
5067 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5068 enum packet_support support, const char *value)
5069 {
5070 remote->remote_packet_size (feature, support, value);
5071 }
5072
5073 static const struct protocol_feature remote_protocol_features[] = {
5074 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5075 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5076 PACKET_qXfer_auxv },
5077 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5078 PACKET_qXfer_exec_file },
5079 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5080 PACKET_qXfer_features },
5081 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5082 PACKET_qXfer_libraries },
5083 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5084 PACKET_qXfer_libraries_svr4 },
5085 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5086 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5087 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5088 PACKET_qXfer_memory_map },
5089 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5090 PACKET_qXfer_spu_read },
5091 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5092 PACKET_qXfer_spu_write },
5093 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5094 PACKET_qXfer_osdata },
5095 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5096 PACKET_qXfer_threads },
5097 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5098 PACKET_qXfer_traceframe_info },
5099 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5100 PACKET_QPassSignals },
5101 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5102 PACKET_QCatchSyscalls },
5103 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5104 PACKET_QProgramSignals },
5105 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5106 PACKET_QSetWorkingDir },
5107 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5108 PACKET_QStartupWithShell },
5109 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5110 PACKET_QEnvironmentHexEncoded },
5111 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5112 PACKET_QEnvironmentReset },
5113 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5114 PACKET_QEnvironmentUnset },
5115 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5116 PACKET_QStartNoAckMode },
5117 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5118 PACKET_multiprocess_feature },
5119 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5120 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5121 PACKET_qXfer_siginfo_read },
5122 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5123 PACKET_qXfer_siginfo_write },
5124 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5125 PACKET_ConditionalTracepoints },
5126 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5127 PACKET_ConditionalBreakpoints },
5128 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5129 PACKET_BreakpointCommands },
5130 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5131 PACKET_FastTracepoints },
5132 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5133 PACKET_StaticTracepoints },
5134 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5135 PACKET_InstallInTrace},
5136 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5137 PACKET_DisconnectedTracing_feature },
5138 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5139 PACKET_bc },
5140 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5141 PACKET_bs },
5142 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5143 PACKET_TracepointSource },
5144 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5145 PACKET_QAllow },
5146 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5147 PACKET_EnableDisableTracepoints_feature },
5148 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5149 PACKET_qXfer_fdpic },
5150 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5151 PACKET_qXfer_uib },
5152 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5153 PACKET_QDisableRandomization },
5154 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5155 { "QTBuffer:size", PACKET_DISABLE,
5156 remote_supported_packet, PACKET_QTBuffer_size},
5157 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5158 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5159 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5160 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5161 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5162 PACKET_qXfer_btrace },
5163 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5164 PACKET_qXfer_btrace_conf },
5165 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5166 PACKET_Qbtrace_conf_bts_size },
5167 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5168 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5169 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5170 PACKET_fork_event_feature },
5171 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5172 PACKET_vfork_event_feature },
5173 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5174 PACKET_exec_event_feature },
5175 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5176 PACKET_Qbtrace_conf_pt_size },
5177 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5178 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5179 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5180 };
5181
5182 static char *remote_support_xml;
5183
5184 /* Register string appended to "xmlRegisters=" in qSupported query. */
5185
5186 void
5187 register_remote_support_xml (const char *xml)
5188 {
5189 #if defined(HAVE_LIBEXPAT)
5190 if (remote_support_xml == NULL)
5191 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5192 else
5193 {
5194 char *copy = xstrdup (remote_support_xml + 13);
5195 char *p = strtok (copy, ",");
5196
5197 do
5198 {
5199 if (strcmp (p, xml) == 0)
5200 {
5201 /* already there */
5202 xfree (copy);
5203 return;
5204 }
5205 }
5206 while ((p = strtok (NULL, ",")) != NULL);
5207 xfree (copy);
5208
5209 remote_support_xml = reconcat (remote_support_xml,
5210 remote_support_xml, ",", xml,
5211 (char *) NULL);
5212 }
5213 #endif
5214 }
5215
5216 static void
5217 remote_query_supported_append (std::string *msg, const char *append)
5218 {
5219 if (!msg->empty ())
5220 msg->append (";");
5221 msg->append (append);
5222 }
5223
5224 void
5225 remote_target::remote_query_supported ()
5226 {
5227 struct remote_state *rs = get_remote_state ();
5228 char *next;
5229 int i;
5230 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5231
5232 /* The packet support flags are handled differently for this packet
5233 than for most others. We treat an error, a disabled packet, and
5234 an empty response identically: any features which must be reported
5235 to be used will be automatically disabled. An empty buffer
5236 accomplishes this, since that is also the representation for a list
5237 containing no features. */
5238
5239 rs->buf[0] = 0;
5240 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5241 {
5242 std::string q;
5243
5244 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5245 remote_query_supported_append (&q, "multiprocess+");
5246
5247 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5248 remote_query_supported_append (&q, "swbreak+");
5249 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5250 remote_query_supported_append (&q, "hwbreak+");
5251
5252 remote_query_supported_append (&q, "qRelocInsn+");
5253
5254 if (packet_set_cmd_state (PACKET_fork_event_feature)
5255 != AUTO_BOOLEAN_FALSE)
5256 remote_query_supported_append (&q, "fork-events+");
5257 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5258 != AUTO_BOOLEAN_FALSE)
5259 remote_query_supported_append (&q, "vfork-events+");
5260 if (packet_set_cmd_state (PACKET_exec_event_feature)
5261 != AUTO_BOOLEAN_FALSE)
5262 remote_query_supported_append (&q, "exec-events+");
5263
5264 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5265 remote_query_supported_append (&q, "vContSupported+");
5266
5267 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5268 remote_query_supported_append (&q, "QThreadEvents+");
5269
5270 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5271 remote_query_supported_append (&q, "no-resumed+");
5272
5273 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5274 the qSupported:xmlRegisters=i386 handling. */
5275 if (remote_support_xml != NULL
5276 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5277 remote_query_supported_append (&q, remote_support_xml);
5278
5279 q = "qSupported:" + q;
5280 putpkt (q.c_str ());
5281
5282 getpkt (&rs->buf, &rs->buf_size, 0);
5283
5284 /* If an error occured, warn, but do not return - just reset the
5285 buffer to empty and go on to disable features. */
5286 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5287 == PACKET_ERROR)
5288 {
5289 warning (_("Remote failure reply: %s"), rs->buf);
5290 rs->buf[0] = 0;
5291 }
5292 }
5293
5294 memset (seen, 0, sizeof (seen));
5295
5296 next = rs->buf;
5297 while (*next)
5298 {
5299 enum packet_support is_supported;
5300 char *p, *end, *name_end, *value;
5301
5302 /* First separate out this item from the rest of the packet. If
5303 there's another item after this, we overwrite the separator
5304 (terminated strings are much easier to work with). */
5305 p = next;
5306 end = strchr (p, ';');
5307 if (end == NULL)
5308 {
5309 end = p + strlen (p);
5310 next = end;
5311 }
5312 else
5313 {
5314 *end = '\0';
5315 next = end + 1;
5316
5317 if (end == p)
5318 {
5319 warning (_("empty item in \"qSupported\" response"));
5320 continue;
5321 }
5322 }
5323
5324 name_end = strchr (p, '=');
5325 if (name_end)
5326 {
5327 /* This is a name=value entry. */
5328 is_supported = PACKET_ENABLE;
5329 value = name_end + 1;
5330 *name_end = '\0';
5331 }
5332 else
5333 {
5334 value = NULL;
5335 switch (end[-1])
5336 {
5337 case '+':
5338 is_supported = PACKET_ENABLE;
5339 break;
5340
5341 case '-':
5342 is_supported = PACKET_DISABLE;
5343 break;
5344
5345 case '?':
5346 is_supported = PACKET_SUPPORT_UNKNOWN;
5347 break;
5348
5349 default:
5350 warning (_("unrecognized item \"%s\" "
5351 "in \"qSupported\" response"), p);
5352 continue;
5353 }
5354 end[-1] = '\0';
5355 }
5356
5357 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5358 if (strcmp (remote_protocol_features[i].name, p) == 0)
5359 {
5360 const struct protocol_feature *feature;
5361
5362 seen[i] = 1;
5363 feature = &remote_protocol_features[i];
5364 feature->func (this, feature, is_supported, value);
5365 break;
5366 }
5367 }
5368
5369 /* If we increased the packet size, make sure to increase the global
5370 buffer size also. We delay this until after parsing the entire
5371 qSupported packet, because this is the same buffer we were
5372 parsing. */
5373 if (rs->buf_size < rs->explicit_packet_size)
5374 {
5375 rs->buf_size = rs->explicit_packet_size;
5376 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5377 }
5378
5379 /* Handle the defaults for unmentioned features. */
5380 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5381 if (!seen[i])
5382 {
5383 const struct protocol_feature *feature;
5384
5385 feature = &remote_protocol_features[i];
5386 feature->func (this, feature, feature->default_support, NULL);
5387 }
5388 }
5389
5390 /* Serial QUIT handler for the remote serial descriptor.
5391
5392 Defers handling a Ctrl-C until we're done with the current
5393 command/response packet sequence, unless:
5394
5395 - We're setting up the connection. Don't send a remote interrupt
5396 request, as we're not fully synced yet. Quit immediately
5397 instead.
5398
5399 - The target has been resumed in the foreground
5400 (target_terminal::is_ours is false) with a synchronous resume
5401 packet, and we're blocked waiting for the stop reply, thus a
5402 Ctrl-C should be immediately sent to the target.
5403
5404 - We get a second Ctrl-C while still within the same serial read or
5405 write. In that case the serial is seemingly wedged --- offer to
5406 quit/disconnect.
5407
5408 - We see a second Ctrl-C without target response, after having
5409 previously interrupted the target. In that case the target/stub
5410 is probably wedged --- offer to quit/disconnect.
5411 */
5412
5413 void
5414 remote_target::remote_serial_quit_handler ()
5415 {
5416 struct remote_state *rs = get_remote_state ();
5417
5418 if (check_quit_flag ())
5419 {
5420 /* If we're starting up, we're not fully synced yet. Quit
5421 immediately. */
5422 if (rs->starting_up)
5423 quit ();
5424 else if (rs->got_ctrlc_during_io)
5425 {
5426 if (query (_("The target is not responding to GDB commands.\n"
5427 "Stop debugging it? ")))
5428 remote_unpush_and_throw ();
5429 }
5430 /* If ^C has already been sent once, offer to disconnect. */
5431 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5432 interrupt_query ();
5433 /* All-stop protocol, and blocked waiting for stop reply. Send
5434 an interrupt request. */
5435 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5436 target_interrupt ();
5437 else
5438 rs->got_ctrlc_during_io = 1;
5439 }
5440 }
5441
5442 /* The remote_target that is current while the quit handler is
5443 overridden with remote_serial_quit_handler. */
5444 static remote_target *curr_quit_handler_target;
5445
5446 static void
5447 remote_serial_quit_handler ()
5448 {
5449 curr_quit_handler_target->remote_serial_quit_handler ();
5450 }
5451
5452 /* Remove any of the remote.c targets from target stack. Upper targets depend
5453 on it so remove them first. */
5454
5455 static void
5456 remote_unpush_target (void)
5457 {
5458 pop_all_targets_at_and_above (process_stratum);
5459 }
5460
5461 static void
5462 remote_unpush_and_throw (void)
5463 {
5464 remote_unpush_target ();
5465 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5466 }
5467
5468 void
5469 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5470 {
5471 remote_target *curr_remote = get_current_remote_target ();
5472
5473 if (name == 0)
5474 error (_("To open a remote debug connection, you need to specify what\n"
5475 "serial device is attached to the remote system\n"
5476 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5477
5478 /* If we're connected to a running target, target_preopen will kill it.
5479 Ask this question first, before target_preopen has a chance to kill
5480 anything. */
5481 if (curr_remote != NULL && !have_inferiors ())
5482 {
5483 if (from_tty
5484 && !query (_("Already connected to a remote target. Disconnect? ")))
5485 error (_("Still connected."));
5486 }
5487
5488 /* Here the possibly existing remote target gets unpushed. */
5489 target_preopen (from_tty);
5490
5491 remote_fileio_reset ();
5492 reopen_exec_file ();
5493 reread_symbols ();
5494
5495 remote_target *remote
5496 = (extended_p ? new extended_remote_target () : new remote_target ());
5497 target_ops_up target_holder (remote);
5498
5499 remote_state *rs = remote->get_remote_state ();
5500
5501 /* See FIXME above. */
5502 if (!target_async_permitted)
5503 rs->wait_forever_enabled_p = 1;
5504
5505 rs->remote_desc = remote_serial_open (name);
5506 if (!rs->remote_desc)
5507 perror_with_name (name);
5508
5509 if (baud_rate != -1)
5510 {
5511 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5512 {
5513 /* The requested speed could not be set. Error out to
5514 top level after closing remote_desc. Take care to
5515 set remote_desc to NULL to avoid closing remote_desc
5516 more than once. */
5517 serial_close (rs->remote_desc);
5518 rs->remote_desc = NULL;
5519 perror_with_name (name);
5520 }
5521 }
5522
5523 serial_setparity (rs->remote_desc, serial_parity);
5524 serial_raw (rs->remote_desc);
5525
5526 /* If there is something sitting in the buffer we might take it as a
5527 response to a command, which would be bad. */
5528 serial_flush_input (rs->remote_desc);
5529
5530 if (from_tty)
5531 {
5532 puts_filtered ("Remote debugging using ");
5533 puts_filtered (name);
5534 puts_filtered ("\n");
5535 }
5536
5537 /* Switch to using the remote target now. */
5538 push_target (remote);
5539 /* The target stack owns the target now. */
5540 target_holder.release ();
5541
5542 /* Register extra event sources in the event loop. */
5543 rs->remote_async_inferior_event_token
5544 = create_async_event_handler (remote_async_inferior_event_handler,
5545 remote);
5546 rs->notif_state = remote_notif_state_allocate (remote);
5547
5548 /* Reset the target state; these things will be queried either by
5549 remote_query_supported or as they are needed. */
5550 reset_all_packet_configs_support ();
5551 rs->cached_wait_status = 0;
5552 rs->explicit_packet_size = 0;
5553 rs->noack_mode = 0;
5554 rs->extended = extended_p;
5555 rs->waiting_for_stop_reply = 0;
5556 rs->ctrlc_pending_p = 0;
5557 rs->got_ctrlc_during_io = 0;
5558
5559 rs->general_thread = not_sent_ptid;
5560 rs->continue_thread = not_sent_ptid;
5561 rs->remote_traceframe_number = -1;
5562
5563 rs->last_resume_exec_dir = EXEC_FORWARD;
5564
5565 /* Probe for ability to use "ThreadInfo" query, as required. */
5566 rs->use_threadinfo_query = 1;
5567 rs->use_threadextra_query = 1;
5568
5569 rs->readahead_cache.invalidate ();
5570
5571 if (target_async_permitted)
5572 {
5573 /* FIXME: cagney/1999-09-23: During the initial connection it is
5574 assumed that the target is already ready and able to respond to
5575 requests. Unfortunately remote_start_remote() eventually calls
5576 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5577 around this. Eventually a mechanism that allows
5578 wait_for_inferior() to expect/get timeouts will be
5579 implemented. */
5580 rs->wait_forever_enabled_p = 0;
5581 }
5582
5583 /* First delete any symbols previously loaded from shared libraries. */
5584 no_shared_libraries (NULL, 0);
5585
5586 /* Start afresh. */
5587 init_thread_list ();
5588
5589 /* Start the remote connection. If error() or QUIT, discard this
5590 target (we'd otherwise be in an inconsistent state) and then
5591 propogate the error on up the exception chain. This ensures that
5592 the caller doesn't stumble along blindly assuming that the
5593 function succeeded. The CLI doesn't have this problem but other
5594 UI's, such as MI do.
5595
5596 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5597 this function should return an error indication letting the
5598 caller restore the previous state. Unfortunately the command
5599 ``target remote'' is directly wired to this function making that
5600 impossible. On a positive note, the CLI side of this problem has
5601 been fixed - the function set_cmd_context() makes it possible for
5602 all the ``target ....'' commands to share a common callback
5603 function. See cli-dump.c. */
5604 {
5605
5606 TRY
5607 {
5608 remote->start_remote (from_tty, extended_p);
5609 }
5610 CATCH (ex, RETURN_MASK_ALL)
5611 {
5612 /* Pop the partially set up target - unless something else did
5613 already before throwing the exception. */
5614 if (ex.error != TARGET_CLOSE_ERROR)
5615 remote_unpush_target ();
5616 throw_exception (ex);
5617 }
5618 END_CATCH
5619 }
5620
5621 remote_btrace_reset (rs);
5622
5623 if (target_async_permitted)
5624 rs->wait_forever_enabled_p = 1;
5625 }
5626
5627 /* Detach the specified process. */
5628
5629 void
5630 remote_target::remote_detach_pid (int pid)
5631 {
5632 struct remote_state *rs = get_remote_state ();
5633
5634 if (remote_multi_process_p (rs))
5635 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5636 else
5637 strcpy (rs->buf, "D");
5638
5639 putpkt (rs->buf);
5640 getpkt (&rs->buf, &rs->buf_size, 0);
5641
5642 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5643 ;
5644 else if (rs->buf[0] == '\0')
5645 error (_("Remote doesn't know how to detach"));
5646 else
5647 error (_("Can't detach process."));
5648 }
5649
5650 /* This detaches a program to which we previously attached, using
5651 inferior_ptid to identify the process. After this is done, GDB
5652 can be used to debug some other program. We better not have left
5653 any breakpoints in the target program or it'll die when it hits
5654 one. */
5655
5656 void
5657 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5658 {
5659 int pid = ptid_get_pid (inferior_ptid);
5660 struct remote_state *rs = get_remote_state ();
5661 int is_fork_parent;
5662
5663 if (!target_has_execution)
5664 error (_("No process to detach from."));
5665
5666 target_announce_detach (from_tty);
5667
5668 /* Tell the remote target to detach. */
5669 remote_detach_pid (pid);
5670
5671 /* Exit only if this is the only active inferior. */
5672 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5673 puts_filtered (_("Ending remote debugging.\n"));
5674
5675 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5676
5677 /* Check to see if we are detaching a fork parent. Note that if we
5678 are detaching a fork child, tp == NULL. */
5679 is_fork_parent = (tp != NULL
5680 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5681
5682 /* If doing detach-on-fork, we don't mourn, because that will delete
5683 breakpoints that should be available for the followed inferior. */
5684 if (!is_fork_parent)
5685 {
5686 /* Save the pid as a string before mourning, since that will
5687 unpush the remote target, and we need the string after. */
5688 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5689
5690 target_mourn_inferior (inferior_ptid);
5691 if (print_inferior_events)
5692 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5693 inf->num, infpid.c_str ());
5694 }
5695 else
5696 {
5697 inferior_ptid = null_ptid;
5698 detach_inferior (current_inferior ());
5699 }
5700 }
5701
5702 void
5703 remote_target::detach (inferior *inf, int from_tty)
5704 {
5705 remote_detach_1 (inf, from_tty);
5706 }
5707
5708 void
5709 extended_remote_target::detach (inferior *inf, int from_tty)
5710 {
5711 remote_detach_1 (inf, from_tty);
5712 }
5713
5714 /* Target follow-fork function for remote targets. On entry, and
5715 at return, the current inferior is the fork parent.
5716
5717 Note that although this is currently only used for extended-remote,
5718 it is named remote_follow_fork in anticipation of using it for the
5719 remote target as well. */
5720
5721 int
5722 remote_target::follow_fork (int follow_child, int detach_fork)
5723 {
5724 struct remote_state *rs = get_remote_state ();
5725 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5726
5727 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5728 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5729 {
5730 /* When following the parent and detaching the child, we detach
5731 the child here. For the case of following the child and
5732 detaching the parent, the detach is done in the target-
5733 independent follow fork code in infrun.c. We can't use
5734 target_detach when detaching an unfollowed child because
5735 the client side doesn't know anything about the child. */
5736 if (detach_fork && !follow_child)
5737 {
5738 /* Detach the fork child. */
5739 ptid_t child_ptid;
5740 pid_t child_pid;
5741
5742 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5743 child_pid = ptid_get_pid (child_ptid);
5744
5745 remote_detach_pid (child_pid);
5746 }
5747 }
5748 return 0;
5749 }
5750
5751 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5752 in the program space of the new inferior. On entry and at return the
5753 current inferior is the exec'ing inferior. INF is the new exec'd
5754 inferior, which may be the same as the exec'ing inferior unless
5755 follow-exec-mode is "new". */
5756
5757 void
5758 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5759 {
5760 /* We know that this is a target file name, so if it has the "target:"
5761 prefix we strip it off before saving it in the program space. */
5762 if (is_target_filename (execd_pathname))
5763 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5764
5765 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5766 }
5767
5768 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5769
5770 void
5771 remote_target::disconnect (const char *args, int from_tty)
5772 {
5773 if (args)
5774 error (_("Argument given to \"disconnect\" when remotely debugging."));
5775
5776 /* Make sure we unpush even the extended remote targets. Calling
5777 target_mourn_inferior won't unpush, and remote_mourn won't
5778 unpush if there is more than one inferior left. */
5779 unpush_target (this);
5780 generic_mourn_inferior ();
5781
5782 if (from_tty)
5783 puts_filtered ("Ending remote debugging.\n");
5784 }
5785
5786 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5787 be chatty about it. */
5788
5789 void
5790 extended_remote_target::attach (const char *args, int from_tty)
5791 {
5792 struct remote_state *rs = get_remote_state ();
5793 int pid;
5794 char *wait_status = NULL;
5795
5796 pid = parse_pid_to_attach (args);
5797
5798 /* Remote PID can be freely equal to getpid, do not check it here the same
5799 way as in other targets. */
5800
5801 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5802 error (_("This target does not support attaching to a process"));
5803
5804 if (from_tty)
5805 {
5806 char *exec_file = get_exec_file (0);
5807
5808 if (exec_file)
5809 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5810 target_pid_to_str (pid_to_ptid (pid)));
5811 else
5812 printf_unfiltered (_("Attaching to %s\n"),
5813 target_pid_to_str (pid_to_ptid (pid)));
5814
5815 gdb_flush (gdb_stdout);
5816 }
5817
5818 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5819 putpkt (rs->buf);
5820 getpkt (&rs->buf, &rs->buf_size, 0);
5821
5822 switch (packet_ok (rs->buf,
5823 &remote_protocol_packets[PACKET_vAttach]))
5824 {
5825 case PACKET_OK:
5826 if (!target_is_non_stop_p ())
5827 {
5828 /* Save the reply for later. */
5829 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5830 strcpy (wait_status, rs->buf);
5831 }
5832 else if (strcmp (rs->buf, "OK") != 0)
5833 error (_("Attaching to %s failed with: %s"),
5834 target_pid_to_str (pid_to_ptid (pid)),
5835 rs->buf);
5836 break;
5837 case PACKET_UNKNOWN:
5838 error (_("This target does not support attaching to a process"));
5839 default:
5840 error (_("Attaching to %s failed"),
5841 target_pid_to_str (pid_to_ptid (pid)));
5842 }
5843
5844 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5845
5846 inferior_ptid = pid_to_ptid (pid);
5847
5848 if (target_is_non_stop_p ())
5849 {
5850 struct thread_info *thread;
5851
5852 /* Get list of threads. */
5853 update_thread_list ();
5854
5855 thread = first_thread_of_inferior (current_inferior ());
5856 if (thread)
5857 inferior_ptid = thread->ptid;
5858 else
5859 inferior_ptid = pid_to_ptid (pid);
5860
5861 /* Invalidate our notion of the remote current thread. */
5862 record_currthread (rs, minus_one_ptid);
5863 }
5864 else
5865 {
5866 /* Now, if we have thread information, update inferior_ptid. */
5867 inferior_ptid = remote_current_thread (inferior_ptid);
5868
5869 /* Add the main thread to the thread list. */
5870 thread_info *thr = add_thread_silent (inferior_ptid);
5871 /* Don't consider the thread stopped until we've processed the
5872 saved stop reply. */
5873 set_executing (thr->ptid, true);
5874 }
5875
5876 /* Next, if the target can specify a description, read it. We do
5877 this before anything involving memory or registers. */
5878 target_find_description ();
5879
5880 if (!target_is_non_stop_p ())
5881 {
5882 /* Use the previously fetched status. */
5883 gdb_assert (wait_status != NULL);
5884
5885 if (target_can_async_p ())
5886 {
5887 struct notif_event *reply
5888 = remote_notif_parse (this, &notif_client_stop, wait_status);
5889
5890 push_stop_reply ((struct stop_reply *) reply);
5891
5892 target_async (1);
5893 }
5894 else
5895 {
5896 gdb_assert (wait_status != NULL);
5897 strcpy (rs->buf, wait_status);
5898 rs->cached_wait_status = 1;
5899 }
5900 }
5901 else
5902 gdb_assert (wait_status == NULL);
5903 }
5904
5905 /* Implementation of the to_post_attach method. */
5906
5907 void
5908 extended_remote_target::post_attach (int pid)
5909 {
5910 /* Get text, data & bss offsets. */
5911 get_offsets ();
5912
5913 /* In certain cases GDB might not have had the chance to start
5914 symbol lookup up until now. This could happen if the debugged
5915 binary is not using shared libraries, the vsyscall page is not
5916 present (on Linux) and the binary itself hadn't changed since the
5917 debugging process was started. */
5918 if (symfile_objfile != NULL)
5919 remote_check_symbols();
5920 }
5921
5922 \f
5923 /* Check for the availability of vCont. This function should also check
5924 the response. */
5925
5926 void
5927 remote_target::remote_vcont_probe ()
5928 {
5929 remote_state *rs = get_remote_state ();
5930 char *buf;
5931
5932 strcpy (rs->buf, "vCont?");
5933 putpkt (rs->buf);
5934 getpkt (&rs->buf, &rs->buf_size, 0);
5935 buf = rs->buf;
5936
5937 /* Make sure that the features we assume are supported. */
5938 if (startswith (buf, "vCont"))
5939 {
5940 char *p = &buf[5];
5941 int support_c, support_C;
5942
5943 rs->supports_vCont.s = 0;
5944 rs->supports_vCont.S = 0;
5945 support_c = 0;
5946 support_C = 0;
5947 rs->supports_vCont.t = 0;
5948 rs->supports_vCont.r = 0;
5949 while (p && *p == ';')
5950 {
5951 p++;
5952 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5953 rs->supports_vCont.s = 1;
5954 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5955 rs->supports_vCont.S = 1;
5956 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5957 support_c = 1;
5958 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5959 support_C = 1;
5960 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5961 rs->supports_vCont.t = 1;
5962 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5963 rs->supports_vCont.r = 1;
5964
5965 p = strchr (p, ';');
5966 }
5967
5968 /* If c, and C are not all supported, we can't use vCont. Clearing
5969 BUF will make packet_ok disable the packet. */
5970 if (!support_c || !support_C)
5971 buf[0] = 0;
5972 }
5973
5974 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5975 }
5976
5977 /* Helper function for building "vCont" resumptions. Write a
5978 resumption to P. ENDP points to one-passed-the-end of the buffer
5979 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5980 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5981 resumed thread should be single-stepped and/or signalled. If PTID
5982 equals minus_one_ptid, then all threads are resumed; if PTID
5983 represents a process, then all threads of the process are resumed;
5984 the thread to be stepped and/or signalled is given in the global
5985 INFERIOR_PTID. */
5986
5987 char *
5988 remote_target::append_resumption (char *p, char *endp,
5989 ptid_t ptid, int step, gdb_signal siggnal)
5990 {
5991 struct remote_state *rs = get_remote_state ();
5992
5993 if (step && siggnal != GDB_SIGNAL_0)
5994 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5995 else if (step
5996 /* GDB is willing to range step. */
5997 && use_range_stepping
5998 /* Target supports range stepping. */
5999 && rs->supports_vCont.r
6000 /* We don't currently support range stepping multiple
6001 threads with a wildcard (though the protocol allows it,
6002 so stubs shouldn't make an active effort to forbid
6003 it). */
6004 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6005 {
6006 struct thread_info *tp;
6007
6008 if (ptid_equal (ptid, minus_one_ptid))
6009 {
6010 /* If we don't know about the target thread's tid, then
6011 we're resuming magic_null_ptid (see caller). */
6012 tp = find_thread_ptid (magic_null_ptid);
6013 }
6014 else
6015 tp = find_thread_ptid (ptid);
6016 gdb_assert (tp != NULL);
6017
6018 if (tp->control.may_range_step)
6019 {
6020 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6021
6022 p += xsnprintf (p, endp - p, ";r%s,%s",
6023 phex_nz (tp->control.step_range_start,
6024 addr_size),
6025 phex_nz (tp->control.step_range_end,
6026 addr_size));
6027 }
6028 else
6029 p += xsnprintf (p, endp - p, ";s");
6030 }
6031 else if (step)
6032 p += xsnprintf (p, endp - p, ";s");
6033 else if (siggnal != GDB_SIGNAL_0)
6034 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6035 else
6036 p += xsnprintf (p, endp - p, ";c");
6037
6038 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
6039 {
6040 ptid_t nptid;
6041
6042 /* All (-1) threads of process. */
6043 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6044
6045 p += xsnprintf (p, endp - p, ":");
6046 p = write_ptid (p, endp, nptid);
6047 }
6048 else if (!ptid_equal (ptid, minus_one_ptid))
6049 {
6050 p += xsnprintf (p, endp - p, ":");
6051 p = write_ptid (p, endp, ptid);
6052 }
6053
6054 return p;
6055 }
6056
6057 /* Clear the thread's private info on resume. */
6058
6059 static void
6060 resume_clear_thread_private_info (struct thread_info *thread)
6061 {
6062 if (thread->priv != NULL)
6063 {
6064 remote_thread_info *priv = get_remote_thread_info (thread);
6065
6066 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6067 priv->watch_data_address = 0;
6068 }
6069 }
6070
6071 /* Append a vCont continue-with-signal action for threads that have a
6072 non-zero stop signal. */
6073
6074 char *
6075 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6076 ptid_t ptid)
6077 {
6078 struct thread_info *thread;
6079
6080 ALL_NON_EXITED_THREADS (thread)
6081 if (ptid_match (thread->ptid, ptid)
6082 && !ptid_equal (inferior_ptid, thread->ptid)
6083 && thread->suspend.stop_signal != GDB_SIGNAL_0)
6084 {
6085 p = append_resumption (p, endp, thread->ptid,
6086 0, thread->suspend.stop_signal);
6087 thread->suspend.stop_signal = GDB_SIGNAL_0;
6088 resume_clear_thread_private_info (thread);
6089 }
6090
6091 return p;
6092 }
6093
6094 /* Set the target running, using the packets that use Hc
6095 (c/s/C/S). */
6096
6097 void
6098 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6099 gdb_signal siggnal)
6100 {
6101 struct remote_state *rs = get_remote_state ();
6102 struct thread_info *thread;
6103 char *buf;
6104
6105 rs->last_sent_signal = siggnal;
6106 rs->last_sent_step = step;
6107
6108 /* The c/s/C/S resume packets use Hc, so set the continue
6109 thread. */
6110 if (ptid_equal (ptid, minus_one_ptid))
6111 set_continue_thread (any_thread_ptid);
6112 else
6113 set_continue_thread (ptid);
6114
6115 ALL_NON_EXITED_THREADS (thread)
6116 resume_clear_thread_private_info (thread);
6117
6118 buf = rs->buf;
6119 if (::execution_direction == EXEC_REVERSE)
6120 {
6121 /* We don't pass signals to the target in reverse exec mode. */
6122 if (info_verbose && siggnal != GDB_SIGNAL_0)
6123 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6124 siggnal);
6125
6126 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6127 error (_("Remote reverse-step not supported."));
6128 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6129 error (_("Remote reverse-continue not supported."));
6130
6131 strcpy (buf, step ? "bs" : "bc");
6132 }
6133 else if (siggnal != GDB_SIGNAL_0)
6134 {
6135 buf[0] = step ? 'S' : 'C';
6136 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6137 buf[2] = tohex (((int) siggnal) & 0xf);
6138 buf[3] = '\0';
6139 }
6140 else
6141 strcpy (buf, step ? "s" : "c");
6142
6143 putpkt (buf);
6144 }
6145
6146 /* Resume the remote inferior by using a "vCont" packet. The thread
6147 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6148 resumed thread should be single-stepped and/or signalled. If PTID
6149 equals minus_one_ptid, then all threads are resumed; the thread to
6150 be stepped and/or signalled is given in the global INFERIOR_PTID.
6151 This function returns non-zero iff it resumes the inferior.
6152
6153 This function issues a strict subset of all possible vCont commands
6154 at the moment. */
6155
6156 int
6157 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6158 enum gdb_signal siggnal)
6159 {
6160 struct remote_state *rs = get_remote_state ();
6161 char *p;
6162 char *endp;
6163
6164 /* No reverse execution actions defined for vCont. */
6165 if (::execution_direction == EXEC_REVERSE)
6166 return 0;
6167
6168 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6169 remote_vcont_probe ();
6170
6171 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6172 return 0;
6173
6174 p = rs->buf;
6175 endp = rs->buf + get_remote_packet_size ();
6176
6177 /* If we could generate a wider range of packets, we'd have to worry
6178 about overflowing BUF. Should there be a generic
6179 "multi-part-packet" packet? */
6180
6181 p += xsnprintf (p, endp - p, "vCont");
6182
6183 if (ptid_equal (ptid, magic_null_ptid))
6184 {
6185 /* MAGIC_NULL_PTID means that we don't have any active threads,
6186 so we don't have any TID numbers the inferior will
6187 understand. Make sure to only send forms that do not specify
6188 a TID. */
6189 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6190 }
6191 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
6192 {
6193 /* Resume all threads (of all processes, or of a single
6194 process), with preference for INFERIOR_PTID. This assumes
6195 inferior_ptid belongs to the set of all threads we are about
6196 to resume. */
6197 if (step || siggnal != GDB_SIGNAL_0)
6198 {
6199 /* Step inferior_ptid, with or without signal. */
6200 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6201 }
6202
6203 /* Also pass down any pending signaled resumption for other
6204 threads not the current. */
6205 p = append_pending_thread_resumptions (p, endp, ptid);
6206
6207 /* And continue others without a signal. */
6208 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6209 }
6210 else
6211 {
6212 /* Scheduler locking; resume only PTID. */
6213 append_resumption (p, endp, ptid, step, siggnal);
6214 }
6215
6216 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6217 putpkt (rs->buf);
6218
6219 if (target_is_non_stop_p ())
6220 {
6221 /* In non-stop, the stub replies to vCont with "OK". The stop
6222 reply will be reported asynchronously by means of a `%Stop'
6223 notification. */
6224 getpkt (&rs->buf, &rs->buf_size, 0);
6225 if (strcmp (rs->buf, "OK") != 0)
6226 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6227 }
6228
6229 return 1;
6230 }
6231
6232 /* Tell the remote machine to resume. */
6233
6234 void
6235 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6236 {
6237 struct remote_state *rs = get_remote_state ();
6238
6239 /* When connected in non-stop mode, the core resumes threads
6240 individually. Resuming remote threads directly in target_resume
6241 would thus result in sending one packet per thread. Instead, to
6242 minimize roundtrip latency, here we just store the resume
6243 request; the actual remote resumption will be done in
6244 target_commit_resume / remote_commit_resume, where we'll be able
6245 to do vCont action coalescing. */
6246 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6247 {
6248 remote_thread_info *remote_thr;
6249
6250 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
6251 remote_thr = get_remote_thread_info (inferior_ptid);
6252 else
6253 remote_thr = get_remote_thread_info (ptid);
6254
6255 remote_thr->last_resume_step = step;
6256 remote_thr->last_resume_sig = siggnal;
6257 return;
6258 }
6259
6260 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6261 (explained in remote-notif.c:handle_notification) so
6262 remote_notif_process is not called. We need find a place where
6263 it is safe to start a 'vNotif' sequence. It is good to do it
6264 before resuming inferior, because inferior was stopped and no RSP
6265 traffic at that moment. */
6266 if (!target_is_non_stop_p ())
6267 remote_notif_process (rs->notif_state, &notif_client_stop);
6268
6269 rs->last_resume_exec_dir = ::execution_direction;
6270
6271 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6272 if (!remote_resume_with_vcont (ptid, step, siggnal))
6273 remote_resume_with_hc (ptid, step, siggnal);
6274
6275 /* We are about to start executing the inferior, let's register it
6276 with the event loop. NOTE: this is the one place where all the
6277 execution commands end up. We could alternatively do this in each
6278 of the execution commands in infcmd.c. */
6279 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6280 into infcmd.c in order to allow inferior function calls to work
6281 NOT asynchronously. */
6282 if (target_can_async_p ())
6283 target_async (1);
6284
6285 /* We've just told the target to resume. The remote server will
6286 wait for the inferior to stop, and then send a stop reply. In
6287 the mean time, we can't start another command/query ourselves
6288 because the stub wouldn't be ready to process it. This applies
6289 only to the base all-stop protocol, however. In non-stop (which
6290 only supports vCont), the stub replies with an "OK", and is
6291 immediate able to process further serial input. */
6292 if (!target_is_non_stop_p ())
6293 rs->waiting_for_stop_reply = 1;
6294 }
6295
6296 static int is_pending_fork_parent_thread (struct thread_info *thread);
6297
6298 /* Private per-inferior info for target remote processes. */
6299
6300 struct remote_inferior : public private_inferior
6301 {
6302 /* Whether we can send a wildcard vCont for this process. */
6303 bool may_wildcard_vcont = true;
6304 };
6305
6306 /* Get the remote private inferior data associated to INF. */
6307
6308 static remote_inferior *
6309 get_remote_inferior (inferior *inf)
6310 {
6311 if (inf->priv == NULL)
6312 inf->priv.reset (new remote_inferior);
6313
6314 return static_cast<remote_inferior *> (inf->priv.get ());
6315 }
6316
6317 /* Class used to track the construction of a vCont packet in the
6318 outgoing packet buffer. This is used to send multiple vCont
6319 packets if we have more actions than would fit a single packet. */
6320
6321 class vcont_builder
6322 {
6323 public:
6324 explicit vcont_builder (remote_target *remote)
6325 : m_remote (remote)
6326 {
6327 restart ();
6328 }
6329
6330 void flush ();
6331 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6332
6333 private:
6334 void restart ();
6335
6336 /* The remote target. */
6337 remote_target *m_remote;
6338
6339 /* Pointer to the first action. P points here if no action has been
6340 appended yet. */
6341 char *m_first_action;
6342
6343 /* Where the next action will be appended. */
6344 char *m_p;
6345
6346 /* The end of the buffer. Must never write past this. */
6347 char *m_endp;
6348 };
6349
6350 /* Prepare the outgoing buffer for a new vCont packet. */
6351
6352 void
6353 vcont_builder::restart ()
6354 {
6355 struct remote_state *rs = m_remote->get_remote_state ();
6356
6357 m_p = rs->buf;
6358 m_endp = rs->buf + m_remote->get_remote_packet_size ();
6359 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6360 m_first_action = m_p;
6361 }
6362
6363 /* If the vCont packet being built has any action, send it to the
6364 remote end. */
6365
6366 void
6367 vcont_builder::flush ()
6368 {
6369 struct remote_state *rs;
6370
6371 if (m_p == m_first_action)
6372 return;
6373
6374 rs = m_remote->get_remote_state ();
6375 m_remote->putpkt (rs->buf);
6376 m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
6377 if (strcmp (rs->buf, "OK") != 0)
6378 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6379 }
6380
6381 /* The largest action is range-stepping, with its two addresses. This
6382 is more than sufficient. If a new, bigger action is created, it'll
6383 quickly trigger a failed assertion in append_resumption (and we'll
6384 just bump this). */
6385 #define MAX_ACTION_SIZE 200
6386
6387 /* Append a new vCont action in the outgoing packet being built. If
6388 the action doesn't fit the packet along with previous actions, push
6389 what we've got so far to the remote end and start over a new vCont
6390 packet (with the new action). */
6391
6392 void
6393 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6394 {
6395 char buf[MAX_ACTION_SIZE + 1];
6396
6397 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6398 ptid, step, siggnal);
6399
6400 /* Check whether this new action would fit in the vCont packet along
6401 with previous actions. If not, send what we've got so far and
6402 start a new vCont packet. */
6403 size_t rsize = endp - buf;
6404 if (rsize > m_endp - m_p)
6405 {
6406 flush ();
6407 restart ();
6408
6409 /* Should now fit. */
6410 gdb_assert (rsize <= m_endp - m_p);
6411 }
6412
6413 memcpy (m_p, buf, rsize);
6414 m_p += rsize;
6415 *m_p = '\0';
6416 }
6417
6418 /* to_commit_resume implementation. */
6419
6420 void
6421 remote_target::commit_resume ()
6422 {
6423 struct inferior *inf;
6424 struct thread_info *tp;
6425 int any_process_wildcard;
6426 int may_global_wildcard_vcont;
6427
6428 /* If connected in all-stop mode, we'd send the remote resume
6429 request directly from remote_resume. Likewise if
6430 reverse-debugging, as there are no defined vCont actions for
6431 reverse execution. */
6432 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6433 return;
6434
6435 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6436 instead of resuming all threads of each process individually.
6437 However, if any thread of a process must remain halted, we can't
6438 send wildcard resumes and must send one action per thread.
6439
6440 Care must be taken to not resume threads/processes the server
6441 side already told us are stopped, but the core doesn't know about
6442 yet, because the events are still in the vStopped notification
6443 queue. For example:
6444
6445 #1 => vCont s:p1.1;c
6446 #2 <= OK
6447 #3 <= %Stopped T05 p1.1
6448 #4 => vStopped
6449 #5 <= T05 p1.2
6450 #6 => vStopped
6451 #7 <= OK
6452 #8 (infrun handles the stop for p1.1 and continues stepping)
6453 #9 => vCont s:p1.1;c
6454
6455 The last vCont above would resume thread p1.2 by mistake, because
6456 the server has no idea that the event for p1.2 had not been
6457 handled yet.
6458
6459 The server side must similarly ignore resume actions for the
6460 thread that has a pending %Stopped notification (and any other
6461 threads with events pending), until GDB acks the notification
6462 with vStopped. Otherwise, e.g., the following case is
6463 mishandled:
6464
6465 #1 => g (or any other packet)
6466 #2 <= [registers]
6467 #3 <= %Stopped T05 p1.2
6468 #4 => vCont s:p1.1;c
6469 #5 <= OK
6470
6471 Above, the server must not resume thread p1.2. GDB can't know
6472 that p1.2 stopped until it acks the %Stopped notification, and
6473 since from GDB's perspective all threads should be running, it
6474 sends a "c" action.
6475
6476 Finally, special care must also be given to handling fork/vfork
6477 events. A (v)fork event actually tells us that two processes
6478 stopped -- the parent and the child. Until we follow the fork,
6479 we must not resume the child. Therefore, if we have a pending
6480 fork follow, we must not send a global wildcard resume action
6481 (vCont;c). We can still send process-wide wildcards though. */
6482
6483 /* Start by assuming a global wildcard (vCont;c) is possible. */
6484 may_global_wildcard_vcont = 1;
6485
6486 /* And assume every process is individually wildcard-able too. */
6487 ALL_NON_EXITED_INFERIORS (inf)
6488 {
6489 remote_inferior *priv = get_remote_inferior (inf);
6490
6491 priv->may_wildcard_vcont = true;
6492 }
6493
6494 /* Check for any pending events (not reported or processed yet) and
6495 disable process and global wildcard resumes appropriately. */
6496 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6497
6498 ALL_NON_EXITED_THREADS (tp)
6499 {
6500 /* If a thread of a process is not meant to be resumed, then we
6501 can't wildcard that process. */
6502 if (!tp->executing)
6503 {
6504 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6505
6506 /* And if we can't wildcard a process, we can't wildcard
6507 everything either. */
6508 may_global_wildcard_vcont = 0;
6509 continue;
6510 }
6511
6512 /* If a thread is the parent of an unfollowed fork, then we
6513 can't do a global wildcard, as that would resume the fork
6514 child. */
6515 if (is_pending_fork_parent_thread (tp))
6516 may_global_wildcard_vcont = 0;
6517 }
6518
6519 /* Now let's build the vCont packet(s). Actions must be appended
6520 from narrower to wider scopes (thread -> process -> global). If
6521 we end up with too many actions for a single packet vcont_builder
6522 flushes the current vCont packet to the remote side and starts a
6523 new one. */
6524 struct vcont_builder vcont_builder (this);
6525
6526 /* Threads first. */
6527 ALL_NON_EXITED_THREADS (tp)
6528 {
6529 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6530
6531 if (!tp->executing || remote_thr->vcont_resumed)
6532 continue;
6533
6534 gdb_assert (!thread_is_in_step_over_chain (tp));
6535
6536 if (!remote_thr->last_resume_step
6537 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6538 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6539 {
6540 /* We'll send a wildcard resume instead. */
6541 remote_thr->vcont_resumed = 1;
6542 continue;
6543 }
6544
6545 vcont_builder.push_action (tp->ptid,
6546 remote_thr->last_resume_step,
6547 remote_thr->last_resume_sig);
6548 remote_thr->vcont_resumed = 1;
6549 }
6550
6551 /* Now check whether we can send any process-wide wildcard. This is
6552 to avoid sending a global wildcard in the case nothing is
6553 supposed to be resumed. */
6554 any_process_wildcard = 0;
6555
6556 ALL_NON_EXITED_INFERIORS (inf)
6557 {
6558 if (get_remote_inferior (inf)->may_wildcard_vcont)
6559 {
6560 any_process_wildcard = 1;
6561 break;
6562 }
6563 }
6564
6565 if (any_process_wildcard)
6566 {
6567 /* If all processes are wildcard-able, then send a single "c"
6568 action, otherwise, send an "all (-1) threads of process"
6569 continue action for each running process, if any. */
6570 if (may_global_wildcard_vcont)
6571 {
6572 vcont_builder.push_action (minus_one_ptid,
6573 false, GDB_SIGNAL_0);
6574 }
6575 else
6576 {
6577 ALL_NON_EXITED_INFERIORS (inf)
6578 {
6579 if (get_remote_inferior (inf)->may_wildcard_vcont)
6580 {
6581 vcont_builder.push_action (pid_to_ptid (inf->pid),
6582 false, GDB_SIGNAL_0);
6583 }
6584 }
6585 }
6586 }
6587
6588 vcont_builder.flush ();
6589 }
6590
6591 \f
6592
6593 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6594 thread, all threads of a remote process, or all threads of all
6595 processes. */
6596
6597 void
6598 remote_target::remote_stop_ns (ptid_t ptid)
6599 {
6600 struct remote_state *rs = get_remote_state ();
6601 char *p = rs->buf;
6602 char *endp = rs->buf + get_remote_packet_size ();
6603
6604 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6605 remote_vcont_probe ();
6606
6607 if (!rs->supports_vCont.t)
6608 error (_("Remote server does not support stopping threads"));
6609
6610 if (ptid_equal (ptid, minus_one_ptid)
6611 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6612 p += xsnprintf (p, endp - p, "vCont;t");
6613 else
6614 {
6615 ptid_t nptid;
6616
6617 p += xsnprintf (p, endp - p, "vCont;t:");
6618
6619 if (ptid_is_pid (ptid))
6620 /* All (-1) threads of process. */
6621 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6622 else
6623 {
6624 /* Small optimization: if we already have a stop reply for
6625 this thread, no use in telling the stub we want this
6626 stopped. */
6627 if (peek_stop_reply (ptid))
6628 return;
6629
6630 nptid = ptid;
6631 }
6632
6633 write_ptid (p, endp, nptid);
6634 }
6635
6636 /* In non-stop, we get an immediate OK reply. The stop reply will
6637 come in asynchronously by notification. */
6638 putpkt (rs->buf);
6639 getpkt (&rs->buf, &rs->buf_size, 0);
6640 if (strcmp (rs->buf, "OK") != 0)
6641 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6642 }
6643
6644 /* All-stop version of target_interrupt. Sends a break or a ^C to
6645 interrupt the remote target. It is undefined which thread of which
6646 process reports the interrupt. */
6647
6648 void
6649 remote_target::remote_interrupt_as ()
6650 {
6651 struct remote_state *rs = get_remote_state ();
6652
6653 rs->ctrlc_pending_p = 1;
6654
6655 /* If the inferior is stopped already, but the core didn't know
6656 about it yet, just ignore the request. The cached wait status
6657 will be collected in remote_wait. */
6658 if (rs->cached_wait_status)
6659 return;
6660
6661 /* Send interrupt_sequence to remote target. */
6662 send_interrupt_sequence ();
6663 }
6664
6665 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6666 the remote target. It is undefined which thread of which process
6667 reports the interrupt. Throws an error if the packet is not
6668 supported by the server. */
6669
6670 void
6671 remote_target::remote_interrupt_ns ()
6672 {
6673 struct remote_state *rs = get_remote_state ();
6674 char *p = rs->buf;
6675 char *endp = rs->buf + get_remote_packet_size ();
6676
6677 xsnprintf (p, endp - p, "vCtrlC");
6678
6679 /* In non-stop, we get an immediate OK reply. The stop reply will
6680 come in asynchronously by notification. */
6681 putpkt (rs->buf);
6682 getpkt (&rs->buf, &rs->buf_size, 0);
6683
6684 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6685 {
6686 case PACKET_OK:
6687 break;
6688 case PACKET_UNKNOWN:
6689 error (_("No support for interrupting the remote target."));
6690 case PACKET_ERROR:
6691 error (_("Interrupting target failed: %s"), rs->buf);
6692 }
6693 }
6694
6695 /* Implement the to_stop function for the remote targets. */
6696
6697 void
6698 remote_target::stop (ptid_t ptid)
6699 {
6700 if (remote_debug)
6701 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6702
6703 if (target_is_non_stop_p ())
6704 remote_stop_ns (ptid);
6705 else
6706 {
6707 /* We don't currently have a way to transparently pause the
6708 remote target in all-stop mode. Interrupt it instead. */
6709 remote_interrupt_as ();
6710 }
6711 }
6712
6713 /* Implement the to_interrupt function for the remote targets. */
6714
6715 void
6716 remote_target::interrupt ()
6717 {
6718 if (remote_debug)
6719 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6720
6721 if (target_is_non_stop_p ())
6722 remote_interrupt_ns ();
6723 else
6724 remote_interrupt_as ();
6725 }
6726
6727 /* Implement the to_pass_ctrlc function for the remote targets. */
6728
6729 void
6730 remote_target::pass_ctrlc ()
6731 {
6732 struct remote_state *rs = get_remote_state ();
6733
6734 if (remote_debug)
6735 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6736
6737 /* If we're starting up, we're not fully synced yet. Quit
6738 immediately. */
6739 if (rs->starting_up)
6740 quit ();
6741 /* If ^C has already been sent once, offer to disconnect. */
6742 else if (rs->ctrlc_pending_p)
6743 interrupt_query ();
6744 else
6745 target_interrupt ();
6746 }
6747
6748 /* Ask the user what to do when an interrupt is received. */
6749
6750 void
6751 remote_target::interrupt_query ()
6752 {
6753 struct remote_state *rs = get_remote_state ();
6754
6755 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6756 {
6757 if (query (_("The target is not responding to interrupt requests.\n"
6758 "Stop debugging it? ")))
6759 {
6760 remote_unpush_target ();
6761 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6762 }
6763 }
6764 else
6765 {
6766 if (query (_("Interrupted while waiting for the program.\n"
6767 "Give up waiting? ")))
6768 quit ();
6769 }
6770 }
6771
6772 /* Enable/disable target terminal ownership. Most targets can use
6773 terminal groups to control terminal ownership. Remote targets are
6774 different in that explicit transfer of ownership to/from GDB/target
6775 is required. */
6776
6777 void
6778 remote_target::terminal_inferior ()
6779 {
6780 /* NOTE: At this point we could also register our selves as the
6781 recipient of all input. Any characters typed could then be
6782 passed on down to the target. */
6783 }
6784
6785 void
6786 remote_target::terminal_ours ()
6787 {
6788 }
6789
6790 static void
6791 remote_console_output (char *msg)
6792 {
6793 char *p;
6794
6795 for (p = msg; p[0] && p[1]; p += 2)
6796 {
6797 char tb[2];
6798 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6799
6800 tb[0] = c;
6801 tb[1] = 0;
6802 fputs_unfiltered (tb, gdb_stdtarg);
6803 }
6804 gdb_flush (gdb_stdtarg);
6805 }
6806
6807 DEF_VEC_O(cached_reg_t);
6808
6809 typedef struct stop_reply
6810 {
6811 struct notif_event base;
6812
6813 /* The identifier of the thread about this event */
6814 ptid_t ptid;
6815
6816 /* The remote state this event is associated with. When the remote
6817 connection, represented by a remote_state object, is closed,
6818 all the associated stop_reply events should be released. */
6819 struct remote_state *rs;
6820
6821 struct target_waitstatus ws;
6822
6823 /* The architecture associated with the expedited registers. */
6824 gdbarch *arch;
6825
6826 /* Expedited registers. This makes remote debugging a bit more
6827 efficient for those targets that provide critical registers as
6828 part of their normal status mechanism (as another roundtrip to
6829 fetch them is avoided). */
6830 VEC(cached_reg_t) *regcache;
6831
6832 enum target_stop_reason stop_reason;
6833
6834 CORE_ADDR watch_data_address;
6835
6836 int core;
6837 } *stop_reply_p;
6838
6839 static void
6840 stop_reply_xfree (struct stop_reply *r)
6841 {
6842 notif_event_xfree ((struct notif_event *) r);
6843 }
6844
6845 /* Return the length of the stop reply queue. */
6846
6847 int
6848 remote_target::stop_reply_queue_length ()
6849 {
6850 remote_state *rs = get_remote_state ();
6851 return rs->stop_reply_queue.size ();
6852 }
6853
6854 void
6855 remote_notif_stop_parse (remote_target *remote,
6856 struct notif_client *self, char *buf,
6857 struct notif_event *event)
6858 {
6859 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
6860 }
6861
6862 static void
6863 remote_notif_stop_ack (remote_target *remote,
6864 struct notif_client *self, char *buf,
6865 struct notif_event *event)
6866 {
6867 struct stop_reply *stop_reply = (struct stop_reply *) event;
6868
6869 /* acknowledge */
6870 putpkt (remote, self->ack_command);
6871
6872 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6873 {
6874 /* We got an unknown stop reply. */
6875 error (_("Unknown stop reply"));
6876 }
6877
6878 remote->push_stop_reply (stop_reply);
6879 }
6880
6881 static int
6882 remote_notif_stop_can_get_pending_events (remote_target *remote,
6883 struct notif_client *self)
6884 {
6885 /* We can't get pending events in remote_notif_process for
6886 notification stop, and we have to do this in remote_wait_ns
6887 instead. If we fetch all queued events from stub, remote stub
6888 may exit and we have no chance to process them back in
6889 remote_wait_ns. */
6890 remote_state *rs = remote->get_remote_state ();
6891 mark_async_event_handler (rs->remote_async_inferior_event_token);
6892 return 0;
6893 }
6894
6895 static void
6896 stop_reply_dtr (struct notif_event *event)
6897 {
6898 struct stop_reply *r = (struct stop_reply *) event;
6899 cached_reg_t *reg;
6900 int ix;
6901
6902 for (ix = 0;
6903 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6904 ix++)
6905 xfree (reg->data);
6906
6907 VEC_free (cached_reg_t, r->regcache);
6908 }
6909
6910 static struct notif_event *
6911 remote_notif_stop_alloc_reply (void)
6912 {
6913 /* We cast to a pointer to the "base class". */
6914 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6915
6916 r->dtr = stop_reply_dtr;
6917
6918 return r;
6919 }
6920
6921 /* A client of notification Stop. */
6922
6923 struct notif_client notif_client_stop =
6924 {
6925 "Stop",
6926 "vStopped",
6927 remote_notif_stop_parse,
6928 remote_notif_stop_ack,
6929 remote_notif_stop_can_get_pending_events,
6930 remote_notif_stop_alloc_reply,
6931 REMOTE_NOTIF_STOP,
6932 };
6933
6934 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6935 the pid of the process that owns the threads we want to check, or
6936 -1 if we want to check all threads. */
6937
6938 static int
6939 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6940 ptid_t thread_ptid)
6941 {
6942 if (ws->kind == TARGET_WAITKIND_FORKED
6943 || ws->kind == TARGET_WAITKIND_VFORKED)
6944 {
6945 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6946 return 1;
6947 }
6948
6949 return 0;
6950 }
6951
6952 /* Return the thread's pending status used to determine whether the
6953 thread is a fork parent stopped at a fork event. */
6954
6955 static struct target_waitstatus *
6956 thread_pending_fork_status (struct thread_info *thread)
6957 {
6958 if (thread->suspend.waitstatus_pending_p)
6959 return &thread->suspend.waitstatus;
6960 else
6961 return &thread->pending_follow;
6962 }
6963
6964 /* Determine if THREAD is a pending fork parent thread. */
6965
6966 static int
6967 is_pending_fork_parent_thread (struct thread_info *thread)
6968 {
6969 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6970 int pid = -1;
6971
6972 return is_pending_fork_parent (ws, pid, thread->ptid);
6973 }
6974
6975 /* If CONTEXT contains any fork child threads that have not been
6976 reported yet, remove them from the CONTEXT list. If such a
6977 thread exists it is because we are stopped at a fork catchpoint
6978 and have not yet called follow_fork, which will set up the
6979 host-side data structures for the new process. */
6980
6981 void
6982 remote_target::remove_new_fork_children (threads_listing_context *context)
6983 {
6984 struct thread_info * thread;
6985 int pid = -1;
6986 struct notif_client *notif = &notif_client_stop;
6987
6988 /* For any threads stopped at a fork event, remove the corresponding
6989 fork child threads from the CONTEXT list. */
6990 ALL_NON_EXITED_THREADS (thread)
6991 {
6992 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6993
6994 if (is_pending_fork_parent (ws, pid, thread->ptid))
6995 context->remove_thread (ws->value.related_pid);
6996 }
6997
6998 /* Check for any pending fork events (not reported or processed yet)
6999 in process PID and remove those fork child threads from the
7000 CONTEXT list as well. */
7001 remote_notif_get_pending_events (notif);
7002 for (auto &event : get_remote_state ()->stop_reply_queue)
7003 if (event->ws.kind == TARGET_WAITKIND_FORKED
7004 || event->ws.kind == TARGET_WAITKIND_VFORKED
7005 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7006 context->remove_thread (event->ws.value.related_pid);
7007 }
7008
7009 /* Check whether any event pending in the vStopped queue would prevent
7010 a global or process wildcard vCont action. Clear
7011 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7012 and clear the event inferior's may_wildcard_vcont flag if we can't
7013 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7014
7015 void
7016 remote_target::check_pending_events_prevent_wildcard_vcont
7017 (int *may_global_wildcard)
7018 {
7019 struct notif_client *notif = &notif_client_stop;
7020
7021 remote_notif_get_pending_events (notif);
7022 for (auto &event : get_remote_state ()->stop_reply_queue)
7023 {
7024 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7025 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7026 continue;
7027
7028 if (event->ws.kind == TARGET_WAITKIND_FORKED
7029 || event->ws.kind == TARGET_WAITKIND_VFORKED)
7030 *may_global_wildcard = 0;
7031
7032 struct inferior *inf = find_inferior_ptid (event->ptid);
7033
7034 /* This may be the first time we heard about this process.
7035 Regardless, we must not do a global wildcard resume, otherwise
7036 we'd resume this process too. */
7037 *may_global_wildcard = 0;
7038 if (inf != NULL)
7039 get_remote_inferior (inf)->may_wildcard_vcont = false;
7040 }
7041 }
7042
7043 /* Discard all pending stop replies of inferior INF. */
7044
7045 void
7046 remote_target::discard_pending_stop_replies (struct inferior *inf)
7047 {
7048 struct stop_reply *reply;
7049 struct remote_state *rs = get_remote_state ();
7050 struct remote_notif_state *rns = rs->notif_state;
7051
7052 /* This function can be notified when an inferior exists. When the
7053 target is not remote, the notification state is NULL. */
7054 if (rs->remote_desc == NULL)
7055 return;
7056
7057 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7058
7059 /* Discard the in-flight notification. */
7060 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
7061 {
7062 stop_reply_xfree (reply);
7063 rns->pending_event[notif_client_stop.id] = NULL;
7064 }
7065
7066 /* Discard the stop replies we have already pulled with
7067 vStopped. */
7068 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7069 rs->stop_reply_queue.end (),
7070 [=] (const stop_reply_up &event)
7071 {
7072 return event->ptid.pid () == inf->pid;
7073 });
7074 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7075 }
7076
7077 /* Discard the stop replies for RS in stop_reply_queue. */
7078
7079 void
7080 remote_target::discard_pending_stop_replies_in_queue ()
7081 {
7082 remote_state *rs = get_remote_state ();
7083
7084 /* Discard the stop replies we have already pulled with
7085 vStopped. */
7086 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7087 rs->stop_reply_queue.end (),
7088 [=] (const stop_reply_up &event)
7089 {
7090 return event->rs == rs;
7091 });
7092 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7093 }
7094
7095 /* Remove the first reply in 'stop_reply_queue' which matches
7096 PTID. */
7097
7098 struct stop_reply *
7099 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7100 {
7101 remote_state *rs = get_remote_state ();
7102
7103 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7104 rs->stop_reply_queue.end (),
7105 [=] (const stop_reply_up &event)
7106 {
7107 return event->ptid.matches (ptid);
7108 });
7109 struct stop_reply *result;
7110 if (iter == rs->stop_reply_queue.end ())
7111 result = nullptr;
7112 else
7113 {
7114 result = iter->release ();
7115 rs->stop_reply_queue.erase (iter);
7116 }
7117
7118 if (notif_debug)
7119 fprintf_unfiltered (gdb_stdlog,
7120 "notif: discard queued event: 'Stop' in %s\n",
7121 target_pid_to_str (ptid));
7122
7123 return result;
7124 }
7125
7126 /* Look for a queued stop reply belonging to PTID. If one is found,
7127 remove it from the queue, and return it. Returns NULL if none is
7128 found. If there are still queued events left to process, tell the
7129 event loop to get back to target_wait soon. */
7130
7131 struct stop_reply *
7132 remote_target::queued_stop_reply (ptid_t ptid)
7133 {
7134 remote_state *rs = get_remote_state ();
7135 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7136
7137 if (!rs->stop_reply_queue.empty ())
7138 {
7139 /* There's still at least an event left. */
7140 mark_async_event_handler (rs->remote_async_inferior_event_token);
7141 }
7142
7143 return r;
7144 }
7145
7146 /* Push a fully parsed stop reply in the stop reply queue. Since we
7147 know that we now have at least one queued event left to pass to the
7148 core side, tell the event loop to get back to target_wait soon. */
7149
7150 void
7151 remote_target::push_stop_reply (struct stop_reply *new_event)
7152 {
7153 remote_state *rs = get_remote_state ();
7154 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7155
7156 if (notif_debug)
7157 fprintf_unfiltered (gdb_stdlog,
7158 "notif: push 'Stop' %s to queue %d\n",
7159 target_pid_to_str (new_event->ptid),
7160 int (rs->stop_reply_queue.size ()));
7161
7162 mark_async_event_handler (rs->remote_async_inferior_event_token);
7163 }
7164
7165 /* Returns true if we have a stop reply for PTID. */
7166
7167 int
7168 remote_target::peek_stop_reply (ptid_t ptid)
7169 {
7170 remote_state *rs = get_remote_state ();
7171 for (auto &event : rs->stop_reply_queue)
7172 if (ptid == event->ptid
7173 && event->ws.kind == TARGET_WAITKIND_STOPPED)
7174 return 1;
7175 return 0;
7176 }
7177
7178 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7179 starting with P and ending with PEND matches PREFIX. */
7180
7181 static int
7182 strprefix (const char *p, const char *pend, const char *prefix)
7183 {
7184 for ( ; p < pend; p++, prefix++)
7185 if (*p != *prefix)
7186 return 0;
7187 return *prefix == '\0';
7188 }
7189
7190 /* Parse the stop reply in BUF. Either the function succeeds, and the
7191 result is stored in EVENT, or throws an error. */
7192
7193 void
7194 remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
7195 {
7196 remote_arch_state *rsa = NULL;
7197 ULONGEST addr;
7198 const char *p;
7199 int skipregs = 0;
7200
7201 event->ptid = null_ptid;
7202 event->rs = get_remote_state ();
7203 event->ws.kind = TARGET_WAITKIND_IGNORE;
7204 event->ws.value.integer = 0;
7205 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7206 event->regcache = NULL;
7207 event->core = -1;
7208
7209 switch (buf[0])
7210 {
7211 case 'T': /* Status with PC, SP, FP, ... */
7212 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7213 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7214 ss = signal number
7215 n... = register number
7216 r... = register contents
7217 */
7218
7219 p = &buf[3]; /* after Txx */
7220 while (*p)
7221 {
7222 const char *p1;
7223 int fieldsize;
7224
7225 p1 = strchr (p, ':');
7226 if (p1 == NULL)
7227 error (_("Malformed packet(a) (missing colon): %s\n\
7228 Packet: '%s'\n"),
7229 p, buf);
7230 if (p == p1)
7231 error (_("Malformed packet(a) (missing register number): %s\n\
7232 Packet: '%s'\n"),
7233 p, buf);
7234
7235 /* Some "registers" are actually extended stop information.
7236 Note if you're adding a new entry here: GDB 7.9 and
7237 earlier assume that all register "numbers" that start
7238 with an hex digit are real register numbers. Make sure
7239 the server only sends such a packet if it knows the
7240 client understands it. */
7241
7242 if (strprefix (p, p1, "thread"))
7243 event->ptid = read_ptid (++p1, &p);
7244 else if (strprefix (p, p1, "syscall_entry"))
7245 {
7246 ULONGEST sysno;
7247
7248 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7249 p = unpack_varlen_hex (++p1, &sysno);
7250 event->ws.value.syscall_number = (int) sysno;
7251 }
7252 else if (strprefix (p, p1, "syscall_return"))
7253 {
7254 ULONGEST sysno;
7255
7256 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7257 p = unpack_varlen_hex (++p1, &sysno);
7258 event->ws.value.syscall_number = (int) sysno;
7259 }
7260 else if (strprefix (p, p1, "watch")
7261 || strprefix (p, p1, "rwatch")
7262 || strprefix (p, p1, "awatch"))
7263 {
7264 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7265 p = unpack_varlen_hex (++p1, &addr);
7266 event->watch_data_address = (CORE_ADDR) addr;
7267 }
7268 else if (strprefix (p, p1, "swbreak"))
7269 {
7270 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7271
7272 /* Make sure the stub doesn't forget to indicate support
7273 with qSupported. */
7274 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7275 error (_("Unexpected swbreak stop reason"));
7276
7277 /* The value part is documented as "must be empty",
7278 though we ignore it, in case we ever decide to make
7279 use of it in a backward compatible way. */
7280 p = strchrnul (p1 + 1, ';');
7281 }
7282 else if (strprefix (p, p1, "hwbreak"))
7283 {
7284 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7285
7286 /* Make sure the stub doesn't forget to indicate support
7287 with qSupported. */
7288 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7289 error (_("Unexpected hwbreak stop reason"));
7290
7291 /* See above. */
7292 p = strchrnul (p1 + 1, ';');
7293 }
7294 else if (strprefix (p, p1, "library"))
7295 {
7296 event->ws.kind = TARGET_WAITKIND_LOADED;
7297 p = strchrnul (p1 + 1, ';');
7298 }
7299 else if (strprefix (p, p1, "replaylog"))
7300 {
7301 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7302 /* p1 will indicate "begin" or "end", but it makes
7303 no difference for now, so ignore it. */
7304 p = strchrnul (p1 + 1, ';');
7305 }
7306 else if (strprefix (p, p1, "core"))
7307 {
7308 ULONGEST c;
7309
7310 p = unpack_varlen_hex (++p1, &c);
7311 event->core = c;
7312 }
7313 else if (strprefix (p, p1, "fork"))
7314 {
7315 event->ws.value.related_pid = read_ptid (++p1, &p);
7316 event->ws.kind = TARGET_WAITKIND_FORKED;
7317 }
7318 else if (strprefix (p, p1, "vfork"))
7319 {
7320 event->ws.value.related_pid = read_ptid (++p1, &p);
7321 event->ws.kind = TARGET_WAITKIND_VFORKED;
7322 }
7323 else if (strprefix (p, p1, "vforkdone"))
7324 {
7325 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7326 p = strchrnul (p1 + 1, ';');
7327 }
7328 else if (strprefix (p, p1, "exec"))
7329 {
7330 ULONGEST ignored;
7331 char pathname[PATH_MAX];
7332 int pathlen;
7333
7334 /* Determine the length of the execd pathname. */
7335 p = unpack_varlen_hex (++p1, &ignored);
7336 pathlen = (p - p1) / 2;
7337
7338 /* Save the pathname for event reporting and for
7339 the next run command. */
7340 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7341 pathname[pathlen] = '\0';
7342
7343 /* This is freed during event handling. */
7344 event->ws.value.execd_pathname = xstrdup (pathname);
7345 event->ws.kind = TARGET_WAITKIND_EXECD;
7346
7347 /* Skip the registers included in this packet, since
7348 they may be for an architecture different from the
7349 one used by the original program. */
7350 skipregs = 1;
7351 }
7352 else if (strprefix (p, p1, "create"))
7353 {
7354 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7355 p = strchrnul (p1 + 1, ';');
7356 }
7357 else
7358 {
7359 ULONGEST pnum;
7360 const char *p_temp;
7361
7362 if (skipregs)
7363 {
7364 p = strchrnul (p1 + 1, ';');
7365 p++;
7366 continue;
7367 }
7368
7369 /* Maybe a real ``P'' register number. */
7370 p_temp = unpack_varlen_hex (p, &pnum);
7371 /* If the first invalid character is the colon, we got a
7372 register number. Otherwise, it's an unknown stop
7373 reason. */
7374 if (p_temp == p1)
7375 {
7376 /* If we haven't parsed the event's thread yet, find
7377 it now, in order to find the architecture of the
7378 reported expedited registers. */
7379 if (event->ptid == null_ptid)
7380 {
7381 const char *thr = strstr (p1 + 1, ";thread:");
7382 if (thr != NULL)
7383 event->ptid = read_ptid (thr + strlen (";thread:"),
7384 NULL);
7385 else
7386 {
7387 /* Either the current thread hasn't changed,
7388 or the inferior is not multi-threaded.
7389 The event must be for the thread we last
7390 set as (or learned as being) current. */
7391 event->ptid = event->rs->general_thread;
7392 }
7393 }
7394
7395 if (rsa == NULL)
7396 {
7397 inferior *inf = (event->ptid == null_ptid
7398 ? NULL
7399 : find_inferior_ptid (event->ptid));
7400 /* If this is the first time we learn anything
7401 about this process, skip the registers
7402 included in this packet, since we don't yet
7403 know which architecture to use to parse them.
7404 We'll determine the architecture later when
7405 we process the stop reply and retrieve the
7406 target description, via
7407 remote_notice_new_inferior ->
7408 post_create_inferior. */
7409 if (inf == NULL)
7410 {
7411 p = strchrnul (p1 + 1, ';');
7412 p++;
7413 continue;
7414 }
7415
7416 event->arch = inf->gdbarch;
7417 rsa = event->rs->get_remote_arch_state (event->arch);
7418 }
7419
7420 packet_reg *reg
7421 = packet_reg_from_pnum (event->arch, rsa, pnum);
7422 cached_reg_t cached_reg;
7423
7424 if (reg == NULL)
7425 error (_("Remote sent bad register number %s: %s\n\
7426 Packet: '%s'\n"),
7427 hex_string (pnum), p, buf);
7428
7429 cached_reg.num = reg->regnum;
7430 cached_reg.data = (gdb_byte *)
7431 xmalloc (register_size (event->arch, reg->regnum));
7432
7433 p = p1 + 1;
7434 fieldsize = hex2bin (p, cached_reg.data,
7435 register_size (event->arch, reg->regnum));
7436 p += 2 * fieldsize;
7437 if (fieldsize < register_size (event->arch, reg->regnum))
7438 warning (_("Remote reply is too short: %s"), buf);
7439
7440 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7441 }
7442 else
7443 {
7444 /* Not a number. Silently skip unknown optional
7445 info. */
7446 p = strchrnul (p1 + 1, ';');
7447 }
7448 }
7449
7450 if (*p != ';')
7451 error (_("Remote register badly formatted: %s\nhere: %s"),
7452 buf, p);
7453 ++p;
7454 }
7455
7456 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7457 break;
7458
7459 /* fall through */
7460 case 'S': /* Old style status, just signal only. */
7461 {
7462 int sig;
7463
7464 event->ws.kind = TARGET_WAITKIND_STOPPED;
7465 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7466 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7467 event->ws.value.sig = (enum gdb_signal) sig;
7468 else
7469 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7470 }
7471 break;
7472 case 'w': /* Thread exited. */
7473 {
7474 const char *p;
7475 ULONGEST value;
7476
7477 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7478 p = unpack_varlen_hex (&buf[1], &value);
7479 event->ws.value.integer = value;
7480 if (*p != ';')
7481 error (_("stop reply packet badly formatted: %s"), buf);
7482 event->ptid = read_ptid (++p, NULL);
7483 break;
7484 }
7485 case 'W': /* Target exited. */
7486 case 'X':
7487 {
7488 const char *p;
7489 int pid;
7490 ULONGEST value;
7491
7492 /* GDB used to accept only 2 hex chars here. Stubs should
7493 only send more if they detect GDB supports multi-process
7494 support. */
7495 p = unpack_varlen_hex (&buf[1], &value);
7496
7497 if (buf[0] == 'W')
7498 {
7499 /* The remote process exited. */
7500 event->ws.kind = TARGET_WAITKIND_EXITED;
7501 event->ws.value.integer = value;
7502 }
7503 else
7504 {
7505 /* The remote process exited with a signal. */
7506 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7507 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7508 event->ws.value.sig = (enum gdb_signal) value;
7509 else
7510 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7511 }
7512
7513 /* If no process is specified, assume inferior_ptid. */
7514 pid = ptid_get_pid (inferior_ptid);
7515 if (*p == '\0')
7516 ;
7517 else if (*p == ';')
7518 {
7519 p++;
7520
7521 if (*p == '\0')
7522 ;
7523 else if (startswith (p, "process:"))
7524 {
7525 ULONGEST upid;
7526
7527 p += sizeof ("process:") - 1;
7528 unpack_varlen_hex (p, &upid);
7529 pid = upid;
7530 }
7531 else
7532 error (_("unknown stop reply packet: %s"), buf);
7533 }
7534 else
7535 error (_("unknown stop reply packet: %s"), buf);
7536 event->ptid = pid_to_ptid (pid);
7537 }
7538 break;
7539 case 'N':
7540 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7541 event->ptid = minus_one_ptid;
7542 break;
7543 }
7544
7545 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7546 error (_("No process or thread specified in stop reply: %s"), buf);
7547 }
7548
7549 /* When the stub wants to tell GDB about a new notification reply, it
7550 sends a notification (%Stop, for example). Those can come it at
7551 any time, hence, we have to make sure that any pending
7552 putpkt/getpkt sequence we're making is finished, before querying
7553 the stub for more events with the corresponding ack command
7554 (vStopped, for example). E.g., if we started a vStopped sequence
7555 immediately upon receiving the notification, something like this
7556 could happen:
7557
7558 1.1) --> Hg 1
7559 1.2) <-- OK
7560 1.3) --> g
7561 1.4) <-- %Stop
7562 1.5) --> vStopped
7563 1.6) <-- (registers reply to step #1.3)
7564
7565 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7566 query.
7567
7568 To solve this, whenever we parse a %Stop notification successfully,
7569 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7570 doing whatever we were doing:
7571
7572 2.1) --> Hg 1
7573 2.2) <-- OK
7574 2.3) --> g
7575 2.4) <-- %Stop
7576 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7577 2.5) <-- (registers reply to step #2.3)
7578
7579 Eventualy after step #2.5, we return to the event loop, which
7580 notices there's an event on the
7581 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7582 associated callback --- the function below. At this point, we're
7583 always safe to start a vStopped sequence. :
7584
7585 2.6) --> vStopped
7586 2.7) <-- T05 thread:2
7587 2.8) --> vStopped
7588 2.9) --> OK
7589 */
7590
7591 void
7592 remote_target::remote_notif_get_pending_events (notif_client *nc)
7593 {
7594 struct remote_state *rs = get_remote_state ();
7595
7596 if (rs->notif_state->pending_event[nc->id] != NULL)
7597 {
7598 if (notif_debug)
7599 fprintf_unfiltered (gdb_stdlog,
7600 "notif: process: '%s' ack pending event\n",
7601 nc->name);
7602
7603 /* acknowledge */
7604 nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7605 rs->notif_state->pending_event[nc->id] = NULL;
7606
7607 while (1)
7608 {
7609 getpkt (&rs->buf, &rs->buf_size, 0);
7610 if (strcmp (rs->buf, "OK") == 0)
7611 break;
7612 else
7613 remote_notif_ack (this, nc, rs->buf);
7614 }
7615 }
7616 else
7617 {
7618 if (notif_debug)
7619 fprintf_unfiltered (gdb_stdlog,
7620 "notif: process: '%s' no pending reply\n",
7621 nc->name);
7622 }
7623 }
7624
7625 /* Wrapper around remote_target::remote_notif_get_pending_events to
7626 avoid having to export the whole remote_target class. */
7627
7628 void
7629 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7630 {
7631 remote->remote_notif_get_pending_events (nc);
7632 }
7633
7634 /* Called when it is decided that STOP_REPLY holds the info of the
7635 event that is to be returned to the core. This function always
7636 destroys STOP_REPLY. */
7637
7638 ptid_t
7639 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7640 struct target_waitstatus *status)
7641 {
7642 ptid_t ptid;
7643
7644 *status = stop_reply->ws;
7645 ptid = stop_reply->ptid;
7646
7647 /* If no thread/process was reported by the stub, assume the current
7648 inferior. */
7649 if (ptid_equal (ptid, null_ptid))
7650 ptid = inferior_ptid;
7651
7652 if (status->kind != TARGET_WAITKIND_EXITED
7653 && status->kind != TARGET_WAITKIND_SIGNALLED
7654 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7655 {
7656 /* Expedited registers. */
7657 if (stop_reply->regcache)
7658 {
7659 struct regcache *regcache
7660 = get_thread_arch_regcache (ptid, stop_reply->arch);
7661 cached_reg_t *reg;
7662 int ix;
7663
7664 for (ix = 0;
7665 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7666 ix++)
7667 {
7668 regcache->raw_supply (reg->num, reg->data);
7669 xfree (reg->data);
7670 }
7671
7672 VEC_free (cached_reg_t, stop_reply->regcache);
7673 }
7674
7675 remote_notice_new_inferior (ptid, 0);
7676 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7677 remote_thr->core = stop_reply->core;
7678 remote_thr->stop_reason = stop_reply->stop_reason;
7679 remote_thr->watch_data_address = stop_reply->watch_data_address;
7680 remote_thr->vcont_resumed = 0;
7681 }
7682
7683 stop_reply_xfree (stop_reply);
7684 return ptid;
7685 }
7686
7687 /* The non-stop mode version of target_wait. */
7688
7689 ptid_t
7690 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7691 {
7692 struct remote_state *rs = get_remote_state ();
7693 struct stop_reply *stop_reply;
7694 int ret;
7695 int is_notif = 0;
7696
7697 /* If in non-stop mode, get out of getpkt even if a
7698 notification is received. */
7699
7700 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7701 0 /* forever */, &is_notif);
7702 while (1)
7703 {
7704 if (ret != -1 && !is_notif)
7705 switch (rs->buf[0])
7706 {
7707 case 'E': /* Error of some sort. */
7708 /* We're out of sync with the target now. Did it continue
7709 or not? We can't tell which thread it was in non-stop,
7710 so just ignore this. */
7711 warning (_("Remote failure reply: %s"), rs->buf);
7712 break;
7713 case 'O': /* Console output. */
7714 remote_console_output (rs->buf + 1);
7715 break;
7716 default:
7717 warning (_("Invalid remote reply: %s"), rs->buf);
7718 break;
7719 }
7720
7721 /* Acknowledge a pending stop reply that may have arrived in the
7722 mean time. */
7723 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7724 remote_notif_get_pending_events (&notif_client_stop);
7725
7726 /* If indeed we noticed a stop reply, we're done. */
7727 stop_reply = queued_stop_reply (ptid);
7728 if (stop_reply != NULL)
7729 return process_stop_reply (stop_reply, status);
7730
7731 /* Still no event. If we're just polling for an event, then
7732 return to the event loop. */
7733 if (options & TARGET_WNOHANG)
7734 {
7735 status->kind = TARGET_WAITKIND_IGNORE;
7736 return minus_one_ptid;
7737 }
7738
7739 /* Otherwise do a blocking wait. */
7740 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7741 1 /* forever */, &is_notif);
7742 }
7743 }
7744
7745 /* Wait until the remote machine stops, then return, storing status in
7746 STATUS just as `wait' would. */
7747
7748 ptid_t
7749 remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
7750 {
7751 struct remote_state *rs = get_remote_state ();
7752 ptid_t event_ptid = null_ptid;
7753 char *buf;
7754 struct stop_reply *stop_reply;
7755
7756 again:
7757
7758 status->kind = TARGET_WAITKIND_IGNORE;
7759 status->value.integer = 0;
7760
7761 stop_reply = queued_stop_reply (ptid);
7762 if (stop_reply != NULL)
7763 return process_stop_reply (stop_reply, status);
7764
7765 if (rs->cached_wait_status)
7766 /* Use the cached wait status, but only once. */
7767 rs->cached_wait_status = 0;
7768 else
7769 {
7770 int ret;
7771 int is_notif;
7772 int forever = ((options & TARGET_WNOHANG) == 0
7773 && rs->wait_forever_enabled_p);
7774
7775 if (!rs->waiting_for_stop_reply)
7776 {
7777 status->kind = TARGET_WAITKIND_NO_RESUMED;
7778 return minus_one_ptid;
7779 }
7780
7781 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7782 _never_ wait for ever -> test on target_is_async_p().
7783 However, before we do that we need to ensure that the caller
7784 knows how to take the target into/out of async mode. */
7785 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7786 forever, &is_notif);
7787
7788 /* GDB gets a notification. Return to core as this event is
7789 not interesting. */
7790 if (ret != -1 && is_notif)
7791 return minus_one_ptid;
7792
7793 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7794 return minus_one_ptid;
7795 }
7796
7797 buf = rs->buf;
7798
7799 /* Assume that the target has acknowledged Ctrl-C unless we receive
7800 an 'F' or 'O' packet. */
7801 if (buf[0] != 'F' && buf[0] != 'O')
7802 rs->ctrlc_pending_p = 0;
7803
7804 switch (buf[0])
7805 {
7806 case 'E': /* Error of some sort. */
7807 /* We're out of sync with the target now. Did it continue or
7808 not? Not is more likely, so report a stop. */
7809 rs->waiting_for_stop_reply = 0;
7810
7811 warning (_("Remote failure reply: %s"), buf);
7812 status->kind = TARGET_WAITKIND_STOPPED;
7813 status->value.sig = GDB_SIGNAL_0;
7814 break;
7815 case 'F': /* File-I/O request. */
7816 /* GDB may access the inferior memory while handling the File-I/O
7817 request, but we don't want GDB accessing memory while waiting
7818 for a stop reply. See the comments in putpkt_binary. Set
7819 waiting_for_stop_reply to 0 temporarily. */
7820 rs->waiting_for_stop_reply = 0;
7821 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
7822 rs->ctrlc_pending_p = 0;
7823 /* GDB handled the File-I/O request, and the target is running
7824 again. Keep waiting for events. */
7825 rs->waiting_for_stop_reply = 1;
7826 break;
7827 case 'N': case 'T': case 'S': case 'X': case 'W':
7828 {
7829 struct stop_reply *stop_reply;
7830
7831 /* There is a stop reply to handle. */
7832 rs->waiting_for_stop_reply = 0;
7833
7834 stop_reply
7835 = (struct stop_reply *) remote_notif_parse (this,
7836 &notif_client_stop,
7837 rs->buf);
7838
7839 event_ptid = process_stop_reply (stop_reply, status);
7840 break;
7841 }
7842 case 'O': /* Console output. */
7843 remote_console_output (buf + 1);
7844 break;
7845 case '\0':
7846 if (rs->last_sent_signal != GDB_SIGNAL_0)
7847 {
7848 /* Zero length reply means that we tried 'S' or 'C' and the
7849 remote system doesn't support it. */
7850 target_terminal::ours_for_output ();
7851 printf_filtered
7852 ("Can't send signals to this remote system. %s not sent.\n",
7853 gdb_signal_to_name (rs->last_sent_signal));
7854 rs->last_sent_signal = GDB_SIGNAL_0;
7855 target_terminal::inferior ();
7856
7857 strcpy (buf, rs->last_sent_step ? "s" : "c");
7858 putpkt (buf);
7859 break;
7860 }
7861 /* fallthrough */
7862 default:
7863 warning (_("Invalid remote reply: %s"), buf);
7864 break;
7865 }
7866
7867 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7868 return minus_one_ptid;
7869 else if (status->kind == TARGET_WAITKIND_IGNORE)
7870 {
7871 /* Nothing interesting happened. If we're doing a non-blocking
7872 poll, we're done. Otherwise, go back to waiting. */
7873 if (options & TARGET_WNOHANG)
7874 return minus_one_ptid;
7875 else
7876 goto again;
7877 }
7878 else if (status->kind != TARGET_WAITKIND_EXITED
7879 && status->kind != TARGET_WAITKIND_SIGNALLED)
7880 {
7881 if (!ptid_equal (event_ptid, null_ptid))
7882 record_currthread (rs, event_ptid);
7883 else
7884 event_ptid = inferior_ptid;
7885 }
7886 else
7887 /* A process exit. Invalidate our notion of current thread. */
7888 record_currthread (rs, minus_one_ptid);
7889
7890 return event_ptid;
7891 }
7892
7893 /* Wait until the remote machine stops, then return, storing status in
7894 STATUS just as `wait' would. */
7895
7896 ptid_t
7897 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7898 {
7899 ptid_t event_ptid;
7900
7901 if (target_is_non_stop_p ())
7902 event_ptid = wait_ns (ptid, status, options);
7903 else
7904 event_ptid = wait_as (ptid, status, options);
7905
7906 if (target_is_async_p ())
7907 {
7908 remote_state *rs = get_remote_state ();
7909
7910 /* If there are are events left in the queue tell the event loop
7911 to return here. */
7912 if (!rs->stop_reply_queue.empty ())
7913 mark_async_event_handler (rs->remote_async_inferior_event_token);
7914 }
7915
7916 return event_ptid;
7917 }
7918
7919 /* Fetch a single register using a 'p' packet. */
7920
7921 int
7922 remote_target::fetch_register_using_p (struct regcache *regcache,
7923 packet_reg *reg)
7924 {
7925 struct gdbarch *gdbarch = regcache->arch ();
7926 struct remote_state *rs = get_remote_state ();
7927 char *buf, *p;
7928 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7929 int i;
7930
7931 if (packet_support (PACKET_p) == PACKET_DISABLE)
7932 return 0;
7933
7934 if (reg->pnum == -1)
7935 return 0;
7936
7937 p = rs->buf;
7938 *p++ = 'p';
7939 p += hexnumstr (p, reg->pnum);
7940 *p++ = '\0';
7941 putpkt (rs->buf);
7942 getpkt (&rs->buf, &rs->buf_size, 0);
7943
7944 buf = rs->buf;
7945
7946 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7947 {
7948 case PACKET_OK:
7949 break;
7950 case PACKET_UNKNOWN:
7951 return 0;
7952 case PACKET_ERROR:
7953 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7954 gdbarch_register_name (regcache->arch (),
7955 reg->regnum),
7956 buf);
7957 }
7958
7959 /* If this register is unfetchable, tell the regcache. */
7960 if (buf[0] == 'x')
7961 {
7962 regcache->raw_supply (reg->regnum, NULL);
7963 return 1;
7964 }
7965
7966 /* Otherwise, parse and supply the value. */
7967 p = buf;
7968 i = 0;
7969 while (p[0] != 0)
7970 {
7971 if (p[1] == 0)
7972 error (_("fetch_register_using_p: early buf termination"));
7973
7974 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7975 p += 2;
7976 }
7977 regcache->raw_supply (reg->regnum, regp);
7978 return 1;
7979 }
7980
7981 /* Fetch the registers included in the target's 'g' packet. */
7982
7983 int
7984 remote_target::send_g_packet ()
7985 {
7986 struct remote_state *rs = get_remote_state ();
7987 int buf_len;
7988
7989 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7990 putpkt (rs->buf);
7991 getpkt (&rs->buf, &rs->buf_size, 0);
7992 if (packet_check_result (rs->buf) == PACKET_ERROR)
7993 error (_("Could not read registers; remote failure reply '%s'"),
7994 rs->buf);
7995
7996 /* We can get out of synch in various cases. If the first character
7997 in the buffer is not a hex character, assume that has happened
7998 and try to fetch another packet to read. */
7999 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8000 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8001 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8002 && rs->buf[0] != 'x') /* New: unavailable register value. */
8003 {
8004 if (remote_debug)
8005 fprintf_unfiltered (gdb_stdlog,
8006 "Bad register packet; fetching a new packet\n");
8007 getpkt (&rs->buf, &rs->buf_size, 0);
8008 }
8009
8010 buf_len = strlen (rs->buf);
8011
8012 /* Sanity check the received packet. */
8013 if (buf_len % 2 != 0)
8014 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
8015
8016 return buf_len / 2;
8017 }
8018
8019 void
8020 remote_target::process_g_packet (struct regcache *regcache)
8021 {
8022 struct gdbarch *gdbarch = regcache->arch ();
8023 struct remote_state *rs = get_remote_state ();
8024 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8025 int i, buf_len;
8026 char *p;
8027 char *regs;
8028
8029 buf_len = strlen (rs->buf);
8030
8031 /* Further sanity checks, with knowledge of the architecture. */
8032 if (buf_len > 2 * rsa->sizeof_g_packet)
8033 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8034 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
8035
8036 /* Save the size of the packet sent to us by the target. It is used
8037 as a heuristic when determining the max size of packets that the
8038 target can safely receive. */
8039 if (rsa->actual_register_packet_size == 0)
8040 rsa->actual_register_packet_size = buf_len;
8041
8042 /* If this is smaller than we guessed the 'g' packet would be,
8043 update our records. A 'g' reply that doesn't include a register's
8044 value implies either that the register is not available, or that
8045 the 'p' packet must be used. */
8046 if (buf_len < 2 * rsa->sizeof_g_packet)
8047 {
8048 long sizeof_g_packet = buf_len / 2;
8049
8050 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8051 {
8052 long offset = rsa->regs[i].offset;
8053 long reg_size = register_size (gdbarch, i);
8054
8055 if (rsa->regs[i].pnum == -1)
8056 continue;
8057
8058 if (offset >= sizeof_g_packet)
8059 rsa->regs[i].in_g_packet = 0;
8060 else if (offset + reg_size > sizeof_g_packet)
8061 error (_("Truncated register %d in remote 'g' packet"), i);
8062 else
8063 rsa->regs[i].in_g_packet = 1;
8064 }
8065
8066 /* Looks valid enough, we can assume this is the correct length
8067 for a 'g' packet. It's important not to adjust
8068 rsa->sizeof_g_packet if we have truncated registers otherwise
8069 this "if" won't be run the next time the method is called
8070 with a packet of the same size and one of the internal errors
8071 below will trigger instead. */
8072 rsa->sizeof_g_packet = sizeof_g_packet;
8073 }
8074
8075 regs = (char *) alloca (rsa->sizeof_g_packet);
8076
8077 /* Unimplemented registers read as all bits zero. */
8078 memset (regs, 0, rsa->sizeof_g_packet);
8079
8080 /* Reply describes registers byte by byte, each byte encoded as two
8081 hex characters. Suck them all up, then supply them to the
8082 register cacheing/storage mechanism. */
8083
8084 p = rs->buf;
8085 for (i = 0; i < rsa->sizeof_g_packet; i++)
8086 {
8087 if (p[0] == 0 || p[1] == 0)
8088 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8089 internal_error (__FILE__, __LINE__,
8090 _("unexpected end of 'g' packet reply"));
8091
8092 if (p[0] == 'x' && p[1] == 'x')
8093 regs[i] = 0; /* 'x' */
8094 else
8095 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8096 p += 2;
8097 }
8098
8099 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8100 {
8101 struct packet_reg *r = &rsa->regs[i];
8102 long reg_size = register_size (gdbarch, i);
8103
8104 if (r->in_g_packet)
8105 {
8106 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
8107 /* This shouldn't happen - we adjusted in_g_packet above. */
8108 internal_error (__FILE__, __LINE__,
8109 _("unexpected end of 'g' packet reply"));
8110 else if (rs->buf[r->offset * 2] == 'x')
8111 {
8112 gdb_assert (r->offset * 2 < strlen (rs->buf));
8113 /* The register isn't available, mark it as such (at
8114 the same time setting the value to zero). */
8115 regcache->raw_supply (r->regnum, NULL);
8116 }
8117 else
8118 regcache->raw_supply (r->regnum, regs + r->offset);
8119 }
8120 }
8121 }
8122
8123 void
8124 remote_target::fetch_registers_using_g (struct regcache *regcache)
8125 {
8126 send_g_packet ();
8127 process_g_packet (regcache);
8128 }
8129
8130 /* Make the remote selected traceframe match GDB's selected
8131 traceframe. */
8132
8133 void
8134 remote_target::set_remote_traceframe ()
8135 {
8136 int newnum;
8137 struct remote_state *rs = get_remote_state ();
8138
8139 if (rs->remote_traceframe_number == get_traceframe_number ())
8140 return;
8141
8142 /* Avoid recursion, remote_trace_find calls us again. */
8143 rs->remote_traceframe_number = get_traceframe_number ();
8144
8145 newnum = target_trace_find (tfind_number,
8146 get_traceframe_number (), 0, 0, NULL);
8147
8148 /* Should not happen. If it does, all bets are off. */
8149 if (newnum != get_traceframe_number ())
8150 warning (_("could not set remote traceframe"));
8151 }
8152
8153 void
8154 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8155 {
8156 struct gdbarch *gdbarch = regcache->arch ();
8157 struct remote_state *rs = get_remote_state ();
8158 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8159 int i;
8160
8161 set_remote_traceframe ();
8162 set_general_thread (regcache->ptid ());
8163
8164 if (regnum >= 0)
8165 {
8166 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8167
8168 gdb_assert (reg != NULL);
8169
8170 /* If this register might be in the 'g' packet, try that first -
8171 we are likely to read more than one register. If this is the
8172 first 'g' packet, we might be overly optimistic about its
8173 contents, so fall back to 'p'. */
8174 if (reg->in_g_packet)
8175 {
8176 fetch_registers_using_g (regcache);
8177 if (reg->in_g_packet)
8178 return;
8179 }
8180
8181 if (fetch_register_using_p (regcache, reg))
8182 return;
8183
8184 /* This register is not available. */
8185 regcache->raw_supply (reg->regnum, NULL);
8186
8187 return;
8188 }
8189
8190 fetch_registers_using_g (regcache);
8191
8192 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8193 if (!rsa->regs[i].in_g_packet)
8194 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8195 {
8196 /* This register is not available. */
8197 regcache->raw_supply (i, NULL);
8198 }
8199 }
8200
8201 /* Prepare to store registers. Since we may send them all (using a
8202 'G' request), we have to read out the ones we don't want to change
8203 first. */
8204
8205 void
8206 remote_target::prepare_to_store (struct regcache *regcache)
8207 {
8208 struct remote_state *rs = get_remote_state ();
8209 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8210 int i;
8211
8212 /* Make sure the entire registers array is valid. */
8213 switch (packet_support (PACKET_P))
8214 {
8215 case PACKET_DISABLE:
8216 case PACKET_SUPPORT_UNKNOWN:
8217 /* Make sure all the necessary registers are cached. */
8218 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8219 if (rsa->regs[i].in_g_packet)
8220 regcache->raw_update (rsa->regs[i].regnum);
8221 break;
8222 case PACKET_ENABLE:
8223 break;
8224 }
8225 }
8226
8227 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8228 packet was not recognized. */
8229
8230 int
8231 remote_target::store_register_using_P (const struct regcache *regcache,
8232 packet_reg *reg)
8233 {
8234 struct gdbarch *gdbarch = regcache->arch ();
8235 struct remote_state *rs = get_remote_state ();
8236 /* Try storing a single register. */
8237 char *buf = rs->buf;
8238 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8239 char *p;
8240
8241 if (packet_support (PACKET_P) == PACKET_DISABLE)
8242 return 0;
8243
8244 if (reg->pnum == -1)
8245 return 0;
8246
8247 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8248 p = buf + strlen (buf);
8249 regcache->raw_collect (reg->regnum, regp);
8250 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8251 putpkt (rs->buf);
8252 getpkt (&rs->buf, &rs->buf_size, 0);
8253
8254 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8255 {
8256 case PACKET_OK:
8257 return 1;
8258 case PACKET_ERROR:
8259 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8260 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8261 case PACKET_UNKNOWN:
8262 return 0;
8263 default:
8264 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8265 }
8266 }
8267
8268 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8269 contents of the register cache buffer. FIXME: ignores errors. */
8270
8271 void
8272 remote_target::store_registers_using_G (const struct regcache *regcache)
8273 {
8274 struct remote_state *rs = get_remote_state ();
8275 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8276 gdb_byte *regs;
8277 char *p;
8278
8279 /* Extract all the registers in the regcache copying them into a
8280 local buffer. */
8281 {
8282 int i;
8283
8284 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8285 memset (regs, 0, rsa->sizeof_g_packet);
8286 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8287 {
8288 struct packet_reg *r = &rsa->regs[i];
8289
8290 if (r->in_g_packet)
8291 regcache->raw_collect (r->regnum, regs + r->offset);
8292 }
8293 }
8294
8295 /* Command describes registers byte by byte,
8296 each byte encoded as two hex characters. */
8297 p = rs->buf;
8298 *p++ = 'G';
8299 bin2hex (regs, p, rsa->sizeof_g_packet);
8300 putpkt (rs->buf);
8301 getpkt (&rs->buf, &rs->buf_size, 0);
8302 if (packet_check_result (rs->buf) == PACKET_ERROR)
8303 error (_("Could not write registers; remote failure reply '%s'"),
8304 rs->buf);
8305 }
8306
8307 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8308 of the register cache buffer. FIXME: ignores errors. */
8309
8310 void
8311 remote_target::store_registers (struct regcache *regcache, int regnum)
8312 {
8313 struct gdbarch *gdbarch = regcache->arch ();
8314 struct remote_state *rs = get_remote_state ();
8315 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8316 int i;
8317
8318 set_remote_traceframe ();
8319 set_general_thread (regcache->ptid ());
8320
8321 if (regnum >= 0)
8322 {
8323 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8324
8325 gdb_assert (reg != NULL);
8326
8327 /* Always prefer to store registers using the 'P' packet if
8328 possible; we often change only a small number of registers.
8329 Sometimes we change a larger number; we'd need help from a
8330 higher layer to know to use 'G'. */
8331 if (store_register_using_P (regcache, reg))
8332 return;
8333
8334 /* For now, don't complain if we have no way to write the
8335 register. GDB loses track of unavailable registers too
8336 easily. Some day, this may be an error. We don't have
8337 any way to read the register, either... */
8338 if (!reg->in_g_packet)
8339 return;
8340
8341 store_registers_using_G (regcache);
8342 return;
8343 }
8344
8345 store_registers_using_G (regcache);
8346
8347 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8348 if (!rsa->regs[i].in_g_packet)
8349 if (!store_register_using_P (regcache, &rsa->regs[i]))
8350 /* See above for why we do not issue an error here. */
8351 continue;
8352 }
8353 \f
8354
8355 /* Return the number of hex digits in num. */
8356
8357 static int
8358 hexnumlen (ULONGEST num)
8359 {
8360 int i;
8361
8362 for (i = 0; num != 0; i++)
8363 num >>= 4;
8364
8365 return std::max (i, 1);
8366 }
8367
8368 /* Set BUF to the minimum number of hex digits representing NUM. */
8369
8370 static int
8371 hexnumstr (char *buf, ULONGEST num)
8372 {
8373 int len = hexnumlen (num);
8374
8375 return hexnumnstr (buf, num, len);
8376 }
8377
8378
8379 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8380
8381 static int
8382 hexnumnstr (char *buf, ULONGEST num, int width)
8383 {
8384 int i;
8385
8386 buf[width] = '\0';
8387
8388 for (i = width - 1; i >= 0; i--)
8389 {
8390 buf[i] = "0123456789abcdef"[(num & 0xf)];
8391 num >>= 4;
8392 }
8393
8394 return width;
8395 }
8396
8397 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8398
8399 static CORE_ADDR
8400 remote_address_masked (CORE_ADDR addr)
8401 {
8402 unsigned int address_size = remote_address_size;
8403
8404 /* If "remoteaddresssize" was not set, default to target address size. */
8405 if (!address_size)
8406 address_size = gdbarch_addr_bit (target_gdbarch ());
8407
8408 if (address_size > 0
8409 && address_size < (sizeof (ULONGEST) * 8))
8410 {
8411 /* Only create a mask when that mask can safely be constructed
8412 in a ULONGEST variable. */
8413 ULONGEST mask = 1;
8414
8415 mask = (mask << address_size) - 1;
8416 addr &= mask;
8417 }
8418 return addr;
8419 }
8420
8421 /* Determine whether the remote target supports binary downloading.
8422 This is accomplished by sending a no-op memory write of zero length
8423 to the target at the specified address. It does not suffice to send
8424 the whole packet, since many stubs strip the eighth bit and
8425 subsequently compute a wrong checksum, which causes real havoc with
8426 remote_write_bytes.
8427
8428 NOTE: This can still lose if the serial line is not eight-bit
8429 clean. In cases like this, the user should clear "remote
8430 X-packet". */
8431
8432 void
8433 remote_target::check_binary_download (CORE_ADDR addr)
8434 {
8435 struct remote_state *rs = get_remote_state ();
8436
8437 switch (packet_support (PACKET_X))
8438 {
8439 case PACKET_DISABLE:
8440 break;
8441 case PACKET_ENABLE:
8442 break;
8443 case PACKET_SUPPORT_UNKNOWN:
8444 {
8445 char *p;
8446
8447 p = rs->buf;
8448 *p++ = 'X';
8449 p += hexnumstr (p, (ULONGEST) addr);
8450 *p++ = ',';
8451 p += hexnumstr (p, (ULONGEST) 0);
8452 *p++ = ':';
8453 *p = '\0';
8454
8455 putpkt_binary (rs->buf, (int) (p - rs->buf));
8456 getpkt (&rs->buf, &rs->buf_size, 0);
8457
8458 if (rs->buf[0] == '\0')
8459 {
8460 if (remote_debug)
8461 fprintf_unfiltered (gdb_stdlog,
8462 "binary downloading NOT "
8463 "supported by target\n");
8464 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8465 }
8466 else
8467 {
8468 if (remote_debug)
8469 fprintf_unfiltered (gdb_stdlog,
8470 "binary downloading supported by target\n");
8471 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8472 }
8473 break;
8474 }
8475 }
8476 }
8477
8478 /* Helper function to resize the payload in order to try to get a good
8479 alignment. We try to write an amount of data such that the next write will
8480 start on an address aligned on REMOTE_ALIGN_WRITES. */
8481
8482 static int
8483 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8484 {
8485 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
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 HEADER is the starting part of the packet.
8491 MEMADDR is the address in the remote memory space.
8492 MYADDR is the address of the buffer in our space.
8493 LEN_UNITS is the number of addressable units to write.
8494 UNIT_SIZE is the length in bytes of an addressable unit.
8495 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8496 should send data as binary ('X'), or hex-encoded ('M').
8497
8498 The function creates packet of the form
8499 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8500
8501 where encoding of <DATA> is terminated by PACKET_FORMAT.
8502
8503 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8504 are omitted.
8505
8506 Return the transferred status, error or OK (an
8507 'enum target_xfer_status' value). Save the number of addressable units
8508 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8509
8510 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8511 exchange between gdb and the stub could look like (?? in place of the
8512 checksum):
8513
8514 -> $m1000,4#??
8515 <- aaaabbbbccccdddd
8516
8517 -> $M1000,3:eeeeffffeeee#??
8518 <- OK
8519
8520 -> $m1000,4#??
8521 <- eeeeffffeeeedddd */
8522
8523 target_xfer_status
8524 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8525 const gdb_byte *myaddr,
8526 ULONGEST len_units,
8527 int unit_size,
8528 ULONGEST *xfered_len_units,
8529 char packet_format, int use_length)
8530 {
8531 struct remote_state *rs = get_remote_state ();
8532 char *p;
8533 char *plen = NULL;
8534 int plenlen = 0;
8535 int todo_units;
8536 int units_written;
8537 int payload_capacity_bytes;
8538 int payload_length_bytes;
8539
8540 if (packet_format != 'X' && packet_format != 'M')
8541 internal_error (__FILE__, __LINE__,
8542 _("remote_write_bytes_aux: bad packet format"));
8543
8544 if (len_units == 0)
8545 return TARGET_XFER_EOF;
8546
8547 payload_capacity_bytes = get_memory_write_packet_size ();
8548
8549 /* The packet buffer will be large enough for the payload;
8550 get_memory_packet_size ensures this. */
8551 rs->buf[0] = '\0';
8552
8553 /* Compute the size of the actual payload by subtracting out the
8554 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8555
8556 payload_capacity_bytes -= strlen ("$,:#NN");
8557 if (!use_length)
8558 /* The comma won't be used. */
8559 payload_capacity_bytes += 1;
8560 payload_capacity_bytes -= strlen (header);
8561 payload_capacity_bytes -= hexnumlen (memaddr);
8562
8563 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8564
8565 strcat (rs->buf, header);
8566 p = rs->buf + strlen (header);
8567
8568 /* Compute a best guess of the number of bytes actually transfered. */
8569 if (packet_format == 'X')
8570 {
8571 /* Best guess at number of bytes that will fit. */
8572 todo_units = std::min (len_units,
8573 (ULONGEST) payload_capacity_bytes / unit_size);
8574 if (use_length)
8575 payload_capacity_bytes -= hexnumlen (todo_units);
8576 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8577 }
8578 else
8579 {
8580 /* Number of bytes that will fit. */
8581 todo_units
8582 = std::min (len_units,
8583 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8584 if (use_length)
8585 payload_capacity_bytes -= hexnumlen (todo_units);
8586 todo_units = std::min (todo_units,
8587 (payload_capacity_bytes / unit_size) / 2);
8588 }
8589
8590 if (todo_units <= 0)
8591 internal_error (__FILE__, __LINE__,
8592 _("minimum packet size too small to write data"));
8593
8594 /* If we already need another packet, then try to align the end
8595 of this packet to a useful boundary. */
8596 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8597 todo_units = align_for_efficient_write (todo_units, memaddr);
8598
8599 /* Append "<memaddr>". */
8600 memaddr = remote_address_masked (memaddr);
8601 p += hexnumstr (p, (ULONGEST) memaddr);
8602
8603 if (use_length)
8604 {
8605 /* Append ",". */
8606 *p++ = ',';
8607
8608 /* Append the length and retain its location and size. It may need to be
8609 adjusted once the packet body has been created. */
8610 plen = p;
8611 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8612 p += plenlen;
8613 }
8614
8615 /* Append ":". */
8616 *p++ = ':';
8617 *p = '\0';
8618
8619 /* Append the packet body. */
8620 if (packet_format == 'X')
8621 {
8622 /* Binary mode. Send target system values byte by byte, in
8623 increasing byte addresses. Only escape certain critical
8624 characters. */
8625 payload_length_bytes =
8626 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8627 &units_written, payload_capacity_bytes);
8628
8629 /* If not all TODO units fit, then we'll need another packet. Make
8630 a second try to keep the end of the packet aligned. Don't do
8631 this if the packet is tiny. */
8632 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8633 {
8634 int new_todo_units;
8635
8636 new_todo_units = align_for_efficient_write (units_written, memaddr);
8637
8638 if (new_todo_units != units_written)
8639 payload_length_bytes =
8640 remote_escape_output (myaddr, new_todo_units, unit_size,
8641 (gdb_byte *) p, &units_written,
8642 payload_capacity_bytes);
8643 }
8644
8645 p += payload_length_bytes;
8646 if (use_length && units_written < todo_units)
8647 {
8648 /* Escape chars have filled up the buffer prematurely,
8649 and we have actually sent fewer units than planned.
8650 Fix-up the length field of the packet. Use the same
8651 number of characters as before. */
8652 plen += hexnumnstr (plen, (ULONGEST) units_written,
8653 plenlen);
8654 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8655 }
8656 }
8657 else
8658 {
8659 /* Normal mode: Send target system values byte by byte, in
8660 increasing byte addresses. Each byte is encoded as a two hex
8661 value. */
8662 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8663 units_written = todo_units;
8664 }
8665
8666 putpkt_binary (rs->buf, (int) (p - rs->buf));
8667 getpkt (&rs->buf, &rs->buf_size, 0);
8668
8669 if (rs->buf[0] == 'E')
8670 return TARGET_XFER_E_IO;
8671
8672 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8673 send fewer units than we'd planned. */
8674 *xfered_len_units = (ULONGEST) units_written;
8675 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8676 }
8677
8678 /* Write memory data directly to the remote machine.
8679 This does not inform the data cache; the data cache uses this.
8680 MEMADDR is the address in the remote memory space.
8681 MYADDR is the address of the buffer in our space.
8682 LEN is the number of bytes.
8683
8684 Return the transferred status, error or OK (an
8685 'enum target_xfer_status' value). Save the number of bytes
8686 transferred in *XFERED_LEN. Only transfer a single packet. */
8687
8688 target_xfer_status
8689 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8690 ULONGEST len, int unit_size,
8691 ULONGEST *xfered_len)
8692 {
8693 const char *packet_format = NULL;
8694
8695 /* Check whether the target supports binary download. */
8696 check_binary_download (memaddr);
8697
8698 switch (packet_support (PACKET_X))
8699 {
8700 case PACKET_ENABLE:
8701 packet_format = "X";
8702 break;
8703 case PACKET_DISABLE:
8704 packet_format = "M";
8705 break;
8706 case PACKET_SUPPORT_UNKNOWN:
8707 internal_error (__FILE__, __LINE__,
8708 _("remote_write_bytes: bad internal state"));
8709 default:
8710 internal_error (__FILE__, __LINE__, _("bad switch"));
8711 }
8712
8713 return remote_write_bytes_aux (packet_format,
8714 memaddr, myaddr, len, unit_size, xfered_len,
8715 packet_format[0], 1);
8716 }
8717
8718 /* Read memory data directly from the remote machine.
8719 This does not use the data cache; the data cache uses this.
8720 MEMADDR is the address in the remote memory space.
8721 MYADDR is the address of the buffer in our space.
8722 LEN_UNITS is the number of addressable memory units to read..
8723 UNIT_SIZE is the length in bytes of an addressable unit.
8724
8725 Return the transferred status, error or OK (an
8726 'enum target_xfer_status' value). Save the number of bytes
8727 transferred in *XFERED_LEN_UNITS.
8728
8729 See the comment of remote_write_bytes_aux for an example of
8730 memory read/write exchange between gdb and the stub. */
8731
8732 target_xfer_status
8733 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8734 ULONGEST len_units,
8735 int unit_size, ULONGEST *xfered_len_units)
8736 {
8737 struct remote_state *rs = get_remote_state ();
8738 int buf_size_bytes; /* Max size of packet output buffer. */
8739 char *p;
8740 int todo_units;
8741 int decoded_bytes;
8742
8743 buf_size_bytes = get_memory_read_packet_size ();
8744 /* The packet buffer will be large enough for the payload;
8745 get_memory_packet_size ensures this. */
8746
8747 /* Number of units that will fit. */
8748 todo_units = std::min (len_units,
8749 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8750
8751 /* Construct "m"<memaddr>","<len>". */
8752 memaddr = remote_address_masked (memaddr);
8753 p = rs->buf;
8754 *p++ = 'm';
8755 p += hexnumstr (p, (ULONGEST) memaddr);
8756 *p++ = ',';
8757 p += hexnumstr (p, (ULONGEST) todo_units);
8758 *p = '\0';
8759 putpkt (rs->buf);
8760 getpkt (&rs->buf, &rs->buf_size, 0);
8761 if (rs->buf[0] == 'E'
8762 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8763 && rs->buf[3] == '\0')
8764 return TARGET_XFER_E_IO;
8765 /* Reply describes memory byte by byte, each byte encoded as two hex
8766 characters. */
8767 p = rs->buf;
8768 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8769 /* Return what we have. Let higher layers handle partial reads. */
8770 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8771 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8772 }
8773
8774 /* Using the set of read-only target sections of remote, read live
8775 read-only memory.
8776
8777 For interface/parameters/return description see target.h,
8778 to_xfer_partial. */
8779
8780 target_xfer_status
8781 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8782 ULONGEST memaddr,
8783 ULONGEST len,
8784 int unit_size,
8785 ULONGEST *xfered_len)
8786 {
8787 struct target_section *secp;
8788 struct target_section_table *table;
8789
8790 secp = target_section_by_addr (this, memaddr);
8791 if (secp != NULL
8792 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8793 secp->the_bfd_section)
8794 & SEC_READONLY))
8795 {
8796 struct target_section *p;
8797 ULONGEST memend = memaddr + len;
8798
8799 table = target_get_section_table (this);
8800
8801 for (p = table->sections; p < table->sections_end; p++)
8802 {
8803 if (memaddr >= p->addr)
8804 {
8805 if (memend <= p->endaddr)
8806 {
8807 /* Entire transfer is within this section. */
8808 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8809 xfered_len);
8810 }
8811 else if (memaddr >= p->endaddr)
8812 {
8813 /* This section ends before the transfer starts. */
8814 continue;
8815 }
8816 else
8817 {
8818 /* This section overlaps the transfer. Just do half. */
8819 len = p->endaddr - memaddr;
8820 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8821 xfered_len);
8822 }
8823 }
8824 }
8825 }
8826
8827 return TARGET_XFER_EOF;
8828 }
8829
8830 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8831 first if the requested memory is unavailable in traceframe.
8832 Otherwise, fall back to remote_read_bytes_1. */
8833
8834 target_xfer_status
8835 remote_target::remote_read_bytes (CORE_ADDR memaddr,
8836 gdb_byte *myaddr, ULONGEST len, int unit_size,
8837 ULONGEST *xfered_len)
8838 {
8839 if (len == 0)
8840 return TARGET_XFER_EOF;
8841
8842 if (get_traceframe_number () != -1)
8843 {
8844 std::vector<mem_range> available;
8845
8846 /* If we fail to get the set of available memory, then the
8847 target does not support querying traceframe info, and so we
8848 attempt reading from the traceframe anyway (assuming the
8849 target implements the old QTro packet then). */
8850 if (traceframe_available_memory (&available, memaddr, len))
8851 {
8852 if (available.empty () || available[0].start != memaddr)
8853 {
8854 enum target_xfer_status res;
8855
8856 /* Don't read into the traceframe's available
8857 memory. */
8858 if (!available.empty ())
8859 {
8860 LONGEST oldlen = len;
8861
8862 len = available[0].start - memaddr;
8863 gdb_assert (len <= oldlen);
8864 }
8865
8866 /* This goes through the topmost target again. */
8867 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
8868 len, unit_size, xfered_len);
8869 if (res == TARGET_XFER_OK)
8870 return TARGET_XFER_OK;
8871 else
8872 {
8873 /* No use trying further, we know some memory starting
8874 at MEMADDR isn't available. */
8875 *xfered_len = len;
8876 return (*xfered_len != 0) ?
8877 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8878 }
8879 }
8880
8881 /* Don't try to read more than how much is available, in
8882 case the target implements the deprecated QTro packet to
8883 cater for older GDBs (the target's knowledge of read-only
8884 sections may be outdated by now). */
8885 len = available[0].length;
8886 }
8887 }
8888
8889 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8890 }
8891
8892 \f
8893
8894 /* Sends a packet with content determined by the printf format string
8895 FORMAT and the remaining arguments, then gets the reply. Returns
8896 whether the packet was a success, a failure, or unknown. */
8897
8898 packet_result
8899 remote_target::remote_send_printf (const char *format, ...)
8900 {
8901 struct remote_state *rs = get_remote_state ();
8902 int max_size = get_remote_packet_size ();
8903 va_list ap;
8904
8905 va_start (ap, format);
8906
8907 rs->buf[0] = '\0';
8908 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8909 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8910
8911 if (putpkt (rs->buf) < 0)
8912 error (_("Communication problem with target."));
8913
8914 rs->buf[0] = '\0';
8915 getpkt (&rs->buf, &rs->buf_size, 0);
8916
8917 return packet_check_result (rs->buf);
8918 }
8919
8920 /* Flash writing can take quite some time. We'll set
8921 effectively infinite timeout for flash operations.
8922 In future, we'll need to decide on a better approach. */
8923 static const int remote_flash_timeout = 1000;
8924
8925 void
8926 remote_target::flash_erase (ULONGEST address, LONGEST length)
8927 {
8928 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8929 enum packet_result ret;
8930 scoped_restore restore_timeout
8931 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8932
8933 ret = remote_send_printf ("vFlashErase:%s,%s",
8934 phex (address, addr_size),
8935 phex (length, 4));
8936 switch (ret)
8937 {
8938 case PACKET_UNKNOWN:
8939 error (_("Remote target does not support flash erase"));
8940 case PACKET_ERROR:
8941 error (_("Error erasing flash with vFlashErase packet"));
8942 default:
8943 break;
8944 }
8945 }
8946
8947 target_xfer_status
8948 remote_target::remote_flash_write (ULONGEST address,
8949 ULONGEST length, ULONGEST *xfered_len,
8950 const gdb_byte *data)
8951 {
8952 scoped_restore restore_timeout
8953 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8954 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8955 xfered_len,'X', 0);
8956 }
8957
8958 void
8959 remote_target::flash_done ()
8960 {
8961 int ret;
8962
8963 scoped_restore restore_timeout
8964 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8965
8966 ret = remote_send_printf ("vFlashDone");
8967
8968 switch (ret)
8969 {
8970 case PACKET_UNKNOWN:
8971 error (_("Remote target does not support vFlashDone"));
8972 case PACKET_ERROR:
8973 error (_("Error finishing flash operation"));
8974 default:
8975 break;
8976 }
8977 }
8978
8979 void
8980 remote_target::files_info ()
8981 {
8982 puts_filtered ("Debugging a target over a serial line.\n");
8983 }
8984 \f
8985 /* Stuff for dealing with the packets which are part of this protocol.
8986 See comment at top of file for details. */
8987
8988 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8989 error to higher layers. Called when a serial error is detected.
8990 The exception message is STRING, followed by a colon and a blank,
8991 the system error message for errno at function entry and final dot
8992 for output compatibility with throw_perror_with_name. */
8993
8994 static void
8995 unpush_and_perror (const char *string)
8996 {
8997 int saved_errno = errno;
8998
8999 remote_unpush_target ();
9000 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9001 safe_strerror (saved_errno));
9002 }
9003
9004 /* Read a single character from the remote end. The current quit
9005 handler is overridden to avoid quitting in the middle of packet
9006 sequence, as that would break communication with the remote server.
9007 See remote_serial_quit_handler for more detail. */
9008
9009 int
9010 remote_target::readchar (int timeout)
9011 {
9012 int ch;
9013 struct remote_state *rs = get_remote_state ();
9014
9015 {
9016 scoped_restore restore_quit_target
9017 = make_scoped_restore (&curr_quit_handler_target, this);
9018 scoped_restore restore_quit
9019 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9020
9021 rs->got_ctrlc_during_io = 0;
9022
9023 ch = serial_readchar (rs->remote_desc, timeout);
9024
9025 if (rs->got_ctrlc_during_io)
9026 set_quit_flag ();
9027 }
9028
9029 if (ch >= 0)
9030 return ch;
9031
9032 switch ((enum serial_rc) ch)
9033 {
9034 case SERIAL_EOF:
9035 remote_unpush_target ();
9036 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9037 /* no return */
9038 case SERIAL_ERROR:
9039 unpush_and_perror (_("Remote communication error. "
9040 "Target disconnected."));
9041 /* no return */
9042 case SERIAL_TIMEOUT:
9043 break;
9044 }
9045 return ch;
9046 }
9047
9048 /* Wrapper for serial_write that closes the target and throws if
9049 writing fails. The current quit handler is overridden to avoid
9050 quitting in the middle of packet sequence, as that would break
9051 communication with the remote server. See
9052 remote_serial_quit_handler for more detail. */
9053
9054 void
9055 remote_target::remote_serial_write (const char *str, int len)
9056 {
9057 struct remote_state *rs = get_remote_state ();
9058
9059 scoped_restore restore_quit_target
9060 = make_scoped_restore (&curr_quit_handler_target, this);
9061 scoped_restore restore_quit
9062 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9063
9064 rs->got_ctrlc_during_io = 0;
9065
9066 if (serial_write (rs->remote_desc, str, len))
9067 {
9068 unpush_and_perror (_("Remote communication error. "
9069 "Target disconnected."));
9070 }
9071
9072 if (rs->got_ctrlc_during_io)
9073 set_quit_flag ();
9074 }
9075
9076 /* Return a string representing an escaped version of BUF, of len N.
9077 E.g. \n is converted to \\n, \t to \\t, etc. */
9078
9079 static std::string
9080 escape_buffer (const char *buf, int n)
9081 {
9082 string_file stb;
9083
9084 stb.putstrn (buf, n, '\\');
9085 return std::move (stb.string ());
9086 }
9087
9088 /* Display a null-terminated packet on stdout, for debugging, using C
9089 string notation. */
9090
9091 static void
9092 print_packet (const char *buf)
9093 {
9094 puts_filtered ("\"");
9095 fputstr_filtered (buf, '"', gdb_stdout);
9096 puts_filtered ("\"");
9097 }
9098
9099 int
9100 remote_target::putpkt (const char *buf)
9101 {
9102 return putpkt_binary (buf, strlen (buf));
9103 }
9104
9105 /* Wrapper around remote_target::putpkt to avoid exporting
9106 remote_target. */
9107
9108 int
9109 putpkt (remote_target *remote, const char *buf)
9110 {
9111 return remote->putpkt (buf);
9112 }
9113
9114 /* Send a packet to the remote machine, with error checking. The data
9115 of the packet is in BUF. The string in BUF can be at most
9116 get_remote_packet_size () - 5 to account for the $, # and checksum,
9117 and for a possible /0 if we are debugging (remote_debug) and want
9118 to print the sent packet as a string. */
9119
9120 int
9121 remote_target::putpkt_binary (const char *buf, int cnt)
9122 {
9123 struct remote_state *rs = get_remote_state ();
9124 int i;
9125 unsigned char csum = 0;
9126 gdb::def_vector<char> data (cnt + 6);
9127 char *buf2 = data.data ();
9128
9129 int ch;
9130 int tcount = 0;
9131 char *p;
9132
9133 /* Catch cases like trying to read memory or listing threads while
9134 we're waiting for a stop reply. The remote server wouldn't be
9135 ready to handle this request, so we'd hang and timeout. We don't
9136 have to worry about this in synchronous mode, because in that
9137 case it's not possible to issue a command while the target is
9138 running. This is not a problem in non-stop mode, because in that
9139 case, the stub is always ready to process serial input. */
9140 if (!target_is_non_stop_p ()
9141 && target_is_async_p ()
9142 && rs->waiting_for_stop_reply)
9143 {
9144 error (_("Cannot execute this command while the target is running.\n"
9145 "Use the \"interrupt\" command to stop the target\n"
9146 "and then try again."));
9147 }
9148
9149 /* We're sending out a new packet. Make sure we don't look at a
9150 stale cached response. */
9151 rs->cached_wait_status = 0;
9152
9153 /* Copy the packet into buffer BUF2, encapsulating it
9154 and giving it a checksum. */
9155
9156 p = buf2;
9157 *p++ = '$';
9158
9159 for (i = 0; i < cnt; i++)
9160 {
9161 csum += buf[i];
9162 *p++ = buf[i];
9163 }
9164 *p++ = '#';
9165 *p++ = tohex ((csum >> 4) & 0xf);
9166 *p++ = tohex (csum & 0xf);
9167
9168 /* Send it over and over until we get a positive ack. */
9169
9170 while (1)
9171 {
9172 int started_error_output = 0;
9173
9174 if (remote_debug)
9175 {
9176 *p = '\0';
9177
9178 int len = (int) (p - buf2);
9179
9180 std::string str
9181 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9182
9183 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9184
9185 if (len > REMOTE_DEBUG_MAX_CHAR)
9186 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9187 len - REMOTE_DEBUG_MAX_CHAR);
9188
9189 fprintf_unfiltered (gdb_stdlog, "...");
9190
9191 gdb_flush (gdb_stdlog);
9192 }
9193 remote_serial_write (buf2, p - buf2);
9194
9195 /* If this is a no acks version of the remote protocol, send the
9196 packet and move on. */
9197 if (rs->noack_mode)
9198 break;
9199
9200 /* Read until either a timeout occurs (-2) or '+' is read.
9201 Handle any notification that arrives in the mean time. */
9202 while (1)
9203 {
9204 ch = readchar (remote_timeout);
9205
9206 if (remote_debug)
9207 {
9208 switch (ch)
9209 {
9210 case '+':
9211 case '-':
9212 case SERIAL_TIMEOUT:
9213 case '$':
9214 case '%':
9215 if (started_error_output)
9216 {
9217 putchar_unfiltered ('\n');
9218 started_error_output = 0;
9219 }
9220 }
9221 }
9222
9223 switch (ch)
9224 {
9225 case '+':
9226 if (remote_debug)
9227 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9228 return 1;
9229 case '-':
9230 if (remote_debug)
9231 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9232 /* FALLTHROUGH */
9233 case SERIAL_TIMEOUT:
9234 tcount++;
9235 if (tcount > 3)
9236 return 0;
9237 break; /* Retransmit buffer. */
9238 case '$':
9239 {
9240 if (remote_debug)
9241 fprintf_unfiltered (gdb_stdlog,
9242 "Packet instead of Ack, ignoring it\n");
9243 /* It's probably an old response sent because an ACK
9244 was lost. Gobble up the packet and ack it so it
9245 doesn't get retransmitted when we resend this
9246 packet. */
9247 skip_frame ();
9248 remote_serial_write ("+", 1);
9249 continue; /* Now, go look for +. */
9250 }
9251
9252 case '%':
9253 {
9254 int val;
9255
9256 /* If we got a notification, handle it, and go back to looking
9257 for an ack. */
9258 /* We've found the start of a notification. Now
9259 collect the data. */
9260 val = read_frame (&rs->buf, &rs->buf_size);
9261 if (val >= 0)
9262 {
9263 if (remote_debug)
9264 {
9265 std::string str = escape_buffer (rs->buf, val);
9266
9267 fprintf_unfiltered (gdb_stdlog,
9268 " Notification received: %s\n",
9269 str.c_str ());
9270 }
9271 handle_notification (rs->notif_state, rs->buf);
9272 /* We're in sync now, rewait for the ack. */
9273 tcount = 0;
9274 }
9275 else
9276 {
9277 if (remote_debug)
9278 {
9279 if (!started_error_output)
9280 {
9281 started_error_output = 1;
9282 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9283 }
9284 fputc_unfiltered (ch & 0177, gdb_stdlog);
9285 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9286 }
9287 }
9288 continue;
9289 }
9290 /* fall-through */
9291 default:
9292 if (remote_debug)
9293 {
9294 if (!started_error_output)
9295 {
9296 started_error_output = 1;
9297 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9298 }
9299 fputc_unfiltered (ch & 0177, gdb_stdlog);
9300 }
9301 continue;
9302 }
9303 break; /* Here to retransmit. */
9304 }
9305
9306 #if 0
9307 /* This is wrong. If doing a long backtrace, the user should be
9308 able to get out next time we call QUIT, without anything as
9309 violent as interrupt_query. If we want to provide a way out of
9310 here without getting to the next QUIT, it should be based on
9311 hitting ^C twice as in remote_wait. */
9312 if (quit_flag)
9313 {
9314 quit_flag = 0;
9315 interrupt_query ();
9316 }
9317 #endif
9318 }
9319
9320 return 0;
9321 }
9322
9323 /* Come here after finding the start of a frame when we expected an
9324 ack. Do our best to discard the rest of this packet. */
9325
9326 void
9327 remote_target::skip_frame ()
9328 {
9329 int c;
9330
9331 while (1)
9332 {
9333 c = readchar (remote_timeout);
9334 switch (c)
9335 {
9336 case SERIAL_TIMEOUT:
9337 /* Nothing we can do. */
9338 return;
9339 case '#':
9340 /* Discard the two bytes of checksum and stop. */
9341 c = readchar (remote_timeout);
9342 if (c >= 0)
9343 c = readchar (remote_timeout);
9344
9345 return;
9346 case '*': /* Run length encoding. */
9347 /* Discard the repeat count. */
9348 c = readchar (remote_timeout);
9349 if (c < 0)
9350 return;
9351 break;
9352 default:
9353 /* A regular character. */
9354 break;
9355 }
9356 }
9357 }
9358
9359 /* Come here after finding the start of the frame. Collect the rest
9360 into *BUF, verifying the checksum, length, and handling run-length
9361 compression. NUL terminate the buffer. If there is not enough room,
9362 expand *BUF using xrealloc.
9363
9364 Returns -1 on error, number of characters in buffer (ignoring the
9365 trailing NULL) on success. (could be extended to return one of the
9366 SERIAL status indications). */
9367
9368 long
9369 remote_target::read_frame (char **buf_p, long *sizeof_buf)
9370 {
9371 unsigned char csum;
9372 long bc;
9373 int c;
9374 char *buf = *buf_p;
9375 struct remote_state *rs = get_remote_state ();
9376
9377 csum = 0;
9378 bc = 0;
9379
9380 while (1)
9381 {
9382 c = readchar (remote_timeout);
9383 switch (c)
9384 {
9385 case SERIAL_TIMEOUT:
9386 if (remote_debug)
9387 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9388 return -1;
9389 case '$':
9390 if (remote_debug)
9391 fputs_filtered ("Saw new packet start in middle of old one\n",
9392 gdb_stdlog);
9393 return -1; /* Start a new packet, count retries. */
9394 case '#':
9395 {
9396 unsigned char pktcsum;
9397 int check_0 = 0;
9398 int check_1 = 0;
9399
9400 buf[bc] = '\0';
9401
9402 check_0 = readchar (remote_timeout);
9403 if (check_0 >= 0)
9404 check_1 = readchar (remote_timeout);
9405
9406 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9407 {
9408 if (remote_debug)
9409 fputs_filtered ("Timeout in checksum, retrying\n",
9410 gdb_stdlog);
9411 return -1;
9412 }
9413 else if (check_0 < 0 || check_1 < 0)
9414 {
9415 if (remote_debug)
9416 fputs_filtered ("Communication error in checksum\n",
9417 gdb_stdlog);
9418 return -1;
9419 }
9420
9421 /* Don't recompute the checksum; with no ack packets we
9422 don't have any way to indicate a packet retransmission
9423 is necessary. */
9424 if (rs->noack_mode)
9425 return bc;
9426
9427 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9428 if (csum == pktcsum)
9429 return bc;
9430
9431 if (remote_debug)
9432 {
9433 std::string str = escape_buffer (buf, bc);
9434
9435 fprintf_unfiltered (gdb_stdlog,
9436 "Bad checksum, sentsum=0x%x, "
9437 "csum=0x%x, buf=%s\n",
9438 pktcsum, csum, str.c_str ());
9439 }
9440 /* Number of characters in buffer ignoring trailing
9441 NULL. */
9442 return -1;
9443 }
9444 case '*': /* Run length encoding. */
9445 {
9446 int repeat;
9447
9448 csum += c;
9449 c = readchar (remote_timeout);
9450 csum += c;
9451 repeat = c - ' ' + 3; /* Compute repeat count. */
9452
9453 /* The character before ``*'' is repeated. */
9454
9455 if (repeat > 0 && repeat <= 255 && bc > 0)
9456 {
9457 if (bc + repeat - 1 >= *sizeof_buf - 1)
9458 {
9459 /* Make some more room in the buffer. */
9460 *sizeof_buf += repeat;
9461 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9462 buf = *buf_p;
9463 }
9464
9465 memset (&buf[bc], buf[bc - 1], repeat);
9466 bc += repeat;
9467 continue;
9468 }
9469
9470 buf[bc] = '\0';
9471 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9472 return -1;
9473 }
9474 default:
9475 if (bc >= *sizeof_buf - 1)
9476 {
9477 /* Make some more room in the buffer. */
9478 *sizeof_buf *= 2;
9479 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9480 buf = *buf_p;
9481 }
9482
9483 buf[bc++] = c;
9484 csum += c;
9485 continue;
9486 }
9487 }
9488 }
9489
9490 /* Read a packet from the remote machine, with error checking, and
9491 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9492 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9493 rather than timing out; this is used (in synchronous mode) to wait
9494 for a target that is is executing user code to stop. */
9495 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9496 don't have to change all the calls to getpkt to deal with the
9497 return value, because at the moment I don't know what the right
9498 thing to do it for those. */
9499
9500 void
9501 remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
9502 {
9503 getpkt_sane (buf, sizeof_buf, forever);
9504 }
9505
9506
9507 /* Read a packet from the remote machine, with error checking, and
9508 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9509 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9510 rather than timing out; this is used (in synchronous mode) to wait
9511 for a target that is is executing user code to stop. If FOREVER ==
9512 0, this function is allowed to time out gracefully and return an
9513 indication of this to the caller. Otherwise return the number of
9514 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9515 enough reason to return to the caller. *IS_NOTIF is an output
9516 boolean that indicates whether *BUF holds a notification or not
9517 (a regular packet). */
9518
9519 int
9520 remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9521 int forever, int expecting_notif,
9522 int *is_notif)
9523 {
9524 struct remote_state *rs = get_remote_state ();
9525 int c;
9526 int tries;
9527 int timeout;
9528 int val = -1;
9529
9530 /* We're reading a new response. Make sure we don't look at a
9531 previously cached response. */
9532 rs->cached_wait_status = 0;
9533
9534 strcpy (*buf, "timeout");
9535
9536 if (forever)
9537 timeout = watchdog > 0 ? watchdog : -1;
9538 else if (expecting_notif)
9539 timeout = 0; /* There should already be a char in the buffer. If
9540 not, bail out. */
9541 else
9542 timeout = remote_timeout;
9543
9544 #define MAX_TRIES 3
9545
9546 /* Process any number of notifications, and then return when
9547 we get a packet. */
9548 for (;;)
9549 {
9550 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9551 times. */
9552 for (tries = 1; tries <= MAX_TRIES; tries++)
9553 {
9554 /* This can loop forever if the remote side sends us
9555 characters continuously, but if it pauses, we'll get
9556 SERIAL_TIMEOUT from readchar because of timeout. Then
9557 we'll count that as a retry.
9558
9559 Note that even when forever is set, we will only wait
9560 forever prior to the start of a packet. After that, we
9561 expect characters to arrive at a brisk pace. They should
9562 show up within remote_timeout intervals. */
9563 do
9564 c = readchar (timeout);
9565 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9566
9567 if (c == SERIAL_TIMEOUT)
9568 {
9569 if (expecting_notif)
9570 return -1; /* Don't complain, it's normal to not get
9571 anything in this case. */
9572
9573 if (forever) /* Watchdog went off? Kill the target. */
9574 {
9575 remote_unpush_target ();
9576 throw_error (TARGET_CLOSE_ERROR,
9577 _("Watchdog timeout has expired. "
9578 "Target detached."));
9579 }
9580 if (remote_debug)
9581 fputs_filtered ("Timed out.\n", gdb_stdlog);
9582 }
9583 else
9584 {
9585 /* We've found the start of a packet or notification.
9586 Now collect the data. */
9587 val = read_frame (buf, sizeof_buf);
9588 if (val >= 0)
9589 break;
9590 }
9591
9592 remote_serial_write ("-", 1);
9593 }
9594
9595 if (tries > MAX_TRIES)
9596 {
9597 /* We have tried hard enough, and just can't receive the
9598 packet/notification. Give up. */
9599 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9600
9601 /* Skip the ack char if we're in no-ack mode. */
9602 if (!rs->noack_mode)
9603 remote_serial_write ("+", 1);
9604 return -1;
9605 }
9606
9607 /* If we got an ordinary packet, return that to our caller. */
9608 if (c == '$')
9609 {
9610 if (remote_debug)
9611 {
9612 std::string str
9613 = escape_buffer (*buf,
9614 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9615
9616 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9617 str.c_str ());
9618
9619 if (val > REMOTE_DEBUG_MAX_CHAR)
9620 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9621 val - REMOTE_DEBUG_MAX_CHAR);
9622
9623 fprintf_unfiltered (gdb_stdlog, "\n");
9624 }
9625
9626 /* Skip the ack char if we're in no-ack mode. */
9627 if (!rs->noack_mode)
9628 remote_serial_write ("+", 1);
9629 if (is_notif != NULL)
9630 *is_notif = 0;
9631 return val;
9632 }
9633
9634 /* If we got a notification, handle it, and go back to looking
9635 for a packet. */
9636 else
9637 {
9638 gdb_assert (c == '%');
9639
9640 if (remote_debug)
9641 {
9642 std::string str = escape_buffer (*buf, val);
9643
9644 fprintf_unfiltered (gdb_stdlog,
9645 " Notification received: %s\n",
9646 str.c_str ());
9647 }
9648 if (is_notif != NULL)
9649 *is_notif = 1;
9650
9651 handle_notification (rs->notif_state, *buf);
9652
9653 /* Notifications require no acknowledgement. */
9654
9655 if (expecting_notif)
9656 return val;
9657 }
9658 }
9659 }
9660
9661 int
9662 remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
9663 {
9664 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9665 }
9666
9667 int
9668 remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9669 int *is_notif)
9670 {
9671 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9672 is_notif);
9673 }
9674
9675 /* Kill any new fork children of process PID that haven't been
9676 processed by follow_fork. */
9677
9678 void
9679 remote_target::kill_new_fork_children (int pid)
9680 {
9681 remote_state *rs = get_remote_state ();
9682 struct thread_info *thread;
9683 struct notif_client *notif = &notif_client_stop;
9684
9685 /* Kill the fork child threads of any threads in process PID
9686 that are stopped at a fork event. */
9687 ALL_NON_EXITED_THREADS (thread)
9688 {
9689 struct target_waitstatus *ws = &thread->pending_follow;
9690
9691 if (is_pending_fork_parent (ws, pid, thread->ptid))
9692 {
9693 int child_pid = ws->value.related_pid.pid ();
9694 int res;
9695
9696 res = remote_vkill (child_pid);
9697 if (res != 0)
9698 error (_("Can't kill fork child process %d"), child_pid);
9699 }
9700 }
9701
9702 /* Check for any pending fork events (not reported or processed yet)
9703 in process PID and kill those fork child threads as well. */
9704 remote_notif_get_pending_events (notif);
9705 for (auto &event : rs->stop_reply_queue)
9706 if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9707 {
9708 int child_pid = event->ws.value.related_pid.pid ();
9709 int res;
9710
9711 res = remote_vkill (child_pid);
9712 if (res != 0)
9713 error (_("Can't kill fork child process %d"), child_pid);
9714 }
9715 }
9716
9717 \f
9718 /* Target hook to kill the current inferior. */
9719
9720 void
9721 remote_target::kill ()
9722 {
9723 int res = -1;
9724 int pid = ptid_get_pid (inferior_ptid);
9725 struct remote_state *rs = get_remote_state ();
9726
9727 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9728 {
9729 /* If we're stopped while forking and we haven't followed yet,
9730 kill the child task. We need to do this before killing the
9731 parent task because if this is a vfork then the parent will
9732 be sleeping. */
9733 kill_new_fork_children (pid);
9734
9735 res = remote_vkill (pid);
9736 if (res == 0)
9737 {
9738 target_mourn_inferior (inferior_ptid);
9739 return;
9740 }
9741 }
9742
9743 /* If we are in 'target remote' mode and we are killing the only
9744 inferior, then we will tell gdbserver to exit and unpush the
9745 target. */
9746 if (res == -1 && !remote_multi_process_p (rs)
9747 && number_of_live_inferiors () == 1)
9748 {
9749 remote_kill_k ();
9750
9751 /* We've killed the remote end, we get to mourn it. If we are
9752 not in extended mode, mourning the inferior also unpushes
9753 remote_ops from the target stack, which closes the remote
9754 connection. */
9755 target_mourn_inferior (inferior_ptid);
9756
9757 return;
9758 }
9759
9760 error (_("Can't kill process"));
9761 }
9762
9763 /* Send a kill request to the target using the 'vKill' packet. */
9764
9765 int
9766 remote_target::remote_vkill (int pid)
9767 {
9768 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9769 return -1;
9770
9771 remote_state *rs = get_remote_state ();
9772
9773 /* Tell the remote target to detach. */
9774 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9775 putpkt (rs->buf);
9776 getpkt (&rs->buf, &rs->buf_size, 0);
9777
9778 switch (packet_ok (rs->buf,
9779 &remote_protocol_packets[PACKET_vKill]))
9780 {
9781 case PACKET_OK:
9782 return 0;
9783 case PACKET_ERROR:
9784 return 1;
9785 case PACKET_UNKNOWN:
9786 return -1;
9787 default:
9788 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9789 }
9790 }
9791
9792 /* Send a kill request to the target using the 'k' packet. */
9793
9794 void
9795 remote_target::remote_kill_k ()
9796 {
9797 /* Catch errors so the user can quit from gdb even when we
9798 aren't on speaking terms with the remote system. */
9799 TRY
9800 {
9801 putpkt ("k");
9802 }
9803 CATCH (ex, RETURN_MASK_ERROR)
9804 {
9805 if (ex.error == TARGET_CLOSE_ERROR)
9806 {
9807 /* If we got an (EOF) error that caused the target
9808 to go away, then we're done, that's what we wanted.
9809 "k" is susceptible to cause a premature EOF, given
9810 that the remote server isn't actually required to
9811 reply to "k", and it can happen that it doesn't
9812 even get to reply ACK to the "k". */
9813 return;
9814 }
9815
9816 /* Otherwise, something went wrong. We didn't actually kill
9817 the target. Just propagate the exception, and let the
9818 user or higher layers decide what to do. */
9819 throw_exception (ex);
9820 }
9821 END_CATCH
9822 }
9823
9824 void
9825 remote_target::mourn_inferior ()
9826 {
9827 struct remote_state *rs = get_remote_state ();
9828
9829 /* We're no longer interested in notification events of an inferior
9830 that exited or was killed/detached. */
9831 discard_pending_stop_replies (current_inferior ());
9832
9833 /* In 'target remote' mode with one inferior, we close the connection. */
9834 if (!rs->extended && number_of_live_inferiors () <= 1)
9835 {
9836 unpush_target (this);
9837
9838 /* remote_close takes care of doing most of the clean up. */
9839 generic_mourn_inferior ();
9840 return;
9841 }
9842
9843 /* In case we got here due to an error, but we're going to stay
9844 connected. */
9845 rs->waiting_for_stop_reply = 0;
9846
9847 /* If the current general thread belonged to the process we just
9848 detached from or has exited, the remote side current general
9849 thread becomes undefined. Considering a case like this:
9850
9851 - We just got here due to a detach.
9852 - The process that we're detaching from happens to immediately
9853 report a global breakpoint being hit in non-stop mode, in the
9854 same thread we had selected before.
9855 - GDB attaches to this process again.
9856 - This event happens to be the next event we handle.
9857
9858 GDB would consider that the current general thread didn't need to
9859 be set on the stub side (with Hg), since for all it knew,
9860 GENERAL_THREAD hadn't changed.
9861
9862 Notice that although in all-stop mode, the remote server always
9863 sets the current thread to the thread reporting the stop event,
9864 that doesn't happen in non-stop mode; in non-stop, the stub *must
9865 not* change the current thread when reporting a breakpoint hit,
9866 due to the decoupling of event reporting and event handling.
9867
9868 To keep things simple, we always invalidate our notion of the
9869 current thread. */
9870 record_currthread (rs, minus_one_ptid);
9871
9872 /* Call common code to mark the inferior as not running. */
9873 generic_mourn_inferior ();
9874
9875 if (!have_inferiors ())
9876 {
9877 if (!remote_multi_process_p (rs))
9878 {
9879 /* Check whether the target is running now - some remote stubs
9880 automatically restart after kill. */
9881 putpkt ("?");
9882 getpkt (&rs->buf, &rs->buf_size, 0);
9883
9884 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9885 {
9886 /* Assume that the target has been restarted. Set
9887 inferior_ptid so that bits of core GDB realizes
9888 there's something here, e.g., so that the user can
9889 say "kill" again. */
9890 inferior_ptid = magic_null_ptid;
9891 }
9892 }
9893 }
9894 }
9895
9896 bool
9897 extended_remote_target::supports_disable_randomization ()
9898 {
9899 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9900 }
9901
9902 void
9903 remote_target::extended_remote_disable_randomization (int val)
9904 {
9905 struct remote_state *rs = get_remote_state ();
9906 char *reply;
9907
9908 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9909 val);
9910 putpkt (rs->buf);
9911 reply = remote_get_noisy_reply ();
9912 if (*reply == '\0')
9913 error (_("Target does not support QDisableRandomization."));
9914 if (strcmp (reply, "OK") != 0)
9915 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9916 }
9917
9918 int
9919 remote_target::extended_remote_run (const std::string &args)
9920 {
9921 struct remote_state *rs = get_remote_state ();
9922 int len;
9923 const char *remote_exec_file = get_remote_exec_file ();
9924
9925 /* If the user has disabled vRun support, or we have detected that
9926 support is not available, do not try it. */
9927 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9928 return -1;
9929
9930 strcpy (rs->buf, "vRun;");
9931 len = strlen (rs->buf);
9932
9933 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9934 error (_("Remote file name too long for run packet"));
9935 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9936 strlen (remote_exec_file));
9937
9938 if (!args.empty ())
9939 {
9940 int i;
9941
9942 gdb_argv argv (args.c_str ());
9943 for (i = 0; argv[i] != NULL; i++)
9944 {
9945 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9946 error (_("Argument list too long for run packet"));
9947 rs->buf[len++] = ';';
9948 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9949 strlen (argv[i]));
9950 }
9951 }
9952
9953 rs->buf[len++] = '\0';
9954
9955 putpkt (rs->buf);
9956 getpkt (&rs->buf, &rs->buf_size, 0);
9957
9958 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9959 {
9960 case PACKET_OK:
9961 /* We have a wait response. All is well. */
9962 return 0;
9963 case PACKET_UNKNOWN:
9964 return -1;
9965 case PACKET_ERROR:
9966 if (remote_exec_file[0] == '\0')
9967 error (_("Running the default executable on the remote target failed; "
9968 "try \"set remote exec-file\"?"));
9969 else
9970 error (_("Running \"%s\" on the remote target failed"),
9971 remote_exec_file);
9972 default:
9973 gdb_assert_not_reached (_("bad switch"));
9974 }
9975 }
9976
9977 /* Helper function to send set/unset environment packets. ACTION is
9978 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9979 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9980 sent. */
9981
9982 void
9983 remote_target::send_environment_packet (const char *action,
9984 const char *packet,
9985 const char *value)
9986 {
9987 remote_state *rs = get_remote_state ();
9988
9989 /* Convert the environment variable to an hex string, which
9990 is the best format to be transmitted over the wire. */
9991 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9992 strlen (value));
9993
9994 xsnprintf (rs->buf, get_remote_packet_size (),
9995 "%s:%s", packet, encoded_value.c_str ());
9996
9997 putpkt (rs->buf);
9998 getpkt (&rs->buf, &rs->buf_size, 0);
9999 if (strcmp (rs->buf, "OK") != 0)
10000 warning (_("Unable to %s environment variable '%s' on remote."),
10001 action, value);
10002 }
10003
10004 /* Helper function to handle the QEnvironment* packets. */
10005
10006 void
10007 remote_target::extended_remote_environment_support ()
10008 {
10009 remote_state *rs = get_remote_state ();
10010
10011 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10012 {
10013 putpkt ("QEnvironmentReset");
10014 getpkt (&rs->buf, &rs->buf_size, 0);
10015 if (strcmp (rs->buf, "OK") != 0)
10016 warning (_("Unable to reset environment on remote."));
10017 }
10018
10019 gdb_environ *e = &current_inferior ()->environment;
10020
10021 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10022 for (const std::string &el : e->user_set_env ())
10023 send_environment_packet ("set", "QEnvironmentHexEncoded",
10024 el.c_str ());
10025
10026 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10027 for (const std::string &el : e->user_unset_env ())
10028 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10029 }
10030
10031 /* Helper function to set the current working directory for the
10032 inferior in the remote target. */
10033
10034 void
10035 remote_target::extended_remote_set_inferior_cwd ()
10036 {
10037 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10038 {
10039 const char *inferior_cwd = get_inferior_cwd ();
10040 remote_state *rs = get_remote_state ();
10041
10042 if (inferior_cwd != NULL)
10043 {
10044 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10045 strlen (inferior_cwd));
10046
10047 xsnprintf (rs->buf, get_remote_packet_size (),
10048 "QSetWorkingDir:%s", hexpath.c_str ());
10049 }
10050 else
10051 {
10052 /* An empty inferior_cwd means that the user wants us to
10053 reset the remote server's inferior's cwd. */
10054 xsnprintf (rs->buf, get_remote_packet_size (),
10055 "QSetWorkingDir:");
10056 }
10057
10058 putpkt (rs->buf);
10059 getpkt (&rs->buf, &rs->buf_size, 0);
10060 if (packet_ok (rs->buf,
10061 &remote_protocol_packets[PACKET_QSetWorkingDir])
10062 != PACKET_OK)
10063 error (_("\
10064 Remote replied unexpectedly while setting the inferior's working\n\
10065 directory: %s"),
10066 rs->buf);
10067
10068 }
10069 }
10070
10071 /* In the extended protocol we want to be able to do things like
10072 "run" and have them basically work as expected. So we need
10073 a special create_inferior function. We support changing the
10074 executable file and the command line arguments, but not the
10075 environment. */
10076
10077 void
10078 extended_remote_target::create_inferior (const char *exec_file,
10079 const std::string &args,
10080 char **env, int from_tty)
10081 {
10082 int run_worked;
10083 char *stop_reply;
10084 struct remote_state *rs = get_remote_state ();
10085 const char *remote_exec_file = get_remote_exec_file ();
10086
10087 /* If running asynchronously, register the target file descriptor
10088 with the event loop. */
10089 if (target_can_async_p ())
10090 target_async (1);
10091
10092 /* Disable address space randomization if requested (and supported). */
10093 if (supports_disable_randomization ())
10094 extended_remote_disable_randomization (disable_randomization);
10095
10096 /* If startup-with-shell is on, we inform gdbserver to start the
10097 remote inferior using a shell. */
10098 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10099 {
10100 xsnprintf (rs->buf, get_remote_packet_size (),
10101 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10102 putpkt (rs->buf);
10103 getpkt (&rs->buf, &rs->buf_size, 0);
10104 if (strcmp (rs->buf, "OK") != 0)
10105 error (_("\
10106 Remote replied unexpectedly while setting startup-with-shell: %s"),
10107 rs->buf);
10108 }
10109
10110 extended_remote_environment_support ();
10111
10112 extended_remote_set_inferior_cwd ();
10113
10114 /* Now restart the remote server. */
10115 run_worked = extended_remote_run (args) != -1;
10116 if (!run_worked)
10117 {
10118 /* vRun was not supported. Fail if we need it to do what the
10119 user requested. */
10120 if (remote_exec_file[0])
10121 error (_("Remote target does not support \"set remote exec-file\""));
10122 if (!args.empty ())
10123 error (_("Remote target does not support \"set args\" or run <ARGS>"));
10124
10125 /* Fall back to "R". */
10126 extended_remote_restart ();
10127 }
10128
10129 if (!have_inferiors ())
10130 {
10131 /* Clean up from the last time we ran, before we mark the target
10132 running again. This will mark breakpoints uninserted, and
10133 get_offsets may insert breakpoints. */
10134 init_thread_list ();
10135 init_wait_for_inferior ();
10136 }
10137
10138 /* vRun's success return is a stop reply. */
10139 stop_reply = run_worked ? rs->buf : NULL;
10140 add_current_inferior_and_thread (stop_reply);
10141
10142 /* Get updated offsets, if the stub uses qOffsets. */
10143 get_offsets ();
10144 }
10145 \f
10146
10147 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10148 the list of conditions (in agent expression bytecode format), if any, the
10149 target needs to evaluate. The output is placed into the packet buffer
10150 started from BUF and ended at BUF_END. */
10151
10152 static int
10153 remote_add_target_side_condition (struct gdbarch *gdbarch,
10154 struct bp_target_info *bp_tgt, char *buf,
10155 char *buf_end)
10156 {
10157 if (bp_tgt->conditions.empty ())
10158 return 0;
10159
10160 buf += strlen (buf);
10161 xsnprintf (buf, buf_end - buf, "%s", ";");
10162 buf++;
10163
10164 /* Send conditions to the target. */
10165 for (agent_expr *aexpr : bp_tgt->conditions)
10166 {
10167 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10168 buf += strlen (buf);
10169 for (int i = 0; i < aexpr->len; ++i)
10170 buf = pack_hex_byte (buf, aexpr->buf[i]);
10171 *buf = '\0';
10172 }
10173 return 0;
10174 }
10175
10176 static void
10177 remote_add_target_side_commands (struct gdbarch *gdbarch,
10178 struct bp_target_info *bp_tgt, char *buf)
10179 {
10180 if (bp_tgt->tcommands.empty ())
10181 return;
10182
10183 buf += strlen (buf);
10184
10185 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10186 buf += strlen (buf);
10187
10188 /* Concatenate all the agent expressions that are commands into the
10189 cmds parameter. */
10190 for (agent_expr *aexpr : bp_tgt->tcommands)
10191 {
10192 sprintf (buf, "X%x,", aexpr->len);
10193 buf += strlen (buf);
10194 for (int i = 0; i < aexpr->len; ++i)
10195 buf = pack_hex_byte (buf, aexpr->buf[i]);
10196 *buf = '\0';
10197 }
10198 }
10199
10200 /* Insert a breakpoint. On targets that have software breakpoint
10201 support, we ask the remote target to do the work; on targets
10202 which don't, we insert a traditional memory breakpoint. */
10203
10204 int
10205 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10206 struct bp_target_info *bp_tgt)
10207 {
10208 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10209 If it succeeds, then set the support to PACKET_ENABLE. If it
10210 fails, and the user has explicitly requested the Z support then
10211 report an error, otherwise, mark it disabled and go on. */
10212
10213 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10214 {
10215 CORE_ADDR addr = bp_tgt->reqstd_address;
10216 struct remote_state *rs;
10217 char *p, *endbuf;
10218
10219 /* Make sure the remote is pointing at the right process, if
10220 necessary. */
10221 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10222 set_general_process ();
10223
10224 rs = get_remote_state ();
10225 p = rs->buf;
10226 endbuf = rs->buf + get_remote_packet_size ();
10227
10228 *(p++) = 'Z';
10229 *(p++) = '0';
10230 *(p++) = ',';
10231 addr = (ULONGEST) remote_address_masked (addr);
10232 p += hexnumstr (p, addr);
10233 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10234
10235 if (supports_evaluation_of_breakpoint_conditions ())
10236 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10237
10238 if (can_run_breakpoint_commands ())
10239 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10240
10241 putpkt (rs->buf);
10242 getpkt (&rs->buf, &rs->buf_size, 0);
10243
10244 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10245 {
10246 case PACKET_ERROR:
10247 return -1;
10248 case PACKET_OK:
10249 return 0;
10250 case PACKET_UNKNOWN:
10251 break;
10252 }
10253 }
10254
10255 /* If this breakpoint has target-side commands but this stub doesn't
10256 support Z0 packets, throw error. */
10257 if (!bp_tgt->tcommands.empty ())
10258 throw_error (NOT_SUPPORTED_ERROR, _("\
10259 Target doesn't support breakpoints that have target side commands."));
10260
10261 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10262 }
10263
10264 int
10265 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10266 struct bp_target_info *bp_tgt,
10267 enum remove_bp_reason reason)
10268 {
10269 CORE_ADDR addr = bp_tgt->placed_address;
10270 struct remote_state *rs = get_remote_state ();
10271
10272 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10273 {
10274 char *p = rs->buf;
10275 char *endbuf = rs->buf + get_remote_packet_size ();
10276
10277 /* Make sure the remote is pointing at the right process, if
10278 necessary. */
10279 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10280 set_general_process ();
10281
10282 *(p++) = 'z';
10283 *(p++) = '0';
10284 *(p++) = ',';
10285
10286 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10287 p += hexnumstr (p, addr);
10288 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10289
10290 putpkt (rs->buf);
10291 getpkt (&rs->buf, &rs->buf_size, 0);
10292
10293 return (rs->buf[0] == 'E');
10294 }
10295
10296 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10297 }
10298
10299 static enum Z_packet_type
10300 watchpoint_to_Z_packet (int type)
10301 {
10302 switch (type)
10303 {
10304 case hw_write:
10305 return Z_PACKET_WRITE_WP;
10306 break;
10307 case hw_read:
10308 return Z_PACKET_READ_WP;
10309 break;
10310 case hw_access:
10311 return Z_PACKET_ACCESS_WP;
10312 break;
10313 default:
10314 internal_error (__FILE__, __LINE__,
10315 _("hw_bp_to_z: bad watchpoint type %d"), type);
10316 }
10317 }
10318
10319 int
10320 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10321 enum target_hw_bp_type type, struct expression *cond)
10322 {
10323 struct remote_state *rs = get_remote_state ();
10324 char *endbuf = rs->buf + get_remote_packet_size ();
10325 char *p;
10326 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10327
10328 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10329 return 1;
10330
10331 /* Make sure the remote is pointing at the right process, if
10332 necessary. */
10333 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10334 set_general_process ();
10335
10336 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10337 p = strchr (rs->buf, '\0');
10338 addr = remote_address_masked (addr);
10339 p += hexnumstr (p, (ULONGEST) addr);
10340 xsnprintf (p, endbuf - p, ",%x", len);
10341
10342 putpkt (rs->buf);
10343 getpkt (&rs->buf, &rs->buf_size, 0);
10344
10345 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10346 {
10347 case PACKET_ERROR:
10348 return -1;
10349 case PACKET_UNKNOWN:
10350 return 1;
10351 case PACKET_OK:
10352 return 0;
10353 }
10354 internal_error (__FILE__, __LINE__,
10355 _("remote_insert_watchpoint: reached end of function"));
10356 }
10357
10358 bool
10359 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10360 CORE_ADDR start, int length)
10361 {
10362 CORE_ADDR diff = remote_address_masked (addr - start);
10363
10364 return diff < length;
10365 }
10366
10367
10368 int
10369 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10370 enum target_hw_bp_type type, struct expression *cond)
10371 {
10372 struct remote_state *rs = get_remote_state ();
10373 char *endbuf = rs->buf + get_remote_packet_size ();
10374 char *p;
10375 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10376
10377 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10378 return -1;
10379
10380 /* Make sure the remote is pointing at the right process, if
10381 necessary. */
10382 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10383 set_general_process ();
10384
10385 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10386 p = strchr (rs->buf, '\0');
10387 addr = remote_address_masked (addr);
10388 p += hexnumstr (p, (ULONGEST) addr);
10389 xsnprintf (p, endbuf - p, ",%x", len);
10390 putpkt (rs->buf);
10391 getpkt (&rs->buf, &rs->buf_size, 0);
10392
10393 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10394 {
10395 case PACKET_ERROR:
10396 case PACKET_UNKNOWN:
10397 return -1;
10398 case PACKET_OK:
10399 return 0;
10400 }
10401 internal_error (__FILE__, __LINE__,
10402 _("remote_remove_watchpoint: reached end of function"));
10403 }
10404
10405
10406 int remote_hw_watchpoint_limit = -1;
10407 int remote_hw_watchpoint_length_limit = -1;
10408 int remote_hw_breakpoint_limit = -1;
10409
10410 int
10411 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10412 {
10413 if (remote_hw_watchpoint_length_limit == 0)
10414 return 0;
10415 else if (remote_hw_watchpoint_length_limit < 0)
10416 return 1;
10417 else if (len <= remote_hw_watchpoint_length_limit)
10418 return 1;
10419 else
10420 return 0;
10421 }
10422
10423 int
10424 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10425 {
10426 if (type == bp_hardware_breakpoint)
10427 {
10428 if (remote_hw_breakpoint_limit == 0)
10429 return 0;
10430 else if (remote_hw_breakpoint_limit < 0)
10431 return 1;
10432 else if (cnt <= remote_hw_breakpoint_limit)
10433 return 1;
10434 }
10435 else
10436 {
10437 if (remote_hw_watchpoint_limit == 0)
10438 return 0;
10439 else if (remote_hw_watchpoint_limit < 0)
10440 return 1;
10441 else if (ot)
10442 return -1;
10443 else if (cnt <= remote_hw_watchpoint_limit)
10444 return 1;
10445 }
10446 return -1;
10447 }
10448
10449 /* The to_stopped_by_sw_breakpoint method of target remote. */
10450
10451 bool
10452 remote_target::stopped_by_sw_breakpoint ()
10453 {
10454 struct thread_info *thread = inferior_thread ();
10455
10456 return (thread->priv != NULL
10457 && (get_remote_thread_info (thread)->stop_reason
10458 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10459 }
10460
10461 /* The to_supports_stopped_by_sw_breakpoint method of target
10462 remote. */
10463
10464 bool
10465 remote_target::supports_stopped_by_sw_breakpoint ()
10466 {
10467 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10468 }
10469
10470 /* The to_stopped_by_hw_breakpoint method of target remote. */
10471
10472 bool
10473 remote_target::stopped_by_hw_breakpoint ()
10474 {
10475 struct thread_info *thread = inferior_thread ();
10476
10477 return (thread->priv != NULL
10478 && (get_remote_thread_info (thread)->stop_reason
10479 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10480 }
10481
10482 /* The to_supports_stopped_by_hw_breakpoint method of target
10483 remote. */
10484
10485 bool
10486 remote_target::supports_stopped_by_hw_breakpoint ()
10487 {
10488 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10489 }
10490
10491 bool
10492 remote_target::stopped_by_watchpoint ()
10493 {
10494 struct thread_info *thread = inferior_thread ();
10495
10496 return (thread->priv != NULL
10497 && (get_remote_thread_info (thread)->stop_reason
10498 == TARGET_STOPPED_BY_WATCHPOINT));
10499 }
10500
10501 bool
10502 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10503 {
10504 struct thread_info *thread = inferior_thread ();
10505
10506 if (thread->priv != NULL
10507 && (get_remote_thread_info (thread)->stop_reason
10508 == TARGET_STOPPED_BY_WATCHPOINT))
10509 {
10510 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10511 return true;
10512 }
10513
10514 return false;
10515 }
10516
10517
10518 int
10519 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10520 struct bp_target_info *bp_tgt)
10521 {
10522 CORE_ADDR addr = bp_tgt->reqstd_address;
10523 struct remote_state *rs;
10524 char *p, *endbuf;
10525 char *message;
10526
10527 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10528 return -1;
10529
10530 /* Make sure the remote is pointing at the right process, if
10531 necessary. */
10532 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10533 set_general_process ();
10534
10535 rs = get_remote_state ();
10536 p = rs->buf;
10537 endbuf = rs->buf + get_remote_packet_size ();
10538
10539 *(p++) = 'Z';
10540 *(p++) = '1';
10541 *(p++) = ',';
10542
10543 addr = remote_address_masked (addr);
10544 p += hexnumstr (p, (ULONGEST) addr);
10545 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10546
10547 if (supports_evaluation_of_breakpoint_conditions ())
10548 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10549
10550 if (can_run_breakpoint_commands ())
10551 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10552
10553 putpkt (rs->buf);
10554 getpkt (&rs->buf, &rs->buf_size, 0);
10555
10556 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10557 {
10558 case PACKET_ERROR:
10559 if (rs->buf[1] == '.')
10560 {
10561 message = strchr (rs->buf + 2, '.');
10562 if (message)
10563 error (_("Remote failure reply: %s"), message + 1);
10564 }
10565 return -1;
10566 case PACKET_UNKNOWN:
10567 return -1;
10568 case PACKET_OK:
10569 return 0;
10570 }
10571 internal_error (__FILE__, __LINE__,
10572 _("remote_insert_hw_breakpoint: reached end of function"));
10573 }
10574
10575
10576 int
10577 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10578 struct bp_target_info *bp_tgt)
10579 {
10580 CORE_ADDR addr;
10581 struct remote_state *rs = get_remote_state ();
10582 char *p = rs->buf;
10583 char *endbuf = rs->buf + get_remote_packet_size ();
10584
10585 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10586 return -1;
10587
10588 /* Make sure the remote is pointing at the right process, if
10589 necessary. */
10590 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10591 set_general_process ();
10592
10593 *(p++) = 'z';
10594 *(p++) = '1';
10595 *(p++) = ',';
10596
10597 addr = remote_address_masked (bp_tgt->placed_address);
10598 p += hexnumstr (p, (ULONGEST) addr);
10599 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10600
10601 putpkt (rs->buf);
10602 getpkt (&rs->buf, &rs->buf_size, 0);
10603
10604 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10605 {
10606 case PACKET_ERROR:
10607 case PACKET_UNKNOWN:
10608 return -1;
10609 case PACKET_OK:
10610 return 0;
10611 }
10612 internal_error (__FILE__, __LINE__,
10613 _("remote_remove_hw_breakpoint: reached end of function"));
10614 }
10615
10616 /* Verify memory using the "qCRC:" request. */
10617
10618 int
10619 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10620 {
10621 struct remote_state *rs = get_remote_state ();
10622 unsigned long host_crc, target_crc;
10623 char *tmp;
10624
10625 /* It doesn't make sense to use qCRC if the remote target is
10626 connected but not running. */
10627 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10628 {
10629 enum packet_result result;
10630
10631 /* Make sure the remote is pointing at the right process. */
10632 set_general_process ();
10633
10634 /* FIXME: assumes lma can fit into long. */
10635 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10636 (long) lma, (long) size);
10637 putpkt (rs->buf);
10638
10639 /* Be clever; compute the host_crc before waiting for target
10640 reply. */
10641 host_crc = xcrc32 (data, size, 0xffffffff);
10642
10643 getpkt (&rs->buf, &rs->buf_size, 0);
10644
10645 result = packet_ok (rs->buf,
10646 &remote_protocol_packets[PACKET_qCRC]);
10647 if (result == PACKET_ERROR)
10648 return -1;
10649 else if (result == PACKET_OK)
10650 {
10651 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10652 target_crc = target_crc * 16 + fromhex (*tmp);
10653
10654 return (host_crc == target_crc);
10655 }
10656 }
10657
10658 return simple_verify_memory (this, data, lma, size);
10659 }
10660
10661 /* compare-sections command
10662
10663 With no arguments, compares each loadable section in the exec bfd
10664 with the same memory range on the target, and reports mismatches.
10665 Useful for verifying the image on the target against the exec file. */
10666
10667 static void
10668 compare_sections_command (const char *args, int from_tty)
10669 {
10670 asection *s;
10671 const char *sectname;
10672 bfd_size_type size;
10673 bfd_vma lma;
10674 int matched = 0;
10675 int mismatched = 0;
10676 int res;
10677 int read_only = 0;
10678
10679 if (!exec_bfd)
10680 error (_("command cannot be used without an exec file"));
10681
10682 if (args != NULL && strcmp (args, "-r") == 0)
10683 {
10684 read_only = 1;
10685 args = NULL;
10686 }
10687
10688 for (s = exec_bfd->sections; s; s = s->next)
10689 {
10690 if (!(s->flags & SEC_LOAD))
10691 continue; /* Skip non-loadable section. */
10692
10693 if (read_only && (s->flags & SEC_READONLY) == 0)
10694 continue; /* Skip writeable sections */
10695
10696 size = bfd_get_section_size (s);
10697 if (size == 0)
10698 continue; /* Skip zero-length section. */
10699
10700 sectname = bfd_get_section_name (exec_bfd, s);
10701 if (args && strcmp (args, sectname) != 0)
10702 continue; /* Not the section selected by user. */
10703
10704 matched = 1; /* Do this section. */
10705 lma = s->lma;
10706
10707 gdb::byte_vector sectdata (size);
10708 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10709
10710 res = target_verify_memory (sectdata.data (), lma, size);
10711
10712 if (res == -1)
10713 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10714 paddress (target_gdbarch (), lma),
10715 paddress (target_gdbarch (), lma + size));
10716
10717 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10718 paddress (target_gdbarch (), lma),
10719 paddress (target_gdbarch (), lma + size));
10720 if (res)
10721 printf_filtered ("matched.\n");
10722 else
10723 {
10724 printf_filtered ("MIS-MATCHED!\n");
10725 mismatched++;
10726 }
10727 }
10728 if (mismatched > 0)
10729 warning (_("One or more sections of the target image does not match\n\
10730 the loaded file\n"));
10731 if (args && !matched)
10732 printf_filtered (_("No loaded section named '%s'.\n"), args);
10733 }
10734
10735 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10736 into remote target. The number of bytes written to the remote
10737 target is returned, or -1 for error. */
10738
10739 target_xfer_status
10740 remote_target::remote_write_qxfer (const char *object_name,
10741 const char *annex, const gdb_byte *writebuf,
10742 ULONGEST offset, LONGEST len,
10743 ULONGEST *xfered_len,
10744 struct packet_config *packet)
10745 {
10746 int i, buf_len;
10747 ULONGEST n;
10748 struct remote_state *rs = get_remote_state ();
10749 int max_size = get_memory_write_packet_size ();
10750
10751 if (packet_config_support (packet) == PACKET_DISABLE)
10752 return TARGET_XFER_E_IO;
10753
10754 /* Insert header. */
10755 i = snprintf (rs->buf, max_size,
10756 "qXfer:%s:write:%s:%s:",
10757 object_name, annex ? annex : "",
10758 phex_nz (offset, sizeof offset));
10759 max_size -= (i + 1);
10760
10761 /* Escape as much data as fits into rs->buf. */
10762 buf_len = remote_escape_output
10763 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10764
10765 if (putpkt_binary (rs->buf, i + buf_len) < 0
10766 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10767 || packet_ok (rs->buf, packet) != PACKET_OK)
10768 return TARGET_XFER_E_IO;
10769
10770 unpack_varlen_hex (rs->buf, &n);
10771
10772 *xfered_len = n;
10773 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10774 }
10775
10776 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10777 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10778 number of bytes read is returned, or 0 for EOF, or -1 for error.
10779 The number of bytes read may be less than LEN without indicating an
10780 EOF. PACKET is checked and updated to indicate whether the remote
10781 target supports this object. */
10782
10783 target_xfer_status
10784 remote_target::remote_read_qxfer (const char *object_name,
10785 const char *annex,
10786 gdb_byte *readbuf, ULONGEST offset,
10787 LONGEST len,
10788 ULONGEST *xfered_len,
10789 struct packet_config *packet)
10790 {
10791 struct remote_state *rs = get_remote_state ();
10792 LONGEST i, n, packet_len;
10793
10794 if (packet_config_support (packet) == PACKET_DISABLE)
10795 return TARGET_XFER_E_IO;
10796
10797 /* Check whether we've cached an end-of-object packet that matches
10798 this request. */
10799 if (rs->finished_object)
10800 {
10801 if (strcmp (object_name, rs->finished_object) == 0
10802 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10803 && offset == rs->finished_offset)
10804 return TARGET_XFER_EOF;
10805
10806
10807 /* Otherwise, we're now reading something different. Discard
10808 the cache. */
10809 xfree (rs->finished_object);
10810 xfree (rs->finished_annex);
10811 rs->finished_object = NULL;
10812 rs->finished_annex = NULL;
10813 }
10814
10815 /* Request only enough to fit in a single packet. The actual data
10816 may not, since we don't know how much of it will need to be escaped;
10817 the target is free to respond with slightly less data. We subtract
10818 five to account for the response type and the protocol frame. */
10819 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10820 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10821 object_name, annex ? annex : "",
10822 phex_nz (offset, sizeof offset),
10823 phex_nz (n, sizeof n));
10824 i = putpkt (rs->buf);
10825 if (i < 0)
10826 return TARGET_XFER_E_IO;
10827
10828 rs->buf[0] = '\0';
10829 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10830 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10831 return TARGET_XFER_E_IO;
10832
10833 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10834 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10835
10836 /* 'm' means there is (or at least might be) more data after this
10837 batch. That does not make sense unless there's at least one byte
10838 of data in this reply. */
10839 if (rs->buf[0] == 'm' && packet_len == 1)
10840 error (_("Remote qXfer reply contained no data."));
10841
10842 /* Got some data. */
10843 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10844 packet_len - 1, readbuf, n);
10845
10846 /* 'l' is an EOF marker, possibly including a final block of data,
10847 or possibly empty. If we have the final block of a non-empty
10848 object, record this fact to bypass a subsequent partial read. */
10849 if (rs->buf[0] == 'l' && offset + i > 0)
10850 {
10851 rs->finished_object = xstrdup (object_name);
10852 rs->finished_annex = xstrdup (annex ? annex : "");
10853 rs->finished_offset = offset + i;
10854 }
10855
10856 if (i == 0)
10857 return TARGET_XFER_EOF;
10858 else
10859 {
10860 *xfered_len = i;
10861 return TARGET_XFER_OK;
10862 }
10863 }
10864
10865 enum target_xfer_status
10866 remote_target::xfer_partial (enum target_object object,
10867 const char *annex, gdb_byte *readbuf,
10868 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10869 ULONGEST *xfered_len)
10870 {
10871 struct remote_state *rs;
10872 int i;
10873 char *p2;
10874 char query_type;
10875 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10876
10877 set_remote_traceframe ();
10878 set_general_thread (inferior_ptid);
10879
10880 rs = get_remote_state ();
10881
10882 /* Handle memory using the standard memory routines. */
10883 if (object == TARGET_OBJECT_MEMORY)
10884 {
10885 /* If the remote target is connected but not running, we should
10886 pass this request down to a lower stratum (e.g. the executable
10887 file). */
10888 if (!target_has_execution)
10889 return TARGET_XFER_EOF;
10890
10891 if (writebuf != NULL)
10892 return remote_write_bytes (offset, writebuf, len, unit_size,
10893 xfered_len);
10894 else
10895 return remote_read_bytes (offset, readbuf, len, unit_size,
10896 xfered_len);
10897 }
10898
10899 /* Handle SPU memory using qxfer packets. */
10900 if (object == TARGET_OBJECT_SPU)
10901 {
10902 if (readbuf)
10903 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10904 xfered_len, &remote_protocol_packets
10905 [PACKET_qXfer_spu_read]);
10906 else
10907 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10908 xfered_len, &remote_protocol_packets
10909 [PACKET_qXfer_spu_write]);
10910 }
10911
10912 /* Handle extra signal info using qxfer packets. */
10913 if (object == TARGET_OBJECT_SIGNAL_INFO)
10914 {
10915 if (readbuf)
10916 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10917 xfered_len, &remote_protocol_packets
10918 [PACKET_qXfer_siginfo_read]);
10919 else
10920 return remote_write_qxfer ("siginfo", annex,
10921 writebuf, offset, len, xfered_len,
10922 &remote_protocol_packets
10923 [PACKET_qXfer_siginfo_write]);
10924 }
10925
10926 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10927 {
10928 if (readbuf)
10929 return remote_read_qxfer ("statictrace", annex,
10930 readbuf, offset, len, xfered_len,
10931 &remote_protocol_packets
10932 [PACKET_qXfer_statictrace_read]);
10933 else
10934 return TARGET_XFER_E_IO;
10935 }
10936
10937 /* Only handle flash writes. */
10938 if (writebuf != NULL)
10939 {
10940 switch (object)
10941 {
10942 case TARGET_OBJECT_FLASH:
10943 return remote_flash_write (offset, len, xfered_len,
10944 writebuf);
10945
10946 default:
10947 return TARGET_XFER_E_IO;
10948 }
10949 }
10950
10951 /* Map pre-existing objects onto letters. DO NOT do this for new
10952 objects!!! Instead specify new query packets. */
10953 switch (object)
10954 {
10955 case TARGET_OBJECT_AVR:
10956 query_type = 'R';
10957 break;
10958
10959 case TARGET_OBJECT_AUXV:
10960 gdb_assert (annex == NULL);
10961 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10962 xfered_len,
10963 &remote_protocol_packets[PACKET_qXfer_auxv]);
10964
10965 case TARGET_OBJECT_AVAILABLE_FEATURES:
10966 return remote_read_qxfer
10967 ("features", annex, readbuf, offset, len, xfered_len,
10968 &remote_protocol_packets[PACKET_qXfer_features]);
10969
10970 case TARGET_OBJECT_LIBRARIES:
10971 return remote_read_qxfer
10972 ("libraries", annex, readbuf, offset, len, xfered_len,
10973 &remote_protocol_packets[PACKET_qXfer_libraries]);
10974
10975 case TARGET_OBJECT_LIBRARIES_SVR4:
10976 return remote_read_qxfer
10977 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10978 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10979
10980 case TARGET_OBJECT_MEMORY_MAP:
10981 gdb_assert (annex == NULL);
10982 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10983 xfered_len,
10984 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10985
10986 case TARGET_OBJECT_OSDATA:
10987 /* Should only get here if we're connected. */
10988 gdb_assert (rs->remote_desc);
10989 return remote_read_qxfer
10990 ("osdata", annex, readbuf, offset, len, xfered_len,
10991 &remote_protocol_packets[PACKET_qXfer_osdata]);
10992
10993 case TARGET_OBJECT_THREADS:
10994 gdb_assert (annex == NULL);
10995 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10996 xfered_len,
10997 &remote_protocol_packets[PACKET_qXfer_threads]);
10998
10999 case TARGET_OBJECT_TRACEFRAME_INFO:
11000 gdb_assert (annex == NULL);
11001 return remote_read_qxfer
11002 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11003 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11004
11005 case TARGET_OBJECT_FDPIC:
11006 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11007 xfered_len,
11008 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11009
11010 case TARGET_OBJECT_OPENVMS_UIB:
11011 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11012 xfered_len,
11013 &remote_protocol_packets[PACKET_qXfer_uib]);
11014
11015 case TARGET_OBJECT_BTRACE:
11016 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11017 xfered_len,
11018 &remote_protocol_packets[PACKET_qXfer_btrace]);
11019
11020 case TARGET_OBJECT_BTRACE_CONF:
11021 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11022 len, xfered_len,
11023 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11024
11025 case TARGET_OBJECT_EXEC_FILE:
11026 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11027 len, xfered_len,
11028 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11029
11030 default:
11031 return TARGET_XFER_E_IO;
11032 }
11033
11034 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11035 large enough let the caller deal with it. */
11036 if (len < get_remote_packet_size ())
11037 return TARGET_XFER_E_IO;
11038 len = get_remote_packet_size ();
11039
11040 /* Except for querying the minimum buffer size, target must be open. */
11041 if (!rs->remote_desc)
11042 error (_("remote query is only available after target open"));
11043
11044 gdb_assert (annex != NULL);
11045 gdb_assert (readbuf != NULL);
11046
11047 p2 = rs->buf;
11048 *p2++ = 'q';
11049 *p2++ = query_type;
11050
11051 /* We used one buffer char for the remote protocol q command and
11052 another for the query type. As the remote protocol encapsulation
11053 uses 4 chars plus one extra in case we are debugging
11054 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11055 string. */
11056 i = 0;
11057 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11058 {
11059 /* Bad caller may have sent forbidden characters. */
11060 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11061 *p2++ = annex[i];
11062 i++;
11063 }
11064 *p2 = '\0';
11065 gdb_assert (annex[i] == '\0');
11066
11067 i = putpkt (rs->buf);
11068 if (i < 0)
11069 return TARGET_XFER_E_IO;
11070
11071 getpkt (&rs->buf, &rs->buf_size, 0);
11072 strcpy ((char *) readbuf, rs->buf);
11073
11074 *xfered_len = strlen ((char *) readbuf);
11075 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11076 }
11077
11078 /* Implementation of to_get_memory_xfer_limit. */
11079
11080 ULONGEST
11081 remote_target::get_memory_xfer_limit ()
11082 {
11083 return get_memory_write_packet_size ();
11084 }
11085
11086 int
11087 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11088 const gdb_byte *pattern, ULONGEST pattern_len,
11089 CORE_ADDR *found_addrp)
11090 {
11091 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11092 struct remote_state *rs = get_remote_state ();
11093 int max_size = get_memory_write_packet_size ();
11094 struct packet_config *packet =
11095 &remote_protocol_packets[PACKET_qSearch_memory];
11096 /* Number of packet bytes used to encode the pattern;
11097 this could be more than PATTERN_LEN due to escape characters. */
11098 int escaped_pattern_len;
11099 /* Amount of pattern that was encodable in the packet. */
11100 int used_pattern_len;
11101 int i;
11102 int found;
11103 ULONGEST found_addr;
11104
11105 /* Don't go to the target if we don't have to. This is done before
11106 checking packet_config_support to avoid the possibility that a
11107 success for this edge case means the facility works in
11108 general. */
11109 if (pattern_len > search_space_len)
11110 return 0;
11111 if (pattern_len == 0)
11112 {
11113 *found_addrp = start_addr;
11114 return 1;
11115 }
11116
11117 /* If we already know the packet isn't supported, fall back to the simple
11118 way of searching memory. */
11119
11120 if (packet_config_support (packet) == PACKET_DISABLE)
11121 {
11122 /* Target doesn't provided special support, fall back and use the
11123 standard support (copy memory and do the search here). */
11124 return simple_search_memory (this, start_addr, search_space_len,
11125 pattern, pattern_len, found_addrp);
11126 }
11127
11128 /* Make sure the remote is pointing at the right process. */
11129 set_general_process ();
11130
11131 /* Insert header. */
11132 i = snprintf (rs->buf, max_size,
11133 "qSearch:memory:%s;%s;",
11134 phex_nz (start_addr, addr_size),
11135 phex_nz (search_space_len, sizeof (search_space_len)));
11136 max_size -= (i + 1);
11137
11138 /* Escape as much data as fits into rs->buf. */
11139 escaped_pattern_len =
11140 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
11141 &used_pattern_len, max_size);
11142
11143 /* Bail if the pattern is too large. */
11144 if (used_pattern_len != pattern_len)
11145 error (_("Pattern is too large to transmit to remote target."));
11146
11147 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11148 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11149 || packet_ok (rs->buf, packet) != PACKET_OK)
11150 {
11151 /* The request may not have worked because the command is not
11152 supported. If so, fall back to the simple way. */
11153 if (packet_config_support (packet) == PACKET_DISABLE)
11154 {
11155 return simple_search_memory (this, start_addr, search_space_len,
11156 pattern, pattern_len, found_addrp);
11157 }
11158 return -1;
11159 }
11160
11161 if (rs->buf[0] == '0')
11162 found = 0;
11163 else if (rs->buf[0] == '1')
11164 {
11165 found = 1;
11166 if (rs->buf[1] != ',')
11167 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11168 unpack_varlen_hex (rs->buf + 2, &found_addr);
11169 *found_addrp = found_addr;
11170 }
11171 else
11172 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11173
11174 return found;
11175 }
11176
11177 void
11178 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11179 {
11180 struct remote_state *rs = get_remote_state ();
11181 char *p = rs->buf;
11182
11183 if (!rs->remote_desc)
11184 error (_("remote rcmd is only available after target open"));
11185
11186 /* Send a NULL command across as an empty command. */
11187 if (command == NULL)
11188 command = "";
11189
11190 /* The query prefix. */
11191 strcpy (rs->buf, "qRcmd,");
11192 p = strchr (rs->buf, '\0');
11193
11194 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11195 > get_remote_packet_size ())
11196 error (_("\"monitor\" command ``%s'' is too long."), command);
11197
11198 /* Encode the actual command. */
11199 bin2hex ((const gdb_byte *) command, p, strlen (command));
11200
11201 if (putpkt (rs->buf) < 0)
11202 error (_("Communication problem with target."));
11203
11204 /* get/display the response */
11205 while (1)
11206 {
11207 char *buf;
11208
11209 /* XXX - see also remote_get_noisy_reply(). */
11210 QUIT; /* Allow user to bail out with ^C. */
11211 rs->buf[0] = '\0';
11212 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11213 {
11214 /* Timeout. Continue to (try to) read responses.
11215 This is better than stopping with an error, assuming the stub
11216 is still executing the (long) monitor command.
11217 If needed, the user can interrupt gdb using C-c, obtaining
11218 an effect similar to stop on timeout. */
11219 continue;
11220 }
11221 buf = rs->buf;
11222 if (buf[0] == '\0')
11223 error (_("Target does not support this command."));
11224 if (buf[0] == 'O' && buf[1] != 'K')
11225 {
11226 remote_console_output (buf + 1); /* 'O' message from stub. */
11227 continue;
11228 }
11229 if (strcmp (buf, "OK") == 0)
11230 break;
11231 if (strlen (buf) == 3 && buf[0] == 'E'
11232 && isdigit (buf[1]) && isdigit (buf[2]))
11233 {
11234 error (_("Protocol error with Rcmd"));
11235 }
11236 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11237 {
11238 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11239
11240 fputc_unfiltered (c, outbuf);
11241 }
11242 break;
11243 }
11244 }
11245
11246 std::vector<mem_region>
11247 remote_target::memory_map ()
11248 {
11249 std::vector<mem_region> result;
11250 gdb::optional<gdb::char_vector> text
11251 = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
11252
11253 if (text)
11254 result = parse_memory_map (text->data ());
11255
11256 return result;
11257 }
11258
11259 static void
11260 packet_command (const char *args, int from_tty)
11261 {
11262 remote_target *remote = get_current_remote_target ();
11263
11264 if (remote == nullptr)
11265 error (_("command can only be used with remote target"));
11266
11267 remote->packet_command (args, from_tty);
11268 }
11269
11270 void
11271 remote_target::packet_command (const char *args, int from_tty)
11272 {
11273 if (!args)
11274 error (_("remote-packet command requires packet text as argument"));
11275
11276 puts_filtered ("sending: ");
11277 print_packet (args);
11278 puts_filtered ("\n");
11279 putpkt (args);
11280
11281 remote_state *rs = get_remote_state ();
11282
11283 getpkt (&rs->buf, &rs->buf_size, 0);
11284 puts_filtered ("received: ");
11285 print_packet (rs->buf);
11286 puts_filtered ("\n");
11287 }
11288
11289 #if 0
11290 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11291
11292 static void display_thread_info (struct gdb_ext_thread_info *info);
11293
11294 static void threadset_test_cmd (char *cmd, int tty);
11295
11296 static void threadalive_test (char *cmd, int tty);
11297
11298 static void threadlist_test_cmd (char *cmd, int tty);
11299
11300 int get_and_display_threadinfo (threadref *ref);
11301
11302 static void threadinfo_test_cmd (char *cmd, int tty);
11303
11304 static int thread_display_step (threadref *ref, void *context);
11305
11306 static void threadlist_update_test_cmd (char *cmd, int tty);
11307
11308 static void init_remote_threadtests (void);
11309
11310 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11311
11312 static void
11313 threadset_test_cmd (const char *cmd, int tty)
11314 {
11315 int sample_thread = SAMPLE_THREAD;
11316
11317 printf_filtered (_("Remote threadset test\n"));
11318 set_general_thread (sample_thread);
11319 }
11320
11321
11322 static void
11323 threadalive_test (const char *cmd, int tty)
11324 {
11325 int sample_thread = SAMPLE_THREAD;
11326 int pid = ptid_get_pid (inferior_ptid);
11327 ptid_t ptid = ptid_build (pid, sample_thread, 0);
11328
11329 if (remote_thread_alive (ptid))
11330 printf_filtered ("PASS: Thread alive test\n");
11331 else
11332 printf_filtered ("FAIL: Thread alive test\n");
11333 }
11334
11335 void output_threadid (char *title, threadref *ref);
11336
11337 void
11338 output_threadid (char *title, threadref *ref)
11339 {
11340 char hexid[20];
11341
11342 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
11343 hexid[16] = 0;
11344 printf_filtered ("%s %s\n", title, (&hexid[0]));
11345 }
11346
11347 static void
11348 threadlist_test_cmd (const char *cmd, int tty)
11349 {
11350 int startflag = 1;
11351 threadref nextthread;
11352 int done, result_count;
11353 threadref threadlist[3];
11354
11355 printf_filtered ("Remote Threadlist test\n");
11356 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11357 &result_count, &threadlist[0]))
11358 printf_filtered ("FAIL: threadlist test\n");
11359 else
11360 {
11361 threadref *scan = threadlist;
11362 threadref *limit = scan + result_count;
11363
11364 while (scan < limit)
11365 output_threadid (" thread ", scan++);
11366 }
11367 }
11368
11369 void
11370 display_thread_info (struct gdb_ext_thread_info *info)
11371 {
11372 output_threadid ("Threadid: ", &info->threadid);
11373 printf_filtered ("Name: %s\n ", info->shortname);
11374 printf_filtered ("State: %s\n", info->display);
11375 printf_filtered ("other: %s\n\n", info->more_display);
11376 }
11377
11378 int
11379 get_and_display_threadinfo (threadref *ref)
11380 {
11381 int result;
11382 int set;
11383 struct gdb_ext_thread_info threadinfo;
11384
11385 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11386 | TAG_MOREDISPLAY | TAG_DISPLAY;
11387 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11388 display_thread_info (&threadinfo);
11389 return result;
11390 }
11391
11392 static void
11393 threadinfo_test_cmd (const char *cmd, int tty)
11394 {
11395 int athread = SAMPLE_THREAD;
11396 threadref thread;
11397 int set;
11398
11399 int_to_threadref (&thread, athread);
11400 printf_filtered ("Remote Threadinfo test\n");
11401 if (!get_and_display_threadinfo (&thread))
11402 printf_filtered ("FAIL cannot get thread info\n");
11403 }
11404
11405 static int
11406 thread_display_step (threadref *ref, void *context)
11407 {
11408 /* output_threadid(" threadstep ",ref); *//* simple test */
11409 return get_and_display_threadinfo (ref);
11410 }
11411
11412 static void
11413 threadlist_update_test_cmd (const char *cmd, int tty)
11414 {
11415 printf_filtered ("Remote Threadlist update test\n");
11416 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11417 }
11418
11419 static void
11420 init_remote_threadtests (void)
11421 {
11422 add_com ("tlist", class_obscure, threadlist_test_cmd,
11423 _("Fetch and print the remote list of "
11424 "thread identifiers, one pkt only"));
11425 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11426 _("Fetch and display info about one thread"));
11427 add_com ("tset", class_obscure, threadset_test_cmd,
11428 _("Test setting to a different thread"));
11429 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11430 _("Iterate through updating all remote thread info"));
11431 add_com ("talive", class_obscure, threadalive_test,
11432 _(" Remote thread alive test "));
11433 }
11434
11435 #endif /* 0 */
11436
11437 /* Convert a thread ID to a string. Returns the string in a static
11438 buffer. */
11439
11440 const char *
11441 remote_target::pid_to_str (ptid_t ptid)
11442 {
11443 static char buf[64];
11444 struct remote_state *rs = get_remote_state ();
11445
11446 if (ptid_equal (ptid, null_ptid))
11447 return normal_pid_to_str (ptid);
11448 else if (ptid_is_pid (ptid))
11449 {
11450 /* Printing an inferior target id. */
11451
11452 /* When multi-process extensions are off, there's no way in the
11453 remote protocol to know the remote process id, if there's any
11454 at all. There's one exception --- when we're connected with
11455 target extended-remote, and we manually attached to a process
11456 with "attach PID". We don't record anywhere a flag that
11457 allows us to distinguish that case from the case of
11458 connecting with extended-remote and the stub already being
11459 attached to a process, and reporting yes to qAttached, hence
11460 no smart special casing here. */
11461 if (!remote_multi_process_p (rs))
11462 {
11463 xsnprintf (buf, sizeof buf, "Remote target");
11464 return buf;
11465 }
11466
11467 return normal_pid_to_str (ptid);
11468 }
11469 else
11470 {
11471 if (ptid_equal (magic_null_ptid, ptid))
11472 xsnprintf (buf, sizeof buf, "Thread <main>");
11473 else if (remote_multi_process_p (rs))
11474 if (ptid_get_lwp (ptid) == 0)
11475 return normal_pid_to_str (ptid);
11476 else
11477 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11478 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11479 else
11480 xsnprintf (buf, sizeof buf, "Thread %ld",
11481 ptid_get_lwp (ptid));
11482 return buf;
11483 }
11484 }
11485
11486 /* Get the address of the thread local variable in OBJFILE which is
11487 stored at OFFSET within the thread local storage for thread PTID. */
11488
11489 CORE_ADDR
11490 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11491 CORE_ADDR offset)
11492 {
11493 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11494 {
11495 struct remote_state *rs = get_remote_state ();
11496 char *p = rs->buf;
11497 char *endp = rs->buf + get_remote_packet_size ();
11498 enum packet_result result;
11499
11500 strcpy (p, "qGetTLSAddr:");
11501 p += strlen (p);
11502 p = write_ptid (p, endp, ptid);
11503 *p++ = ',';
11504 p += hexnumstr (p, offset);
11505 *p++ = ',';
11506 p += hexnumstr (p, lm);
11507 *p++ = '\0';
11508
11509 putpkt (rs->buf);
11510 getpkt (&rs->buf, &rs->buf_size, 0);
11511 result = packet_ok (rs->buf,
11512 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11513 if (result == PACKET_OK)
11514 {
11515 ULONGEST result;
11516
11517 unpack_varlen_hex (rs->buf, &result);
11518 return result;
11519 }
11520 else if (result == PACKET_UNKNOWN)
11521 throw_error (TLS_GENERIC_ERROR,
11522 _("Remote target doesn't support qGetTLSAddr packet"));
11523 else
11524 throw_error (TLS_GENERIC_ERROR,
11525 _("Remote target failed to process qGetTLSAddr request"));
11526 }
11527 else
11528 throw_error (TLS_GENERIC_ERROR,
11529 _("TLS not supported or disabled on this target"));
11530 /* Not reached. */
11531 return 0;
11532 }
11533
11534 /* Provide thread local base, i.e. Thread Information Block address.
11535 Returns 1 if ptid is found and thread_local_base is non zero. */
11536
11537 bool
11538 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11539 {
11540 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11541 {
11542 struct remote_state *rs = get_remote_state ();
11543 char *p = rs->buf;
11544 char *endp = rs->buf + get_remote_packet_size ();
11545 enum packet_result result;
11546
11547 strcpy (p, "qGetTIBAddr:");
11548 p += strlen (p);
11549 p = write_ptid (p, endp, ptid);
11550 *p++ = '\0';
11551
11552 putpkt (rs->buf);
11553 getpkt (&rs->buf, &rs->buf_size, 0);
11554 result = packet_ok (rs->buf,
11555 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11556 if (result == PACKET_OK)
11557 {
11558 ULONGEST result;
11559
11560 unpack_varlen_hex (rs->buf, &result);
11561 if (addr)
11562 *addr = (CORE_ADDR) result;
11563 return true;
11564 }
11565 else if (result == PACKET_UNKNOWN)
11566 error (_("Remote target doesn't support qGetTIBAddr packet"));
11567 else
11568 error (_("Remote target failed to process qGetTIBAddr request"));
11569 }
11570 else
11571 error (_("qGetTIBAddr not supported or disabled on this target"));
11572 /* Not reached. */
11573 return false;
11574 }
11575
11576 /* Support for inferring a target description based on the current
11577 architecture and the size of a 'g' packet. While the 'g' packet
11578 can have any size (since optional registers can be left off the
11579 end), some sizes are easily recognizable given knowledge of the
11580 approximate architecture. */
11581
11582 struct remote_g_packet_guess
11583 {
11584 int bytes;
11585 const struct target_desc *tdesc;
11586 };
11587 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11588 DEF_VEC_O(remote_g_packet_guess_s);
11589
11590 struct remote_g_packet_data
11591 {
11592 VEC(remote_g_packet_guess_s) *guesses;
11593 };
11594
11595 static struct gdbarch_data *remote_g_packet_data_handle;
11596
11597 static void *
11598 remote_g_packet_data_init (struct obstack *obstack)
11599 {
11600 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11601 }
11602
11603 void
11604 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11605 const struct target_desc *tdesc)
11606 {
11607 struct remote_g_packet_data *data
11608 = ((struct remote_g_packet_data *)
11609 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11610 struct remote_g_packet_guess new_guess, *guess;
11611 int ix;
11612
11613 gdb_assert (tdesc != NULL);
11614
11615 for (ix = 0;
11616 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11617 ix++)
11618 if (guess->bytes == bytes)
11619 internal_error (__FILE__, __LINE__,
11620 _("Duplicate g packet description added for size %d"),
11621 bytes);
11622
11623 new_guess.bytes = bytes;
11624 new_guess.tdesc = tdesc;
11625 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11626 }
11627
11628 /* Return 1 if remote_read_description would do anything on this target
11629 and architecture, 0 otherwise. */
11630
11631 static int
11632 remote_read_description_p (struct target_ops *target)
11633 {
11634 struct remote_g_packet_data *data
11635 = ((struct remote_g_packet_data *)
11636 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11637
11638 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11639 return 1;
11640
11641 return 0;
11642 }
11643
11644 const struct target_desc *
11645 remote_target::read_description ()
11646 {
11647 struct remote_g_packet_data *data
11648 = ((struct remote_g_packet_data *)
11649 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11650
11651 /* Do not try this during initial connection, when we do not know
11652 whether there is a running but stopped thread. */
11653 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11654 return beneath ()->read_description ();
11655
11656 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11657 {
11658 struct remote_g_packet_guess *guess;
11659 int ix;
11660 int bytes = send_g_packet ();
11661
11662 for (ix = 0;
11663 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11664 ix++)
11665 if (guess->bytes == bytes)
11666 return guess->tdesc;
11667
11668 /* We discard the g packet. A minor optimization would be to
11669 hold on to it, and fill the register cache once we have selected
11670 an architecture, but it's too tricky to do safely. */
11671 }
11672
11673 return beneath ()->read_description ();
11674 }
11675
11676 /* Remote file transfer support. This is host-initiated I/O, not
11677 target-initiated; for target-initiated, see remote-fileio.c. */
11678
11679 /* If *LEFT is at least the length of STRING, copy STRING to
11680 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11681 decrease *LEFT. Otherwise raise an error. */
11682
11683 static void
11684 remote_buffer_add_string (char **buffer, int *left, const char *string)
11685 {
11686 int len = strlen (string);
11687
11688 if (len > *left)
11689 error (_("Packet too long for target."));
11690
11691 memcpy (*buffer, string, len);
11692 *buffer += len;
11693 *left -= len;
11694
11695 /* NUL-terminate the buffer as a convenience, if there is
11696 room. */
11697 if (*left)
11698 **buffer = '\0';
11699 }
11700
11701 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11702 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11703 decrease *LEFT. Otherwise raise an error. */
11704
11705 static void
11706 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11707 int len)
11708 {
11709 if (2 * len > *left)
11710 error (_("Packet too long for target."));
11711
11712 bin2hex (bytes, *buffer, len);
11713 *buffer += 2 * len;
11714 *left -= 2 * len;
11715
11716 /* NUL-terminate the buffer as a convenience, if there is
11717 room. */
11718 if (*left)
11719 **buffer = '\0';
11720 }
11721
11722 /* If *LEFT is large enough, convert VALUE to hex and add it to
11723 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11724 decrease *LEFT. Otherwise raise an error. */
11725
11726 static void
11727 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11728 {
11729 int len = hexnumlen (value);
11730
11731 if (len > *left)
11732 error (_("Packet too long for target."));
11733
11734 hexnumstr (*buffer, value);
11735 *buffer += len;
11736 *left -= len;
11737
11738 /* NUL-terminate the buffer as a convenience, if there is
11739 room. */
11740 if (*left)
11741 **buffer = '\0';
11742 }
11743
11744 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11745 value, *REMOTE_ERRNO to the remote error number or zero if none
11746 was included, and *ATTACHMENT to point to the start of the annex
11747 if any. The length of the packet isn't needed here; there may
11748 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11749
11750 Return 0 if the packet could be parsed, -1 if it could not. If
11751 -1 is returned, the other variables may not be initialized. */
11752
11753 static int
11754 remote_hostio_parse_result (char *buffer, int *retcode,
11755 int *remote_errno, char **attachment)
11756 {
11757 char *p, *p2;
11758
11759 *remote_errno = 0;
11760 *attachment = NULL;
11761
11762 if (buffer[0] != 'F')
11763 return -1;
11764
11765 errno = 0;
11766 *retcode = strtol (&buffer[1], &p, 16);
11767 if (errno != 0 || p == &buffer[1])
11768 return -1;
11769
11770 /* Check for ",errno". */
11771 if (*p == ',')
11772 {
11773 errno = 0;
11774 *remote_errno = strtol (p + 1, &p2, 16);
11775 if (errno != 0 || p + 1 == p2)
11776 return -1;
11777 p = p2;
11778 }
11779
11780 /* Check for ";attachment". If there is no attachment, the
11781 packet should end here. */
11782 if (*p == ';')
11783 {
11784 *attachment = p + 1;
11785 return 0;
11786 }
11787 else if (*p == '\0')
11788 return 0;
11789 else
11790 return -1;
11791 }
11792
11793 /* Send a prepared I/O packet to the target and read its response.
11794 The prepared packet is in the global RS->BUF before this function
11795 is called, and the answer is there when we return.
11796
11797 COMMAND_BYTES is the length of the request to send, which may include
11798 binary data. WHICH_PACKET is the packet configuration to check
11799 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11800 is set to the error number and -1 is returned. Otherwise the value
11801 returned by the function is returned.
11802
11803 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11804 attachment is expected; an error will be reported if there's a
11805 mismatch. If one is found, *ATTACHMENT will be set to point into
11806 the packet buffer and *ATTACHMENT_LEN will be set to the
11807 attachment's length. */
11808
11809 int
11810 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11811 int *remote_errno, char **attachment,
11812 int *attachment_len)
11813 {
11814 struct remote_state *rs = get_remote_state ();
11815 int ret, bytes_read;
11816 char *attachment_tmp;
11817
11818 if (packet_support (which_packet) == PACKET_DISABLE)
11819 {
11820 *remote_errno = FILEIO_ENOSYS;
11821 return -1;
11822 }
11823
11824 putpkt_binary (rs->buf, command_bytes);
11825 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11826
11827 /* If it timed out, something is wrong. Don't try to parse the
11828 buffer. */
11829 if (bytes_read < 0)
11830 {
11831 *remote_errno = FILEIO_EINVAL;
11832 return -1;
11833 }
11834
11835 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11836 {
11837 case PACKET_ERROR:
11838 *remote_errno = FILEIO_EINVAL;
11839 return -1;
11840 case PACKET_UNKNOWN:
11841 *remote_errno = FILEIO_ENOSYS;
11842 return -1;
11843 case PACKET_OK:
11844 break;
11845 }
11846
11847 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11848 &attachment_tmp))
11849 {
11850 *remote_errno = FILEIO_EINVAL;
11851 return -1;
11852 }
11853
11854 /* Make sure we saw an attachment if and only if we expected one. */
11855 if ((attachment_tmp == NULL && attachment != NULL)
11856 || (attachment_tmp != NULL && attachment == NULL))
11857 {
11858 *remote_errno = FILEIO_EINVAL;
11859 return -1;
11860 }
11861
11862 /* If an attachment was found, it must point into the packet buffer;
11863 work out how many bytes there were. */
11864 if (attachment_tmp != NULL)
11865 {
11866 *attachment = attachment_tmp;
11867 *attachment_len = bytes_read - (*attachment - rs->buf);
11868 }
11869
11870 return ret;
11871 }
11872
11873 /* See declaration.h. */
11874
11875 void
11876 readahead_cache::invalidate ()
11877 {
11878 this->fd = -1;
11879 }
11880
11881 /* See declaration.h. */
11882
11883 void
11884 readahead_cache::invalidate_fd (int fd)
11885 {
11886 if (this->fd == fd)
11887 this->fd = -1;
11888 }
11889
11890 /* Set the filesystem remote_hostio functions that take FILENAME
11891 arguments will use. Return 0 on success, or -1 if an error
11892 occurs (and set *REMOTE_ERRNO). */
11893
11894 int
11895 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11896 int *remote_errno)
11897 {
11898 struct remote_state *rs = get_remote_state ();
11899 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11900 char *p = rs->buf;
11901 int left = get_remote_packet_size () - 1;
11902 char arg[9];
11903 int ret;
11904
11905 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11906 return 0;
11907
11908 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11909 return 0;
11910
11911 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11912
11913 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11914 remote_buffer_add_string (&p, &left, arg);
11915
11916 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11917 remote_errno, NULL, NULL);
11918
11919 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11920 return 0;
11921
11922 if (ret == 0)
11923 rs->fs_pid = required_pid;
11924
11925 return ret;
11926 }
11927
11928 /* Implementation of to_fileio_open. */
11929
11930 int
11931 remote_target::remote_hostio_open (inferior *inf, const char *filename,
11932 int flags, int mode, int warn_if_slow,
11933 int *remote_errno)
11934 {
11935 struct remote_state *rs = get_remote_state ();
11936 char *p = rs->buf;
11937 int left = get_remote_packet_size () - 1;
11938
11939 if (warn_if_slow)
11940 {
11941 static int warning_issued = 0;
11942
11943 printf_unfiltered (_("Reading %s from remote target...\n"),
11944 filename);
11945
11946 if (!warning_issued)
11947 {
11948 warning (_("File transfers from remote targets can be slow."
11949 " Use \"set sysroot\" to access files locally"
11950 " instead."));
11951 warning_issued = 1;
11952 }
11953 }
11954
11955 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11956 return -1;
11957
11958 remote_buffer_add_string (&p, &left, "vFile:open:");
11959
11960 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11961 strlen (filename));
11962 remote_buffer_add_string (&p, &left, ",");
11963
11964 remote_buffer_add_int (&p, &left, flags);
11965 remote_buffer_add_string (&p, &left, ",");
11966
11967 remote_buffer_add_int (&p, &left, mode);
11968
11969 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11970 remote_errno, NULL, NULL);
11971 }
11972
11973 int
11974 remote_target::fileio_open (struct inferior *inf, const char *filename,
11975 int flags, int mode, int warn_if_slow,
11976 int *remote_errno)
11977 {
11978 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
11979 remote_errno);
11980 }
11981
11982 /* Implementation of to_fileio_pwrite. */
11983
11984 int
11985 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
11986 ULONGEST offset, int *remote_errno)
11987 {
11988 struct remote_state *rs = get_remote_state ();
11989 char *p = rs->buf;
11990 int left = get_remote_packet_size ();
11991 int out_len;
11992
11993 rs->readahead_cache.invalidate_fd (fd);
11994
11995 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11996
11997 remote_buffer_add_int (&p, &left, fd);
11998 remote_buffer_add_string (&p, &left, ",");
11999
12000 remote_buffer_add_int (&p, &left, offset);
12001 remote_buffer_add_string (&p, &left, ",");
12002
12003 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12004 get_remote_packet_size () - (p - rs->buf));
12005
12006 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12007 remote_errno, NULL, NULL);
12008 }
12009
12010 int
12011 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12012 ULONGEST offset, int *remote_errno)
12013 {
12014 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12015 }
12016
12017 /* Helper for the implementation of to_fileio_pread. Read the file
12018 from the remote side with vFile:pread. */
12019
12020 int
12021 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12022 ULONGEST offset, int *remote_errno)
12023 {
12024 struct remote_state *rs = get_remote_state ();
12025 char *p = rs->buf;
12026 char *attachment;
12027 int left = get_remote_packet_size ();
12028 int ret, attachment_len;
12029 int read_len;
12030
12031 remote_buffer_add_string (&p, &left, "vFile:pread:");
12032
12033 remote_buffer_add_int (&p, &left, fd);
12034 remote_buffer_add_string (&p, &left, ",");
12035
12036 remote_buffer_add_int (&p, &left, len);
12037 remote_buffer_add_string (&p, &left, ",");
12038
12039 remote_buffer_add_int (&p, &left, offset);
12040
12041 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12042 remote_errno, &attachment,
12043 &attachment_len);
12044
12045 if (ret < 0)
12046 return ret;
12047
12048 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12049 read_buf, len);
12050 if (read_len != ret)
12051 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12052
12053 return ret;
12054 }
12055
12056 /* See declaration.h. */
12057
12058 int
12059 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12060 ULONGEST offset)
12061 {
12062 if (this->fd == fd
12063 && this->offset <= offset
12064 && offset < this->offset + this->bufsize)
12065 {
12066 ULONGEST max = this->offset + this->bufsize;
12067
12068 if (offset + len > max)
12069 len = max - offset;
12070
12071 memcpy (read_buf, this->buf + offset - this->offset, len);
12072 return len;
12073 }
12074
12075 return 0;
12076 }
12077
12078 /* Implementation of to_fileio_pread. */
12079
12080 int
12081 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12082 ULONGEST offset, int *remote_errno)
12083 {
12084 int ret;
12085 struct remote_state *rs = get_remote_state ();
12086 readahead_cache *cache = &rs->readahead_cache;
12087
12088 ret = cache->pread (fd, read_buf, len, offset);
12089 if (ret > 0)
12090 {
12091 cache->hit_count++;
12092
12093 if (remote_debug)
12094 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12095 pulongest (cache->hit_count));
12096 return ret;
12097 }
12098
12099 cache->miss_count++;
12100 if (remote_debug)
12101 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12102 pulongest (cache->miss_count));
12103
12104 cache->fd = fd;
12105 cache->offset = offset;
12106 cache->bufsize = get_remote_packet_size ();
12107 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12108
12109 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12110 cache->offset, remote_errno);
12111 if (ret <= 0)
12112 {
12113 cache->invalidate_fd (fd);
12114 return ret;
12115 }
12116
12117 cache->bufsize = ret;
12118 return cache->pread (fd, read_buf, len, offset);
12119 }
12120
12121 int
12122 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12123 ULONGEST offset, int *remote_errno)
12124 {
12125 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12126 }
12127
12128 /* Implementation of to_fileio_close. */
12129
12130 int
12131 remote_target::remote_hostio_close (int fd, int *remote_errno)
12132 {
12133 struct remote_state *rs = get_remote_state ();
12134 char *p = rs->buf;
12135 int left = get_remote_packet_size () - 1;
12136
12137 rs->readahead_cache.invalidate_fd (fd);
12138
12139 remote_buffer_add_string (&p, &left, "vFile:close:");
12140
12141 remote_buffer_add_int (&p, &left, fd);
12142
12143 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12144 remote_errno, NULL, NULL);
12145 }
12146
12147 int
12148 remote_target::fileio_close (int fd, int *remote_errno)
12149 {
12150 return remote_hostio_close (fd, remote_errno);
12151 }
12152
12153 /* Implementation of to_fileio_unlink. */
12154
12155 int
12156 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12157 int *remote_errno)
12158 {
12159 struct remote_state *rs = get_remote_state ();
12160 char *p = rs->buf;
12161 int left = get_remote_packet_size () - 1;
12162
12163 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12164 return -1;
12165
12166 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12167
12168 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12169 strlen (filename));
12170
12171 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12172 remote_errno, NULL, NULL);
12173 }
12174
12175 int
12176 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12177 int *remote_errno)
12178 {
12179 return remote_hostio_unlink (inf, filename, remote_errno);
12180 }
12181
12182 /* Implementation of to_fileio_readlink. */
12183
12184 gdb::optional<std::string>
12185 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12186 int *remote_errno)
12187 {
12188 struct remote_state *rs = get_remote_state ();
12189 char *p = rs->buf;
12190 char *attachment;
12191 int left = get_remote_packet_size ();
12192 int len, attachment_len;
12193 int read_len;
12194
12195 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12196 return {};
12197
12198 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12199
12200 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12201 strlen (filename));
12202
12203 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12204 remote_errno, &attachment,
12205 &attachment_len);
12206
12207 if (len < 0)
12208 return {};
12209
12210 std::string ret (len, '\0');
12211
12212 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12213 (gdb_byte *) &ret[0], len);
12214 if (read_len != len)
12215 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12216
12217 return ret;
12218 }
12219
12220 /* Implementation of to_fileio_fstat. */
12221
12222 int
12223 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12224 {
12225 struct remote_state *rs = get_remote_state ();
12226 char *p = rs->buf;
12227 int left = get_remote_packet_size ();
12228 int attachment_len, ret;
12229 char *attachment;
12230 struct fio_stat fst;
12231 int read_len;
12232
12233 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12234
12235 remote_buffer_add_int (&p, &left, fd);
12236
12237 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12238 remote_errno, &attachment,
12239 &attachment_len);
12240 if (ret < 0)
12241 {
12242 if (*remote_errno != FILEIO_ENOSYS)
12243 return ret;
12244
12245 /* Strictly we should return -1, ENOSYS here, but when
12246 "set sysroot remote:" was implemented in August 2008
12247 BFD's need for a stat function was sidestepped with
12248 this hack. This was not remedied until March 2015
12249 so we retain the previous behavior to avoid breaking
12250 compatibility.
12251
12252 Note that the memset is a March 2015 addition; older
12253 GDBs set st_size *and nothing else* so the structure
12254 would have garbage in all other fields. This might
12255 break something but retaining the previous behavior
12256 here would be just too wrong. */
12257
12258 memset (st, 0, sizeof (struct stat));
12259 st->st_size = INT_MAX;
12260 return 0;
12261 }
12262
12263 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12264 (gdb_byte *) &fst, sizeof (fst));
12265
12266 if (read_len != ret)
12267 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12268
12269 if (read_len != sizeof (fst))
12270 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12271 read_len, (int) sizeof (fst));
12272
12273 remote_fileio_to_host_stat (&fst, st);
12274
12275 return 0;
12276 }
12277
12278 /* Implementation of to_filesystem_is_local. */
12279
12280 bool
12281 remote_target::filesystem_is_local ()
12282 {
12283 /* Valgrind GDB presents itself as a remote target but works
12284 on the local filesystem: it does not implement remote get
12285 and users are not expected to set a sysroot. To handle
12286 this case we treat the remote filesystem as local if the
12287 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12288 does not support vFile:open. */
12289 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12290 {
12291 enum packet_support ps = packet_support (PACKET_vFile_open);
12292
12293 if (ps == PACKET_SUPPORT_UNKNOWN)
12294 {
12295 int fd, remote_errno;
12296
12297 /* Try opening a file to probe support. The supplied
12298 filename is irrelevant, we only care about whether
12299 the stub recognizes the packet or not. */
12300 fd = remote_hostio_open (NULL, "just probing",
12301 FILEIO_O_RDONLY, 0700, 0,
12302 &remote_errno);
12303
12304 if (fd >= 0)
12305 remote_hostio_close (fd, &remote_errno);
12306
12307 ps = packet_support (PACKET_vFile_open);
12308 }
12309
12310 if (ps == PACKET_DISABLE)
12311 {
12312 static int warning_issued = 0;
12313
12314 if (!warning_issued)
12315 {
12316 warning (_("remote target does not support file"
12317 " transfer, attempting to access files"
12318 " from local filesystem."));
12319 warning_issued = 1;
12320 }
12321
12322 return true;
12323 }
12324 }
12325
12326 return false;
12327 }
12328
12329 static int
12330 remote_fileio_errno_to_host (int errnum)
12331 {
12332 switch (errnum)
12333 {
12334 case FILEIO_EPERM:
12335 return EPERM;
12336 case FILEIO_ENOENT:
12337 return ENOENT;
12338 case FILEIO_EINTR:
12339 return EINTR;
12340 case FILEIO_EIO:
12341 return EIO;
12342 case FILEIO_EBADF:
12343 return EBADF;
12344 case FILEIO_EACCES:
12345 return EACCES;
12346 case FILEIO_EFAULT:
12347 return EFAULT;
12348 case FILEIO_EBUSY:
12349 return EBUSY;
12350 case FILEIO_EEXIST:
12351 return EEXIST;
12352 case FILEIO_ENODEV:
12353 return ENODEV;
12354 case FILEIO_ENOTDIR:
12355 return ENOTDIR;
12356 case FILEIO_EISDIR:
12357 return EISDIR;
12358 case FILEIO_EINVAL:
12359 return EINVAL;
12360 case FILEIO_ENFILE:
12361 return ENFILE;
12362 case FILEIO_EMFILE:
12363 return EMFILE;
12364 case FILEIO_EFBIG:
12365 return EFBIG;
12366 case FILEIO_ENOSPC:
12367 return ENOSPC;
12368 case FILEIO_ESPIPE:
12369 return ESPIPE;
12370 case FILEIO_EROFS:
12371 return EROFS;
12372 case FILEIO_ENOSYS:
12373 return ENOSYS;
12374 case FILEIO_ENAMETOOLONG:
12375 return ENAMETOOLONG;
12376 }
12377 return -1;
12378 }
12379
12380 static char *
12381 remote_hostio_error (int errnum)
12382 {
12383 int host_error = remote_fileio_errno_to_host (errnum);
12384
12385 if (host_error == -1)
12386 error (_("Unknown remote I/O error %d"), errnum);
12387 else
12388 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12389 }
12390
12391 /* A RAII wrapper around a remote file descriptor. */
12392
12393 class scoped_remote_fd
12394 {
12395 public:
12396 scoped_remote_fd (remote_target *remote, int fd)
12397 : m_remote (remote), m_fd (fd)
12398 {
12399 }
12400
12401 ~scoped_remote_fd ()
12402 {
12403 if (m_fd != -1)
12404 {
12405 try
12406 {
12407 int remote_errno;
12408 m_remote->remote_hostio_close (m_fd, &remote_errno);
12409 }
12410 catch (...)
12411 {
12412 /* Swallow exception before it escapes the dtor. If
12413 something goes wrong, likely the connection is gone,
12414 and there's nothing else that can be done. */
12415 }
12416 }
12417 }
12418
12419 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12420
12421 /* Release ownership of the file descriptor, and return it. */
12422 int release () noexcept
12423 {
12424 int fd = m_fd;
12425 m_fd = -1;
12426 return fd;
12427 }
12428
12429 /* Return the owned file descriptor. */
12430 int get () const noexcept
12431 {
12432 return m_fd;
12433 }
12434
12435 private:
12436 /* The remote target. */
12437 remote_target *m_remote;
12438
12439 /* The owned remote I/O file descriptor. */
12440 int m_fd;
12441 };
12442
12443 void
12444 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12445 {
12446 remote_target *remote = get_current_remote_target ();
12447
12448 if (remote == nullptr)
12449 error (_("command can only be used with remote target"));
12450
12451 remote->remote_file_put (local_file, remote_file, from_tty);
12452 }
12453
12454 void
12455 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12456 int from_tty)
12457 {
12458 int retcode, remote_errno, bytes, io_size;
12459 int bytes_in_buffer;
12460 int saw_eof;
12461 ULONGEST offset;
12462
12463 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12464 if (file == NULL)
12465 perror_with_name (local_file);
12466
12467 scoped_remote_fd fd
12468 (this, remote_hostio_open (NULL,
12469 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12470 | FILEIO_O_TRUNC),
12471 0700, 0, &remote_errno));
12472 if (fd.get () == -1)
12473 remote_hostio_error (remote_errno);
12474
12475 /* Send up to this many bytes at once. They won't all fit in the
12476 remote packet limit, so we'll transfer slightly fewer. */
12477 io_size = get_remote_packet_size ();
12478 gdb::byte_vector buffer (io_size);
12479
12480 bytes_in_buffer = 0;
12481 saw_eof = 0;
12482 offset = 0;
12483 while (bytes_in_buffer || !saw_eof)
12484 {
12485 if (!saw_eof)
12486 {
12487 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12488 io_size - bytes_in_buffer,
12489 file.get ());
12490 if (bytes == 0)
12491 {
12492 if (ferror (file.get ()))
12493 error (_("Error reading %s."), local_file);
12494 else
12495 {
12496 /* EOF. Unless there is something still in the
12497 buffer from the last iteration, we are done. */
12498 saw_eof = 1;
12499 if (bytes_in_buffer == 0)
12500 break;
12501 }
12502 }
12503 }
12504 else
12505 bytes = 0;
12506
12507 bytes += bytes_in_buffer;
12508 bytes_in_buffer = 0;
12509
12510 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12511 offset, &remote_errno);
12512
12513 if (retcode < 0)
12514 remote_hostio_error (remote_errno);
12515 else if (retcode == 0)
12516 error (_("Remote write of %d bytes returned 0!"), bytes);
12517 else if (retcode < bytes)
12518 {
12519 /* Short write. Save the rest of the read data for the next
12520 write. */
12521 bytes_in_buffer = bytes - retcode;
12522 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12523 }
12524
12525 offset += retcode;
12526 }
12527
12528 if (remote_hostio_close (fd.release (), &remote_errno))
12529 remote_hostio_error (remote_errno);
12530
12531 if (from_tty)
12532 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12533 }
12534
12535 void
12536 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12537 {
12538 remote_target *remote = get_current_remote_target ();
12539
12540 if (remote == nullptr)
12541 error (_("command can only be used with remote target"));
12542
12543 remote->remote_file_get (remote_file, local_file, from_tty);
12544 }
12545
12546 void
12547 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12548 int from_tty)
12549 {
12550 int remote_errno, bytes, io_size;
12551 ULONGEST offset;
12552
12553 scoped_remote_fd fd
12554 (this, remote_hostio_open (NULL,
12555 remote_file, FILEIO_O_RDONLY, 0, 0,
12556 &remote_errno));
12557 if (fd.get () == -1)
12558 remote_hostio_error (remote_errno);
12559
12560 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12561 if (file == NULL)
12562 perror_with_name (local_file);
12563
12564 /* Send up to this many bytes at once. They won't all fit in the
12565 remote packet limit, so we'll transfer slightly fewer. */
12566 io_size = get_remote_packet_size ();
12567 gdb::byte_vector buffer (io_size);
12568
12569 offset = 0;
12570 while (1)
12571 {
12572 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12573 &remote_errno);
12574 if (bytes == 0)
12575 /* Success, but no bytes, means end-of-file. */
12576 break;
12577 if (bytes == -1)
12578 remote_hostio_error (remote_errno);
12579
12580 offset += bytes;
12581
12582 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12583 if (bytes == 0)
12584 perror_with_name (local_file);
12585 }
12586
12587 if (remote_hostio_close (fd.release (), &remote_errno))
12588 remote_hostio_error (remote_errno);
12589
12590 if (from_tty)
12591 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12592 }
12593
12594 void
12595 remote_file_delete (const char *remote_file, int from_tty)
12596 {
12597 remote_target *remote = get_current_remote_target ();
12598
12599 if (remote == nullptr)
12600 error (_("command can only be used with remote target"));
12601
12602 remote->remote_file_delete (remote_file, from_tty);
12603 }
12604
12605 void
12606 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12607 {
12608 int retcode, remote_errno;
12609
12610 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12611 if (retcode == -1)
12612 remote_hostio_error (remote_errno);
12613
12614 if (from_tty)
12615 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12616 }
12617
12618 static void
12619 remote_put_command (const char *args, int from_tty)
12620 {
12621 if (args == NULL)
12622 error_no_arg (_("file to put"));
12623
12624 gdb_argv argv (args);
12625 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12626 error (_("Invalid parameters to remote put"));
12627
12628 remote_file_put (argv[0], argv[1], from_tty);
12629 }
12630
12631 static void
12632 remote_get_command (const char *args, int from_tty)
12633 {
12634 if (args == NULL)
12635 error_no_arg (_("file to get"));
12636
12637 gdb_argv argv (args);
12638 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12639 error (_("Invalid parameters to remote get"));
12640
12641 remote_file_get (argv[0], argv[1], from_tty);
12642 }
12643
12644 static void
12645 remote_delete_command (const char *args, int from_tty)
12646 {
12647 if (args == NULL)
12648 error_no_arg (_("file to delete"));
12649
12650 gdb_argv argv (args);
12651 if (argv[0] == NULL || argv[1] != NULL)
12652 error (_("Invalid parameters to remote delete"));
12653
12654 remote_file_delete (argv[0], from_tty);
12655 }
12656
12657 static void
12658 remote_command (const char *args, int from_tty)
12659 {
12660 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12661 }
12662
12663 bool
12664 remote_target::can_execute_reverse ()
12665 {
12666 if (packet_support (PACKET_bs) == PACKET_ENABLE
12667 || packet_support (PACKET_bc) == PACKET_ENABLE)
12668 return true;
12669 else
12670 return false;
12671 }
12672
12673 bool
12674 remote_target::supports_non_stop ()
12675 {
12676 return true;
12677 }
12678
12679 bool
12680 remote_target::supports_disable_randomization ()
12681 {
12682 /* Only supported in extended mode. */
12683 return false;
12684 }
12685
12686 bool
12687 remote_target::supports_multi_process ()
12688 {
12689 struct remote_state *rs = get_remote_state ();
12690
12691 return remote_multi_process_p (rs);
12692 }
12693
12694 static int
12695 remote_supports_cond_tracepoints ()
12696 {
12697 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12698 }
12699
12700 bool
12701 remote_target::supports_evaluation_of_breakpoint_conditions ()
12702 {
12703 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12704 }
12705
12706 static int
12707 remote_supports_fast_tracepoints ()
12708 {
12709 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12710 }
12711
12712 static int
12713 remote_supports_static_tracepoints ()
12714 {
12715 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12716 }
12717
12718 static int
12719 remote_supports_install_in_trace ()
12720 {
12721 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12722 }
12723
12724 bool
12725 remote_target::supports_enable_disable_tracepoint ()
12726 {
12727 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12728 == PACKET_ENABLE);
12729 }
12730
12731 bool
12732 remote_target::supports_string_tracing ()
12733 {
12734 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12735 }
12736
12737 bool
12738 remote_target::can_run_breakpoint_commands ()
12739 {
12740 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12741 }
12742
12743 void
12744 remote_target::trace_init ()
12745 {
12746 struct remote_state *rs = get_remote_state ();
12747
12748 putpkt ("QTinit");
12749 remote_get_noisy_reply ();
12750 if (strcmp (rs->buf, "OK") != 0)
12751 error (_("Target does not support this command."));
12752 }
12753
12754 /* Recursive routine to walk through command list including loops, and
12755 download packets for each command. */
12756
12757 void
12758 remote_target::remote_download_command_source (int num, ULONGEST addr,
12759 struct command_line *cmds)
12760 {
12761 struct remote_state *rs = get_remote_state ();
12762 struct command_line *cmd;
12763
12764 for (cmd = cmds; cmd; cmd = cmd->next)
12765 {
12766 QUIT; /* Allow user to bail out with ^C. */
12767 strcpy (rs->buf, "QTDPsrc:");
12768 encode_source_string (num, addr, "cmd", cmd->line,
12769 rs->buf + strlen (rs->buf),
12770 rs->buf_size - strlen (rs->buf));
12771 putpkt (rs->buf);
12772 remote_get_noisy_reply ();
12773 if (strcmp (rs->buf, "OK"))
12774 warning (_("Target does not support source download."));
12775
12776 if (cmd->control_type == while_control
12777 || cmd->control_type == while_stepping_control)
12778 {
12779 remote_download_command_source (num, addr, cmd->body_list_0.get ());
12780
12781 QUIT; /* Allow user to bail out with ^C. */
12782 strcpy (rs->buf, "QTDPsrc:");
12783 encode_source_string (num, addr, "cmd", "end",
12784 rs->buf + strlen (rs->buf),
12785 rs->buf_size - strlen (rs->buf));
12786 putpkt (rs->buf);
12787 remote_get_noisy_reply ();
12788 if (strcmp (rs->buf, "OK"))
12789 warning (_("Target does not support source download."));
12790 }
12791 }
12792 }
12793
12794 void
12795 remote_target::download_tracepoint (struct bp_location *loc)
12796 {
12797 #define BUF_SIZE 2048
12798
12799 CORE_ADDR tpaddr;
12800 char addrbuf[40];
12801 char buf[BUF_SIZE];
12802 std::vector<std::string> tdp_actions;
12803 std::vector<std::string> stepping_actions;
12804 char *pkt;
12805 struct breakpoint *b = loc->owner;
12806 struct tracepoint *t = (struct tracepoint *) b;
12807 struct remote_state *rs = get_remote_state ();
12808
12809 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12810
12811 tpaddr = loc->address;
12812 sprintf_vma (addrbuf, tpaddr);
12813 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12814 addrbuf, /* address */
12815 (b->enable_state == bp_enabled ? 'E' : 'D'),
12816 t->step_count, t->pass_count);
12817 /* Fast tracepoints are mostly handled by the target, but we can
12818 tell the target how big of an instruction block should be moved
12819 around. */
12820 if (b->type == bp_fast_tracepoint)
12821 {
12822 /* Only test for support at download time; we may not know
12823 target capabilities at definition time. */
12824 if (remote_supports_fast_tracepoints ())
12825 {
12826 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12827 NULL))
12828 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12829 gdb_insn_length (loc->gdbarch, tpaddr));
12830 else
12831 /* If it passed validation at definition but fails now,
12832 something is very wrong. */
12833 internal_error (__FILE__, __LINE__,
12834 _("Fast tracepoint not "
12835 "valid during download"));
12836 }
12837 else
12838 /* Fast tracepoints are functionally identical to regular
12839 tracepoints, so don't take lack of support as a reason to
12840 give up on the trace run. */
12841 warning (_("Target does not support fast tracepoints, "
12842 "downloading %d as regular tracepoint"), b->number);
12843 }
12844 else if (b->type == bp_static_tracepoint)
12845 {
12846 /* Only test for support at download time; we may not know
12847 target capabilities at definition time. */
12848 if (remote_supports_static_tracepoints ())
12849 {
12850 struct static_tracepoint_marker marker;
12851
12852 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12853 strcat (buf, ":S");
12854 else
12855 error (_("Static tracepoint not valid during download"));
12856 }
12857 else
12858 /* Fast tracepoints are functionally identical to regular
12859 tracepoints, so don't take lack of support as a reason
12860 to give up on the trace run. */
12861 error (_("Target does not support static tracepoints"));
12862 }
12863 /* If the tracepoint has a conditional, make it into an agent
12864 expression and append to the definition. */
12865 if (loc->cond)
12866 {
12867 /* Only test support at download time, we may not know target
12868 capabilities at definition time. */
12869 if (remote_supports_cond_tracepoints ())
12870 {
12871 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12872 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12873 aexpr->len);
12874 pkt = buf + strlen (buf);
12875 for (int ndx = 0; ndx < aexpr->len; ++ndx)
12876 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12877 *pkt = '\0';
12878 }
12879 else
12880 warning (_("Target does not support conditional tracepoints, "
12881 "ignoring tp %d cond"), b->number);
12882 }
12883
12884 if (b->commands || *default_collect)
12885 strcat (buf, "-");
12886 putpkt (buf);
12887 remote_get_noisy_reply ();
12888 if (strcmp (rs->buf, "OK"))
12889 error (_("Target does not support tracepoints."));
12890
12891 /* do_single_steps (t); */
12892 for (auto action_it = tdp_actions.begin ();
12893 action_it != tdp_actions.end (); action_it++)
12894 {
12895 QUIT; /* Allow user to bail out with ^C. */
12896
12897 bool has_more = (action_it != tdp_actions.end ()
12898 || !stepping_actions.empty ());
12899
12900 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12901 b->number, addrbuf, /* address */
12902 action_it->c_str (),
12903 has_more ? '-' : 0);
12904 putpkt (buf);
12905 remote_get_noisy_reply ();
12906 if (strcmp (rs->buf, "OK"))
12907 error (_("Error on target while setting tracepoints."));
12908 }
12909
12910 for (auto action_it = stepping_actions.begin ();
12911 action_it != stepping_actions.end (); action_it++)
12912 {
12913 QUIT; /* Allow user to bail out with ^C. */
12914
12915 bool is_first = action_it == stepping_actions.begin ();
12916 bool has_more = action_it != stepping_actions.end ();
12917
12918 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12919 b->number, addrbuf, /* address */
12920 is_first ? "S" : "",
12921 action_it->c_str (),
12922 has_more ? "-" : "");
12923 putpkt (buf);
12924 remote_get_noisy_reply ();
12925 if (strcmp (rs->buf, "OK"))
12926 error (_("Error on target while setting tracepoints."));
12927 }
12928
12929 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12930 {
12931 if (b->location != NULL)
12932 {
12933 strcpy (buf, "QTDPsrc:");
12934 encode_source_string (b->number, loc->address, "at",
12935 event_location_to_string (b->location.get ()),
12936 buf + strlen (buf), 2048 - strlen (buf));
12937 putpkt (buf);
12938 remote_get_noisy_reply ();
12939 if (strcmp (rs->buf, "OK"))
12940 warning (_("Target does not support source download."));
12941 }
12942 if (b->cond_string)
12943 {
12944 strcpy (buf, "QTDPsrc:");
12945 encode_source_string (b->number, loc->address,
12946 "cond", b->cond_string, buf + strlen (buf),
12947 2048 - strlen (buf));
12948 putpkt (buf);
12949 remote_get_noisy_reply ();
12950 if (strcmp (rs->buf, "OK"))
12951 warning (_("Target does not support source download."));
12952 }
12953 remote_download_command_source (b->number, loc->address,
12954 breakpoint_commands (b));
12955 }
12956 }
12957
12958 bool
12959 remote_target::can_download_tracepoint ()
12960 {
12961 struct remote_state *rs = get_remote_state ();
12962 struct trace_status *ts;
12963 int status;
12964
12965 /* Don't try to install tracepoints until we've relocated our
12966 symbols, and fetched and merged the target's tracepoint list with
12967 ours. */
12968 if (rs->starting_up)
12969 return false;
12970
12971 ts = current_trace_status ();
12972 status = get_trace_status (ts);
12973
12974 if (status == -1 || !ts->running_known || !ts->running)
12975 return false;
12976
12977 /* If we are in a tracing experiment, but remote stub doesn't support
12978 installing tracepoint in trace, we have to return. */
12979 if (!remote_supports_install_in_trace ())
12980 return false;
12981
12982 return true;
12983 }
12984
12985
12986 void
12987 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12988 {
12989 struct remote_state *rs = get_remote_state ();
12990 char *p;
12991
12992 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12993 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12994 tsv.builtin);
12995 p = rs->buf + strlen (rs->buf);
12996 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12997 error (_("Trace state variable name too long for tsv definition packet"));
12998 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12999 *p++ = '\0';
13000 putpkt (rs->buf);
13001 remote_get_noisy_reply ();
13002 if (*rs->buf == '\0')
13003 error (_("Target does not support this command."));
13004 if (strcmp (rs->buf, "OK") != 0)
13005 error (_("Error on target while downloading trace state variable."));
13006 }
13007
13008 void
13009 remote_target::enable_tracepoint (struct bp_location *location)
13010 {
13011 struct remote_state *rs = get_remote_state ();
13012 char addr_buf[40];
13013
13014 sprintf_vma (addr_buf, location->address);
13015 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13016 location->owner->number, addr_buf);
13017 putpkt (rs->buf);
13018 remote_get_noisy_reply ();
13019 if (*rs->buf == '\0')
13020 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13021 if (strcmp (rs->buf, "OK") != 0)
13022 error (_("Error on target while enabling tracepoint."));
13023 }
13024
13025 void
13026 remote_target::disable_tracepoint (struct bp_location *location)
13027 {
13028 struct remote_state *rs = get_remote_state ();
13029 char addr_buf[40];
13030
13031 sprintf_vma (addr_buf, location->address);
13032 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13033 location->owner->number, addr_buf);
13034 putpkt (rs->buf);
13035 remote_get_noisy_reply ();
13036 if (*rs->buf == '\0')
13037 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13038 if (strcmp (rs->buf, "OK") != 0)
13039 error (_("Error on target while disabling tracepoint."));
13040 }
13041
13042 void
13043 remote_target::trace_set_readonly_regions ()
13044 {
13045 asection *s;
13046 bfd *abfd = NULL;
13047 bfd_size_type size;
13048 bfd_vma vma;
13049 int anysecs = 0;
13050 int offset = 0;
13051
13052 if (!exec_bfd)
13053 return; /* No information to give. */
13054
13055 struct remote_state *rs = get_remote_state ();
13056
13057 strcpy (rs->buf, "QTro");
13058 offset = strlen (rs->buf);
13059 for (s = exec_bfd->sections; s; s = s->next)
13060 {
13061 char tmp1[40], tmp2[40];
13062 int sec_length;
13063
13064 if ((s->flags & SEC_LOAD) == 0 ||
13065 /* (s->flags & SEC_CODE) == 0 || */
13066 (s->flags & SEC_READONLY) == 0)
13067 continue;
13068
13069 anysecs = 1;
13070 vma = bfd_get_section_vma (abfd, s);
13071 size = bfd_get_section_size (s);
13072 sprintf_vma (tmp1, vma);
13073 sprintf_vma (tmp2, vma + size);
13074 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13075 if (offset + sec_length + 1 > rs->buf_size)
13076 {
13077 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13078 warning (_("\
13079 Too many sections for read-only sections definition packet."));
13080 break;
13081 }
13082 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
13083 tmp1, tmp2);
13084 offset += sec_length;
13085 }
13086 if (anysecs)
13087 {
13088 putpkt (rs->buf);
13089 getpkt (&rs->buf, &rs->buf_size, 0);
13090 }
13091 }
13092
13093 void
13094 remote_target::trace_start ()
13095 {
13096 struct remote_state *rs = get_remote_state ();
13097
13098 putpkt ("QTStart");
13099 remote_get_noisy_reply ();
13100 if (*rs->buf == '\0')
13101 error (_("Target does not support this command."));
13102 if (strcmp (rs->buf, "OK") != 0)
13103 error (_("Bogus reply from target: %s"), rs->buf);
13104 }
13105
13106 int
13107 remote_target::get_trace_status (struct trace_status *ts)
13108 {
13109 /* Initialize it just to avoid a GCC false warning. */
13110 char *p = NULL;
13111 /* FIXME we need to get register block size some other way. */
13112 extern int trace_regblock_size;
13113 enum packet_result result;
13114 struct remote_state *rs = get_remote_state ();
13115
13116 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13117 return -1;
13118
13119 trace_regblock_size
13120 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13121
13122 putpkt ("qTStatus");
13123
13124 TRY
13125 {
13126 p = remote_get_noisy_reply ();
13127 }
13128 CATCH (ex, RETURN_MASK_ERROR)
13129 {
13130 if (ex.error != TARGET_CLOSE_ERROR)
13131 {
13132 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13133 return -1;
13134 }
13135 throw_exception (ex);
13136 }
13137 END_CATCH
13138
13139 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13140
13141 /* If the remote target doesn't do tracing, flag it. */
13142 if (result == PACKET_UNKNOWN)
13143 return -1;
13144
13145 /* We're working with a live target. */
13146 ts->filename = NULL;
13147
13148 if (*p++ != 'T')
13149 error (_("Bogus trace status reply from target: %s"), rs->buf);
13150
13151 /* Function 'parse_trace_status' sets default value of each field of
13152 'ts' at first, so we don't have to do it here. */
13153 parse_trace_status (p, ts);
13154
13155 return ts->running;
13156 }
13157
13158 void
13159 remote_target::get_tracepoint_status (struct breakpoint *bp,
13160 struct uploaded_tp *utp)
13161 {
13162 struct remote_state *rs = get_remote_state ();
13163 char *reply;
13164 struct bp_location *loc;
13165 struct tracepoint *tp = (struct tracepoint *) bp;
13166 size_t size = get_remote_packet_size ();
13167
13168 if (tp)
13169 {
13170 tp->hit_count = 0;
13171 tp->traceframe_usage = 0;
13172 for (loc = tp->loc; loc; loc = loc->next)
13173 {
13174 /* If the tracepoint was never downloaded, don't go asking for
13175 any status. */
13176 if (tp->number_on_target == 0)
13177 continue;
13178 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13179 phex_nz (loc->address, 0));
13180 putpkt (rs->buf);
13181 reply = remote_get_noisy_reply ();
13182 if (reply && *reply)
13183 {
13184 if (*reply == 'V')
13185 parse_tracepoint_status (reply + 1, bp, utp);
13186 }
13187 }
13188 }
13189 else if (utp)
13190 {
13191 utp->hit_count = 0;
13192 utp->traceframe_usage = 0;
13193 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13194 phex_nz (utp->addr, 0));
13195 putpkt (rs->buf);
13196 reply = remote_get_noisy_reply ();
13197 if (reply && *reply)
13198 {
13199 if (*reply == 'V')
13200 parse_tracepoint_status (reply + 1, bp, utp);
13201 }
13202 }
13203 }
13204
13205 void
13206 remote_target::trace_stop ()
13207 {
13208 struct remote_state *rs = get_remote_state ();
13209
13210 putpkt ("QTStop");
13211 remote_get_noisy_reply ();
13212 if (*rs->buf == '\0')
13213 error (_("Target does not support this command."));
13214 if (strcmp (rs->buf, "OK") != 0)
13215 error (_("Bogus reply from target: %s"), rs->buf);
13216 }
13217
13218 int
13219 remote_target::trace_find (enum trace_find_type type, int num,
13220 CORE_ADDR addr1, CORE_ADDR addr2,
13221 int *tpp)
13222 {
13223 struct remote_state *rs = get_remote_state ();
13224 char *endbuf = rs->buf + get_remote_packet_size ();
13225 char *p, *reply;
13226 int target_frameno = -1, target_tracept = -1;
13227
13228 /* Lookups other than by absolute frame number depend on the current
13229 trace selected, so make sure it is correct on the remote end
13230 first. */
13231 if (type != tfind_number)
13232 set_remote_traceframe ();
13233
13234 p = rs->buf;
13235 strcpy (p, "QTFrame:");
13236 p = strchr (p, '\0');
13237 switch (type)
13238 {
13239 case tfind_number:
13240 xsnprintf (p, endbuf - p, "%x", num);
13241 break;
13242 case tfind_pc:
13243 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13244 break;
13245 case tfind_tp:
13246 xsnprintf (p, endbuf - p, "tdp:%x", num);
13247 break;
13248 case tfind_range:
13249 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13250 phex_nz (addr2, 0));
13251 break;
13252 case tfind_outside:
13253 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13254 phex_nz (addr2, 0));
13255 break;
13256 default:
13257 error (_("Unknown trace find type %d"), type);
13258 }
13259
13260 putpkt (rs->buf);
13261 reply = remote_get_noisy_reply ();
13262 if (*reply == '\0')
13263 error (_("Target does not support this command."));
13264
13265 while (reply && *reply)
13266 switch (*reply)
13267 {
13268 case 'F':
13269 p = ++reply;
13270 target_frameno = (int) strtol (p, &reply, 16);
13271 if (reply == p)
13272 error (_("Unable to parse trace frame number"));
13273 /* Don't update our remote traceframe number cache on failure
13274 to select a remote traceframe. */
13275 if (target_frameno == -1)
13276 return -1;
13277 break;
13278 case 'T':
13279 p = ++reply;
13280 target_tracept = (int) strtol (p, &reply, 16);
13281 if (reply == p)
13282 error (_("Unable to parse tracepoint number"));
13283 break;
13284 case 'O': /* "OK"? */
13285 if (reply[1] == 'K' && reply[2] == '\0')
13286 reply += 2;
13287 else
13288 error (_("Bogus reply from target: %s"), reply);
13289 break;
13290 default:
13291 error (_("Bogus reply from target: %s"), reply);
13292 }
13293 if (tpp)
13294 *tpp = target_tracept;
13295
13296 rs->remote_traceframe_number = target_frameno;
13297 return target_frameno;
13298 }
13299
13300 bool
13301 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13302 {
13303 struct remote_state *rs = get_remote_state ();
13304 char *reply;
13305 ULONGEST uval;
13306
13307 set_remote_traceframe ();
13308
13309 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13310 putpkt (rs->buf);
13311 reply = remote_get_noisy_reply ();
13312 if (reply && *reply)
13313 {
13314 if (*reply == 'V')
13315 {
13316 unpack_varlen_hex (reply + 1, &uval);
13317 *val = (LONGEST) uval;
13318 return true;
13319 }
13320 }
13321 return false;
13322 }
13323
13324 int
13325 remote_target::save_trace_data (const char *filename)
13326 {
13327 struct remote_state *rs = get_remote_state ();
13328 char *p, *reply;
13329
13330 p = rs->buf;
13331 strcpy (p, "QTSave:");
13332 p += strlen (p);
13333 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13334 error (_("Remote file name too long for trace save packet"));
13335 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13336 *p++ = '\0';
13337 putpkt (rs->buf);
13338 reply = remote_get_noisy_reply ();
13339 if (*reply == '\0')
13340 error (_("Target does not support this command."));
13341 if (strcmp (reply, "OK") != 0)
13342 error (_("Bogus reply from target: %s"), reply);
13343 return 0;
13344 }
13345
13346 /* This is basically a memory transfer, but needs to be its own packet
13347 because we don't know how the target actually organizes its trace
13348 memory, plus we want to be able to ask for as much as possible, but
13349 not be unhappy if we don't get as much as we ask for. */
13350
13351 LONGEST
13352 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13353 {
13354 struct remote_state *rs = get_remote_state ();
13355 char *reply;
13356 char *p;
13357 int rslt;
13358
13359 p = rs->buf;
13360 strcpy (p, "qTBuffer:");
13361 p += strlen (p);
13362 p += hexnumstr (p, offset);
13363 *p++ = ',';
13364 p += hexnumstr (p, len);
13365 *p++ = '\0';
13366
13367 putpkt (rs->buf);
13368 reply = remote_get_noisy_reply ();
13369 if (reply && *reply)
13370 {
13371 /* 'l' by itself means we're at the end of the buffer and
13372 there is nothing more to get. */
13373 if (*reply == 'l')
13374 return 0;
13375
13376 /* Convert the reply into binary. Limit the number of bytes to
13377 convert according to our passed-in buffer size, rather than
13378 what was returned in the packet; if the target is
13379 unexpectedly generous and gives us a bigger reply than we
13380 asked for, we don't want to crash. */
13381 rslt = hex2bin (reply, buf, len);
13382 return rslt;
13383 }
13384
13385 /* Something went wrong, flag as an error. */
13386 return -1;
13387 }
13388
13389 void
13390 remote_target::set_disconnected_tracing (int val)
13391 {
13392 struct remote_state *rs = get_remote_state ();
13393
13394 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13395 {
13396 char *reply;
13397
13398 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13399 putpkt (rs->buf);
13400 reply = remote_get_noisy_reply ();
13401 if (*reply == '\0')
13402 error (_("Target does not support this command."));
13403 if (strcmp (reply, "OK") != 0)
13404 error (_("Bogus reply from target: %s"), reply);
13405 }
13406 else if (val)
13407 warning (_("Target does not support disconnected tracing."));
13408 }
13409
13410 int
13411 remote_target::core_of_thread (ptid_t ptid)
13412 {
13413 struct thread_info *info = find_thread_ptid (ptid);
13414
13415 if (info != NULL && info->priv != NULL)
13416 return get_remote_thread_info (info)->core;
13417
13418 return -1;
13419 }
13420
13421 void
13422 remote_target::set_circular_trace_buffer (int val)
13423 {
13424 struct remote_state *rs = get_remote_state ();
13425 char *reply;
13426
13427 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13428 putpkt (rs->buf);
13429 reply = remote_get_noisy_reply ();
13430 if (*reply == '\0')
13431 error (_("Target does not support this command."));
13432 if (strcmp (reply, "OK") != 0)
13433 error (_("Bogus reply from target: %s"), reply);
13434 }
13435
13436 traceframe_info_up
13437 remote_target::traceframe_info ()
13438 {
13439 gdb::optional<gdb::char_vector> text
13440 = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
13441 NULL);
13442 if (text)
13443 return parse_traceframe_info (text->data ());
13444
13445 return NULL;
13446 }
13447
13448 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13449 instruction on which a fast tracepoint may be placed. Returns -1
13450 if the packet is not supported, and 0 if the minimum instruction
13451 length is unknown. */
13452
13453 int
13454 remote_target::get_min_fast_tracepoint_insn_len ()
13455 {
13456 struct remote_state *rs = get_remote_state ();
13457 char *reply;
13458
13459 /* If we're not debugging a process yet, the IPA can't be
13460 loaded. */
13461 if (!target_has_execution)
13462 return 0;
13463
13464 /* Make sure the remote is pointing at the right process. */
13465 set_general_process ();
13466
13467 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13468 putpkt (rs->buf);
13469 reply = remote_get_noisy_reply ();
13470 if (*reply == '\0')
13471 return -1;
13472 else
13473 {
13474 ULONGEST min_insn_len;
13475
13476 unpack_varlen_hex (reply, &min_insn_len);
13477
13478 return (int) min_insn_len;
13479 }
13480 }
13481
13482 void
13483 remote_target::set_trace_buffer_size (LONGEST val)
13484 {
13485 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13486 {
13487 struct remote_state *rs = get_remote_state ();
13488 char *buf = rs->buf;
13489 char *endbuf = rs->buf + get_remote_packet_size ();
13490 enum packet_result result;
13491
13492 gdb_assert (val >= 0 || val == -1);
13493 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13494 /* Send -1 as literal "-1" to avoid host size dependency. */
13495 if (val < 0)
13496 {
13497 *buf++ = '-';
13498 buf += hexnumstr (buf, (ULONGEST) -val);
13499 }
13500 else
13501 buf += hexnumstr (buf, (ULONGEST) val);
13502
13503 putpkt (rs->buf);
13504 remote_get_noisy_reply ();
13505 result = packet_ok (rs->buf,
13506 &remote_protocol_packets[PACKET_QTBuffer_size]);
13507
13508 if (result != PACKET_OK)
13509 warning (_("Bogus reply from target: %s"), rs->buf);
13510 }
13511 }
13512
13513 bool
13514 remote_target::set_trace_notes (const char *user, const char *notes,
13515 const char *stop_notes)
13516 {
13517 struct remote_state *rs = get_remote_state ();
13518 char *reply;
13519 char *buf = rs->buf;
13520 char *endbuf = rs->buf + get_remote_packet_size ();
13521 int nbytes;
13522
13523 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13524 if (user)
13525 {
13526 buf += xsnprintf (buf, endbuf - buf, "user:");
13527 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13528 buf += 2 * nbytes;
13529 *buf++ = ';';
13530 }
13531 if (notes)
13532 {
13533 buf += xsnprintf (buf, endbuf - buf, "notes:");
13534 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13535 buf += 2 * nbytes;
13536 *buf++ = ';';
13537 }
13538 if (stop_notes)
13539 {
13540 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13541 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13542 buf += 2 * nbytes;
13543 *buf++ = ';';
13544 }
13545 /* Ensure the buffer is terminated. */
13546 *buf = '\0';
13547
13548 putpkt (rs->buf);
13549 reply = remote_get_noisy_reply ();
13550 if (*reply == '\0')
13551 return false;
13552
13553 if (strcmp (reply, "OK") != 0)
13554 error (_("Bogus reply from target: %s"), reply);
13555
13556 return true;
13557 }
13558
13559 bool
13560 remote_target::use_agent (bool use)
13561 {
13562 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13563 {
13564 struct remote_state *rs = get_remote_state ();
13565
13566 /* If the stub supports QAgent. */
13567 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13568 putpkt (rs->buf);
13569 getpkt (&rs->buf, &rs->buf_size, 0);
13570
13571 if (strcmp (rs->buf, "OK") == 0)
13572 {
13573 ::use_agent = use;
13574 return true;
13575 }
13576 }
13577
13578 return false;
13579 }
13580
13581 bool
13582 remote_target::can_use_agent ()
13583 {
13584 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13585 }
13586
13587 struct btrace_target_info
13588 {
13589 /* The ptid of the traced thread. */
13590 ptid_t ptid;
13591
13592 /* The obtained branch trace configuration. */
13593 struct btrace_config conf;
13594 };
13595
13596 /* Reset our idea of our target's btrace configuration. */
13597
13598 static void
13599 remote_btrace_reset (remote_state *rs)
13600 {
13601 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13602 }
13603
13604 /* Synchronize the configuration with the target. */
13605
13606 void
13607 remote_target::btrace_sync_conf (const btrace_config *conf)
13608 {
13609 struct packet_config *packet;
13610 struct remote_state *rs;
13611 char *buf, *pos, *endbuf;
13612
13613 rs = get_remote_state ();
13614 buf = rs->buf;
13615 endbuf = buf + get_remote_packet_size ();
13616
13617 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13618 if (packet_config_support (packet) == PACKET_ENABLE
13619 && conf->bts.size != rs->btrace_config.bts.size)
13620 {
13621 pos = buf;
13622 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13623 conf->bts.size);
13624
13625 putpkt (buf);
13626 getpkt (&buf, &rs->buf_size, 0);
13627
13628 if (packet_ok (buf, packet) == PACKET_ERROR)
13629 {
13630 if (buf[0] == 'E' && buf[1] == '.')
13631 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13632 else
13633 error (_("Failed to configure the BTS buffer size."));
13634 }
13635
13636 rs->btrace_config.bts.size = conf->bts.size;
13637 }
13638
13639 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13640 if (packet_config_support (packet) == PACKET_ENABLE
13641 && conf->pt.size != rs->btrace_config.pt.size)
13642 {
13643 pos = buf;
13644 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13645 conf->pt.size);
13646
13647 putpkt (buf);
13648 getpkt (&buf, &rs->buf_size, 0);
13649
13650 if (packet_ok (buf, packet) == PACKET_ERROR)
13651 {
13652 if (buf[0] == 'E' && buf[1] == '.')
13653 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13654 else
13655 error (_("Failed to configure the trace buffer size."));
13656 }
13657
13658 rs->btrace_config.pt.size = conf->pt.size;
13659 }
13660 }
13661
13662 /* Read the current thread's btrace configuration from the target and
13663 store it into CONF. */
13664
13665 static void
13666 btrace_read_config (struct btrace_config *conf)
13667 {
13668 gdb::optional<gdb::char_vector> xml
13669 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
13670 if (xml)
13671 parse_xml_btrace_conf (conf, xml->data ());
13672 }
13673
13674 /* Maybe reopen target btrace. */
13675
13676 void
13677 remote_target::remote_btrace_maybe_reopen ()
13678 {
13679 struct remote_state *rs = get_remote_state ();
13680 struct thread_info *tp;
13681 int btrace_target_pushed = 0;
13682 int warned = 0;
13683
13684 scoped_restore_current_thread restore_thread;
13685
13686 ALL_NON_EXITED_THREADS (tp)
13687 {
13688 set_general_thread (tp->ptid);
13689
13690 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13691 btrace_read_config (&rs->btrace_config);
13692
13693 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13694 continue;
13695
13696 #if !defined (HAVE_LIBIPT)
13697 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13698 {
13699 if (!warned)
13700 {
13701 warned = 1;
13702 warning (_("Target is recording using Intel Processor Trace "
13703 "but support was disabled at compile time."));
13704 }
13705
13706 continue;
13707 }
13708 #endif /* !defined (HAVE_LIBIPT) */
13709
13710 /* Push target, once, but before anything else happens. This way our
13711 changes to the threads will be cleaned up by unpushing the target
13712 in case btrace_read_config () throws. */
13713 if (!btrace_target_pushed)
13714 {
13715 btrace_target_pushed = 1;
13716 record_btrace_push_target ();
13717 printf_filtered (_("Target is recording using %s.\n"),
13718 btrace_format_string (rs->btrace_config.format));
13719 }
13720
13721 tp->btrace.target = XCNEW (struct btrace_target_info);
13722 tp->btrace.target->ptid = tp->ptid;
13723 tp->btrace.target->conf = rs->btrace_config;
13724 }
13725 }
13726
13727 /* Enable branch tracing. */
13728
13729 struct btrace_target_info *
13730 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13731 {
13732 struct btrace_target_info *tinfo = NULL;
13733 struct packet_config *packet = NULL;
13734 struct remote_state *rs = get_remote_state ();
13735 char *buf = rs->buf;
13736 char *endbuf = rs->buf + get_remote_packet_size ();
13737
13738 switch (conf->format)
13739 {
13740 case BTRACE_FORMAT_BTS:
13741 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13742 break;
13743
13744 case BTRACE_FORMAT_PT:
13745 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13746 break;
13747 }
13748
13749 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13750 error (_("Target does not support branch tracing."));
13751
13752 btrace_sync_conf (conf);
13753
13754 set_general_thread (ptid);
13755
13756 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13757 putpkt (rs->buf);
13758 getpkt (&rs->buf, &rs->buf_size, 0);
13759
13760 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13761 {
13762 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13763 error (_("Could not enable branch tracing for %s: %s"),
13764 target_pid_to_str (ptid), rs->buf + 2);
13765 else
13766 error (_("Could not enable branch tracing for %s."),
13767 target_pid_to_str (ptid));
13768 }
13769
13770 tinfo = XCNEW (struct btrace_target_info);
13771 tinfo->ptid = ptid;
13772
13773 /* If we fail to read the configuration, we lose some information, but the
13774 tracing itself is not impacted. */
13775 TRY
13776 {
13777 btrace_read_config (&tinfo->conf);
13778 }
13779 CATCH (err, RETURN_MASK_ERROR)
13780 {
13781 if (err.message != NULL)
13782 warning ("%s", err.message);
13783 }
13784 END_CATCH
13785
13786 return tinfo;
13787 }
13788
13789 /* Disable branch tracing. */
13790
13791 void
13792 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13793 {
13794 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13795 struct remote_state *rs = get_remote_state ();
13796 char *buf = rs->buf;
13797 char *endbuf = rs->buf + get_remote_packet_size ();
13798
13799 if (packet_config_support (packet) != PACKET_ENABLE)
13800 error (_("Target does not support branch tracing."));
13801
13802 set_general_thread (tinfo->ptid);
13803
13804 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13805 putpkt (rs->buf);
13806 getpkt (&rs->buf, &rs->buf_size, 0);
13807
13808 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13809 {
13810 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13811 error (_("Could not disable branch tracing for %s: %s"),
13812 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13813 else
13814 error (_("Could not disable branch tracing for %s."),
13815 target_pid_to_str (tinfo->ptid));
13816 }
13817
13818 xfree (tinfo);
13819 }
13820
13821 /* Teardown branch tracing. */
13822
13823 void
13824 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13825 {
13826 /* We must not talk to the target during teardown. */
13827 xfree (tinfo);
13828 }
13829
13830 /* Read the branch trace. */
13831
13832 enum btrace_error
13833 remote_target::read_btrace (struct btrace_data *btrace,
13834 struct btrace_target_info *tinfo,
13835 enum btrace_read_type type)
13836 {
13837 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13838 const char *annex;
13839
13840 if (packet_config_support (packet) != PACKET_ENABLE)
13841 error (_("Target does not support branch tracing."));
13842
13843 #if !defined(HAVE_LIBEXPAT)
13844 error (_("Cannot process branch tracing result. XML parsing not supported."));
13845 #endif
13846
13847 switch (type)
13848 {
13849 case BTRACE_READ_ALL:
13850 annex = "all";
13851 break;
13852 case BTRACE_READ_NEW:
13853 annex = "new";
13854 break;
13855 case BTRACE_READ_DELTA:
13856 annex = "delta";
13857 break;
13858 default:
13859 internal_error (__FILE__, __LINE__,
13860 _("Bad branch tracing read type: %u."),
13861 (unsigned int) type);
13862 }
13863
13864 gdb::optional<gdb::char_vector> xml
13865 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
13866 if (!xml)
13867 return BTRACE_ERR_UNKNOWN;
13868
13869 parse_xml_btrace (btrace, xml->data ());
13870
13871 return BTRACE_ERR_NONE;
13872 }
13873
13874 const struct btrace_config *
13875 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13876 {
13877 return &tinfo->conf;
13878 }
13879
13880 bool
13881 remote_target::augmented_libraries_svr4_read ()
13882 {
13883 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13884 == PACKET_ENABLE);
13885 }
13886
13887 /* Implementation of to_load. */
13888
13889 void
13890 remote_target::load (const char *name, int from_tty)
13891 {
13892 generic_load (name, from_tty);
13893 }
13894
13895 /* Accepts an integer PID; returns a string representing a file that
13896 can be opened on the remote side to get the symbols for the child
13897 process. Returns NULL if the operation is not supported. */
13898
13899 char *
13900 remote_target::pid_to_exec_file (int pid)
13901 {
13902 static gdb::optional<gdb::char_vector> filename;
13903 struct inferior *inf;
13904 char *annex = NULL;
13905
13906 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13907 return NULL;
13908
13909 inf = find_inferior_pid (pid);
13910 if (inf == NULL)
13911 internal_error (__FILE__, __LINE__,
13912 _("not currently attached to process %d"), pid);
13913
13914 if (!inf->fake_pid_p)
13915 {
13916 const int annex_size = 9;
13917
13918 annex = (char *) alloca (annex_size);
13919 xsnprintf (annex, annex_size, "%x", pid);
13920 }
13921
13922 filename = target_read_stralloc (current_top_target (),
13923 TARGET_OBJECT_EXEC_FILE, annex);
13924
13925 return filename ? filename->data () : nullptr;
13926 }
13927
13928 /* Implement the to_can_do_single_step target_ops method. */
13929
13930 int
13931 remote_target::can_do_single_step ()
13932 {
13933 /* We can only tell whether target supports single step or not by
13934 supported s and S vCont actions if the stub supports vContSupported
13935 feature. If the stub doesn't support vContSupported feature,
13936 we have conservatively to think target doesn't supports single
13937 step. */
13938 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13939 {
13940 struct remote_state *rs = get_remote_state ();
13941
13942 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13943 remote_vcont_probe ();
13944
13945 return rs->supports_vCont.s && rs->supports_vCont.S;
13946 }
13947 else
13948 return 0;
13949 }
13950
13951 /* Implementation of the to_execution_direction method for the remote
13952 target. */
13953
13954 enum exec_direction_kind
13955 remote_target::execution_direction ()
13956 {
13957 struct remote_state *rs = get_remote_state ();
13958
13959 return rs->last_resume_exec_dir;
13960 }
13961
13962 /* Return pointer to the thread_info struct which corresponds to
13963 THREAD_HANDLE (having length HANDLE_LEN). */
13964
13965 thread_info *
13966 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13967 int handle_len,
13968 inferior *inf)
13969 {
13970 struct thread_info *tp;
13971
13972 ALL_NON_EXITED_THREADS (tp)
13973 {
13974 remote_thread_info *priv = get_remote_thread_info (tp);
13975
13976 if (tp->inf == inf && priv != NULL)
13977 {
13978 if (handle_len != priv->thread_handle.size ())
13979 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13980 handle_len, priv->thread_handle.size ());
13981 if (memcmp (thread_handle, priv->thread_handle.data (),
13982 handle_len) == 0)
13983 return tp;
13984 }
13985 }
13986
13987 return NULL;
13988 }
13989
13990 bool
13991 remote_target::can_async_p ()
13992 {
13993 struct remote_state *rs = get_remote_state ();
13994
13995 /* We don't go async if the user has explicitly prevented it with the
13996 "maint set target-async" command. */
13997 if (!target_async_permitted)
13998 return false;
13999
14000 /* We're async whenever the serial device is. */
14001 return serial_can_async_p (rs->remote_desc);
14002 }
14003
14004 bool
14005 remote_target::is_async_p ()
14006 {
14007 struct remote_state *rs = get_remote_state ();
14008
14009 if (!target_async_permitted)
14010 /* We only enable async when the user specifically asks for it. */
14011 return false;
14012
14013 /* We're async whenever the serial device is. */
14014 return serial_is_async_p (rs->remote_desc);
14015 }
14016
14017 /* Pass the SERIAL event on and up to the client. One day this code
14018 will be able to delay notifying the client of an event until the
14019 point where an entire packet has been received. */
14020
14021 static serial_event_ftype remote_async_serial_handler;
14022
14023 static void
14024 remote_async_serial_handler (struct serial *scb, void *context)
14025 {
14026 /* Don't propogate error information up to the client. Instead let
14027 the client find out about the error by querying the target. */
14028 inferior_event_handler (INF_REG_EVENT, NULL);
14029 }
14030
14031 static void
14032 remote_async_inferior_event_handler (gdb_client_data data)
14033 {
14034 inferior_event_handler (INF_REG_EVENT, data);
14035 }
14036
14037 void
14038 remote_target::async (int enable)
14039 {
14040 struct remote_state *rs = get_remote_state ();
14041
14042 if (enable)
14043 {
14044 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14045
14046 /* If there are pending events in the stop reply queue tell the
14047 event loop to process them. */
14048 if (!rs->stop_reply_queue.empty ())
14049 mark_async_event_handler (rs->remote_async_inferior_event_token);
14050 /* For simplicity, below we clear the pending events token
14051 without remembering whether it is marked, so here we always
14052 mark it. If there's actually no pending notification to
14053 process, this ends up being a no-op (other than a spurious
14054 event-loop wakeup). */
14055 if (target_is_non_stop_p ())
14056 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14057 }
14058 else
14059 {
14060 serial_async (rs->remote_desc, NULL, NULL);
14061 /* If the core is disabling async, it doesn't want to be
14062 disturbed with target events. Clear all async event sources
14063 too. */
14064 clear_async_event_handler (rs->remote_async_inferior_event_token);
14065 if (target_is_non_stop_p ())
14066 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14067 }
14068 }
14069
14070 /* Implementation of the to_thread_events method. */
14071
14072 void
14073 remote_target::thread_events (int enable)
14074 {
14075 struct remote_state *rs = get_remote_state ();
14076 size_t size = get_remote_packet_size ();
14077
14078 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14079 return;
14080
14081 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14082 putpkt (rs->buf);
14083 getpkt (&rs->buf, &rs->buf_size, 0);
14084
14085 switch (packet_ok (rs->buf,
14086 &remote_protocol_packets[PACKET_QThreadEvents]))
14087 {
14088 case PACKET_OK:
14089 if (strcmp (rs->buf, "OK") != 0)
14090 error (_("Remote refused setting thread events: %s"), rs->buf);
14091 break;
14092 case PACKET_ERROR:
14093 warning (_("Remote failure reply: %s"), rs->buf);
14094 break;
14095 case PACKET_UNKNOWN:
14096 break;
14097 }
14098 }
14099
14100 static void
14101 set_remote_cmd (const char *args, int from_tty)
14102 {
14103 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
14104 }
14105
14106 static void
14107 show_remote_cmd (const char *args, int from_tty)
14108 {
14109 /* We can't just use cmd_show_list here, because we want to skip
14110 the redundant "show remote Z-packet" and the legacy aliases. */
14111 struct cmd_list_element *list = remote_show_cmdlist;
14112 struct ui_out *uiout = current_uiout;
14113
14114 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14115 for (; list != NULL; list = list->next)
14116 if (strcmp (list->name, "Z-packet") == 0)
14117 continue;
14118 else if (list->type == not_set_cmd)
14119 /* Alias commands are exactly like the original, except they
14120 don't have the normal type. */
14121 continue;
14122 else
14123 {
14124 ui_out_emit_tuple option_emitter (uiout, "option");
14125
14126 uiout->field_string ("name", list->name);
14127 uiout->text (": ");
14128 if (list->type == show_cmd)
14129 do_show_command (NULL, from_tty, list);
14130 else
14131 cmd_func (list, NULL, from_tty);
14132 }
14133 }
14134
14135
14136 /* Function to be called whenever a new objfile (shlib) is detected. */
14137 static void
14138 remote_new_objfile (struct objfile *objfile)
14139 {
14140 remote_target *remote = get_current_remote_target ();
14141
14142 if (remote != NULL) /* Have a remote connection. */
14143 remote->remote_check_symbols ();
14144 }
14145
14146 /* Pull all the tracepoints defined on the target and create local
14147 data structures representing them. We don't want to create real
14148 tracepoints yet, we don't want to mess up the user's existing
14149 collection. */
14150
14151 int
14152 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14153 {
14154 struct remote_state *rs = get_remote_state ();
14155 char *p;
14156
14157 /* Ask for a first packet of tracepoint definition. */
14158 putpkt ("qTfP");
14159 getpkt (&rs->buf, &rs->buf_size, 0);
14160 p = rs->buf;
14161 while (*p && *p != 'l')
14162 {
14163 parse_tracepoint_definition (p, utpp);
14164 /* Ask for another packet of tracepoint definition. */
14165 putpkt ("qTsP");
14166 getpkt (&rs->buf, &rs->buf_size, 0);
14167 p = rs->buf;
14168 }
14169 return 0;
14170 }
14171
14172 int
14173 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14174 {
14175 struct remote_state *rs = get_remote_state ();
14176 char *p;
14177
14178 /* Ask for a first packet of variable definition. */
14179 putpkt ("qTfV");
14180 getpkt (&rs->buf, &rs->buf_size, 0);
14181 p = rs->buf;
14182 while (*p && *p != 'l')
14183 {
14184 parse_tsv_definition (p, utsvp);
14185 /* Ask for another packet of variable definition. */
14186 putpkt ("qTsV");
14187 getpkt (&rs->buf, &rs->buf_size, 0);
14188 p = rs->buf;
14189 }
14190 return 0;
14191 }
14192
14193 /* The "set/show range-stepping" show hook. */
14194
14195 static void
14196 show_range_stepping (struct ui_file *file, int from_tty,
14197 struct cmd_list_element *c,
14198 const char *value)
14199 {
14200 fprintf_filtered (file,
14201 _("Debugger's willingness to use range stepping "
14202 "is %s.\n"), value);
14203 }
14204
14205 /* Return true if the vCont;r action is supported by the remote
14206 stub. */
14207
14208 bool
14209 remote_target::vcont_r_supported ()
14210 {
14211 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14212 remote_vcont_probe ();
14213
14214 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14215 && get_remote_state ()->supports_vCont.r);
14216 }
14217
14218 /* The "set/show range-stepping" set hook. */
14219
14220 static void
14221 set_range_stepping (const char *ignore_args, int from_tty,
14222 struct cmd_list_element *c)
14223 {
14224 /* When enabling, check whether range stepping is actually supported
14225 by the target, and warn if not. */
14226 if (use_range_stepping)
14227 {
14228 remote_target *remote = get_current_remote_target ();
14229 if (remote == NULL
14230 || !remote->vcont_r_supported ())
14231 warning (_("Range stepping is not supported by the current target"));
14232 }
14233 }
14234
14235 void
14236 _initialize_remote (void)
14237 {
14238 struct cmd_list_element *cmd;
14239 const char *cmd_name;
14240
14241 /* architecture specific data */
14242 remote_g_packet_data_handle =
14243 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14244
14245 remote_pspace_data
14246 = register_program_space_data_with_cleanup (NULL,
14247 remote_pspace_data_cleanup);
14248
14249 add_target (remote_target_info, remote_target::open);
14250 add_target (extended_remote_target_info, extended_remote_target::open);
14251
14252 /* Hook into new objfile notification. */
14253 gdb::observers::new_objfile.attach (remote_new_objfile);
14254
14255 #if 0
14256 init_remote_threadtests ();
14257 #endif
14258
14259 /* set/show remote ... */
14260
14261 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14262 Remote protocol specific variables\n\
14263 Configure various remote-protocol specific variables such as\n\
14264 the packets being used"),
14265 &remote_set_cmdlist, "set remote ",
14266 0 /* allow-unknown */, &setlist);
14267 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14268 Remote protocol specific variables\n\
14269 Configure various remote-protocol specific variables such as\n\
14270 the packets being used"),
14271 &remote_show_cmdlist, "show remote ",
14272 0 /* allow-unknown */, &showlist);
14273
14274 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14275 Compare section data on target to the exec file.\n\
14276 Argument is a single section name (default: all loaded sections).\n\
14277 To compare only read-only loaded sections, specify the -r option."),
14278 &cmdlist);
14279
14280 add_cmd ("packet", class_maintenance, packet_command, _("\
14281 Send an arbitrary packet to a remote target.\n\
14282 maintenance packet TEXT\n\
14283 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14284 this command sends the string TEXT to the inferior, and displays the\n\
14285 response packet. GDB supplies the initial `$' character, and the\n\
14286 terminating `#' character and checksum."),
14287 &maintenancelist);
14288
14289 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14290 Set whether to send break if interrupted."), _("\
14291 Show whether to send break if interrupted."), _("\
14292 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14293 set_remotebreak, show_remotebreak,
14294 &setlist, &showlist);
14295 cmd_name = "remotebreak";
14296 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14297 deprecate_cmd (cmd, "set remote interrupt-sequence");
14298 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14299 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14300 deprecate_cmd (cmd, "show remote interrupt-sequence");
14301
14302 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14303 interrupt_sequence_modes, &interrupt_sequence_mode,
14304 _("\
14305 Set interrupt sequence to remote target."), _("\
14306 Show interrupt sequence to remote target."), _("\
14307 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14308 NULL, show_interrupt_sequence,
14309 &remote_set_cmdlist,
14310 &remote_show_cmdlist);
14311
14312 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14313 &interrupt_on_connect, _("\
14314 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14315 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14316 If set, interrupt sequence is sent to remote target."),
14317 NULL, NULL,
14318 &remote_set_cmdlist, &remote_show_cmdlist);
14319
14320 /* Install commands for configuring memory read/write packets. */
14321
14322 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14323 Set the maximum number of bytes per memory write packet (deprecated)."),
14324 &setlist);
14325 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14326 Show the maximum number of bytes per memory write packet (deprecated)."),
14327 &showlist);
14328 add_cmd ("memory-write-packet-size", no_class,
14329 set_memory_write_packet_size, _("\
14330 Set the maximum number of bytes per memory-write packet.\n\
14331 Specify the number of bytes in a packet or 0 (zero) for the\n\
14332 default packet size. The actual limit is further reduced\n\
14333 dependent on the target. Specify ``fixed'' to disable the\n\
14334 further restriction and ``limit'' to enable that restriction."),
14335 &remote_set_cmdlist);
14336 add_cmd ("memory-read-packet-size", no_class,
14337 set_memory_read_packet_size, _("\
14338 Set the maximum number of bytes per memory-read packet.\n\
14339 Specify the number of bytes in a packet or 0 (zero) for the\n\
14340 default packet size. The actual limit is further reduced\n\
14341 dependent on the target. Specify ``fixed'' to disable the\n\
14342 further restriction and ``limit'' to enable that restriction."),
14343 &remote_set_cmdlist);
14344 add_cmd ("memory-write-packet-size", no_class,
14345 show_memory_write_packet_size,
14346 _("Show the maximum number of bytes per memory-write packet."),
14347 &remote_show_cmdlist);
14348 add_cmd ("memory-read-packet-size", no_class,
14349 show_memory_read_packet_size,
14350 _("Show the maximum number of bytes per memory-read packet."),
14351 &remote_show_cmdlist);
14352
14353 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14354 &remote_hw_watchpoint_limit, _("\
14355 Set the maximum number of target hardware watchpoints."), _("\
14356 Show the maximum number of target hardware watchpoints."), _("\
14357 Specify a negative limit for unlimited."),
14358 NULL, NULL, /* FIXME: i18n: The maximum
14359 number of target hardware
14360 watchpoints is %s. */
14361 &remote_set_cmdlist, &remote_show_cmdlist);
14362 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14363 &remote_hw_watchpoint_length_limit, _("\
14364 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14365 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14366 Specify a negative limit for unlimited."),
14367 NULL, NULL, /* FIXME: i18n: The maximum
14368 length (in bytes) of a target
14369 hardware watchpoint is %s. */
14370 &remote_set_cmdlist, &remote_show_cmdlist);
14371 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14372 &remote_hw_breakpoint_limit, _("\
14373 Set the maximum number of target hardware breakpoints."), _("\
14374 Show the maximum number of target hardware breakpoints."), _("\
14375 Specify a negative limit for unlimited."),
14376 NULL, NULL, /* FIXME: i18n: The maximum
14377 number of target hardware
14378 breakpoints is %s. */
14379 &remote_set_cmdlist, &remote_show_cmdlist);
14380
14381 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14382 &remote_address_size, _("\
14383 Set the maximum size of the address (in bits) in a memory packet."), _("\
14384 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14385 NULL,
14386 NULL, /* FIXME: i18n: */
14387 &setlist, &showlist);
14388
14389 init_all_packet_configs ();
14390
14391 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14392 "X", "binary-download", 1);
14393
14394 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14395 "vCont", "verbose-resume", 0);
14396
14397 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14398 "QPassSignals", "pass-signals", 0);
14399
14400 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14401 "QCatchSyscalls", "catch-syscalls", 0);
14402
14403 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14404 "QProgramSignals", "program-signals", 0);
14405
14406 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14407 "QSetWorkingDir", "set-working-dir", 0);
14408
14409 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14410 "QStartupWithShell", "startup-with-shell", 0);
14411
14412 add_packet_config_cmd (&remote_protocol_packets
14413 [PACKET_QEnvironmentHexEncoded],
14414 "QEnvironmentHexEncoded", "environment-hex-encoded",
14415 0);
14416
14417 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14418 "QEnvironmentReset", "environment-reset",
14419 0);
14420
14421 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14422 "QEnvironmentUnset", "environment-unset",
14423 0);
14424
14425 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14426 "qSymbol", "symbol-lookup", 0);
14427
14428 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14429 "P", "set-register", 1);
14430
14431 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14432 "p", "fetch-register", 1);
14433
14434 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14435 "Z0", "software-breakpoint", 0);
14436
14437 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14438 "Z1", "hardware-breakpoint", 0);
14439
14440 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14441 "Z2", "write-watchpoint", 0);
14442
14443 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14444 "Z3", "read-watchpoint", 0);
14445
14446 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14447 "Z4", "access-watchpoint", 0);
14448
14449 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14450 "qXfer:auxv:read", "read-aux-vector", 0);
14451
14452 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14453 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14454
14455 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14456 "qXfer:features:read", "target-features", 0);
14457
14458 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14459 "qXfer:libraries:read", "library-info", 0);
14460
14461 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14462 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14463
14464 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14465 "qXfer:memory-map:read", "memory-map", 0);
14466
14467 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14468 "qXfer:spu:read", "read-spu-object", 0);
14469
14470 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14471 "qXfer:spu:write", "write-spu-object", 0);
14472
14473 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14474 "qXfer:osdata:read", "osdata", 0);
14475
14476 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14477 "qXfer:threads:read", "threads", 0);
14478
14479 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14480 "qXfer:siginfo:read", "read-siginfo-object", 0);
14481
14482 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14483 "qXfer:siginfo:write", "write-siginfo-object", 0);
14484
14485 add_packet_config_cmd
14486 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14487 "qXfer:traceframe-info:read", "traceframe-info", 0);
14488
14489 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14490 "qXfer:uib:read", "unwind-info-block", 0);
14491
14492 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14493 "qGetTLSAddr", "get-thread-local-storage-address",
14494 0);
14495
14496 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14497 "qGetTIBAddr", "get-thread-information-block-address",
14498 0);
14499
14500 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14501 "bc", "reverse-continue", 0);
14502
14503 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14504 "bs", "reverse-step", 0);
14505
14506 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14507 "qSupported", "supported-packets", 0);
14508
14509 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14510 "qSearch:memory", "search-memory", 0);
14511
14512 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14513 "qTStatus", "trace-status", 0);
14514
14515 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14516 "vFile:setfs", "hostio-setfs", 0);
14517
14518 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14519 "vFile:open", "hostio-open", 0);
14520
14521 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14522 "vFile:pread", "hostio-pread", 0);
14523
14524 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14525 "vFile:pwrite", "hostio-pwrite", 0);
14526
14527 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14528 "vFile:close", "hostio-close", 0);
14529
14530 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14531 "vFile:unlink", "hostio-unlink", 0);
14532
14533 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14534 "vFile:readlink", "hostio-readlink", 0);
14535
14536 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14537 "vFile:fstat", "hostio-fstat", 0);
14538
14539 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14540 "vAttach", "attach", 0);
14541
14542 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14543 "vRun", "run", 0);
14544
14545 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14546 "QStartNoAckMode", "noack", 0);
14547
14548 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14549 "vKill", "kill", 0);
14550
14551 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14552 "qAttached", "query-attached", 0);
14553
14554 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14555 "ConditionalTracepoints",
14556 "conditional-tracepoints", 0);
14557
14558 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14559 "ConditionalBreakpoints",
14560 "conditional-breakpoints", 0);
14561
14562 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14563 "BreakpointCommands",
14564 "breakpoint-commands", 0);
14565
14566 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14567 "FastTracepoints", "fast-tracepoints", 0);
14568
14569 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14570 "TracepointSource", "TracepointSource", 0);
14571
14572 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14573 "QAllow", "allow", 0);
14574
14575 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14576 "StaticTracepoints", "static-tracepoints", 0);
14577
14578 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14579 "InstallInTrace", "install-in-trace", 0);
14580
14581 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14582 "qXfer:statictrace:read", "read-sdata-object", 0);
14583
14584 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14585 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14586
14587 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14588 "QDisableRandomization", "disable-randomization", 0);
14589
14590 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14591 "QAgent", "agent", 0);
14592
14593 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14594 "QTBuffer:size", "trace-buffer-size", 0);
14595
14596 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14597 "Qbtrace:off", "disable-btrace", 0);
14598
14599 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14600 "Qbtrace:bts", "enable-btrace-bts", 0);
14601
14602 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14603 "Qbtrace:pt", "enable-btrace-pt", 0);
14604
14605 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14606 "qXfer:btrace", "read-btrace", 0);
14607
14608 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14609 "qXfer:btrace-conf", "read-btrace-conf", 0);
14610
14611 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14612 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14613
14614 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14615 "multiprocess-feature", "multiprocess-feature", 0);
14616
14617 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14618 "swbreak-feature", "swbreak-feature", 0);
14619
14620 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14621 "hwbreak-feature", "hwbreak-feature", 0);
14622
14623 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14624 "fork-event-feature", "fork-event-feature", 0);
14625
14626 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14627 "vfork-event-feature", "vfork-event-feature", 0);
14628
14629 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14630 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14631
14632 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14633 "vContSupported", "verbose-resume-supported", 0);
14634
14635 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14636 "exec-event-feature", "exec-event-feature", 0);
14637
14638 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14639 "vCtrlC", "ctrl-c", 0);
14640
14641 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14642 "QThreadEvents", "thread-events", 0);
14643
14644 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14645 "N stop reply", "no-resumed-stop-reply", 0);
14646
14647 /* Assert that we've registered "set remote foo-packet" commands
14648 for all packet configs. */
14649 {
14650 int i;
14651
14652 for (i = 0; i < PACKET_MAX; i++)
14653 {
14654 /* Ideally all configs would have a command associated. Some
14655 still don't though. */
14656 int excepted;
14657
14658 switch (i)
14659 {
14660 case PACKET_QNonStop:
14661 case PACKET_EnableDisableTracepoints_feature:
14662 case PACKET_tracenz_feature:
14663 case PACKET_DisconnectedTracing_feature:
14664 case PACKET_augmented_libraries_svr4_read_feature:
14665 case PACKET_qCRC:
14666 /* Additions to this list need to be well justified:
14667 pre-existing packets are OK; new packets are not. */
14668 excepted = 1;
14669 break;
14670 default:
14671 excepted = 0;
14672 break;
14673 }
14674
14675 /* This catches both forgetting to add a config command, and
14676 forgetting to remove a packet from the exception list. */
14677 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14678 }
14679 }
14680
14681 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14682 Z sub-packet has its own set and show commands, but users may
14683 have sets to this variable in their .gdbinit files (or in their
14684 documentation). */
14685 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14686 &remote_Z_packet_detect, _("\
14687 Set use of remote protocol `Z' packets"), _("\
14688 Show use of remote protocol `Z' packets "), _("\
14689 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14690 packets."),
14691 set_remote_protocol_Z_packet_cmd,
14692 show_remote_protocol_Z_packet_cmd,
14693 /* FIXME: i18n: Use of remote protocol
14694 `Z' packets is %s. */
14695 &remote_set_cmdlist, &remote_show_cmdlist);
14696
14697 add_prefix_cmd ("remote", class_files, remote_command, _("\
14698 Manipulate files on the remote system\n\
14699 Transfer files to and from the remote target system."),
14700 &remote_cmdlist, "remote ",
14701 0 /* allow-unknown */, &cmdlist);
14702
14703 add_cmd ("put", class_files, remote_put_command,
14704 _("Copy a local file to the remote system."),
14705 &remote_cmdlist);
14706
14707 add_cmd ("get", class_files, remote_get_command,
14708 _("Copy a remote file to the local system."),
14709 &remote_cmdlist);
14710
14711 add_cmd ("delete", class_files, remote_delete_command,
14712 _("Delete a remote file."),
14713 &remote_cmdlist);
14714
14715 add_setshow_string_noescape_cmd ("exec-file", class_files,
14716 &remote_exec_file_var, _("\
14717 Set the remote pathname for \"run\""), _("\
14718 Show the remote pathname for \"run\""), NULL,
14719 set_remote_exec_file,
14720 show_remote_exec_file,
14721 &remote_set_cmdlist,
14722 &remote_show_cmdlist);
14723
14724 add_setshow_boolean_cmd ("range-stepping", class_run,
14725 &use_range_stepping, _("\
14726 Enable or disable range stepping."), _("\
14727 Show whether target-assisted range stepping is enabled."), _("\
14728 If on, and the target supports it, when stepping a source line, GDB\n\
14729 tells the target to step the corresponding range of addresses itself instead\n\
14730 of issuing multiple single-steps. This speeds up source level\n\
14731 stepping. If off, GDB always issues single-steps, even if range\n\
14732 stepping is supported by the target. The default is on."),
14733 set_range_stepping,
14734 show_range_stepping,
14735 &setlist,
14736 &showlist);
14737
14738 /* Eventually initialize fileio. See fileio.c */
14739 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14740
14741 /* Take advantage of the fact that the TID field is not used, to tag
14742 special ptids with it set to != 0. */
14743 magic_null_ptid = ptid_build (42000, -1, 1);
14744 not_sent_ptid = ptid_build (42000, -2, 1);
14745 any_thread_ptid = ptid_build (42000, 0, 1);
14746 }
This page took 0.361474 seconds and 4 git commands to generate.