gdb: generalize commit_resume, avoid commit-resuming when threads have pending statuses
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2021 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 "process-stratum-target.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 "gdbsupport/filestuff.h"
46 #include "gdbsupport/rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdbsupport/gdb_sys_time.h"
51
52 #include "gdbsupport/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"
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 "gdbsupport/agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "gdbsupport/scoped_restore.h"
76 #include "gdbsupport/environ.h"
77 #include "gdbsupport/byte-vector.h"
78 #include "gdbsupport/search.h"
79 #include <algorithm>
80 #include <unordered_map>
81 #include "async-event.h"
82 #include "gdbsupport/selftest.h"
83
84 /* The remote target. */
85
86 static const char remote_doc[] = N_("\
87 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
88 Specify the serial device it is connected to\n\
89 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
90
91 /* See remote.h */
92
93 bool remote_debug = false;
94
95 #define OPAQUETHREADBYTES 8
96
97 /* a 64 bit opaque identifier */
98 typedef unsigned char threadref[OPAQUETHREADBYTES];
99
100 struct gdb_ext_thread_info;
101 struct threads_listing_context;
102 typedef int (*rmt_thread_action) (threadref *ref, void *context);
103 struct protocol_feature;
104 struct packet_reg;
105
106 struct stop_reply;
107 typedef std::unique_ptr<stop_reply> stop_reply_up;
108
109 /* Generic configuration support for packets the stub optionally
110 supports. Allows the user to specify the use of the packet as well
111 as allowing GDB to auto-detect support in the remote stub. */
112
113 enum packet_support
114 {
115 PACKET_SUPPORT_UNKNOWN = 0,
116 PACKET_ENABLE,
117 PACKET_DISABLE
118 };
119
120 /* Analyze a packet's return value and update the packet config
121 accordingly. */
122
123 enum packet_result
124 {
125 PACKET_ERROR,
126 PACKET_OK,
127 PACKET_UNKNOWN
128 };
129
130 struct threads_listing_context;
131
132 /* Stub vCont actions support.
133
134 Each field is a boolean flag indicating whether the stub reports
135 support for the corresponding action. */
136
137 struct vCont_action_support
138 {
139 /* vCont;t */
140 bool t = false;
141
142 /* vCont;r */
143 bool r = false;
144
145 /* vCont;s */
146 bool s = false;
147
148 /* vCont;S */
149 bool S = false;
150 };
151
152 /* About this many threadids fit in a packet. */
153
154 #define MAXTHREADLISTRESULTS 32
155
156 /* Data for the vFile:pread readahead cache. */
157
158 struct readahead_cache
159 {
160 /* Invalidate the readahead cache. */
161 void invalidate ();
162
163 /* Invalidate the readahead cache if it is holding data for FD. */
164 void invalidate_fd (int fd);
165
166 /* Serve pread from the readahead cache. Returns number of bytes
167 read, or 0 if the request can't be served from the cache. */
168 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
169
170 /* The file descriptor for the file that is being cached. -1 if the
171 cache is invalid. */
172 int fd = -1;
173
174 /* The offset into the file that the cache buffer corresponds
175 to. */
176 ULONGEST offset = 0;
177
178 /* The buffer holding the cache contents. */
179 gdb_byte *buf = nullptr;
180 /* The buffer's size. We try to read as much as fits into a packet
181 at a time. */
182 size_t bufsize = 0;
183
184 /* Cache hit and miss counters. */
185 ULONGEST hit_count = 0;
186 ULONGEST miss_count = 0;
187 };
188
189 /* Description of the remote protocol for a given architecture. */
190
191 struct packet_reg
192 {
193 long offset; /* Offset into G packet. */
194 long regnum; /* GDB's internal register number. */
195 LONGEST pnum; /* Remote protocol register number. */
196 int in_g_packet; /* Always part of G packet. */
197 /* long size in bytes; == register_size (target_gdbarch (), regnum);
198 at present. */
199 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
200 at present. */
201 };
202
203 struct remote_arch_state
204 {
205 explicit remote_arch_state (struct gdbarch *gdbarch);
206
207 /* Description of the remote protocol registers. */
208 long sizeof_g_packet;
209
210 /* Description of the remote protocol registers indexed by REGNUM
211 (making an array gdbarch_num_regs in size). */
212 std::unique_ptr<packet_reg[]> regs;
213
214 /* This is the size (in chars) of the first response to the ``g''
215 packet. It is used as a heuristic when determining the maximum
216 size of memory-read and memory-write packets. A target will
217 typically only reserve a buffer large enough to hold the ``g''
218 packet. The size does not include packet overhead (headers and
219 trailers). */
220 long actual_register_packet_size;
221
222 /* This is the maximum size (in chars) of a non read/write packet.
223 It is also used as a cap on the size of read/write packets. */
224 long remote_packet_size;
225 };
226
227 /* Description of the remote protocol state for the currently
228 connected target. This is per-target state, and independent of the
229 selected architecture. */
230
231 class remote_state
232 {
233 public:
234
235 remote_state ();
236 ~remote_state ();
237
238 /* Get the remote arch state for GDBARCH. */
239 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
240
241 public: /* data */
242
243 /* A buffer to use for incoming packets, and its current size. The
244 buffer is grown dynamically for larger incoming packets.
245 Outgoing packets may also be constructed in this buffer.
246 The size of the buffer is always at least REMOTE_PACKET_SIZE;
247 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
248 packets. */
249 gdb::char_vector buf;
250
251 /* True if we're going through initial connection setup (finding out
252 about the remote side's threads, relocating symbols, etc.). */
253 bool starting_up = false;
254
255 /* If we negotiated packet size explicitly (and thus can bypass
256 heuristics for the largest packet size that will not overflow
257 a buffer in the stub), this will be set to that packet size.
258 Otherwise zero, meaning to use the guessed size. */
259 long explicit_packet_size = 0;
260
261 /* remote_wait is normally called when the target is running and
262 waits for a stop reply packet. But sometimes we need to call it
263 when the target is already stopped. We can send a "?" packet
264 and have remote_wait read the response. Or, if we already have
265 the response, we can stash it in BUF and tell remote_wait to
266 skip calling getpkt. This flag is set when BUF contains a
267 stop reply packet and the target is not waiting. */
268 int cached_wait_status = 0;
269
270 /* True, if in no ack mode. That is, neither GDB nor the stub will
271 expect acks from each other. The connection is assumed to be
272 reliable. */
273 bool noack_mode = false;
274
275 /* True if we're connected in extended remote mode. */
276 bool extended = false;
277
278 /* True if we resumed the target and we're waiting for the target to
279 stop. In the mean time, we can't start another command/query.
280 The remote server wouldn't be ready to process it, so we'd
281 timeout waiting for a reply that would never come and eventually
282 we'd close the connection. This can happen in asynchronous mode
283 because we allow GDB commands while the target is running. */
284 bool waiting_for_stop_reply = false;
285
286 /* The status of the stub support for the various vCont actions. */
287 vCont_action_support supports_vCont;
288 /* Whether vCont support was probed already. This is a workaround
289 until packet_support is per-connection. */
290 bool supports_vCont_probed;
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 process_stratum_target
408 {
409 public:
410 remote_target () = default;
411 ~remote_target () override;
412
413 const target_info &info () const override
414 { return remote_target_info; }
415
416 const char *connection_string () override;
417
418 thread_control_capabilities get_thread_control_capabilities () override
419 { return tc_schedlock; }
420
421 /* Open a remote connection. */
422 static void open (const char *, int);
423
424 void close () override;
425
426 void detach (inferior *, int) override;
427 void disconnect (const char *, int) override;
428
429 void commit_resumed () override;
430 void resume (ptid_t, int, enum gdb_signal) override;
431 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
432
433 void fetch_registers (struct regcache *, int) override;
434 void store_registers (struct regcache *, int) override;
435 void prepare_to_store (struct regcache *) override;
436
437 void files_info () override;
438
439 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
440
441 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
442 enum remove_bp_reason) override;
443
444
445 bool stopped_by_sw_breakpoint () override;
446 bool supports_stopped_by_sw_breakpoint () override;
447
448 bool stopped_by_hw_breakpoint () override;
449
450 bool supports_stopped_by_hw_breakpoint () override;
451
452 bool stopped_by_watchpoint () override;
453
454 bool stopped_data_address (CORE_ADDR *) override;
455
456 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
457
458 int can_use_hw_breakpoint (enum bptype, int, int) override;
459
460 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
461
462 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
463
464 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
465
466 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
467 struct expression *) override;
468
469 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
470 struct expression *) override;
471
472 void kill () override;
473
474 void load (const char *, int) override;
475
476 void mourn_inferior () override;
477
478 void pass_signals (gdb::array_view<const unsigned char>) override;
479
480 int set_syscall_catchpoint (int, bool, int,
481 gdb::array_view<const int>) override;
482
483 void program_signals (gdb::array_view<const unsigned char>) override;
484
485 bool thread_alive (ptid_t ptid) override;
486
487 const char *thread_name (struct thread_info *) override;
488
489 void update_thread_list () override;
490
491 std::string pid_to_str (ptid_t) override;
492
493 const char *extra_thread_info (struct thread_info *) override;
494
495 ptid_t get_ada_task_ptid (long lwp, long thread) override;
496
497 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
498 int handle_len,
499 inferior *inf) override;
500
501 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
502 override;
503
504 void stop (ptid_t) override;
505
506 void interrupt () override;
507
508 void pass_ctrlc () override;
509
510 enum target_xfer_status xfer_partial (enum target_object object,
511 const char *annex,
512 gdb_byte *readbuf,
513 const gdb_byte *writebuf,
514 ULONGEST offset, ULONGEST len,
515 ULONGEST *xfered_len) override;
516
517 ULONGEST get_memory_xfer_limit () override;
518
519 void rcmd (const char *command, struct ui_file *output) override;
520
521 char *pid_to_exec_file (int pid) override;
522
523 void log_command (const char *cmd) override
524 {
525 serial_log_command (this, cmd);
526 }
527
528 CORE_ADDR get_thread_local_address (ptid_t ptid,
529 CORE_ADDR load_module_addr,
530 CORE_ADDR offset) override;
531
532 bool can_execute_reverse () override;
533
534 std::vector<mem_region> memory_map () override;
535
536 void flash_erase (ULONGEST address, LONGEST length) override;
537
538 void flash_done () override;
539
540 const struct target_desc *read_description () override;
541
542 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
543 const gdb_byte *pattern, ULONGEST pattern_len,
544 CORE_ADDR *found_addrp) override;
545
546 bool can_async_p () override;
547
548 bool is_async_p () override;
549
550 void async (int) override;
551
552 int async_wait_fd () override;
553
554 void thread_events (int) override;
555
556 int can_do_single_step () override;
557
558 void terminal_inferior () override;
559
560 void terminal_ours () override;
561
562 bool supports_non_stop () override;
563
564 bool supports_multi_process () override;
565
566 bool supports_disable_randomization () override;
567
568 bool filesystem_is_local () override;
569
570
571 int fileio_open (struct inferior *inf, const char *filename,
572 int flags, int mode, int warn_if_slow,
573 int *target_errno) override;
574
575 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
576 ULONGEST offset, int *target_errno) override;
577
578 int fileio_pread (int fd, gdb_byte *read_buf, int len,
579 ULONGEST offset, int *target_errno) override;
580
581 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
582
583 int fileio_close (int fd, int *target_errno) override;
584
585 int fileio_unlink (struct inferior *inf,
586 const char *filename,
587 int *target_errno) override;
588
589 gdb::optional<std::string>
590 fileio_readlink (struct inferior *inf,
591 const char *filename,
592 int *target_errno) override;
593
594 bool supports_enable_disable_tracepoint () override;
595
596 bool supports_string_tracing () override;
597
598 bool supports_evaluation_of_breakpoint_conditions () override;
599
600 bool can_run_breakpoint_commands () override;
601
602 void trace_init () override;
603
604 void download_tracepoint (struct bp_location *location) override;
605
606 bool can_download_tracepoint () override;
607
608 void download_trace_state_variable (const trace_state_variable &tsv) override;
609
610 void enable_tracepoint (struct bp_location *location) override;
611
612 void disable_tracepoint (struct bp_location *location) override;
613
614 void trace_set_readonly_regions () override;
615
616 void trace_start () override;
617
618 int get_trace_status (struct trace_status *ts) override;
619
620 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
621 override;
622
623 void trace_stop () override;
624
625 int trace_find (enum trace_find_type type, int num,
626 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
627
628 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
629
630 int save_trace_data (const char *filename) override;
631
632 int upload_tracepoints (struct uploaded_tp **utpp) override;
633
634 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
635
636 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
637
638 int get_min_fast_tracepoint_insn_len () override;
639
640 void set_disconnected_tracing (int val) override;
641
642 void set_circular_trace_buffer (int val) override;
643
644 void set_trace_buffer_size (LONGEST val) override;
645
646 bool set_trace_notes (const char *user, const char *notes,
647 const char *stopnotes) override;
648
649 int core_of_thread (ptid_t ptid) override;
650
651 int verify_memory (const gdb_byte *data,
652 CORE_ADDR memaddr, ULONGEST size) override;
653
654
655 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
656
657 void set_permissions () override;
658
659 bool static_tracepoint_marker_at (CORE_ADDR,
660 struct static_tracepoint_marker *marker)
661 override;
662
663 std::vector<static_tracepoint_marker>
664 static_tracepoint_markers_by_strid (const char *id) override;
665
666 traceframe_info_up traceframe_info () override;
667
668 bool use_agent (bool use) override;
669 bool can_use_agent () override;
670
671 struct btrace_target_info *enable_btrace (ptid_t ptid,
672 const struct btrace_config *conf) override;
673
674 void disable_btrace (struct btrace_target_info *tinfo) override;
675
676 void teardown_btrace (struct btrace_target_info *tinfo) override;
677
678 enum btrace_error read_btrace (struct btrace_data *data,
679 struct btrace_target_info *btinfo,
680 enum btrace_read_type type) override;
681
682 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
683 bool augmented_libraries_svr4_read () override;
684 bool follow_fork (bool, bool) override;
685 void follow_exec (struct inferior *, const char *) override;
686 int insert_fork_catchpoint (int) override;
687 int remove_fork_catchpoint (int) override;
688 int insert_vfork_catchpoint (int) override;
689 int remove_vfork_catchpoint (int) override;
690 int insert_exec_catchpoint (int) override;
691 int remove_exec_catchpoint (int) override;
692 enum exec_direction_kind execution_direction () override;
693
694 bool supports_memory_tagging () override;
695
696 bool fetch_memtags (CORE_ADDR address, size_t len,
697 gdb::byte_vector &tags, int type) override;
698
699 bool store_memtags (CORE_ADDR address, size_t len,
700 const gdb::byte_vector &tags, int type) override;
701
702 public: /* Remote specific methods. */
703
704 void remote_download_command_source (int num, ULONGEST addr,
705 struct command_line *cmds);
706
707 void remote_file_put (const char *local_file, const char *remote_file,
708 int from_tty);
709 void remote_file_get (const char *remote_file, const char *local_file,
710 int from_tty);
711 void remote_file_delete (const char *remote_file, int from_tty);
712
713 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
714 ULONGEST offset, int *remote_errno);
715 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
716 ULONGEST offset, int *remote_errno);
717 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
718 ULONGEST offset, int *remote_errno);
719
720 int remote_hostio_send_command (int command_bytes, int which_packet,
721 int *remote_errno, const char **attachment,
722 int *attachment_len);
723 int remote_hostio_set_filesystem (struct inferior *inf,
724 int *remote_errno);
725 /* We should get rid of this and use fileio_open directly. */
726 int remote_hostio_open (struct inferior *inf, const char *filename,
727 int flags, int mode, int warn_if_slow,
728 int *remote_errno);
729 int remote_hostio_close (int fd, int *remote_errno);
730
731 int remote_hostio_unlink (inferior *inf, const char *filename,
732 int *remote_errno);
733
734 struct remote_state *get_remote_state ();
735
736 long get_remote_packet_size (void);
737 long get_memory_packet_size (struct memory_packet_config *config);
738
739 long get_memory_write_packet_size ();
740 long get_memory_read_packet_size ();
741
742 char *append_pending_thread_resumptions (char *p, char *endp,
743 ptid_t ptid);
744 static void open_1 (const char *name, int from_tty, int extended_p);
745 void start_remote (int from_tty, int extended_p);
746 void remote_detach_1 (struct inferior *inf, int from_tty);
747
748 char *append_resumption (char *p, char *endp,
749 ptid_t ptid, int step, gdb_signal siggnal);
750 int remote_resume_with_vcont (ptid_t ptid, int step,
751 gdb_signal siggnal);
752
753 thread_info *add_current_inferior_and_thread (const char *wait_status);
754
755 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
756 target_wait_flags options);
757 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
758 target_wait_flags options);
759
760 ptid_t process_stop_reply (struct stop_reply *stop_reply,
761 target_waitstatus *status);
762
763 ptid_t select_thread_for_ambiguous_stop_reply
764 (const struct target_waitstatus *status);
765
766 void remote_notice_new_inferior (ptid_t currthread, int executing);
767
768 void process_initial_stop_replies (int from_tty);
769
770 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
771
772 void btrace_sync_conf (const btrace_config *conf);
773
774 void remote_btrace_maybe_reopen ();
775
776 void remove_new_fork_children (threads_listing_context *context);
777 void kill_new_fork_children (int pid);
778 void discard_pending_stop_replies (struct inferior *inf);
779 int stop_reply_queue_length ();
780
781 void check_pending_events_prevent_wildcard_vcont
782 (int *may_global_wildcard_vcont);
783
784 void discard_pending_stop_replies_in_queue ();
785 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
786 struct stop_reply *queued_stop_reply (ptid_t ptid);
787 int peek_stop_reply (ptid_t ptid);
788 void remote_parse_stop_reply (const char *buf, stop_reply *event);
789
790 void remote_stop_ns (ptid_t ptid);
791 void remote_interrupt_as ();
792 void remote_interrupt_ns ();
793
794 char *remote_get_noisy_reply ();
795 int remote_query_attached (int pid);
796 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
797 int try_open_exec);
798
799 ptid_t remote_current_thread (ptid_t oldpid);
800 ptid_t get_current_thread (const char *wait_status);
801
802 void set_thread (ptid_t ptid, int gen);
803 void set_general_thread (ptid_t ptid);
804 void set_continue_thread (ptid_t ptid);
805 void set_general_process ();
806
807 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
808
809 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
810 gdb_ext_thread_info *info);
811 int remote_get_threadinfo (threadref *threadid, int fieldset,
812 gdb_ext_thread_info *info);
813
814 int parse_threadlist_response (const char *pkt, int result_limit,
815 threadref *original_echo,
816 threadref *resultlist,
817 int *doneflag);
818 int remote_get_threadlist (int startflag, threadref *nextthread,
819 int result_limit, int *done, int *result_count,
820 threadref *threadlist);
821
822 int remote_threadlist_iterator (rmt_thread_action stepfunction,
823 void *context, int looplimit);
824
825 int remote_get_threads_with_ql (threads_listing_context *context);
826 int remote_get_threads_with_qxfer (threads_listing_context *context);
827 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
828
829 void extended_remote_restart ();
830
831 void get_offsets ();
832
833 void remote_check_symbols ();
834
835 void remote_supported_packet (const struct protocol_feature *feature,
836 enum packet_support support,
837 const char *argument);
838
839 void remote_query_supported ();
840
841 void remote_packet_size (const protocol_feature *feature,
842 packet_support support, const char *value);
843
844 void remote_serial_quit_handler ();
845
846 void remote_detach_pid (int pid);
847
848 void remote_vcont_probe ();
849
850 void remote_resume_with_hc (ptid_t ptid, int step,
851 gdb_signal siggnal);
852
853 void send_interrupt_sequence ();
854 void interrupt_query ();
855
856 void remote_notif_get_pending_events (notif_client *nc);
857
858 int fetch_register_using_p (struct regcache *regcache,
859 packet_reg *reg);
860 int send_g_packet ();
861 void process_g_packet (struct regcache *regcache);
862 void fetch_registers_using_g (struct regcache *regcache);
863 int store_register_using_P (const struct regcache *regcache,
864 packet_reg *reg);
865 void store_registers_using_G (const struct regcache *regcache);
866
867 void set_remote_traceframe ();
868
869 void check_binary_download (CORE_ADDR addr);
870
871 target_xfer_status remote_write_bytes_aux (const char *header,
872 CORE_ADDR memaddr,
873 const gdb_byte *myaddr,
874 ULONGEST len_units,
875 int unit_size,
876 ULONGEST *xfered_len_units,
877 char packet_format,
878 int use_length);
879
880 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
881 const gdb_byte *myaddr, ULONGEST len,
882 int unit_size, ULONGEST *xfered_len);
883
884 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
885 ULONGEST len_units,
886 int unit_size, ULONGEST *xfered_len_units);
887
888 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
889 ULONGEST memaddr,
890 ULONGEST len,
891 int unit_size,
892 ULONGEST *xfered_len);
893
894 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
895 gdb_byte *myaddr, ULONGEST len,
896 int unit_size,
897 ULONGEST *xfered_len);
898
899 packet_result remote_send_printf (const char *format, ...)
900 ATTRIBUTE_PRINTF (2, 3);
901
902 target_xfer_status remote_flash_write (ULONGEST address,
903 ULONGEST length, ULONGEST *xfered_len,
904 const gdb_byte *data);
905
906 int readchar (int timeout);
907
908 void remote_serial_write (const char *str, int len);
909
910 int putpkt (const char *buf);
911 int putpkt_binary (const char *buf, int cnt);
912
913 int putpkt (const gdb::char_vector &buf)
914 {
915 return putpkt (buf.data ());
916 }
917
918 void skip_frame ();
919 long read_frame (gdb::char_vector *buf_p);
920 void getpkt (gdb::char_vector *buf, int forever);
921 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
922 int expecting_notif, int *is_notif);
923 int getpkt_sane (gdb::char_vector *buf, int forever);
924 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
925 int *is_notif);
926 int remote_vkill (int pid);
927 void remote_kill_k ();
928
929 void extended_remote_disable_randomization (int val);
930 int extended_remote_run (const std::string &args);
931
932 void send_environment_packet (const char *action,
933 const char *packet,
934 const char *value);
935
936 void extended_remote_environment_support ();
937 void extended_remote_set_inferior_cwd ();
938
939 target_xfer_status remote_write_qxfer (const char *object_name,
940 const char *annex,
941 const gdb_byte *writebuf,
942 ULONGEST offset, LONGEST len,
943 ULONGEST *xfered_len,
944 struct packet_config *packet);
945
946 target_xfer_status remote_read_qxfer (const char *object_name,
947 const char *annex,
948 gdb_byte *readbuf, ULONGEST offset,
949 LONGEST len,
950 ULONGEST *xfered_len,
951 struct packet_config *packet);
952
953 void push_stop_reply (struct stop_reply *new_event);
954
955 bool vcont_r_supported ();
956
957 void packet_command (const char *args, int from_tty);
958
959 private: /* data fields */
960
961 /* The remote state. Don't reference this directly. Use the
962 get_remote_state method instead. */
963 remote_state m_remote_state;
964 };
965
966 static const target_info extended_remote_target_info = {
967 "extended-remote",
968 N_("Extended remote serial target in gdb-specific protocol"),
969 remote_doc
970 };
971
972 /* Set up the extended remote target by extending the standard remote
973 target and adding to it. */
974
975 class extended_remote_target final : public remote_target
976 {
977 public:
978 const target_info &info () const override
979 { return extended_remote_target_info; }
980
981 /* Open an extended-remote connection. */
982 static void open (const char *, int);
983
984 bool can_create_inferior () override { return true; }
985 void create_inferior (const char *, const std::string &,
986 char **, int) override;
987
988 void detach (inferior *, int) override;
989
990 bool can_attach () override { return true; }
991 void attach (const char *, int) override;
992
993 void post_attach (int) override;
994 bool supports_disable_randomization () override;
995 };
996
997 /* Per-program-space data key. */
998 static const struct program_space_key<char, gdb::xfree_deleter<char>>
999 remote_pspace_data;
1000
1001 /* The variable registered as the control variable used by the
1002 remote exec-file commands. While the remote exec-file setting is
1003 per-program-space, the set/show machinery uses this as the
1004 location of the remote exec-file value. */
1005 static char *remote_exec_file_var;
1006
1007 /* The size to align memory write packets, when practical. The protocol
1008 does not guarantee any alignment, and gdb will generate short
1009 writes and unaligned writes, but even as a best-effort attempt this
1010 can improve bulk transfers. For instance, if a write is misaligned
1011 relative to the target's data bus, the stub may need to make an extra
1012 round trip fetching data from the target. This doesn't make a
1013 huge difference, but it's easy to do, so we try to be helpful.
1014
1015 The alignment chosen is arbitrary; usually data bus width is
1016 important here, not the possibly larger cache line size. */
1017 enum { REMOTE_ALIGN_WRITES = 16 };
1018
1019 /* Prototypes for local functions. */
1020
1021 static int hexnumlen (ULONGEST num);
1022
1023 static int stubhex (int ch);
1024
1025 static int hexnumstr (char *, ULONGEST);
1026
1027 static int hexnumnstr (char *, ULONGEST, int);
1028
1029 static CORE_ADDR remote_address_masked (CORE_ADDR);
1030
1031 static void print_packet (const char *);
1032
1033 static int stub_unpack_int (const char *buff, int fieldlength);
1034
1035 struct packet_config;
1036
1037 static void show_packet_config_cmd (struct packet_config *config);
1038
1039 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1040 int from_tty,
1041 struct cmd_list_element *c,
1042 const char *value);
1043
1044 static ptid_t read_ptid (const char *buf, const char **obuf);
1045
1046 static void remote_async_inferior_event_handler (gdb_client_data);
1047
1048 static bool remote_read_description_p (struct target_ops *target);
1049
1050 static void remote_console_output (const char *msg);
1051
1052 static void remote_btrace_reset (remote_state *rs);
1053
1054 static void remote_unpush_and_throw (remote_target *target);
1055
1056 /* For "remote". */
1057
1058 static struct cmd_list_element *remote_cmdlist;
1059
1060 /* For "set remote" and "show remote". */
1061
1062 static struct cmd_list_element *remote_set_cmdlist;
1063 static struct cmd_list_element *remote_show_cmdlist;
1064
1065 /* Controls whether GDB is willing to use range stepping. */
1066
1067 static bool use_range_stepping = true;
1068
1069 /* From the remote target's point of view, each thread is in one of these three
1070 states. */
1071 enum class resume_state
1072 {
1073 /* Not resumed - we haven't been asked to resume this thread. */
1074 NOT_RESUMED,
1075
1076 /* We have been asked to resume this thread, but haven't sent a vCont action
1077 for it yet. We'll need to consider it next time commit_resume is
1078 called. */
1079 RESUMED_PENDING_VCONT,
1080
1081 /* We have been asked to resume this thread, and we have sent a vCont action
1082 for it. */
1083 RESUMED,
1084 };
1085
1086 /* Information about a thread's pending vCont-resume. Used when a thread is in
1087 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1088 stores this information which is then picked up by
1089 remote_target::commit_resume to know which is the proper action for this
1090 thread to include in the vCont packet. */
1091 struct resumed_pending_vcont_info
1092 {
1093 /* True if the last resume call for this thread was a step request, false
1094 if a continue request. */
1095 bool step;
1096
1097 /* The signal specified in the last resume call for this thread. */
1098 gdb_signal sig;
1099 };
1100
1101 /* Private data that we'll store in (struct thread_info)->priv. */
1102 struct remote_thread_info : public private_thread_info
1103 {
1104 std::string extra;
1105 std::string name;
1106 int core = -1;
1107
1108 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1109 sequence of bytes. */
1110 gdb::byte_vector thread_handle;
1111
1112 /* Whether the target stopped for a breakpoint/watchpoint. */
1113 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1114
1115 /* This is set to the data address of the access causing the target
1116 to stop for a watchpoint. */
1117 CORE_ADDR watch_data_address = 0;
1118
1119 /* Get the thread's resume state. */
1120 enum resume_state get_resume_state () const
1121 {
1122 return m_resume_state;
1123 }
1124
1125 /* Put the thread in the NOT_RESUMED state. */
1126 void set_not_resumed ()
1127 {
1128 m_resume_state = resume_state::NOT_RESUMED;
1129 }
1130
1131 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1132 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1133 {
1134 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1135 m_resumed_pending_vcont_info.step = step;
1136 m_resumed_pending_vcont_info.sig = sig;
1137 }
1138
1139 /* Get the information this thread's pending vCont-resumption.
1140
1141 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1142 state. */
1143 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1144 {
1145 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1146
1147 return m_resumed_pending_vcont_info;
1148 }
1149
1150 /* Put the thread in the VCONT_RESUMED state. */
1151 void set_resumed ()
1152 {
1153 m_resume_state = resume_state::RESUMED;
1154 }
1155
1156 private:
1157 /* Resume state for this thread. This is used to implement vCont action
1158 coalescing (only when the target operates in non-stop mode).
1159
1160 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1161 which notes that this thread must be considered in the next commit_resume
1162 call.
1163
1164 remote_target::commit_resume sends a vCont packet with actions for the
1165 threads in the RESUMED_PENDING_VCONT state and moves them to the
1166 VCONT_RESUMED state.
1167
1168 When reporting a stop to the core for a thread, that thread is moved back
1169 to the NOT_RESUMED state. */
1170 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1171
1172 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1173 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1174 };
1175
1176 remote_state::remote_state ()
1177 : buf (400)
1178 {
1179 }
1180
1181 remote_state::~remote_state ()
1182 {
1183 xfree (this->last_pass_packet);
1184 xfree (this->last_program_signals_packet);
1185 xfree (this->finished_object);
1186 xfree (this->finished_annex);
1187 }
1188
1189 /* Utility: generate error from an incoming stub packet. */
1190 static void
1191 trace_error (char *buf)
1192 {
1193 if (*buf++ != 'E')
1194 return; /* not an error msg */
1195 switch (*buf)
1196 {
1197 case '1': /* malformed packet error */
1198 if (*++buf == '0') /* general case: */
1199 error (_("remote.c: error in outgoing packet."));
1200 else
1201 error (_("remote.c: error in outgoing packet at field #%ld."),
1202 strtol (buf, NULL, 16));
1203 default:
1204 error (_("Target returns error code '%s'."), buf);
1205 }
1206 }
1207
1208 /* Utility: wait for reply from stub, while accepting "O" packets. */
1209
1210 char *
1211 remote_target::remote_get_noisy_reply ()
1212 {
1213 struct remote_state *rs = get_remote_state ();
1214
1215 do /* Loop on reply from remote stub. */
1216 {
1217 char *buf;
1218
1219 QUIT; /* Allow user to bail out with ^C. */
1220 getpkt (&rs->buf, 0);
1221 buf = rs->buf.data ();
1222 if (buf[0] == 'E')
1223 trace_error (buf);
1224 else if (startswith (buf, "qRelocInsn:"))
1225 {
1226 ULONGEST ul;
1227 CORE_ADDR from, to, org_to;
1228 const char *p, *pp;
1229 int adjusted_size = 0;
1230 int relocated = 0;
1231
1232 p = buf + strlen ("qRelocInsn:");
1233 pp = unpack_varlen_hex (p, &ul);
1234 if (*pp != ';')
1235 error (_("invalid qRelocInsn packet: %s"), buf);
1236 from = ul;
1237
1238 p = pp + 1;
1239 unpack_varlen_hex (p, &ul);
1240 to = ul;
1241
1242 org_to = to;
1243
1244 try
1245 {
1246 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1247 relocated = 1;
1248 }
1249 catch (const gdb_exception &ex)
1250 {
1251 if (ex.error == MEMORY_ERROR)
1252 {
1253 /* Propagate memory errors silently back to the
1254 target. The stub may have limited the range of
1255 addresses we can write to, for example. */
1256 }
1257 else
1258 {
1259 /* Something unexpectedly bad happened. Be verbose
1260 so we can tell what, and propagate the error back
1261 to the stub, so it doesn't get stuck waiting for
1262 a response. */
1263 exception_fprintf (gdb_stderr, ex,
1264 _("warning: relocating instruction: "));
1265 }
1266 putpkt ("E01");
1267 }
1268
1269 if (relocated)
1270 {
1271 adjusted_size = to - org_to;
1272
1273 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1274 putpkt (buf);
1275 }
1276 }
1277 else if (buf[0] == 'O' && buf[1] != 'K')
1278 remote_console_output (buf + 1); /* 'O' message from stub */
1279 else
1280 return buf; /* Here's the actual reply. */
1281 }
1282 while (1);
1283 }
1284
1285 struct remote_arch_state *
1286 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1287 {
1288 remote_arch_state *rsa;
1289
1290 auto it = this->m_arch_states.find (gdbarch);
1291 if (it == this->m_arch_states.end ())
1292 {
1293 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1294 std::forward_as_tuple (gdbarch),
1295 std::forward_as_tuple (gdbarch));
1296 rsa = &p.first->second;
1297
1298 /* Make sure that the packet buffer is plenty big enough for
1299 this architecture. */
1300 if (this->buf.size () < rsa->remote_packet_size)
1301 this->buf.resize (2 * rsa->remote_packet_size);
1302 }
1303 else
1304 rsa = &it->second;
1305
1306 return rsa;
1307 }
1308
1309 /* Fetch the global remote target state. */
1310
1311 remote_state *
1312 remote_target::get_remote_state ()
1313 {
1314 /* Make sure that the remote architecture state has been
1315 initialized, because doing so might reallocate rs->buf. Any
1316 function which calls getpkt also needs to be mindful of changes
1317 to rs->buf, but this call limits the number of places which run
1318 into trouble. */
1319 m_remote_state.get_remote_arch_state (target_gdbarch ());
1320
1321 return &m_remote_state;
1322 }
1323
1324 /* Fetch the remote exec-file from the current program space. */
1325
1326 static const char *
1327 get_remote_exec_file (void)
1328 {
1329 char *remote_exec_file;
1330
1331 remote_exec_file = remote_pspace_data.get (current_program_space);
1332 if (remote_exec_file == NULL)
1333 return "";
1334
1335 return remote_exec_file;
1336 }
1337
1338 /* Set the remote exec file for PSPACE. */
1339
1340 static void
1341 set_pspace_remote_exec_file (struct program_space *pspace,
1342 const char *remote_exec_file)
1343 {
1344 char *old_file = remote_pspace_data.get (pspace);
1345
1346 xfree (old_file);
1347 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1348 }
1349
1350 /* The "set/show remote exec-file" set command hook. */
1351
1352 static void
1353 set_remote_exec_file (const char *ignored, int from_tty,
1354 struct cmd_list_element *c)
1355 {
1356 gdb_assert (remote_exec_file_var != NULL);
1357 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1358 }
1359
1360 /* The "set/show remote exec-file" show command hook. */
1361
1362 static void
1363 show_remote_exec_file (struct ui_file *file, int from_tty,
1364 struct cmd_list_element *cmd, const char *value)
1365 {
1366 fprintf_filtered (file, "%s\n", get_remote_exec_file ());
1367 }
1368
1369 static int
1370 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1371 {
1372 int regnum, num_remote_regs, offset;
1373 struct packet_reg **remote_regs;
1374
1375 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1376 {
1377 struct packet_reg *r = &regs[regnum];
1378
1379 if (register_size (gdbarch, regnum) == 0)
1380 /* Do not try to fetch zero-sized (placeholder) registers. */
1381 r->pnum = -1;
1382 else
1383 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1384
1385 r->regnum = regnum;
1386 }
1387
1388 /* Define the g/G packet format as the contents of each register
1389 with a remote protocol number, in order of ascending protocol
1390 number. */
1391
1392 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1393 for (num_remote_regs = 0, regnum = 0;
1394 regnum < gdbarch_num_regs (gdbarch);
1395 regnum++)
1396 if (regs[regnum].pnum != -1)
1397 remote_regs[num_remote_regs++] = &regs[regnum];
1398
1399 std::sort (remote_regs, remote_regs + num_remote_regs,
1400 [] (const packet_reg *a, const packet_reg *b)
1401 { return a->pnum < b->pnum; });
1402
1403 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1404 {
1405 remote_regs[regnum]->in_g_packet = 1;
1406 remote_regs[regnum]->offset = offset;
1407 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1408 }
1409
1410 return offset;
1411 }
1412
1413 /* Given the architecture described by GDBARCH, return the remote
1414 protocol register's number and the register's offset in the g/G
1415 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1416 If the target does not have a mapping for REGNUM, return false,
1417 otherwise, return true. */
1418
1419 int
1420 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1421 int *pnum, int *poffset)
1422 {
1423 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1424
1425 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1426
1427 map_regcache_remote_table (gdbarch, regs.data ());
1428
1429 *pnum = regs[regnum].pnum;
1430 *poffset = regs[regnum].offset;
1431
1432 return *pnum != -1;
1433 }
1434
1435 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1436 {
1437 /* Use the architecture to build a regnum<->pnum table, which will be
1438 1:1 unless a feature set specifies otherwise. */
1439 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1440
1441 /* Record the maximum possible size of the g packet - it may turn out
1442 to be smaller. */
1443 this->sizeof_g_packet
1444 = map_regcache_remote_table (gdbarch, this->regs.get ());
1445
1446 /* Default maximum number of characters in a packet body. Many
1447 remote stubs have a hardwired buffer size of 400 bytes
1448 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1449 as the maximum packet-size to ensure that the packet and an extra
1450 NUL character can always fit in the buffer. This stops GDB
1451 trashing stubs that try to squeeze an extra NUL into what is
1452 already a full buffer (As of 1999-12-04 that was most stubs). */
1453 this->remote_packet_size = 400 - 1;
1454
1455 /* This one is filled in when a ``g'' packet is received. */
1456 this->actual_register_packet_size = 0;
1457
1458 /* Should rsa->sizeof_g_packet needs more space than the
1459 default, adjust the size accordingly. Remember that each byte is
1460 encoded as two characters. 32 is the overhead for the packet
1461 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1462 (``$NN:G...#NN'') is a better guess, the below has been padded a
1463 little. */
1464 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1465 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1466 }
1467
1468 /* Get a pointer to the current remote target. If not connected to a
1469 remote target, return NULL. */
1470
1471 static remote_target *
1472 get_current_remote_target ()
1473 {
1474 target_ops *proc_target = current_inferior ()->process_target ();
1475 return dynamic_cast<remote_target *> (proc_target);
1476 }
1477
1478 /* Return the current allowed size of a remote packet. This is
1479 inferred from the current architecture, and should be used to
1480 limit the length of outgoing packets. */
1481 long
1482 remote_target::get_remote_packet_size ()
1483 {
1484 struct remote_state *rs = get_remote_state ();
1485 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1486
1487 if (rs->explicit_packet_size)
1488 return rs->explicit_packet_size;
1489
1490 return rsa->remote_packet_size;
1491 }
1492
1493 static struct packet_reg *
1494 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1495 long regnum)
1496 {
1497 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1498 return NULL;
1499 else
1500 {
1501 struct packet_reg *r = &rsa->regs[regnum];
1502
1503 gdb_assert (r->regnum == regnum);
1504 return r;
1505 }
1506 }
1507
1508 static struct packet_reg *
1509 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1510 LONGEST pnum)
1511 {
1512 int i;
1513
1514 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1515 {
1516 struct packet_reg *r = &rsa->regs[i];
1517
1518 if (r->pnum == pnum)
1519 return r;
1520 }
1521 return NULL;
1522 }
1523
1524 /* Allow the user to specify what sequence to send to the remote
1525 when he requests a program interruption: Although ^C is usually
1526 what remote systems expect (this is the default, here), it is
1527 sometimes preferable to send a break. On other systems such
1528 as the Linux kernel, a break followed by g, which is Magic SysRq g
1529 is required in order to interrupt the execution. */
1530 const char interrupt_sequence_control_c[] = "Ctrl-C";
1531 const char interrupt_sequence_break[] = "BREAK";
1532 const char interrupt_sequence_break_g[] = "BREAK-g";
1533 static const char *const interrupt_sequence_modes[] =
1534 {
1535 interrupt_sequence_control_c,
1536 interrupt_sequence_break,
1537 interrupt_sequence_break_g,
1538 NULL
1539 };
1540 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1541
1542 static void
1543 show_interrupt_sequence (struct ui_file *file, int from_tty,
1544 struct cmd_list_element *c,
1545 const char *value)
1546 {
1547 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1548 fprintf_filtered (file,
1549 _("Send the ASCII ETX character (Ctrl-c) "
1550 "to the remote target to interrupt the "
1551 "execution of the program.\n"));
1552 else if (interrupt_sequence_mode == interrupt_sequence_break)
1553 fprintf_filtered (file,
1554 _("send a break signal to the remote target "
1555 "to interrupt the execution of the program.\n"));
1556 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1557 fprintf_filtered (file,
1558 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1559 "the remote target to interrupt the execution "
1560 "of Linux kernel.\n"));
1561 else
1562 internal_error (__FILE__, __LINE__,
1563 _("Invalid value for interrupt_sequence_mode: %s."),
1564 interrupt_sequence_mode);
1565 }
1566
1567 /* This boolean variable specifies whether interrupt_sequence is sent
1568 to the remote target when gdb connects to it.
1569 This is mostly needed when you debug the Linux kernel: The Linux kernel
1570 expects BREAK g which is Magic SysRq g for connecting gdb. */
1571 static bool interrupt_on_connect = false;
1572
1573 /* This variable is used to implement the "set/show remotebreak" commands.
1574 Since these commands are now deprecated in favor of "set/show remote
1575 interrupt-sequence", it no longer has any effect on the code. */
1576 static bool remote_break;
1577
1578 static void
1579 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1580 {
1581 if (remote_break)
1582 interrupt_sequence_mode = interrupt_sequence_break;
1583 else
1584 interrupt_sequence_mode = interrupt_sequence_control_c;
1585 }
1586
1587 static void
1588 show_remotebreak (struct ui_file *file, int from_tty,
1589 struct cmd_list_element *c,
1590 const char *value)
1591 {
1592 }
1593
1594 /* This variable sets the number of bits in an address that are to be
1595 sent in a memory ("M" or "m") packet. Normally, after stripping
1596 leading zeros, the entire address would be sent. This variable
1597 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1598 initial implementation of remote.c restricted the address sent in
1599 memory packets to ``host::sizeof long'' bytes - (typically 32
1600 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1601 address was never sent. Since fixing this bug may cause a break in
1602 some remote targets this variable is principally provided to
1603 facilitate backward compatibility. */
1604
1605 static unsigned int remote_address_size;
1606
1607 \f
1608 /* User configurable variables for the number of characters in a
1609 memory read/write packet. MIN (rsa->remote_packet_size,
1610 rsa->sizeof_g_packet) is the default. Some targets need smaller
1611 values (fifo overruns, et.al.) and some users need larger values
1612 (speed up transfers). The variables ``preferred_*'' (the user
1613 request), ``current_*'' (what was actually set) and ``forced_*''
1614 (Positive - a soft limit, negative - a hard limit). */
1615
1616 struct memory_packet_config
1617 {
1618 const char *name;
1619 long size;
1620 int fixed_p;
1621 };
1622
1623 /* The default max memory-write-packet-size, when the setting is
1624 "fixed". The 16k is historical. (It came from older GDB's using
1625 alloca for buffers and the knowledge (folklore?) that some hosts
1626 don't cope very well with large alloca calls.) */
1627 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1628
1629 /* The minimum remote packet size for memory transfers. Ensures we
1630 can write at least one byte. */
1631 #define MIN_MEMORY_PACKET_SIZE 20
1632
1633 /* Get the memory packet size, assuming it is fixed. */
1634
1635 static long
1636 get_fixed_memory_packet_size (struct memory_packet_config *config)
1637 {
1638 gdb_assert (config->fixed_p);
1639
1640 if (config->size <= 0)
1641 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1642 else
1643 return config->size;
1644 }
1645
1646 /* Compute the current size of a read/write packet. Since this makes
1647 use of ``actual_register_packet_size'' the computation is dynamic. */
1648
1649 long
1650 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1651 {
1652 struct remote_state *rs = get_remote_state ();
1653 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1654
1655 long what_they_get;
1656 if (config->fixed_p)
1657 what_they_get = get_fixed_memory_packet_size (config);
1658 else
1659 {
1660 what_they_get = get_remote_packet_size ();
1661 /* Limit the packet to the size specified by the user. */
1662 if (config->size > 0
1663 && what_they_get > config->size)
1664 what_they_get = config->size;
1665
1666 /* Limit it to the size of the targets ``g'' response unless we have
1667 permission from the stub to use a larger packet size. */
1668 if (rs->explicit_packet_size == 0
1669 && rsa->actual_register_packet_size > 0
1670 && what_they_get > rsa->actual_register_packet_size)
1671 what_they_get = rsa->actual_register_packet_size;
1672 }
1673 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1674 what_they_get = MIN_MEMORY_PACKET_SIZE;
1675
1676 /* Make sure there is room in the global buffer for this packet
1677 (including its trailing NUL byte). */
1678 if (rs->buf.size () < what_they_get + 1)
1679 rs->buf.resize (2 * what_they_get);
1680
1681 return what_they_get;
1682 }
1683
1684 /* Update the size of a read/write packet. If they user wants
1685 something really big then do a sanity check. */
1686
1687 static void
1688 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1689 {
1690 int fixed_p = config->fixed_p;
1691 long size = config->size;
1692
1693 if (args == NULL)
1694 error (_("Argument required (integer, `fixed' or `limited')."));
1695 else if (strcmp (args, "hard") == 0
1696 || strcmp (args, "fixed") == 0)
1697 fixed_p = 1;
1698 else if (strcmp (args, "soft") == 0
1699 || strcmp (args, "limit") == 0)
1700 fixed_p = 0;
1701 else
1702 {
1703 char *end;
1704
1705 size = strtoul (args, &end, 0);
1706 if (args == end)
1707 error (_("Invalid %s (bad syntax)."), config->name);
1708
1709 /* Instead of explicitly capping the size of a packet to or
1710 disallowing it, the user is allowed to set the size to
1711 something arbitrarily large. */
1712 }
1713
1714 /* Extra checks? */
1715 if (fixed_p && !config->fixed_p)
1716 {
1717 /* So that the query shows the correct value. */
1718 long query_size = (size <= 0
1719 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1720 : size);
1721
1722 if (! query (_("The target may not be able to correctly handle a %s\n"
1723 "of %ld bytes. Change the packet size? "),
1724 config->name, query_size))
1725 error (_("Packet size not changed."));
1726 }
1727 /* Update the config. */
1728 config->fixed_p = fixed_p;
1729 config->size = size;
1730 }
1731
1732 static void
1733 show_memory_packet_size (struct memory_packet_config *config)
1734 {
1735 if (config->size == 0)
1736 printf_filtered (_("The %s is 0 (default). "), config->name);
1737 else
1738 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1739 if (config->fixed_p)
1740 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1741 get_fixed_memory_packet_size (config));
1742 else
1743 {
1744 remote_target *remote = get_current_remote_target ();
1745
1746 if (remote != NULL)
1747 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1748 remote->get_memory_packet_size (config));
1749 else
1750 puts_filtered ("The actual limit will be further reduced "
1751 "dependent on the target.\n");
1752 }
1753 }
1754
1755 /* FIXME: needs to be per-remote-target. */
1756 static struct memory_packet_config memory_write_packet_config =
1757 {
1758 "memory-write-packet-size",
1759 };
1760
1761 static void
1762 set_memory_write_packet_size (const char *args, int from_tty)
1763 {
1764 set_memory_packet_size (args, &memory_write_packet_config);
1765 }
1766
1767 static void
1768 show_memory_write_packet_size (const char *args, int from_tty)
1769 {
1770 show_memory_packet_size (&memory_write_packet_config);
1771 }
1772
1773 /* Show the number of hardware watchpoints that can be used. */
1774
1775 static void
1776 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1777 struct cmd_list_element *c,
1778 const char *value)
1779 {
1780 fprintf_filtered (file, _("The maximum number of target hardware "
1781 "watchpoints is %s.\n"), value);
1782 }
1783
1784 /* Show the length limit (in bytes) for hardware watchpoints. */
1785
1786 static void
1787 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1788 struct cmd_list_element *c,
1789 const char *value)
1790 {
1791 fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1792 "hardware watchpoint is %s.\n"), value);
1793 }
1794
1795 /* Show the number of hardware breakpoints that can be used. */
1796
1797 static void
1798 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1799 struct cmd_list_element *c,
1800 const char *value)
1801 {
1802 fprintf_filtered (file, _("The maximum number of target hardware "
1803 "breakpoints is %s.\n"), value);
1804 }
1805
1806 /* Controls the maximum number of characters to display in the debug output
1807 for each remote packet. The remaining characters are omitted. */
1808
1809 static int remote_packet_max_chars = 512;
1810
1811 /* Show the maximum number of characters to display for each remote packet
1812 when remote debugging is enabled. */
1813
1814 static void
1815 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1816 struct cmd_list_element *c,
1817 const char *value)
1818 {
1819 fprintf_filtered (file, _("Number of remote packet characters to "
1820 "display is %s.\n"), value);
1821 }
1822
1823 long
1824 remote_target::get_memory_write_packet_size ()
1825 {
1826 return get_memory_packet_size (&memory_write_packet_config);
1827 }
1828
1829 /* FIXME: needs to be per-remote-target. */
1830 static struct memory_packet_config memory_read_packet_config =
1831 {
1832 "memory-read-packet-size",
1833 };
1834
1835 static void
1836 set_memory_read_packet_size (const char *args, int from_tty)
1837 {
1838 set_memory_packet_size (args, &memory_read_packet_config);
1839 }
1840
1841 static void
1842 show_memory_read_packet_size (const char *args, int from_tty)
1843 {
1844 show_memory_packet_size (&memory_read_packet_config);
1845 }
1846
1847 long
1848 remote_target::get_memory_read_packet_size ()
1849 {
1850 long size = get_memory_packet_size (&memory_read_packet_config);
1851
1852 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1853 extra buffer size argument before the memory read size can be
1854 increased beyond this. */
1855 if (size > get_remote_packet_size ())
1856 size = get_remote_packet_size ();
1857 return size;
1858 }
1859
1860 \f
1861
1862 struct packet_config
1863 {
1864 const char *name;
1865 const char *title;
1866
1867 /* If auto, GDB auto-detects support for this packet or feature,
1868 either through qSupported, or by trying the packet and looking
1869 at the response. If true, GDB assumes the target supports this
1870 packet. If false, the packet is disabled. Configs that don't
1871 have an associated command always have this set to auto. */
1872 enum auto_boolean detect;
1873
1874 /* Does the target support this packet? */
1875 enum packet_support support;
1876 };
1877
1878 static enum packet_support packet_config_support (struct packet_config *config);
1879 static enum packet_support packet_support (int packet);
1880
1881 static void
1882 show_packet_config_cmd (struct packet_config *config)
1883 {
1884 const char *support = "internal-error";
1885
1886 switch (packet_config_support (config))
1887 {
1888 case PACKET_ENABLE:
1889 support = "enabled";
1890 break;
1891 case PACKET_DISABLE:
1892 support = "disabled";
1893 break;
1894 case PACKET_SUPPORT_UNKNOWN:
1895 support = "unknown";
1896 break;
1897 }
1898 switch (config->detect)
1899 {
1900 case AUTO_BOOLEAN_AUTO:
1901 printf_filtered (_("Support for the `%s' packet "
1902 "is auto-detected, currently %s.\n"),
1903 config->name, support);
1904 break;
1905 case AUTO_BOOLEAN_TRUE:
1906 case AUTO_BOOLEAN_FALSE:
1907 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1908 config->name, support);
1909 break;
1910 }
1911 }
1912
1913 static void
1914 add_packet_config_cmd (struct packet_config *config, const char *name,
1915 const char *title, int legacy)
1916 {
1917 char *set_doc;
1918 char *show_doc;
1919 char *cmd_name;
1920
1921 config->name = name;
1922 config->title = title;
1923 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1924 name, title);
1925 show_doc = xstrprintf ("Show current use of remote "
1926 "protocol `%s' (%s) packet.",
1927 name, title);
1928 /* set/show TITLE-packet {auto,on,off} */
1929 cmd_name = xstrprintf ("%s-packet", title);
1930 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1931 &config->detect, set_doc,
1932 show_doc, NULL, /* help_doc */
1933 NULL,
1934 show_remote_protocol_packet_cmd,
1935 &remote_set_cmdlist, &remote_show_cmdlist);
1936 /* The command code copies the documentation strings. */
1937 xfree (set_doc);
1938 xfree (show_doc);
1939 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1940 if (legacy)
1941 {
1942 char *legacy_name;
1943
1944 legacy_name = xstrprintf ("%s-packet", name);
1945 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1946 &remote_set_cmdlist);
1947 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1948 &remote_show_cmdlist);
1949 }
1950 }
1951
1952 static enum packet_result
1953 packet_check_result (const char *buf)
1954 {
1955 if (buf[0] != '\0')
1956 {
1957 /* The stub recognized the packet request. Check that the
1958 operation succeeded. */
1959 if (buf[0] == 'E'
1960 && isxdigit (buf[1]) && isxdigit (buf[2])
1961 && buf[3] == '\0')
1962 /* "Enn" - definitely an error. */
1963 return PACKET_ERROR;
1964
1965 /* Always treat "E." as an error. This will be used for
1966 more verbose error messages, such as E.memtypes. */
1967 if (buf[0] == 'E' && buf[1] == '.')
1968 return PACKET_ERROR;
1969
1970 /* The packet may or may not be OK. Just assume it is. */
1971 return PACKET_OK;
1972 }
1973 else
1974 /* The stub does not support the packet. */
1975 return PACKET_UNKNOWN;
1976 }
1977
1978 static enum packet_result
1979 packet_check_result (const gdb::char_vector &buf)
1980 {
1981 return packet_check_result (buf.data ());
1982 }
1983
1984 static enum packet_result
1985 packet_ok (const char *buf, struct packet_config *config)
1986 {
1987 enum packet_result result;
1988
1989 if (config->detect != AUTO_BOOLEAN_TRUE
1990 && config->support == PACKET_DISABLE)
1991 internal_error (__FILE__, __LINE__,
1992 _("packet_ok: attempt to use a disabled packet"));
1993
1994 result = packet_check_result (buf);
1995 switch (result)
1996 {
1997 case PACKET_OK:
1998 case PACKET_ERROR:
1999 /* The stub recognized the packet request. */
2000 if (config->support == PACKET_SUPPORT_UNKNOWN)
2001 {
2002 remote_debug_printf ("Packet %s (%s) is supported",
2003 config->name, config->title);
2004 config->support = PACKET_ENABLE;
2005 }
2006 break;
2007 case PACKET_UNKNOWN:
2008 /* The stub does not support the packet. */
2009 if (config->detect == AUTO_BOOLEAN_AUTO
2010 && config->support == PACKET_ENABLE)
2011 {
2012 /* If the stub previously indicated that the packet was
2013 supported then there is a protocol error. */
2014 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2015 config->name, config->title);
2016 }
2017 else if (config->detect == AUTO_BOOLEAN_TRUE)
2018 {
2019 /* The user set it wrong. */
2020 error (_("Enabled packet %s (%s) not recognized by stub"),
2021 config->name, config->title);
2022 }
2023
2024 remote_debug_printf ("Packet %s (%s) is NOT supported",
2025 config->name, config->title);
2026 config->support = PACKET_DISABLE;
2027 break;
2028 }
2029
2030 return result;
2031 }
2032
2033 static enum packet_result
2034 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2035 {
2036 return packet_ok (buf.data (), config);
2037 }
2038
2039 enum {
2040 PACKET_vCont = 0,
2041 PACKET_X,
2042 PACKET_qSymbol,
2043 PACKET_P,
2044 PACKET_p,
2045 PACKET_Z0,
2046 PACKET_Z1,
2047 PACKET_Z2,
2048 PACKET_Z3,
2049 PACKET_Z4,
2050 PACKET_vFile_setfs,
2051 PACKET_vFile_open,
2052 PACKET_vFile_pread,
2053 PACKET_vFile_pwrite,
2054 PACKET_vFile_close,
2055 PACKET_vFile_unlink,
2056 PACKET_vFile_readlink,
2057 PACKET_vFile_fstat,
2058 PACKET_qXfer_auxv,
2059 PACKET_qXfer_features,
2060 PACKET_qXfer_exec_file,
2061 PACKET_qXfer_libraries,
2062 PACKET_qXfer_libraries_svr4,
2063 PACKET_qXfer_memory_map,
2064 PACKET_qXfer_osdata,
2065 PACKET_qXfer_threads,
2066 PACKET_qXfer_statictrace_read,
2067 PACKET_qXfer_traceframe_info,
2068 PACKET_qXfer_uib,
2069 PACKET_qGetTIBAddr,
2070 PACKET_qGetTLSAddr,
2071 PACKET_qSupported,
2072 PACKET_qTStatus,
2073 PACKET_QPassSignals,
2074 PACKET_QCatchSyscalls,
2075 PACKET_QProgramSignals,
2076 PACKET_QSetWorkingDir,
2077 PACKET_QStartupWithShell,
2078 PACKET_QEnvironmentHexEncoded,
2079 PACKET_QEnvironmentReset,
2080 PACKET_QEnvironmentUnset,
2081 PACKET_qCRC,
2082 PACKET_qSearch_memory,
2083 PACKET_vAttach,
2084 PACKET_vRun,
2085 PACKET_QStartNoAckMode,
2086 PACKET_vKill,
2087 PACKET_qXfer_siginfo_read,
2088 PACKET_qXfer_siginfo_write,
2089 PACKET_qAttached,
2090
2091 /* Support for conditional tracepoints. */
2092 PACKET_ConditionalTracepoints,
2093
2094 /* Support for target-side breakpoint conditions. */
2095 PACKET_ConditionalBreakpoints,
2096
2097 /* Support for target-side breakpoint commands. */
2098 PACKET_BreakpointCommands,
2099
2100 /* Support for fast tracepoints. */
2101 PACKET_FastTracepoints,
2102
2103 /* Support for static tracepoints. */
2104 PACKET_StaticTracepoints,
2105
2106 /* Support for installing tracepoints while a trace experiment is
2107 running. */
2108 PACKET_InstallInTrace,
2109
2110 PACKET_bc,
2111 PACKET_bs,
2112 PACKET_TracepointSource,
2113 PACKET_QAllow,
2114 PACKET_qXfer_fdpic,
2115 PACKET_QDisableRandomization,
2116 PACKET_QAgent,
2117 PACKET_QTBuffer_size,
2118 PACKET_Qbtrace_off,
2119 PACKET_Qbtrace_bts,
2120 PACKET_Qbtrace_pt,
2121 PACKET_qXfer_btrace,
2122
2123 /* Support for the QNonStop packet. */
2124 PACKET_QNonStop,
2125
2126 /* Support for the QThreadEvents packet. */
2127 PACKET_QThreadEvents,
2128
2129 /* Support for multi-process extensions. */
2130 PACKET_multiprocess_feature,
2131
2132 /* Support for enabling and disabling tracepoints while a trace
2133 experiment is running. */
2134 PACKET_EnableDisableTracepoints_feature,
2135
2136 /* Support for collecting strings using the tracenz bytecode. */
2137 PACKET_tracenz_feature,
2138
2139 /* Support for continuing to run a trace experiment while GDB is
2140 disconnected. */
2141 PACKET_DisconnectedTracing_feature,
2142
2143 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2144 PACKET_augmented_libraries_svr4_read_feature,
2145
2146 /* Support for the qXfer:btrace-conf:read packet. */
2147 PACKET_qXfer_btrace_conf,
2148
2149 /* Support for the Qbtrace-conf:bts:size packet. */
2150 PACKET_Qbtrace_conf_bts_size,
2151
2152 /* Support for swbreak+ feature. */
2153 PACKET_swbreak_feature,
2154
2155 /* Support for hwbreak+ feature. */
2156 PACKET_hwbreak_feature,
2157
2158 /* Support for fork events. */
2159 PACKET_fork_event_feature,
2160
2161 /* Support for vfork events. */
2162 PACKET_vfork_event_feature,
2163
2164 /* Support for the Qbtrace-conf:pt:size packet. */
2165 PACKET_Qbtrace_conf_pt_size,
2166
2167 /* Support for exec events. */
2168 PACKET_exec_event_feature,
2169
2170 /* Support for query supported vCont actions. */
2171 PACKET_vContSupported,
2172
2173 /* Support remote CTRL-C. */
2174 PACKET_vCtrlC,
2175
2176 /* Support TARGET_WAITKIND_NO_RESUMED. */
2177 PACKET_no_resumed,
2178
2179 /* Support for memory tagging, allocation tag fetch/store
2180 packets and the tag violation stop replies. */
2181 PACKET_memory_tagging_feature,
2182
2183 PACKET_MAX
2184 };
2185
2186 /* FIXME: needs to be per-remote-target. Ignoring this for now,
2187 assuming all remote targets are the same server (thus all support
2188 the same packets). */
2189 static struct packet_config remote_protocol_packets[PACKET_MAX];
2190
2191 /* Returns the packet's corresponding "set remote foo-packet" command
2192 state. See struct packet_config for more details. */
2193
2194 static enum auto_boolean
2195 packet_set_cmd_state (int packet)
2196 {
2197 return remote_protocol_packets[packet].detect;
2198 }
2199
2200 /* Returns whether a given packet or feature is supported. This takes
2201 into account the state of the corresponding "set remote foo-packet"
2202 command, which may be used to bypass auto-detection. */
2203
2204 static enum packet_support
2205 packet_config_support (struct packet_config *config)
2206 {
2207 switch (config->detect)
2208 {
2209 case AUTO_BOOLEAN_TRUE:
2210 return PACKET_ENABLE;
2211 case AUTO_BOOLEAN_FALSE:
2212 return PACKET_DISABLE;
2213 case AUTO_BOOLEAN_AUTO:
2214 return config->support;
2215 default:
2216 gdb_assert_not_reached (_("bad switch"));
2217 }
2218 }
2219
2220 /* Same as packet_config_support, but takes the packet's enum value as
2221 argument. */
2222
2223 static enum packet_support
2224 packet_support (int packet)
2225 {
2226 struct packet_config *config = &remote_protocol_packets[packet];
2227
2228 return packet_config_support (config);
2229 }
2230
2231 static void
2232 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2233 struct cmd_list_element *c,
2234 const char *value)
2235 {
2236 struct packet_config *packet;
2237
2238 for (packet = remote_protocol_packets;
2239 packet < &remote_protocol_packets[PACKET_MAX];
2240 packet++)
2241 {
2242 if (&packet->detect == c->var)
2243 {
2244 show_packet_config_cmd (packet);
2245 return;
2246 }
2247 }
2248 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2249 c->name);
2250 }
2251
2252 /* Should we try one of the 'Z' requests? */
2253
2254 enum Z_packet_type
2255 {
2256 Z_PACKET_SOFTWARE_BP,
2257 Z_PACKET_HARDWARE_BP,
2258 Z_PACKET_WRITE_WP,
2259 Z_PACKET_READ_WP,
2260 Z_PACKET_ACCESS_WP,
2261 NR_Z_PACKET_TYPES
2262 };
2263
2264 /* For compatibility with older distributions. Provide a ``set remote
2265 Z-packet ...'' command that updates all the Z packet types. */
2266
2267 static enum auto_boolean remote_Z_packet_detect;
2268
2269 static void
2270 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2271 struct cmd_list_element *c)
2272 {
2273 int i;
2274
2275 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2276 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2277 }
2278
2279 static void
2280 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2281 struct cmd_list_element *c,
2282 const char *value)
2283 {
2284 int i;
2285
2286 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2287 {
2288 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2289 }
2290 }
2291
2292 /* Returns true if the multi-process extensions are in effect. */
2293
2294 static int
2295 remote_multi_process_p (struct remote_state *rs)
2296 {
2297 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2298 }
2299
2300 /* Returns true if fork events are supported. */
2301
2302 static int
2303 remote_fork_event_p (struct remote_state *rs)
2304 {
2305 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2306 }
2307
2308 /* Returns true if vfork events are supported. */
2309
2310 static int
2311 remote_vfork_event_p (struct remote_state *rs)
2312 {
2313 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2314 }
2315
2316 /* Returns true if exec events are supported. */
2317
2318 static int
2319 remote_exec_event_p (struct remote_state *rs)
2320 {
2321 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2322 }
2323
2324 /* Returns true if memory tagging is supported, false otherwise. */
2325
2326 static bool
2327 remote_memory_tagging_p ()
2328 {
2329 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2330 }
2331
2332 /* Insert fork catchpoint target routine. If fork events are enabled
2333 then return success, nothing more to do. */
2334
2335 int
2336 remote_target::insert_fork_catchpoint (int pid)
2337 {
2338 struct remote_state *rs = get_remote_state ();
2339
2340 return !remote_fork_event_p (rs);
2341 }
2342
2343 /* Remove fork catchpoint target routine. Nothing to do, just
2344 return success. */
2345
2346 int
2347 remote_target::remove_fork_catchpoint (int pid)
2348 {
2349 return 0;
2350 }
2351
2352 /* Insert vfork catchpoint target routine. If vfork events are enabled
2353 then return success, nothing more to do. */
2354
2355 int
2356 remote_target::insert_vfork_catchpoint (int pid)
2357 {
2358 struct remote_state *rs = get_remote_state ();
2359
2360 return !remote_vfork_event_p (rs);
2361 }
2362
2363 /* Remove vfork catchpoint target routine. Nothing to do, just
2364 return success. */
2365
2366 int
2367 remote_target::remove_vfork_catchpoint (int pid)
2368 {
2369 return 0;
2370 }
2371
2372 /* Insert exec catchpoint target routine. If exec events are
2373 enabled, just return success. */
2374
2375 int
2376 remote_target::insert_exec_catchpoint (int pid)
2377 {
2378 struct remote_state *rs = get_remote_state ();
2379
2380 return !remote_exec_event_p (rs);
2381 }
2382
2383 /* Remove exec catchpoint target routine. Nothing to do, just
2384 return success. */
2385
2386 int
2387 remote_target::remove_exec_catchpoint (int pid)
2388 {
2389 return 0;
2390 }
2391
2392 \f
2393
2394 /* Take advantage of the fact that the TID field is not used, to tag
2395 special ptids with it set to != 0. */
2396 static const ptid_t magic_null_ptid (42000, -1, 1);
2397 static const ptid_t not_sent_ptid (42000, -2, 1);
2398 static const ptid_t any_thread_ptid (42000, 0, 1);
2399
2400 /* Find out if the stub attached to PID (and hence GDB should offer to
2401 detach instead of killing it when bailing out). */
2402
2403 int
2404 remote_target::remote_query_attached (int pid)
2405 {
2406 struct remote_state *rs = get_remote_state ();
2407 size_t size = get_remote_packet_size ();
2408
2409 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2410 return 0;
2411
2412 if (remote_multi_process_p (rs))
2413 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2414 else
2415 xsnprintf (rs->buf.data (), size, "qAttached");
2416
2417 putpkt (rs->buf);
2418 getpkt (&rs->buf, 0);
2419
2420 switch (packet_ok (rs->buf,
2421 &remote_protocol_packets[PACKET_qAttached]))
2422 {
2423 case PACKET_OK:
2424 if (strcmp (rs->buf.data (), "1") == 0)
2425 return 1;
2426 break;
2427 case PACKET_ERROR:
2428 warning (_("Remote failure reply: %s"), rs->buf.data ());
2429 break;
2430 case PACKET_UNKNOWN:
2431 break;
2432 }
2433
2434 return 0;
2435 }
2436
2437 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2438 has been invented by GDB, instead of reported by the target. Since
2439 we can be connected to a remote system before before knowing about
2440 any inferior, mark the target with execution when we find the first
2441 inferior. If ATTACHED is 1, then we had just attached to this
2442 inferior. If it is 0, then we just created this inferior. If it
2443 is -1, then try querying the remote stub to find out if it had
2444 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2445 attempt to open this inferior's executable as the main executable
2446 if no main executable is open already. */
2447
2448 inferior *
2449 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2450 int try_open_exec)
2451 {
2452 struct inferior *inf;
2453
2454 /* Check whether this process we're learning about is to be
2455 considered attached, or if is to be considered to have been
2456 spawned by the stub. */
2457 if (attached == -1)
2458 attached = remote_query_attached (pid);
2459
2460 if (gdbarch_has_global_solist (target_gdbarch ()))
2461 {
2462 /* If the target shares code across all inferiors, then every
2463 attach adds a new inferior. */
2464 inf = add_inferior (pid);
2465
2466 /* ... and every inferior is bound to the same program space.
2467 However, each inferior may still have its own address
2468 space. */
2469 inf->aspace = maybe_new_address_space ();
2470 inf->pspace = current_program_space;
2471 }
2472 else
2473 {
2474 /* In the traditional debugging scenario, there's a 1-1 match
2475 between program/address spaces. We simply bind the inferior
2476 to the program space's address space. */
2477 inf = current_inferior ();
2478
2479 /* However, if the current inferior is already bound to a
2480 process, find some other empty inferior. */
2481 if (inf->pid != 0)
2482 {
2483 inf = nullptr;
2484 for (inferior *it : all_inferiors ())
2485 if (it->pid == 0)
2486 {
2487 inf = it;
2488 break;
2489 }
2490 }
2491 if (inf == nullptr)
2492 {
2493 /* Since all inferiors were already bound to a process, add
2494 a new inferior. */
2495 inf = add_inferior_with_spaces ();
2496 }
2497 switch_to_inferior_no_thread (inf);
2498 inf->push_target (this);
2499 inferior_appeared (inf, pid);
2500 }
2501
2502 inf->attach_flag = attached;
2503 inf->fake_pid_p = fake_pid_p;
2504
2505 /* If no main executable is currently open then attempt to
2506 open the file that was executed to create this inferior. */
2507 if (try_open_exec && get_exec_file (0) == NULL)
2508 exec_file_locate_attach (pid, 0, 1);
2509
2510 /* Check for exec file mismatch, and let the user solve it. */
2511 validate_exec_file (1);
2512
2513 return inf;
2514 }
2515
2516 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2517 static remote_thread_info *get_remote_thread_info (remote_target *target,
2518 ptid_t ptid);
2519
2520 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2521 according to RUNNING. */
2522
2523 thread_info *
2524 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2525 {
2526 struct remote_state *rs = get_remote_state ();
2527 struct thread_info *thread;
2528
2529 /* GDB historically didn't pull threads in the initial connection
2530 setup. If the remote target doesn't even have a concept of
2531 threads (e.g., a bare-metal target), even if internally we
2532 consider that a single-threaded target, mentioning a new thread
2533 might be confusing to the user. Be silent then, preserving the
2534 age old behavior. */
2535 if (rs->starting_up)
2536 thread = add_thread_silent (this, ptid);
2537 else
2538 thread = add_thread (this, ptid);
2539
2540 /* We start by assuming threads are resumed. That state then gets updated
2541 when we process a matching stop reply. */
2542 get_remote_thread_info (thread)->set_resumed ();
2543
2544 set_executing (this, ptid, executing);
2545 set_running (this, ptid, running);
2546
2547 return thread;
2548 }
2549
2550 /* Come here when we learn about a thread id from the remote target.
2551 It may be the first time we hear about such thread, so take the
2552 opportunity to add it to GDB's thread list. In case this is the
2553 first time we're noticing its corresponding inferior, add it to
2554 GDB's inferior list as well. EXECUTING indicates whether the
2555 thread is (internally) executing or stopped. */
2556
2557 void
2558 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2559 {
2560 /* In non-stop mode, we assume new found threads are (externally)
2561 running until proven otherwise with a stop reply. In all-stop,
2562 we can only get here if all threads are stopped. */
2563 int running = target_is_non_stop_p () ? 1 : 0;
2564
2565 /* If this is a new thread, add it to GDB's thread list.
2566 If we leave it up to WFI to do this, bad things will happen. */
2567
2568 thread_info *tp = find_thread_ptid (this, currthread);
2569 if (tp != NULL && tp->state == THREAD_EXITED)
2570 {
2571 /* We're seeing an event on a thread id we knew had exited.
2572 This has to be a new thread reusing the old id. Add it. */
2573 remote_add_thread (currthread, running, executing);
2574 return;
2575 }
2576
2577 if (!in_thread_list (this, currthread))
2578 {
2579 struct inferior *inf = NULL;
2580 int pid = currthread.pid ();
2581
2582 if (inferior_ptid.is_pid ()
2583 && pid == inferior_ptid.pid ())
2584 {
2585 /* inferior_ptid has no thread member yet. This can happen
2586 with the vAttach -> remote_wait,"TAAthread:" path if the
2587 stub doesn't support qC. This is the first stop reported
2588 after an attach, so this is the main thread. Update the
2589 ptid in the thread list. */
2590 if (in_thread_list (this, ptid_t (pid)))
2591 thread_change_ptid (this, inferior_ptid, currthread);
2592 else
2593 {
2594 thread_info *thr
2595 = remote_add_thread (currthread, running, executing);
2596 switch_to_thread (thr);
2597 }
2598 return;
2599 }
2600
2601 if (magic_null_ptid == inferior_ptid)
2602 {
2603 /* inferior_ptid is not set yet. This can happen with the
2604 vRun -> remote_wait,"TAAthread:" path if the stub
2605 doesn't support qC. This is the first stop reported
2606 after an attach, so this is the main thread. Update the
2607 ptid in the thread list. */
2608 thread_change_ptid (this, inferior_ptid, currthread);
2609 return;
2610 }
2611
2612 /* When connecting to a target remote, or to a target
2613 extended-remote which already was debugging an inferior, we
2614 may not know about it yet. Add it before adding its child
2615 thread, so notifications are emitted in a sensible order. */
2616 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2617 {
2618 struct remote_state *rs = get_remote_state ();
2619 bool fake_pid_p = !remote_multi_process_p (rs);
2620
2621 inf = remote_add_inferior (fake_pid_p,
2622 currthread.pid (), -1, 1);
2623 }
2624
2625 /* This is really a new thread. Add it. */
2626 thread_info *new_thr
2627 = remote_add_thread (currthread, running, executing);
2628
2629 /* If we found a new inferior, let the common code do whatever
2630 it needs to with it (e.g., read shared libraries, insert
2631 breakpoints), unless we're just setting up an all-stop
2632 connection. */
2633 if (inf != NULL)
2634 {
2635 struct remote_state *rs = get_remote_state ();
2636
2637 if (!rs->starting_up)
2638 notice_new_inferior (new_thr, executing, 0);
2639 }
2640 }
2641 }
2642
2643 /* Return THREAD's private thread data, creating it if necessary. */
2644
2645 static remote_thread_info *
2646 get_remote_thread_info (thread_info *thread)
2647 {
2648 gdb_assert (thread != NULL);
2649
2650 if (thread->priv == NULL)
2651 thread->priv.reset (new remote_thread_info);
2652
2653 return static_cast<remote_thread_info *> (thread->priv.get ());
2654 }
2655
2656 /* Return PTID's private thread data, creating it if necessary. */
2657
2658 static remote_thread_info *
2659 get_remote_thread_info (remote_target *target, ptid_t ptid)
2660 {
2661 thread_info *thr = find_thread_ptid (target, ptid);
2662 return get_remote_thread_info (thr);
2663 }
2664
2665 /* Call this function as a result of
2666 1) A halt indication (T packet) containing a thread id
2667 2) A direct query of currthread
2668 3) Successful execution of set thread */
2669
2670 static void
2671 record_currthread (struct remote_state *rs, ptid_t currthread)
2672 {
2673 rs->general_thread = currthread;
2674 }
2675
2676 /* If 'QPassSignals' is supported, tell the remote stub what signals
2677 it can simply pass through to the inferior without reporting. */
2678
2679 void
2680 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2681 {
2682 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2683 {
2684 char *pass_packet, *p;
2685 int count = 0;
2686 struct remote_state *rs = get_remote_state ();
2687
2688 gdb_assert (pass_signals.size () < 256);
2689 for (size_t i = 0; i < pass_signals.size (); i++)
2690 {
2691 if (pass_signals[i])
2692 count++;
2693 }
2694 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2695 strcpy (pass_packet, "QPassSignals:");
2696 p = pass_packet + strlen (pass_packet);
2697 for (size_t i = 0; i < pass_signals.size (); i++)
2698 {
2699 if (pass_signals[i])
2700 {
2701 if (i >= 16)
2702 *p++ = tohex (i >> 4);
2703 *p++ = tohex (i & 15);
2704 if (count)
2705 *p++ = ';';
2706 else
2707 break;
2708 count--;
2709 }
2710 }
2711 *p = 0;
2712 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2713 {
2714 putpkt (pass_packet);
2715 getpkt (&rs->buf, 0);
2716 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2717 xfree (rs->last_pass_packet);
2718 rs->last_pass_packet = pass_packet;
2719 }
2720 else
2721 xfree (pass_packet);
2722 }
2723 }
2724
2725 /* If 'QCatchSyscalls' is supported, tell the remote stub
2726 to report syscalls to GDB. */
2727
2728 int
2729 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2730 gdb::array_view<const int> syscall_counts)
2731 {
2732 const char *catch_packet;
2733 enum packet_result result;
2734 int n_sysno = 0;
2735
2736 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2737 {
2738 /* Not supported. */
2739 return 1;
2740 }
2741
2742 if (needed && any_count == 0)
2743 {
2744 /* Count how many syscalls are to be caught. */
2745 for (size_t i = 0; i < syscall_counts.size (); i++)
2746 {
2747 if (syscall_counts[i] != 0)
2748 n_sysno++;
2749 }
2750 }
2751
2752 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2753 pid, needed, any_count, n_sysno);
2754
2755 std::string built_packet;
2756 if (needed)
2757 {
2758 /* Prepare a packet with the sysno list, assuming max 8+1
2759 characters for a sysno. If the resulting packet size is too
2760 big, fallback on the non-selective packet. */
2761 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2762 built_packet.reserve (maxpktsz);
2763 built_packet = "QCatchSyscalls:1";
2764 if (any_count == 0)
2765 {
2766 /* Add in each syscall to be caught. */
2767 for (size_t i = 0; i < syscall_counts.size (); i++)
2768 {
2769 if (syscall_counts[i] != 0)
2770 string_appendf (built_packet, ";%zx", i);
2771 }
2772 }
2773 if (built_packet.size () > get_remote_packet_size ())
2774 {
2775 /* catch_packet too big. Fallback to less efficient
2776 non selective mode, with GDB doing the filtering. */
2777 catch_packet = "QCatchSyscalls:1";
2778 }
2779 else
2780 catch_packet = built_packet.c_str ();
2781 }
2782 else
2783 catch_packet = "QCatchSyscalls:0";
2784
2785 struct remote_state *rs = get_remote_state ();
2786
2787 putpkt (catch_packet);
2788 getpkt (&rs->buf, 0);
2789 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2790 if (result == PACKET_OK)
2791 return 0;
2792 else
2793 return -1;
2794 }
2795
2796 /* If 'QProgramSignals' is supported, tell the remote stub what
2797 signals it should pass through to the inferior when detaching. */
2798
2799 void
2800 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2801 {
2802 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2803 {
2804 char *packet, *p;
2805 int count = 0;
2806 struct remote_state *rs = get_remote_state ();
2807
2808 gdb_assert (signals.size () < 256);
2809 for (size_t i = 0; i < signals.size (); i++)
2810 {
2811 if (signals[i])
2812 count++;
2813 }
2814 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2815 strcpy (packet, "QProgramSignals:");
2816 p = packet + strlen (packet);
2817 for (size_t i = 0; i < signals.size (); i++)
2818 {
2819 if (signal_pass_state (i))
2820 {
2821 if (i >= 16)
2822 *p++ = tohex (i >> 4);
2823 *p++ = tohex (i & 15);
2824 if (count)
2825 *p++ = ';';
2826 else
2827 break;
2828 count--;
2829 }
2830 }
2831 *p = 0;
2832 if (!rs->last_program_signals_packet
2833 || strcmp (rs->last_program_signals_packet, packet) != 0)
2834 {
2835 putpkt (packet);
2836 getpkt (&rs->buf, 0);
2837 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2838 xfree (rs->last_program_signals_packet);
2839 rs->last_program_signals_packet = packet;
2840 }
2841 else
2842 xfree (packet);
2843 }
2844 }
2845
2846 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2847 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2848 thread. If GEN is set, set the general thread, if not, then set
2849 the step/continue thread. */
2850 void
2851 remote_target::set_thread (ptid_t ptid, int gen)
2852 {
2853 struct remote_state *rs = get_remote_state ();
2854 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2855 char *buf = rs->buf.data ();
2856 char *endbuf = buf + get_remote_packet_size ();
2857
2858 if (state == ptid)
2859 return;
2860
2861 *buf++ = 'H';
2862 *buf++ = gen ? 'g' : 'c';
2863 if (ptid == magic_null_ptid)
2864 xsnprintf (buf, endbuf - buf, "0");
2865 else if (ptid == any_thread_ptid)
2866 xsnprintf (buf, endbuf - buf, "0");
2867 else if (ptid == minus_one_ptid)
2868 xsnprintf (buf, endbuf - buf, "-1");
2869 else
2870 write_ptid (buf, endbuf, ptid);
2871 putpkt (rs->buf);
2872 getpkt (&rs->buf, 0);
2873 if (gen)
2874 rs->general_thread = ptid;
2875 else
2876 rs->continue_thread = ptid;
2877 }
2878
2879 void
2880 remote_target::set_general_thread (ptid_t ptid)
2881 {
2882 set_thread (ptid, 1);
2883 }
2884
2885 void
2886 remote_target::set_continue_thread (ptid_t ptid)
2887 {
2888 set_thread (ptid, 0);
2889 }
2890
2891 /* Change the remote current process. Which thread within the process
2892 ends up selected isn't important, as long as it is the same process
2893 as what INFERIOR_PTID points to.
2894
2895 This comes from that fact that there is no explicit notion of
2896 "selected process" in the protocol. The selected process for
2897 general operations is the process the selected general thread
2898 belongs to. */
2899
2900 void
2901 remote_target::set_general_process ()
2902 {
2903 struct remote_state *rs = get_remote_state ();
2904
2905 /* If the remote can't handle multiple processes, don't bother. */
2906 if (!remote_multi_process_p (rs))
2907 return;
2908
2909 /* We only need to change the remote current thread if it's pointing
2910 at some other process. */
2911 if (rs->general_thread.pid () != inferior_ptid.pid ())
2912 set_general_thread (inferior_ptid);
2913 }
2914
2915 \f
2916 /* Return nonzero if this is the main thread that we made up ourselves
2917 to model non-threaded targets as single-threaded. */
2918
2919 static int
2920 remote_thread_always_alive (ptid_t ptid)
2921 {
2922 if (ptid == magic_null_ptid)
2923 /* The main thread is always alive. */
2924 return 1;
2925
2926 if (ptid.pid () != 0 && ptid.lwp () == 0)
2927 /* The main thread is always alive. This can happen after a
2928 vAttach, if the remote side doesn't support
2929 multi-threading. */
2930 return 1;
2931
2932 return 0;
2933 }
2934
2935 /* Return nonzero if the thread PTID is still alive on the remote
2936 system. */
2937
2938 bool
2939 remote_target::thread_alive (ptid_t ptid)
2940 {
2941 struct remote_state *rs = get_remote_state ();
2942 char *p, *endp;
2943
2944 /* Check if this is a thread that we made up ourselves to model
2945 non-threaded targets as single-threaded. */
2946 if (remote_thread_always_alive (ptid))
2947 return 1;
2948
2949 p = rs->buf.data ();
2950 endp = p + get_remote_packet_size ();
2951
2952 *p++ = 'T';
2953 write_ptid (p, endp, ptid);
2954
2955 putpkt (rs->buf);
2956 getpkt (&rs->buf, 0);
2957 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2958 }
2959
2960 /* Return a pointer to a thread name if we know it and NULL otherwise.
2961 The thread_info object owns the memory for the name. */
2962
2963 const char *
2964 remote_target::thread_name (struct thread_info *info)
2965 {
2966 if (info->priv != NULL)
2967 {
2968 const std::string &name = get_remote_thread_info (info)->name;
2969 return !name.empty () ? name.c_str () : NULL;
2970 }
2971
2972 return NULL;
2973 }
2974
2975 /* About these extended threadlist and threadinfo packets. They are
2976 variable length packets but, the fields within them are often fixed
2977 length. They are redundant enough to send over UDP as is the
2978 remote protocol in general. There is a matching unit test module
2979 in libstub. */
2980
2981 /* WARNING: This threadref data structure comes from the remote O.S.,
2982 libstub protocol encoding, and remote.c. It is not particularly
2983 changable. */
2984
2985 /* Right now, the internal structure is int. We want it to be bigger.
2986 Plan to fix this. */
2987
2988 typedef int gdb_threadref; /* Internal GDB thread reference. */
2989
2990 /* gdb_ext_thread_info is an internal GDB data structure which is
2991 equivalent to the reply of the remote threadinfo packet. */
2992
2993 struct gdb_ext_thread_info
2994 {
2995 threadref threadid; /* External form of thread reference. */
2996 int active; /* Has state interesting to GDB?
2997 regs, stack. */
2998 char display[256]; /* Brief state display, name,
2999 blocked/suspended. */
3000 char shortname[32]; /* To be used to name threads. */
3001 char more_display[256]; /* Long info, statistics, queue depth,
3002 whatever. */
3003 };
3004
3005 /* The volume of remote transfers can be limited by submitting
3006 a mask containing bits specifying the desired information.
3007 Use a union of these values as the 'selection' parameter to
3008 get_thread_info. FIXME: Make these TAG names more thread specific. */
3009
3010 #define TAG_THREADID 1
3011 #define TAG_EXISTS 2
3012 #define TAG_DISPLAY 4
3013 #define TAG_THREADNAME 8
3014 #define TAG_MOREDISPLAY 16
3015
3016 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3017
3018 static const char *unpack_nibble (const char *buf, int *val);
3019
3020 static const char *unpack_byte (const char *buf, int *value);
3021
3022 static char *pack_int (char *buf, int value);
3023
3024 static const char *unpack_int (const char *buf, int *value);
3025
3026 static const char *unpack_string (const char *src, char *dest, int length);
3027
3028 static char *pack_threadid (char *pkt, threadref *id);
3029
3030 static const char *unpack_threadid (const char *inbuf, threadref *id);
3031
3032 void int_to_threadref (threadref *id, int value);
3033
3034 static int threadref_to_int (threadref *ref);
3035
3036 static void copy_threadref (threadref *dest, threadref *src);
3037
3038 static int threadmatch (threadref *dest, threadref *src);
3039
3040 static char *pack_threadinfo_request (char *pkt, int mode,
3041 threadref *id);
3042
3043 static char *pack_threadlist_request (char *pkt, int startflag,
3044 int threadcount,
3045 threadref *nextthread);
3046
3047 static int remote_newthread_step (threadref *ref, void *context);
3048
3049
3050 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3051 buffer we're allowed to write to. Returns
3052 BUF+CHARACTERS_WRITTEN. */
3053
3054 char *
3055 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3056 {
3057 int pid, tid;
3058 struct remote_state *rs = get_remote_state ();
3059
3060 if (remote_multi_process_p (rs))
3061 {
3062 pid = ptid.pid ();
3063 if (pid < 0)
3064 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3065 else
3066 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3067 }
3068 tid = ptid.lwp ();
3069 if (tid < 0)
3070 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3071 else
3072 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3073
3074 return buf;
3075 }
3076
3077 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3078 last parsed char. Returns null_ptid if no thread id is found, and
3079 throws an error if the thread id has an invalid format. */
3080
3081 static ptid_t
3082 read_ptid (const char *buf, const char **obuf)
3083 {
3084 const char *p = buf;
3085 const char *pp;
3086 ULONGEST pid = 0, tid = 0;
3087
3088 if (*p == 'p')
3089 {
3090 /* Multi-process ptid. */
3091 pp = unpack_varlen_hex (p + 1, &pid);
3092 if (*pp != '.')
3093 error (_("invalid remote ptid: %s"), p);
3094
3095 p = pp;
3096 pp = unpack_varlen_hex (p + 1, &tid);
3097 if (obuf)
3098 *obuf = pp;
3099 return ptid_t (pid, tid, 0);
3100 }
3101
3102 /* No multi-process. Just a tid. */
3103 pp = unpack_varlen_hex (p, &tid);
3104
3105 /* Return null_ptid when no thread id is found. */
3106 if (p == pp)
3107 {
3108 if (obuf)
3109 *obuf = pp;
3110 return null_ptid;
3111 }
3112
3113 /* Since the stub is not sending a process id, then default to
3114 what's in inferior_ptid, unless it's null at this point. If so,
3115 then since there's no way to know the pid of the reported
3116 threads, use the magic number. */
3117 if (inferior_ptid == null_ptid)
3118 pid = magic_null_ptid.pid ();
3119 else
3120 pid = inferior_ptid.pid ();
3121
3122 if (obuf)
3123 *obuf = pp;
3124 return ptid_t (pid, tid, 0);
3125 }
3126
3127 static int
3128 stubhex (int ch)
3129 {
3130 if (ch >= 'a' && ch <= 'f')
3131 return ch - 'a' + 10;
3132 if (ch >= '0' && ch <= '9')
3133 return ch - '0';
3134 if (ch >= 'A' && ch <= 'F')
3135 return ch - 'A' + 10;
3136 return -1;
3137 }
3138
3139 static int
3140 stub_unpack_int (const char *buff, int fieldlength)
3141 {
3142 int nibble;
3143 int retval = 0;
3144
3145 while (fieldlength)
3146 {
3147 nibble = stubhex (*buff++);
3148 retval |= nibble;
3149 fieldlength--;
3150 if (fieldlength)
3151 retval = retval << 4;
3152 }
3153 return retval;
3154 }
3155
3156 static const char *
3157 unpack_nibble (const char *buf, int *val)
3158 {
3159 *val = fromhex (*buf++);
3160 return buf;
3161 }
3162
3163 static const char *
3164 unpack_byte (const char *buf, int *value)
3165 {
3166 *value = stub_unpack_int (buf, 2);
3167 return buf + 2;
3168 }
3169
3170 static char *
3171 pack_int (char *buf, int value)
3172 {
3173 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3174 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3175 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3176 buf = pack_hex_byte (buf, (value & 0xff));
3177 return buf;
3178 }
3179
3180 static const char *
3181 unpack_int (const char *buf, int *value)
3182 {
3183 *value = stub_unpack_int (buf, 8);
3184 return buf + 8;
3185 }
3186
3187 #if 0 /* Currently unused, uncomment when needed. */
3188 static char *pack_string (char *pkt, char *string);
3189
3190 static char *
3191 pack_string (char *pkt, char *string)
3192 {
3193 char ch;
3194 int len;
3195
3196 len = strlen (string);
3197 if (len > 200)
3198 len = 200; /* Bigger than most GDB packets, junk??? */
3199 pkt = pack_hex_byte (pkt, len);
3200 while (len-- > 0)
3201 {
3202 ch = *string++;
3203 if ((ch == '\0') || (ch == '#'))
3204 ch = '*'; /* Protect encapsulation. */
3205 *pkt++ = ch;
3206 }
3207 return pkt;
3208 }
3209 #endif /* 0 (unused) */
3210
3211 static const char *
3212 unpack_string (const char *src, char *dest, int length)
3213 {
3214 while (length--)
3215 *dest++ = *src++;
3216 *dest = '\0';
3217 return src;
3218 }
3219
3220 static char *
3221 pack_threadid (char *pkt, threadref *id)
3222 {
3223 char *limit;
3224 unsigned char *altid;
3225
3226 altid = (unsigned char *) id;
3227 limit = pkt + BUF_THREAD_ID_SIZE;
3228 while (pkt < limit)
3229 pkt = pack_hex_byte (pkt, *altid++);
3230 return pkt;
3231 }
3232
3233
3234 static const char *
3235 unpack_threadid (const char *inbuf, threadref *id)
3236 {
3237 char *altref;
3238 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3239 int x, y;
3240
3241 altref = (char *) id;
3242
3243 while (inbuf < limit)
3244 {
3245 x = stubhex (*inbuf++);
3246 y = stubhex (*inbuf++);
3247 *altref++ = (x << 4) | y;
3248 }
3249 return inbuf;
3250 }
3251
3252 /* Externally, threadrefs are 64 bits but internally, they are still
3253 ints. This is due to a mismatch of specifications. We would like
3254 to use 64bit thread references internally. This is an adapter
3255 function. */
3256
3257 void
3258 int_to_threadref (threadref *id, int value)
3259 {
3260 unsigned char *scan;
3261
3262 scan = (unsigned char *) id;
3263 {
3264 int i = 4;
3265 while (i--)
3266 *scan++ = 0;
3267 }
3268 *scan++ = (value >> 24) & 0xff;
3269 *scan++ = (value >> 16) & 0xff;
3270 *scan++ = (value >> 8) & 0xff;
3271 *scan++ = (value & 0xff);
3272 }
3273
3274 static int
3275 threadref_to_int (threadref *ref)
3276 {
3277 int i, value = 0;
3278 unsigned char *scan;
3279
3280 scan = *ref;
3281 scan += 4;
3282 i = 4;
3283 while (i-- > 0)
3284 value = (value << 8) | ((*scan++) & 0xff);
3285 return value;
3286 }
3287
3288 static void
3289 copy_threadref (threadref *dest, threadref *src)
3290 {
3291 int i;
3292 unsigned char *csrc, *cdest;
3293
3294 csrc = (unsigned char *) src;
3295 cdest = (unsigned char *) dest;
3296 i = 8;
3297 while (i--)
3298 *cdest++ = *csrc++;
3299 }
3300
3301 static int
3302 threadmatch (threadref *dest, threadref *src)
3303 {
3304 /* Things are broken right now, so just assume we got a match. */
3305 #if 0
3306 unsigned char *srcp, *destp;
3307 int i, result;
3308 srcp = (char *) src;
3309 destp = (char *) dest;
3310
3311 result = 1;
3312 while (i-- > 0)
3313 result &= (*srcp++ == *destp++) ? 1 : 0;
3314 return result;
3315 #endif
3316 return 1;
3317 }
3318
3319 /*
3320 threadid:1, # always request threadid
3321 context_exists:2,
3322 display:4,
3323 unique_name:8,
3324 more_display:16
3325 */
3326
3327 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3328
3329 static char *
3330 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3331 {
3332 *pkt++ = 'q'; /* Info Query */
3333 *pkt++ = 'P'; /* process or thread info */
3334 pkt = pack_int (pkt, mode); /* mode */
3335 pkt = pack_threadid (pkt, id); /* threadid */
3336 *pkt = '\0'; /* terminate */
3337 return pkt;
3338 }
3339
3340 /* These values tag the fields in a thread info response packet. */
3341 /* Tagging the fields allows us to request specific fields and to
3342 add more fields as time goes by. */
3343
3344 #define TAG_THREADID 1 /* Echo the thread identifier. */
3345 #define TAG_EXISTS 2 /* Is this process defined enough to
3346 fetch registers and its stack? */
3347 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3348 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3349 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3350 the process. */
3351
3352 int
3353 remote_target::remote_unpack_thread_info_response (const char *pkt,
3354 threadref *expectedref,
3355 gdb_ext_thread_info *info)
3356 {
3357 struct remote_state *rs = get_remote_state ();
3358 int mask, length;
3359 int tag;
3360 threadref ref;
3361 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3362 int retval = 1;
3363
3364 /* info->threadid = 0; FIXME: implement zero_threadref. */
3365 info->active = 0;
3366 info->display[0] = '\0';
3367 info->shortname[0] = '\0';
3368 info->more_display[0] = '\0';
3369
3370 /* Assume the characters indicating the packet type have been
3371 stripped. */
3372 pkt = unpack_int (pkt, &mask); /* arg mask */
3373 pkt = unpack_threadid (pkt, &ref);
3374
3375 if (mask == 0)
3376 warning (_("Incomplete response to threadinfo request."));
3377 if (!threadmatch (&ref, expectedref))
3378 { /* This is an answer to a different request. */
3379 warning (_("ERROR RMT Thread info mismatch."));
3380 return 0;
3381 }
3382 copy_threadref (&info->threadid, &ref);
3383
3384 /* Loop on tagged fields , try to bail if something goes wrong. */
3385
3386 /* Packets are terminated with nulls. */
3387 while ((pkt < limit) && mask && *pkt)
3388 {
3389 pkt = unpack_int (pkt, &tag); /* tag */
3390 pkt = unpack_byte (pkt, &length); /* length */
3391 if (!(tag & mask)) /* Tags out of synch with mask. */
3392 {
3393 warning (_("ERROR RMT: threadinfo tag mismatch."));
3394 retval = 0;
3395 break;
3396 }
3397 if (tag == TAG_THREADID)
3398 {
3399 if (length != 16)
3400 {
3401 warning (_("ERROR RMT: length of threadid is not 16."));
3402 retval = 0;
3403 break;
3404 }
3405 pkt = unpack_threadid (pkt, &ref);
3406 mask = mask & ~TAG_THREADID;
3407 continue;
3408 }
3409 if (tag == TAG_EXISTS)
3410 {
3411 info->active = stub_unpack_int (pkt, length);
3412 pkt += length;
3413 mask = mask & ~(TAG_EXISTS);
3414 if (length > 8)
3415 {
3416 warning (_("ERROR RMT: 'exists' length too long."));
3417 retval = 0;
3418 break;
3419 }
3420 continue;
3421 }
3422 if (tag == TAG_THREADNAME)
3423 {
3424 pkt = unpack_string (pkt, &info->shortname[0], length);
3425 mask = mask & ~TAG_THREADNAME;
3426 continue;
3427 }
3428 if (tag == TAG_DISPLAY)
3429 {
3430 pkt = unpack_string (pkt, &info->display[0], length);
3431 mask = mask & ~TAG_DISPLAY;
3432 continue;
3433 }
3434 if (tag == TAG_MOREDISPLAY)
3435 {
3436 pkt = unpack_string (pkt, &info->more_display[0], length);
3437 mask = mask & ~TAG_MOREDISPLAY;
3438 continue;
3439 }
3440 warning (_("ERROR RMT: unknown thread info tag."));
3441 break; /* Not a tag we know about. */
3442 }
3443 return retval;
3444 }
3445
3446 int
3447 remote_target::remote_get_threadinfo (threadref *threadid,
3448 int fieldset,
3449 gdb_ext_thread_info *info)
3450 {
3451 struct remote_state *rs = get_remote_state ();
3452 int result;
3453
3454 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3455 putpkt (rs->buf);
3456 getpkt (&rs->buf, 0);
3457
3458 if (rs->buf[0] == '\0')
3459 return 0;
3460
3461 result = remote_unpack_thread_info_response (&rs->buf[2],
3462 threadid, info);
3463 return result;
3464 }
3465
3466 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3467
3468 static char *
3469 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3470 threadref *nextthread)
3471 {
3472 *pkt++ = 'q'; /* info query packet */
3473 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3474 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3475 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3476 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3477 *pkt = '\0';
3478 return pkt;
3479 }
3480
3481 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3482
3483 int
3484 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3485 threadref *original_echo,
3486 threadref *resultlist,
3487 int *doneflag)
3488 {
3489 struct remote_state *rs = get_remote_state ();
3490 int count, resultcount, done;
3491
3492 resultcount = 0;
3493 /* Assume the 'q' and 'M chars have been stripped. */
3494 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3495 /* done parse past here */
3496 pkt = unpack_byte (pkt, &count); /* count field */
3497 pkt = unpack_nibble (pkt, &done);
3498 /* The first threadid is the argument threadid. */
3499 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3500 while ((count-- > 0) && (pkt < limit))
3501 {
3502 pkt = unpack_threadid (pkt, resultlist++);
3503 if (resultcount++ >= result_limit)
3504 break;
3505 }
3506 if (doneflag)
3507 *doneflag = done;
3508 return resultcount;
3509 }
3510
3511 /* Fetch the next batch of threads from the remote. Returns -1 if the
3512 qL packet is not supported, 0 on error and 1 on success. */
3513
3514 int
3515 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3516 int result_limit, int *done, int *result_count,
3517 threadref *threadlist)
3518 {
3519 struct remote_state *rs = get_remote_state ();
3520 int result = 1;
3521
3522 /* Truncate result limit to be smaller than the packet size. */
3523 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3524 >= get_remote_packet_size ())
3525 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3526
3527 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3528 nextthread);
3529 putpkt (rs->buf);
3530 getpkt (&rs->buf, 0);
3531 if (rs->buf[0] == '\0')
3532 {
3533 /* Packet not supported. */
3534 return -1;
3535 }
3536
3537 *result_count =
3538 parse_threadlist_response (&rs->buf[2], result_limit,
3539 &rs->echo_nextthread, threadlist, done);
3540
3541 if (!threadmatch (&rs->echo_nextthread, nextthread))
3542 {
3543 /* FIXME: This is a good reason to drop the packet. */
3544 /* Possibly, there is a duplicate response. */
3545 /* Possibilities :
3546 retransmit immediatly - race conditions
3547 retransmit after timeout - yes
3548 exit
3549 wait for packet, then exit
3550 */
3551 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3552 return 0; /* I choose simply exiting. */
3553 }
3554 if (*result_count <= 0)
3555 {
3556 if (*done != 1)
3557 {
3558 warning (_("RMT ERROR : failed to get remote thread list."));
3559 result = 0;
3560 }
3561 return result; /* break; */
3562 }
3563 if (*result_count > result_limit)
3564 {
3565 *result_count = 0;
3566 warning (_("RMT ERROR: threadlist response longer than requested."));
3567 return 0;
3568 }
3569 return result;
3570 }
3571
3572 /* Fetch the list of remote threads, with the qL packet, and call
3573 STEPFUNCTION for each thread found. Stops iterating and returns 1
3574 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3575 STEPFUNCTION returns false. If the packet is not supported,
3576 returns -1. */
3577
3578 int
3579 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3580 void *context, int looplimit)
3581 {
3582 struct remote_state *rs = get_remote_state ();
3583 int done, i, result_count;
3584 int startflag = 1;
3585 int result = 1;
3586 int loopcount = 0;
3587
3588 done = 0;
3589 while (!done)
3590 {
3591 if (loopcount++ > looplimit)
3592 {
3593 result = 0;
3594 warning (_("Remote fetch threadlist -infinite loop-."));
3595 break;
3596 }
3597 result = remote_get_threadlist (startflag, &rs->nextthread,
3598 MAXTHREADLISTRESULTS,
3599 &done, &result_count,
3600 rs->resultthreadlist);
3601 if (result <= 0)
3602 break;
3603 /* Clear for later iterations. */
3604 startflag = 0;
3605 /* Setup to resume next batch of thread references, set nextthread. */
3606 if (result_count >= 1)
3607 copy_threadref (&rs->nextthread,
3608 &rs->resultthreadlist[result_count - 1]);
3609 i = 0;
3610 while (result_count--)
3611 {
3612 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3613 {
3614 result = 0;
3615 break;
3616 }
3617 }
3618 }
3619 return result;
3620 }
3621
3622 /* A thread found on the remote target. */
3623
3624 struct thread_item
3625 {
3626 explicit thread_item (ptid_t ptid_)
3627 : ptid (ptid_)
3628 {}
3629
3630 thread_item (thread_item &&other) = default;
3631 thread_item &operator= (thread_item &&other) = default;
3632
3633 DISABLE_COPY_AND_ASSIGN (thread_item);
3634
3635 /* The thread's PTID. */
3636 ptid_t ptid;
3637
3638 /* The thread's extra info. */
3639 std::string extra;
3640
3641 /* The thread's name. */
3642 std::string name;
3643
3644 /* The core the thread was running on. -1 if not known. */
3645 int core = -1;
3646
3647 /* The thread handle associated with the thread. */
3648 gdb::byte_vector thread_handle;
3649 };
3650
3651 /* Context passed around to the various methods listing remote
3652 threads. As new threads are found, they're added to the ITEMS
3653 vector. */
3654
3655 struct threads_listing_context
3656 {
3657 /* Return true if this object contains an entry for a thread with ptid
3658 PTID. */
3659
3660 bool contains_thread (ptid_t ptid) const
3661 {
3662 auto match_ptid = [&] (const thread_item &item)
3663 {
3664 return item.ptid == ptid;
3665 };
3666
3667 auto it = std::find_if (this->items.begin (),
3668 this->items.end (),
3669 match_ptid);
3670
3671 return it != this->items.end ();
3672 }
3673
3674 /* Remove the thread with ptid PTID. */
3675
3676 void remove_thread (ptid_t ptid)
3677 {
3678 auto match_ptid = [&] (const thread_item &item)
3679 {
3680 return item.ptid == ptid;
3681 };
3682
3683 auto it = std::remove_if (this->items.begin (),
3684 this->items.end (),
3685 match_ptid);
3686
3687 if (it != this->items.end ())
3688 this->items.erase (it);
3689 }
3690
3691 /* The threads found on the remote target. */
3692 std::vector<thread_item> items;
3693 };
3694
3695 static int
3696 remote_newthread_step (threadref *ref, void *data)
3697 {
3698 struct threads_listing_context *context
3699 = (struct threads_listing_context *) data;
3700 int pid = inferior_ptid.pid ();
3701 int lwp = threadref_to_int (ref);
3702 ptid_t ptid (pid, lwp);
3703
3704 context->items.emplace_back (ptid);
3705
3706 return 1; /* continue iterator */
3707 }
3708
3709 #define CRAZY_MAX_THREADS 1000
3710
3711 ptid_t
3712 remote_target::remote_current_thread (ptid_t oldpid)
3713 {
3714 struct remote_state *rs = get_remote_state ();
3715
3716 putpkt ("qC");
3717 getpkt (&rs->buf, 0);
3718 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3719 {
3720 const char *obuf;
3721 ptid_t result;
3722
3723 result = read_ptid (&rs->buf[2], &obuf);
3724 if (*obuf != '\0')
3725 remote_debug_printf ("warning: garbage in qC reply");
3726
3727 return result;
3728 }
3729 else
3730 return oldpid;
3731 }
3732
3733 /* List remote threads using the deprecated qL packet. */
3734
3735 int
3736 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3737 {
3738 if (remote_threadlist_iterator (remote_newthread_step, context,
3739 CRAZY_MAX_THREADS) >= 0)
3740 return 1;
3741
3742 return 0;
3743 }
3744
3745 #if defined(HAVE_LIBEXPAT)
3746
3747 static void
3748 start_thread (struct gdb_xml_parser *parser,
3749 const struct gdb_xml_element *element,
3750 void *user_data,
3751 std::vector<gdb_xml_value> &attributes)
3752 {
3753 struct threads_listing_context *data
3754 = (struct threads_listing_context *) user_data;
3755 struct gdb_xml_value *attr;
3756
3757 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3758 ptid_t ptid = read_ptid (id, NULL);
3759
3760 data->items.emplace_back (ptid);
3761 thread_item &item = data->items.back ();
3762
3763 attr = xml_find_attribute (attributes, "core");
3764 if (attr != NULL)
3765 item.core = *(ULONGEST *) attr->value.get ();
3766
3767 attr = xml_find_attribute (attributes, "name");
3768 if (attr != NULL)
3769 item.name = (const char *) attr->value.get ();
3770
3771 attr = xml_find_attribute (attributes, "handle");
3772 if (attr != NULL)
3773 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3774 }
3775
3776 static void
3777 end_thread (struct gdb_xml_parser *parser,
3778 const struct gdb_xml_element *element,
3779 void *user_data, const char *body_text)
3780 {
3781 struct threads_listing_context *data
3782 = (struct threads_listing_context *) user_data;
3783
3784 if (body_text != NULL && *body_text != '\0')
3785 data->items.back ().extra = body_text;
3786 }
3787
3788 const struct gdb_xml_attribute thread_attributes[] = {
3789 { "id", GDB_XML_AF_NONE, NULL, NULL },
3790 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3791 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3792 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3793 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3794 };
3795
3796 const struct gdb_xml_element thread_children[] = {
3797 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3798 };
3799
3800 const struct gdb_xml_element threads_children[] = {
3801 { "thread", thread_attributes, thread_children,
3802 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3803 start_thread, end_thread },
3804 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3805 };
3806
3807 const struct gdb_xml_element threads_elements[] = {
3808 { "threads", NULL, threads_children,
3809 GDB_XML_EF_NONE, NULL, NULL },
3810 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3811 };
3812
3813 #endif
3814
3815 /* List remote threads using qXfer:threads:read. */
3816
3817 int
3818 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3819 {
3820 #if defined(HAVE_LIBEXPAT)
3821 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3822 {
3823 gdb::optional<gdb::char_vector> xml
3824 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3825
3826 if (xml && (*xml)[0] != '\0')
3827 {
3828 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3829 threads_elements, xml->data (), context);
3830 }
3831
3832 return 1;
3833 }
3834 #endif
3835
3836 return 0;
3837 }
3838
3839 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3840
3841 int
3842 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3843 {
3844 struct remote_state *rs = get_remote_state ();
3845
3846 if (rs->use_threadinfo_query)
3847 {
3848 const char *bufp;
3849
3850 putpkt ("qfThreadInfo");
3851 getpkt (&rs->buf, 0);
3852 bufp = rs->buf.data ();
3853 if (bufp[0] != '\0') /* q packet recognized */
3854 {
3855 while (*bufp++ == 'm') /* reply contains one or more TID */
3856 {
3857 do
3858 {
3859 ptid_t ptid = read_ptid (bufp, &bufp);
3860 context->items.emplace_back (ptid);
3861 }
3862 while (*bufp++ == ','); /* comma-separated list */
3863 putpkt ("qsThreadInfo");
3864 getpkt (&rs->buf, 0);
3865 bufp = rs->buf.data ();
3866 }
3867 return 1;
3868 }
3869 else
3870 {
3871 /* Packet not recognized. */
3872 rs->use_threadinfo_query = 0;
3873 }
3874 }
3875
3876 return 0;
3877 }
3878
3879 /* Return true if INF only has one non-exited thread. */
3880
3881 static bool
3882 has_single_non_exited_thread (inferior *inf)
3883 {
3884 int count = 0;
3885 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3886 if (++count > 1)
3887 break;
3888 return count == 1;
3889 }
3890
3891 /* Implement the to_update_thread_list function for the remote
3892 targets. */
3893
3894 void
3895 remote_target::update_thread_list ()
3896 {
3897 struct threads_listing_context context;
3898 int got_list = 0;
3899
3900 /* We have a few different mechanisms to fetch the thread list. Try
3901 them all, starting with the most preferred one first, falling
3902 back to older methods. */
3903 if (remote_get_threads_with_qxfer (&context)
3904 || remote_get_threads_with_qthreadinfo (&context)
3905 || remote_get_threads_with_ql (&context))
3906 {
3907 got_list = 1;
3908
3909 if (context.items.empty ()
3910 && remote_thread_always_alive (inferior_ptid))
3911 {
3912 /* Some targets don't really support threads, but still
3913 reply an (empty) thread list in response to the thread
3914 listing packets, instead of replying "packet not
3915 supported". Exit early so we don't delete the main
3916 thread. */
3917 return;
3918 }
3919
3920 /* CONTEXT now holds the current thread list on the remote
3921 target end. Delete GDB-side threads no longer found on the
3922 target. */
3923 for (thread_info *tp : all_threads_safe ())
3924 {
3925 if (tp->inf->process_target () != this)
3926 continue;
3927
3928 if (!context.contains_thread (tp->ptid))
3929 {
3930 /* Do not remove the thread if it is the last thread in
3931 the inferior. This situation happens when we have a
3932 pending exit process status to process. Otherwise we
3933 may end up with a seemingly live inferior (i.e. pid
3934 != 0) that has no threads. */
3935 if (has_single_non_exited_thread (tp->inf))
3936 continue;
3937
3938 /* Not found. */
3939 delete_thread (tp);
3940 }
3941 }
3942
3943 /* Remove any unreported fork child threads from CONTEXT so
3944 that we don't interfere with follow fork, which is where
3945 creation of such threads is handled. */
3946 remove_new_fork_children (&context);
3947
3948 /* And now add threads we don't know about yet to our list. */
3949 for (thread_item &item : context.items)
3950 {
3951 if (item.ptid != null_ptid)
3952 {
3953 /* In non-stop mode, we assume new found threads are
3954 executing until proven otherwise with a stop reply.
3955 In all-stop, we can only get here if all threads are
3956 stopped. */
3957 int executing = target_is_non_stop_p () ? 1 : 0;
3958
3959 remote_notice_new_inferior (item.ptid, executing);
3960
3961 thread_info *tp = find_thread_ptid (this, item.ptid);
3962 remote_thread_info *info = get_remote_thread_info (tp);
3963 info->core = item.core;
3964 info->extra = std::move (item.extra);
3965 info->name = std::move (item.name);
3966 info->thread_handle = std::move (item.thread_handle);
3967 }
3968 }
3969 }
3970
3971 if (!got_list)
3972 {
3973 /* If no thread listing method is supported, then query whether
3974 each known thread is alive, one by one, with the T packet.
3975 If the target doesn't support threads at all, then this is a
3976 no-op. See remote_thread_alive. */
3977 prune_threads ();
3978 }
3979 }
3980
3981 /*
3982 * Collect a descriptive string about the given thread.
3983 * The target may say anything it wants to about the thread
3984 * (typically info about its blocked / runnable state, name, etc.).
3985 * This string will appear in the info threads display.
3986 *
3987 * Optional: targets are not required to implement this function.
3988 */
3989
3990 const char *
3991 remote_target::extra_thread_info (thread_info *tp)
3992 {
3993 struct remote_state *rs = get_remote_state ();
3994 int set;
3995 threadref id;
3996 struct gdb_ext_thread_info threadinfo;
3997
3998 if (rs->remote_desc == 0) /* paranoia */
3999 internal_error (__FILE__, __LINE__,
4000 _("remote_threads_extra_info"));
4001
4002 if (tp->ptid == magic_null_ptid
4003 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4004 /* This is the main thread which was added by GDB. The remote
4005 server doesn't know about it. */
4006 return NULL;
4007
4008 std::string &extra = get_remote_thread_info (tp)->extra;
4009
4010 /* If already have cached info, use it. */
4011 if (!extra.empty ())
4012 return extra.c_str ();
4013
4014 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4015 {
4016 /* If we're using qXfer:threads:read, then the extra info is
4017 included in the XML. So if we didn't have anything cached,
4018 it's because there's really no extra info. */
4019 return NULL;
4020 }
4021
4022 if (rs->use_threadextra_query)
4023 {
4024 char *b = rs->buf.data ();
4025 char *endb = b + get_remote_packet_size ();
4026
4027 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4028 b += strlen (b);
4029 write_ptid (b, endb, tp->ptid);
4030
4031 putpkt (rs->buf);
4032 getpkt (&rs->buf, 0);
4033 if (rs->buf[0] != 0)
4034 {
4035 extra.resize (strlen (rs->buf.data ()) / 2);
4036 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4037 return extra.c_str ();
4038 }
4039 }
4040
4041 /* If the above query fails, fall back to the old method. */
4042 rs->use_threadextra_query = 0;
4043 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4044 | TAG_MOREDISPLAY | TAG_DISPLAY;
4045 int_to_threadref (&id, tp->ptid.lwp ());
4046 if (remote_get_threadinfo (&id, set, &threadinfo))
4047 if (threadinfo.active)
4048 {
4049 if (*threadinfo.shortname)
4050 string_appendf (extra, " Name: %s", threadinfo.shortname);
4051 if (*threadinfo.display)
4052 {
4053 if (!extra.empty ())
4054 extra += ',';
4055 string_appendf (extra, " State: %s", threadinfo.display);
4056 }
4057 if (*threadinfo.more_display)
4058 {
4059 if (!extra.empty ())
4060 extra += ',';
4061 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4062 }
4063 return extra.c_str ();
4064 }
4065 return NULL;
4066 }
4067 \f
4068
4069 bool
4070 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4071 struct static_tracepoint_marker *marker)
4072 {
4073 struct remote_state *rs = get_remote_state ();
4074 char *p = rs->buf.data ();
4075
4076 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4077 p += strlen (p);
4078 p += hexnumstr (p, addr);
4079 putpkt (rs->buf);
4080 getpkt (&rs->buf, 0);
4081 p = rs->buf.data ();
4082
4083 if (*p == 'E')
4084 error (_("Remote failure reply: %s"), p);
4085
4086 if (*p++ == 'm')
4087 {
4088 parse_static_tracepoint_marker_definition (p, NULL, marker);
4089 return true;
4090 }
4091
4092 return false;
4093 }
4094
4095 std::vector<static_tracepoint_marker>
4096 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4097 {
4098 struct remote_state *rs = get_remote_state ();
4099 std::vector<static_tracepoint_marker> markers;
4100 const char *p;
4101 static_tracepoint_marker marker;
4102
4103 /* Ask for a first packet of static tracepoint marker
4104 definition. */
4105 putpkt ("qTfSTM");
4106 getpkt (&rs->buf, 0);
4107 p = rs->buf.data ();
4108 if (*p == 'E')
4109 error (_("Remote failure reply: %s"), p);
4110
4111 while (*p++ == 'm')
4112 {
4113 do
4114 {
4115 parse_static_tracepoint_marker_definition (p, &p, &marker);
4116
4117 if (strid == NULL || marker.str_id == strid)
4118 markers.push_back (std::move (marker));
4119 }
4120 while (*p++ == ','); /* comma-separated list */
4121 /* Ask for another packet of static tracepoint definition. */
4122 putpkt ("qTsSTM");
4123 getpkt (&rs->buf, 0);
4124 p = rs->buf.data ();
4125 }
4126
4127 return markers;
4128 }
4129
4130 \f
4131 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4132
4133 ptid_t
4134 remote_target::get_ada_task_ptid (long lwp, long thread)
4135 {
4136 return ptid_t (inferior_ptid.pid (), lwp, 0);
4137 }
4138 \f
4139
4140 /* Restart the remote side; this is an extended protocol operation. */
4141
4142 void
4143 remote_target::extended_remote_restart ()
4144 {
4145 struct remote_state *rs = get_remote_state ();
4146
4147 /* Send the restart command; for reasons I don't understand the
4148 remote side really expects a number after the "R". */
4149 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4150 putpkt (rs->buf);
4151
4152 remote_fileio_reset ();
4153 }
4154 \f
4155 /* Clean up connection to a remote debugger. */
4156
4157 void
4158 remote_target::close ()
4159 {
4160 /* Make sure we leave stdin registered in the event loop. */
4161 terminal_ours ();
4162
4163 trace_reset_local_state ();
4164
4165 delete this;
4166 }
4167
4168 remote_target::~remote_target ()
4169 {
4170 struct remote_state *rs = get_remote_state ();
4171
4172 /* Check for NULL because we may get here with a partially
4173 constructed target/connection. */
4174 if (rs->remote_desc == nullptr)
4175 return;
4176
4177 serial_close (rs->remote_desc);
4178
4179 /* We are destroying the remote target, so we should discard
4180 everything of this target. */
4181 discard_pending_stop_replies_in_queue ();
4182
4183 if (rs->remote_async_inferior_event_token)
4184 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4185
4186 delete rs->notif_state;
4187 }
4188
4189 /* Query the remote side for the text, data and bss offsets. */
4190
4191 void
4192 remote_target::get_offsets ()
4193 {
4194 struct remote_state *rs = get_remote_state ();
4195 char *buf;
4196 char *ptr;
4197 int lose, num_segments = 0, do_sections, do_segments;
4198 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4199
4200 if (current_program_space->symfile_object_file == NULL)
4201 return;
4202
4203 putpkt ("qOffsets");
4204 getpkt (&rs->buf, 0);
4205 buf = rs->buf.data ();
4206
4207 if (buf[0] == '\000')
4208 return; /* Return silently. Stub doesn't support
4209 this command. */
4210 if (buf[0] == 'E')
4211 {
4212 warning (_("Remote failure reply: %s"), buf);
4213 return;
4214 }
4215
4216 /* Pick up each field in turn. This used to be done with scanf, but
4217 scanf will make trouble if CORE_ADDR size doesn't match
4218 conversion directives correctly. The following code will work
4219 with any size of CORE_ADDR. */
4220 text_addr = data_addr = bss_addr = 0;
4221 ptr = buf;
4222 lose = 0;
4223
4224 if (startswith (ptr, "Text="))
4225 {
4226 ptr += 5;
4227 /* Don't use strtol, could lose on big values. */
4228 while (*ptr && *ptr != ';')
4229 text_addr = (text_addr << 4) + fromhex (*ptr++);
4230
4231 if (startswith (ptr, ";Data="))
4232 {
4233 ptr += 6;
4234 while (*ptr && *ptr != ';')
4235 data_addr = (data_addr << 4) + fromhex (*ptr++);
4236 }
4237 else
4238 lose = 1;
4239
4240 if (!lose && startswith (ptr, ";Bss="))
4241 {
4242 ptr += 5;
4243 while (*ptr && *ptr != ';')
4244 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4245
4246 if (bss_addr != data_addr)
4247 warning (_("Target reported unsupported offsets: %s"), buf);
4248 }
4249 else
4250 lose = 1;
4251 }
4252 else if (startswith (ptr, "TextSeg="))
4253 {
4254 ptr += 8;
4255 /* Don't use strtol, could lose on big values. */
4256 while (*ptr && *ptr != ';')
4257 text_addr = (text_addr << 4) + fromhex (*ptr++);
4258 num_segments = 1;
4259
4260 if (startswith (ptr, ";DataSeg="))
4261 {
4262 ptr += 9;
4263 while (*ptr && *ptr != ';')
4264 data_addr = (data_addr << 4) + fromhex (*ptr++);
4265 num_segments++;
4266 }
4267 }
4268 else
4269 lose = 1;
4270
4271 if (lose)
4272 error (_("Malformed response to offset query, %s"), buf);
4273 else if (*ptr != '\0')
4274 warning (_("Target reported unsupported offsets: %s"), buf);
4275
4276 objfile *objf = current_program_space->symfile_object_file;
4277 section_offsets offs = objf->section_offsets;
4278
4279 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
4280 do_segments = (data != NULL);
4281 do_sections = num_segments == 0;
4282
4283 if (num_segments > 0)
4284 {
4285 segments[0] = text_addr;
4286 segments[1] = data_addr;
4287 }
4288 /* If we have two segments, we can still try to relocate everything
4289 by assuming that the .text and .data offsets apply to the whole
4290 text and data segments. Convert the offsets given in the packet
4291 to base addresses for symfile_map_offsets_to_segments. */
4292 else if (data != nullptr && data->segments.size () == 2)
4293 {
4294 segments[0] = data->segments[0].base + text_addr;
4295 segments[1] = data->segments[1].base + data_addr;
4296 num_segments = 2;
4297 }
4298 /* If the object file has only one segment, assume that it is text
4299 rather than data; main programs with no writable data are rare,
4300 but programs with no code are useless. Of course the code might
4301 have ended up in the data segment... to detect that we would need
4302 the permissions here. */
4303 else if (data && data->segments.size () == 1)
4304 {
4305 segments[0] = data->segments[0].base + text_addr;
4306 num_segments = 1;
4307 }
4308 /* There's no way to relocate by segment. */
4309 else
4310 do_segments = 0;
4311
4312 if (do_segments)
4313 {
4314 int ret = symfile_map_offsets_to_segments (objf->obfd,
4315 data.get (), offs,
4316 num_segments, segments);
4317
4318 if (ret == 0 && !do_sections)
4319 error (_("Can not handle qOffsets TextSeg "
4320 "response with this symbol file"));
4321
4322 if (ret > 0)
4323 do_sections = 0;
4324 }
4325
4326 if (do_sections)
4327 {
4328 offs[SECT_OFF_TEXT (objf)] = text_addr;
4329
4330 /* This is a temporary kludge to force data and bss to use the
4331 same offsets because that's what nlmconv does now. The real
4332 solution requires changes to the stub and remote.c that I
4333 don't have time to do right now. */
4334
4335 offs[SECT_OFF_DATA (objf)] = data_addr;
4336 offs[SECT_OFF_BSS (objf)] = data_addr;
4337 }
4338
4339 objfile_relocate (objf, offs);
4340 }
4341
4342 /* Send interrupt_sequence to remote target. */
4343
4344 void
4345 remote_target::send_interrupt_sequence ()
4346 {
4347 struct remote_state *rs = get_remote_state ();
4348
4349 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4350 remote_serial_write ("\x03", 1);
4351 else if (interrupt_sequence_mode == interrupt_sequence_break)
4352 serial_send_break (rs->remote_desc);
4353 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4354 {
4355 serial_send_break (rs->remote_desc);
4356 remote_serial_write ("g", 1);
4357 }
4358 else
4359 internal_error (__FILE__, __LINE__,
4360 _("Invalid value for interrupt_sequence_mode: %s."),
4361 interrupt_sequence_mode);
4362 }
4363
4364
4365 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4366 and extract the PTID. Returns NULL_PTID if not found. */
4367
4368 static ptid_t
4369 stop_reply_extract_thread (const char *stop_reply)
4370 {
4371 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4372 {
4373 const char *p;
4374
4375 /* Txx r:val ; r:val (...) */
4376 p = &stop_reply[3];
4377
4378 /* Look for "register" named "thread". */
4379 while (*p != '\0')
4380 {
4381 const char *p1;
4382
4383 p1 = strchr (p, ':');
4384 if (p1 == NULL)
4385 return null_ptid;
4386
4387 if (strncmp (p, "thread", p1 - p) == 0)
4388 return read_ptid (++p1, &p);
4389
4390 p1 = strchr (p, ';');
4391 if (p1 == NULL)
4392 return null_ptid;
4393 p1++;
4394
4395 p = p1;
4396 }
4397 }
4398
4399 return null_ptid;
4400 }
4401
4402 /* Determine the remote side's current thread. If we have a stop
4403 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4404 "thread" register we can extract the current thread from. If not,
4405 ask the remote which is the current thread with qC. The former
4406 method avoids a roundtrip. */
4407
4408 ptid_t
4409 remote_target::get_current_thread (const char *wait_status)
4410 {
4411 ptid_t ptid = null_ptid;
4412
4413 /* Note we don't use remote_parse_stop_reply as that makes use of
4414 the target architecture, which we haven't yet fully determined at
4415 this point. */
4416 if (wait_status != NULL)
4417 ptid = stop_reply_extract_thread (wait_status);
4418 if (ptid == null_ptid)
4419 ptid = remote_current_thread (inferior_ptid);
4420
4421 return ptid;
4422 }
4423
4424 /* Query the remote target for which is the current thread/process,
4425 add it to our tables, and update INFERIOR_PTID. The caller is
4426 responsible for setting the state such that the remote end is ready
4427 to return the current thread.
4428
4429 This function is called after handling the '?' or 'vRun' packets,
4430 whose response is a stop reply from which we can also try
4431 extracting the thread. If the target doesn't support the explicit
4432 qC query, we infer the current thread from that stop reply, passed
4433 in in WAIT_STATUS, which may be NULL.
4434
4435 The function returns pointer to the main thread of the inferior. */
4436
4437 thread_info *
4438 remote_target::add_current_inferior_and_thread (const char *wait_status)
4439 {
4440 struct remote_state *rs = get_remote_state ();
4441 bool fake_pid_p = false;
4442
4443 switch_to_no_thread ();
4444
4445 /* Now, if we have thread information, update the current thread's
4446 ptid. */
4447 ptid_t curr_ptid = get_current_thread (wait_status);
4448
4449 if (curr_ptid != null_ptid)
4450 {
4451 if (!remote_multi_process_p (rs))
4452 fake_pid_p = true;
4453 }
4454 else
4455 {
4456 /* Without this, some commands which require an active target
4457 (such as kill) won't work. This variable serves (at least)
4458 double duty as both the pid of the target process (if it has
4459 such), and as a flag indicating that a target is active. */
4460 curr_ptid = magic_null_ptid;
4461 fake_pid_p = true;
4462 }
4463
4464 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4465
4466 /* Add the main thread and switch to it. Don't try reading
4467 registers yet, since we haven't fetched the target description
4468 yet. */
4469 thread_info *tp = add_thread_silent (this, curr_ptid);
4470 switch_to_thread_no_regs (tp);
4471
4472 return tp;
4473 }
4474
4475 /* Print info about a thread that was found already stopped on
4476 connection. */
4477
4478 static void
4479 print_one_stopped_thread (struct thread_info *thread)
4480 {
4481 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4482
4483 switch_to_thread (thread);
4484 thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
4485 set_current_sal_from_frame (get_current_frame ());
4486
4487 thread->suspend.waitstatus_pending_p = 0;
4488
4489 if (ws->kind == TARGET_WAITKIND_STOPPED)
4490 {
4491 enum gdb_signal sig = ws->value.sig;
4492
4493 if (signal_print_state (sig))
4494 gdb::observers::signal_received.notify (sig);
4495 }
4496 gdb::observers::normal_stop.notify (NULL, 1);
4497 }
4498
4499 /* Process all initial stop replies the remote side sent in response
4500 to the ? packet. These indicate threads that were already stopped
4501 on initial connection. We mark these threads as stopped and print
4502 their current frame before giving the user the prompt. */
4503
4504 void
4505 remote_target::process_initial_stop_replies (int from_tty)
4506 {
4507 int pending_stop_replies = stop_reply_queue_length ();
4508 struct thread_info *selected = NULL;
4509 struct thread_info *lowest_stopped = NULL;
4510 struct thread_info *first = NULL;
4511
4512 /* Consume the initial pending events. */
4513 while (pending_stop_replies-- > 0)
4514 {
4515 ptid_t waiton_ptid = minus_one_ptid;
4516 ptid_t event_ptid;
4517 struct target_waitstatus ws;
4518 int ignore_event = 0;
4519
4520 memset (&ws, 0, sizeof (ws));
4521 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4522 if (remote_debug)
4523 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4524
4525 switch (ws.kind)
4526 {
4527 case TARGET_WAITKIND_IGNORE:
4528 case TARGET_WAITKIND_NO_RESUMED:
4529 case TARGET_WAITKIND_SIGNALLED:
4530 case TARGET_WAITKIND_EXITED:
4531 /* We shouldn't see these, but if we do, just ignore. */
4532 remote_debug_printf ("event ignored");
4533 ignore_event = 1;
4534 break;
4535
4536 case TARGET_WAITKIND_EXECD:
4537 xfree (ws.value.execd_pathname);
4538 break;
4539 default:
4540 break;
4541 }
4542
4543 if (ignore_event)
4544 continue;
4545
4546 thread_info *evthread = find_thread_ptid (this, event_ptid);
4547
4548 if (ws.kind == TARGET_WAITKIND_STOPPED)
4549 {
4550 enum gdb_signal sig = ws.value.sig;
4551
4552 /* Stubs traditionally report SIGTRAP as initial signal,
4553 instead of signal 0. Suppress it. */
4554 if (sig == GDB_SIGNAL_TRAP)
4555 sig = GDB_SIGNAL_0;
4556 evthread->suspend.stop_signal = sig;
4557 ws.value.sig = sig;
4558 }
4559
4560 evthread->suspend.waitstatus = ws;
4561
4562 if (ws.kind != TARGET_WAITKIND_STOPPED
4563 || ws.value.sig != GDB_SIGNAL_0)
4564 evthread->suspend.waitstatus_pending_p = 1;
4565
4566 set_executing (this, event_ptid, false);
4567 set_running (this, event_ptid, false);
4568 get_remote_thread_info (evthread)->set_not_resumed ();
4569 }
4570
4571 /* "Notice" the new inferiors before anything related to
4572 registers/memory. */
4573 for (inferior *inf : all_non_exited_inferiors (this))
4574 {
4575 inf->needs_setup = 1;
4576
4577 if (non_stop)
4578 {
4579 thread_info *thread = any_live_thread_of_inferior (inf);
4580 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4581 from_tty);
4582 }
4583 }
4584
4585 /* If all-stop on top of non-stop, pause all threads. Note this
4586 records the threads' stop pc, so must be done after "noticing"
4587 the inferiors. */
4588 if (!non_stop)
4589 {
4590 stop_all_threads ();
4591
4592 /* If all threads of an inferior were already stopped, we
4593 haven't setup the inferior yet. */
4594 for (inferior *inf : all_non_exited_inferiors (this))
4595 {
4596 if (inf->needs_setup)
4597 {
4598 thread_info *thread = any_live_thread_of_inferior (inf);
4599 switch_to_thread_no_regs (thread);
4600 setup_inferior (0);
4601 }
4602 }
4603 }
4604
4605 /* Now go over all threads that are stopped, and print their current
4606 frame. If all-stop, then if there's a signalled thread, pick
4607 that as current. */
4608 for (thread_info *thread : all_non_exited_threads (this))
4609 {
4610 if (first == NULL)
4611 first = thread;
4612
4613 if (!non_stop)
4614 thread->set_running (false);
4615 else if (thread->state != THREAD_STOPPED)
4616 continue;
4617
4618 if (selected == NULL
4619 && thread->suspend.waitstatus_pending_p)
4620 selected = thread;
4621
4622 if (lowest_stopped == NULL
4623 || thread->inf->num < lowest_stopped->inf->num
4624 || thread->per_inf_num < lowest_stopped->per_inf_num)
4625 lowest_stopped = thread;
4626
4627 if (non_stop)
4628 print_one_stopped_thread (thread);
4629 }
4630
4631 /* In all-stop, we only print the status of one thread, and leave
4632 others with their status pending. */
4633 if (!non_stop)
4634 {
4635 thread_info *thread = selected;
4636 if (thread == NULL)
4637 thread = lowest_stopped;
4638 if (thread == NULL)
4639 thread = first;
4640
4641 print_one_stopped_thread (thread);
4642 }
4643
4644 /* For "info program". */
4645 thread_info *thread = inferior_thread ();
4646 if (thread->state == THREAD_STOPPED)
4647 set_last_target_status (this, inferior_ptid, thread->suspend.waitstatus);
4648 }
4649
4650 /* Start the remote connection and sync state. */
4651
4652 void
4653 remote_target::start_remote (int from_tty, int extended_p)
4654 {
4655 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4656
4657 struct remote_state *rs = get_remote_state ();
4658 struct packet_config *noack_config;
4659
4660 /* Signal other parts that we're going through the initial setup,
4661 and so things may not be stable yet. E.g., we don't try to
4662 install tracepoints until we've relocated symbols. Also, a
4663 Ctrl-C before we're connected and synced up can't interrupt the
4664 target. Instead, it offers to drop the (potentially wedged)
4665 connection. */
4666 rs->starting_up = 1;
4667
4668 QUIT;
4669
4670 if (interrupt_on_connect)
4671 send_interrupt_sequence ();
4672
4673 /* Ack any packet which the remote side has already sent. */
4674 remote_serial_write ("+", 1);
4675
4676 /* The first packet we send to the target is the optional "supported
4677 packets" request. If the target can answer this, it will tell us
4678 which later probes to skip. */
4679 remote_query_supported ();
4680
4681 /* If the stub wants to get a QAllow, compose one and send it. */
4682 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4683 set_permissions ();
4684
4685 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4686 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4687 as a reply to known packet. For packet "vFile:setfs:" it is an
4688 invalid reply and GDB would return error in
4689 remote_hostio_set_filesystem, making remote files access impossible.
4690 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4691 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4692 {
4693 const char v_mustreplyempty[] = "vMustReplyEmpty";
4694
4695 putpkt (v_mustreplyempty);
4696 getpkt (&rs->buf, 0);
4697 if (strcmp (rs->buf.data (), "OK") == 0)
4698 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4699 else if (strcmp (rs->buf.data (), "") != 0)
4700 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4701 rs->buf.data ());
4702 }
4703
4704 /* Next, we possibly activate noack mode.
4705
4706 If the QStartNoAckMode packet configuration is set to AUTO,
4707 enable noack mode if the stub reported a wish for it with
4708 qSupported.
4709
4710 If set to TRUE, then enable noack mode even if the stub didn't
4711 report it in qSupported. If the stub doesn't reply OK, the
4712 session ends with an error.
4713
4714 If FALSE, then don't activate noack mode, regardless of what the
4715 stub claimed should be the default with qSupported. */
4716
4717 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4718 if (packet_config_support (noack_config) != PACKET_DISABLE)
4719 {
4720 putpkt ("QStartNoAckMode");
4721 getpkt (&rs->buf, 0);
4722 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4723 rs->noack_mode = 1;
4724 }
4725
4726 if (extended_p)
4727 {
4728 /* Tell the remote that we are using the extended protocol. */
4729 putpkt ("!");
4730 getpkt (&rs->buf, 0);
4731 }
4732
4733 /* Let the target know which signals it is allowed to pass down to
4734 the program. */
4735 update_signals_program_target ();
4736
4737 /* Next, if the target can specify a description, read it. We do
4738 this before anything involving memory or registers. */
4739 target_find_description ();
4740
4741 /* Next, now that we know something about the target, update the
4742 address spaces in the program spaces. */
4743 update_address_spaces ();
4744
4745 /* On OSs where the list of libraries is global to all
4746 processes, we fetch them early. */
4747 if (gdbarch_has_global_solist (target_gdbarch ()))
4748 solib_add (NULL, from_tty, auto_solib_add);
4749
4750 if (target_is_non_stop_p ())
4751 {
4752 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4753 error (_("Non-stop mode requested, but remote "
4754 "does not support non-stop"));
4755
4756 putpkt ("QNonStop:1");
4757 getpkt (&rs->buf, 0);
4758
4759 if (strcmp (rs->buf.data (), "OK") != 0)
4760 error (_("Remote refused setting non-stop mode with: %s"),
4761 rs->buf.data ());
4762
4763 /* Find about threads and processes the stub is already
4764 controlling. We default to adding them in the running state.
4765 The '?' query below will then tell us about which threads are
4766 stopped. */
4767 this->update_thread_list ();
4768 }
4769 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4770 {
4771 /* Don't assume that the stub can operate in all-stop mode.
4772 Request it explicitly. */
4773 putpkt ("QNonStop:0");
4774 getpkt (&rs->buf, 0);
4775
4776 if (strcmp (rs->buf.data (), "OK") != 0)
4777 error (_("Remote refused setting all-stop mode with: %s"),
4778 rs->buf.data ());
4779 }
4780
4781 /* Upload TSVs regardless of whether the target is running or not. The
4782 remote stub, such as GDBserver, may have some predefined or builtin
4783 TSVs, even if the target is not running. */
4784 if (get_trace_status (current_trace_status ()) != -1)
4785 {
4786 struct uploaded_tsv *uploaded_tsvs = NULL;
4787
4788 upload_trace_state_variables (&uploaded_tsvs);
4789 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4790 }
4791
4792 /* Check whether the target is running now. */
4793 putpkt ("?");
4794 getpkt (&rs->buf, 0);
4795
4796 if (!target_is_non_stop_p ())
4797 {
4798 char *wait_status = NULL;
4799
4800 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4801 {
4802 if (!extended_p)
4803 error (_("The target is not running (try extended-remote?)"));
4804
4805 /* We're connected, but not running. Drop out before we
4806 call start_remote. */
4807 rs->starting_up = 0;
4808 return;
4809 }
4810 else
4811 {
4812 /* Save the reply for later. */
4813 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4814 strcpy (wait_status, rs->buf.data ());
4815 }
4816
4817 /* Fetch thread list. */
4818 target_update_thread_list ();
4819
4820 /* Let the stub know that we want it to return the thread. */
4821 set_continue_thread (minus_one_ptid);
4822
4823 if (thread_count (this) == 0)
4824 {
4825 /* Target has no concept of threads at all. GDB treats
4826 non-threaded target as single-threaded; add a main
4827 thread. */
4828 thread_info *tp = add_current_inferior_and_thread (wait_status);
4829 get_remote_thread_info (tp)->set_resumed ();
4830 }
4831 else
4832 {
4833 /* We have thread information; select the thread the target
4834 says should be current. If we're reconnecting to a
4835 multi-threaded program, this will ideally be the thread
4836 that last reported an event before GDB disconnected. */
4837 ptid_t curr_thread = get_current_thread (wait_status);
4838 if (curr_thread == null_ptid)
4839 {
4840 /* Odd... The target was able to list threads, but not
4841 tell us which thread was current (no "thread"
4842 register in T stop reply?). Just pick the first
4843 thread in the thread list then. */
4844
4845 remote_debug_printf ("warning: couldn't determine remote "
4846 "current thread; picking first in list.");
4847
4848 for (thread_info *tp : all_non_exited_threads (this,
4849 minus_one_ptid))
4850 {
4851 switch_to_thread (tp);
4852 break;
4853 }
4854 }
4855 else
4856 switch_to_thread (find_thread_ptid (this, curr_thread));
4857 }
4858
4859 /* init_wait_for_inferior should be called before get_offsets in order
4860 to manage `inserted' flag in bp loc in a correct state.
4861 breakpoint_init_inferior, called from init_wait_for_inferior, set
4862 `inserted' flag to 0, while before breakpoint_re_set, called from
4863 start_remote, set `inserted' flag to 1. In the initialization of
4864 inferior, breakpoint_init_inferior should be called first, and then
4865 breakpoint_re_set can be called. If this order is broken, state of
4866 `inserted' flag is wrong, and cause some problems on breakpoint
4867 manipulation. */
4868 init_wait_for_inferior ();
4869
4870 get_offsets (); /* Get text, data & bss offsets. */
4871
4872 /* If we could not find a description using qXfer, and we know
4873 how to do it some other way, try again. This is not
4874 supported for non-stop; it could be, but it is tricky if
4875 there are no stopped threads when we connect. */
4876 if (remote_read_description_p (this)
4877 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4878 {
4879 target_clear_description ();
4880 target_find_description ();
4881 }
4882
4883 /* Use the previously fetched status. */
4884 gdb_assert (wait_status != NULL);
4885 strcpy (rs->buf.data (), wait_status);
4886 rs->cached_wait_status = 1;
4887
4888 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4889 }
4890 else
4891 {
4892 /* Clear WFI global state. Do this before finding about new
4893 threads and inferiors, and setting the current inferior.
4894 Otherwise we would clear the proceed status of the current
4895 inferior when we want its stop_soon state to be preserved
4896 (see notice_new_inferior). */
4897 init_wait_for_inferior ();
4898
4899 /* In non-stop, we will either get an "OK", meaning that there
4900 are no stopped threads at this time; or, a regular stop
4901 reply. In the latter case, there may be more than one thread
4902 stopped --- we pull them all out using the vStopped
4903 mechanism. */
4904 if (strcmp (rs->buf.data (), "OK") != 0)
4905 {
4906 struct notif_client *notif = &notif_client_stop;
4907
4908 /* remote_notif_get_pending_replies acks this one, and gets
4909 the rest out. */
4910 rs->notif_state->pending_event[notif_client_stop.id]
4911 = remote_notif_parse (this, notif, rs->buf.data ());
4912 remote_notif_get_pending_events (notif);
4913 }
4914
4915 if (thread_count (this) == 0)
4916 {
4917 if (!extended_p)
4918 error (_("The target is not running (try extended-remote?)"));
4919
4920 /* We're connected, but not running. Drop out before we
4921 call start_remote. */
4922 rs->starting_up = 0;
4923 return;
4924 }
4925
4926 /* Report all signals during attach/startup. */
4927 pass_signals ({});
4928
4929 /* If there are already stopped threads, mark them stopped and
4930 report their stops before giving the prompt to the user. */
4931 process_initial_stop_replies (from_tty);
4932
4933 if (target_can_async_p ())
4934 target_async (1);
4935 }
4936
4937 /* If we connected to a live target, do some additional setup. */
4938 if (target_has_execution ())
4939 {
4940 /* No use without a symbol-file. */
4941 if (current_program_space->symfile_object_file)
4942 remote_check_symbols ();
4943 }
4944
4945 /* Possibly the target has been engaged in a trace run started
4946 previously; find out where things are at. */
4947 if (get_trace_status (current_trace_status ()) != -1)
4948 {
4949 struct uploaded_tp *uploaded_tps = NULL;
4950
4951 if (current_trace_status ()->running)
4952 printf_filtered (_("Trace is already running on the target.\n"));
4953
4954 upload_tracepoints (&uploaded_tps);
4955
4956 merge_uploaded_tracepoints (&uploaded_tps);
4957 }
4958
4959 /* Possibly the target has been engaged in a btrace record started
4960 previously; find out where things are at. */
4961 remote_btrace_maybe_reopen ();
4962
4963 /* The thread and inferior lists are now synchronized with the
4964 target, our symbols have been relocated, and we're merged the
4965 target's tracepoints with ours. We're done with basic start
4966 up. */
4967 rs->starting_up = 0;
4968
4969 /* Maybe breakpoints are global and need to be inserted now. */
4970 if (breakpoints_should_be_inserted_now ())
4971 insert_breakpoints ();
4972 }
4973
4974 const char *
4975 remote_target::connection_string ()
4976 {
4977 remote_state *rs = get_remote_state ();
4978
4979 if (rs->remote_desc->name != NULL)
4980 return rs->remote_desc->name;
4981 else
4982 return NULL;
4983 }
4984
4985 /* Open a connection to a remote debugger.
4986 NAME is the filename used for communication. */
4987
4988 void
4989 remote_target::open (const char *name, int from_tty)
4990 {
4991 open_1 (name, from_tty, 0);
4992 }
4993
4994 /* Open a connection to a remote debugger using the extended
4995 remote gdb protocol. NAME is the filename used for communication. */
4996
4997 void
4998 extended_remote_target::open (const char *name, int from_tty)
4999 {
5000 open_1 (name, from_tty, 1 /*extended_p */);
5001 }
5002
5003 /* Reset all packets back to "unknown support". Called when opening a
5004 new connection to a remote target. */
5005
5006 static void
5007 reset_all_packet_configs_support (void)
5008 {
5009 int i;
5010
5011 for (i = 0; i < PACKET_MAX; i++)
5012 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5013 }
5014
5015 /* Initialize all packet configs. */
5016
5017 static void
5018 init_all_packet_configs (void)
5019 {
5020 int i;
5021
5022 for (i = 0; i < PACKET_MAX; i++)
5023 {
5024 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5025 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5026 }
5027 }
5028
5029 /* Symbol look-up. */
5030
5031 void
5032 remote_target::remote_check_symbols ()
5033 {
5034 char *tmp;
5035 int end;
5036
5037 /* The remote side has no concept of inferiors that aren't running
5038 yet, it only knows about running processes. If we're connected
5039 but our current inferior is not running, we should not invite the
5040 remote target to request symbol lookups related to its
5041 (unrelated) current process. */
5042 if (!target_has_execution ())
5043 return;
5044
5045 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5046 return;
5047
5048 /* Make sure the remote is pointing at the right process. Note
5049 there's no way to select "no process". */
5050 set_general_process ();
5051
5052 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5053 because we need both at the same time. */
5054 gdb::char_vector msg (get_remote_packet_size ());
5055 gdb::char_vector reply (get_remote_packet_size ());
5056
5057 /* Invite target to request symbol lookups. */
5058
5059 putpkt ("qSymbol::");
5060 getpkt (&reply, 0);
5061 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5062
5063 while (startswith (reply.data (), "qSymbol:"))
5064 {
5065 struct bound_minimal_symbol sym;
5066
5067 tmp = &reply[8];
5068 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5069 strlen (tmp) / 2);
5070 msg[end] = '\0';
5071 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5072 if (sym.minsym == NULL)
5073 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5074 &reply[8]);
5075 else
5076 {
5077 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5078 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
5079
5080 /* If this is a function address, return the start of code
5081 instead of any data function descriptor. */
5082 sym_addr = gdbarch_convert_from_func_ptr_addr
5083 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5084
5085 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5086 phex_nz (sym_addr, addr_size), &reply[8]);
5087 }
5088
5089 putpkt (msg.data ());
5090 getpkt (&reply, 0);
5091 }
5092 }
5093
5094 static struct serial *
5095 remote_serial_open (const char *name)
5096 {
5097 static int udp_warning = 0;
5098
5099 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5100 of in ser-tcp.c, because it is the remote protocol assuming that the
5101 serial connection is reliable and not the serial connection promising
5102 to be. */
5103 if (!udp_warning && startswith (name, "udp:"))
5104 {
5105 warning (_("The remote protocol may be unreliable over UDP.\n"
5106 "Some events may be lost, rendering further debugging "
5107 "impossible."));
5108 udp_warning = 1;
5109 }
5110
5111 return serial_open (name);
5112 }
5113
5114 /* Inform the target of our permission settings. The permission flags
5115 work without this, but if the target knows the settings, it can do
5116 a couple things. First, it can add its own check, to catch cases
5117 that somehow manage to get by the permissions checks in target
5118 methods. Second, if the target is wired to disallow particular
5119 settings (for instance, a system in the field that is not set up to
5120 be able to stop at a breakpoint), it can object to any unavailable
5121 permissions. */
5122
5123 void
5124 remote_target::set_permissions ()
5125 {
5126 struct remote_state *rs = get_remote_state ();
5127
5128 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5129 "WriteReg:%x;WriteMem:%x;"
5130 "InsertBreak:%x;InsertTrace:%x;"
5131 "InsertFastTrace:%x;Stop:%x",
5132 may_write_registers, may_write_memory,
5133 may_insert_breakpoints, may_insert_tracepoints,
5134 may_insert_fast_tracepoints, may_stop);
5135 putpkt (rs->buf);
5136 getpkt (&rs->buf, 0);
5137
5138 /* If the target didn't like the packet, warn the user. Do not try
5139 to undo the user's settings, that would just be maddening. */
5140 if (strcmp (rs->buf.data (), "OK") != 0)
5141 warning (_("Remote refused setting permissions with: %s"),
5142 rs->buf.data ());
5143 }
5144
5145 /* This type describes each known response to the qSupported
5146 packet. */
5147 struct protocol_feature
5148 {
5149 /* The name of this protocol feature. */
5150 const char *name;
5151
5152 /* The default for this protocol feature. */
5153 enum packet_support default_support;
5154
5155 /* The function to call when this feature is reported, or after
5156 qSupported processing if the feature is not supported.
5157 The first argument points to this structure. The second
5158 argument indicates whether the packet requested support be
5159 enabled, disabled, or probed (or the default, if this function
5160 is being called at the end of processing and this feature was
5161 not reported). The third argument may be NULL; if not NULL, it
5162 is a NUL-terminated string taken from the packet following
5163 this feature's name and an equals sign. */
5164 void (*func) (remote_target *remote, const struct protocol_feature *,
5165 enum packet_support, const char *);
5166
5167 /* The corresponding packet for this feature. Only used if
5168 FUNC is remote_supported_packet. */
5169 int packet;
5170 };
5171
5172 static void
5173 remote_supported_packet (remote_target *remote,
5174 const struct protocol_feature *feature,
5175 enum packet_support support,
5176 const char *argument)
5177 {
5178 if (argument)
5179 {
5180 warning (_("Remote qSupported response supplied an unexpected value for"
5181 " \"%s\"."), feature->name);
5182 return;
5183 }
5184
5185 remote_protocol_packets[feature->packet].support = support;
5186 }
5187
5188 void
5189 remote_target::remote_packet_size (const protocol_feature *feature,
5190 enum packet_support support, const char *value)
5191 {
5192 struct remote_state *rs = get_remote_state ();
5193
5194 int packet_size;
5195 char *value_end;
5196
5197 if (support != PACKET_ENABLE)
5198 return;
5199
5200 if (value == NULL || *value == '\0')
5201 {
5202 warning (_("Remote target reported \"%s\" without a size."),
5203 feature->name);
5204 return;
5205 }
5206
5207 errno = 0;
5208 packet_size = strtol (value, &value_end, 16);
5209 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5210 {
5211 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5212 feature->name, value);
5213 return;
5214 }
5215
5216 /* Record the new maximum packet size. */
5217 rs->explicit_packet_size = packet_size;
5218 }
5219
5220 static void
5221 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5222 enum packet_support support, const char *value)
5223 {
5224 remote->remote_packet_size (feature, support, value);
5225 }
5226
5227 static const struct protocol_feature remote_protocol_features[] = {
5228 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5229 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5230 PACKET_qXfer_auxv },
5231 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5232 PACKET_qXfer_exec_file },
5233 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5234 PACKET_qXfer_features },
5235 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5236 PACKET_qXfer_libraries },
5237 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5238 PACKET_qXfer_libraries_svr4 },
5239 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5240 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5241 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5242 PACKET_qXfer_memory_map },
5243 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5244 PACKET_qXfer_osdata },
5245 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5246 PACKET_qXfer_threads },
5247 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5248 PACKET_qXfer_traceframe_info },
5249 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5250 PACKET_QPassSignals },
5251 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5252 PACKET_QCatchSyscalls },
5253 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5254 PACKET_QProgramSignals },
5255 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5256 PACKET_QSetWorkingDir },
5257 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5258 PACKET_QStartupWithShell },
5259 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5260 PACKET_QEnvironmentHexEncoded },
5261 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5262 PACKET_QEnvironmentReset },
5263 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5264 PACKET_QEnvironmentUnset },
5265 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5266 PACKET_QStartNoAckMode },
5267 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5268 PACKET_multiprocess_feature },
5269 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5270 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5271 PACKET_qXfer_siginfo_read },
5272 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5273 PACKET_qXfer_siginfo_write },
5274 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5275 PACKET_ConditionalTracepoints },
5276 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5277 PACKET_ConditionalBreakpoints },
5278 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5279 PACKET_BreakpointCommands },
5280 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5281 PACKET_FastTracepoints },
5282 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5283 PACKET_StaticTracepoints },
5284 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5285 PACKET_InstallInTrace},
5286 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5287 PACKET_DisconnectedTracing_feature },
5288 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5289 PACKET_bc },
5290 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5291 PACKET_bs },
5292 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5293 PACKET_TracepointSource },
5294 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5295 PACKET_QAllow },
5296 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5297 PACKET_EnableDisableTracepoints_feature },
5298 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5299 PACKET_qXfer_fdpic },
5300 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5301 PACKET_qXfer_uib },
5302 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5303 PACKET_QDisableRandomization },
5304 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5305 { "QTBuffer:size", PACKET_DISABLE,
5306 remote_supported_packet, PACKET_QTBuffer_size},
5307 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5308 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5309 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5310 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5311 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5312 PACKET_qXfer_btrace },
5313 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5314 PACKET_qXfer_btrace_conf },
5315 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5316 PACKET_Qbtrace_conf_bts_size },
5317 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5318 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5319 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5320 PACKET_fork_event_feature },
5321 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5322 PACKET_vfork_event_feature },
5323 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5324 PACKET_exec_event_feature },
5325 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5326 PACKET_Qbtrace_conf_pt_size },
5327 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5328 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5329 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5330 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5331 PACKET_memory_tagging_feature },
5332 };
5333
5334 static char *remote_support_xml;
5335
5336 /* Register string appended to "xmlRegisters=" in qSupported query. */
5337
5338 void
5339 register_remote_support_xml (const char *xml)
5340 {
5341 #if defined(HAVE_LIBEXPAT)
5342 if (remote_support_xml == NULL)
5343 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5344 else
5345 {
5346 char *copy = xstrdup (remote_support_xml + 13);
5347 char *saveptr;
5348 char *p = strtok_r (copy, ",", &saveptr);
5349
5350 do
5351 {
5352 if (strcmp (p, xml) == 0)
5353 {
5354 /* already there */
5355 xfree (copy);
5356 return;
5357 }
5358 }
5359 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5360 xfree (copy);
5361
5362 remote_support_xml = reconcat (remote_support_xml,
5363 remote_support_xml, ",", xml,
5364 (char *) NULL);
5365 }
5366 #endif
5367 }
5368
5369 static void
5370 remote_query_supported_append (std::string *msg, const char *append)
5371 {
5372 if (!msg->empty ())
5373 msg->append (";");
5374 msg->append (append);
5375 }
5376
5377 void
5378 remote_target::remote_query_supported ()
5379 {
5380 struct remote_state *rs = get_remote_state ();
5381 char *next;
5382 int i;
5383 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5384
5385 /* The packet support flags are handled differently for this packet
5386 than for most others. We treat an error, a disabled packet, and
5387 an empty response identically: any features which must be reported
5388 to be used will be automatically disabled. An empty buffer
5389 accomplishes this, since that is also the representation for a list
5390 containing no features. */
5391
5392 rs->buf[0] = 0;
5393 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5394 {
5395 std::string q;
5396
5397 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5398 remote_query_supported_append (&q, "multiprocess+");
5399
5400 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5401 remote_query_supported_append (&q, "swbreak+");
5402 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5403 remote_query_supported_append (&q, "hwbreak+");
5404
5405 remote_query_supported_append (&q, "qRelocInsn+");
5406
5407 if (packet_set_cmd_state (PACKET_fork_event_feature)
5408 != AUTO_BOOLEAN_FALSE)
5409 remote_query_supported_append (&q, "fork-events+");
5410 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5411 != AUTO_BOOLEAN_FALSE)
5412 remote_query_supported_append (&q, "vfork-events+");
5413 if (packet_set_cmd_state (PACKET_exec_event_feature)
5414 != AUTO_BOOLEAN_FALSE)
5415 remote_query_supported_append (&q, "exec-events+");
5416
5417 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5418 remote_query_supported_append (&q, "vContSupported+");
5419
5420 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5421 remote_query_supported_append (&q, "QThreadEvents+");
5422
5423 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5424 remote_query_supported_append (&q, "no-resumed+");
5425
5426 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5427 != AUTO_BOOLEAN_FALSE)
5428 remote_query_supported_append (&q, "memory-tagging+");
5429
5430 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5431 the qSupported:xmlRegisters=i386 handling. */
5432 if (remote_support_xml != NULL
5433 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5434 remote_query_supported_append (&q, remote_support_xml);
5435
5436 q = "qSupported:" + q;
5437 putpkt (q.c_str ());
5438
5439 getpkt (&rs->buf, 0);
5440
5441 /* If an error occured, warn, but do not return - just reset the
5442 buffer to empty and go on to disable features. */
5443 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5444 == PACKET_ERROR)
5445 {
5446 warning (_("Remote failure reply: %s"), rs->buf.data ());
5447 rs->buf[0] = 0;
5448 }
5449 }
5450
5451 memset (seen, 0, sizeof (seen));
5452
5453 next = rs->buf.data ();
5454 while (*next)
5455 {
5456 enum packet_support is_supported;
5457 char *p, *end, *name_end, *value;
5458
5459 /* First separate out this item from the rest of the packet. If
5460 there's another item after this, we overwrite the separator
5461 (terminated strings are much easier to work with). */
5462 p = next;
5463 end = strchr (p, ';');
5464 if (end == NULL)
5465 {
5466 end = p + strlen (p);
5467 next = end;
5468 }
5469 else
5470 {
5471 *end = '\0';
5472 next = end + 1;
5473
5474 if (end == p)
5475 {
5476 warning (_("empty item in \"qSupported\" response"));
5477 continue;
5478 }
5479 }
5480
5481 name_end = strchr (p, '=');
5482 if (name_end)
5483 {
5484 /* This is a name=value entry. */
5485 is_supported = PACKET_ENABLE;
5486 value = name_end + 1;
5487 *name_end = '\0';
5488 }
5489 else
5490 {
5491 value = NULL;
5492 switch (end[-1])
5493 {
5494 case '+':
5495 is_supported = PACKET_ENABLE;
5496 break;
5497
5498 case '-':
5499 is_supported = PACKET_DISABLE;
5500 break;
5501
5502 case '?':
5503 is_supported = PACKET_SUPPORT_UNKNOWN;
5504 break;
5505
5506 default:
5507 warning (_("unrecognized item \"%s\" "
5508 "in \"qSupported\" response"), p);
5509 continue;
5510 }
5511 end[-1] = '\0';
5512 }
5513
5514 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5515 if (strcmp (remote_protocol_features[i].name, p) == 0)
5516 {
5517 const struct protocol_feature *feature;
5518
5519 seen[i] = 1;
5520 feature = &remote_protocol_features[i];
5521 feature->func (this, feature, is_supported, value);
5522 break;
5523 }
5524 }
5525
5526 /* If we increased the packet size, make sure to increase the global
5527 buffer size also. We delay this until after parsing the entire
5528 qSupported packet, because this is the same buffer we were
5529 parsing. */
5530 if (rs->buf.size () < rs->explicit_packet_size)
5531 rs->buf.resize (rs->explicit_packet_size);
5532
5533 /* Handle the defaults for unmentioned features. */
5534 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5535 if (!seen[i])
5536 {
5537 const struct protocol_feature *feature;
5538
5539 feature = &remote_protocol_features[i];
5540 feature->func (this, feature, feature->default_support, NULL);
5541 }
5542 }
5543
5544 /* Serial QUIT handler for the remote serial descriptor.
5545
5546 Defers handling a Ctrl-C until we're done with the current
5547 command/response packet sequence, unless:
5548
5549 - We're setting up the connection. Don't send a remote interrupt
5550 request, as we're not fully synced yet. Quit immediately
5551 instead.
5552
5553 - The target has been resumed in the foreground
5554 (target_terminal::is_ours is false) with a synchronous resume
5555 packet, and we're blocked waiting for the stop reply, thus a
5556 Ctrl-C should be immediately sent to the target.
5557
5558 - We get a second Ctrl-C while still within the same serial read or
5559 write. In that case the serial is seemingly wedged --- offer to
5560 quit/disconnect.
5561
5562 - We see a second Ctrl-C without target response, after having
5563 previously interrupted the target. In that case the target/stub
5564 is probably wedged --- offer to quit/disconnect.
5565 */
5566
5567 void
5568 remote_target::remote_serial_quit_handler ()
5569 {
5570 struct remote_state *rs = get_remote_state ();
5571
5572 if (check_quit_flag ())
5573 {
5574 /* If we're starting up, we're not fully synced yet. Quit
5575 immediately. */
5576 if (rs->starting_up)
5577 quit ();
5578 else if (rs->got_ctrlc_during_io)
5579 {
5580 if (query (_("The target is not responding to GDB commands.\n"
5581 "Stop debugging it? ")))
5582 remote_unpush_and_throw (this);
5583 }
5584 /* If ^C has already been sent once, offer to disconnect. */
5585 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5586 interrupt_query ();
5587 /* All-stop protocol, and blocked waiting for stop reply. Send
5588 an interrupt request. */
5589 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5590 target_interrupt ();
5591 else
5592 rs->got_ctrlc_during_io = 1;
5593 }
5594 }
5595
5596 /* The remote_target that is current while the quit handler is
5597 overridden with remote_serial_quit_handler. */
5598 static remote_target *curr_quit_handler_target;
5599
5600 static void
5601 remote_serial_quit_handler ()
5602 {
5603 curr_quit_handler_target->remote_serial_quit_handler ();
5604 }
5605
5606 /* Remove the remote target from the target stack of each inferior
5607 that is using it. Upper targets depend on it so remove them
5608 first. */
5609
5610 static void
5611 remote_unpush_target (remote_target *target)
5612 {
5613 /* We have to unpush the target from all inferiors, even those that
5614 aren't running. */
5615 scoped_restore_current_inferior restore_current_inferior;
5616
5617 for (inferior *inf : all_inferiors (target))
5618 {
5619 switch_to_inferior_no_thread (inf);
5620 pop_all_targets_at_and_above (process_stratum);
5621 generic_mourn_inferior ();
5622 }
5623 }
5624
5625 static void
5626 remote_unpush_and_throw (remote_target *target)
5627 {
5628 remote_unpush_target (target);
5629 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5630 }
5631
5632 void
5633 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5634 {
5635 remote_target *curr_remote = get_current_remote_target ();
5636
5637 if (name == 0)
5638 error (_("To open a remote debug connection, you need to specify what\n"
5639 "serial device is attached to the remote system\n"
5640 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5641
5642 /* If we're connected to a running target, target_preopen will kill it.
5643 Ask this question first, before target_preopen has a chance to kill
5644 anything. */
5645 if (curr_remote != NULL && !target_has_execution ())
5646 {
5647 if (from_tty
5648 && !query (_("Already connected to a remote target. Disconnect? ")))
5649 error (_("Still connected."));
5650 }
5651
5652 /* Here the possibly existing remote target gets unpushed. */
5653 target_preopen (from_tty);
5654
5655 remote_fileio_reset ();
5656 reopen_exec_file ();
5657 reread_symbols ();
5658
5659 remote_target *remote
5660 = (extended_p ? new extended_remote_target () : new remote_target ());
5661 target_ops_up target_holder (remote);
5662
5663 remote_state *rs = remote->get_remote_state ();
5664
5665 /* See FIXME above. */
5666 if (!target_async_permitted)
5667 rs->wait_forever_enabled_p = 1;
5668
5669 rs->remote_desc = remote_serial_open (name);
5670 if (!rs->remote_desc)
5671 perror_with_name (name);
5672
5673 if (baud_rate != -1)
5674 {
5675 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5676 {
5677 /* The requested speed could not be set. Error out to
5678 top level after closing remote_desc. Take care to
5679 set remote_desc to NULL to avoid closing remote_desc
5680 more than once. */
5681 serial_close (rs->remote_desc);
5682 rs->remote_desc = NULL;
5683 perror_with_name (name);
5684 }
5685 }
5686
5687 serial_setparity (rs->remote_desc, serial_parity);
5688 serial_raw (rs->remote_desc);
5689
5690 /* If there is something sitting in the buffer we might take it as a
5691 response to a command, which would be bad. */
5692 serial_flush_input (rs->remote_desc);
5693
5694 if (from_tty)
5695 {
5696 puts_filtered ("Remote debugging using ");
5697 puts_filtered (name);
5698 puts_filtered ("\n");
5699 }
5700
5701 /* Switch to using the remote target now. */
5702 current_inferior ()->push_target (std::move (target_holder));
5703
5704 /* Register extra event sources in the event loop. */
5705 rs->remote_async_inferior_event_token
5706 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5707 "remote");
5708 rs->notif_state = remote_notif_state_allocate (remote);
5709
5710 /* Reset the target state; these things will be queried either by
5711 remote_query_supported or as they are needed. */
5712 reset_all_packet_configs_support ();
5713 rs->cached_wait_status = 0;
5714 rs->explicit_packet_size = 0;
5715 rs->noack_mode = 0;
5716 rs->extended = extended_p;
5717 rs->waiting_for_stop_reply = 0;
5718 rs->ctrlc_pending_p = 0;
5719 rs->got_ctrlc_during_io = 0;
5720
5721 rs->general_thread = not_sent_ptid;
5722 rs->continue_thread = not_sent_ptid;
5723 rs->remote_traceframe_number = -1;
5724
5725 rs->last_resume_exec_dir = EXEC_FORWARD;
5726
5727 /* Probe for ability to use "ThreadInfo" query, as required. */
5728 rs->use_threadinfo_query = 1;
5729 rs->use_threadextra_query = 1;
5730
5731 rs->readahead_cache.invalidate ();
5732
5733 if (target_async_permitted)
5734 {
5735 /* FIXME: cagney/1999-09-23: During the initial connection it is
5736 assumed that the target is already ready and able to respond to
5737 requests. Unfortunately remote_start_remote() eventually calls
5738 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5739 around this. Eventually a mechanism that allows
5740 wait_for_inferior() to expect/get timeouts will be
5741 implemented. */
5742 rs->wait_forever_enabled_p = 0;
5743 }
5744
5745 /* First delete any symbols previously loaded from shared libraries. */
5746 no_shared_libraries (NULL, 0);
5747
5748 /* Start the remote connection. If error() or QUIT, discard this
5749 target (we'd otherwise be in an inconsistent state) and then
5750 propogate the error on up the exception chain. This ensures that
5751 the caller doesn't stumble along blindly assuming that the
5752 function succeeded. The CLI doesn't have this problem but other
5753 UI's, such as MI do.
5754
5755 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5756 this function should return an error indication letting the
5757 caller restore the previous state. Unfortunately the command
5758 ``target remote'' is directly wired to this function making that
5759 impossible. On a positive note, the CLI side of this problem has
5760 been fixed - the function set_cmd_context() makes it possible for
5761 all the ``target ....'' commands to share a common callback
5762 function. See cli-dump.c. */
5763 {
5764
5765 try
5766 {
5767 remote->start_remote (from_tty, extended_p);
5768 }
5769 catch (const gdb_exception &ex)
5770 {
5771 /* Pop the partially set up target - unless something else did
5772 already before throwing the exception. */
5773 if (ex.error != TARGET_CLOSE_ERROR)
5774 remote_unpush_target (remote);
5775 throw;
5776 }
5777 }
5778
5779 remote_btrace_reset (rs);
5780
5781 if (target_async_permitted)
5782 rs->wait_forever_enabled_p = 1;
5783 }
5784
5785 /* Detach the specified process. */
5786
5787 void
5788 remote_target::remote_detach_pid (int pid)
5789 {
5790 struct remote_state *rs = get_remote_state ();
5791
5792 /* This should not be necessary, but the handling for D;PID in
5793 GDBserver versions prior to 8.2 incorrectly assumes that the
5794 selected process points to the same process we're detaching,
5795 leading to misbehavior (and possibly GDBserver crashing) when it
5796 does not. Since it's easy and cheap, work around it by forcing
5797 GDBserver to select GDB's current process. */
5798 set_general_process ();
5799
5800 if (remote_multi_process_p (rs))
5801 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5802 else
5803 strcpy (rs->buf.data (), "D");
5804
5805 putpkt (rs->buf);
5806 getpkt (&rs->buf, 0);
5807
5808 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5809 ;
5810 else if (rs->buf[0] == '\0')
5811 error (_("Remote doesn't know how to detach"));
5812 else
5813 error (_("Can't detach process."));
5814 }
5815
5816 /* This detaches a program to which we previously attached, using
5817 inferior_ptid to identify the process. After this is done, GDB
5818 can be used to debug some other program. We better not have left
5819 any breakpoints in the target program or it'll die when it hits
5820 one. */
5821
5822 void
5823 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5824 {
5825 int pid = inferior_ptid.pid ();
5826 struct remote_state *rs = get_remote_state ();
5827 int is_fork_parent;
5828
5829 if (!target_has_execution ())
5830 error (_("No process to detach from."));
5831
5832 target_announce_detach (from_tty);
5833
5834 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5835 {
5836 /* If we're in breakpoints-always-inserted mode, or the inferior
5837 is running, we have to remove breakpoints before detaching.
5838 We don't do this in common code instead because not all
5839 targets support removing breakpoints while the target is
5840 running. The remote target / gdbserver does, though. */
5841 remove_breakpoints_inf (current_inferior ());
5842 }
5843
5844 /* Tell the remote target to detach. */
5845 remote_detach_pid (pid);
5846
5847 /* Exit only if this is the only active inferior. */
5848 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5849 puts_filtered (_("Ending remote debugging.\n"));
5850
5851 thread_info *tp = find_thread_ptid (this, inferior_ptid);
5852
5853 /* Check to see if we are detaching a fork parent. Note that if we
5854 are detaching a fork child, tp == NULL. */
5855 is_fork_parent = (tp != NULL
5856 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5857
5858 /* If doing detach-on-fork, we don't mourn, because that will delete
5859 breakpoints that should be available for the followed inferior. */
5860 if (!is_fork_parent)
5861 {
5862 /* Save the pid as a string before mourning, since that will
5863 unpush the remote target, and we need the string after. */
5864 std::string infpid = target_pid_to_str (ptid_t (pid));
5865
5866 target_mourn_inferior (inferior_ptid);
5867 if (print_inferior_events)
5868 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5869 inf->num, infpid.c_str ());
5870 }
5871 else
5872 {
5873 switch_to_no_thread ();
5874 detach_inferior (current_inferior ());
5875 }
5876 }
5877
5878 void
5879 remote_target::detach (inferior *inf, int from_tty)
5880 {
5881 remote_detach_1 (inf, from_tty);
5882 }
5883
5884 void
5885 extended_remote_target::detach (inferior *inf, int from_tty)
5886 {
5887 remote_detach_1 (inf, from_tty);
5888 }
5889
5890 /* Target follow-fork function for remote targets. On entry, and
5891 at return, the current inferior is the fork parent.
5892
5893 Note that although this is currently only used for extended-remote,
5894 it is named remote_follow_fork in anticipation of using it for the
5895 remote target as well. */
5896
5897 bool
5898 remote_target::follow_fork (bool follow_child, bool detach_fork)
5899 {
5900 struct remote_state *rs = get_remote_state ();
5901 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5902
5903 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5904 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5905 {
5906 /* When following the parent and detaching the child, we detach
5907 the child here. For the case of following the child and
5908 detaching the parent, the detach is done in the target-
5909 independent follow fork code in infrun.c. We can't use
5910 target_detach when detaching an unfollowed child because
5911 the client side doesn't know anything about the child. */
5912 if (detach_fork && !follow_child)
5913 {
5914 /* Detach the fork child. */
5915 ptid_t child_ptid;
5916 pid_t child_pid;
5917
5918 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5919 child_pid = child_ptid.pid ();
5920
5921 remote_detach_pid (child_pid);
5922 }
5923 }
5924
5925 return false;
5926 }
5927
5928 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5929 in the program space of the new inferior. On entry and at return the
5930 current inferior is the exec'ing inferior. INF is the new exec'd
5931 inferior, which may be the same as the exec'ing inferior unless
5932 follow-exec-mode is "new". */
5933
5934 void
5935 remote_target::follow_exec (struct inferior *inf, const char *execd_pathname)
5936 {
5937 /* We know that this is a target file name, so if it has the "target:"
5938 prefix we strip it off before saving it in the program space. */
5939 if (is_target_filename (execd_pathname))
5940 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5941
5942 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5943 }
5944
5945 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5946
5947 void
5948 remote_target::disconnect (const char *args, int from_tty)
5949 {
5950 if (args)
5951 error (_("Argument given to \"disconnect\" when remotely debugging."));
5952
5953 /* Make sure we unpush even the extended remote targets. Calling
5954 target_mourn_inferior won't unpush, and
5955 remote_target::mourn_inferior won't unpush if there is more than
5956 one inferior left. */
5957 remote_unpush_target (this);
5958
5959 if (from_tty)
5960 puts_filtered ("Ending remote debugging.\n");
5961 }
5962
5963 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5964 be chatty about it. */
5965
5966 void
5967 extended_remote_target::attach (const char *args, int from_tty)
5968 {
5969 struct remote_state *rs = get_remote_state ();
5970 int pid;
5971 char *wait_status = NULL;
5972
5973 pid = parse_pid_to_attach (args);
5974
5975 /* Remote PID can be freely equal to getpid, do not check it here the same
5976 way as in other targets. */
5977
5978 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5979 error (_("This target does not support attaching to a process"));
5980
5981 if (from_tty)
5982 {
5983 const char *exec_file = get_exec_file (0);
5984
5985 if (exec_file)
5986 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5987 target_pid_to_str (ptid_t (pid)).c_str ());
5988 else
5989 printf_unfiltered (_("Attaching to %s\n"),
5990 target_pid_to_str (ptid_t (pid)).c_str ());
5991 }
5992
5993 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
5994 putpkt (rs->buf);
5995 getpkt (&rs->buf, 0);
5996
5997 switch (packet_ok (rs->buf,
5998 &remote_protocol_packets[PACKET_vAttach]))
5999 {
6000 case PACKET_OK:
6001 if (!target_is_non_stop_p ())
6002 {
6003 /* Save the reply for later. */
6004 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6005 strcpy (wait_status, rs->buf.data ());
6006 }
6007 else if (strcmp (rs->buf.data (), "OK") != 0)
6008 error (_("Attaching to %s failed with: %s"),
6009 target_pid_to_str (ptid_t (pid)).c_str (),
6010 rs->buf.data ());
6011 break;
6012 case PACKET_UNKNOWN:
6013 error (_("This target does not support attaching to a process"));
6014 default:
6015 error (_("Attaching to %s failed"),
6016 target_pid_to_str (ptid_t (pid)).c_str ());
6017 }
6018
6019 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6020
6021 inferior_ptid = ptid_t (pid);
6022
6023 if (target_is_non_stop_p ())
6024 {
6025 /* Get list of threads. */
6026 update_thread_list ();
6027
6028 thread_info *thread = first_thread_of_inferior (current_inferior ());
6029 if (thread != nullptr)
6030 switch_to_thread (thread);
6031
6032 /* Invalidate our notion of the remote current thread. */
6033 record_currthread (rs, minus_one_ptid);
6034 }
6035 else
6036 {
6037 /* Now, if we have thread information, update the main thread's
6038 ptid. */
6039 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6040
6041 /* Add the main thread to the thread list. */
6042 thread_info *thr = add_thread_silent (this, curr_ptid);
6043
6044 switch_to_thread (thr);
6045
6046 /* Don't consider the thread stopped until we've processed the
6047 saved stop reply. */
6048 set_executing (this, thr->ptid, true);
6049 }
6050
6051 /* Next, if the target can specify a description, read it. We do
6052 this before anything involving memory or registers. */
6053 target_find_description ();
6054
6055 if (!target_is_non_stop_p ())
6056 {
6057 /* Use the previously fetched status. */
6058 gdb_assert (wait_status != NULL);
6059
6060 if (target_can_async_p ())
6061 {
6062 struct notif_event *reply
6063 = remote_notif_parse (this, &notif_client_stop, wait_status);
6064
6065 push_stop_reply ((struct stop_reply *) reply);
6066
6067 target_async (1);
6068 }
6069 else
6070 {
6071 gdb_assert (wait_status != NULL);
6072 strcpy (rs->buf.data (), wait_status);
6073 rs->cached_wait_status = 1;
6074 }
6075 }
6076 else
6077 {
6078 gdb_assert (wait_status == NULL);
6079
6080 gdb_assert (target_can_async_p ());
6081 target_async (1);
6082 }
6083 }
6084
6085 /* Implementation of the to_post_attach method. */
6086
6087 void
6088 extended_remote_target::post_attach (int pid)
6089 {
6090 /* Get text, data & bss offsets. */
6091 get_offsets ();
6092
6093 /* In certain cases GDB might not have had the chance to start
6094 symbol lookup up until now. This could happen if the debugged
6095 binary is not using shared libraries, the vsyscall page is not
6096 present (on Linux) and the binary itself hadn't changed since the
6097 debugging process was started. */
6098 if (current_program_space->symfile_object_file != NULL)
6099 remote_check_symbols();
6100 }
6101
6102 \f
6103 /* Check for the availability of vCont. This function should also check
6104 the response. */
6105
6106 void
6107 remote_target::remote_vcont_probe ()
6108 {
6109 remote_state *rs = get_remote_state ();
6110 char *buf;
6111
6112 strcpy (rs->buf.data (), "vCont?");
6113 putpkt (rs->buf);
6114 getpkt (&rs->buf, 0);
6115 buf = rs->buf.data ();
6116
6117 /* Make sure that the features we assume are supported. */
6118 if (startswith (buf, "vCont"))
6119 {
6120 char *p = &buf[5];
6121 int support_c, support_C;
6122
6123 rs->supports_vCont.s = 0;
6124 rs->supports_vCont.S = 0;
6125 support_c = 0;
6126 support_C = 0;
6127 rs->supports_vCont.t = 0;
6128 rs->supports_vCont.r = 0;
6129 while (p && *p == ';')
6130 {
6131 p++;
6132 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6133 rs->supports_vCont.s = 1;
6134 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6135 rs->supports_vCont.S = 1;
6136 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6137 support_c = 1;
6138 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6139 support_C = 1;
6140 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6141 rs->supports_vCont.t = 1;
6142 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6143 rs->supports_vCont.r = 1;
6144
6145 p = strchr (p, ';');
6146 }
6147
6148 /* If c, and C are not all supported, we can't use vCont. Clearing
6149 BUF will make packet_ok disable the packet. */
6150 if (!support_c || !support_C)
6151 buf[0] = 0;
6152 }
6153
6154 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6155 rs->supports_vCont_probed = true;
6156 }
6157
6158 /* Helper function for building "vCont" resumptions. Write a
6159 resumption to P. ENDP points to one-passed-the-end of the buffer
6160 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6161 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6162 resumed thread should be single-stepped and/or signalled. If PTID
6163 equals minus_one_ptid, then all threads are resumed; if PTID
6164 represents a process, then all threads of the process are resumed;
6165 the thread to be stepped and/or signalled is given in the global
6166 INFERIOR_PTID. */
6167
6168 char *
6169 remote_target::append_resumption (char *p, char *endp,
6170 ptid_t ptid, int step, gdb_signal siggnal)
6171 {
6172 struct remote_state *rs = get_remote_state ();
6173
6174 if (step && siggnal != GDB_SIGNAL_0)
6175 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6176 else if (step
6177 /* GDB is willing to range step. */
6178 && use_range_stepping
6179 /* Target supports range stepping. */
6180 && rs->supports_vCont.r
6181 /* We don't currently support range stepping multiple
6182 threads with a wildcard (though the protocol allows it,
6183 so stubs shouldn't make an active effort to forbid
6184 it). */
6185 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6186 {
6187 struct thread_info *tp;
6188
6189 if (ptid == minus_one_ptid)
6190 {
6191 /* If we don't know about the target thread's tid, then
6192 we're resuming magic_null_ptid (see caller). */
6193 tp = find_thread_ptid (this, magic_null_ptid);
6194 }
6195 else
6196 tp = find_thread_ptid (this, ptid);
6197 gdb_assert (tp != NULL);
6198
6199 if (tp->control.may_range_step)
6200 {
6201 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6202
6203 p += xsnprintf (p, endp - p, ";r%s,%s",
6204 phex_nz (tp->control.step_range_start,
6205 addr_size),
6206 phex_nz (tp->control.step_range_end,
6207 addr_size));
6208 }
6209 else
6210 p += xsnprintf (p, endp - p, ";s");
6211 }
6212 else if (step)
6213 p += xsnprintf (p, endp - p, ";s");
6214 else if (siggnal != GDB_SIGNAL_0)
6215 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6216 else
6217 p += xsnprintf (p, endp - p, ";c");
6218
6219 if (remote_multi_process_p (rs) && ptid.is_pid ())
6220 {
6221 ptid_t nptid;
6222
6223 /* All (-1) threads of process. */
6224 nptid = ptid_t (ptid.pid (), -1, 0);
6225
6226 p += xsnprintf (p, endp - p, ":");
6227 p = write_ptid (p, endp, nptid);
6228 }
6229 else if (ptid != minus_one_ptid)
6230 {
6231 p += xsnprintf (p, endp - p, ":");
6232 p = write_ptid (p, endp, ptid);
6233 }
6234
6235 return p;
6236 }
6237
6238 /* Clear the thread's private info on resume. */
6239
6240 static void
6241 resume_clear_thread_private_info (struct thread_info *thread)
6242 {
6243 if (thread->priv != NULL)
6244 {
6245 remote_thread_info *priv = get_remote_thread_info (thread);
6246
6247 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6248 priv->watch_data_address = 0;
6249 }
6250 }
6251
6252 /* Append a vCont continue-with-signal action for threads that have a
6253 non-zero stop signal. */
6254
6255 char *
6256 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6257 ptid_t ptid)
6258 {
6259 for (thread_info *thread : all_non_exited_threads (this, ptid))
6260 if (inferior_ptid != thread->ptid
6261 && thread->suspend.stop_signal != GDB_SIGNAL_0)
6262 {
6263 p = append_resumption (p, endp, thread->ptid,
6264 0, thread->suspend.stop_signal);
6265 thread->suspend.stop_signal = GDB_SIGNAL_0;
6266 resume_clear_thread_private_info (thread);
6267 }
6268
6269 return p;
6270 }
6271
6272 /* Set the target running, using the packets that use Hc
6273 (c/s/C/S). */
6274
6275 void
6276 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6277 gdb_signal siggnal)
6278 {
6279 struct remote_state *rs = get_remote_state ();
6280 char *buf;
6281
6282 rs->last_sent_signal = siggnal;
6283 rs->last_sent_step = step;
6284
6285 /* The c/s/C/S resume packets use Hc, so set the continue
6286 thread. */
6287 if (ptid == minus_one_ptid)
6288 set_continue_thread (any_thread_ptid);
6289 else
6290 set_continue_thread (ptid);
6291
6292 for (thread_info *thread : all_non_exited_threads (this))
6293 resume_clear_thread_private_info (thread);
6294
6295 buf = rs->buf.data ();
6296 if (::execution_direction == EXEC_REVERSE)
6297 {
6298 /* We don't pass signals to the target in reverse exec mode. */
6299 if (info_verbose && siggnal != GDB_SIGNAL_0)
6300 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6301 siggnal);
6302
6303 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6304 error (_("Remote reverse-step not supported."));
6305 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6306 error (_("Remote reverse-continue not supported."));
6307
6308 strcpy (buf, step ? "bs" : "bc");
6309 }
6310 else if (siggnal != GDB_SIGNAL_0)
6311 {
6312 buf[0] = step ? 'S' : 'C';
6313 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6314 buf[2] = tohex (((int) siggnal) & 0xf);
6315 buf[3] = '\0';
6316 }
6317 else
6318 strcpy (buf, step ? "s" : "c");
6319
6320 putpkt (buf);
6321 }
6322
6323 /* Resume the remote inferior by using a "vCont" packet. The thread
6324 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6325 resumed thread should be single-stepped and/or signalled. If PTID
6326 equals minus_one_ptid, then all threads are resumed; the thread to
6327 be stepped and/or signalled is given in the global INFERIOR_PTID.
6328 This function returns non-zero iff it resumes the inferior.
6329
6330 This function issues a strict subset of all possible vCont commands
6331 at the moment. */
6332
6333 int
6334 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6335 enum gdb_signal siggnal)
6336 {
6337 struct remote_state *rs = get_remote_state ();
6338 char *p;
6339 char *endp;
6340
6341 /* No reverse execution actions defined for vCont. */
6342 if (::execution_direction == EXEC_REVERSE)
6343 return 0;
6344
6345 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6346 remote_vcont_probe ();
6347
6348 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6349 return 0;
6350
6351 p = rs->buf.data ();
6352 endp = p + get_remote_packet_size ();
6353
6354 /* If we could generate a wider range of packets, we'd have to worry
6355 about overflowing BUF. Should there be a generic
6356 "multi-part-packet" packet? */
6357
6358 p += xsnprintf (p, endp - p, "vCont");
6359
6360 if (ptid == magic_null_ptid)
6361 {
6362 /* MAGIC_NULL_PTID means that we don't have any active threads,
6363 so we don't have any TID numbers the inferior will
6364 understand. Make sure to only send forms that do not specify
6365 a TID. */
6366 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6367 }
6368 else if (ptid == minus_one_ptid || ptid.is_pid ())
6369 {
6370 /* Resume all threads (of all processes, or of a single
6371 process), with preference for INFERIOR_PTID. This assumes
6372 inferior_ptid belongs to the set of all threads we are about
6373 to resume. */
6374 if (step || siggnal != GDB_SIGNAL_0)
6375 {
6376 /* Step inferior_ptid, with or without signal. */
6377 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6378 }
6379
6380 /* Also pass down any pending signaled resumption for other
6381 threads not the current. */
6382 p = append_pending_thread_resumptions (p, endp, ptid);
6383
6384 /* And continue others without a signal. */
6385 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6386 }
6387 else
6388 {
6389 /* Scheduler locking; resume only PTID. */
6390 append_resumption (p, endp, ptid, step, siggnal);
6391 }
6392
6393 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6394 putpkt (rs->buf);
6395
6396 if (target_is_non_stop_p ())
6397 {
6398 /* In non-stop, the stub replies to vCont with "OK". The stop
6399 reply will be reported asynchronously by means of a `%Stop'
6400 notification. */
6401 getpkt (&rs->buf, 0);
6402 if (strcmp (rs->buf.data (), "OK") != 0)
6403 error (_("Unexpected vCont reply in non-stop mode: %s"),
6404 rs->buf.data ());
6405 }
6406
6407 return 1;
6408 }
6409
6410 /* Tell the remote machine to resume. */
6411
6412 void
6413 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6414 {
6415 struct remote_state *rs = get_remote_state ();
6416
6417 /* When connected in non-stop mode, the core resumes threads
6418 individually. Resuming remote threads directly in target_resume
6419 would thus result in sending one packet per thread. Instead, to
6420 minimize roundtrip latency, here we just store the resume
6421 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6422 resumption will be done in remote_target::commit_resume, where we'll be
6423 able to do vCont action coalescing. */
6424 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6425 {
6426 remote_thread_info *remote_thr;
6427
6428 if (minus_one_ptid == ptid || ptid.is_pid ())
6429 remote_thr = get_remote_thread_info (this, inferior_ptid);
6430 else
6431 remote_thr = get_remote_thread_info (this, ptid);
6432
6433 /* We don't expect the core to ask to resume an already resumed (from
6434 its point of view) thread. */
6435 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6436
6437 remote_thr->set_resumed_pending_vcont (step, siggnal);
6438 return;
6439 }
6440
6441 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6442 (explained in remote-notif.c:handle_notification) so
6443 remote_notif_process is not called. We need find a place where
6444 it is safe to start a 'vNotif' sequence. It is good to do it
6445 before resuming inferior, because inferior was stopped and no RSP
6446 traffic at that moment. */
6447 if (!target_is_non_stop_p ())
6448 remote_notif_process (rs->notif_state, &notif_client_stop);
6449
6450 rs->last_resume_exec_dir = ::execution_direction;
6451
6452 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6453 if (!remote_resume_with_vcont (ptid, step, siggnal))
6454 remote_resume_with_hc (ptid, step, siggnal);
6455
6456 /* Update resumed state tracked by the remote target. */
6457 for (thread_info *tp : all_non_exited_threads (this, ptid))
6458 get_remote_thread_info (tp)->set_resumed ();
6459
6460 /* We are about to start executing the inferior, let's register it
6461 with the event loop. NOTE: this is the one place where all the
6462 execution commands end up. We could alternatively do this in each
6463 of the execution commands in infcmd.c. */
6464 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6465 into infcmd.c in order to allow inferior function calls to work
6466 NOT asynchronously. */
6467 if (target_can_async_p ())
6468 target_async (1);
6469
6470 /* We've just told the target to resume. The remote server will
6471 wait for the inferior to stop, and then send a stop reply. In
6472 the mean time, we can't start another command/query ourselves
6473 because the stub wouldn't be ready to process it. This applies
6474 only to the base all-stop protocol, however. In non-stop (which
6475 only supports vCont), the stub replies with an "OK", and is
6476 immediate able to process further serial input. */
6477 if (!target_is_non_stop_p ())
6478 rs->waiting_for_stop_reply = 1;
6479 }
6480
6481 static int is_pending_fork_parent_thread (struct thread_info *thread);
6482
6483 /* Private per-inferior info for target remote processes. */
6484
6485 struct remote_inferior : public private_inferior
6486 {
6487 /* Whether we can send a wildcard vCont for this process. */
6488 bool may_wildcard_vcont = true;
6489 };
6490
6491 /* Get the remote private inferior data associated to INF. */
6492
6493 static remote_inferior *
6494 get_remote_inferior (inferior *inf)
6495 {
6496 if (inf->priv == NULL)
6497 inf->priv.reset (new remote_inferior);
6498
6499 return static_cast<remote_inferior *> (inf->priv.get ());
6500 }
6501
6502 struct stop_reply : public notif_event
6503 {
6504 ~stop_reply ();
6505
6506 /* The identifier of the thread about this event */
6507 ptid_t ptid;
6508
6509 /* The remote state this event is associated with. When the remote
6510 connection, represented by a remote_state object, is closed,
6511 all the associated stop_reply events should be released. */
6512 struct remote_state *rs;
6513
6514 struct target_waitstatus ws;
6515
6516 /* The architecture associated with the expedited registers. */
6517 gdbarch *arch;
6518
6519 /* Expedited registers. This makes remote debugging a bit more
6520 efficient for those targets that provide critical registers as
6521 part of their normal status mechanism (as another roundtrip to
6522 fetch them is avoided). */
6523 std::vector<cached_reg_t> regcache;
6524
6525 enum target_stop_reason stop_reason;
6526
6527 CORE_ADDR watch_data_address;
6528
6529 int core;
6530 };
6531
6532 /* Class used to track the construction of a vCont packet in the
6533 outgoing packet buffer. This is used to send multiple vCont
6534 packets if we have more actions than would fit a single packet. */
6535
6536 class vcont_builder
6537 {
6538 public:
6539 explicit vcont_builder (remote_target *remote)
6540 : m_remote (remote)
6541 {
6542 restart ();
6543 }
6544
6545 void flush ();
6546 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6547
6548 private:
6549 void restart ();
6550
6551 /* The remote target. */
6552 remote_target *m_remote;
6553
6554 /* Pointer to the first action. P points here if no action has been
6555 appended yet. */
6556 char *m_first_action;
6557
6558 /* Where the next action will be appended. */
6559 char *m_p;
6560
6561 /* The end of the buffer. Must never write past this. */
6562 char *m_endp;
6563 };
6564
6565 /* Prepare the outgoing buffer for a new vCont packet. */
6566
6567 void
6568 vcont_builder::restart ()
6569 {
6570 struct remote_state *rs = m_remote->get_remote_state ();
6571
6572 m_p = rs->buf.data ();
6573 m_endp = m_p + m_remote->get_remote_packet_size ();
6574 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6575 m_first_action = m_p;
6576 }
6577
6578 /* If the vCont packet being built has any action, send it to the
6579 remote end. */
6580
6581 void
6582 vcont_builder::flush ()
6583 {
6584 struct remote_state *rs;
6585
6586 if (m_p == m_first_action)
6587 return;
6588
6589 rs = m_remote->get_remote_state ();
6590 m_remote->putpkt (rs->buf);
6591 m_remote->getpkt (&rs->buf, 0);
6592 if (strcmp (rs->buf.data (), "OK") != 0)
6593 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6594 }
6595
6596 /* The largest action is range-stepping, with its two addresses. This
6597 is more than sufficient. If a new, bigger action is created, it'll
6598 quickly trigger a failed assertion in append_resumption (and we'll
6599 just bump this). */
6600 #define MAX_ACTION_SIZE 200
6601
6602 /* Append a new vCont action in the outgoing packet being built. If
6603 the action doesn't fit the packet along with previous actions, push
6604 what we've got so far to the remote end and start over a new vCont
6605 packet (with the new action). */
6606
6607 void
6608 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6609 {
6610 char buf[MAX_ACTION_SIZE + 1];
6611
6612 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6613 ptid, step, siggnal);
6614
6615 /* Check whether this new action would fit in the vCont packet along
6616 with previous actions. If not, send what we've got so far and
6617 start a new vCont packet. */
6618 size_t rsize = endp - buf;
6619 if (rsize > m_endp - m_p)
6620 {
6621 flush ();
6622 restart ();
6623
6624 /* Should now fit. */
6625 gdb_assert (rsize <= m_endp - m_p);
6626 }
6627
6628 memcpy (m_p, buf, rsize);
6629 m_p += rsize;
6630 *m_p = '\0';
6631 }
6632
6633 /* to_commit_resume implementation. */
6634
6635 void
6636 remote_target::commit_resumed ()
6637 {
6638 int any_process_wildcard;
6639 int may_global_wildcard_vcont;
6640
6641 /* If connected in all-stop mode, we'd send the remote resume
6642 request directly from remote_resume. Likewise if
6643 reverse-debugging, as there are no defined vCont actions for
6644 reverse execution. */
6645 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6646 return;
6647
6648 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6649 instead of resuming all threads of each process individually.
6650 However, if any thread of a process must remain halted, we can't
6651 send wildcard resumes and must send one action per thread.
6652
6653 Care must be taken to not resume threads/processes the server
6654 side already told us are stopped, but the core doesn't know about
6655 yet, because the events are still in the vStopped notification
6656 queue. For example:
6657
6658 #1 => vCont s:p1.1;c
6659 #2 <= OK
6660 #3 <= %Stopped T05 p1.1
6661 #4 => vStopped
6662 #5 <= T05 p1.2
6663 #6 => vStopped
6664 #7 <= OK
6665 #8 (infrun handles the stop for p1.1 and continues stepping)
6666 #9 => vCont s:p1.1;c
6667
6668 The last vCont above would resume thread p1.2 by mistake, because
6669 the server has no idea that the event for p1.2 had not been
6670 handled yet.
6671
6672 The server side must similarly ignore resume actions for the
6673 thread that has a pending %Stopped notification (and any other
6674 threads with events pending), until GDB acks the notification
6675 with vStopped. Otherwise, e.g., the following case is
6676 mishandled:
6677
6678 #1 => g (or any other packet)
6679 #2 <= [registers]
6680 #3 <= %Stopped T05 p1.2
6681 #4 => vCont s:p1.1;c
6682 #5 <= OK
6683
6684 Above, the server must not resume thread p1.2. GDB can't know
6685 that p1.2 stopped until it acks the %Stopped notification, and
6686 since from GDB's perspective all threads should be running, it
6687 sends a "c" action.
6688
6689 Finally, special care must also be given to handling fork/vfork
6690 events. A (v)fork event actually tells us that two processes
6691 stopped -- the parent and the child. Until we follow the fork,
6692 we must not resume the child. Therefore, if we have a pending
6693 fork follow, we must not send a global wildcard resume action
6694 (vCont;c). We can still send process-wide wildcards though. */
6695
6696 /* Start by assuming a global wildcard (vCont;c) is possible. */
6697 may_global_wildcard_vcont = 1;
6698
6699 /* And assume every process is individually wildcard-able too. */
6700 for (inferior *inf : all_non_exited_inferiors (this))
6701 {
6702 remote_inferior *priv = get_remote_inferior (inf);
6703
6704 priv->may_wildcard_vcont = true;
6705 }
6706
6707 /* Check for any pending events (not reported or processed yet) and
6708 disable process and global wildcard resumes appropriately. */
6709 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6710
6711 bool any_pending_vcont_resume = false;
6712
6713 for (thread_info *tp : all_non_exited_threads (this))
6714 {
6715 remote_thread_info *priv = get_remote_thread_info (tp);
6716
6717 /* If a thread of a process is not meant to be resumed, then we
6718 can't wildcard that process. */
6719 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6720 {
6721 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6722
6723 /* And if we can't wildcard a process, we can't wildcard
6724 everything either. */
6725 may_global_wildcard_vcont = 0;
6726 continue;
6727 }
6728
6729 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6730 any_pending_vcont_resume = true;
6731
6732 /* If a thread is the parent of an unfollowed fork, then we
6733 can't do a global wildcard, as that would resume the fork
6734 child. */
6735 if (is_pending_fork_parent_thread (tp))
6736 may_global_wildcard_vcont = 0;
6737 }
6738
6739 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6740 do. */
6741 if (!any_pending_vcont_resume)
6742 return;
6743
6744 /* Now let's build the vCont packet(s). Actions must be appended
6745 from narrower to wider scopes (thread -> process -> global). If
6746 we end up with too many actions for a single packet vcont_builder
6747 flushes the current vCont packet to the remote side and starts a
6748 new one. */
6749 struct vcont_builder vcont_builder (this);
6750
6751 /* Threads first. */
6752 for (thread_info *tp : all_non_exited_threads (this))
6753 {
6754 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6755
6756 /* If the thread was previously vCont-resumed, no need to send a specific
6757 action for it. If we didn't receive a resume request for it, don't
6758 send an action for it either. */
6759 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6760 continue;
6761
6762 gdb_assert (!thread_is_in_step_over_chain (tp));
6763
6764 /* We should never be commit-resuming a thread that has a stop reply.
6765 Otherwise, we would end up reporting a stop event for a thread while
6766 it is running on the remote target. */
6767 remote_state *rs = get_remote_state ();
6768 for (const auto &stop_reply : rs->stop_reply_queue)
6769 gdb_assert (stop_reply->ptid != tp->ptid);
6770
6771 const resumed_pending_vcont_info &info
6772 = remote_thr->resumed_pending_vcont_info ();
6773
6774 /* Check if we need to send a specific action for this thread. If not,
6775 it will be included in a wildcard resume instead. */
6776 if (info.step || info.sig != GDB_SIGNAL_0
6777 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6778 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6779
6780 remote_thr->set_resumed ();
6781 }
6782
6783 /* Now check whether we can send any process-wide wildcard. This is
6784 to avoid sending a global wildcard in the case nothing is
6785 supposed to be resumed. */
6786 any_process_wildcard = 0;
6787
6788 for (inferior *inf : all_non_exited_inferiors (this))
6789 {
6790 if (get_remote_inferior (inf)->may_wildcard_vcont)
6791 {
6792 any_process_wildcard = 1;
6793 break;
6794 }
6795 }
6796
6797 if (any_process_wildcard)
6798 {
6799 /* If all processes are wildcard-able, then send a single "c"
6800 action, otherwise, send an "all (-1) threads of process"
6801 continue action for each running process, if any. */
6802 if (may_global_wildcard_vcont)
6803 {
6804 vcont_builder.push_action (minus_one_ptid,
6805 false, GDB_SIGNAL_0);
6806 }
6807 else
6808 {
6809 for (inferior *inf : all_non_exited_inferiors (this))
6810 {
6811 if (get_remote_inferior (inf)->may_wildcard_vcont)
6812 {
6813 vcont_builder.push_action (ptid_t (inf->pid),
6814 false, GDB_SIGNAL_0);
6815 }
6816 }
6817 }
6818 }
6819
6820 vcont_builder.flush ();
6821 }
6822
6823 \f
6824
6825 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6826 thread, all threads of a remote process, or all threads of all
6827 processes. */
6828
6829 void
6830 remote_target::remote_stop_ns (ptid_t ptid)
6831 {
6832 struct remote_state *rs = get_remote_state ();
6833 char *p = rs->buf.data ();
6834 char *endp = p + get_remote_packet_size ();
6835
6836 /* If any thread that needs to stop was resumed but pending a vCont
6837 resume, generate a phony stop_reply. However, first check
6838 whether the thread wasn't resumed with a signal. Generating a
6839 phony stop in that case would result in losing the signal. */
6840 bool needs_commit = false;
6841 for (thread_info *tp : all_non_exited_threads (this, ptid))
6842 {
6843 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6844
6845 if (remote_thr->get_resume_state ()
6846 == resume_state::RESUMED_PENDING_VCONT)
6847 {
6848 const resumed_pending_vcont_info &info
6849 = remote_thr->resumed_pending_vcont_info ();
6850 if (info.sig != GDB_SIGNAL_0)
6851 {
6852 /* This signal must be forwarded to the inferior. We
6853 could commit-resume just this thread, but its simpler
6854 to just commit-resume everything. */
6855 needs_commit = true;
6856 break;
6857 }
6858 }
6859 }
6860
6861 if (needs_commit)
6862 commit_resumed ();
6863 else
6864 for (thread_info *tp : all_non_exited_threads (this, ptid))
6865 {
6866 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6867
6868 if (remote_thr->get_resume_state ()
6869 == resume_state::RESUMED_PENDING_VCONT)
6870 {
6871 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
6872 "vCont-resume (%d, %ld, %ld)", tp->ptid.pid(),
6873 tp->ptid.lwp (), tp->ptid.tid ());
6874
6875 /* Check that the thread wasn't resumed with a signal.
6876 Generating a phony stop would result in losing the
6877 signal. */
6878 const resumed_pending_vcont_info &info
6879 = remote_thr->resumed_pending_vcont_info ();
6880 gdb_assert (info.sig == GDB_SIGNAL_0);
6881
6882 stop_reply *sr = new stop_reply ();
6883 sr->ptid = tp->ptid;
6884 sr->rs = rs;
6885 sr->ws.kind = TARGET_WAITKIND_STOPPED;
6886 sr->ws.value.sig = GDB_SIGNAL_0;
6887 sr->arch = tp->inf->gdbarch;
6888 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6889 sr->watch_data_address = 0;
6890 sr->core = 0;
6891 this->push_stop_reply (sr);
6892
6893 /* Pretend that this thread was actually resumed on the
6894 remote target, then stopped. If we leave it in the
6895 RESUMED_PENDING_VCONT state and the commit_resumed
6896 method is called while the stop reply is still in the
6897 queue, we'll end up reporting a stop event to the core
6898 for that thread while it is running on the remote
6899 target... that would be bad. */
6900 remote_thr->set_resumed ();
6901 }
6902 }
6903
6904 /* FIXME: This supports_vCont_probed check is a workaround until
6905 packet_support is per-connection. */
6906 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
6907 || !rs->supports_vCont_probed)
6908 remote_vcont_probe ();
6909
6910 if (!rs->supports_vCont.t)
6911 error (_("Remote server does not support stopping threads"));
6912
6913 if (ptid == minus_one_ptid
6914 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
6915 p += xsnprintf (p, endp - p, "vCont;t");
6916 else
6917 {
6918 ptid_t nptid;
6919
6920 p += xsnprintf (p, endp - p, "vCont;t:");
6921
6922 if (ptid.is_pid ())
6923 /* All (-1) threads of process. */
6924 nptid = ptid_t (ptid.pid (), -1, 0);
6925 else
6926 {
6927 /* Small optimization: if we already have a stop reply for
6928 this thread, no use in telling the stub we want this
6929 stopped. */
6930 if (peek_stop_reply (ptid))
6931 return;
6932
6933 nptid = ptid;
6934 }
6935
6936 write_ptid (p, endp, nptid);
6937 }
6938
6939 /* In non-stop, we get an immediate OK reply. The stop reply will
6940 come in asynchronously by notification. */
6941 putpkt (rs->buf);
6942 getpkt (&rs->buf, 0);
6943 if (strcmp (rs->buf.data (), "OK") != 0)
6944 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
6945 rs->buf.data ());
6946 }
6947
6948 /* All-stop version of target_interrupt. Sends a break or a ^C to
6949 interrupt the remote target. It is undefined which thread of which
6950 process reports the interrupt. */
6951
6952 void
6953 remote_target::remote_interrupt_as ()
6954 {
6955 struct remote_state *rs = get_remote_state ();
6956
6957 rs->ctrlc_pending_p = 1;
6958
6959 /* If the inferior is stopped already, but the core didn't know
6960 about it yet, just ignore the request. The cached wait status
6961 will be collected in remote_wait. */
6962 if (rs->cached_wait_status)
6963 return;
6964
6965 /* Send interrupt_sequence to remote target. */
6966 send_interrupt_sequence ();
6967 }
6968
6969 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6970 the remote target. It is undefined which thread of which process
6971 reports the interrupt. Throws an error if the packet is not
6972 supported by the server. */
6973
6974 void
6975 remote_target::remote_interrupt_ns ()
6976 {
6977 struct remote_state *rs = get_remote_state ();
6978 char *p = rs->buf.data ();
6979 char *endp = p + get_remote_packet_size ();
6980
6981 xsnprintf (p, endp - p, "vCtrlC");
6982
6983 /* In non-stop, we get an immediate OK reply. The stop reply will
6984 come in asynchronously by notification. */
6985 putpkt (rs->buf);
6986 getpkt (&rs->buf, 0);
6987
6988 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6989 {
6990 case PACKET_OK:
6991 break;
6992 case PACKET_UNKNOWN:
6993 error (_("No support for interrupting the remote target."));
6994 case PACKET_ERROR:
6995 error (_("Interrupting target failed: %s"), rs->buf.data ());
6996 }
6997 }
6998
6999 /* Implement the to_stop function for the remote targets. */
7000
7001 void
7002 remote_target::stop (ptid_t ptid)
7003 {
7004 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7005
7006 if (target_is_non_stop_p ())
7007 remote_stop_ns (ptid);
7008 else
7009 {
7010 /* We don't currently have a way to transparently pause the
7011 remote target in all-stop mode. Interrupt it instead. */
7012 remote_interrupt_as ();
7013 }
7014 }
7015
7016 /* Implement the to_interrupt function for the remote targets. */
7017
7018 void
7019 remote_target::interrupt ()
7020 {
7021 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7022
7023 if (target_is_non_stop_p ())
7024 remote_interrupt_ns ();
7025 else
7026 remote_interrupt_as ();
7027 }
7028
7029 /* Implement the to_pass_ctrlc function for the remote targets. */
7030
7031 void
7032 remote_target::pass_ctrlc ()
7033 {
7034 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7035
7036 struct remote_state *rs = get_remote_state ();
7037
7038 /* If we're starting up, we're not fully synced yet. Quit
7039 immediately. */
7040 if (rs->starting_up)
7041 quit ();
7042 /* If ^C has already been sent once, offer to disconnect. */
7043 else if (rs->ctrlc_pending_p)
7044 interrupt_query ();
7045 else
7046 target_interrupt ();
7047 }
7048
7049 /* Ask the user what to do when an interrupt is received. */
7050
7051 void
7052 remote_target::interrupt_query ()
7053 {
7054 struct remote_state *rs = get_remote_state ();
7055
7056 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7057 {
7058 if (query (_("The target is not responding to interrupt requests.\n"
7059 "Stop debugging it? ")))
7060 {
7061 remote_unpush_target (this);
7062 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7063 }
7064 }
7065 else
7066 {
7067 if (query (_("Interrupted while waiting for the program.\n"
7068 "Give up waiting? ")))
7069 quit ();
7070 }
7071 }
7072
7073 /* Enable/disable target terminal ownership. Most targets can use
7074 terminal groups to control terminal ownership. Remote targets are
7075 different in that explicit transfer of ownership to/from GDB/target
7076 is required. */
7077
7078 void
7079 remote_target::terminal_inferior ()
7080 {
7081 /* NOTE: At this point we could also register our selves as the
7082 recipient of all input. Any characters typed could then be
7083 passed on down to the target. */
7084 }
7085
7086 void
7087 remote_target::terminal_ours ()
7088 {
7089 }
7090
7091 static void
7092 remote_console_output (const char *msg)
7093 {
7094 const char *p;
7095
7096 for (p = msg; p[0] && p[1]; p += 2)
7097 {
7098 char tb[2];
7099 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7100
7101 tb[0] = c;
7102 tb[1] = 0;
7103 gdb_stdtarg->puts (tb);
7104 }
7105 gdb_stdtarg->flush ();
7106 }
7107
7108 /* Return the length of the stop reply queue. */
7109
7110 int
7111 remote_target::stop_reply_queue_length ()
7112 {
7113 remote_state *rs = get_remote_state ();
7114 return rs->stop_reply_queue.size ();
7115 }
7116
7117 static void
7118 remote_notif_stop_parse (remote_target *remote,
7119 struct notif_client *self, const char *buf,
7120 struct notif_event *event)
7121 {
7122 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7123 }
7124
7125 static void
7126 remote_notif_stop_ack (remote_target *remote,
7127 struct notif_client *self, const char *buf,
7128 struct notif_event *event)
7129 {
7130 struct stop_reply *stop_reply = (struct stop_reply *) event;
7131
7132 /* acknowledge */
7133 putpkt (remote, self->ack_command);
7134
7135 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7136 the notification. It was left in the queue because we need to
7137 acknowledge it and pull the rest of the notifications out. */
7138 if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
7139 remote->push_stop_reply (stop_reply);
7140 }
7141
7142 static int
7143 remote_notif_stop_can_get_pending_events (remote_target *remote,
7144 struct notif_client *self)
7145 {
7146 /* We can't get pending events in remote_notif_process for
7147 notification stop, and we have to do this in remote_wait_ns
7148 instead. If we fetch all queued events from stub, remote stub
7149 may exit and we have no chance to process them back in
7150 remote_wait_ns. */
7151 remote_state *rs = remote->get_remote_state ();
7152 mark_async_event_handler (rs->remote_async_inferior_event_token);
7153 return 0;
7154 }
7155
7156 stop_reply::~stop_reply ()
7157 {
7158 for (cached_reg_t &reg : regcache)
7159 xfree (reg.data);
7160 }
7161
7162 static notif_event_up
7163 remote_notif_stop_alloc_reply ()
7164 {
7165 return notif_event_up (new struct stop_reply ());
7166 }
7167
7168 /* A client of notification Stop. */
7169
7170 struct notif_client notif_client_stop =
7171 {
7172 "Stop",
7173 "vStopped",
7174 remote_notif_stop_parse,
7175 remote_notif_stop_ack,
7176 remote_notif_stop_can_get_pending_events,
7177 remote_notif_stop_alloc_reply,
7178 REMOTE_NOTIF_STOP,
7179 };
7180
7181 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
7182 the pid of the process that owns the threads we want to check, or
7183 -1 if we want to check all threads. */
7184
7185 static int
7186 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
7187 ptid_t thread_ptid)
7188 {
7189 if (ws->kind == TARGET_WAITKIND_FORKED
7190 || ws->kind == TARGET_WAITKIND_VFORKED)
7191 {
7192 if (event_pid == -1 || event_pid == thread_ptid.pid ())
7193 return 1;
7194 }
7195
7196 return 0;
7197 }
7198
7199 /* Return the thread's pending status used to determine whether the
7200 thread is a fork parent stopped at a fork event. */
7201
7202 static struct target_waitstatus *
7203 thread_pending_fork_status (struct thread_info *thread)
7204 {
7205 if (thread->suspend.waitstatus_pending_p)
7206 return &thread->suspend.waitstatus;
7207 else
7208 return &thread->pending_follow;
7209 }
7210
7211 /* Determine if THREAD is a pending fork parent thread. */
7212
7213 static int
7214 is_pending_fork_parent_thread (struct thread_info *thread)
7215 {
7216 struct target_waitstatus *ws = thread_pending_fork_status (thread);
7217 int pid = -1;
7218
7219 return is_pending_fork_parent (ws, pid, thread->ptid);
7220 }
7221
7222 /* If CONTEXT contains any fork child threads that have not been
7223 reported yet, remove them from the CONTEXT list. If such a
7224 thread exists it is because we are stopped at a fork catchpoint
7225 and have not yet called follow_fork, which will set up the
7226 host-side data structures for the new process. */
7227
7228 void
7229 remote_target::remove_new_fork_children (threads_listing_context *context)
7230 {
7231 int pid = -1;
7232 struct notif_client *notif = &notif_client_stop;
7233
7234 /* For any threads stopped at a fork event, remove the corresponding
7235 fork child threads from the CONTEXT list. */
7236 for (thread_info *thread : all_non_exited_threads (this))
7237 {
7238 struct target_waitstatus *ws = thread_pending_fork_status (thread);
7239
7240 if (is_pending_fork_parent (ws, pid, thread->ptid))
7241 context->remove_thread (ws->value.related_pid);
7242 }
7243
7244 /* Check for any pending fork events (not reported or processed yet)
7245 in process PID and remove those fork child threads from the
7246 CONTEXT list as well. */
7247 remote_notif_get_pending_events (notif);
7248 for (auto &event : get_remote_state ()->stop_reply_queue)
7249 if (event->ws.kind == TARGET_WAITKIND_FORKED
7250 || event->ws.kind == TARGET_WAITKIND_VFORKED
7251 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7252 context->remove_thread (event->ws.value.related_pid);
7253 }
7254
7255 /* Check whether any event pending in the vStopped queue would prevent
7256 a global or process wildcard vCont action. Clear
7257 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7258 and clear the event inferior's may_wildcard_vcont flag if we can't
7259 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7260
7261 void
7262 remote_target::check_pending_events_prevent_wildcard_vcont
7263 (int *may_global_wildcard)
7264 {
7265 struct notif_client *notif = &notif_client_stop;
7266
7267 remote_notif_get_pending_events (notif);
7268 for (auto &event : get_remote_state ()->stop_reply_queue)
7269 {
7270 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7271 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7272 continue;
7273
7274 if (event->ws.kind == TARGET_WAITKIND_FORKED
7275 || event->ws.kind == TARGET_WAITKIND_VFORKED)
7276 *may_global_wildcard = 0;
7277
7278 /* This may be the first time we heard about this process.
7279 Regardless, we must not do a global wildcard resume, otherwise
7280 we'd resume this process too. */
7281 *may_global_wildcard = 0;
7282 if (event->ptid != null_ptid)
7283 {
7284 inferior *inf = find_inferior_ptid (this, event->ptid);
7285 if (inf != NULL)
7286 get_remote_inferior (inf)->may_wildcard_vcont = false;
7287 }
7288 }
7289 }
7290
7291 /* Discard all pending stop replies of inferior INF. */
7292
7293 void
7294 remote_target::discard_pending_stop_replies (struct inferior *inf)
7295 {
7296 struct stop_reply *reply;
7297 struct remote_state *rs = get_remote_state ();
7298 struct remote_notif_state *rns = rs->notif_state;
7299
7300 /* This function can be notified when an inferior exists. When the
7301 target is not remote, the notification state is NULL. */
7302 if (rs->remote_desc == NULL)
7303 return;
7304
7305 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7306
7307 /* Discard the in-flight notification. */
7308 if (reply != NULL && reply->ptid.pid () == inf->pid)
7309 {
7310 /* Leave the notification pending, since the server expects that
7311 we acknowledge it with vStopped. But clear its contents, so
7312 that later on when we acknowledge it, we also discard it. */
7313 reply->ws.kind = TARGET_WAITKIND_IGNORE;
7314
7315 if (remote_debug)
7316 fprintf_unfiltered (gdb_stdlog,
7317 "discarded in-flight notification\n");
7318 }
7319
7320 /* Discard the stop replies we have already pulled with
7321 vStopped. */
7322 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7323 rs->stop_reply_queue.end (),
7324 [=] (const stop_reply_up &event)
7325 {
7326 return event->ptid.pid () == inf->pid;
7327 });
7328 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7329 }
7330
7331 /* Discard the stop replies for RS in stop_reply_queue. */
7332
7333 void
7334 remote_target::discard_pending_stop_replies_in_queue ()
7335 {
7336 remote_state *rs = get_remote_state ();
7337
7338 /* Discard the stop replies we have already pulled with
7339 vStopped. */
7340 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7341 rs->stop_reply_queue.end (),
7342 [=] (const stop_reply_up &event)
7343 {
7344 return event->rs == rs;
7345 });
7346 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7347 }
7348
7349 /* Remove the first reply in 'stop_reply_queue' which matches
7350 PTID. */
7351
7352 struct stop_reply *
7353 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7354 {
7355 remote_state *rs = get_remote_state ();
7356
7357 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7358 rs->stop_reply_queue.end (),
7359 [=] (const stop_reply_up &event)
7360 {
7361 return event->ptid.matches (ptid);
7362 });
7363 struct stop_reply *result;
7364 if (iter == rs->stop_reply_queue.end ())
7365 result = nullptr;
7366 else
7367 {
7368 result = iter->release ();
7369 rs->stop_reply_queue.erase (iter);
7370 }
7371
7372 if (notif_debug)
7373 fprintf_unfiltered (gdb_stdlog,
7374 "notif: discard queued event: 'Stop' in %s\n",
7375 target_pid_to_str (ptid).c_str ());
7376
7377 return result;
7378 }
7379
7380 /* Look for a queued stop reply belonging to PTID. If one is found,
7381 remove it from the queue, and return it. Returns NULL if none is
7382 found. If there are still queued events left to process, tell the
7383 event loop to get back to target_wait soon. */
7384
7385 struct stop_reply *
7386 remote_target::queued_stop_reply (ptid_t ptid)
7387 {
7388 remote_state *rs = get_remote_state ();
7389 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7390
7391 if (!rs->stop_reply_queue.empty ())
7392 {
7393 /* There's still at least an event left. */
7394 mark_async_event_handler (rs->remote_async_inferior_event_token);
7395 }
7396
7397 return r;
7398 }
7399
7400 /* Push a fully parsed stop reply in the stop reply queue. Since we
7401 know that we now have at least one queued event left to pass to the
7402 core side, tell the event loop to get back to target_wait soon. */
7403
7404 void
7405 remote_target::push_stop_reply (struct stop_reply *new_event)
7406 {
7407 remote_state *rs = get_remote_state ();
7408 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7409
7410 if (notif_debug)
7411 fprintf_unfiltered (gdb_stdlog,
7412 "notif: push 'Stop' %s to queue %d\n",
7413 target_pid_to_str (new_event->ptid).c_str (),
7414 int (rs->stop_reply_queue.size ()));
7415
7416 mark_async_event_handler (rs->remote_async_inferior_event_token);
7417 }
7418
7419 /* Returns true if we have a stop reply for PTID. */
7420
7421 int
7422 remote_target::peek_stop_reply (ptid_t ptid)
7423 {
7424 remote_state *rs = get_remote_state ();
7425 for (auto &event : rs->stop_reply_queue)
7426 if (ptid == event->ptid
7427 && event->ws.kind == TARGET_WAITKIND_STOPPED)
7428 return 1;
7429 return 0;
7430 }
7431
7432 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7433 starting with P and ending with PEND matches PREFIX. */
7434
7435 static int
7436 strprefix (const char *p, const char *pend, const char *prefix)
7437 {
7438 for ( ; p < pend; p++, prefix++)
7439 if (*p != *prefix)
7440 return 0;
7441 return *prefix == '\0';
7442 }
7443
7444 /* Parse the stop reply in BUF. Either the function succeeds, and the
7445 result is stored in EVENT, or throws an error. */
7446
7447 void
7448 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7449 {
7450 remote_arch_state *rsa = NULL;
7451 ULONGEST addr;
7452 const char *p;
7453 int skipregs = 0;
7454
7455 event->ptid = null_ptid;
7456 event->rs = get_remote_state ();
7457 event->ws.kind = TARGET_WAITKIND_IGNORE;
7458 event->ws.value.integer = 0;
7459 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7460 event->regcache.clear ();
7461 event->core = -1;
7462
7463 switch (buf[0])
7464 {
7465 case 'T': /* Status with PC, SP, FP, ... */
7466 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7467 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7468 ss = signal number
7469 n... = register number
7470 r... = register contents
7471 */
7472
7473 p = &buf[3]; /* after Txx */
7474 while (*p)
7475 {
7476 const char *p1;
7477 int fieldsize;
7478
7479 p1 = strchr (p, ':');
7480 if (p1 == NULL)
7481 error (_("Malformed packet(a) (missing colon): %s\n\
7482 Packet: '%s'\n"),
7483 p, buf);
7484 if (p == p1)
7485 error (_("Malformed packet(a) (missing register number): %s\n\
7486 Packet: '%s'\n"),
7487 p, buf);
7488
7489 /* Some "registers" are actually extended stop information.
7490 Note if you're adding a new entry here: GDB 7.9 and
7491 earlier assume that all register "numbers" that start
7492 with an hex digit are real register numbers. Make sure
7493 the server only sends such a packet if it knows the
7494 client understands it. */
7495
7496 if (strprefix (p, p1, "thread"))
7497 event->ptid = read_ptid (++p1, &p);
7498 else if (strprefix (p, p1, "syscall_entry"))
7499 {
7500 ULONGEST sysno;
7501
7502 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7503 p = unpack_varlen_hex (++p1, &sysno);
7504 event->ws.value.syscall_number = (int) sysno;
7505 }
7506 else if (strprefix (p, p1, "syscall_return"))
7507 {
7508 ULONGEST sysno;
7509
7510 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7511 p = unpack_varlen_hex (++p1, &sysno);
7512 event->ws.value.syscall_number = (int) sysno;
7513 }
7514 else if (strprefix (p, p1, "watch")
7515 || strprefix (p, p1, "rwatch")
7516 || strprefix (p, p1, "awatch"))
7517 {
7518 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7519 p = unpack_varlen_hex (++p1, &addr);
7520 event->watch_data_address = (CORE_ADDR) addr;
7521 }
7522 else if (strprefix (p, p1, "swbreak"))
7523 {
7524 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7525
7526 /* Make sure the stub doesn't forget to indicate support
7527 with qSupported. */
7528 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7529 error (_("Unexpected swbreak stop reason"));
7530
7531 /* The value part is documented as "must be empty",
7532 though we ignore it, in case we ever decide to make
7533 use of it in a backward compatible way. */
7534 p = strchrnul (p1 + 1, ';');
7535 }
7536 else if (strprefix (p, p1, "hwbreak"))
7537 {
7538 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7539
7540 /* Make sure the stub doesn't forget to indicate support
7541 with qSupported. */
7542 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7543 error (_("Unexpected hwbreak stop reason"));
7544
7545 /* See above. */
7546 p = strchrnul (p1 + 1, ';');
7547 }
7548 else if (strprefix (p, p1, "library"))
7549 {
7550 event->ws.kind = TARGET_WAITKIND_LOADED;
7551 p = strchrnul (p1 + 1, ';');
7552 }
7553 else if (strprefix (p, p1, "replaylog"))
7554 {
7555 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7556 /* p1 will indicate "begin" or "end", but it makes
7557 no difference for now, so ignore it. */
7558 p = strchrnul (p1 + 1, ';');
7559 }
7560 else if (strprefix (p, p1, "core"))
7561 {
7562 ULONGEST c;
7563
7564 p = unpack_varlen_hex (++p1, &c);
7565 event->core = c;
7566 }
7567 else if (strprefix (p, p1, "fork"))
7568 {
7569 event->ws.value.related_pid = read_ptid (++p1, &p);
7570 event->ws.kind = TARGET_WAITKIND_FORKED;
7571 }
7572 else if (strprefix (p, p1, "vfork"))
7573 {
7574 event->ws.value.related_pid = read_ptid (++p1, &p);
7575 event->ws.kind = TARGET_WAITKIND_VFORKED;
7576 }
7577 else if (strprefix (p, p1, "vforkdone"))
7578 {
7579 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7580 p = strchrnul (p1 + 1, ';');
7581 }
7582 else if (strprefix (p, p1, "exec"))
7583 {
7584 ULONGEST ignored;
7585 int pathlen;
7586
7587 /* Determine the length of the execd pathname. */
7588 p = unpack_varlen_hex (++p1, &ignored);
7589 pathlen = (p - p1) / 2;
7590
7591 /* Save the pathname for event reporting and for
7592 the next run command. */
7593 gdb::unique_xmalloc_ptr<char[]> pathname
7594 ((char *) xmalloc (pathlen + 1));
7595 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7596 pathname[pathlen] = '\0';
7597
7598 /* This is freed during event handling. */
7599 event->ws.value.execd_pathname = pathname.release ();
7600 event->ws.kind = TARGET_WAITKIND_EXECD;
7601
7602 /* Skip the registers included in this packet, since
7603 they may be for an architecture different from the
7604 one used by the original program. */
7605 skipregs = 1;
7606 }
7607 else if (strprefix (p, p1, "create"))
7608 {
7609 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7610 p = strchrnul (p1 + 1, ';');
7611 }
7612 else
7613 {
7614 ULONGEST pnum;
7615 const char *p_temp;
7616
7617 if (skipregs)
7618 {
7619 p = strchrnul (p1 + 1, ';');
7620 p++;
7621 continue;
7622 }
7623
7624 /* Maybe a real ``P'' register number. */
7625 p_temp = unpack_varlen_hex (p, &pnum);
7626 /* If the first invalid character is the colon, we got a
7627 register number. Otherwise, it's an unknown stop
7628 reason. */
7629 if (p_temp == p1)
7630 {
7631 /* If we haven't parsed the event's thread yet, find
7632 it now, in order to find the architecture of the
7633 reported expedited registers. */
7634 if (event->ptid == null_ptid)
7635 {
7636 /* If there is no thread-id information then leave
7637 the event->ptid as null_ptid. Later in
7638 process_stop_reply we will pick a suitable
7639 thread. */
7640 const char *thr = strstr (p1 + 1, ";thread:");
7641 if (thr != NULL)
7642 event->ptid = read_ptid (thr + strlen (";thread:"),
7643 NULL);
7644 }
7645
7646 if (rsa == NULL)
7647 {
7648 inferior *inf
7649 = (event->ptid == null_ptid
7650 ? NULL
7651 : find_inferior_ptid (this, event->ptid));
7652 /* If this is the first time we learn anything
7653 about this process, skip the registers
7654 included in this packet, since we don't yet
7655 know which architecture to use to parse them.
7656 We'll determine the architecture later when
7657 we process the stop reply and retrieve the
7658 target description, via
7659 remote_notice_new_inferior ->
7660 post_create_inferior. */
7661 if (inf == NULL)
7662 {
7663 p = strchrnul (p1 + 1, ';');
7664 p++;
7665 continue;
7666 }
7667
7668 event->arch = inf->gdbarch;
7669 rsa = event->rs->get_remote_arch_state (event->arch);
7670 }
7671
7672 packet_reg *reg
7673 = packet_reg_from_pnum (event->arch, rsa, pnum);
7674 cached_reg_t cached_reg;
7675
7676 if (reg == NULL)
7677 error (_("Remote sent bad register number %s: %s\n\
7678 Packet: '%s'\n"),
7679 hex_string (pnum), p, buf);
7680
7681 cached_reg.num = reg->regnum;
7682 cached_reg.data = (gdb_byte *)
7683 xmalloc (register_size (event->arch, reg->regnum));
7684
7685 p = p1 + 1;
7686 fieldsize = hex2bin (p, cached_reg.data,
7687 register_size (event->arch, reg->regnum));
7688 p += 2 * fieldsize;
7689 if (fieldsize < register_size (event->arch, reg->regnum))
7690 warning (_("Remote reply is too short: %s"), buf);
7691
7692 event->regcache.push_back (cached_reg);
7693 }
7694 else
7695 {
7696 /* Not a number. Silently skip unknown optional
7697 info. */
7698 p = strchrnul (p1 + 1, ';');
7699 }
7700 }
7701
7702 if (*p != ';')
7703 error (_("Remote register badly formatted: %s\nhere: %s"),
7704 buf, p);
7705 ++p;
7706 }
7707
7708 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7709 break;
7710
7711 /* fall through */
7712 case 'S': /* Old style status, just signal only. */
7713 {
7714 int sig;
7715
7716 event->ws.kind = TARGET_WAITKIND_STOPPED;
7717 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7718 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7719 event->ws.value.sig = (enum gdb_signal) sig;
7720 else
7721 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7722 }
7723 break;
7724 case 'w': /* Thread exited. */
7725 {
7726 ULONGEST value;
7727
7728 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7729 p = unpack_varlen_hex (&buf[1], &value);
7730 event->ws.value.integer = value;
7731 if (*p != ';')
7732 error (_("stop reply packet badly formatted: %s"), buf);
7733 event->ptid = read_ptid (++p, NULL);
7734 break;
7735 }
7736 case 'W': /* Target exited. */
7737 case 'X':
7738 {
7739 ULONGEST value;
7740
7741 /* GDB used to accept only 2 hex chars here. Stubs should
7742 only send more if they detect GDB supports multi-process
7743 support. */
7744 p = unpack_varlen_hex (&buf[1], &value);
7745
7746 if (buf[0] == 'W')
7747 {
7748 /* The remote process exited. */
7749 event->ws.kind = TARGET_WAITKIND_EXITED;
7750 event->ws.value.integer = value;
7751 }
7752 else
7753 {
7754 /* The remote process exited with a signal. */
7755 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7756 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7757 event->ws.value.sig = (enum gdb_signal) value;
7758 else
7759 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7760 }
7761
7762 /* If no process is specified, return null_ptid, and let the
7763 caller figure out the right process to use. */
7764 int pid = 0;
7765 if (*p == '\0')
7766 ;
7767 else if (*p == ';')
7768 {
7769 p++;
7770
7771 if (*p == '\0')
7772 ;
7773 else if (startswith (p, "process:"))
7774 {
7775 ULONGEST upid;
7776
7777 p += sizeof ("process:") - 1;
7778 unpack_varlen_hex (p, &upid);
7779 pid = upid;
7780 }
7781 else
7782 error (_("unknown stop reply packet: %s"), buf);
7783 }
7784 else
7785 error (_("unknown stop reply packet: %s"), buf);
7786 event->ptid = ptid_t (pid);
7787 }
7788 break;
7789 case 'N':
7790 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7791 event->ptid = minus_one_ptid;
7792 break;
7793 }
7794 }
7795
7796 /* When the stub wants to tell GDB about a new notification reply, it
7797 sends a notification (%Stop, for example). Those can come it at
7798 any time, hence, we have to make sure that any pending
7799 putpkt/getpkt sequence we're making is finished, before querying
7800 the stub for more events with the corresponding ack command
7801 (vStopped, for example). E.g., if we started a vStopped sequence
7802 immediately upon receiving the notification, something like this
7803 could happen:
7804
7805 1.1) --> Hg 1
7806 1.2) <-- OK
7807 1.3) --> g
7808 1.4) <-- %Stop
7809 1.5) --> vStopped
7810 1.6) <-- (registers reply to step #1.3)
7811
7812 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7813 query.
7814
7815 To solve this, whenever we parse a %Stop notification successfully,
7816 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7817 doing whatever we were doing:
7818
7819 2.1) --> Hg 1
7820 2.2) <-- OK
7821 2.3) --> g
7822 2.4) <-- %Stop
7823 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7824 2.5) <-- (registers reply to step #2.3)
7825
7826 Eventually after step #2.5, we return to the event loop, which
7827 notices there's an event on the
7828 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7829 associated callback --- the function below. At this point, we're
7830 always safe to start a vStopped sequence. :
7831
7832 2.6) --> vStopped
7833 2.7) <-- T05 thread:2
7834 2.8) --> vStopped
7835 2.9) --> OK
7836 */
7837
7838 void
7839 remote_target::remote_notif_get_pending_events (notif_client *nc)
7840 {
7841 struct remote_state *rs = get_remote_state ();
7842
7843 if (rs->notif_state->pending_event[nc->id] != NULL)
7844 {
7845 if (notif_debug)
7846 fprintf_unfiltered (gdb_stdlog,
7847 "notif: process: '%s' ack pending event\n",
7848 nc->name);
7849
7850 /* acknowledge */
7851 nc->ack (this, nc, rs->buf.data (),
7852 rs->notif_state->pending_event[nc->id]);
7853 rs->notif_state->pending_event[nc->id] = NULL;
7854
7855 while (1)
7856 {
7857 getpkt (&rs->buf, 0);
7858 if (strcmp (rs->buf.data (), "OK") == 0)
7859 break;
7860 else
7861 remote_notif_ack (this, nc, rs->buf.data ());
7862 }
7863 }
7864 else
7865 {
7866 if (notif_debug)
7867 fprintf_unfiltered (gdb_stdlog,
7868 "notif: process: '%s' no pending reply\n",
7869 nc->name);
7870 }
7871 }
7872
7873 /* Wrapper around remote_target::remote_notif_get_pending_events to
7874 avoid having to export the whole remote_target class. */
7875
7876 void
7877 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7878 {
7879 remote->remote_notif_get_pending_events (nc);
7880 }
7881
7882 /* Called from process_stop_reply when the stop packet we are responding
7883 to didn't include a process-id or thread-id. STATUS is the stop event
7884 we are responding to.
7885
7886 It is the task of this function to select a suitable thread (or process)
7887 and return its ptid, this is the thread (or process) we will assume the
7888 stop event came from.
7889
7890 In some cases there isn't really any choice about which thread (or
7891 process) is selected, a basic remote with a single process containing a
7892 single thread might choose not to send any process-id or thread-id in
7893 its stop packets, this function will select and return the one and only
7894 thread.
7895
7896 However, if a target supports multiple threads (or processes) and still
7897 doesn't include a thread-id (or process-id) in its stop packet then
7898 first, this is a badly behaving target, and second, we're going to have
7899 to select a thread (or process) at random and use that. This function
7900 will print a warning to the user if it detects that there is the
7901 possibility that GDB is guessing which thread (or process) to
7902 report.
7903
7904 Note that this is called before GDB fetches the updated thread list from the
7905 target. So it's possible for the stop reply to be ambiguous and for GDB to
7906 not realize it. For example, if there's initially one thread, the target
7907 spawns a second thread, and then sends a stop reply without an id that
7908 concerns the first thread. GDB will assume the stop reply is about the
7909 first thread - the only thread it knows about - without printing a warning.
7910 Anyway, if the remote meant for the stop reply to be about the second thread,
7911 then it would be really broken, because GDB doesn't know about that thread
7912 yet. */
7913
7914 ptid_t
7915 remote_target::select_thread_for_ambiguous_stop_reply
7916 (const struct target_waitstatus *status)
7917 {
7918 /* Some stop events apply to all threads in an inferior, while others
7919 only apply to a single thread. */
7920 bool process_wide_stop
7921 = (status->kind == TARGET_WAITKIND_EXITED
7922 || status->kind == TARGET_WAITKIND_SIGNALLED);
7923
7924 thread_info *first_resumed_thread = nullptr;
7925 bool ambiguous = false;
7926
7927 /* Consider all non-exited threads of the target, find the first resumed
7928 one. */
7929 for (thread_info *thr : all_non_exited_threads (this))
7930 {
7931 remote_thread_info *remote_thr = get_remote_thread_info (thr);
7932
7933 if (remote_thr->get_resume_state () != resume_state::RESUMED)
7934 continue;
7935
7936 if (first_resumed_thread == nullptr)
7937 first_resumed_thread = thr;
7938 else if (!process_wide_stop
7939 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
7940 ambiguous = true;
7941 }
7942
7943 gdb_assert (first_resumed_thread != nullptr);
7944
7945 /* Warn if the remote target is sending ambiguous stop replies. */
7946 if (ambiguous)
7947 {
7948 static bool warned = false;
7949
7950 if (!warned)
7951 {
7952 /* If you are seeing this warning then the remote target has
7953 stopped without specifying a thread-id, but the target
7954 does have multiple threads (or inferiors), and so GDB is
7955 having to guess which thread stopped.
7956
7957 Examples of what might cause this are the target sending
7958 and 'S' stop packet, or a 'T' stop packet and not
7959 including a thread-id.
7960
7961 Additionally, the target might send a 'W' or 'X packet
7962 without including a process-id, when the target has
7963 multiple running inferiors. */
7964 if (process_wide_stop)
7965 warning (_("multi-inferior target stopped without "
7966 "sending a process-id, using first "
7967 "non-exited inferior"));
7968 else
7969 warning (_("multi-threaded target stopped without "
7970 "sending a thread-id, using first "
7971 "non-exited thread"));
7972 warned = true;
7973 }
7974 }
7975
7976 /* If this is a stop for all threads then don't use a particular threads
7977 ptid, instead create a new ptid where only the pid field is set. */
7978 if (process_wide_stop)
7979 return ptid_t (first_resumed_thread->ptid.pid ());
7980 else
7981 return first_resumed_thread->ptid;
7982 }
7983
7984 /* Called when it is decided that STOP_REPLY holds the info of the
7985 event that is to be returned to the core. This function always
7986 destroys STOP_REPLY. */
7987
7988 ptid_t
7989 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7990 struct target_waitstatus *status)
7991 {
7992 *status = stop_reply->ws;
7993 ptid_t ptid = stop_reply->ptid;
7994
7995 /* If no thread/process was reported by the stub then select a suitable
7996 thread/process. */
7997 if (ptid == null_ptid)
7998 ptid = select_thread_for_ambiguous_stop_reply (status);
7999 gdb_assert (ptid != null_ptid);
8000
8001 if (status->kind != TARGET_WAITKIND_EXITED
8002 && status->kind != TARGET_WAITKIND_SIGNALLED
8003 && status->kind != TARGET_WAITKIND_NO_RESUMED)
8004 {
8005 /* Expedited registers. */
8006 if (!stop_reply->regcache.empty ())
8007 {
8008 struct regcache *regcache
8009 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8010
8011 for (cached_reg_t &reg : stop_reply->regcache)
8012 {
8013 regcache->raw_supply (reg.num, reg.data);
8014 xfree (reg.data);
8015 }
8016
8017 stop_reply->regcache.clear ();
8018 }
8019
8020 remote_notice_new_inferior (ptid, 0);
8021 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8022 remote_thr->core = stop_reply->core;
8023 remote_thr->stop_reason = stop_reply->stop_reason;
8024 remote_thr->watch_data_address = stop_reply->watch_data_address;
8025
8026 if (target_is_non_stop_p ())
8027 {
8028 /* If the target works in non-stop mode, a stop-reply indicates that
8029 only this thread stopped. */
8030 remote_thr->set_not_resumed ();
8031 }
8032 else
8033 {
8034 /* If the target works in all-stop mode, a stop-reply indicates that
8035 all the target's threads stopped. */
8036 for (thread_info *tp : all_non_exited_threads (this))
8037 get_remote_thread_info (tp)->set_not_resumed ();
8038 }
8039 }
8040
8041 delete stop_reply;
8042 return ptid;
8043 }
8044
8045 /* The non-stop mode version of target_wait. */
8046
8047 ptid_t
8048 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8049 target_wait_flags options)
8050 {
8051 struct remote_state *rs = get_remote_state ();
8052 struct stop_reply *stop_reply;
8053 int ret;
8054 int is_notif = 0;
8055
8056 /* If in non-stop mode, get out of getpkt even if a
8057 notification is received. */
8058
8059 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8060 while (1)
8061 {
8062 if (ret != -1 && !is_notif)
8063 switch (rs->buf[0])
8064 {
8065 case 'E': /* Error of some sort. */
8066 /* We're out of sync with the target now. Did it continue
8067 or not? We can't tell which thread it was in non-stop,
8068 so just ignore this. */
8069 warning (_("Remote failure reply: %s"), rs->buf.data ());
8070 break;
8071 case 'O': /* Console output. */
8072 remote_console_output (&rs->buf[1]);
8073 break;
8074 default:
8075 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8076 break;
8077 }
8078
8079 /* Acknowledge a pending stop reply that may have arrived in the
8080 mean time. */
8081 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8082 remote_notif_get_pending_events (&notif_client_stop);
8083
8084 /* If indeed we noticed a stop reply, we're done. */
8085 stop_reply = queued_stop_reply (ptid);
8086 if (stop_reply != NULL)
8087 return process_stop_reply (stop_reply, status);
8088
8089 /* Still no event. If we're just polling for an event, then
8090 return to the event loop. */
8091 if (options & TARGET_WNOHANG)
8092 {
8093 status->kind = TARGET_WAITKIND_IGNORE;
8094 return minus_one_ptid;
8095 }
8096
8097 /* Otherwise do a blocking wait. */
8098 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8099 }
8100 }
8101
8102 /* Return the first resumed thread. */
8103
8104 static ptid_t
8105 first_remote_resumed_thread (remote_target *target)
8106 {
8107 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8108 if (tp->resumed)
8109 return tp->ptid;
8110 return null_ptid;
8111 }
8112
8113 /* Wait until the remote machine stops, then return, storing status in
8114 STATUS just as `wait' would. */
8115
8116 ptid_t
8117 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8118 target_wait_flags options)
8119 {
8120 struct remote_state *rs = get_remote_state ();
8121 ptid_t event_ptid = null_ptid;
8122 char *buf;
8123 struct stop_reply *stop_reply;
8124
8125 again:
8126
8127 status->kind = TARGET_WAITKIND_IGNORE;
8128 status->value.integer = 0;
8129
8130 stop_reply = queued_stop_reply (ptid);
8131 if (stop_reply != NULL)
8132 return process_stop_reply (stop_reply, status);
8133
8134 if (rs->cached_wait_status)
8135 /* Use the cached wait status, but only once. */
8136 rs->cached_wait_status = 0;
8137 else
8138 {
8139 int ret;
8140 int is_notif;
8141 int forever = ((options & TARGET_WNOHANG) == 0
8142 && rs->wait_forever_enabled_p);
8143
8144 if (!rs->waiting_for_stop_reply)
8145 {
8146 status->kind = TARGET_WAITKIND_NO_RESUMED;
8147 return minus_one_ptid;
8148 }
8149
8150 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8151 _never_ wait for ever -> test on target_is_async_p().
8152 However, before we do that we need to ensure that the caller
8153 knows how to take the target into/out of async mode. */
8154 ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8155
8156 /* GDB gets a notification. Return to core as this event is
8157 not interesting. */
8158 if (ret != -1 && is_notif)
8159 return minus_one_ptid;
8160
8161 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8162 return minus_one_ptid;
8163 }
8164
8165 buf = rs->buf.data ();
8166
8167 /* Assume that the target has acknowledged Ctrl-C unless we receive
8168 an 'F' or 'O' packet. */
8169 if (buf[0] != 'F' && buf[0] != 'O')
8170 rs->ctrlc_pending_p = 0;
8171
8172 switch (buf[0])
8173 {
8174 case 'E': /* Error of some sort. */
8175 /* We're out of sync with the target now. Did it continue or
8176 not? Not is more likely, so report a stop. */
8177 rs->waiting_for_stop_reply = 0;
8178
8179 warning (_("Remote failure reply: %s"), buf);
8180 status->kind = TARGET_WAITKIND_STOPPED;
8181 status->value.sig = GDB_SIGNAL_0;
8182 break;
8183 case 'F': /* File-I/O request. */
8184 /* GDB may access the inferior memory while handling the File-I/O
8185 request, but we don't want GDB accessing memory while waiting
8186 for a stop reply. See the comments in putpkt_binary. Set
8187 waiting_for_stop_reply to 0 temporarily. */
8188 rs->waiting_for_stop_reply = 0;
8189 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8190 rs->ctrlc_pending_p = 0;
8191 /* GDB handled the File-I/O request, and the target is running
8192 again. Keep waiting for events. */
8193 rs->waiting_for_stop_reply = 1;
8194 break;
8195 case 'N': case 'T': case 'S': case 'X': case 'W':
8196 {
8197 /* There is a stop reply to handle. */
8198 rs->waiting_for_stop_reply = 0;
8199
8200 stop_reply
8201 = (struct stop_reply *) remote_notif_parse (this,
8202 &notif_client_stop,
8203 rs->buf.data ());
8204
8205 event_ptid = process_stop_reply (stop_reply, status);
8206 break;
8207 }
8208 case 'O': /* Console output. */
8209 remote_console_output (buf + 1);
8210 break;
8211 case '\0':
8212 if (rs->last_sent_signal != GDB_SIGNAL_0)
8213 {
8214 /* Zero length reply means that we tried 'S' or 'C' and the
8215 remote system doesn't support it. */
8216 target_terminal::ours_for_output ();
8217 printf_filtered
8218 ("Can't send signals to this remote system. %s not sent.\n",
8219 gdb_signal_to_name (rs->last_sent_signal));
8220 rs->last_sent_signal = GDB_SIGNAL_0;
8221 target_terminal::inferior ();
8222
8223 strcpy (buf, rs->last_sent_step ? "s" : "c");
8224 putpkt (buf);
8225 break;
8226 }
8227 /* fallthrough */
8228 default:
8229 warning (_("Invalid remote reply: %s"), buf);
8230 break;
8231 }
8232
8233 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
8234 return minus_one_ptid;
8235 else if (status->kind == TARGET_WAITKIND_IGNORE)
8236 {
8237 /* Nothing interesting happened. If we're doing a non-blocking
8238 poll, we're done. Otherwise, go back to waiting. */
8239 if (options & TARGET_WNOHANG)
8240 return minus_one_ptid;
8241 else
8242 goto again;
8243 }
8244 else if (status->kind != TARGET_WAITKIND_EXITED
8245 && status->kind != TARGET_WAITKIND_SIGNALLED)
8246 {
8247 if (event_ptid != null_ptid)
8248 record_currthread (rs, event_ptid);
8249 else
8250 event_ptid = first_remote_resumed_thread (this);
8251 }
8252 else
8253 {
8254 /* A process exit. Invalidate our notion of current thread. */
8255 record_currthread (rs, minus_one_ptid);
8256 /* It's possible that the packet did not include a pid. */
8257 if (event_ptid == null_ptid)
8258 event_ptid = first_remote_resumed_thread (this);
8259 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8260 if (event_ptid == null_ptid)
8261 event_ptid = magic_null_ptid;
8262 }
8263
8264 return event_ptid;
8265 }
8266
8267 /* Wait until the remote machine stops, then return, storing status in
8268 STATUS just as `wait' would. */
8269
8270 ptid_t
8271 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8272 target_wait_flags options)
8273 {
8274 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8275
8276 remote_state *rs = get_remote_state ();
8277
8278 /* Start by clearing the flag that asks for our wait method to be called,
8279 we'll mark it again at the end if needed. */
8280 if (target_is_async_p ())
8281 clear_async_event_handler (rs->remote_async_inferior_event_token);
8282
8283 ptid_t event_ptid;
8284
8285 if (target_is_non_stop_p ())
8286 event_ptid = wait_ns (ptid, status, options);
8287 else
8288 event_ptid = wait_as (ptid, status, options);
8289
8290 if (target_is_async_p ())
8291 {
8292 /* If there are events left in the queue, or unacknowledged
8293 notifications, then tell the event loop to call us again. */
8294 if (!rs->stop_reply_queue.empty ()
8295 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8296 mark_async_event_handler (rs->remote_async_inferior_event_token);
8297 }
8298
8299 return event_ptid;
8300 }
8301
8302 /* Fetch a single register using a 'p' packet. */
8303
8304 int
8305 remote_target::fetch_register_using_p (struct regcache *regcache,
8306 packet_reg *reg)
8307 {
8308 struct gdbarch *gdbarch = regcache->arch ();
8309 struct remote_state *rs = get_remote_state ();
8310 char *buf, *p;
8311 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8312 int i;
8313
8314 if (packet_support (PACKET_p) == PACKET_DISABLE)
8315 return 0;
8316
8317 if (reg->pnum == -1)
8318 return 0;
8319
8320 p = rs->buf.data ();
8321 *p++ = 'p';
8322 p += hexnumstr (p, reg->pnum);
8323 *p++ = '\0';
8324 putpkt (rs->buf);
8325 getpkt (&rs->buf, 0);
8326
8327 buf = rs->buf.data ();
8328
8329 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8330 {
8331 case PACKET_OK:
8332 break;
8333 case PACKET_UNKNOWN:
8334 return 0;
8335 case PACKET_ERROR:
8336 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8337 gdbarch_register_name (regcache->arch (),
8338 reg->regnum),
8339 buf);
8340 }
8341
8342 /* If this register is unfetchable, tell the regcache. */
8343 if (buf[0] == 'x')
8344 {
8345 regcache->raw_supply (reg->regnum, NULL);
8346 return 1;
8347 }
8348
8349 /* Otherwise, parse and supply the value. */
8350 p = buf;
8351 i = 0;
8352 while (p[0] != 0)
8353 {
8354 if (p[1] == 0)
8355 error (_("fetch_register_using_p: early buf termination"));
8356
8357 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8358 p += 2;
8359 }
8360 regcache->raw_supply (reg->regnum, regp);
8361 return 1;
8362 }
8363
8364 /* Fetch the registers included in the target's 'g' packet. */
8365
8366 int
8367 remote_target::send_g_packet ()
8368 {
8369 struct remote_state *rs = get_remote_state ();
8370 int buf_len;
8371
8372 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8373 putpkt (rs->buf);
8374 getpkt (&rs->buf, 0);
8375 if (packet_check_result (rs->buf) == PACKET_ERROR)
8376 error (_("Could not read registers; remote failure reply '%s'"),
8377 rs->buf.data ());
8378
8379 /* We can get out of synch in various cases. If the first character
8380 in the buffer is not a hex character, assume that has happened
8381 and try to fetch another packet to read. */
8382 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8383 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8384 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8385 && rs->buf[0] != 'x') /* New: unavailable register value. */
8386 {
8387 remote_debug_printf ("Bad register packet; fetching a new packet");
8388 getpkt (&rs->buf, 0);
8389 }
8390
8391 buf_len = strlen (rs->buf.data ());
8392
8393 /* Sanity check the received packet. */
8394 if (buf_len % 2 != 0)
8395 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8396
8397 return buf_len / 2;
8398 }
8399
8400 void
8401 remote_target::process_g_packet (struct regcache *regcache)
8402 {
8403 struct gdbarch *gdbarch = regcache->arch ();
8404 struct remote_state *rs = get_remote_state ();
8405 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8406 int i, buf_len;
8407 char *p;
8408 char *regs;
8409
8410 buf_len = strlen (rs->buf.data ());
8411
8412 /* Further sanity checks, with knowledge of the architecture. */
8413 if (buf_len > 2 * rsa->sizeof_g_packet)
8414 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8415 "bytes): %s"),
8416 rsa->sizeof_g_packet, buf_len / 2,
8417 rs->buf.data ());
8418
8419 /* Save the size of the packet sent to us by the target. It is used
8420 as a heuristic when determining the max size of packets that the
8421 target can safely receive. */
8422 if (rsa->actual_register_packet_size == 0)
8423 rsa->actual_register_packet_size = buf_len;
8424
8425 /* If this is smaller than we guessed the 'g' packet would be,
8426 update our records. A 'g' reply that doesn't include a register's
8427 value implies either that the register is not available, or that
8428 the 'p' packet must be used. */
8429 if (buf_len < 2 * rsa->sizeof_g_packet)
8430 {
8431 long sizeof_g_packet = buf_len / 2;
8432
8433 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8434 {
8435 long offset = rsa->regs[i].offset;
8436 long reg_size = register_size (gdbarch, i);
8437
8438 if (rsa->regs[i].pnum == -1)
8439 continue;
8440
8441 if (offset >= sizeof_g_packet)
8442 rsa->regs[i].in_g_packet = 0;
8443 else if (offset + reg_size > sizeof_g_packet)
8444 error (_("Truncated register %d in remote 'g' packet"), i);
8445 else
8446 rsa->regs[i].in_g_packet = 1;
8447 }
8448
8449 /* Looks valid enough, we can assume this is the correct length
8450 for a 'g' packet. It's important not to adjust
8451 rsa->sizeof_g_packet if we have truncated registers otherwise
8452 this "if" won't be run the next time the method is called
8453 with a packet of the same size and one of the internal errors
8454 below will trigger instead. */
8455 rsa->sizeof_g_packet = sizeof_g_packet;
8456 }
8457
8458 regs = (char *) alloca (rsa->sizeof_g_packet);
8459
8460 /* Unimplemented registers read as all bits zero. */
8461 memset (regs, 0, rsa->sizeof_g_packet);
8462
8463 /* Reply describes registers byte by byte, each byte encoded as two
8464 hex characters. Suck them all up, then supply them to the
8465 register cacheing/storage mechanism. */
8466
8467 p = rs->buf.data ();
8468 for (i = 0; i < rsa->sizeof_g_packet; i++)
8469 {
8470 if (p[0] == 0 || p[1] == 0)
8471 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8472 internal_error (__FILE__, __LINE__,
8473 _("unexpected end of 'g' packet reply"));
8474
8475 if (p[0] == 'x' && p[1] == 'x')
8476 regs[i] = 0; /* 'x' */
8477 else
8478 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8479 p += 2;
8480 }
8481
8482 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8483 {
8484 struct packet_reg *r = &rsa->regs[i];
8485 long reg_size = register_size (gdbarch, i);
8486
8487 if (r->in_g_packet)
8488 {
8489 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8490 /* This shouldn't happen - we adjusted in_g_packet above. */
8491 internal_error (__FILE__, __LINE__,
8492 _("unexpected end of 'g' packet reply"));
8493 else if (rs->buf[r->offset * 2] == 'x')
8494 {
8495 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8496 /* The register isn't available, mark it as such (at
8497 the same time setting the value to zero). */
8498 regcache->raw_supply (r->regnum, NULL);
8499 }
8500 else
8501 regcache->raw_supply (r->regnum, regs + r->offset);
8502 }
8503 }
8504 }
8505
8506 void
8507 remote_target::fetch_registers_using_g (struct regcache *regcache)
8508 {
8509 send_g_packet ();
8510 process_g_packet (regcache);
8511 }
8512
8513 /* Make the remote selected traceframe match GDB's selected
8514 traceframe. */
8515
8516 void
8517 remote_target::set_remote_traceframe ()
8518 {
8519 int newnum;
8520 struct remote_state *rs = get_remote_state ();
8521
8522 if (rs->remote_traceframe_number == get_traceframe_number ())
8523 return;
8524
8525 /* Avoid recursion, remote_trace_find calls us again. */
8526 rs->remote_traceframe_number = get_traceframe_number ();
8527
8528 newnum = target_trace_find (tfind_number,
8529 get_traceframe_number (), 0, 0, NULL);
8530
8531 /* Should not happen. If it does, all bets are off. */
8532 if (newnum != get_traceframe_number ())
8533 warning (_("could not set remote traceframe"));
8534 }
8535
8536 void
8537 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8538 {
8539 struct gdbarch *gdbarch = regcache->arch ();
8540 struct remote_state *rs = get_remote_state ();
8541 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8542 int i;
8543
8544 set_remote_traceframe ();
8545 set_general_thread (regcache->ptid ());
8546
8547 if (regnum >= 0)
8548 {
8549 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8550
8551 gdb_assert (reg != NULL);
8552
8553 /* If this register might be in the 'g' packet, try that first -
8554 we are likely to read more than one register. If this is the
8555 first 'g' packet, we might be overly optimistic about its
8556 contents, so fall back to 'p'. */
8557 if (reg->in_g_packet)
8558 {
8559 fetch_registers_using_g (regcache);
8560 if (reg->in_g_packet)
8561 return;
8562 }
8563
8564 if (fetch_register_using_p (regcache, reg))
8565 return;
8566
8567 /* This register is not available. */
8568 regcache->raw_supply (reg->regnum, NULL);
8569
8570 return;
8571 }
8572
8573 fetch_registers_using_g (regcache);
8574
8575 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8576 if (!rsa->regs[i].in_g_packet)
8577 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8578 {
8579 /* This register is not available. */
8580 regcache->raw_supply (i, NULL);
8581 }
8582 }
8583
8584 /* Prepare to store registers. Since we may send them all (using a
8585 'G' request), we have to read out the ones we don't want to change
8586 first. */
8587
8588 void
8589 remote_target::prepare_to_store (struct regcache *regcache)
8590 {
8591 struct remote_state *rs = get_remote_state ();
8592 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8593 int i;
8594
8595 /* Make sure the entire registers array is valid. */
8596 switch (packet_support (PACKET_P))
8597 {
8598 case PACKET_DISABLE:
8599 case PACKET_SUPPORT_UNKNOWN:
8600 /* Make sure all the necessary registers are cached. */
8601 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8602 if (rsa->regs[i].in_g_packet)
8603 regcache->raw_update (rsa->regs[i].regnum);
8604 break;
8605 case PACKET_ENABLE:
8606 break;
8607 }
8608 }
8609
8610 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8611 packet was not recognized. */
8612
8613 int
8614 remote_target::store_register_using_P (const struct regcache *regcache,
8615 packet_reg *reg)
8616 {
8617 struct gdbarch *gdbarch = regcache->arch ();
8618 struct remote_state *rs = get_remote_state ();
8619 /* Try storing a single register. */
8620 char *buf = rs->buf.data ();
8621 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8622 char *p;
8623
8624 if (packet_support (PACKET_P) == PACKET_DISABLE)
8625 return 0;
8626
8627 if (reg->pnum == -1)
8628 return 0;
8629
8630 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8631 p = buf + strlen (buf);
8632 regcache->raw_collect (reg->regnum, regp);
8633 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8634 putpkt (rs->buf);
8635 getpkt (&rs->buf, 0);
8636
8637 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8638 {
8639 case PACKET_OK:
8640 return 1;
8641 case PACKET_ERROR:
8642 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8643 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8644 case PACKET_UNKNOWN:
8645 return 0;
8646 default:
8647 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8648 }
8649 }
8650
8651 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8652 contents of the register cache buffer. FIXME: ignores errors. */
8653
8654 void
8655 remote_target::store_registers_using_G (const struct regcache *regcache)
8656 {
8657 struct remote_state *rs = get_remote_state ();
8658 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8659 gdb_byte *regs;
8660 char *p;
8661
8662 /* Extract all the registers in the regcache copying them into a
8663 local buffer. */
8664 {
8665 int i;
8666
8667 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8668 memset (regs, 0, rsa->sizeof_g_packet);
8669 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8670 {
8671 struct packet_reg *r = &rsa->regs[i];
8672
8673 if (r->in_g_packet)
8674 regcache->raw_collect (r->regnum, regs + r->offset);
8675 }
8676 }
8677
8678 /* Command describes registers byte by byte,
8679 each byte encoded as two hex characters. */
8680 p = rs->buf.data ();
8681 *p++ = 'G';
8682 bin2hex (regs, p, rsa->sizeof_g_packet);
8683 putpkt (rs->buf);
8684 getpkt (&rs->buf, 0);
8685 if (packet_check_result (rs->buf) == PACKET_ERROR)
8686 error (_("Could not write registers; remote failure reply '%s'"),
8687 rs->buf.data ());
8688 }
8689
8690 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8691 of the register cache buffer. FIXME: ignores errors. */
8692
8693 void
8694 remote_target::store_registers (struct regcache *regcache, int regnum)
8695 {
8696 struct gdbarch *gdbarch = regcache->arch ();
8697 struct remote_state *rs = get_remote_state ();
8698 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8699 int i;
8700
8701 set_remote_traceframe ();
8702 set_general_thread (regcache->ptid ());
8703
8704 if (regnum >= 0)
8705 {
8706 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8707
8708 gdb_assert (reg != NULL);
8709
8710 /* Always prefer to store registers using the 'P' packet if
8711 possible; we often change only a small number of registers.
8712 Sometimes we change a larger number; we'd need help from a
8713 higher layer to know to use 'G'. */
8714 if (store_register_using_P (regcache, reg))
8715 return;
8716
8717 /* For now, don't complain if we have no way to write the
8718 register. GDB loses track of unavailable registers too
8719 easily. Some day, this may be an error. We don't have
8720 any way to read the register, either... */
8721 if (!reg->in_g_packet)
8722 return;
8723
8724 store_registers_using_G (regcache);
8725 return;
8726 }
8727
8728 store_registers_using_G (regcache);
8729
8730 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8731 if (!rsa->regs[i].in_g_packet)
8732 if (!store_register_using_P (regcache, &rsa->regs[i]))
8733 /* See above for why we do not issue an error here. */
8734 continue;
8735 }
8736 \f
8737
8738 /* Return the number of hex digits in num. */
8739
8740 static int
8741 hexnumlen (ULONGEST num)
8742 {
8743 int i;
8744
8745 for (i = 0; num != 0; i++)
8746 num >>= 4;
8747
8748 return std::max (i, 1);
8749 }
8750
8751 /* Set BUF to the minimum number of hex digits representing NUM. */
8752
8753 static int
8754 hexnumstr (char *buf, ULONGEST num)
8755 {
8756 int len = hexnumlen (num);
8757
8758 return hexnumnstr (buf, num, len);
8759 }
8760
8761
8762 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8763
8764 static int
8765 hexnumnstr (char *buf, ULONGEST num, int width)
8766 {
8767 int i;
8768
8769 buf[width] = '\0';
8770
8771 for (i = width - 1; i >= 0; i--)
8772 {
8773 buf[i] = "0123456789abcdef"[(num & 0xf)];
8774 num >>= 4;
8775 }
8776
8777 return width;
8778 }
8779
8780 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8781
8782 static CORE_ADDR
8783 remote_address_masked (CORE_ADDR addr)
8784 {
8785 unsigned int address_size = remote_address_size;
8786
8787 /* If "remoteaddresssize" was not set, default to target address size. */
8788 if (!address_size)
8789 address_size = gdbarch_addr_bit (target_gdbarch ());
8790
8791 if (address_size > 0
8792 && address_size < (sizeof (ULONGEST) * 8))
8793 {
8794 /* Only create a mask when that mask can safely be constructed
8795 in a ULONGEST variable. */
8796 ULONGEST mask = 1;
8797
8798 mask = (mask << address_size) - 1;
8799 addr &= mask;
8800 }
8801 return addr;
8802 }
8803
8804 /* Determine whether the remote target supports binary downloading.
8805 This is accomplished by sending a no-op memory write of zero length
8806 to the target at the specified address. It does not suffice to send
8807 the whole packet, since many stubs strip the eighth bit and
8808 subsequently compute a wrong checksum, which causes real havoc with
8809 remote_write_bytes.
8810
8811 NOTE: This can still lose if the serial line is not eight-bit
8812 clean. In cases like this, the user should clear "remote
8813 X-packet". */
8814
8815 void
8816 remote_target::check_binary_download (CORE_ADDR addr)
8817 {
8818 struct remote_state *rs = get_remote_state ();
8819
8820 switch (packet_support (PACKET_X))
8821 {
8822 case PACKET_DISABLE:
8823 break;
8824 case PACKET_ENABLE:
8825 break;
8826 case PACKET_SUPPORT_UNKNOWN:
8827 {
8828 char *p;
8829
8830 p = rs->buf.data ();
8831 *p++ = 'X';
8832 p += hexnumstr (p, (ULONGEST) addr);
8833 *p++ = ',';
8834 p += hexnumstr (p, (ULONGEST) 0);
8835 *p++ = ':';
8836 *p = '\0';
8837
8838 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8839 getpkt (&rs->buf, 0);
8840
8841 if (rs->buf[0] == '\0')
8842 {
8843 remote_debug_printf ("binary downloading NOT supported by target");
8844 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8845 }
8846 else
8847 {
8848 remote_debug_printf ("binary downloading supported by target");
8849 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8850 }
8851 break;
8852 }
8853 }
8854 }
8855
8856 /* Helper function to resize the payload in order to try to get a good
8857 alignment. We try to write an amount of data such that the next write will
8858 start on an address aligned on REMOTE_ALIGN_WRITES. */
8859
8860 static int
8861 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8862 {
8863 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8864 }
8865
8866 /* Write memory data directly to the remote machine.
8867 This does not inform the data cache; the data cache uses this.
8868 HEADER is the starting part of the packet.
8869 MEMADDR is the address in the remote memory space.
8870 MYADDR is the address of the buffer in our space.
8871 LEN_UNITS is the number of addressable units to write.
8872 UNIT_SIZE is the length in bytes of an addressable unit.
8873 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8874 should send data as binary ('X'), or hex-encoded ('M').
8875
8876 The function creates packet of the form
8877 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8878
8879 where encoding of <DATA> is terminated by PACKET_FORMAT.
8880
8881 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8882 are omitted.
8883
8884 Return the transferred status, error or OK (an
8885 'enum target_xfer_status' value). Save the number of addressable units
8886 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8887
8888 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8889 exchange between gdb and the stub could look like (?? in place of the
8890 checksum):
8891
8892 -> $m1000,4#??
8893 <- aaaabbbbccccdddd
8894
8895 -> $M1000,3:eeeeffffeeee#??
8896 <- OK
8897
8898 -> $m1000,4#??
8899 <- eeeeffffeeeedddd */
8900
8901 target_xfer_status
8902 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8903 const gdb_byte *myaddr,
8904 ULONGEST len_units,
8905 int unit_size,
8906 ULONGEST *xfered_len_units,
8907 char packet_format, int use_length)
8908 {
8909 struct remote_state *rs = get_remote_state ();
8910 char *p;
8911 char *plen = NULL;
8912 int plenlen = 0;
8913 int todo_units;
8914 int units_written;
8915 int payload_capacity_bytes;
8916 int payload_length_bytes;
8917
8918 if (packet_format != 'X' && packet_format != 'M')
8919 internal_error (__FILE__, __LINE__,
8920 _("remote_write_bytes_aux: bad packet format"));
8921
8922 if (len_units == 0)
8923 return TARGET_XFER_EOF;
8924
8925 payload_capacity_bytes = get_memory_write_packet_size ();
8926
8927 /* The packet buffer will be large enough for the payload;
8928 get_memory_packet_size ensures this. */
8929 rs->buf[0] = '\0';
8930
8931 /* Compute the size of the actual payload by subtracting out the
8932 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8933
8934 payload_capacity_bytes -= strlen ("$,:#NN");
8935 if (!use_length)
8936 /* The comma won't be used. */
8937 payload_capacity_bytes += 1;
8938 payload_capacity_bytes -= strlen (header);
8939 payload_capacity_bytes -= hexnumlen (memaddr);
8940
8941 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8942
8943 strcat (rs->buf.data (), header);
8944 p = rs->buf.data () + strlen (header);
8945
8946 /* Compute a best guess of the number of bytes actually transfered. */
8947 if (packet_format == 'X')
8948 {
8949 /* Best guess at number of bytes that will fit. */
8950 todo_units = std::min (len_units,
8951 (ULONGEST) payload_capacity_bytes / unit_size);
8952 if (use_length)
8953 payload_capacity_bytes -= hexnumlen (todo_units);
8954 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8955 }
8956 else
8957 {
8958 /* Number of bytes that will fit. */
8959 todo_units
8960 = std::min (len_units,
8961 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8962 if (use_length)
8963 payload_capacity_bytes -= hexnumlen (todo_units);
8964 todo_units = std::min (todo_units,
8965 (payload_capacity_bytes / unit_size) / 2);
8966 }
8967
8968 if (todo_units <= 0)
8969 internal_error (__FILE__, __LINE__,
8970 _("minimum packet size too small to write data"));
8971
8972 /* If we already need another packet, then try to align the end
8973 of this packet to a useful boundary. */
8974 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8975 todo_units = align_for_efficient_write (todo_units, memaddr);
8976
8977 /* Append "<memaddr>". */
8978 memaddr = remote_address_masked (memaddr);
8979 p += hexnumstr (p, (ULONGEST) memaddr);
8980
8981 if (use_length)
8982 {
8983 /* Append ",". */
8984 *p++ = ',';
8985
8986 /* Append the length and retain its location and size. It may need to be
8987 adjusted once the packet body has been created. */
8988 plen = p;
8989 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8990 p += plenlen;
8991 }
8992
8993 /* Append ":". */
8994 *p++ = ':';
8995 *p = '\0';
8996
8997 /* Append the packet body. */
8998 if (packet_format == 'X')
8999 {
9000 /* Binary mode. Send target system values byte by byte, in
9001 increasing byte addresses. Only escape certain critical
9002 characters. */
9003 payload_length_bytes =
9004 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9005 &units_written, payload_capacity_bytes);
9006
9007 /* If not all TODO units fit, then we'll need another packet. Make
9008 a second try to keep the end of the packet aligned. Don't do
9009 this if the packet is tiny. */
9010 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9011 {
9012 int new_todo_units;
9013
9014 new_todo_units = align_for_efficient_write (units_written, memaddr);
9015
9016 if (new_todo_units != units_written)
9017 payload_length_bytes =
9018 remote_escape_output (myaddr, new_todo_units, unit_size,
9019 (gdb_byte *) p, &units_written,
9020 payload_capacity_bytes);
9021 }
9022
9023 p += payload_length_bytes;
9024 if (use_length && units_written < todo_units)
9025 {
9026 /* Escape chars have filled up the buffer prematurely,
9027 and we have actually sent fewer units than planned.
9028 Fix-up the length field of the packet. Use the same
9029 number of characters as before. */
9030 plen += hexnumnstr (plen, (ULONGEST) units_written,
9031 plenlen);
9032 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9033 }
9034 }
9035 else
9036 {
9037 /* Normal mode: Send target system values byte by byte, in
9038 increasing byte addresses. Each byte is encoded as a two hex
9039 value. */
9040 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9041 units_written = todo_units;
9042 }
9043
9044 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9045 getpkt (&rs->buf, 0);
9046
9047 if (rs->buf[0] == 'E')
9048 return TARGET_XFER_E_IO;
9049
9050 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9051 send fewer units than we'd planned. */
9052 *xfered_len_units = (ULONGEST) units_written;
9053 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9054 }
9055
9056 /* Write memory data directly to the remote machine.
9057 This does not inform the data cache; the data cache uses this.
9058 MEMADDR is the address in the remote memory space.
9059 MYADDR is the address of the buffer in our space.
9060 LEN is the number of bytes.
9061
9062 Return the transferred status, error or OK (an
9063 'enum target_xfer_status' value). Save the number of bytes
9064 transferred in *XFERED_LEN. Only transfer a single packet. */
9065
9066 target_xfer_status
9067 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9068 ULONGEST len, int unit_size,
9069 ULONGEST *xfered_len)
9070 {
9071 const char *packet_format = NULL;
9072
9073 /* Check whether the target supports binary download. */
9074 check_binary_download (memaddr);
9075
9076 switch (packet_support (PACKET_X))
9077 {
9078 case PACKET_ENABLE:
9079 packet_format = "X";
9080 break;
9081 case PACKET_DISABLE:
9082 packet_format = "M";
9083 break;
9084 case PACKET_SUPPORT_UNKNOWN:
9085 internal_error (__FILE__, __LINE__,
9086 _("remote_write_bytes: bad internal state"));
9087 default:
9088 internal_error (__FILE__, __LINE__, _("bad switch"));
9089 }
9090
9091 return remote_write_bytes_aux (packet_format,
9092 memaddr, myaddr, len, unit_size, xfered_len,
9093 packet_format[0], 1);
9094 }
9095
9096 /* Read memory data directly from the remote machine.
9097 This does not use the data cache; the data cache uses this.
9098 MEMADDR is the address in the remote memory space.
9099 MYADDR is the address of the buffer in our space.
9100 LEN_UNITS is the number of addressable memory units to read..
9101 UNIT_SIZE is the length in bytes of an addressable unit.
9102
9103 Return the transferred status, error or OK (an
9104 'enum target_xfer_status' value). Save the number of bytes
9105 transferred in *XFERED_LEN_UNITS.
9106
9107 See the comment of remote_write_bytes_aux for an example of
9108 memory read/write exchange between gdb and the stub. */
9109
9110 target_xfer_status
9111 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9112 ULONGEST len_units,
9113 int unit_size, ULONGEST *xfered_len_units)
9114 {
9115 struct remote_state *rs = get_remote_state ();
9116 int buf_size_bytes; /* Max size of packet output buffer. */
9117 char *p;
9118 int todo_units;
9119 int decoded_bytes;
9120
9121 buf_size_bytes = get_memory_read_packet_size ();
9122 /* The packet buffer will be large enough for the payload;
9123 get_memory_packet_size ensures this. */
9124
9125 /* Number of units that will fit. */
9126 todo_units = std::min (len_units,
9127 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9128
9129 /* Construct "m"<memaddr>","<len>". */
9130 memaddr = remote_address_masked (memaddr);
9131 p = rs->buf.data ();
9132 *p++ = 'm';
9133 p += hexnumstr (p, (ULONGEST) memaddr);
9134 *p++ = ',';
9135 p += hexnumstr (p, (ULONGEST) todo_units);
9136 *p = '\0';
9137 putpkt (rs->buf);
9138 getpkt (&rs->buf, 0);
9139 if (rs->buf[0] == 'E'
9140 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9141 && rs->buf[3] == '\0')
9142 return TARGET_XFER_E_IO;
9143 /* Reply describes memory byte by byte, each byte encoded as two hex
9144 characters. */
9145 p = rs->buf.data ();
9146 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9147 /* Return what we have. Let higher layers handle partial reads. */
9148 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9149 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9150 }
9151
9152 /* Using the set of read-only target sections of remote, read live
9153 read-only memory.
9154
9155 For interface/parameters/return description see target.h,
9156 to_xfer_partial. */
9157
9158 target_xfer_status
9159 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9160 ULONGEST memaddr,
9161 ULONGEST len,
9162 int unit_size,
9163 ULONGEST *xfered_len)
9164 {
9165 const struct target_section *secp;
9166
9167 secp = target_section_by_addr (this, memaddr);
9168 if (secp != NULL
9169 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9170 {
9171 ULONGEST memend = memaddr + len;
9172
9173 const target_section_table *table = target_get_section_table (this);
9174 for (const target_section &p : *table)
9175 {
9176 if (memaddr >= p.addr)
9177 {
9178 if (memend <= p.endaddr)
9179 {
9180 /* Entire transfer is within this section. */
9181 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9182 xfered_len);
9183 }
9184 else if (memaddr >= p.endaddr)
9185 {
9186 /* This section ends before the transfer starts. */
9187 continue;
9188 }
9189 else
9190 {
9191 /* This section overlaps the transfer. Just do half. */
9192 len = p.endaddr - memaddr;
9193 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9194 xfered_len);
9195 }
9196 }
9197 }
9198 }
9199
9200 return TARGET_XFER_EOF;
9201 }
9202
9203 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9204 first if the requested memory is unavailable in traceframe.
9205 Otherwise, fall back to remote_read_bytes_1. */
9206
9207 target_xfer_status
9208 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9209 gdb_byte *myaddr, ULONGEST len, int unit_size,
9210 ULONGEST *xfered_len)
9211 {
9212 if (len == 0)
9213 return TARGET_XFER_EOF;
9214
9215 if (get_traceframe_number () != -1)
9216 {
9217 std::vector<mem_range> available;
9218
9219 /* If we fail to get the set of available memory, then the
9220 target does not support querying traceframe info, and so we
9221 attempt reading from the traceframe anyway (assuming the
9222 target implements the old QTro packet then). */
9223 if (traceframe_available_memory (&available, memaddr, len))
9224 {
9225 if (available.empty () || available[0].start != memaddr)
9226 {
9227 enum target_xfer_status res;
9228
9229 /* Don't read into the traceframe's available
9230 memory. */
9231 if (!available.empty ())
9232 {
9233 LONGEST oldlen = len;
9234
9235 len = available[0].start - memaddr;
9236 gdb_assert (len <= oldlen);
9237 }
9238
9239 /* This goes through the topmost target again. */
9240 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9241 len, unit_size, xfered_len);
9242 if (res == TARGET_XFER_OK)
9243 return TARGET_XFER_OK;
9244 else
9245 {
9246 /* No use trying further, we know some memory starting
9247 at MEMADDR isn't available. */
9248 *xfered_len = len;
9249 return (*xfered_len != 0) ?
9250 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9251 }
9252 }
9253
9254 /* Don't try to read more than how much is available, in
9255 case the target implements the deprecated QTro packet to
9256 cater for older GDBs (the target's knowledge of read-only
9257 sections may be outdated by now). */
9258 len = available[0].length;
9259 }
9260 }
9261
9262 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9263 }
9264
9265 \f
9266
9267 /* Sends a packet with content determined by the printf format string
9268 FORMAT and the remaining arguments, then gets the reply. Returns
9269 whether the packet was a success, a failure, or unknown. */
9270
9271 packet_result
9272 remote_target::remote_send_printf (const char *format, ...)
9273 {
9274 struct remote_state *rs = get_remote_state ();
9275 int max_size = get_remote_packet_size ();
9276 va_list ap;
9277
9278 va_start (ap, format);
9279
9280 rs->buf[0] = '\0';
9281 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9282
9283 va_end (ap);
9284
9285 if (size >= max_size)
9286 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
9287
9288 if (putpkt (rs->buf) < 0)
9289 error (_("Communication problem with target."));
9290
9291 rs->buf[0] = '\0';
9292 getpkt (&rs->buf, 0);
9293
9294 return packet_check_result (rs->buf);
9295 }
9296
9297 /* Flash writing can take quite some time. We'll set
9298 effectively infinite timeout for flash operations.
9299 In future, we'll need to decide on a better approach. */
9300 static const int remote_flash_timeout = 1000;
9301
9302 void
9303 remote_target::flash_erase (ULONGEST address, LONGEST length)
9304 {
9305 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9306 enum packet_result ret;
9307 scoped_restore restore_timeout
9308 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9309
9310 ret = remote_send_printf ("vFlashErase:%s,%s",
9311 phex (address, addr_size),
9312 phex (length, 4));
9313 switch (ret)
9314 {
9315 case PACKET_UNKNOWN:
9316 error (_("Remote target does not support flash erase"));
9317 case PACKET_ERROR:
9318 error (_("Error erasing flash with vFlashErase packet"));
9319 default:
9320 break;
9321 }
9322 }
9323
9324 target_xfer_status
9325 remote_target::remote_flash_write (ULONGEST address,
9326 ULONGEST length, ULONGEST *xfered_len,
9327 const gdb_byte *data)
9328 {
9329 scoped_restore restore_timeout
9330 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9331 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9332 xfered_len,'X', 0);
9333 }
9334
9335 void
9336 remote_target::flash_done ()
9337 {
9338 int ret;
9339
9340 scoped_restore restore_timeout
9341 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9342
9343 ret = remote_send_printf ("vFlashDone");
9344
9345 switch (ret)
9346 {
9347 case PACKET_UNKNOWN:
9348 error (_("Remote target does not support vFlashDone"));
9349 case PACKET_ERROR:
9350 error (_("Error finishing flash operation"));
9351 default:
9352 break;
9353 }
9354 }
9355
9356 void
9357 remote_target::files_info ()
9358 {
9359 puts_filtered ("Debugging a target over a serial line.\n");
9360 }
9361 \f
9362 /* Stuff for dealing with the packets which are part of this protocol.
9363 See comment at top of file for details. */
9364
9365 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9366 error to higher layers. Called when a serial error is detected.
9367 The exception message is STRING, followed by a colon and a blank,
9368 the system error message for errno at function entry and final dot
9369 for output compatibility with throw_perror_with_name. */
9370
9371 static void
9372 unpush_and_perror (remote_target *target, const char *string)
9373 {
9374 int saved_errno = errno;
9375
9376 remote_unpush_target (target);
9377 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9378 safe_strerror (saved_errno));
9379 }
9380
9381 /* Read a single character from the remote end. The current quit
9382 handler is overridden to avoid quitting in the middle of packet
9383 sequence, as that would break communication with the remote server.
9384 See remote_serial_quit_handler for more detail. */
9385
9386 int
9387 remote_target::readchar (int timeout)
9388 {
9389 int ch;
9390 struct remote_state *rs = get_remote_state ();
9391
9392 {
9393 scoped_restore restore_quit_target
9394 = make_scoped_restore (&curr_quit_handler_target, this);
9395 scoped_restore restore_quit
9396 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9397
9398 rs->got_ctrlc_during_io = 0;
9399
9400 ch = serial_readchar (rs->remote_desc, timeout);
9401
9402 if (rs->got_ctrlc_during_io)
9403 set_quit_flag ();
9404 }
9405
9406 if (ch >= 0)
9407 return ch;
9408
9409 switch ((enum serial_rc) ch)
9410 {
9411 case SERIAL_EOF:
9412 remote_unpush_target (this);
9413 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9414 /* no return */
9415 case SERIAL_ERROR:
9416 unpush_and_perror (this, _("Remote communication error. "
9417 "Target disconnected."));
9418 /* no return */
9419 case SERIAL_TIMEOUT:
9420 break;
9421 }
9422 return ch;
9423 }
9424
9425 /* Wrapper for serial_write that closes the target and throws if
9426 writing fails. The current quit handler is overridden to avoid
9427 quitting in the middle of packet sequence, as that would break
9428 communication with the remote server. See
9429 remote_serial_quit_handler for more detail. */
9430
9431 void
9432 remote_target::remote_serial_write (const char *str, int len)
9433 {
9434 struct remote_state *rs = get_remote_state ();
9435
9436 scoped_restore restore_quit_target
9437 = make_scoped_restore (&curr_quit_handler_target, this);
9438 scoped_restore restore_quit
9439 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9440
9441 rs->got_ctrlc_during_io = 0;
9442
9443 if (serial_write (rs->remote_desc, str, len))
9444 {
9445 unpush_and_perror (this, _("Remote communication error. "
9446 "Target disconnected."));
9447 }
9448
9449 if (rs->got_ctrlc_during_io)
9450 set_quit_flag ();
9451 }
9452
9453 /* Return a string representing an escaped version of BUF, of len N.
9454 E.g. \n is converted to \\n, \t to \\t, etc. */
9455
9456 static std::string
9457 escape_buffer (const char *buf, int n)
9458 {
9459 string_file stb;
9460
9461 stb.putstrn (buf, n, '\\');
9462 return std::move (stb.string ());
9463 }
9464
9465 /* Display a null-terminated packet on stdout, for debugging, using C
9466 string notation. */
9467
9468 static void
9469 print_packet (const char *buf)
9470 {
9471 puts_filtered ("\"");
9472 fputstr_filtered (buf, '"', gdb_stdout);
9473 puts_filtered ("\"");
9474 }
9475
9476 int
9477 remote_target::putpkt (const char *buf)
9478 {
9479 return putpkt_binary (buf, strlen (buf));
9480 }
9481
9482 /* Wrapper around remote_target::putpkt to avoid exporting
9483 remote_target. */
9484
9485 int
9486 putpkt (remote_target *remote, const char *buf)
9487 {
9488 return remote->putpkt (buf);
9489 }
9490
9491 /* Send a packet to the remote machine, with error checking. The data
9492 of the packet is in BUF. The string in BUF can be at most
9493 get_remote_packet_size () - 5 to account for the $, # and checksum,
9494 and for a possible /0 if we are debugging (remote_debug) and want
9495 to print the sent packet as a string. */
9496
9497 int
9498 remote_target::putpkt_binary (const char *buf, int cnt)
9499 {
9500 struct remote_state *rs = get_remote_state ();
9501 int i;
9502 unsigned char csum = 0;
9503 gdb::def_vector<char> data (cnt + 6);
9504 char *buf2 = data.data ();
9505
9506 int ch;
9507 int tcount = 0;
9508 char *p;
9509
9510 /* Catch cases like trying to read memory or listing threads while
9511 we're waiting for a stop reply. The remote server wouldn't be
9512 ready to handle this request, so we'd hang and timeout. We don't
9513 have to worry about this in synchronous mode, because in that
9514 case it's not possible to issue a command while the target is
9515 running. This is not a problem in non-stop mode, because in that
9516 case, the stub is always ready to process serial input. */
9517 if (!target_is_non_stop_p ()
9518 && target_is_async_p ()
9519 && rs->waiting_for_stop_reply)
9520 {
9521 error (_("Cannot execute this command while the target is running.\n"
9522 "Use the \"interrupt\" command to stop the target\n"
9523 "and then try again."));
9524 }
9525
9526 /* We're sending out a new packet. Make sure we don't look at a
9527 stale cached response. */
9528 rs->cached_wait_status = 0;
9529
9530 /* Copy the packet into buffer BUF2, encapsulating it
9531 and giving it a checksum. */
9532
9533 p = buf2;
9534 *p++ = '$';
9535
9536 for (i = 0; i < cnt; i++)
9537 {
9538 csum += buf[i];
9539 *p++ = buf[i];
9540 }
9541 *p++ = '#';
9542 *p++ = tohex ((csum >> 4) & 0xf);
9543 *p++ = tohex (csum & 0xf);
9544
9545 /* Send it over and over until we get a positive ack. */
9546
9547 while (1)
9548 {
9549 if (remote_debug)
9550 {
9551 *p = '\0';
9552
9553 int len = (int) (p - buf2);
9554 int max_chars;
9555
9556 if (remote_packet_max_chars < 0)
9557 max_chars = len;
9558 else
9559 max_chars = remote_packet_max_chars;
9560
9561 std::string str
9562 = escape_buffer (buf2, std::min (len, max_chars));
9563
9564 if (len > max_chars)
9565 remote_debug_printf_nofunc
9566 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9567 len - max_chars);
9568 else
9569 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9570 }
9571 remote_serial_write (buf2, p - buf2);
9572
9573 /* If this is a no acks version of the remote protocol, send the
9574 packet and move on. */
9575 if (rs->noack_mode)
9576 break;
9577
9578 /* Read until either a timeout occurs (-2) or '+' is read.
9579 Handle any notification that arrives in the mean time. */
9580 while (1)
9581 {
9582 ch = readchar (remote_timeout);
9583
9584 switch (ch)
9585 {
9586 case '+':
9587 remote_debug_printf_nofunc ("Received Ack");
9588 return 1;
9589 case '-':
9590 remote_debug_printf_nofunc ("Received Nak");
9591 /* FALLTHROUGH */
9592 case SERIAL_TIMEOUT:
9593 tcount++;
9594 if (tcount > 3)
9595 return 0;
9596 break; /* Retransmit buffer. */
9597 case '$':
9598 {
9599 remote_debug_printf ("Packet instead of Ack, ignoring it");
9600 /* It's probably an old response sent because an ACK
9601 was lost. Gobble up the packet and ack it so it
9602 doesn't get retransmitted when we resend this
9603 packet. */
9604 skip_frame ();
9605 remote_serial_write ("+", 1);
9606 continue; /* Now, go look for +. */
9607 }
9608
9609 case '%':
9610 {
9611 int val;
9612
9613 /* If we got a notification, handle it, and go back to looking
9614 for an ack. */
9615 /* We've found the start of a notification. Now
9616 collect the data. */
9617 val = read_frame (&rs->buf);
9618 if (val >= 0)
9619 {
9620 remote_debug_printf_nofunc
9621 (" Notification received: %s",
9622 escape_buffer (rs->buf.data (), val).c_str ());
9623
9624 handle_notification (rs->notif_state, rs->buf.data ());
9625 /* We're in sync now, rewait for the ack. */
9626 tcount = 0;
9627 }
9628 else
9629 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9630 rs->buf.data ());
9631 continue;
9632 }
9633 /* fall-through */
9634 default:
9635 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9636 rs->buf.data ());
9637 continue;
9638 }
9639 break; /* Here to retransmit. */
9640 }
9641
9642 #if 0
9643 /* This is wrong. If doing a long backtrace, the user should be
9644 able to get out next time we call QUIT, without anything as
9645 violent as interrupt_query. If we want to provide a way out of
9646 here without getting to the next QUIT, it should be based on
9647 hitting ^C twice as in remote_wait. */
9648 if (quit_flag)
9649 {
9650 quit_flag = 0;
9651 interrupt_query ();
9652 }
9653 #endif
9654 }
9655
9656 return 0;
9657 }
9658
9659 /* Come here after finding the start of a frame when we expected an
9660 ack. Do our best to discard the rest of this packet. */
9661
9662 void
9663 remote_target::skip_frame ()
9664 {
9665 int c;
9666
9667 while (1)
9668 {
9669 c = readchar (remote_timeout);
9670 switch (c)
9671 {
9672 case SERIAL_TIMEOUT:
9673 /* Nothing we can do. */
9674 return;
9675 case '#':
9676 /* Discard the two bytes of checksum and stop. */
9677 c = readchar (remote_timeout);
9678 if (c >= 0)
9679 c = readchar (remote_timeout);
9680
9681 return;
9682 case '*': /* Run length encoding. */
9683 /* Discard the repeat count. */
9684 c = readchar (remote_timeout);
9685 if (c < 0)
9686 return;
9687 break;
9688 default:
9689 /* A regular character. */
9690 break;
9691 }
9692 }
9693 }
9694
9695 /* Come here after finding the start of the frame. Collect the rest
9696 into *BUF, verifying the checksum, length, and handling run-length
9697 compression. NUL terminate the buffer. If there is not enough room,
9698 expand *BUF.
9699
9700 Returns -1 on error, number of characters in buffer (ignoring the
9701 trailing NULL) on success. (could be extended to return one of the
9702 SERIAL status indications). */
9703
9704 long
9705 remote_target::read_frame (gdb::char_vector *buf_p)
9706 {
9707 unsigned char csum;
9708 long bc;
9709 int c;
9710 char *buf = buf_p->data ();
9711 struct remote_state *rs = get_remote_state ();
9712
9713 csum = 0;
9714 bc = 0;
9715
9716 while (1)
9717 {
9718 c = readchar (remote_timeout);
9719 switch (c)
9720 {
9721 case SERIAL_TIMEOUT:
9722 remote_debug_printf ("Timeout in mid-packet, retrying");
9723 return -1;
9724
9725 case '$':
9726 remote_debug_printf ("Saw new packet start in middle of old one");
9727 return -1; /* Start a new packet, count retries. */
9728
9729 case '#':
9730 {
9731 unsigned char pktcsum;
9732 int check_0 = 0;
9733 int check_1 = 0;
9734
9735 buf[bc] = '\0';
9736
9737 check_0 = readchar (remote_timeout);
9738 if (check_0 >= 0)
9739 check_1 = readchar (remote_timeout);
9740
9741 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9742 {
9743 remote_debug_printf ("Timeout in checksum, retrying");
9744 return -1;
9745 }
9746 else if (check_0 < 0 || check_1 < 0)
9747 {
9748 remote_debug_printf ("Communication error in checksum");
9749 return -1;
9750 }
9751
9752 /* Don't recompute the checksum; with no ack packets we
9753 don't have any way to indicate a packet retransmission
9754 is necessary. */
9755 if (rs->noack_mode)
9756 return bc;
9757
9758 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9759 if (csum == pktcsum)
9760 return bc;
9761
9762 remote_debug_printf
9763 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9764 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9765
9766 /* Number of characters in buffer ignoring trailing
9767 NULL. */
9768 return -1;
9769 }
9770 case '*': /* Run length encoding. */
9771 {
9772 int repeat;
9773
9774 csum += c;
9775 c = readchar (remote_timeout);
9776 csum += c;
9777 repeat = c - ' ' + 3; /* Compute repeat count. */
9778
9779 /* The character before ``*'' is repeated. */
9780
9781 if (repeat > 0 && repeat <= 255 && bc > 0)
9782 {
9783 if (bc + repeat - 1 >= buf_p->size () - 1)
9784 {
9785 /* Make some more room in the buffer. */
9786 buf_p->resize (buf_p->size () + repeat);
9787 buf = buf_p->data ();
9788 }
9789
9790 memset (&buf[bc], buf[bc - 1], repeat);
9791 bc += repeat;
9792 continue;
9793 }
9794
9795 buf[bc] = '\0';
9796 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9797 return -1;
9798 }
9799 default:
9800 if (bc >= buf_p->size () - 1)
9801 {
9802 /* Make some more room in the buffer. */
9803 buf_p->resize (buf_p->size () * 2);
9804 buf = buf_p->data ();
9805 }
9806
9807 buf[bc++] = c;
9808 csum += c;
9809 continue;
9810 }
9811 }
9812 }
9813
9814 /* Set this to the maximum number of seconds to wait instead of waiting forever
9815 in target_wait(). If this timer times out, then it generates an error and
9816 the command is aborted. This replaces most of the need for timeouts in the
9817 GDB test suite, and makes it possible to distinguish between a hung target
9818 and one with slow communications. */
9819
9820 static int watchdog = 0;
9821 static void
9822 show_watchdog (struct ui_file *file, int from_tty,
9823 struct cmd_list_element *c, const char *value)
9824 {
9825 fprintf_filtered (file, _("Watchdog timer is %s.\n"), value);
9826 }
9827
9828 /* Read a packet from the remote machine, with error checking, and
9829 store it in *BUF. Resize *BUF if necessary to hold the result. If
9830 FOREVER, wait forever rather than timing out; this is used (in
9831 synchronous mode) to wait for a target that is is executing user
9832 code to stop. */
9833 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9834 don't have to change all the calls to getpkt to deal with the
9835 return value, because at the moment I don't know what the right
9836 thing to do it for those. */
9837
9838 void
9839 remote_target::getpkt (gdb::char_vector *buf, int forever)
9840 {
9841 getpkt_sane (buf, forever);
9842 }
9843
9844
9845 /* Read a packet from the remote machine, with error checking, and
9846 store it in *BUF. Resize *BUF if necessary to hold the result. If
9847 FOREVER, wait forever rather than timing out; this is used (in
9848 synchronous mode) to wait for a target that is is executing user
9849 code to stop. If FOREVER == 0, this function is allowed to time
9850 out gracefully and return an indication of this to the caller.
9851 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9852 consider receiving a notification enough reason to return to the
9853 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9854 holds a notification or not (a regular packet). */
9855
9856 int
9857 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9858 int forever, int expecting_notif,
9859 int *is_notif)
9860 {
9861 struct remote_state *rs = get_remote_state ();
9862 int c;
9863 int tries;
9864 int timeout;
9865 int val = -1;
9866
9867 /* We're reading a new response. Make sure we don't look at a
9868 previously cached response. */
9869 rs->cached_wait_status = 0;
9870
9871 strcpy (buf->data (), "timeout");
9872
9873 if (forever)
9874 timeout = watchdog > 0 ? watchdog : -1;
9875 else if (expecting_notif)
9876 timeout = 0; /* There should already be a char in the buffer. If
9877 not, bail out. */
9878 else
9879 timeout = remote_timeout;
9880
9881 #define MAX_TRIES 3
9882
9883 /* Process any number of notifications, and then return when
9884 we get a packet. */
9885 for (;;)
9886 {
9887 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9888 times. */
9889 for (tries = 1; tries <= MAX_TRIES; tries++)
9890 {
9891 /* This can loop forever if the remote side sends us
9892 characters continuously, but if it pauses, we'll get
9893 SERIAL_TIMEOUT from readchar because of timeout. Then
9894 we'll count that as a retry.
9895
9896 Note that even when forever is set, we will only wait
9897 forever prior to the start of a packet. After that, we
9898 expect characters to arrive at a brisk pace. They should
9899 show up within remote_timeout intervals. */
9900 do
9901 c = readchar (timeout);
9902 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9903
9904 if (c == SERIAL_TIMEOUT)
9905 {
9906 if (expecting_notif)
9907 return -1; /* Don't complain, it's normal to not get
9908 anything in this case. */
9909
9910 if (forever) /* Watchdog went off? Kill the target. */
9911 {
9912 remote_unpush_target (this);
9913 throw_error (TARGET_CLOSE_ERROR,
9914 _("Watchdog timeout has expired. "
9915 "Target detached."));
9916 }
9917
9918 remote_debug_printf ("Timed out.");
9919 }
9920 else
9921 {
9922 /* We've found the start of a packet or notification.
9923 Now collect the data. */
9924 val = read_frame (buf);
9925 if (val >= 0)
9926 break;
9927 }
9928
9929 remote_serial_write ("-", 1);
9930 }
9931
9932 if (tries > MAX_TRIES)
9933 {
9934 /* We have tried hard enough, and just can't receive the
9935 packet/notification. Give up. */
9936 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9937
9938 /* Skip the ack char if we're in no-ack mode. */
9939 if (!rs->noack_mode)
9940 remote_serial_write ("+", 1);
9941 return -1;
9942 }
9943
9944 /* If we got an ordinary packet, return that to our caller. */
9945 if (c == '$')
9946 {
9947 if (remote_debug)
9948 {
9949 int max_chars;
9950
9951 if (remote_packet_max_chars < 0)
9952 max_chars = val;
9953 else
9954 max_chars = remote_packet_max_chars;
9955
9956 std::string str
9957 = escape_buffer (buf->data (),
9958 std::min (val, max_chars));
9959
9960 if (val > max_chars)
9961 remote_debug_printf_nofunc
9962 ("Packet received: %s [%d bytes omitted]", str.c_str (),
9963 val - max_chars);
9964 else
9965 remote_debug_printf_nofunc ("Packet received: %s",
9966 str.c_str ());
9967 }
9968
9969 /* Skip the ack char if we're in no-ack mode. */
9970 if (!rs->noack_mode)
9971 remote_serial_write ("+", 1);
9972 if (is_notif != NULL)
9973 *is_notif = 0;
9974 return val;
9975 }
9976
9977 /* If we got a notification, handle it, and go back to looking
9978 for a packet. */
9979 else
9980 {
9981 gdb_assert (c == '%');
9982
9983 remote_debug_printf_nofunc
9984 (" Notification received: %s",
9985 escape_buffer (buf->data (), val).c_str ());
9986
9987 if (is_notif != NULL)
9988 *is_notif = 1;
9989
9990 handle_notification (rs->notif_state, buf->data ());
9991
9992 /* Notifications require no acknowledgement. */
9993
9994 if (expecting_notif)
9995 return val;
9996 }
9997 }
9998 }
9999
10000 int
10001 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10002 {
10003 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10004 }
10005
10006 int
10007 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10008 int *is_notif)
10009 {
10010 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10011 }
10012
10013 /* Kill any new fork children of process PID that haven't been
10014 processed by follow_fork. */
10015
10016 void
10017 remote_target::kill_new_fork_children (int pid)
10018 {
10019 remote_state *rs = get_remote_state ();
10020 struct notif_client *notif = &notif_client_stop;
10021
10022 /* Kill the fork child threads of any threads in process PID
10023 that are stopped at a fork event. */
10024 for (thread_info *thread : all_non_exited_threads (this))
10025 {
10026 struct target_waitstatus *ws = &thread->pending_follow;
10027
10028 if (is_pending_fork_parent (ws, pid, thread->ptid))
10029 {
10030 int child_pid = ws->value.related_pid.pid ();
10031 int res;
10032
10033 res = remote_vkill (child_pid);
10034 if (res != 0)
10035 error (_("Can't kill fork child process %d"), child_pid);
10036 }
10037 }
10038
10039 /* Check for any pending fork events (not reported or processed yet)
10040 in process PID and kill those fork child threads as well. */
10041 remote_notif_get_pending_events (notif);
10042 for (auto &event : rs->stop_reply_queue)
10043 if (is_pending_fork_parent (&event->ws, pid, event->ptid))
10044 {
10045 int child_pid = event->ws.value.related_pid.pid ();
10046 int res;
10047
10048 res = remote_vkill (child_pid);
10049 if (res != 0)
10050 error (_("Can't kill fork child process %d"), child_pid);
10051 }
10052 }
10053
10054 \f
10055 /* Target hook to kill the current inferior. */
10056
10057 void
10058 remote_target::kill ()
10059 {
10060 int res = -1;
10061 int pid = inferior_ptid.pid ();
10062 struct remote_state *rs = get_remote_state ();
10063
10064 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
10065 {
10066 /* If we're stopped while forking and we haven't followed yet,
10067 kill the child task. We need to do this before killing the
10068 parent task because if this is a vfork then the parent will
10069 be sleeping. */
10070 kill_new_fork_children (pid);
10071
10072 res = remote_vkill (pid);
10073 if (res == 0)
10074 {
10075 target_mourn_inferior (inferior_ptid);
10076 return;
10077 }
10078 }
10079
10080 /* If we are in 'target remote' mode and we are killing the only
10081 inferior, then we will tell gdbserver to exit and unpush the
10082 target. */
10083 if (res == -1 && !remote_multi_process_p (rs)
10084 && number_of_live_inferiors (this) == 1)
10085 {
10086 remote_kill_k ();
10087
10088 /* We've killed the remote end, we get to mourn it. If we are
10089 not in extended mode, mourning the inferior also unpushes
10090 remote_ops from the target stack, which closes the remote
10091 connection. */
10092 target_mourn_inferior (inferior_ptid);
10093
10094 return;
10095 }
10096
10097 error (_("Can't kill process"));
10098 }
10099
10100 /* Send a kill request to the target using the 'vKill' packet. */
10101
10102 int
10103 remote_target::remote_vkill (int pid)
10104 {
10105 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10106 return -1;
10107
10108 remote_state *rs = get_remote_state ();
10109
10110 /* Tell the remote target to detach. */
10111 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10112 putpkt (rs->buf);
10113 getpkt (&rs->buf, 0);
10114
10115 switch (packet_ok (rs->buf,
10116 &remote_protocol_packets[PACKET_vKill]))
10117 {
10118 case PACKET_OK:
10119 return 0;
10120 case PACKET_ERROR:
10121 return 1;
10122 case PACKET_UNKNOWN:
10123 return -1;
10124 default:
10125 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10126 }
10127 }
10128
10129 /* Send a kill request to the target using the 'k' packet. */
10130
10131 void
10132 remote_target::remote_kill_k ()
10133 {
10134 /* Catch errors so the user can quit from gdb even when we
10135 aren't on speaking terms with the remote system. */
10136 try
10137 {
10138 putpkt ("k");
10139 }
10140 catch (const gdb_exception_error &ex)
10141 {
10142 if (ex.error == TARGET_CLOSE_ERROR)
10143 {
10144 /* If we got an (EOF) error that caused the target
10145 to go away, then we're done, that's what we wanted.
10146 "k" is susceptible to cause a premature EOF, given
10147 that the remote server isn't actually required to
10148 reply to "k", and it can happen that it doesn't
10149 even get to reply ACK to the "k". */
10150 return;
10151 }
10152
10153 /* Otherwise, something went wrong. We didn't actually kill
10154 the target. Just propagate the exception, and let the
10155 user or higher layers decide what to do. */
10156 throw;
10157 }
10158 }
10159
10160 void
10161 remote_target::mourn_inferior ()
10162 {
10163 struct remote_state *rs = get_remote_state ();
10164
10165 /* We're no longer interested in notification events of an inferior
10166 that exited or was killed/detached. */
10167 discard_pending_stop_replies (current_inferior ());
10168
10169 /* In 'target remote' mode with one inferior, we close the connection. */
10170 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10171 {
10172 remote_unpush_target (this);
10173 return;
10174 }
10175
10176 /* In case we got here due to an error, but we're going to stay
10177 connected. */
10178 rs->waiting_for_stop_reply = 0;
10179
10180 /* If the current general thread belonged to the process we just
10181 detached from or has exited, the remote side current general
10182 thread becomes undefined. Considering a case like this:
10183
10184 - We just got here due to a detach.
10185 - The process that we're detaching from happens to immediately
10186 report a global breakpoint being hit in non-stop mode, in the
10187 same thread we had selected before.
10188 - GDB attaches to this process again.
10189 - This event happens to be the next event we handle.
10190
10191 GDB would consider that the current general thread didn't need to
10192 be set on the stub side (with Hg), since for all it knew,
10193 GENERAL_THREAD hadn't changed.
10194
10195 Notice that although in all-stop mode, the remote server always
10196 sets the current thread to the thread reporting the stop event,
10197 that doesn't happen in non-stop mode; in non-stop, the stub *must
10198 not* change the current thread when reporting a breakpoint hit,
10199 due to the decoupling of event reporting and event handling.
10200
10201 To keep things simple, we always invalidate our notion of the
10202 current thread. */
10203 record_currthread (rs, minus_one_ptid);
10204
10205 /* Call common code to mark the inferior as not running. */
10206 generic_mourn_inferior ();
10207 }
10208
10209 bool
10210 extended_remote_target::supports_disable_randomization ()
10211 {
10212 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10213 }
10214
10215 void
10216 remote_target::extended_remote_disable_randomization (int val)
10217 {
10218 struct remote_state *rs = get_remote_state ();
10219 char *reply;
10220
10221 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10222 "QDisableRandomization:%x", val);
10223 putpkt (rs->buf);
10224 reply = remote_get_noisy_reply ();
10225 if (*reply == '\0')
10226 error (_("Target does not support QDisableRandomization."));
10227 if (strcmp (reply, "OK") != 0)
10228 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10229 }
10230
10231 int
10232 remote_target::extended_remote_run (const std::string &args)
10233 {
10234 struct remote_state *rs = get_remote_state ();
10235 int len;
10236 const char *remote_exec_file = get_remote_exec_file ();
10237
10238 /* If the user has disabled vRun support, or we have detected that
10239 support is not available, do not try it. */
10240 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10241 return -1;
10242
10243 strcpy (rs->buf.data (), "vRun;");
10244 len = strlen (rs->buf.data ());
10245
10246 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10247 error (_("Remote file name too long for run packet"));
10248 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10249 strlen (remote_exec_file));
10250
10251 if (!args.empty ())
10252 {
10253 int i;
10254
10255 gdb_argv argv (args.c_str ());
10256 for (i = 0; argv[i] != NULL; i++)
10257 {
10258 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10259 error (_("Argument list too long for run packet"));
10260 rs->buf[len++] = ';';
10261 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10262 strlen (argv[i]));
10263 }
10264 }
10265
10266 rs->buf[len++] = '\0';
10267
10268 putpkt (rs->buf);
10269 getpkt (&rs->buf, 0);
10270
10271 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10272 {
10273 case PACKET_OK:
10274 /* We have a wait response. All is well. */
10275 return 0;
10276 case PACKET_UNKNOWN:
10277 return -1;
10278 case PACKET_ERROR:
10279 if (remote_exec_file[0] == '\0')
10280 error (_("Running the default executable on the remote target failed; "
10281 "try \"set remote exec-file\"?"));
10282 else
10283 error (_("Running \"%s\" on the remote target failed"),
10284 remote_exec_file);
10285 default:
10286 gdb_assert_not_reached (_("bad switch"));
10287 }
10288 }
10289
10290 /* Helper function to send set/unset environment packets. ACTION is
10291 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10292 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10293 sent. */
10294
10295 void
10296 remote_target::send_environment_packet (const char *action,
10297 const char *packet,
10298 const char *value)
10299 {
10300 remote_state *rs = get_remote_state ();
10301
10302 /* Convert the environment variable to an hex string, which
10303 is the best format to be transmitted over the wire. */
10304 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10305 strlen (value));
10306
10307 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10308 "%s:%s", packet, encoded_value.c_str ());
10309
10310 putpkt (rs->buf);
10311 getpkt (&rs->buf, 0);
10312 if (strcmp (rs->buf.data (), "OK") != 0)
10313 warning (_("Unable to %s environment variable '%s' on remote."),
10314 action, value);
10315 }
10316
10317 /* Helper function to handle the QEnvironment* packets. */
10318
10319 void
10320 remote_target::extended_remote_environment_support ()
10321 {
10322 remote_state *rs = get_remote_state ();
10323
10324 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10325 {
10326 putpkt ("QEnvironmentReset");
10327 getpkt (&rs->buf, 0);
10328 if (strcmp (rs->buf.data (), "OK") != 0)
10329 warning (_("Unable to reset environment on remote."));
10330 }
10331
10332 gdb_environ *e = &current_inferior ()->environment;
10333
10334 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10335 for (const std::string &el : e->user_set_env ())
10336 send_environment_packet ("set", "QEnvironmentHexEncoded",
10337 el.c_str ());
10338
10339 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10340 for (const std::string &el : e->user_unset_env ())
10341 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10342 }
10343
10344 /* Helper function to set the current working directory for the
10345 inferior in the remote target. */
10346
10347 void
10348 remote_target::extended_remote_set_inferior_cwd ()
10349 {
10350 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10351 {
10352 const char *inferior_cwd = get_inferior_cwd ();
10353 remote_state *rs = get_remote_state ();
10354
10355 if (inferior_cwd != NULL)
10356 {
10357 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10358 strlen (inferior_cwd));
10359
10360 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10361 "QSetWorkingDir:%s", hexpath.c_str ());
10362 }
10363 else
10364 {
10365 /* An empty inferior_cwd means that the user wants us to
10366 reset the remote server's inferior's cwd. */
10367 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10368 "QSetWorkingDir:");
10369 }
10370
10371 putpkt (rs->buf);
10372 getpkt (&rs->buf, 0);
10373 if (packet_ok (rs->buf,
10374 &remote_protocol_packets[PACKET_QSetWorkingDir])
10375 != PACKET_OK)
10376 error (_("\
10377 Remote replied unexpectedly while setting the inferior's working\n\
10378 directory: %s"),
10379 rs->buf.data ());
10380
10381 }
10382 }
10383
10384 /* In the extended protocol we want to be able to do things like
10385 "run" and have them basically work as expected. So we need
10386 a special create_inferior function. We support changing the
10387 executable file and the command line arguments, but not the
10388 environment. */
10389
10390 void
10391 extended_remote_target::create_inferior (const char *exec_file,
10392 const std::string &args,
10393 char **env, int from_tty)
10394 {
10395 int run_worked;
10396 char *stop_reply;
10397 struct remote_state *rs = get_remote_state ();
10398 const char *remote_exec_file = get_remote_exec_file ();
10399
10400 /* If running asynchronously, register the target file descriptor
10401 with the event loop. */
10402 if (target_can_async_p ())
10403 target_async (1);
10404
10405 /* Disable address space randomization if requested (and supported). */
10406 if (supports_disable_randomization ())
10407 extended_remote_disable_randomization (disable_randomization);
10408
10409 /* If startup-with-shell is on, we inform gdbserver to start the
10410 remote inferior using a shell. */
10411 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10412 {
10413 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10414 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10415 putpkt (rs->buf);
10416 getpkt (&rs->buf, 0);
10417 if (strcmp (rs->buf.data (), "OK") != 0)
10418 error (_("\
10419 Remote replied unexpectedly while setting startup-with-shell: %s"),
10420 rs->buf.data ());
10421 }
10422
10423 extended_remote_environment_support ();
10424
10425 extended_remote_set_inferior_cwd ();
10426
10427 /* Now restart the remote server. */
10428 run_worked = extended_remote_run (args) != -1;
10429 if (!run_worked)
10430 {
10431 /* vRun was not supported. Fail if we need it to do what the
10432 user requested. */
10433 if (remote_exec_file[0])
10434 error (_("Remote target does not support \"set remote exec-file\""));
10435 if (!args.empty ())
10436 error (_("Remote target does not support \"set args\" or run ARGS"));
10437
10438 /* Fall back to "R". */
10439 extended_remote_restart ();
10440 }
10441
10442 /* vRun's success return is a stop reply. */
10443 stop_reply = run_worked ? rs->buf.data () : NULL;
10444 add_current_inferior_and_thread (stop_reply);
10445
10446 /* Get updated offsets, if the stub uses qOffsets. */
10447 get_offsets ();
10448 }
10449 \f
10450
10451 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10452 the list of conditions (in agent expression bytecode format), if any, the
10453 target needs to evaluate. The output is placed into the packet buffer
10454 started from BUF and ended at BUF_END. */
10455
10456 static int
10457 remote_add_target_side_condition (struct gdbarch *gdbarch,
10458 struct bp_target_info *bp_tgt, char *buf,
10459 char *buf_end)
10460 {
10461 if (bp_tgt->conditions.empty ())
10462 return 0;
10463
10464 buf += strlen (buf);
10465 xsnprintf (buf, buf_end - buf, "%s", ";");
10466 buf++;
10467
10468 /* Send conditions to the target. */
10469 for (agent_expr *aexpr : bp_tgt->conditions)
10470 {
10471 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10472 buf += strlen (buf);
10473 for (int i = 0; i < aexpr->len; ++i)
10474 buf = pack_hex_byte (buf, aexpr->buf[i]);
10475 *buf = '\0';
10476 }
10477 return 0;
10478 }
10479
10480 static void
10481 remote_add_target_side_commands (struct gdbarch *gdbarch,
10482 struct bp_target_info *bp_tgt, char *buf)
10483 {
10484 if (bp_tgt->tcommands.empty ())
10485 return;
10486
10487 buf += strlen (buf);
10488
10489 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10490 buf += strlen (buf);
10491
10492 /* Concatenate all the agent expressions that are commands into the
10493 cmds parameter. */
10494 for (agent_expr *aexpr : bp_tgt->tcommands)
10495 {
10496 sprintf (buf, "X%x,", aexpr->len);
10497 buf += strlen (buf);
10498 for (int i = 0; i < aexpr->len; ++i)
10499 buf = pack_hex_byte (buf, aexpr->buf[i]);
10500 *buf = '\0';
10501 }
10502 }
10503
10504 /* Insert a breakpoint. On targets that have software breakpoint
10505 support, we ask the remote target to do the work; on targets
10506 which don't, we insert a traditional memory breakpoint. */
10507
10508 int
10509 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10510 struct bp_target_info *bp_tgt)
10511 {
10512 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10513 If it succeeds, then set the support to PACKET_ENABLE. If it
10514 fails, and the user has explicitly requested the Z support then
10515 report an error, otherwise, mark it disabled and go on. */
10516
10517 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10518 {
10519 CORE_ADDR addr = bp_tgt->reqstd_address;
10520 struct remote_state *rs;
10521 char *p, *endbuf;
10522
10523 /* Make sure the remote is pointing at the right process, if
10524 necessary. */
10525 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10526 set_general_process ();
10527
10528 rs = get_remote_state ();
10529 p = rs->buf.data ();
10530 endbuf = p + get_remote_packet_size ();
10531
10532 *(p++) = 'Z';
10533 *(p++) = '0';
10534 *(p++) = ',';
10535 addr = (ULONGEST) remote_address_masked (addr);
10536 p += hexnumstr (p, addr);
10537 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10538
10539 if (supports_evaluation_of_breakpoint_conditions ())
10540 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10541
10542 if (can_run_breakpoint_commands ())
10543 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10544
10545 putpkt (rs->buf);
10546 getpkt (&rs->buf, 0);
10547
10548 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10549 {
10550 case PACKET_ERROR:
10551 return -1;
10552 case PACKET_OK:
10553 return 0;
10554 case PACKET_UNKNOWN:
10555 break;
10556 }
10557 }
10558
10559 /* If this breakpoint has target-side commands but this stub doesn't
10560 support Z0 packets, throw error. */
10561 if (!bp_tgt->tcommands.empty ())
10562 throw_error (NOT_SUPPORTED_ERROR, _("\
10563 Target doesn't support breakpoints that have target side commands."));
10564
10565 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10566 }
10567
10568 int
10569 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10570 struct bp_target_info *bp_tgt,
10571 enum remove_bp_reason reason)
10572 {
10573 CORE_ADDR addr = bp_tgt->placed_address;
10574 struct remote_state *rs = get_remote_state ();
10575
10576 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10577 {
10578 char *p = rs->buf.data ();
10579 char *endbuf = p + get_remote_packet_size ();
10580
10581 /* Make sure the remote is pointing at the right process, if
10582 necessary. */
10583 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10584 set_general_process ();
10585
10586 *(p++) = 'z';
10587 *(p++) = '0';
10588 *(p++) = ',';
10589
10590 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10591 p += hexnumstr (p, addr);
10592 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10593
10594 putpkt (rs->buf);
10595 getpkt (&rs->buf, 0);
10596
10597 return (rs->buf[0] == 'E');
10598 }
10599
10600 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10601 }
10602
10603 static enum Z_packet_type
10604 watchpoint_to_Z_packet (int type)
10605 {
10606 switch (type)
10607 {
10608 case hw_write:
10609 return Z_PACKET_WRITE_WP;
10610 break;
10611 case hw_read:
10612 return Z_PACKET_READ_WP;
10613 break;
10614 case hw_access:
10615 return Z_PACKET_ACCESS_WP;
10616 break;
10617 default:
10618 internal_error (__FILE__, __LINE__,
10619 _("hw_bp_to_z: bad watchpoint type %d"), type);
10620 }
10621 }
10622
10623 int
10624 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10625 enum target_hw_bp_type type, struct expression *cond)
10626 {
10627 struct remote_state *rs = get_remote_state ();
10628 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10629 char *p;
10630 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10631
10632 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10633 return 1;
10634
10635 /* Make sure the remote is pointing at the right process, if
10636 necessary. */
10637 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10638 set_general_process ();
10639
10640 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10641 p = strchr (rs->buf.data (), '\0');
10642 addr = remote_address_masked (addr);
10643 p += hexnumstr (p, (ULONGEST) addr);
10644 xsnprintf (p, endbuf - p, ",%x", len);
10645
10646 putpkt (rs->buf);
10647 getpkt (&rs->buf, 0);
10648
10649 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10650 {
10651 case PACKET_ERROR:
10652 return -1;
10653 case PACKET_UNKNOWN:
10654 return 1;
10655 case PACKET_OK:
10656 return 0;
10657 }
10658 internal_error (__FILE__, __LINE__,
10659 _("remote_insert_watchpoint: reached end of function"));
10660 }
10661
10662 bool
10663 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10664 CORE_ADDR start, int length)
10665 {
10666 CORE_ADDR diff = remote_address_masked (addr - start);
10667
10668 return diff < length;
10669 }
10670
10671
10672 int
10673 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10674 enum target_hw_bp_type type, struct expression *cond)
10675 {
10676 struct remote_state *rs = get_remote_state ();
10677 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10678 char *p;
10679 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10680
10681 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10682 return -1;
10683
10684 /* Make sure the remote is pointing at the right process, if
10685 necessary. */
10686 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10687 set_general_process ();
10688
10689 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10690 p = strchr (rs->buf.data (), '\0');
10691 addr = remote_address_masked (addr);
10692 p += hexnumstr (p, (ULONGEST) addr);
10693 xsnprintf (p, endbuf - p, ",%x", len);
10694 putpkt (rs->buf);
10695 getpkt (&rs->buf, 0);
10696
10697 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10698 {
10699 case PACKET_ERROR:
10700 case PACKET_UNKNOWN:
10701 return -1;
10702 case PACKET_OK:
10703 return 0;
10704 }
10705 internal_error (__FILE__, __LINE__,
10706 _("remote_remove_watchpoint: reached end of function"));
10707 }
10708
10709
10710 static int remote_hw_watchpoint_limit = -1;
10711 static int remote_hw_watchpoint_length_limit = -1;
10712 static int remote_hw_breakpoint_limit = -1;
10713
10714 int
10715 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10716 {
10717 if (remote_hw_watchpoint_length_limit == 0)
10718 return 0;
10719 else if (remote_hw_watchpoint_length_limit < 0)
10720 return 1;
10721 else if (len <= remote_hw_watchpoint_length_limit)
10722 return 1;
10723 else
10724 return 0;
10725 }
10726
10727 int
10728 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10729 {
10730 if (type == bp_hardware_breakpoint)
10731 {
10732 if (remote_hw_breakpoint_limit == 0)
10733 return 0;
10734 else if (remote_hw_breakpoint_limit < 0)
10735 return 1;
10736 else if (cnt <= remote_hw_breakpoint_limit)
10737 return 1;
10738 }
10739 else
10740 {
10741 if (remote_hw_watchpoint_limit == 0)
10742 return 0;
10743 else if (remote_hw_watchpoint_limit < 0)
10744 return 1;
10745 else if (ot)
10746 return -1;
10747 else if (cnt <= remote_hw_watchpoint_limit)
10748 return 1;
10749 }
10750 return -1;
10751 }
10752
10753 /* The to_stopped_by_sw_breakpoint method of target remote. */
10754
10755 bool
10756 remote_target::stopped_by_sw_breakpoint ()
10757 {
10758 struct thread_info *thread = inferior_thread ();
10759
10760 return (thread->priv != NULL
10761 && (get_remote_thread_info (thread)->stop_reason
10762 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10763 }
10764
10765 /* The to_supports_stopped_by_sw_breakpoint method of target
10766 remote. */
10767
10768 bool
10769 remote_target::supports_stopped_by_sw_breakpoint ()
10770 {
10771 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10772 }
10773
10774 /* The to_stopped_by_hw_breakpoint method of target remote. */
10775
10776 bool
10777 remote_target::stopped_by_hw_breakpoint ()
10778 {
10779 struct thread_info *thread = inferior_thread ();
10780
10781 return (thread->priv != NULL
10782 && (get_remote_thread_info (thread)->stop_reason
10783 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10784 }
10785
10786 /* The to_supports_stopped_by_hw_breakpoint method of target
10787 remote. */
10788
10789 bool
10790 remote_target::supports_stopped_by_hw_breakpoint ()
10791 {
10792 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10793 }
10794
10795 bool
10796 remote_target::stopped_by_watchpoint ()
10797 {
10798 struct thread_info *thread = inferior_thread ();
10799
10800 return (thread->priv != NULL
10801 && (get_remote_thread_info (thread)->stop_reason
10802 == TARGET_STOPPED_BY_WATCHPOINT));
10803 }
10804
10805 bool
10806 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10807 {
10808 struct thread_info *thread = inferior_thread ();
10809
10810 if (thread->priv != NULL
10811 && (get_remote_thread_info (thread)->stop_reason
10812 == TARGET_STOPPED_BY_WATCHPOINT))
10813 {
10814 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10815 return true;
10816 }
10817
10818 return false;
10819 }
10820
10821
10822 int
10823 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10824 struct bp_target_info *bp_tgt)
10825 {
10826 CORE_ADDR addr = bp_tgt->reqstd_address;
10827 struct remote_state *rs;
10828 char *p, *endbuf;
10829 char *message;
10830
10831 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10832 return -1;
10833
10834 /* Make sure the remote is pointing at the right process, if
10835 necessary. */
10836 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10837 set_general_process ();
10838
10839 rs = get_remote_state ();
10840 p = rs->buf.data ();
10841 endbuf = p + get_remote_packet_size ();
10842
10843 *(p++) = 'Z';
10844 *(p++) = '1';
10845 *(p++) = ',';
10846
10847 addr = remote_address_masked (addr);
10848 p += hexnumstr (p, (ULONGEST) addr);
10849 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10850
10851 if (supports_evaluation_of_breakpoint_conditions ())
10852 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10853
10854 if (can_run_breakpoint_commands ())
10855 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10856
10857 putpkt (rs->buf);
10858 getpkt (&rs->buf, 0);
10859
10860 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10861 {
10862 case PACKET_ERROR:
10863 if (rs->buf[1] == '.')
10864 {
10865 message = strchr (&rs->buf[2], '.');
10866 if (message)
10867 error (_("Remote failure reply: %s"), message + 1);
10868 }
10869 return -1;
10870 case PACKET_UNKNOWN:
10871 return -1;
10872 case PACKET_OK:
10873 return 0;
10874 }
10875 internal_error (__FILE__, __LINE__,
10876 _("remote_insert_hw_breakpoint: reached end of function"));
10877 }
10878
10879
10880 int
10881 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10882 struct bp_target_info *bp_tgt)
10883 {
10884 CORE_ADDR addr;
10885 struct remote_state *rs = get_remote_state ();
10886 char *p = rs->buf.data ();
10887 char *endbuf = p + get_remote_packet_size ();
10888
10889 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10890 return -1;
10891
10892 /* Make sure the remote is pointing at the right process, if
10893 necessary. */
10894 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10895 set_general_process ();
10896
10897 *(p++) = 'z';
10898 *(p++) = '1';
10899 *(p++) = ',';
10900
10901 addr = remote_address_masked (bp_tgt->placed_address);
10902 p += hexnumstr (p, (ULONGEST) addr);
10903 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10904
10905 putpkt (rs->buf);
10906 getpkt (&rs->buf, 0);
10907
10908 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10909 {
10910 case PACKET_ERROR:
10911 case PACKET_UNKNOWN:
10912 return -1;
10913 case PACKET_OK:
10914 return 0;
10915 }
10916 internal_error (__FILE__, __LINE__,
10917 _("remote_remove_hw_breakpoint: reached end of function"));
10918 }
10919
10920 /* Verify memory using the "qCRC:" request. */
10921
10922 int
10923 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10924 {
10925 struct remote_state *rs = get_remote_state ();
10926 unsigned long host_crc, target_crc;
10927 char *tmp;
10928
10929 /* It doesn't make sense to use qCRC if the remote target is
10930 connected but not running. */
10931 if (target_has_execution ()
10932 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10933 {
10934 enum packet_result result;
10935
10936 /* Make sure the remote is pointing at the right process. */
10937 set_general_process ();
10938
10939 /* FIXME: assumes lma can fit into long. */
10940 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
10941 (long) lma, (long) size);
10942 putpkt (rs->buf);
10943
10944 /* Be clever; compute the host_crc before waiting for target
10945 reply. */
10946 host_crc = xcrc32 (data, size, 0xffffffff);
10947
10948 getpkt (&rs->buf, 0);
10949
10950 result = packet_ok (rs->buf,
10951 &remote_protocol_packets[PACKET_qCRC]);
10952 if (result == PACKET_ERROR)
10953 return -1;
10954 else if (result == PACKET_OK)
10955 {
10956 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10957 target_crc = target_crc * 16 + fromhex (*tmp);
10958
10959 return (host_crc == target_crc);
10960 }
10961 }
10962
10963 return simple_verify_memory (this, data, lma, size);
10964 }
10965
10966 /* compare-sections command
10967
10968 With no arguments, compares each loadable section in the exec bfd
10969 with the same memory range on the target, and reports mismatches.
10970 Useful for verifying the image on the target against the exec file. */
10971
10972 static void
10973 compare_sections_command (const char *args, int from_tty)
10974 {
10975 asection *s;
10976 const char *sectname;
10977 bfd_size_type size;
10978 bfd_vma lma;
10979 int matched = 0;
10980 int mismatched = 0;
10981 int res;
10982 int read_only = 0;
10983
10984 if (!current_program_space->exec_bfd ())
10985 error (_("command cannot be used without an exec file"));
10986
10987 if (args != NULL && strcmp (args, "-r") == 0)
10988 {
10989 read_only = 1;
10990 args = NULL;
10991 }
10992
10993 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
10994 {
10995 if (!(s->flags & SEC_LOAD))
10996 continue; /* Skip non-loadable section. */
10997
10998 if (read_only && (s->flags & SEC_READONLY) == 0)
10999 continue; /* Skip writeable sections */
11000
11001 size = bfd_section_size (s);
11002 if (size == 0)
11003 continue; /* Skip zero-length section. */
11004
11005 sectname = bfd_section_name (s);
11006 if (args && strcmp (args, sectname) != 0)
11007 continue; /* Not the section selected by user. */
11008
11009 matched = 1; /* Do this section. */
11010 lma = s->lma;
11011
11012 gdb::byte_vector sectdata (size);
11013 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11014 sectdata.data (), 0, size);
11015
11016 res = target_verify_memory (sectdata.data (), lma, size);
11017
11018 if (res == -1)
11019 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11020 paddress (target_gdbarch (), lma),
11021 paddress (target_gdbarch (), lma + size));
11022
11023 printf_filtered ("Section %s, range %s -- %s: ", sectname,
11024 paddress (target_gdbarch (), lma),
11025 paddress (target_gdbarch (), lma + size));
11026 if (res)
11027 printf_filtered ("matched.\n");
11028 else
11029 {
11030 printf_filtered ("MIS-MATCHED!\n");
11031 mismatched++;
11032 }
11033 }
11034 if (mismatched > 0)
11035 warning (_("One or more sections of the target image does not match\n\
11036 the loaded file\n"));
11037 if (args && !matched)
11038 printf_filtered (_("No loaded section named '%s'.\n"), args);
11039 }
11040
11041 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11042 into remote target. The number of bytes written to the remote
11043 target is returned, or -1 for error. */
11044
11045 target_xfer_status
11046 remote_target::remote_write_qxfer (const char *object_name,
11047 const char *annex, const gdb_byte *writebuf,
11048 ULONGEST offset, LONGEST len,
11049 ULONGEST *xfered_len,
11050 struct packet_config *packet)
11051 {
11052 int i, buf_len;
11053 ULONGEST n;
11054 struct remote_state *rs = get_remote_state ();
11055 int max_size = get_memory_write_packet_size ();
11056
11057 if (packet_config_support (packet) == PACKET_DISABLE)
11058 return TARGET_XFER_E_IO;
11059
11060 /* Insert header. */
11061 i = snprintf (rs->buf.data (), max_size,
11062 "qXfer:%s:write:%s:%s:",
11063 object_name, annex ? annex : "",
11064 phex_nz (offset, sizeof offset));
11065 max_size -= (i + 1);
11066
11067 /* Escape as much data as fits into rs->buf. */
11068 buf_len = remote_escape_output
11069 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11070
11071 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11072 || getpkt_sane (&rs->buf, 0) < 0
11073 || packet_ok (rs->buf, packet) != PACKET_OK)
11074 return TARGET_XFER_E_IO;
11075
11076 unpack_varlen_hex (rs->buf.data (), &n);
11077
11078 *xfered_len = n;
11079 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11080 }
11081
11082 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11083 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11084 number of bytes read is returned, or 0 for EOF, or -1 for error.
11085 The number of bytes read may be less than LEN without indicating an
11086 EOF. PACKET is checked and updated to indicate whether the remote
11087 target supports this object. */
11088
11089 target_xfer_status
11090 remote_target::remote_read_qxfer (const char *object_name,
11091 const char *annex,
11092 gdb_byte *readbuf, ULONGEST offset,
11093 LONGEST len,
11094 ULONGEST *xfered_len,
11095 struct packet_config *packet)
11096 {
11097 struct remote_state *rs = get_remote_state ();
11098 LONGEST i, n, packet_len;
11099
11100 if (packet_config_support (packet) == PACKET_DISABLE)
11101 return TARGET_XFER_E_IO;
11102
11103 /* Check whether we've cached an end-of-object packet that matches
11104 this request. */
11105 if (rs->finished_object)
11106 {
11107 if (strcmp (object_name, rs->finished_object) == 0
11108 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11109 && offset == rs->finished_offset)
11110 return TARGET_XFER_EOF;
11111
11112
11113 /* Otherwise, we're now reading something different. Discard
11114 the cache. */
11115 xfree (rs->finished_object);
11116 xfree (rs->finished_annex);
11117 rs->finished_object = NULL;
11118 rs->finished_annex = NULL;
11119 }
11120
11121 /* Request only enough to fit in a single packet. The actual data
11122 may not, since we don't know how much of it will need to be escaped;
11123 the target is free to respond with slightly less data. We subtract
11124 five to account for the response type and the protocol frame. */
11125 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11126 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11127 "qXfer:%s:read:%s:%s,%s",
11128 object_name, annex ? annex : "",
11129 phex_nz (offset, sizeof offset),
11130 phex_nz (n, sizeof n));
11131 i = putpkt (rs->buf);
11132 if (i < 0)
11133 return TARGET_XFER_E_IO;
11134
11135 rs->buf[0] = '\0';
11136 packet_len = getpkt_sane (&rs->buf, 0);
11137 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
11138 return TARGET_XFER_E_IO;
11139
11140 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11141 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11142
11143 /* 'm' means there is (or at least might be) more data after this
11144 batch. That does not make sense unless there's at least one byte
11145 of data in this reply. */
11146 if (rs->buf[0] == 'm' && packet_len == 1)
11147 error (_("Remote qXfer reply contained no data."));
11148
11149 /* Got some data. */
11150 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11151 packet_len - 1, readbuf, n);
11152
11153 /* 'l' is an EOF marker, possibly including a final block of data,
11154 or possibly empty. If we have the final block of a non-empty
11155 object, record this fact to bypass a subsequent partial read. */
11156 if (rs->buf[0] == 'l' && offset + i > 0)
11157 {
11158 rs->finished_object = xstrdup (object_name);
11159 rs->finished_annex = xstrdup (annex ? annex : "");
11160 rs->finished_offset = offset + i;
11161 }
11162
11163 if (i == 0)
11164 return TARGET_XFER_EOF;
11165 else
11166 {
11167 *xfered_len = i;
11168 return TARGET_XFER_OK;
11169 }
11170 }
11171
11172 enum target_xfer_status
11173 remote_target::xfer_partial (enum target_object object,
11174 const char *annex, gdb_byte *readbuf,
11175 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11176 ULONGEST *xfered_len)
11177 {
11178 struct remote_state *rs;
11179 int i;
11180 char *p2;
11181 char query_type;
11182 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11183
11184 set_remote_traceframe ();
11185 set_general_thread (inferior_ptid);
11186
11187 rs = get_remote_state ();
11188
11189 /* Handle memory using the standard memory routines. */
11190 if (object == TARGET_OBJECT_MEMORY)
11191 {
11192 /* If the remote target is connected but not running, we should
11193 pass this request down to a lower stratum (e.g. the executable
11194 file). */
11195 if (!target_has_execution ())
11196 return TARGET_XFER_EOF;
11197
11198 if (writebuf != NULL)
11199 return remote_write_bytes (offset, writebuf, len, unit_size,
11200 xfered_len);
11201 else
11202 return remote_read_bytes (offset, readbuf, len, unit_size,
11203 xfered_len);
11204 }
11205
11206 /* Handle extra signal info using qxfer packets. */
11207 if (object == TARGET_OBJECT_SIGNAL_INFO)
11208 {
11209 if (readbuf)
11210 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11211 xfered_len, &remote_protocol_packets
11212 [PACKET_qXfer_siginfo_read]);
11213 else
11214 return remote_write_qxfer ("siginfo", annex,
11215 writebuf, offset, len, xfered_len,
11216 &remote_protocol_packets
11217 [PACKET_qXfer_siginfo_write]);
11218 }
11219
11220 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11221 {
11222 if (readbuf)
11223 return remote_read_qxfer ("statictrace", annex,
11224 readbuf, offset, len, xfered_len,
11225 &remote_protocol_packets
11226 [PACKET_qXfer_statictrace_read]);
11227 else
11228 return TARGET_XFER_E_IO;
11229 }
11230
11231 /* Only handle flash writes. */
11232 if (writebuf != NULL)
11233 {
11234 switch (object)
11235 {
11236 case TARGET_OBJECT_FLASH:
11237 return remote_flash_write (offset, len, xfered_len,
11238 writebuf);
11239
11240 default:
11241 return TARGET_XFER_E_IO;
11242 }
11243 }
11244
11245 /* Map pre-existing objects onto letters. DO NOT do this for new
11246 objects!!! Instead specify new query packets. */
11247 switch (object)
11248 {
11249 case TARGET_OBJECT_AVR:
11250 query_type = 'R';
11251 break;
11252
11253 case TARGET_OBJECT_AUXV:
11254 gdb_assert (annex == NULL);
11255 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11256 xfered_len,
11257 &remote_protocol_packets[PACKET_qXfer_auxv]);
11258
11259 case TARGET_OBJECT_AVAILABLE_FEATURES:
11260 return remote_read_qxfer
11261 ("features", annex, readbuf, offset, len, xfered_len,
11262 &remote_protocol_packets[PACKET_qXfer_features]);
11263
11264 case TARGET_OBJECT_LIBRARIES:
11265 return remote_read_qxfer
11266 ("libraries", annex, readbuf, offset, len, xfered_len,
11267 &remote_protocol_packets[PACKET_qXfer_libraries]);
11268
11269 case TARGET_OBJECT_LIBRARIES_SVR4:
11270 return remote_read_qxfer
11271 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11272 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11273
11274 case TARGET_OBJECT_MEMORY_MAP:
11275 gdb_assert (annex == NULL);
11276 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11277 xfered_len,
11278 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11279
11280 case TARGET_OBJECT_OSDATA:
11281 /* Should only get here if we're connected. */
11282 gdb_assert (rs->remote_desc);
11283 return remote_read_qxfer
11284 ("osdata", annex, readbuf, offset, len, xfered_len,
11285 &remote_protocol_packets[PACKET_qXfer_osdata]);
11286
11287 case TARGET_OBJECT_THREADS:
11288 gdb_assert (annex == NULL);
11289 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11290 xfered_len,
11291 &remote_protocol_packets[PACKET_qXfer_threads]);
11292
11293 case TARGET_OBJECT_TRACEFRAME_INFO:
11294 gdb_assert (annex == NULL);
11295 return remote_read_qxfer
11296 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11297 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11298
11299 case TARGET_OBJECT_FDPIC:
11300 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11301 xfered_len,
11302 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11303
11304 case TARGET_OBJECT_OPENVMS_UIB:
11305 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11306 xfered_len,
11307 &remote_protocol_packets[PACKET_qXfer_uib]);
11308
11309 case TARGET_OBJECT_BTRACE:
11310 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11311 xfered_len,
11312 &remote_protocol_packets[PACKET_qXfer_btrace]);
11313
11314 case TARGET_OBJECT_BTRACE_CONF:
11315 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11316 len, xfered_len,
11317 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11318
11319 case TARGET_OBJECT_EXEC_FILE:
11320 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11321 len, xfered_len,
11322 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11323
11324 default:
11325 return TARGET_XFER_E_IO;
11326 }
11327
11328 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11329 large enough let the caller deal with it. */
11330 if (len < get_remote_packet_size ())
11331 return TARGET_XFER_E_IO;
11332 len = get_remote_packet_size ();
11333
11334 /* Except for querying the minimum buffer size, target must be open. */
11335 if (!rs->remote_desc)
11336 error (_("remote query is only available after target open"));
11337
11338 gdb_assert (annex != NULL);
11339 gdb_assert (readbuf != NULL);
11340
11341 p2 = rs->buf.data ();
11342 *p2++ = 'q';
11343 *p2++ = query_type;
11344
11345 /* We used one buffer char for the remote protocol q command and
11346 another for the query type. As the remote protocol encapsulation
11347 uses 4 chars plus one extra in case we are debugging
11348 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11349 string. */
11350 i = 0;
11351 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11352 {
11353 /* Bad caller may have sent forbidden characters. */
11354 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11355 *p2++ = annex[i];
11356 i++;
11357 }
11358 *p2 = '\0';
11359 gdb_assert (annex[i] == '\0');
11360
11361 i = putpkt (rs->buf);
11362 if (i < 0)
11363 return TARGET_XFER_E_IO;
11364
11365 getpkt (&rs->buf, 0);
11366 strcpy ((char *) readbuf, rs->buf.data ());
11367
11368 *xfered_len = strlen ((char *) readbuf);
11369 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11370 }
11371
11372 /* Implementation of to_get_memory_xfer_limit. */
11373
11374 ULONGEST
11375 remote_target::get_memory_xfer_limit ()
11376 {
11377 return get_memory_write_packet_size ();
11378 }
11379
11380 int
11381 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11382 const gdb_byte *pattern, ULONGEST pattern_len,
11383 CORE_ADDR *found_addrp)
11384 {
11385 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11386 struct remote_state *rs = get_remote_state ();
11387 int max_size = get_memory_write_packet_size ();
11388 struct packet_config *packet =
11389 &remote_protocol_packets[PACKET_qSearch_memory];
11390 /* Number of packet bytes used to encode the pattern;
11391 this could be more than PATTERN_LEN due to escape characters. */
11392 int escaped_pattern_len;
11393 /* Amount of pattern that was encodable in the packet. */
11394 int used_pattern_len;
11395 int i;
11396 int found;
11397 ULONGEST found_addr;
11398
11399 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11400 {
11401 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11402 == len);
11403 };
11404
11405 /* Don't go to the target if we don't have to. This is done before
11406 checking packet_config_support to avoid the possibility that a
11407 success for this edge case means the facility works in
11408 general. */
11409 if (pattern_len > search_space_len)
11410 return 0;
11411 if (pattern_len == 0)
11412 {
11413 *found_addrp = start_addr;
11414 return 1;
11415 }
11416
11417 /* If we already know the packet isn't supported, fall back to the simple
11418 way of searching memory. */
11419
11420 if (packet_config_support (packet) == PACKET_DISABLE)
11421 {
11422 /* Target doesn't provided special support, fall back and use the
11423 standard support (copy memory and do the search here). */
11424 return simple_search_memory (read_memory, start_addr, search_space_len,
11425 pattern, pattern_len, found_addrp);
11426 }
11427
11428 /* Make sure the remote is pointing at the right process. */
11429 set_general_process ();
11430
11431 /* Insert header. */
11432 i = snprintf (rs->buf.data (), max_size,
11433 "qSearch:memory:%s;%s;",
11434 phex_nz (start_addr, addr_size),
11435 phex_nz (search_space_len, sizeof (search_space_len)));
11436 max_size -= (i + 1);
11437
11438 /* Escape as much data as fits into rs->buf. */
11439 escaped_pattern_len =
11440 remote_escape_output (pattern, pattern_len, 1,
11441 (gdb_byte *) rs->buf.data () + i,
11442 &used_pattern_len, max_size);
11443
11444 /* Bail if the pattern is too large. */
11445 if (used_pattern_len != pattern_len)
11446 error (_("Pattern is too large to transmit to remote target."));
11447
11448 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11449 || getpkt_sane (&rs->buf, 0) < 0
11450 || packet_ok (rs->buf, packet) != PACKET_OK)
11451 {
11452 /* The request may not have worked because the command is not
11453 supported. If so, fall back to the simple way. */
11454 if (packet_config_support (packet) == PACKET_DISABLE)
11455 {
11456 return simple_search_memory (read_memory, start_addr, search_space_len,
11457 pattern, pattern_len, found_addrp);
11458 }
11459 return -1;
11460 }
11461
11462 if (rs->buf[0] == '0')
11463 found = 0;
11464 else if (rs->buf[0] == '1')
11465 {
11466 found = 1;
11467 if (rs->buf[1] != ',')
11468 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11469 unpack_varlen_hex (&rs->buf[2], &found_addr);
11470 *found_addrp = found_addr;
11471 }
11472 else
11473 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11474
11475 return found;
11476 }
11477
11478 void
11479 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11480 {
11481 struct remote_state *rs = get_remote_state ();
11482 char *p = rs->buf.data ();
11483
11484 if (!rs->remote_desc)
11485 error (_("remote rcmd is only available after target open"));
11486
11487 /* Send a NULL command across as an empty command. */
11488 if (command == NULL)
11489 command = "";
11490
11491 /* The query prefix. */
11492 strcpy (rs->buf.data (), "qRcmd,");
11493 p = strchr (rs->buf.data (), '\0');
11494
11495 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11496 > get_remote_packet_size ())
11497 error (_("\"monitor\" command ``%s'' is too long."), command);
11498
11499 /* Encode the actual command. */
11500 bin2hex ((const gdb_byte *) command, p, strlen (command));
11501
11502 if (putpkt (rs->buf) < 0)
11503 error (_("Communication problem with target."));
11504
11505 /* get/display the response */
11506 while (1)
11507 {
11508 char *buf;
11509
11510 /* XXX - see also remote_get_noisy_reply(). */
11511 QUIT; /* Allow user to bail out with ^C. */
11512 rs->buf[0] = '\0';
11513 if (getpkt_sane (&rs->buf, 0) == -1)
11514 {
11515 /* Timeout. Continue to (try to) read responses.
11516 This is better than stopping with an error, assuming the stub
11517 is still executing the (long) monitor command.
11518 If needed, the user can interrupt gdb using C-c, obtaining
11519 an effect similar to stop on timeout. */
11520 continue;
11521 }
11522 buf = rs->buf.data ();
11523 if (buf[0] == '\0')
11524 error (_("Target does not support this command."));
11525 if (buf[0] == 'O' && buf[1] != 'K')
11526 {
11527 remote_console_output (buf + 1); /* 'O' message from stub. */
11528 continue;
11529 }
11530 if (strcmp (buf, "OK") == 0)
11531 break;
11532 if (strlen (buf) == 3 && buf[0] == 'E'
11533 && isdigit (buf[1]) && isdigit (buf[2]))
11534 {
11535 error (_("Protocol error with Rcmd"));
11536 }
11537 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11538 {
11539 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11540
11541 fputc_unfiltered (c, outbuf);
11542 }
11543 break;
11544 }
11545 }
11546
11547 std::vector<mem_region>
11548 remote_target::memory_map ()
11549 {
11550 std::vector<mem_region> result;
11551 gdb::optional<gdb::char_vector> text
11552 = target_read_stralloc (current_inferior ()->top_target (),
11553 TARGET_OBJECT_MEMORY_MAP, NULL);
11554
11555 if (text)
11556 result = parse_memory_map (text->data ());
11557
11558 return result;
11559 }
11560
11561 static void
11562 packet_command (const char *args, int from_tty)
11563 {
11564 remote_target *remote = get_current_remote_target ();
11565
11566 if (remote == nullptr)
11567 error (_("command can only be used with remote target"));
11568
11569 remote->packet_command (args, from_tty);
11570 }
11571
11572 void
11573 remote_target::packet_command (const char *args, int from_tty)
11574 {
11575 if (!args)
11576 error (_("remote-packet command requires packet text as argument"));
11577
11578 puts_filtered ("sending: ");
11579 print_packet (args);
11580 puts_filtered ("\n");
11581 putpkt (args);
11582
11583 remote_state *rs = get_remote_state ();
11584
11585 getpkt (&rs->buf, 0);
11586 puts_filtered ("received: ");
11587 print_packet (rs->buf.data ());
11588 puts_filtered ("\n");
11589 }
11590
11591 #if 0
11592 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11593
11594 static void display_thread_info (struct gdb_ext_thread_info *info);
11595
11596 static void threadset_test_cmd (char *cmd, int tty);
11597
11598 static void threadalive_test (char *cmd, int tty);
11599
11600 static void threadlist_test_cmd (char *cmd, int tty);
11601
11602 int get_and_display_threadinfo (threadref *ref);
11603
11604 static void threadinfo_test_cmd (char *cmd, int tty);
11605
11606 static int thread_display_step (threadref *ref, void *context);
11607
11608 static void threadlist_update_test_cmd (char *cmd, int tty);
11609
11610 static void init_remote_threadtests (void);
11611
11612 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11613
11614 static void
11615 threadset_test_cmd (const char *cmd, int tty)
11616 {
11617 int sample_thread = SAMPLE_THREAD;
11618
11619 printf_filtered (_("Remote threadset test\n"));
11620 set_general_thread (sample_thread);
11621 }
11622
11623
11624 static void
11625 threadalive_test (const char *cmd, int tty)
11626 {
11627 int sample_thread = SAMPLE_THREAD;
11628 int pid = inferior_ptid.pid ();
11629 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11630
11631 if (remote_thread_alive (ptid))
11632 printf_filtered ("PASS: Thread alive test\n");
11633 else
11634 printf_filtered ("FAIL: Thread alive test\n");
11635 }
11636
11637 void output_threadid (char *title, threadref *ref);
11638
11639 void
11640 output_threadid (char *title, threadref *ref)
11641 {
11642 char hexid[20];
11643
11644 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11645 hexid[16] = 0;
11646 printf_filtered ("%s %s\n", title, (&hexid[0]));
11647 }
11648
11649 static void
11650 threadlist_test_cmd (const char *cmd, int tty)
11651 {
11652 int startflag = 1;
11653 threadref nextthread;
11654 int done, result_count;
11655 threadref threadlist[3];
11656
11657 printf_filtered ("Remote Threadlist test\n");
11658 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11659 &result_count, &threadlist[0]))
11660 printf_filtered ("FAIL: threadlist test\n");
11661 else
11662 {
11663 threadref *scan = threadlist;
11664 threadref *limit = scan + result_count;
11665
11666 while (scan < limit)
11667 output_threadid (" thread ", scan++);
11668 }
11669 }
11670
11671 void
11672 display_thread_info (struct gdb_ext_thread_info *info)
11673 {
11674 output_threadid ("Threadid: ", &info->threadid);
11675 printf_filtered ("Name: %s\n ", info->shortname);
11676 printf_filtered ("State: %s\n", info->display);
11677 printf_filtered ("other: %s\n\n", info->more_display);
11678 }
11679
11680 int
11681 get_and_display_threadinfo (threadref *ref)
11682 {
11683 int result;
11684 int set;
11685 struct gdb_ext_thread_info threadinfo;
11686
11687 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11688 | TAG_MOREDISPLAY | TAG_DISPLAY;
11689 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11690 display_thread_info (&threadinfo);
11691 return result;
11692 }
11693
11694 static void
11695 threadinfo_test_cmd (const char *cmd, int tty)
11696 {
11697 int athread = SAMPLE_THREAD;
11698 threadref thread;
11699 int set;
11700
11701 int_to_threadref (&thread, athread);
11702 printf_filtered ("Remote Threadinfo test\n");
11703 if (!get_and_display_threadinfo (&thread))
11704 printf_filtered ("FAIL cannot get thread info\n");
11705 }
11706
11707 static int
11708 thread_display_step (threadref *ref, void *context)
11709 {
11710 /* output_threadid(" threadstep ",ref); *//* simple test */
11711 return get_and_display_threadinfo (ref);
11712 }
11713
11714 static void
11715 threadlist_update_test_cmd (const char *cmd, int tty)
11716 {
11717 printf_filtered ("Remote Threadlist update test\n");
11718 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11719 }
11720
11721 static void
11722 init_remote_threadtests (void)
11723 {
11724 add_com ("tlist", class_obscure, threadlist_test_cmd,
11725 _("Fetch and print the remote list of "
11726 "thread identifiers, one pkt only."));
11727 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11728 _("Fetch and display info about one thread."));
11729 add_com ("tset", class_obscure, threadset_test_cmd,
11730 _("Test setting to a different thread."));
11731 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11732 _("Iterate through updating all remote thread info."));
11733 add_com ("talive", class_obscure, threadalive_test,
11734 _("Remote thread alive test."));
11735 }
11736
11737 #endif /* 0 */
11738
11739 /* Convert a thread ID to a string. */
11740
11741 std::string
11742 remote_target::pid_to_str (ptid_t ptid)
11743 {
11744 struct remote_state *rs = get_remote_state ();
11745
11746 if (ptid == null_ptid)
11747 return normal_pid_to_str (ptid);
11748 else if (ptid.is_pid ())
11749 {
11750 /* Printing an inferior target id. */
11751
11752 /* When multi-process extensions are off, there's no way in the
11753 remote protocol to know the remote process id, if there's any
11754 at all. There's one exception --- when we're connected with
11755 target extended-remote, and we manually attached to a process
11756 with "attach PID". We don't record anywhere a flag that
11757 allows us to distinguish that case from the case of
11758 connecting with extended-remote and the stub already being
11759 attached to a process, and reporting yes to qAttached, hence
11760 no smart special casing here. */
11761 if (!remote_multi_process_p (rs))
11762 return "Remote target";
11763
11764 return normal_pid_to_str (ptid);
11765 }
11766 else
11767 {
11768 if (magic_null_ptid == ptid)
11769 return "Thread <main>";
11770 else if (remote_multi_process_p (rs))
11771 if (ptid.lwp () == 0)
11772 return normal_pid_to_str (ptid);
11773 else
11774 return string_printf ("Thread %d.%ld",
11775 ptid.pid (), ptid.lwp ());
11776 else
11777 return string_printf ("Thread %ld", ptid.lwp ());
11778 }
11779 }
11780
11781 /* Get the address of the thread local variable in OBJFILE which is
11782 stored at OFFSET within the thread local storage for thread PTID. */
11783
11784 CORE_ADDR
11785 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11786 CORE_ADDR offset)
11787 {
11788 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11789 {
11790 struct remote_state *rs = get_remote_state ();
11791 char *p = rs->buf.data ();
11792 char *endp = p + get_remote_packet_size ();
11793 enum packet_result result;
11794
11795 strcpy (p, "qGetTLSAddr:");
11796 p += strlen (p);
11797 p = write_ptid (p, endp, ptid);
11798 *p++ = ',';
11799 p += hexnumstr (p, offset);
11800 *p++ = ',';
11801 p += hexnumstr (p, lm);
11802 *p++ = '\0';
11803
11804 putpkt (rs->buf);
11805 getpkt (&rs->buf, 0);
11806 result = packet_ok (rs->buf,
11807 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11808 if (result == PACKET_OK)
11809 {
11810 ULONGEST addr;
11811
11812 unpack_varlen_hex (rs->buf.data (), &addr);
11813 return addr;
11814 }
11815 else if (result == PACKET_UNKNOWN)
11816 throw_error (TLS_GENERIC_ERROR,
11817 _("Remote target doesn't support qGetTLSAddr packet"));
11818 else
11819 throw_error (TLS_GENERIC_ERROR,
11820 _("Remote target failed to process qGetTLSAddr request"));
11821 }
11822 else
11823 throw_error (TLS_GENERIC_ERROR,
11824 _("TLS not supported or disabled on this target"));
11825 /* Not reached. */
11826 return 0;
11827 }
11828
11829 /* Provide thread local base, i.e. Thread Information Block address.
11830 Returns 1 if ptid is found and thread_local_base is non zero. */
11831
11832 bool
11833 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11834 {
11835 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11836 {
11837 struct remote_state *rs = get_remote_state ();
11838 char *p = rs->buf.data ();
11839 char *endp = p + get_remote_packet_size ();
11840 enum packet_result result;
11841
11842 strcpy (p, "qGetTIBAddr:");
11843 p += strlen (p);
11844 p = write_ptid (p, endp, ptid);
11845 *p++ = '\0';
11846
11847 putpkt (rs->buf);
11848 getpkt (&rs->buf, 0);
11849 result = packet_ok (rs->buf,
11850 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11851 if (result == PACKET_OK)
11852 {
11853 ULONGEST val;
11854 unpack_varlen_hex (rs->buf.data (), &val);
11855 if (addr)
11856 *addr = (CORE_ADDR) val;
11857 return true;
11858 }
11859 else if (result == PACKET_UNKNOWN)
11860 error (_("Remote target doesn't support qGetTIBAddr packet"));
11861 else
11862 error (_("Remote target failed to process qGetTIBAddr request"));
11863 }
11864 else
11865 error (_("qGetTIBAddr not supported or disabled on this target"));
11866 /* Not reached. */
11867 return false;
11868 }
11869
11870 /* Support for inferring a target description based on the current
11871 architecture and the size of a 'g' packet. While the 'g' packet
11872 can have any size (since optional registers can be left off the
11873 end), some sizes are easily recognizable given knowledge of the
11874 approximate architecture. */
11875
11876 struct remote_g_packet_guess
11877 {
11878 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11879 : bytes (bytes_),
11880 tdesc (tdesc_)
11881 {
11882 }
11883
11884 int bytes;
11885 const struct target_desc *tdesc;
11886 };
11887
11888 struct remote_g_packet_data : public allocate_on_obstack
11889 {
11890 std::vector<remote_g_packet_guess> guesses;
11891 };
11892
11893 static struct gdbarch_data *remote_g_packet_data_handle;
11894
11895 static void *
11896 remote_g_packet_data_init (struct obstack *obstack)
11897 {
11898 return new (obstack) remote_g_packet_data;
11899 }
11900
11901 void
11902 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11903 const struct target_desc *tdesc)
11904 {
11905 struct remote_g_packet_data *data
11906 = ((struct remote_g_packet_data *)
11907 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11908
11909 gdb_assert (tdesc != NULL);
11910
11911 for (const remote_g_packet_guess &guess : data->guesses)
11912 if (guess.bytes == bytes)
11913 internal_error (__FILE__, __LINE__,
11914 _("Duplicate g packet description added for size %d"),
11915 bytes);
11916
11917 data->guesses.emplace_back (bytes, tdesc);
11918 }
11919
11920 /* Return true if remote_read_description would do anything on this target
11921 and architecture, false otherwise. */
11922
11923 static bool
11924 remote_read_description_p (struct target_ops *target)
11925 {
11926 struct remote_g_packet_data *data
11927 = ((struct remote_g_packet_data *)
11928 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11929
11930 return !data->guesses.empty ();
11931 }
11932
11933 const struct target_desc *
11934 remote_target::read_description ()
11935 {
11936 struct remote_g_packet_data *data
11937 = ((struct remote_g_packet_data *)
11938 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11939
11940 /* Do not try this during initial connection, when we do not know
11941 whether there is a running but stopped thread. */
11942 if (!target_has_execution () || inferior_ptid == null_ptid)
11943 return beneath ()->read_description ();
11944
11945 if (!data->guesses.empty ())
11946 {
11947 int bytes = send_g_packet ();
11948
11949 for (const remote_g_packet_guess &guess : data->guesses)
11950 if (guess.bytes == bytes)
11951 return guess.tdesc;
11952
11953 /* We discard the g packet. A minor optimization would be to
11954 hold on to it, and fill the register cache once we have selected
11955 an architecture, but it's too tricky to do safely. */
11956 }
11957
11958 return beneath ()->read_description ();
11959 }
11960
11961 /* Remote file transfer support. This is host-initiated I/O, not
11962 target-initiated; for target-initiated, see remote-fileio.c. */
11963
11964 /* If *LEFT is at least the length of STRING, copy STRING to
11965 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11966 decrease *LEFT. Otherwise raise an error. */
11967
11968 static void
11969 remote_buffer_add_string (char **buffer, int *left, const char *string)
11970 {
11971 int len = strlen (string);
11972
11973 if (len > *left)
11974 error (_("Packet too long for target."));
11975
11976 memcpy (*buffer, string, len);
11977 *buffer += len;
11978 *left -= len;
11979
11980 /* NUL-terminate the buffer as a convenience, if there is
11981 room. */
11982 if (*left)
11983 **buffer = '\0';
11984 }
11985
11986 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11987 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11988 decrease *LEFT. Otherwise raise an error. */
11989
11990 static void
11991 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11992 int len)
11993 {
11994 if (2 * len > *left)
11995 error (_("Packet too long for target."));
11996
11997 bin2hex (bytes, *buffer, len);
11998 *buffer += 2 * len;
11999 *left -= 2 * len;
12000
12001 /* NUL-terminate the buffer as a convenience, if there is
12002 room. */
12003 if (*left)
12004 **buffer = '\0';
12005 }
12006
12007 /* If *LEFT is large enough, convert VALUE to hex and add it to
12008 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12009 decrease *LEFT. Otherwise raise an error. */
12010
12011 static void
12012 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12013 {
12014 int len = hexnumlen (value);
12015
12016 if (len > *left)
12017 error (_("Packet too long for target."));
12018
12019 hexnumstr (*buffer, value);
12020 *buffer += len;
12021 *left -= len;
12022
12023 /* NUL-terminate the buffer as a convenience, if there is
12024 room. */
12025 if (*left)
12026 **buffer = '\0';
12027 }
12028
12029 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12030 value, *REMOTE_ERRNO to the remote error number or zero if none
12031 was included, and *ATTACHMENT to point to the start of the annex
12032 if any. The length of the packet isn't needed here; there may
12033 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12034
12035 Return 0 if the packet could be parsed, -1 if it could not. If
12036 -1 is returned, the other variables may not be initialized. */
12037
12038 static int
12039 remote_hostio_parse_result (const char *buffer, int *retcode,
12040 int *remote_errno, const char **attachment)
12041 {
12042 char *p, *p2;
12043
12044 *remote_errno = 0;
12045 *attachment = NULL;
12046
12047 if (buffer[0] != 'F')
12048 return -1;
12049
12050 errno = 0;
12051 *retcode = strtol (&buffer[1], &p, 16);
12052 if (errno != 0 || p == &buffer[1])
12053 return -1;
12054
12055 /* Check for ",errno". */
12056 if (*p == ',')
12057 {
12058 errno = 0;
12059 *remote_errno = strtol (p + 1, &p2, 16);
12060 if (errno != 0 || p + 1 == p2)
12061 return -1;
12062 p = p2;
12063 }
12064
12065 /* Check for ";attachment". If there is no attachment, the
12066 packet should end here. */
12067 if (*p == ';')
12068 {
12069 *attachment = p + 1;
12070 return 0;
12071 }
12072 else if (*p == '\0')
12073 return 0;
12074 else
12075 return -1;
12076 }
12077
12078 /* Send a prepared I/O packet to the target and read its response.
12079 The prepared packet is in the global RS->BUF before this function
12080 is called, and the answer is there when we return.
12081
12082 COMMAND_BYTES is the length of the request to send, which may include
12083 binary data. WHICH_PACKET is the packet configuration to check
12084 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12085 is set to the error number and -1 is returned. Otherwise the value
12086 returned by the function is returned.
12087
12088 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12089 attachment is expected; an error will be reported if there's a
12090 mismatch. If one is found, *ATTACHMENT will be set to point into
12091 the packet buffer and *ATTACHMENT_LEN will be set to the
12092 attachment's length. */
12093
12094 int
12095 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12096 int *remote_errno, const char **attachment,
12097 int *attachment_len)
12098 {
12099 struct remote_state *rs = get_remote_state ();
12100 int ret, bytes_read;
12101 const char *attachment_tmp;
12102
12103 if (packet_support (which_packet) == PACKET_DISABLE)
12104 {
12105 *remote_errno = FILEIO_ENOSYS;
12106 return -1;
12107 }
12108
12109 putpkt_binary (rs->buf.data (), command_bytes);
12110 bytes_read = getpkt_sane (&rs->buf, 0);
12111
12112 /* If it timed out, something is wrong. Don't try to parse the
12113 buffer. */
12114 if (bytes_read < 0)
12115 {
12116 *remote_errno = FILEIO_EINVAL;
12117 return -1;
12118 }
12119
12120 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12121 {
12122 case PACKET_ERROR:
12123 *remote_errno = FILEIO_EINVAL;
12124 return -1;
12125 case PACKET_UNKNOWN:
12126 *remote_errno = FILEIO_ENOSYS;
12127 return -1;
12128 case PACKET_OK:
12129 break;
12130 }
12131
12132 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12133 &attachment_tmp))
12134 {
12135 *remote_errno = FILEIO_EINVAL;
12136 return -1;
12137 }
12138
12139 /* Make sure we saw an attachment if and only if we expected one. */
12140 if ((attachment_tmp == NULL && attachment != NULL)
12141 || (attachment_tmp != NULL && attachment == NULL))
12142 {
12143 *remote_errno = FILEIO_EINVAL;
12144 return -1;
12145 }
12146
12147 /* If an attachment was found, it must point into the packet buffer;
12148 work out how many bytes there were. */
12149 if (attachment_tmp != NULL)
12150 {
12151 *attachment = attachment_tmp;
12152 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12153 }
12154
12155 return ret;
12156 }
12157
12158 /* See declaration.h. */
12159
12160 void
12161 readahead_cache::invalidate ()
12162 {
12163 this->fd = -1;
12164 }
12165
12166 /* See declaration.h. */
12167
12168 void
12169 readahead_cache::invalidate_fd (int fd)
12170 {
12171 if (this->fd == fd)
12172 this->fd = -1;
12173 }
12174
12175 /* Set the filesystem remote_hostio functions that take FILENAME
12176 arguments will use. Return 0 on success, or -1 if an error
12177 occurs (and set *REMOTE_ERRNO). */
12178
12179 int
12180 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12181 int *remote_errno)
12182 {
12183 struct remote_state *rs = get_remote_state ();
12184 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12185 char *p = rs->buf.data ();
12186 int left = get_remote_packet_size () - 1;
12187 char arg[9];
12188 int ret;
12189
12190 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12191 return 0;
12192
12193 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12194 return 0;
12195
12196 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12197
12198 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12199 remote_buffer_add_string (&p, &left, arg);
12200
12201 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12202 remote_errno, NULL, NULL);
12203
12204 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12205 return 0;
12206
12207 if (ret == 0)
12208 rs->fs_pid = required_pid;
12209
12210 return ret;
12211 }
12212
12213 /* Implementation of to_fileio_open. */
12214
12215 int
12216 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12217 int flags, int mode, int warn_if_slow,
12218 int *remote_errno)
12219 {
12220 struct remote_state *rs = get_remote_state ();
12221 char *p = rs->buf.data ();
12222 int left = get_remote_packet_size () - 1;
12223
12224 if (warn_if_slow)
12225 {
12226 static int warning_issued = 0;
12227
12228 printf_unfiltered (_("Reading %s from remote target...\n"),
12229 filename);
12230
12231 if (!warning_issued)
12232 {
12233 warning (_("File transfers from remote targets can be slow."
12234 " Use \"set sysroot\" to access files locally"
12235 " instead."));
12236 warning_issued = 1;
12237 }
12238 }
12239
12240 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12241 return -1;
12242
12243 remote_buffer_add_string (&p, &left, "vFile:open:");
12244
12245 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12246 strlen (filename));
12247 remote_buffer_add_string (&p, &left, ",");
12248
12249 remote_buffer_add_int (&p, &left, flags);
12250 remote_buffer_add_string (&p, &left, ",");
12251
12252 remote_buffer_add_int (&p, &left, mode);
12253
12254 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12255 remote_errno, NULL, NULL);
12256 }
12257
12258 int
12259 remote_target::fileio_open (struct inferior *inf, const char *filename,
12260 int flags, int mode, int warn_if_slow,
12261 int *remote_errno)
12262 {
12263 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12264 remote_errno);
12265 }
12266
12267 /* Implementation of to_fileio_pwrite. */
12268
12269 int
12270 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12271 ULONGEST offset, int *remote_errno)
12272 {
12273 struct remote_state *rs = get_remote_state ();
12274 char *p = rs->buf.data ();
12275 int left = get_remote_packet_size ();
12276 int out_len;
12277
12278 rs->readahead_cache.invalidate_fd (fd);
12279
12280 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12281
12282 remote_buffer_add_int (&p, &left, fd);
12283 remote_buffer_add_string (&p, &left, ",");
12284
12285 remote_buffer_add_int (&p, &left, offset);
12286 remote_buffer_add_string (&p, &left, ",");
12287
12288 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12289 (get_remote_packet_size ()
12290 - (p - rs->buf.data ())));
12291
12292 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12293 remote_errno, NULL, NULL);
12294 }
12295
12296 int
12297 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12298 ULONGEST offset, int *remote_errno)
12299 {
12300 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12301 }
12302
12303 /* Helper for the implementation of to_fileio_pread. Read the file
12304 from the remote side with vFile:pread. */
12305
12306 int
12307 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12308 ULONGEST offset, int *remote_errno)
12309 {
12310 struct remote_state *rs = get_remote_state ();
12311 char *p = rs->buf.data ();
12312 const char *attachment;
12313 int left = get_remote_packet_size ();
12314 int ret, attachment_len;
12315 int read_len;
12316
12317 remote_buffer_add_string (&p, &left, "vFile:pread:");
12318
12319 remote_buffer_add_int (&p, &left, fd);
12320 remote_buffer_add_string (&p, &left, ",");
12321
12322 remote_buffer_add_int (&p, &left, len);
12323 remote_buffer_add_string (&p, &left, ",");
12324
12325 remote_buffer_add_int (&p, &left, offset);
12326
12327 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12328 remote_errno, &attachment,
12329 &attachment_len);
12330
12331 if (ret < 0)
12332 return ret;
12333
12334 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12335 read_buf, len);
12336 if (read_len != ret)
12337 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12338
12339 return ret;
12340 }
12341
12342 /* See declaration.h. */
12343
12344 int
12345 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12346 ULONGEST offset)
12347 {
12348 if (this->fd == fd
12349 && this->offset <= offset
12350 && offset < this->offset + this->bufsize)
12351 {
12352 ULONGEST max = this->offset + this->bufsize;
12353
12354 if (offset + len > max)
12355 len = max - offset;
12356
12357 memcpy (read_buf, this->buf + offset - this->offset, len);
12358 return len;
12359 }
12360
12361 return 0;
12362 }
12363
12364 /* Implementation of to_fileio_pread. */
12365
12366 int
12367 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12368 ULONGEST offset, int *remote_errno)
12369 {
12370 int ret;
12371 struct remote_state *rs = get_remote_state ();
12372 readahead_cache *cache = &rs->readahead_cache;
12373
12374 ret = cache->pread (fd, read_buf, len, offset);
12375 if (ret > 0)
12376 {
12377 cache->hit_count++;
12378
12379 remote_debug_printf ("readahead cache hit %s",
12380 pulongest (cache->hit_count));
12381 return ret;
12382 }
12383
12384 cache->miss_count++;
12385
12386 remote_debug_printf ("readahead cache miss %s",
12387 pulongest (cache->miss_count));
12388
12389 cache->fd = fd;
12390 cache->offset = offset;
12391 cache->bufsize = get_remote_packet_size ();
12392 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12393
12394 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12395 cache->offset, remote_errno);
12396 if (ret <= 0)
12397 {
12398 cache->invalidate_fd (fd);
12399 return ret;
12400 }
12401
12402 cache->bufsize = ret;
12403 return cache->pread (fd, read_buf, len, offset);
12404 }
12405
12406 int
12407 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12408 ULONGEST offset, int *remote_errno)
12409 {
12410 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12411 }
12412
12413 /* Implementation of to_fileio_close. */
12414
12415 int
12416 remote_target::remote_hostio_close (int fd, int *remote_errno)
12417 {
12418 struct remote_state *rs = get_remote_state ();
12419 char *p = rs->buf.data ();
12420 int left = get_remote_packet_size () - 1;
12421
12422 rs->readahead_cache.invalidate_fd (fd);
12423
12424 remote_buffer_add_string (&p, &left, "vFile:close:");
12425
12426 remote_buffer_add_int (&p, &left, fd);
12427
12428 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12429 remote_errno, NULL, NULL);
12430 }
12431
12432 int
12433 remote_target::fileio_close (int fd, int *remote_errno)
12434 {
12435 return remote_hostio_close (fd, remote_errno);
12436 }
12437
12438 /* Implementation of to_fileio_unlink. */
12439
12440 int
12441 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12442 int *remote_errno)
12443 {
12444 struct remote_state *rs = get_remote_state ();
12445 char *p = rs->buf.data ();
12446 int left = get_remote_packet_size () - 1;
12447
12448 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12449 return -1;
12450
12451 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12452
12453 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12454 strlen (filename));
12455
12456 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12457 remote_errno, NULL, NULL);
12458 }
12459
12460 int
12461 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12462 int *remote_errno)
12463 {
12464 return remote_hostio_unlink (inf, filename, remote_errno);
12465 }
12466
12467 /* Implementation of to_fileio_readlink. */
12468
12469 gdb::optional<std::string>
12470 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12471 int *remote_errno)
12472 {
12473 struct remote_state *rs = get_remote_state ();
12474 char *p = rs->buf.data ();
12475 const char *attachment;
12476 int left = get_remote_packet_size ();
12477 int len, attachment_len;
12478 int read_len;
12479
12480 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12481 return {};
12482
12483 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12484
12485 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12486 strlen (filename));
12487
12488 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12489 remote_errno, &attachment,
12490 &attachment_len);
12491
12492 if (len < 0)
12493 return {};
12494
12495 std::string ret (len, '\0');
12496
12497 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12498 (gdb_byte *) &ret[0], len);
12499 if (read_len != len)
12500 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12501
12502 return ret;
12503 }
12504
12505 /* Implementation of to_fileio_fstat. */
12506
12507 int
12508 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12509 {
12510 struct remote_state *rs = get_remote_state ();
12511 char *p = rs->buf.data ();
12512 int left = get_remote_packet_size ();
12513 int attachment_len, ret;
12514 const char *attachment;
12515 struct fio_stat fst;
12516 int read_len;
12517
12518 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12519
12520 remote_buffer_add_int (&p, &left, fd);
12521
12522 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12523 remote_errno, &attachment,
12524 &attachment_len);
12525 if (ret < 0)
12526 {
12527 if (*remote_errno != FILEIO_ENOSYS)
12528 return ret;
12529
12530 /* Strictly we should return -1, ENOSYS here, but when
12531 "set sysroot remote:" was implemented in August 2008
12532 BFD's need for a stat function was sidestepped with
12533 this hack. This was not remedied until March 2015
12534 so we retain the previous behavior to avoid breaking
12535 compatibility.
12536
12537 Note that the memset is a March 2015 addition; older
12538 GDBs set st_size *and nothing else* so the structure
12539 would have garbage in all other fields. This might
12540 break something but retaining the previous behavior
12541 here would be just too wrong. */
12542
12543 memset (st, 0, sizeof (struct stat));
12544 st->st_size = INT_MAX;
12545 return 0;
12546 }
12547
12548 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12549 (gdb_byte *) &fst, sizeof (fst));
12550
12551 if (read_len != ret)
12552 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12553
12554 if (read_len != sizeof (fst))
12555 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12556 read_len, (int) sizeof (fst));
12557
12558 remote_fileio_to_host_stat (&fst, st);
12559
12560 return 0;
12561 }
12562
12563 /* Implementation of to_filesystem_is_local. */
12564
12565 bool
12566 remote_target::filesystem_is_local ()
12567 {
12568 /* Valgrind GDB presents itself as a remote target but works
12569 on the local filesystem: it does not implement remote get
12570 and users are not expected to set a sysroot. To handle
12571 this case we treat the remote filesystem as local if the
12572 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12573 does not support vFile:open. */
12574 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12575 {
12576 enum packet_support ps = packet_support (PACKET_vFile_open);
12577
12578 if (ps == PACKET_SUPPORT_UNKNOWN)
12579 {
12580 int fd, remote_errno;
12581
12582 /* Try opening a file to probe support. The supplied
12583 filename is irrelevant, we only care about whether
12584 the stub recognizes the packet or not. */
12585 fd = remote_hostio_open (NULL, "just probing",
12586 FILEIO_O_RDONLY, 0700, 0,
12587 &remote_errno);
12588
12589 if (fd >= 0)
12590 remote_hostio_close (fd, &remote_errno);
12591
12592 ps = packet_support (PACKET_vFile_open);
12593 }
12594
12595 if (ps == PACKET_DISABLE)
12596 {
12597 static int warning_issued = 0;
12598
12599 if (!warning_issued)
12600 {
12601 warning (_("remote target does not support file"
12602 " transfer, attempting to access files"
12603 " from local filesystem."));
12604 warning_issued = 1;
12605 }
12606
12607 return true;
12608 }
12609 }
12610
12611 return false;
12612 }
12613
12614 static int
12615 remote_fileio_errno_to_host (int errnum)
12616 {
12617 switch (errnum)
12618 {
12619 case FILEIO_EPERM:
12620 return EPERM;
12621 case FILEIO_ENOENT:
12622 return ENOENT;
12623 case FILEIO_EINTR:
12624 return EINTR;
12625 case FILEIO_EIO:
12626 return EIO;
12627 case FILEIO_EBADF:
12628 return EBADF;
12629 case FILEIO_EACCES:
12630 return EACCES;
12631 case FILEIO_EFAULT:
12632 return EFAULT;
12633 case FILEIO_EBUSY:
12634 return EBUSY;
12635 case FILEIO_EEXIST:
12636 return EEXIST;
12637 case FILEIO_ENODEV:
12638 return ENODEV;
12639 case FILEIO_ENOTDIR:
12640 return ENOTDIR;
12641 case FILEIO_EISDIR:
12642 return EISDIR;
12643 case FILEIO_EINVAL:
12644 return EINVAL;
12645 case FILEIO_ENFILE:
12646 return ENFILE;
12647 case FILEIO_EMFILE:
12648 return EMFILE;
12649 case FILEIO_EFBIG:
12650 return EFBIG;
12651 case FILEIO_ENOSPC:
12652 return ENOSPC;
12653 case FILEIO_ESPIPE:
12654 return ESPIPE;
12655 case FILEIO_EROFS:
12656 return EROFS;
12657 case FILEIO_ENOSYS:
12658 return ENOSYS;
12659 case FILEIO_ENAMETOOLONG:
12660 return ENAMETOOLONG;
12661 }
12662 return -1;
12663 }
12664
12665 static char *
12666 remote_hostio_error (int errnum)
12667 {
12668 int host_error = remote_fileio_errno_to_host (errnum);
12669
12670 if (host_error == -1)
12671 error (_("Unknown remote I/O error %d"), errnum);
12672 else
12673 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12674 }
12675
12676 /* A RAII wrapper around a remote file descriptor. */
12677
12678 class scoped_remote_fd
12679 {
12680 public:
12681 scoped_remote_fd (remote_target *remote, int fd)
12682 : m_remote (remote), m_fd (fd)
12683 {
12684 }
12685
12686 ~scoped_remote_fd ()
12687 {
12688 if (m_fd != -1)
12689 {
12690 try
12691 {
12692 int remote_errno;
12693 m_remote->remote_hostio_close (m_fd, &remote_errno);
12694 }
12695 catch (...)
12696 {
12697 /* Swallow exception before it escapes the dtor. If
12698 something goes wrong, likely the connection is gone,
12699 and there's nothing else that can be done. */
12700 }
12701 }
12702 }
12703
12704 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12705
12706 /* Release ownership of the file descriptor, and return it. */
12707 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12708 {
12709 int fd = m_fd;
12710 m_fd = -1;
12711 return fd;
12712 }
12713
12714 /* Return the owned file descriptor. */
12715 int get () const noexcept
12716 {
12717 return m_fd;
12718 }
12719
12720 private:
12721 /* The remote target. */
12722 remote_target *m_remote;
12723
12724 /* The owned remote I/O file descriptor. */
12725 int m_fd;
12726 };
12727
12728 void
12729 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12730 {
12731 remote_target *remote = get_current_remote_target ();
12732
12733 if (remote == nullptr)
12734 error (_("command can only be used with remote target"));
12735
12736 remote->remote_file_put (local_file, remote_file, from_tty);
12737 }
12738
12739 void
12740 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12741 int from_tty)
12742 {
12743 int retcode, remote_errno, bytes, io_size;
12744 int bytes_in_buffer;
12745 int saw_eof;
12746 ULONGEST offset;
12747
12748 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12749 if (file == NULL)
12750 perror_with_name (local_file);
12751
12752 scoped_remote_fd fd
12753 (this, remote_hostio_open (NULL,
12754 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12755 | FILEIO_O_TRUNC),
12756 0700, 0, &remote_errno));
12757 if (fd.get () == -1)
12758 remote_hostio_error (remote_errno);
12759
12760 /* Send up to this many bytes at once. They won't all fit in the
12761 remote packet limit, so we'll transfer slightly fewer. */
12762 io_size = get_remote_packet_size ();
12763 gdb::byte_vector buffer (io_size);
12764
12765 bytes_in_buffer = 0;
12766 saw_eof = 0;
12767 offset = 0;
12768 while (bytes_in_buffer || !saw_eof)
12769 {
12770 if (!saw_eof)
12771 {
12772 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12773 io_size - bytes_in_buffer,
12774 file.get ());
12775 if (bytes == 0)
12776 {
12777 if (ferror (file.get ()))
12778 error (_("Error reading %s."), local_file);
12779 else
12780 {
12781 /* EOF. Unless there is something still in the
12782 buffer from the last iteration, we are done. */
12783 saw_eof = 1;
12784 if (bytes_in_buffer == 0)
12785 break;
12786 }
12787 }
12788 }
12789 else
12790 bytes = 0;
12791
12792 bytes += bytes_in_buffer;
12793 bytes_in_buffer = 0;
12794
12795 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12796 offset, &remote_errno);
12797
12798 if (retcode < 0)
12799 remote_hostio_error (remote_errno);
12800 else if (retcode == 0)
12801 error (_("Remote write of %d bytes returned 0!"), bytes);
12802 else if (retcode < bytes)
12803 {
12804 /* Short write. Save the rest of the read data for the next
12805 write. */
12806 bytes_in_buffer = bytes - retcode;
12807 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12808 }
12809
12810 offset += retcode;
12811 }
12812
12813 if (remote_hostio_close (fd.release (), &remote_errno))
12814 remote_hostio_error (remote_errno);
12815
12816 if (from_tty)
12817 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12818 }
12819
12820 void
12821 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12822 {
12823 remote_target *remote = get_current_remote_target ();
12824
12825 if (remote == nullptr)
12826 error (_("command can only be used with remote target"));
12827
12828 remote->remote_file_get (remote_file, local_file, from_tty);
12829 }
12830
12831 void
12832 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12833 int from_tty)
12834 {
12835 int remote_errno, bytes, io_size;
12836 ULONGEST offset;
12837
12838 scoped_remote_fd fd
12839 (this, remote_hostio_open (NULL,
12840 remote_file, FILEIO_O_RDONLY, 0, 0,
12841 &remote_errno));
12842 if (fd.get () == -1)
12843 remote_hostio_error (remote_errno);
12844
12845 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12846 if (file == NULL)
12847 perror_with_name (local_file);
12848
12849 /* Send up to this many bytes at once. They won't all fit in the
12850 remote packet limit, so we'll transfer slightly fewer. */
12851 io_size = get_remote_packet_size ();
12852 gdb::byte_vector buffer (io_size);
12853
12854 offset = 0;
12855 while (1)
12856 {
12857 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12858 &remote_errno);
12859 if (bytes == 0)
12860 /* Success, but no bytes, means end-of-file. */
12861 break;
12862 if (bytes == -1)
12863 remote_hostio_error (remote_errno);
12864
12865 offset += bytes;
12866
12867 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12868 if (bytes == 0)
12869 perror_with_name (local_file);
12870 }
12871
12872 if (remote_hostio_close (fd.release (), &remote_errno))
12873 remote_hostio_error (remote_errno);
12874
12875 if (from_tty)
12876 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12877 }
12878
12879 void
12880 remote_file_delete (const char *remote_file, int from_tty)
12881 {
12882 remote_target *remote = get_current_remote_target ();
12883
12884 if (remote == nullptr)
12885 error (_("command can only be used with remote target"));
12886
12887 remote->remote_file_delete (remote_file, from_tty);
12888 }
12889
12890 void
12891 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12892 {
12893 int retcode, remote_errno;
12894
12895 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12896 if (retcode == -1)
12897 remote_hostio_error (remote_errno);
12898
12899 if (from_tty)
12900 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12901 }
12902
12903 static void
12904 remote_put_command (const char *args, int from_tty)
12905 {
12906 if (args == NULL)
12907 error_no_arg (_("file to put"));
12908
12909 gdb_argv argv (args);
12910 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12911 error (_("Invalid parameters to remote put"));
12912
12913 remote_file_put (argv[0], argv[1], from_tty);
12914 }
12915
12916 static void
12917 remote_get_command (const char *args, int from_tty)
12918 {
12919 if (args == NULL)
12920 error_no_arg (_("file to get"));
12921
12922 gdb_argv argv (args);
12923 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12924 error (_("Invalid parameters to remote get"));
12925
12926 remote_file_get (argv[0], argv[1], from_tty);
12927 }
12928
12929 static void
12930 remote_delete_command (const char *args, int from_tty)
12931 {
12932 if (args == NULL)
12933 error_no_arg (_("file to delete"));
12934
12935 gdb_argv argv (args);
12936 if (argv[0] == NULL || argv[1] != NULL)
12937 error (_("Invalid parameters to remote delete"));
12938
12939 remote_file_delete (argv[0], from_tty);
12940 }
12941
12942 bool
12943 remote_target::can_execute_reverse ()
12944 {
12945 if (packet_support (PACKET_bs) == PACKET_ENABLE
12946 || packet_support (PACKET_bc) == PACKET_ENABLE)
12947 return true;
12948 else
12949 return false;
12950 }
12951
12952 bool
12953 remote_target::supports_non_stop ()
12954 {
12955 return true;
12956 }
12957
12958 bool
12959 remote_target::supports_disable_randomization ()
12960 {
12961 /* Only supported in extended mode. */
12962 return false;
12963 }
12964
12965 bool
12966 remote_target::supports_multi_process ()
12967 {
12968 struct remote_state *rs = get_remote_state ();
12969
12970 return remote_multi_process_p (rs);
12971 }
12972
12973 static int
12974 remote_supports_cond_tracepoints ()
12975 {
12976 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12977 }
12978
12979 bool
12980 remote_target::supports_evaluation_of_breakpoint_conditions ()
12981 {
12982 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12983 }
12984
12985 static int
12986 remote_supports_fast_tracepoints ()
12987 {
12988 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12989 }
12990
12991 static int
12992 remote_supports_static_tracepoints ()
12993 {
12994 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12995 }
12996
12997 static int
12998 remote_supports_install_in_trace ()
12999 {
13000 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13001 }
13002
13003 bool
13004 remote_target::supports_enable_disable_tracepoint ()
13005 {
13006 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13007 == PACKET_ENABLE);
13008 }
13009
13010 bool
13011 remote_target::supports_string_tracing ()
13012 {
13013 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13014 }
13015
13016 bool
13017 remote_target::can_run_breakpoint_commands ()
13018 {
13019 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13020 }
13021
13022 void
13023 remote_target::trace_init ()
13024 {
13025 struct remote_state *rs = get_remote_state ();
13026
13027 putpkt ("QTinit");
13028 remote_get_noisy_reply ();
13029 if (strcmp (rs->buf.data (), "OK") != 0)
13030 error (_("Target does not support this command."));
13031 }
13032
13033 /* Recursive routine to walk through command list including loops, and
13034 download packets for each command. */
13035
13036 void
13037 remote_target::remote_download_command_source (int num, ULONGEST addr,
13038 struct command_line *cmds)
13039 {
13040 struct remote_state *rs = get_remote_state ();
13041 struct command_line *cmd;
13042
13043 for (cmd = cmds; cmd; cmd = cmd->next)
13044 {
13045 QUIT; /* Allow user to bail out with ^C. */
13046 strcpy (rs->buf.data (), "QTDPsrc:");
13047 encode_source_string (num, addr, "cmd", cmd->line,
13048 rs->buf.data () + strlen (rs->buf.data ()),
13049 rs->buf.size () - strlen (rs->buf.data ()));
13050 putpkt (rs->buf);
13051 remote_get_noisy_reply ();
13052 if (strcmp (rs->buf.data (), "OK"))
13053 warning (_("Target does not support source download."));
13054
13055 if (cmd->control_type == while_control
13056 || cmd->control_type == while_stepping_control)
13057 {
13058 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13059
13060 QUIT; /* Allow user to bail out with ^C. */
13061 strcpy (rs->buf.data (), "QTDPsrc:");
13062 encode_source_string (num, addr, "cmd", "end",
13063 rs->buf.data () + strlen (rs->buf.data ()),
13064 rs->buf.size () - strlen (rs->buf.data ()));
13065 putpkt (rs->buf);
13066 remote_get_noisy_reply ();
13067 if (strcmp (rs->buf.data (), "OK"))
13068 warning (_("Target does not support source download."));
13069 }
13070 }
13071 }
13072
13073 void
13074 remote_target::download_tracepoint (struct bp_location *loc)
13075 {
13076 CORE_ADDR tpaddr;
13077 char addrbuf[40];
13078 std::vector<std::string> tdp_actions;
13079 std::vector<std::string> stepping_actions;
13080 char *pkt;
13081 struct breakpoint *b = loc->owner;
13082 struct tracepoint *t = (struct tracepoint *) b;
13083 struct remote_state *rs = get_remote_state ();
13084 int ret;
13085 const char *err_msg = _("Tracepoint packet too large for target.");
13086 size_t size_left;
13087
13088 /* We use a buffer other than rs->buf because we'll build strings
13089 across multiple statements, and other statements in between could
13090 modify rs->buf. */
13091 gdb::char_vector buf (get_remote_packet_size ());
13092
13093 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13094
13095 tpaddr = loc->address;
13096 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13097 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13098 b->number, addrbuf, /* address */
13099 (b->enable_state == bp_enabled ? 'E' : 'D'),
13100 t->step_count, t->pass_count);
13101
13102 if (ret < 0 || ret >= buf.size ())
13103 error ("%s", err_msg);
13104
13105 /* Fast tracepoints are mostly handled by the target, but we can
13106 tell the target how big of an instruction block should be moved
13107 around. */
13108 if (b->type == bp_fast_tracepoint)
13109 {
13110 /* Only test for support at download time; we may not know
13111 target capabilities at definition time. */
13112 if (remote_supports_fast_tracepoints ())
13113 {
13114 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13115 NULL))
13116 {
13117 size_left = buf.size () - strlen (buf.data ());
13118 ret = snprintf (buf.data () + strlen (buf.data ()),
13119 size_left, ":F%x",
13120 gdb_insn_length (loc->gdbarch, tpaddr));
13121
13122 if (ret < 0 || ret >= size_left)
13123 error ("%s", err_msg);
13124 }
13125 else
13126 /* If it passed validation at definition but fails now,
13127 something is very wrong. */
13128 internal_error (__FILE__, __LINE__,
13129 _("Fast tracepoint not "
13130 "valid during download"));
13131 }
13132 else
13133 /* Fast tracepoints are functionally identical to regular
13134 tracepoints, so don't take lack of support as a reason to
13135 give up on the trace run. */
13136 warning (_("Target does not support fast tracepoints, "
13137 "downloading %d as regular tracepoint"), b->number);
13138 }
13139 else if (b->type == bp_static_tracepoint)
13140 {
13141 /* Only test for support at download time; we may not know
13142 target capabilities at definition time. */
13143 if (remote_supports_static_tracepoints ())
13144 {
13145 struct static_tracepoint_marker marker;
13146
13147 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13148 {
13149 size_left = buf.size () - strlen (buf.data ());
13150 ret = snprintf (buf.data () + strlen (buf.data ()),
13151 size_left, ":S");
13152
13153 if (ret < 0 || ret >= size_left)
13154 error ("%s", err_msg);
13155 }
13156 else
13157 error (_("Static tracepoint not valid during download"));
13158 }
13159 else
13160 /* Fast tracepoints are functionally identical to regular
13161 tracepoints, so don't take lack of support as a reason
13162 to give up on the trace run. */
13163 error (_("Target does not support static tracepoints"));
13164 }
13165 /* If the tracepoint has a conditional, make it into an agent
13166 expression and append to the definition. */
13167 if (loc->cond)
13168 {
13169 /* Only test support at download time, we may not know target
13170 capabilities at definition time. */
13171 if (remote_supports_cond_tracepoints ())
13172 {
13173 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13174 loc->cond.get ());
13175
13176 size_left = buf.size () - strlen (buf.data ());
13177
13178 ret = snprintf (buf.data () + strlen (buf.data ()),
13179 size_left, ":X%x,", aexpr->len);
13180
13181 if (ret < 0 || ret >= size_left)
13182 error ("%s", err_msg);
13183
13184 size_left = buf.size () - strlen (buf.data ());
13185
13186 /* Two bytes to encode each aexpr byte, plus the terminating
13187 null byte. */
13188 if (aexpr->len * 2 + 1 > size_left)
13189 error ("%s", err_msg);
13190
13191 pkt = buf.data () + strlen (buf.data ());
13192
13193 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13194 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13195 *pkt = '\0';
13196 }
13197 else
13198 warning (_("Target does not support conditional tracepoints, "
13199 "ignoring tp %d cond"), b->number);
13200 }
13201
13202 if (b->commands || *default_collect)
13203 {
13204 size_left = buf.size () - strlen (buf.data ());
13205
13206 ret = snprintf (buf.data () + strlen (buf.data ()),
13207 size_left, "-");
13208
13209 if (ret < 0 || ret >= size_left)
13210 error ("%s", err_msg);
13211 }
13212
13213 putpkt (buf.data ());
13214 remote_get_noisy_reply ();
13215 if (strcmp (rs->buf.data (), "OK"))
13216 error (_("Target does not support tracepoints."));
13217
13218 /* do_single_steps (t); */
13219 for (auto action_it = tdp_actions.begin ();
13220 action_it != tdp_actions.end (); action_it++)
13221 {
13222 QUIT; /* Allow user to bail out with ^C. */
13223
13224 bool has_more = ((action_it + 1) != tdp_actions.end ()
13225 || !stepping_actions.empty ());
13226
13227 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13228 b->number, addrbuf, /* address */
13229 action_it->c_str (),
13230 has_more ? '-' : 0);
13231
13232 if (ret < 0 || ret >= buf.size ())
13233 error ("%s", err_msg);
13234
13235 putpkt (buf.data ());
13236 remote_get_noisy_reply ();
13237 if (strcmp (rs->buf.data (), "OK"))
13238 error (_("Error on target while setting tracepoints."));
13239 }
13240
13241 for (auto action_it = stepping_actions.begin ();
13242 action_it != stepping_actions.end (); action_it++)
13243 {
13244 QUIT; /* Allow user to bail out with ^C. */
13245
13246 bool is_first = action_it == stepping_actions.begin ();
13247 bool has_more = (action_it + 1) != stepping_actions.end ();
13248
13249 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13250 b->number, addrbuf, /* address */
13251 is_first ? "S" : "",
13252 action_it->c_str (),
13253 has_more ? "-" : "");
13254
13255 if (ret < 0 || ret >= buf.size ())
13256 error ("%s", err_msg);
13257
13258 putpkt (buf.data ());
13259 remote_get_noisy_reply ();
13260 if (strcmp (rs->buf.data (), "OK"))
13261 error (_("Error on target while setting tracepoints."));
13262 }
13263
13264 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13265 {
13266 if (b->location != NULL)
13267 {
13268 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13269
13270 if (ret < 0 || ret >= buf.size ())
13271 error ("%s", err_msg);
13272
13273 encode_source_string (b->number, loc->address, "at",
13274 event_location_to_string (b->location.get ()),
13275 buf.data () + strlen (buf.data ()),
13276 buf.size () - strlen (buf.data ()));
13277 putpkt (buf.data ());
13278 remote_get_noisy_reply ();
13279 if (strcmp (rs->buf.data (), "OK"))
13280 warning (_("Target does not support source download."));
13281 }
13282 if (b->cond_string)
13283 {
13284 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13285
13286 if (ret < 0 || ret >= buf.size ())
13287 error ("%s", err_msg);
13288
13289 encode_source_string (b->number, loc->address,
13290 "cond", b->cond_string,
13291 buf.data () + strlen (buf.data ()),
13292 buf.size () - strlen (buf.data ()));
13293 putpkt (buf.data ());
13294 remote_get_noisy_reply ();
13295 if (strcmp (rs->buf.data (), "OK"))
13296 warning (_("Target does not support source download."));
13297 }
13298 remote_download_command_source (b->number, loc->address,
13299 breakpoint_commands (b));
13300 }
13301 }
13302
13303 bool
13304 remote_target::can_download_tracepoint ()
13305 {
13306 struct remote_state *rs = get_remote_state ();
13307 struct trace_status *ts;
13308 int status;
13309
13310 /* Don't try to install tracepoints until we've relocated our
13311 symbols, and fetched and merged the target's tracepoint list with
13312 ours. */
13313 if (rs->starting_up)
13314 return false;
13315
13316 ts = current_trace_status ();
13317 status = get_trace_status (ts);
13318
13319 if (status == -1 || !ts->running_known || !ts->running)
13320 return false;
13321
13322 /* If we are in a tracing experiment, but remote stub doesn't support
13323 installing tracepoint in trace, we have to return. */
13324 if (!remote_supports_install_in_trace ())
13325 return false;
13326
13327 return true;
13328 }
13329
13330
13331 void
13332 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13333 {
13334 struct remote_state *rs = get_remote_state ();
13335 char *p;
13336
13337 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13338 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13339 tsv.builtin);
13340 p = rs->buf.data () + strlen (rs->buf.data ());
13341 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13342 >= get_remote_packet_size ())
13343 error (_("Trace state variable name too long for tsv definition packet"));
13344 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13345 *p++ = '\0';
13346 putpkt (rs->buf);
13347 remote_get_noisy_reply ();
13348 if (rs->buf[0] == '\0')
13349 error (_("Target does not support this command."));
13350 if (strcmp (rs->buf.data (), "OK") != 0)
13351 error (_("Error on target while downloading trace state variable."));
13352 }
13353
13354 void
13355 remote_target::enable_tracepoint (struct bp_location *location)
13356 {
13357 struct remote_state *rs = get_remote_state ();
13358
13359 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13360 location->owner->number,
13361 phex (location->address, sizeof (CORE_ADDR)));
13362 putpkt (rs->buf);
13363 remote_get_noisy_reply ();
13364 if (rs->buf[0] == '\0')
13365 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13366 if (strcmp (rs->buf.data (), "OK") != 0)
13367 error (_("Error on target while enabling tracepoint."));
13368 }
13369
13370 void
13371 remote_target::disable_tracepoint (struct bp_location *location)
13372 {
13373 struct remote_state *rs = get_remote_state ();
13374
13375 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13376 location->owner->number,
13377 phex (location->address, sizeof (CORE_ADDR)));
13378 putpkt (rs->buf);
13379 remote_get_noisy_reply ();
13380 if (rs->buf[0] == '\0')
13381 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13382 if (strcmp (rs->buf.data (), "OK") != 0)
13383 error (_("Error on target while disabling tracepoint."));
13384 }
13385
13386 void
13387 remote_target::trace_set_readonly_regions ()
13388 {
13389 asection *s;
13390 bfd_size_type size;
13391 bfd_vma vma;
13392 int anysecs = 0;
13393 int offset = 0;
13394
13395 if (!current_program_space->exec_bfd ())
13396 return; /* No information to give. */
13397
13398 struct remote_state *rs = get_remote_state ();
13399
13400 strcpy (rs->buf.data (), "QTro");
13401 offset = strlen (rs->buf.data ());
13402 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
13403 {
13404 char tmp1[40], tmp2[40];
13405 int sec_length;
13406
13407 if ((s->flags & SEC_LOAD) == 0 ||
13408 /* (s->flags & SEC_CODE) == 0 || */
13409 (s->flags & SEC_READONLY) == 0)
13410 continue;
13411
13412 anysecs = 1;
13413 vma = bfd_section_vma (s);
13414 size = bfd_section_size (s);
13415 sprintf_vma (tmp1, vma);
13416 sprintf_vma (tmp2, vma + size);
13417 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13418 if (offset + sec_length + 1 > rs->buf.size ())
13419 {
13420 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13421 warning (_("\
13422 Too many sections for read-only sections definition packet."));
13423 break;
13424 }
13425 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13426 tmp1, tmp2);
13427 offset += sec_length;
13428 }
13429 if (anysecs)
13430 {
13431 putpkt (rs->buf);
13432 getpkt (&rs->buf, 0);
13433 }
13434 }
13435
13436 void
13437 remote_target::trace_start ()
13438 {
13439 struct remote_state *rs = get_remote_state ();
13440
13441 putpkt ("QTStart");
13442 remote_get_noisy_reply ();
13443 if (rs->buf[0] == '\0')
13444 error (_("Target does not support this command."));
13445 if (strcmp (rs->buf.data (), "OK") != 0)
13446 error (_("Bogus reply from target: %s"), rs->buf.data ());
13447 }
13448
13449 int
13450 remote_target::get_trace_status (struct trace_status *ts)
13451 {
13452 /* Initialize it just to avoid a GCC false warning. */
13453 char *p = NULL;
13454 enum packet_result result;
13455 struct remote_state *rs = get_remote_state ();
13456
13457 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13458 return -1;
13459
13460 /* FIXME we need to get register block size some other way. */
13461 trace_regblock_size
13462 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13463
13464 putpkt ("qTStatus");
13465
13466 try
13467 {
13468 p = remote_get_noisy_reply ();
13469 }
13470 catch (const gdb_exception_error &ex)
13471 {
13472 if (ex.error != TARGET_CLOSE_ERROR)
13473 {
13474 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13475 return -1;
13476 }
13477 throw;
13478 }
13479
13480 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13481
13482 /* If the remote target doesn't do tracing, flag it. */
13483 if (result == PACKET_UNKNOWN)
13484 return -1;
13485
13486 /* We're working with a live target. */
13487 ts->filename = NULL;
13488
13489 if (*p++ != 'T')
13490 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13491
13492 /* Function 'parse_trace_status' sets default value of each field of
13493 'ts' at first, so we don't have to do it here. */
13494 parse_trace_status (p, ts);
13495
13496 return ts->running;
13497 }
13498
13499 void
13500 remote_target::get_tracepoint_status (struct breakpoint *bp,
13501 struct uploaded_tp *utp)
13502 {
13503 struct remote_state *rs = get_remote_state ();
13504 char *reply;
13505 struct bp_location *loc;
13506 struct tracepoint *tp = (struct tracepoint *) bp;
13507 size_t size = get_remote_packet_size ();
13508
13509 if (tp)
13510 {
13511 tp->hit_count = 0;
13512 tp->traceframe_usage = 0;
13513 for (loc = tp->loc; loc; loc = loc->next)
13514 {
13515 /* If the tracepoint was never downloaded, don't go asking for
13516 any status. */
13517 if (tp->number_on_target == 0)
13518 continue;
13519 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13520 phex_nz (loc->address, 0));
13521 putpkt (rs->buf);
13522 reply = remote_get_noisy_reply ();
13523 if (reply && *reply)
13524 {
13525 if (*reply == 'V')
13526 parse_tracepoint_status (reply + 1, bp, utp);
13527 }
13528 }
13529 }
13530 else if (utp)
13531 {
13532 utp->hit_count = 0;
13533 utp->traceframe_usage = 0;
13534 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13535 phex_nz (utp->addr, 0));
13536 putpkt (rs->buf);
13537 reply = remote_get_noisy_reply ();
13538 if (reply && *reply)
13539 {
13540 if (*reply == 'V')
13541 parse_tracepoint_status (reply + 1, bp, utp);
13542 }
13543 }
13544 }
13545
13546 void
13547 remote_target::trace_stop ()
13548 {
13549 struct remote_state *rs = get_remote_state ();
13550
13551 putpkt ("QTStop");
13552 remote_get_noisy_reply ();
13553 if (rs->buf[0] == '\0')
13554 error (_("Target does not support this command."));
13555 if (strcmp (rs->buf.data (), "OK") != 0)
13556 error (_("Bogus reply from target: %s"), rs->buf.data ());
13557 }
13558
13559 int
13560 remote_target::trace_find (enum trace_find_type type, int num,
13561 CORE_ADDR addr1, CORE_ADDR addr2,
13562 int *tpp)
13563 {
13564 struct remote_state *rs = get_remote_state ();
13565 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13566 char *p, *reply;
13567 int target_frameno = -1, target_tracept = -1;
13568
13569 /* Lookups other than by absolute frame number depend on the current
13570 trace selected, so make sure it is correct on the remote end
13571 first. */
13572 if (type != tfind_number)
13573 set_remote_traceframe ();
13574
13575 p = rs->buf.data ();
13576 strcpy (p, "QTFrame:");
13577 p = strchr (p, '\0');
13578 switch (type)
13579 {
13580 case tfind_number:
13581 xsnprintf (p, endbuf - p, "%x", num);
13582 break;
13583 case tfind_pc:
13584 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13585 break;
13586 case tfind_tp:
13587 xsnprintf (p, endbuf - p, "tdp:%x", num);
13588 break;
13589 case tfind_range:
13590 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13591 phex_nz (addr2, 0));
13592 break;
13593 case tfind_outside:
13594 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13595 phex_nz (addr2, 0));
13596 break;
13597 default:
13598 error (_("Unknown trace find type %d"), type);
13599 }
13600
13601 putpkt (rs->buf);
13602 reply = remote_get_noisy_reply ();
13603 if (*reply == '\0')
13604 error (_("Target does not support this command."));
13605
13606 while (reply && *reply)
13607 switch (*reply)
13608 {
13609 case 'F':
13610 p = ++reply;
13611 target_frameno = (int) strtol (p, &reply, 16);
13612 if (reply == p)
13613 error (_("Unable to parse trace frame number"));
13614 /* Don't update our remote traceframe number cache on failure
13615 to select a remote traceframe. */
13616 if (target_frameno == -1)
13617 return -1;
13618 break;
13619 case 'T':
13620 p = ++reply;
13621 target_tracept = (int) strtol (p, &reply, 16);
13622 if (reply == p)
13623 error (_("Unable to parse tracepoint number"));
13624 break;
13625 case 'O': /* "OK"? */
13626 if (reply[1] == 'K' && reply[2] == '\0')
13627 reply += 2;
13628 else
13629 error (_("Bogus reply from target: %s"), reply);
13630 break;
13631 default:
13632 error (_("Bogus reply from target: %s"), reply);
13633 }
13634 if (tpp)
13635 *tpp = target_tracept;
13636
13637 rs->remote_traceframe_number = target_frameno;
13638 return target_frameno;
13639 }
13640
13641 bool
13642 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13643 {
13644 struct remote_state *rs = get_remote_state ();
13645 char *reply;
13646 ULONGEST uval;
13647
13648 set_remote_traceframe ();
13649
13650 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13651 putpkt (rs->buf);
13652 reply = remote_get_noisy_reply ();
13653 if (reply && *reply)
13654 {
13655 if (*reply == 'V')
13656 {
13657 unpack_varlen_hex (reply + 1, &uval);
13658 *val = (LONGEST) uval;
13659 return true;
13660 }
13661 }
13662 return false;
13663 }
13664
13665 int
13666 remote_target::save_trace_data (const char *filename)
13667 {
13668 struct remote_state *rs = get_remote_state ();
13669 char *p, *reply;
13670
13671 p = rs->buf.data ();
13672 strcpy (p, "QTSave:");
13673 p += strlen (p);
13674 if ((p - rs->buf.data ()) + strlen (filename) * 2
13675 >= get_remote_packet_size ())
13676 error (_("Remote file name too long for trace save packet"));
13677 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13678 *p++ = '\0';
13679 putpkt (rs->buf);
13680 reply = remote_get_noisy_reply ();
13681 if (*reply == '\0')
13682 error (_("Target does not support this command."));
13683 if (strcmp (reply, "OK") != 0)
13684 error (_("Bogus reply from target: %s"), reply);
13685 return 0;
13686 }
13687
13688 /* This is basically a memory transfer, but needs to be its own packet
13689 because we don't know how the target actually organizes its trace
13690 memory, plus we want to be able to ask for as much as possible, but
13691 not be unhappy if we don't get as much as we ask for. */
13692
13693 LONGEST
13694 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13695 {
13696 struct remote_state *rs = get_remote_state ();
13697 char *reply;
13698 char *p;
13699 int rslt;
13700
13701 p = rs->buf.data ();
13702 strcpy (p, "qTBuffer:");
13703 p += strlen (p);
13704 p += hexnumstr (p, offset);
13705 *p++ = ',';
13706 p += hexnumstr (p, len);
13707 *p++ = '\0';
13708
13709 putpkt (rs->buf);
13710 reply = remote_get_noisy_reply ();
13711 if (reply && *reply)
13712 {
13713 /* 'l' by itself means we're at the end of the buffer and
13714 there is nothing more to get. */
13715 if (*reply == 'l')
13716 return 0;
13717
13718 /* Convert the reply into binary. Limit the number of bytes to
13719 convert according to our passed-in buffer size, rather than
13720 what was returned in the packet; if the target is
13721 unexpectedly generous and gives us a bigger reply than we
13722 asked for, we don't want to crash. */
13723 rslt = hex2bin (reply, buf, len);
13724 return rslt;
13725 }
13726
13727 /* Something went wrong, flag as an error. */
13728 return -1;
13729 }
13730
13731 void
13732 remote_target::set_disconnected_tracing (int val)
13733 {
13734 struct remote_state *rs = get_remote_state ();
13735
13736 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13737 {
13738 char *reply;
13739
13740 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13741 "QTDisconnected:%x", val);
13742 putpkt (rs->buf);
13743 reply = remote_get_noisy_reply ();
13744 if (*reply == '\0')
13745 error (_("Target does not support this command."));
13746 if (strcmp (reply, "OK") != 0)
13747 error (_("Bogus reply from target: %s"), reply);
13748 }
13749 else if (val)
13750 warning (_("Target does not support disconnected tracing."));
13751 }
13752
13753 int
13754 remote_target::core_of_thread (ptid_t ptid)
13755 {
13756 thread_info *info = find_thread_ptid (this, ptid);
13757
13758 if (info != NULL && info->priv != NULL)
13759 return get_remote_thread_info (info)->core;
13760
13761 return -1;
13762 }
13763
13764 void
13765 remote_target::set_circular_trace_buffer (int val)
13766 {
13767 struct remote_state *rs = get_remote_state ();
13768 char *reply;
13769
13770 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13771 "QTBuffer:circular:%x", val);
13772 putpkt (rs->buf);
13773 reply = remote_get_noisy_reply ();
13774 if (*reply == '\0')
13775 error (_("Target does not support this command."));
13776 if (strcmp (reply, "OK") != 0)
13777 error (_("Bogus reply from target: %s"), reply);
13778 }
13779
13780 traceframe_info_up
13781 remote_target::traceframe_info ()
13782 {
13783 gdb::optional<gdb::char_vector> text
13784 = target_read_stralloc (current_inferior ()->top_target (),
13785 TARGET_OBJECT_TRACEFRAME_INFO,
13786 NULL);
13787 if (text)
13788 return parse_traceframe_info (text->data ());
13789
13790 return NULL;
13791 }
13792
13793 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13794 instruction on which a fast tracepoint may be placed. Returns -1
13795 if the packet is not supported, and 0 if the minimum instruction
13796 length is unknown. */
13797
13798 int
13799 remote_target::get_min_fast_tracepoint_insn_len ()
13800 {
13801 struct remote_state *rs = get_remote_state ();
13802 char *reply;
13803
13804 /* If we're not debugging a process yet, the IPA can't be
13805 loaded. */
13806 if (!target_has_execution ())
13807 return 0;
13808
13809 /* Make sure the remote is pointing at the right process. */
13810 set_general_process ();
13811
13812 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13813 putpkt (rs->buf);
13814 reply = remote_get_noisy_reply ();
13815 if (*reply == '\0')
13816 return -1;
13817 else
13818 {
13819 ULONGEST min_insn_len;
13820
13821 unpack_varlen_hex (reply, &min_insn_len);
13822
13823 return (int) min_insn_len;
13824 }
13825 }
13826
13827 void
13828 remote_target::set_trace_buffer_size (LONGEST val)
13829 {
13830 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13831 {
13832 struct remote_state *rs = get_remote_state ();
13833 char *buf = rs->buf.data ();
13834 char *endbuf = buf + get_remote_packet_size ();
13835 enum packet_result result;
13836
13837 gdb_assert (val >= 0 || val == -1);
13838 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13839 /* Send -1 as literal "-1" to avoid host size dependency. */
13840 if (val < 0)
13841 {
13842 *buf++ = '-';
13843 buf += hexnumstr (buf, (ULONGEST) -val);
13844 }
13845 else
13846 buf += hexnumstr (buf, (ULONGEST) val);
13847
13848 putpkt (rs->buf);
13849 remote_get_noisy_reply ();
13850 result = packet_ok (rs->buf,
13851 &remote_protocol_packets[PACKET_QTBuffer_size]);
13852
13853 if (result != PACKET_OK)
13854 warning (_("Bogus reply from target: %s"), rs->buf.data ());
13855 }
13856 }
13857
13858 bool
13859 remote_target::set_trace_notes (const char *user, const char *notes,
13860 const char *stop_notes)
13861 {
13862 struct remote_state *rs = get_remote_state ();
13863 char *reply;
13864 char *buf = rs->buf.data ();
13865 char *endbuf = buf + get_remote_packet_size ();
13866 int nbytes;
13867
13868 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13869 if (user)
13870 {
13871 buf += xsnprintf (buf, endbuf - buf, "user:");
13872 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13873 buf += 2 * nbytes;
13874 *buf++ = ';';
13875 }
13876 if (notes)
13877 {
13878 buf += xsnprintf (buf, endbuf - buf, "notes:");
13879 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13880 buf += 2 * nbytes;
13881 *buf++ = ';';
13882 }
13883 if (stop_notes)
13884 {
13885 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13886 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13887 buf += 2 * nbytes;
13888 *buf++ = ';';
13889 }
13890 /* Ensure the buffer is terminated. */
13891 *buf = '\0';
13892
13893 putpkt (rs->buf);
13894 reply = remote_get_noisy_reply ();
13895 if (*reply == '\0')
13896 return false;
13897
13898 if (strcmp (reply, "OK") != 0)
13899 error (_("Bogus reply from target: %s"), reply);
13900
13901 return true;
13902 }
13903
13904 bool
13905 remote_target::use_agent (bool use)
13906 {
13907 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13908 {
13909 struct remote_state *rs = get_remote_state ();
13910
13911 /* If the stub supports QAgent. */
13912 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
13913 putpkt (rs->buf);
13914 getpkt (&rs->buf, 0);
13915
13916 if (strcmp (rs->buf.data (), "OK") == 0)
13917 {
13918 ::use_agent = use;
13919 return true;
13920 }
13921 }
13922
13923 return false;
13924 }
13925
13926 bool
13927 remote_target::can_use_agent ()
13928 {
13929 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13930 }
13931
13932 struct btrace_target_info
13933 {
13934 /* The ptid of the traced thread. */
13935 ptid_t ptid;
13936
13937 /* The obtained branch trace configuration. */
13938 struct btrace_config conf;
13939 };
13940
13941 /* Reset our idea of our target's btrace configuration. */
13942
13943 static void
13944 remote_btrace_reset (remote_state *rs)
13945 {
13946 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13947 }
13948
13949 /* Synchronize the configuration with the target. */
13950
13951 void
13952 remote_target::btrace_sync_conf (const btrace_config *conf)
13953 {
13954 struct packet_config *packet;
13955 struct remote_state *rs;
13956 char *buf, *pos, *endbuf;
13957
13958 rs = get_remote_state ();
13959 buf = rs->buf.data ();
13960 endbuf = buf + get_remote_packet_size ();
13961
13962 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13963 if (packet_config_support (packet) == PACKET_ENABLE
13964 && conf->bts.size != rs->btrace_config.bts.size)
13965 {
13966 pos = buf;
13967 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13968 conf->bts.size);
13969
13970 putpkt (buf);
13971 getpkt (&rs->buf, 0);
13972
13973 if (packet_ok (buf, packet) == PACKET_ERROR)
13974 {
13975 if (buf[0] == 'E' && buf[1] == '.')
13976 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13977 else
13978 error (_("Failed to configure the BTS buffer size."));
13979 }
13980
13981 rs->btrace_config.bts.size = conf->bts.size;
13982 }
13983
13984 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13985 if (packet_config_support (packet) == PACKET_ENABLE
13986 && conf->pt.size != rs->btrace_config.pt.size)
13987 {
13988 pos = buf;
13989 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13990 conf->pt.size);
13991
13992 putpkt (buf);
13993 getpkt (&rs->buf, 0);
13994
13995 if (packet_ok (buf, packet) == PACKET_ERROR)
13996 {
13997 if (buf[0] == 'E' && buf[1] == '.')
13998 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13999 else
14000 error (_("Failed to configure the trace buffer size."));
14001 }
14002
14003 rs->btrace_config.pt.size = conf->pt.size;
14004 }
14005 }
14006
14007 /* Read the current thread's btrace configuration from the target and
14008 store it into CONF. */
14009
14010 static void
14011 btrace_read_config (struct btrace_config *conf)
14012 {
14013 gdb::optional<gdb::char_vector> xml
14014 = target_read_stralloc (current_inferior ()->top_target (),
14015 TARGET_OBJECT_BTRACE_CONF, "");
14016 if (xml)
14017 parse_xml_btrace_conf (conf, xml->data ());
14018 }
14019
14020 /* Maybe reopen target btrace. */
14021
14022 void
14023 remote_target::remote_btrace_maybe_reopen ()
14024 {
14025 struct remote_state *rs = get_remote_state ();
14026 int btrace_target_pushed = 0;
14027 #if !defined (HAVE_LIBIPT)
14028 int warned = 0;
14029 #endif
14030
14031 /* Don't bother walking the entirety of the remote thread list when
14032 we know the feature isn't supported by the remote. */
14033 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14034 return;
14035
14036 scoped_restore_current_thread restore_thread;
14037
14038 for (thread_info *tp : all_non_exited_threads (this))
14039 {
14040 set_general_thread (tp->ptid);
14041
14042 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14043 btrace_read_config (&rs->btrace_config);
14044
14045 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14046 continue;
14047
14048 #if !defined (HAVE_LIBIPT)
14049 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14050 {
14051 if (!warned)
14052 {
14053 warned = 1;
14054 warning (_("Target is recording using Intel Processor Trace "
14055 "but support was disabled at compile time."));
14056 }
14057
14058 continue;
14059 }
14060 #endif /* !defined (HAVE_LIBIPT) */
14061
14062 /* Push target, once, but before anything else happens. This way our
14063 changes to the threads will be cleaned up by unpushing the target
14064 in case btrace_read_config () throws. */
14065 if (!btrace_target_pushed)
14066 {
14067 btrace_target_pushed = 1;
14068 record_btrace_push_target ();
14069 printf_filtered (_("Target is recording using %s.\n"),
14070 btrace_format_string (rs->btrace_config.format));
14071 }
14072
14073 tp->btrace.target = XCNEW (struct btrace_target_info);
14074 tp->btrace.target->ptid = tp->ptid;
14075 tp->btrace.target->conf = rs->btrace_config;
14076 }
14077 }
14078
14079 /* Enable branch tracing. */
14080
14081 struct btrace_target_info *
14082 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
14083 {
14084 struct btrace_target_info *tinfo = NULL;
14085 struct packet_config *packet = NULL;
14086 struct remote_state *rs = get_remote_state ();
14087 char *buf = rs->buf.data ();
14088 char *endbuf = buf + get_remote_packet_size ();
14089
14090 switch (conf->format)
14091 {
14092 case BTRACE_FORMAT_BTS:
14093 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14094 break;
14095
14096 case BTRACE_FORMAT_PT:
14097 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14098 break;
14099 }
14100
14101 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14102 error (_("Target does not support branch tracing."));
14103
14104 btrace_sync_conf (conf);
14105
14106 set_general_thread (ptid);
14107
14108 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14109 putpkt (rs->buf);
14110 getpkt (&rs->buf, 0);
14111
14112 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14113 {
14114 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14115 error (_("Could not enable branch tracing for %s: %s"),
14116 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14117 else
14118 error (_("Could not enable branch tracing for %s."),
14119 target_pid_to_str (ptid).c_str ());
14120 }
14121
14122 tinfo = XCNEW (struct btrace_target_info);
14123 tinfo->ptid = ptid;
14124
14125 /* If we fail to read the configuration, we lose some information, but the
14126 tracing itself is not impacted. */
14127 try
14128 {
14129 btrace_read_config (&tinfo->conf);
14130 }
14131 catch (const gdb_exception_error &err)
14132 {
14133 if (err.message != NULL)
14134 warning ("%s", err.what ());
14135 }
14136
14137 return tinfo;
14138 }
14139
14140 /* Disable branch tracing. */
14141
14142 void
14143 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14144 {
14145 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14146 struct remote_state *rs = get_remote_state ();
14147 char *buf = rs->buf.data ();
14148 char *endbuf = buf + get_remote_packet_size ();
14149
14150 if (packet_config_support (packet) != PACKET_ENABLE)
14151 error (_("Target does not support branch tracing."));
14152
14153 set_general_thread (tinfo->ptid);
14154
14155 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14156 putpkt (rs->buf);
14157 getpkt (&rs->buf, 0);
14158
14159 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14160 {
14161 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14162 error (_("Could not disable branch tracing for %s: %s"),
14163 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14164 else
14165 error (_("Could not disable branch tracing for %s."),
14166 target_pid_to_str (tinfo->ptid).c_str ());
14167 }
14168
14169 xfree (tinfo);
14170 }
14171
14172 /* Teardown branch tracing. */
14173
14174 void
14175 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14176 {
14177 /* We must not talk to the target during teardown. */
14178 xfree (tinfo);
14179 }
14180
14181 /* Read the branch trace. */
14182
14183 enum btrace_error
14184 remote_target::read_btrace (struct btrace_data *btrace,
14185 struct btrace_target_info *tinfo,
14186 enum btrace_read_type type)
14187 {
14188 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14189 const char *annex;
14190
14191 if (packet_config_support (packet) != PACKET_ENABLE)
14192 error (_("Target does not support branch tracing."));
14193
14194 #if !defined(HAVE_LIBEXPAT)
14195 error (_("Cannot process branch tracing result. XML parsing not supported."));
14196 #endif
14197
14198 switch (type)
14199 {
14200 case BTRACE_READ_ALL:
14201 annex = "all";
14202 break;
14203 case BTRACE_READ_NEW:
14204 annex = "new";
14205 break;
14206 case BTRACE_READ_DELTA:
14207 annex = "delta";
14208 break;
14209 default:
14210 internal_error (__FILE__, __LINE__,
14211 _("Bad branch tracing read type: %u."),
14212 (unsigned int) type);
14213 }
14214
14215 gdb::optional<gdb::char_vector> xml
14216 = target_read_stralloc (current_inferior ()->top_target (),
14217 TARGET_OBJECT_BTRACE, annex);
14218 if (!xml)
14219 return BTRACE_ERR_UNKNOWN;
14220
14221 parse_xml_btrace (btrace, xml->data ());
14222
14223 return BTRACE_ERR_NONE;
14224 }
14225
14226 const struct btrace_config *
14227 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14228 {
14229 return &tinfo->conf;
14230 }
14231
14232 bool
14233 remote_target::augmented_libraries_svr4_read ()
14234 {
14235 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14236 == PACKET_ENABLE);
14237 }
14238
14239 /* Implementation of to_load. */
14240
14241 void
14242 remote_target::load (const char *name, int from_tty)
14243 {
14244 generic_load (name, from_tty);
14245 }
14246
14247 /* Accepts an integer PID; returns a string representing a file that
14248 can be opened on the remote side to get the symbols for the child
14249 process. Returns NULL if the operation is not supported. */
14250
14251 char *
14252 remote_target::pid_to_exec_file (int pid)
14253 {
14254 static gdb::optional<gdb::char_vector> filename;
14255 char *annex = NULL;
14256
14257 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14258 return NULL;
14259
14260 inferior *inf = find_inferior_pid (this, pid);
14261 if (inf == NULL)
14262 internal_error (__FILE__, __LINE__,
14263 _("not currently attached to process %d"), pid);
14264
14265 if (!inf->fake_pid_p)
14266 {
14267 const int annex_size = 9;
14268
14269 annex = (char *) alloca (annex_size);
14270 xsnprintf (annex, annex_size, "%x", pid);
14271 }
14272
14273 filename = target_read_stralloc (current_inferior ()->top_target (),
14274 TARGET_OBJECT_EXEC_FILE, annex);
14275
14276 return filename ? filename->data () : nullptr;
14277 }
14278
14279 /* Implement the to_can_do_single_step target_ops method. */
14280
14281 int
14282 remote_target::can_do_single_step ()
14283 {
14284 /* We can only tell whether target supports single step or not by
14285 supported s and S vCont actions if the stub supports vContSupported
14286 feature. If the stub doesn't support vContSupported feature,
14287 we have conservatively to think target doesn't supports single
14288 step. */
14289 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14290 {
14291 struct remote_state *rs = get_remote_state ();
14292
14293 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14294 remote_vcont_probe ();
14295
14296 return rs->supports_vCont.s && rs->supports_vCont.S;
14297 }
14298 else
14299 return 0;
14300 }
14301
14302 /* Implementation of the to_execution_direction method for the remote
14303 target. */
14304
14305 enum exec_direction_kind
14306 remote_target::execution_direction ()
14307 {
14308 struct remote_state *rs = get_remote_state ();
14309
14310 return rs->last_resume_exec_dir;
14311 }
14312
14313 /* Return pointer to the thread_info struct which corresponds to
14314 THREAD_HANDLE (having length HANDLE_LEN). */
14315
14316 thread_info *
14317 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14318 int handle_len,
14319 inferior *inf)
14320 {
14321 for (thread_info *tp : all_non_exited_threads (this))
14322 {
14323 remote_thread_info *priv = get_remote_thread_info (tp);
14324
14325 if (tp->inf == inf && priv != NULL)
14326 {
14327 if (handle_len != priv->thread_handle.size ())
14328 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14329 handle_len, priv->thread_handle.size ());
14330 if (memcmp (thread_handle, priv->thread_handle.data (),
14331 handle_len) == 0)
14332 return tp;
14333 }
14334 }
14335
14336 return NULL;
14337 }
14338
14339 gdb::byte_vector
14340 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14341 {
14342 remote_thread_info *priv = get_remote_thread_info (tp);
14343 return priv->thread_handle;
14344 }
14345
14346 bool
14347 remote_target::can_async_p ()
14348 {
14349 struct remote_state *rs = get_remote_state ();
14350
14351 /* We don't go async if the user has explicitly prevented it with the
14352 "maint set target-async" command. */
14353 if (!target_async_permitted)
14354 return false;
14355
14356 /* We're async whenever the serial device is. */
14357 return serial_can_async_p (rs->remote_desc);
14358 }
14359
14360 bool
14361 remote_target::is_async_p ()
14362 {
14363 struct remote_state *rs = get_remote_state ();
14364
14365 if (!target_async_permitted)
14366 /* We only enable async when the user specifically asks for it. */
14367 return false;
14368
14369 /* We're async whenever the serial device is. */
14370 return serial_is_async_p (rs->remote_desc);
14371 }
14372
14373 /* Pass the SERIAL event on and up to the client. One day this code
14374 will be able to delay notifying the client of an event until the
14375 point where an entire packet has been received. */
14376
14377 static serial_event_ftype remote_async_serial_handler;
14378
14379 static void
14380 remote_async_serial_handler (struct serial *scb, void *context)
14381 {
14382 /* Don't propogate error information up to the client. Instead let
14383 the client find out about the error by querying the target. */
14384 inferior_event_handler (INF_REG_EVENT);
14385 }
14386
14387 static void
14388 remote_async_inferior_event_handler (gdb_client_data data)
14389 {
14390 inferior_event_handler (INF_REG_EVENT);
14391 }
14392
14393 int
14394 remote_target::async_wait_fd ()
14395 {
14396 struct remote_state *rs = get_remote_state ();
14397 return rs->remote_desc->fd;
14398 }
14399
14400 void
14401 remote_target::async (int enable)
14402 {
14403 struct remote_state *rs = get_remote_state ();
14404
14405 if (enable)
14406 {
14407 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14408
14409 /* If there are pending events in the stop reply queue tell the
14410 event loop to process them. */
14411 if (!rs->stop_reply_queue.empty ())
14412 mark_async_event_handler (rs->remote_async_inferior_event_token);
14413 /* For simplicity, below we clear the pending events token
14414 without remembering whether it is marked, so here we always
14415 mark it. If there's actually no pending notification to
14416 process, this ends up being a no-op (other than a spurious
14417 event-loop wakeup). */
14418 if (target_is_non_stop_p ())
14419 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14420 }
14421 else
14422 {
14423 serial_async (rs->remote_desc, NULL, NULL);
14424 /* If the core is disabling async, it doesn't want to be
14425 disturbed with target events. Clear all async event sources
14426 too. */
14427 clear_async_event_handler (rs->remote_async_inferior_event_token);
14428 if (target_is_non_stop_p ())
14429 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14430 }
14431 }
14432
14433 /* Implementation of the to_thread_events method. */
14434
14435 void
14436 remote_target::thread_events (int enable)
14437 {
14438 struct remote_state *rs = get_remote_state ();
14439 size_t size = get_remote_packet_size ();
14440
14441 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14442 return;
14443
14444 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14445 putpkt (rs->buf);
14446 getpkt (&rs->buf, 0);
14447
14448 switch (packet_ok (rs->buf,
14449 &remote_protocol_packets[PACKET_QThreadEvents]))
14450 {
14451 case PACKET_OK:
14452 if (strcmp (rs->buf.data (), "OK") != 0)
14453 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14454 break;
14455 case PACKET_ERROR:
14456 warning (_("Remote failure reply: %s"), rs->buf.data ());
14457 break;
14458 case PACKET_UNKNOWN:
14459 break;
14460 }
14461 }
14462
14463 static void
14464 show_remote_cmd (const char *args, int from_tty)
14465 {
14466 /* We can't just use cmd_show_list here, because we want to skip
14467 the redundant "show remote Z-packet" and the legacy aliases. */
14468 struct cmd_list_element *list = remote_show_cmdlist;
14469 struct ui_out *uiout = current_uiout;
14470
14471 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14472 for (; list != NULL; list = list->next)
14473 if (strcmp (list->name, "Z-packet") == 0)
14474 continue;
14475 else if (list->type == not_set_cmd)
14476 /* Alias commands are exactly like the original, except they
14477 don't have the normal type. */
14478 continue;
14479 else
14480 {
14481 ui_out_emit_tuple option_emitter (uiout, "option");
14482
14483 uiout->field_string ("name", list->name);
14484 uiout->text (": ");
14485 if (list->type == show_cmd)
14486 do_show_command (NULL, from_tty, list);
14487 else
14488 cmd_func (list, NULL, from_tty);
14489 }
14490 }
14491
14492
14493 /* Function to be called whenever a new objfile (shlib) is detected. */
14494 static void
14495 remote_new_objfile (struct objfile *objfile)
14496 {
14497 remote_target *remote = get_current_remote_target ();
14498
14499 if (remote != NULL) /* Have a remote connection. */
14500 remote->remote_check_symbols ();
14501 }
14502
14503 /* Pull all the tracepoints defined on the target and create local
14504 data structures representing them. We don't want to create real
14505 tracepoints yet, we don't want to mess up the user's existing
14506 collection. */
14507
14508 int
14509 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14510 {
14511 struct remote_state *rs = get_remote_state ();
14512 char *p;
14513
14514 /* Ask for a first packet of tracepoint definition. */
14515 putpkt ("qTfP");
14516 getpkt (&rs->buf, 0);
14517 p = rs->buf.data ();
14518 while (*p && *p != 'l')
14519 {
14520 parse_tracepoint_definition (p, utpp);
14521 /* Ask for another packet of tracepoint definition. */
14522 putpkt ("qTsP");
14523 getpkt (&rs->buf, 0);
14524 p = rs->buf.data ();
14525 }
14526 return 0;
14527 }
14528
14529 int
14530 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14531 {
14532 struct remote_state *rs = get_remote_state ();
14533 char *p;
14534
14535 /* Ask for a first packet of variable definition. */
14536 putpkt ("qTfV");
14537 getpkt (&rs->buf, 0);
14538 p = rs->buf.data ();
14539 while (*p && *p != 'l')
14540 {
14541 parse_tsv_definition (p, utsvp);
14542 /* Ask for another packet of variable definition. */
14543 putpkt ("qTsV");
14544 getpkt (&rs->buf, 0);
14545 p = rs->buf.data ();
14546 }
14547 return 0;
14548 }
14549
14550 /* The "set/show range-stepping" show hook. */
14551
14552 static void
14553 show_range_stepping (struct ui_file *file, int from_tty,
14554 struct cmd_list_element *c,
14555 const char *value)
14556 {
14557 fprintf_filtered (file,
14558 _("Debugger's willingness to use range stepping "
14559 "is %s.\n"), value);
14560 }
14561
14562 /* Return true if the vCont;r action is supported by the remote
14563 stub. */
14564
14565 bool
14566 remote_target::vcont_r_supported ()
14567 {
14568 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14569 remote_vcont_probe ();
14570
14571 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14572 && get_remote_state ()->supports_vCont.r);
14573 }
14574
14575 /* The "set/show range-stepping" set hook. */
14576
14577 static void
14578 set_range_stepping (const char *ignore_args, int from_tty,
14579 struct cmd_list_element *c)
14580 {
14581 /* When enabling, check whether range stepping is actually supported
14582 by the target, and warn if not. */
14583 if (use_range_stepping)
14584 {
14585 remote_target *remote = get_current_remote_target ();
14586 if (remote == NULL
14587 || !remote->vcont_r_supported ())
14588 warning (_("Range stepping is not supported by the current target"));
14589 }
14590 }
14591
14592 static void
14593 show_remote_debug (struct ui_file *file, int from_tty,
14594 struct cmd_list_element *c, const char *value)
14595 {
14596 fprintf_filtered (file, _("Debugging of remote protocol is %s.\n"),
14597 value);
14598 }
14599
14600 static void
14601 show_remote_timeout (struct ui_file *file, int from_tty,
14602 struct cmd_list_element *c, const char *value)
14603 {
14604 fprintf_filtered (file,
14605 _("Timeout limit to wait for target to respond is %s.\n"),
14606 value);
14607 }
14608
14609 /* Implement the "supports_memory_tagging" target_ops method. */
14610
14611 bool
14612 remote_target::supports_memory_tagging ()
14613 {
14614 return remote_memory_tagging_p ();
14615 }
14616
14617 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14618
14619 static void
14620 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14621 size_t len, int type)
14622 {
14623 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14624
14625 std::string request = string_printf ("qMemTags:%s,%s:%s",
14626 phex_nz (address, addr_size),
14627 phex_nz (len, sizeof (len)),
14628 phex_nz (type, sizeof (type)));
14629
14630 strcpy (packet.data (), request.c_str ());
14631 }
14632
14633 /* Parse the qMemTags packet reply into TAGS.
14634
14635 Return true if successful, false otherwise. */
14636
14637 static bool
14638 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14639 gdb::byte_vector &tags)
14640 {
14641 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14642 return false;
14643
14644 /* Copy the tag data. */
14645 tags = hex2bin (reply.data () + 1);
14646
14647 return true;
14648 }
14649
14650 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14651
14652 static void
14653 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14654 size_t len, int type,
14655 const gdb::byte_vector &tags)
14656 {
14657 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14658
14659 /* Put together the main packet, address and length. */
14660 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14661 phex_nz (address, addr_size),
14662 phex_nz (len, sizeof (len)),
14663 phex_nz (type, sizeof (type)));
14664 request += bin2hex (tags.data (), tags.size ());
14665
14666 /* Check if we have exceeded the maximum packet size. */
14667 if (packet.size () < request.length ())
14668 error (_("Contents too big for packet QMemTags."));
14669
14670 strcpy (packet.data (), request.c_str ());
14671 }
14672
14673 /* Implement the "fetch_memtags" target_ops method. */
14674
14675 bool
14676 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14677 gdb::byte_vector &tags, int type)
14678 {
14679 /* Make sure the qMemTags packet is supported. */
14680 if (!remote_memory_tagging_p ())
14681 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14682
14683 struct remote_state *rs = get_remote_state ();
14684
14685 create_fetch_memtags_request (rs->buf, address, len, type);
14686
14687 putpkt (rs->buf);
14688 getpkt (&rs->buf, 0);
14689
14690 return parse_fetch_memtags_reply (rs->buf, tags);
14691 }
14692
14693 /* Implement the "store_memtags" target_ops method. */
14694
14695 bool
14696 remote_target::store_memtags (CORE_ADDR address, size_t len,
14697 const gdb::byte_vector &tags, int type)
14698 {
14699 /* Make sure the QMemTags packet is supported. */
14700 if (!remote_memory_tagging_p ())
14701 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14702
14703 struct remote_state *rs = get_remote_state ();
14704
14705 create_store_memtags_request (rs->buf, address, len, type, tags);
14706
14707 putpkt (rs->buf);
14708 getpkt (&rs->buf, 0);
14709
14710 /* Verify if the request was successful. */
14711 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14712 }
14713
14714 #if GDB_SELF_TEST
14715
14716 namespace selftests {
14717
14718 static void
14719 test_memory_tagging_functions ()
14720 {
14721 remote_target remote;
14722
14723 struct packet_config *config
14724 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14725
14726 scoped_restore restore_memtag_support_
14727 = make_scoped_restore (&config->support);
14728
14729 /* Test memory tagging packet support. */
14730 config->support = PACKET_SUPPORT_UNKNOWN;
14731 SELF_CHECK (remote.supports_memory_tagging () == false);
14732 config->support = PACKET_DISABLE;
14733 SELF_CHECK (remote.supports_memory_tagging () == false);
14734 config->support = PACKET_ENABLE;
14735 SELF_CHECK (remote.supports_memory_tagging () == true);
14736
14737 /* Setup testing. */
14738 gdb::char_vector packet;
14739 gdb::byte_vector tags, bv;
14740 std::string expected, reply;
14741 packet.resize (32000);
14742
14743 /* Test creating a qMemTags request. */
14744
14745 expected = "qMemTags:0,0:0";
14746 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14747 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14748
14749 expected = "qMemTags:deadbeef,10:1";
14750 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14751 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14752
14753 /* Test parsing a qMemTags reply. */
14754
14755 /* Error reply, tags vector unmodified. */
14756 reply = "E00";
14757 strcpy (packet.data (), reply.c_str ());
14758 tags.resize (0);
14759 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14760 SELF_CHECK (tags.size () == 0);
14761
14762 /* Valid reply, tags vector updated. */
14763 tags.resize (0);
14764 bv.resize (0);
14765
14766 for (int i = 0; i < 5; i++)
14767 bv.push_back (i);
14768
14769 reply = "m" + bin2hex (bv.data (), bv.size ());
14770 strcpy (packet.data (), reply.c_str ());
14771
14772 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14773 SELF_CHECK (tags.size () == 5);
14774
14775 for (int i = 0; i < 5; i++)
14776 SELF_CHECK (tags[i] == i);
14777
14778 /* Test creating a QMemTags request. */
14779
14780 /* Empty tag data. */
14781 tags.resize (0);
14782 expected = "QMemTags:0,0:0:";
14783 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14784 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14785 expected.length ()) == 0);
14786
14787 /* Non-empty tag data. */
14788 tags.resize (0);
14789 for (int i = 0; i < 5; i++)
14790 tags.push_back (i);
14791 expected = "QMemTags:deadbeef,ff:1:0001020304";
14792 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14793 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14794 expected.length ()) == 0);
14795 }
14796
14797 } // namespace selftests
14798 #endif /* GDB_SELF_TEST */
14799
14800 void _initialize_remote ();
14801 void
14802 _initialize_remote ()
14803 {
14804 struct cmd_list_element *cmd;
14805 const char *cmd_name;
14806
14807 /* architecture specific data */
14808 remote_g_packet_data_handle =
14809 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14810
14811 add_target (remote_target_info, remote_target::open);
14812 add_target (extended_remote_target_info, extended_remote_target::open);
14813
14814 /* Hook into new objfile notification. */
14815 gdb::observers::new_objfile.attach (remote_new_objfile);
14816
14817 #if 0
14818 init_remote_threadtests ();
14819 #endif
14820
14821 /* set/show remote ... */
14822
14823 add_basic_prefix_cmd ("remote", class_maintenance, _("\
14824 Remote protocol specific variables.\n\
14825 Configure various remote-protocol specific variables such as\n\
14826 the packets being used."),
14827 &remote_set_cmdlist, "set remote ",
14828 0 /* allow-unknown */, &setlist);
14829 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14830 Remote protocol specific variables.\n\
14831 Configure various remote-protocol specific variables such as\n\
14832 the packets being used."),
14833 &remote_show_cmdlist, "show remote ",
14834 0 /* allow-unknown */, &showlist);
14835
14836 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14837 Compare section data on target to the exec file.\n\
14838 Argument is a single section name (default: all loaded sections).\n\
14839 To compare only read-only loaded sections, specify the -r option."),
14840 &cmdlist);
14841
14842 add_cmd ("packet", class_maintenance, packet_command, _("\
14843 Send an arbitrary packet to a remote target.\n\
14844 maintenance packet TEXT\n\
14845 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14846 this command sends the string TEXT to the inferior, and displays the\n\
14847 response packet. GDB supplies the initial `$' character, and the\n\
14848 terminating `#' character and checksum."),
14849 &maintenancelist);
14850
14851 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14852 Set whether to send break if interrupted."), _("\
14853 Show whether to send break if interrupted."), _("\
14854 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14855 set_remotebreak, show_remotebreak,
14856 &setlist, &showlist);
14857 cmd_name = "remotebreak";
14858 cmd = lookup_cmd (&cmd_name, setlist, "", NULL, -1, 1);
14859 deprecate_cmd (cmd, "set remote interrupt-sequence");
14860 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14861 cmd = lookup_cmd (&cmd_name, showlist, "", NULL, -1, 1);
14862 deprecate_cmd (cmd, "show remote interrupt-sequence");
14863
14864 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14865 interrupt_sequence_modes, &interrupt_sequence_mode,
14866 _("\
14867 Set interrupt sequence to remote target."), _("\
14868 Show interrupt sequence to remote target."), _("\
14869 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14870 NULL, show_interrupt_sequence,
14871 &remote_set_cmdlist,
14872 &remote_show_cmdlist);
14873
14874 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14875 &interrupt_on_connect, _("\
14876 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14877 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14878 If set, interrupt sequence is sent to remote target."),
14879 NULL, NULL,
14880 &remote_set_cmdlist, &remote_show_cmdlist);
14881
14882 /* Install commands for configuring memory read/write packets. */
14883
14884 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14885 Set the maximum number of bytes per memory write packet (deprecated)."),
14886 &setlist);
14887 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14888 Show the maximum number of bytes per memory write packet (deprecated)."),
14889 &showlist);
14890 add_cmd ("memory-write-packet-size", no_class,
14891 set_memory_write_packet_size, _("\
14892 Set the maximum number of bytes per memory-write packet.\n\
14893 Specify the number of bytes in a packet or 0 (zero) for the\n\
14894 default packet size. The actual limit is further reduced\n\
14895 dependent on the target. Specify ``fixed'' to disable the\n\
14896 further restriction and ``limit'' to enable that restriction."),
14897 &remote_set_cmdlist);
14898 add_cmd ("memory-read-packet-size", no_class,
14899 set_memory_read_packet_size, _("\
14900 Set the maximum number of bytes per memory-read packet.\n\
14901 Specify the number of bytes in a packet or 0 (zero) for the\n\
14902 default packet size. The actual limit is further reduced\n\
14903 dependent on the target. Specify ``fixed'' to disable the\n\
14904 further restriction and ``limit'' to enable that restriction."),
14905 &remote_set_cmdlist);
14906 add_cmd ("memory-write-packet-size", no_class,
14907 show_memory_write_packet_size,
14908 _("Show the maximum number of bytes per memory-write packet."),
14909 &remote_show_cmdlist);
14910 add_cmd ("memory-read-packet-size", no_class,
14911 show_memory_read_packet_size,
14912 _("Show the maximum number of bytes per memory-read packet."),
14913 &remote_show_cmdlist);
14914
14915 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
14916 &remote_hw_watchpoint_limit, _("\
14917 Set the maximum number of target hardware watchpoints."), _("\
14918 Show the maximum number of target hardware watchpoints."), _("\
14919 Specify \"unlimited\" for unlimited hardware watchpoints."),
14920 NULL, show_hardware_watchpoint_limit,
14921 &remote_set_cmdlist,
14922 &remote_show_cmdlist);
14923 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
14924 no_class,
14925 &remote_hw_watchpoint_length_limit, _("\
14926 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14927 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14928 Specify \"unlimited\" to allow watchpoints of unlimited size."),
14929 NULL, show_hardware_watchpoint_length_limit,
14930 &remote_set_cmdlist, &remote_show_cmdlist);
14931 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
14932 &remote_hw_breakpoint_limit, _("\
14933 Set the maximum number of target hardware breakpoints."), _("\
14934 Show the maximum number of target hardware breakpoints."), _("\
14935 Specify \"unlimited\" for unlimited hardware breakpoints."),
14936 NULL, show_hardware_breakpoint_limit,
14937 &remote_set_cmdlist, &remote_show_cmdlist);
14938
14939 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14940 &remote_address_size, _("\
14941 Set the maximum size of the address (in bits) in a memory packet."), _("\
14942 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14943 NULL,
14944 NULL, /* FIXME: i18n: */
14945 &setlist, &showlist);
14946
14947 init_all_packet_configs ();
14948
14949 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14950 "X", "binary-download", 1);
14951
14952 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14953 "vCont", "verbose-resume", 0);
14954
14955 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14956 "QPassSignals", "pass-signals", 0);
14957
14958 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14959 "QCatchSyscalls", "catch-syscalls", 0);
14960
14961 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14962 "QProgramSignals", "program-signals", 0);
14963
14964 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14965 "QSetWorkingDir", "set-working-dir", 0);
14966
14967 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14968 "QStartupWithShell", "startup-with-shell", 0);
14969
14970 add_packet_config_cmd (&remote_protocol_packets
14971 [PACKET_QEnvironmentHexEncoded],
14972 "QEnvironmentHexEncoded", "environment-hex-encoded",
14973 0);
14974
14975 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14976 "QEnvironmentReset", "environment-reset",
14977 0);
14978
14979 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14980 "QEnvironmentUnset", "environment-unset",
14981 0);
14982
14983 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14984 "qSymbol", "symbol-lookup", 0);
14985
14986 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14987 "P", "set-register", 1);
14988
14989 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14990 "p", "fetch-register", 1);
14991
14992 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14993 "Z0", "software-breakpoint", 0);
14994
14995 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14996 "Z1", "hardware-breakpoint", 0);
14997
14998 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14999 "Z2", "write-watchpoint", 0);
15000
15001 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
15002 "Z3", "read-watchpoint", 0);
15003
15004 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
15005 "Z4", "access-watchpoint", 0);
15006
15007 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15008 "qXfer:auxv:read", "read-aux-vector", 0);
15009
15010 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15011 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15012
15013 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15014 "qXfer:features:read", "target-features", 0);
15015
15016 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15017 "qXfer:libraries:read", "library-info", 0);
15018
15019 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15020 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15021
15022 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15023 "qXfer:memory-map:read", "memory-map", 0);
15024
15025 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
15026 "qXfer:osdata:read", "osdata", 0);
15027
15028 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15029 "qXfer:threads:read", "threads", 0);
15030
15031 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
15032 "qXfer:siginfo:read", "read-siginfo-object", 0);
15033
15034 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
15035 "qXfer:siginfo:write", "write-siginfo-object", 0);
15036
15037 add_packet_config_cmd
15038 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
15039 "qXfer:traceframe-info:read", "traceframe-info", 0);
15040
15041 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15042 "qXfer:uib:read", "unwind-info-block", 0);
15043
15044 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
15045 "qGetTLSAddr", "get-thread-local-storage-address",
15046 0);
15047
15048 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15049 "qGetTIBAddr", "get-thread-information-block-address",
15050 0);
15051
15052 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15053 "bc", "reverse-continue", 0);
15054
15055 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15056 "bs", "reverse-step", 0);
15057
15058 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15059 "qSupported", "supported-packets", 0);
15060
15061 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15062 "qSearch:memory", "search-memory", 0);
15063
15064 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15065 "qTStatus", "trace-status", 0);
15066
15067 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15068 "vFile:setfs", "hostio-setfs", 0);
15069
15070 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15071 "vFile:open", "hostio-open", 0);
15072
15073 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15074 "vFile:pread", "hostio-pread", 0);
15075
15076 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15077 "vFile:pwrite", "hostio-pwrite", 0);
15078
15079 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15080 "vFile:close", "hostio-close", 0);
15081
15082 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15083 "vFile:unlink", "hostio-unlink", 0);
15084
15085 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15086 "vFile:readlink", "hostio-readlink", 0);
15087
15088 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15089 "vFile:fstat", "hostio-fstat", 0);
15090
15091 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15092 "vAttach", "attach", 0);
15093
15094 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15095 "vRun", "run", 0);
15096
15097 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15098 "QStartNoAckMode", "noack", 0);
15099
15100 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15101 "vKill", "kill", 0);
15102
15103 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15104 "qAttached", "query-attached", 0);
15105
15106 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15107 "ConditionalTracepoints",
15108 "conditional-tracepoints", 0);
15109
15110 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15111 "ConditionalBreakpoints",
15112 "conditional-breakpoints", 0);
15113
15114 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15115 "BreakpointCommands",
15116 "breakpoint-commands", 0);
15117
15118 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15119 "FastTracepoints", "fast-tracepoints", 0);
15120
15121 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15122 "TracepointSource", "TracepointSource", 0);
15123
15124 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15125 "QAllow", "allow", 0);
15126
15127 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15128 "StaticTracepoints", "static-tracepoints", 0);
15129
15130 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15131 "InstallInTrace", "install-in-trace", 0);
15132
15133 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15134 "qXfer:statictrace:read", "read-sdata-object", 0);
15135
15136 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15137 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15138
15139 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15140 "QDisableRandomization", "disable-randomization", 0);
15141
15142 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15143 "QAgent", "agent", 0);
15144
15145 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15146 "QTBuffer:size", "trace-buffer-size", 0);
15147
15148 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15149 "Qbtrace:off", "disable-btrace", 0);
15150
15151 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15152 "Qbtrace:bts", "enable-btrace-bts", 0);
15153
15154 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15155 "Qbtrace:pt", "enable-btrace-pt", 0);
15156
15157 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15158 "qXfer:btrace", "read-btrace", 0);
15159
15160 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15161 "qXfer:btrace-conf", "read-btrace-conf", 0);
15162
15163 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15164 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15165
15166 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15167 "multiprocess-feature", "multiprocess-feature", 0);
15168
15169 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15170 "swbreak-feature", "swbreak-feature", 0);
15171
15172 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15173 "hwbreak-feature", "hwbreak-feature", 0);
15174
15175 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15176 "fork-event-feature", "fork-event-feature", 0);
15177
15178 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15179 "vfork-event-feature", "vfork-event-feature", 0);
15180
15181 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15182 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15183
15184 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15185 "vContSupported", "verbose-resume-supported", 0);
15186
15187 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15188 "exec-event-feature", "exec-event-feature", 0);
15189
15190 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15191 "vCtrlC", "ctrl-c", 0);
15192
15193 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15194 "QThreadEvents", "thread-events", 0);
15195
15196 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15197 "N stop reply", "no-resumed-stop-reply", 0);
15198
15199 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15200 "memory-tagging-feature", "memory-tagging-feature", 0);
15201
15202 /* Assert that we've registered "set remote foo-packet" commands
15203 for all packet configs. */
15204 {
15205 int i;
15206
15207 for (i = 0; i < PACKET_MAX; i++)
15208 {
15209 /* Ideally all configs would have a command associated. Some
15210 still don't though. */
15211 int excepted;
15212
15213 switch (i)
15214 {
15215 case PACKET_QNonStop:
15216 case PACKET_EnableDisableTracepoints_feature:
15217 case PACKET_tracenz_feature:
15218 case PACKET_DisconnectedTracing_feature:
15219 case PACKET_augmented_libraries_svr4_read_feature:
15220 case PACKET_qCRC:
15221 /* Additions to this list need to be well justified:
15222 pre-existing packets are OK; new packets are not. */
15223 excepted = 1;
15224 break;
15225 default:
15226 excepted = 0;
15227 break;
15228 }
15229
15230 /* This catches both forgetting to add a config command, and
15231 forgetting to remove a packet from the exception list. */
15232 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15233 }
15234 }
15235
15236 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15237 Z sub-packet has its own set and show commands, but users may
15238 have sets to this variable in their .gdbinit files (or in their
15239 documentation). */
15240 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15241 &remote_Z_packet_detect, _("\
15242 Set use of remote protocol `Z' packets."), _("\
15243 Show use of remote protocol `Z' packets."), _("\
15244 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15245 packets."),
15246 set_remote_protocol_Z_packet_cmd,
15247 show_remote_protocol_Z_packet_cmd,
15248 /* FIXME: i18n: Use of remote protocol
15249 `Z' packets is %s. */
15250 &remote_set_cmdlist, &remote_show_cmdlist);
15251
15252 add_basic_prefix_cmd ("remote", class_files, _("\
15253 Manipulate files on the remote system.\n\
15254 Transfer files to and from the remote target system."),
15255 &remote_cmdlist, "remote ",
15256 0 /* allow-unknown */, &cmdlist);
15257
15258 add_cmd ("put", class_files, remote_put_command,
15259 _("Copy a local file to the remote system."),
15260 &remote_cmdlist);
15261
15262 add_cmd ("get", class_files, remote_get_command,
15263 _("Copy a remote file to the local system."),
15264 &remote_cmdlist);
15265
15266 add_cmd ("delete", class_files, remote_delete_command,
15267 _("Delete a remote file."),
15268 &remote_cmdlist);
15269
15270 add_setshow_string_noescape_cmd ("exec-file", class_files,
15271 &remote_exec_file_var, _("\
15272 Set the remote pathname for \"run\"."), _("\
15273 Show the remote pathname for \"run\"."), NULL,
15274 set_remote_exec_file,
15275 show_remote_exec_file,
15276 &remote_set_cmdlist,
15277 &remote_show_cmdlist);
15278
15279 add_setshow_boolean_cmd ("range-stepping", class_run,
15280 &use_range_stepping, _("\
15281 Enable or disable range stepping."), _("\
15282 Show whether target-assisted range stepping is enabled."), _("\
15283 If on, and the target supports it, when stepping a source line, GDB\n\
15284 tells the target to step the corresponding range of addresses itself instead\n\
15285 of issuing multiple single-steps. This speeds up source level\n\
15286 stepping. If off, GDB always issues single-steps, even if range\n\
15287 stepping is supported by the target. The default is on."),
15288 set_range_stepping,
15289 show_range_stepping,
15290 &setlist,
15291 &showlist);
15292
15293 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15294 Set watchdog timer."), _("\
15295 Show watchdog timer."), _("\
15296 When non-zero, this timeout is used instead of waiting forever for a target\n\
15297 to finish a low-level step or continue operation. If the specified amount\n\
15298 of time passes without a response from the target, an error occurs."),
15299 NULL,
15300 show_watchdog,
15301 &setlist, &showlist);
15302
15303 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15304 &remote_packet_max_chars, _("\
15305 Set the maximum number of characters to display for each remote packet."), _("\
15306 Show the maximum number of characters to display for each remote packet."), _("\
15307 Specify \"unlimited\" to display all the characters."),
15308 NULL, show_remote_packet_max_chars,
15309 &setdebuglist, &showdebuglist);
15310
15311 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15312 _("Set debugging of remote protocol."),
15313 _("Show debugging of remote protocol."),
15314 _("\
15315 When enabled, each packet sent or received with the remote target\n\
15316 is displayed."),
15317 NULL,
15318 show_remote_debug,
15319 &setdebuglist, &showdebuglist);
15320
15321 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15322 &remote_timeout, _("\
15323 Set timeout limit to wait for target to respond."), _("\
15324 Show timeout limit to wait for target to respond."), _("\
15325 This value is used to set the time limit for gdb to wait for a response\n\
15326 from the target."),
15327 NULL,
15328 show_remote_timeout,
15329 &setlist, &showlist);
15330
15331 /* Eventually initialize fileio. See fileio.c */
15332 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15333
15334 #if GDB_SELF_TEST
15335 selftests::register_test ("remote_memory_tagging",
15336 selftests::test_memory_tagging_functions);
15337 #endif
15338 }