7ed9330ce39f4311e6b72701cf7372b4816e6471
[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 bool has_pending_events () override;
433
434 void fetch_registers (struct regcache *, int) override;
435 void store_registers (struct regcache *, int) override;
436 void prepare_to_store (struct regcache *) override;
437
438 void files_info () override;
439
440 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
441
442 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
443 enum remove_bp_reason) override;
444
445
446 bool stopped_by_sw_breakpoint () override;
447 bool supports_stopped_by_sw_breakpoint () override;
448
449 bool stopped_by_hw_breakpoint () override;
450
451 bool supports_stopped_by_hw_breakpoint () override;
452
453 bool stopped_by_watchpoint () override;
454
455 bool stopped_data_address (CORE_ADDR *) override;
456
457 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
458
459 int can_use_hw_breakpoint (enum bptype, int, int) override;
460
461 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
462
463 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
464
465 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
466
467 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
468 struct expression *) override;
469
470 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
471 struct expression *) override;
472
473 void kill () override;
474
475 void load (const char *, int) override;
476
477 void mourn_inferior () override;
478
479 void pass_signals (gdb::array_view<const unsigned char>) override;
480
481 int set_syscall_catchpoint (int, bool, int,
482 gdb::array_view<const int>) override;
483
484 void program_signals (gdb::array_view<const unsigned char>) override;
485
486 bool thread_alive (ptid_t ptid) override;
487
488 const char *thread_name (struct thread_info *) override;
489
490 void update_thread_list () override;
491
492 std::string pid_to_str (ptid_t) override;
493
494 const char *extra_thread_info (struct thread_info *) override;
495
496 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
497
498 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
499 int handle_len,
500 inferior *inf) override;
501
502 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
503 override;
504
505 void stop (ptid_t) override;
506
507 void interrupt () override;
508
509 void pass_ctrlc () override;
510
511 enum target_xfer_status xfer_partial (enum target_object object,
512 const char *annex,
513 gdb_byte *readbuf,
514 const gdb_byte *writebuf,
515 ULONGEST offset, ULONGEST len,
516 ULONGEST *xfered_len) override;
517
518 ULONGEST get_memory_xfer_limit () override;
519
520 void rcmd (const char *command, struct ui_file *output) override;
521
522 char *pid_to_exec_file (int pid) override;
523
524 void log_command (const char *cmd) override
525 {
526 serial_log_command (this, cmd);
527 }
528
529 CORE_ADDR get_thread_local_address (ptid_t ptid,
530 CORE_ADDR load_module_addr,
531 CORE_ADDR offset) override;
532
533 bool can_execute_reverse () override;
534
535 std::vector<mem_region> memory_map () override;
536
537 void flash_erase (ULONGEST address, LONGEST length) override;
538
539 void flash_done () override;
540
541 const struct target_desc *read_description () override;
542
543 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
544 const gdb_byte *pattern, ULONGEST pattern_len,
545 CORE_ADDR *found_addrp) override;
546
547 bool can_async_p () override;
548
549 bool is_async_p () override;
550
551 void async (int) override;
552
553 int async_wait_fd () override;
554
555 void thread_events (int) override;
556
557 int can_do_single_step () override;
558
559 void terminal_inferior () override;
560
561 void terminal_ours () override;
562
563 bool supports_non_stop () override;
564
565 bool supports_multi_process () override;
566
567 bool supports_disable_randomization () override;
568
569 bool filesystem_is_local () override;
570
571
572 int fileio_open (struct inferior *inf, const char *filename,
573 int flags, int mode, int warn_if_slow,
574 int *target_errno) override;
575
576 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
577 ULONGEST offset, int *target_errno) override;
578
579 int fileio_pread (int fd, gdb_byte *read_buf, int len,
580 ULONGEST offset, int *target_errno) override;
581
582 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
583
584 int fileio_close (int fd, int *target_errno) override;
585
586 int fileio_unlink (struct inferior *inf,
587 const char *filename,
588 int *target_errno) override;
589
590 gdb::optional<std::string>
591 fileio_readlink (struct inferior *inf,
592 const char *filename,
593 int *target_errno) override;
594
595 bool supports_enable_disable_tracepoint () override;
596
597 bool supports_string_tracing () override;
598
599 bool supports_evaluation_of_breakpoint_conditions () override;
600
601 bool can_run_breakpoint_commands () override;
602
603 void trace_init () override;
604
605 void download_tracepoint (struct bp_location *location) override;
606
607 bool can_download_tracepoint () override;
608
609 void download_trace_state_variable (const trace_state_variable &tsv) override;
610
611 void enable_tracepoint (struct bp_location *location) override;
612
613 void disable_tracepoint (struct bp_location *location) override;
614
615 void trace_set_readonly_regions () override;
616
617 void trace_start () override;
618
619 int get_trace_status (struct trace_status *ts) override;
620
621 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
622 override;
623
624 void trace_stop () override;
625
626 int trace_find (enum trace_find_type type, int num,
627 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
628
629 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
630
631 int save_trace_data (const char *filename) override;
632
633 int upload_tracepoints (struct uploaded_tp **utpp) override;
634
635 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
636
637 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
638
639 int get_min_fast_tracepoint_insn_len () override;
640
641 void set_disconnected_tracing (int val) override;
642
643 void set_circular_trace_buffer (int val) override;
644
645 void set_trace_buffer_size (LONGEST val) override;
646
647 bool set_trace_notes (const char *user, const char *notes,
648 const char *stopnotes) override;
649
650 int core_of_thread (ptid_t ptid) override;
651
652 int verify_memory (const gdb_byte *data,
653 CORE_ADDR memaddr, ULONGEST size) override;
654
655
656 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
657
658 void set_permissions () override;
659
660 bool static_tracepoint_marker_at (CORE_ADDR,
661 struct static_tracepoint_marker *marker)
662 override;
663
664 std::vector<static_tracepoint_marker>
665 static_tracepoint_markers_by_strid (const char *id) override;
666
667 traceframe_info_up traceframe_info () override;
668
669 bool use_agent (bool use) override;
670 bool can_use_agent () override;
671
672 struct btrace_target_info *enable_btrace (ptid_t ptid,
673 const struct btrace_config *conf) override;
674
675 void disable_btrace (struct btrace_target_info *tinfo) override;
676
677 void teardown_btrace (struct btrace_target_info *tinfo) override;
678
679 enum btrace_error read_btrace (struct btrace_data *data,
680 struct btrace_target_info *btinfo,
681 enum btrace_read_type type) override;
682
683 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
684 bool augmented_libraries_svr4_read () override;
685 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
686 void follow_exec (inferior *, ptid_t, const char *) override;
687 int insert_fork_catchpoint (int) override;
688 int remove_fork_catchpoint (int) override;
689 int insert_vfork_catchpoint (int) override;
690 int remove_vfork_catchpoint (int) override;
691 int insert_exec_catchpoint (int) override;
692 int remove_exec_catchpoint (int) override;
693 enum exec_direction_kind execution_direction () override;
694
695 bool supports_memory_tagging () override;
696
697 bool fetch_memtags (CORE_ADDR address, size_t len,
698 gdb::byte_vector &tags, int type) override;
699
700 bool store_memtags (CORE_ADDR address, size_t len,
701 const gdb::byte_vector &tags, int type) override;
702
703 public: /* Remote specific methods. */
704
705 void remote_download_command_source (int num, ULONGEST addr,
706 struct command_line *cmds);
707
708 void remote_file_put (const char *local_file, const char *remote_file,
709 int from_tty);
710 void remote_file_get (const char *remote_file, const char *local_file,
711 int from_tty);
712 void remote_file_delete (const char *remote_file, int from_tty);
713
714 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
715 ULONGEST offset, int *remote_errno);
716 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
717 ULONGEST offset, int *remote_errno);
718 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
719 ULONGEST offset, int *remote_errno);
720
721 int remote_hostio_send_command (int command_bytes, int which_packet,
722 int *remote_errno, const char **attachment,
723 int *attachment_len);
724 int remote_hostio_set_filesystem (struct inferior *inf,
725 int *remote_errno);
726 /* We should get rid of this and use fileio_open directly. */
727 int remote_hostio_open (struct inferior *inf, const char *filename,
728 int flags, int mode, int warn_if_slow,
729 int *remote_errno);
730 int remote_hostio_close (int fd, int *remote_errno);
731
732 int remote_hostio_unlink (inferior *inf, const char *filename,
733 int *remote_errno);
734
735 struct remote_state *get_remote_state ();
736
737 long get_remote_packet_size (void);
738 long get_memory_packet_size (struct memory_packet_config *config);
739
740 long get_memory_write_packet_size ();
741 long get_memory_read_packet_size ();
742
743 char *append_pending_thread_resumptions (char *p, char *endp,
744 ptid_t ptid);
745 static void open_1 (const char *name, int from_tty, int extended_p);
746 void start_remote (int from_tty, int extended_p);
747 void remote_detach_1 (struct inferior *inf, int from_tty);
748
749 char *append_resumption (char *p, char *endp,
750 ptid_t ptid, int step, gdb_signal siggnal);
751 int remote_resume_with_vcont (ptid_t ptid, int step,
752 gdb_signal siggnal);
753
754 thread_info *add_current_inferior_and_thread (const char *wait_status);
755
756 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
757 target_wait_flags options);
758 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
759 target_wait_flags options);
760
761 ptid_t process_stop_reply (struct stop_reply *stop_reply,
762 target_waitstatus *status);
763
764 ptid_t select_thread_for_ambiguous_stop_reply
765 (const struct target_waitstatus &status);
766
767 void remote_notice_new_inferior (ptid_t currthread, bool executing);
768
769 void print_one_stopped_thread (thread_info *thread);
770 void process_initial_stop_replies (int from_tty);
771
772 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
773
774 void btrace_sync_conf (const btrace_config *conf);
775
776 void remote_btrace_maybe_reopen ();
777
778 void remove_new_fork_children (threads_listing_context *context);
779 void kill_new_fork_children (int pid);
780 void discard_pending_stop_replies (struct inferior *inf);
781 int stop_reply_queue_length ();
782
783 void check_pending_events_prevent_wildcard_vcont
784 (bool *may_global_wildcard_vcont);
785
786 void discard_pending_stop_replies_in_queue ();
787 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
788 struct stop_reply *queued_stop_reply (ptid_t ptid);
789 int peek_stop_reply (ptid_t ptid);
790 void remote_parse_stop_reply (const char *buf, stop_reply *event);
791
792 void remote_stop_ns (ptid_t ptid);
793 void remote_interrupt_as ();
794 void remote_interrupt_ns ();
795
796 char *remote_get_noisy_reply ();
797 int remote_query_attached (int pid);
798 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
799 int try_open_exec);
800
801 ptid_t remote_current_thread (ptid_t oldpid);
802 ptid_t get_current_thread (const char *wait_status);
803
804 void set_thread (ptid_t ptid, int gen);
805 void set_general_thread (ptid_t ptid);
806 void set_continue_thread (ptid_t ptid);
807 void set_general_process ();
808
809 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
810
811 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
812 gdb_ext_thread_info *info);
813 int remote_get_threadinfo (threadref *threadid, int fieldset,
814 gdb_ext_thread_info *info);
815
816 int parse_threadlist_response (const char *pkt, int result_limit,
817 threadref *original_echo,
818 threadref *resultlist,
819 int *doneflag);
820 int remote_get_threadlist (int startflag, threadref *nextthread,
821 int result_limit, int *done, int *result_count,
822 threadref *threadlist);
823
824 int remote_threadlist_iterator (rmt_thread_action stepfunction,
825 void *context, int looplimit);
826
827 int remote_get_threads_with_ql (threads_listing_context *context);
828 int remote_get_threads_with_qxfer (threads_listing_context *context);
829 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
830
831 void extended_remote_restart ();
832
833 void get_offsets ();
834
835 void remote_check_symbols ();
836
837 void remote_supported_packet (const struct protocol_feature *feature,
838 enum packet_support support,
839 const char *argument);
840
841 void remote_query_supported ();
842
843 void remote_packet_size (const protocol_feature *feature,
844 packet_support support, const char *value);
845
846 void remote_serial_quit_handler ();
847
848 void remote_detach_pid (int pid);
849
850 void remote_vcont_probe ();
851
852 void remote_resume_with_hc (ptid_t ptid, int step,
853 gdb_signal siggnal);
854
855 void send_interrupt_sequence ();
856 void interrupt_query ();
857
858 void remote_notif_get_pending_events (notif_client *nc);
859
860 int fetch_register_using_p (struct regcache *regcache,
861 packet_reg *reg);
862 int send_g_packet ();
863 void process_g_packet (struct regcache *regcache);
864 void fetch_registers_using_g (struct regcache *regcache);
865 int store_register_using_P (const struct regcache *regcache,
866 packet_reg *reg);
867 void store_registers_using_G (const struct regcache *regcache);
868
869 void set_remote_traceframe ();
870
871 void check_binary_download (CORE_ADDR addr);
872
873 target_xfer_status remote_write_bytes_aux (const char *header,
874 CORE_ADDR memaddr,
875 const gdb_byte *myaddr,
876 ULONGEST len_units,
877 int unit_size,
878 ULONGEST *xfered_len_units,
879 char packet_format,
880 int use_length);
881
882 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
883 const gdb_byte *myaddr, ULONGEST len,
884 int unit_size, ULONGEST *xfered_len);
885
886 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
887 ULONGEST len_units,
888 int unit_size, ULONGEST *xfered_len_units);
889
890 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
891 ULONGEST memaddr,
892 ULONGEST len,
893 int unit_size,
894 ULONGEST *xfered_len);
895
896 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
897 gdb_byte *myaddr, ULONGEST len,
898 int unit_size,
899 ULONGEST *xfered_len);
900
901 packet_result remote_send_printf (const char *format, ...)
902 ATTRIBUTE_PRINTF (2, 3);
903
904 target_xfer_status remote_flash_write (ULONGEST address,
905 ULONGEST length, ULONGEST *xfered_len,
906 const gdb_byte *data);
907
908 int readchar (int timeout);
909
910 void remote_serial_write (const char *str, int len);
911
912 int putpkt (const char *buf);
913 int putpkt_binary (const char *buf, int cnt);
914
915 int putpkt (const gdb::char_vector &buf)
916 {
917 return putpkt (buf.data ());
918 }
919
920 void skip_frame ();
921 long read_frame (gdb::char_vector *buf_p);
922 void getpkt (gdb::char_vector *buf, int forever);
923 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
924 int expecting_notif, int *is_notif);
925 int getpkt_sane (gdb::char_vector *buf, int forever);
926 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
927 int *is_notif);
928 int remote_vkill (int pid);
929 void remote_kill_k ();
930
931 void extended_remote_disable_randomization (int val);
932 int extended_remote_run (const std::string &args);
933
934 void send_environment_packet (const char *action,
935 const char *packet,
936 const char *value);
937
938 void extended_remote_environment_support ();
939 void extended_remote_set_inferior_cwd ();
940
941 target_xfer_status remote_write_qxfer (const char *object_name,
942 const char *annex,
943 const gdb_byte *writebuf,
944 ULONGEST offset, LONGEST len,
945 ULONGEST *xfered_len,
946 struct packet_config *packet);
947
948 target_xfer_status remote_read_qxfer (const char *object_name,
949 const char *annex,
950 gdb_byte *readbuf, ULONGEST offset,
951 LONGEST len,
952 ULONGEST *xfered_len,
953 struct packet_config *packet);
954
955 void push_stop_reply (struct stop_reply *new_event);
956
957 bool vcont_r_supported ();
958
959 private:
960
961 bool start_remote_1 (int from_tty, int extended_p);
962
963 /* The remote state. Don't reference this directly. Use the
964 get_remote_state method instead. */
965 remote_state m_remote_state;
966 };
967
968 static const target_info extended_remote_target_info = {
969 "extended-remote",
970 N_("Extended remote serial target in gdb-specific protocol"),
971 remote_doc
972 };
973
974 /* Set up the extended remote target by extending the standard remote
975 target and adding to it. */
976
977 class extended_remote_target final : public remote_target
978 {
979 public:
980 const target_info &info () const override
981 { return extended_remote_target_info; }
982
983 /* Open an extended-remote connection. */
984 static void open (const char *, int);
985
986 bool can_create_inferior () override { return true; }
987 void create_inferior (const char *, const std::string &,
988 char **, int) override;
989
990 void detach (inferior *, int) override;
991
992 bool can_attach () override { return true; }
993 void attach (const char *, int) override;
994
995 void post_attach (int) override;
996 bool supports_disable_randomization () override;
997 };
998
999 /* See remote.h. */
1000
1001 bool
1002 is_remote_target (process_stratum_target *target)
1003 {
1004 remote_target *rt = dynamic_cast<remote_target *> (target);
1005 return rt != nullptr;
1006 }
1007
1008 /* Per-program-space data key. */
1009 static const struct program_space_key<char, gdb::xfree_deleter<char>>
1010 remote_pspace_data;
1011
1012 /* The variable registered as the control variable used by the
1013 remote exec-file commands. While the remote exec-file setting is
1014 per-program-space, the set/show machinery uses this as the
1015 location of the remote exec-file value. */
1016 static std::string remote_exec_file_var;
1017
1018 /* The size to align memory write packets, when practical. The protocol
1019 does not guarantee any alignment, and gdb will generate short
1020 writes and unaligned writes, but even as a best-effort attempt this
1021 can improve bulk transfers. For instance, if a write is misaligned
1022 relative to the target's data bus, the stub may need to make an extra
1023 round trip fetching data from the target. This doesn't make a
1024 huge difference, but it's easy to do, so we try to be helpful.
1025
1026 The alignment chosen is arbitrary; usually data bus width is
1027 important here, not the possibly larger cache line size. */
1028 enum { REMOTE_ALIGN_WRITES = 16 };
1029
1030 /* Prototypes for local functions. */
1031
1032 static int hexnumlen (ULONGEST num);
1033
1034 static int stubhex (int ch);
1035
1036 static int hexnumstr (char *, ULONGEST);
1037
1038 static int hexnumnstr (char *, ULONGEST, int);
1039
1040 static CORE_ADDR remote_address_masked (CORE_ADDR);
1041
1042 static int stub_unpack_int (const char *buff, int fieldlength);
1043
1044 struct packet_config;
1045
1046 static void show_packet_config_cmd (struct packet_config *config);
1047
1048 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1049 int from_tty,
1050 struct cmd_list_element *c,
1051 const char *value);
1052
1053 static ptid_t read_ptid (const char *buf, const char **obuf);
1054
1055 static void remote_async_inferior_event_handler (gdb_client_data);
1056
1057 static bool remote_read_description_p (struct target_ops *target);
1058
1059 static void remote_console_output (const char *msg);
1060
1061 static void remote_btrace_reset (remote_state *rs);
1062
1063 static void remote_unpush_and_throw (remote_target *target);
1064
1065 /* For "remote". */
1066
1067 static struct cmd_list_element *remote_cmdlist;
1068
1069 /* For "set remote" and "show remote". */
1070
1071 static struct cmd_list_element *remote_set_cmdlist;
1072 static struct cmd_list_element *remote_show_cmdlist;
1073
1074 /* Controls whether GDB is willing to use range stepping. */
1075
1076 static bool use_range_stepping = true;
1077
1078 /* From the remote target's point of view, each thread is in one of these three
1079 states. */
1080 enum class resume_state
1081 {
1082 /* Not resumed - we haven't been asked to resume this thread. */
1083 NOT_RESUMED,
1084
1085 /* We have been asked to resume this thread, but haven't sent a vCont action
1086 for it yet. We'll need to consider it next time commit_resume is
1087 called. */
1088 RESUMED_PENDING_VCONT,
1089
1090 /* We have been asked to resume this thread, and we have sent a vCont action
1091 for it. */
1092 RESUMED,
1093 };
1094
1095 /* Information about a thread's pending vCont-resume. Used when a thread is in
1096 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1097 stores this information which is then picked up by
1098 remote_target::commit_resume to know which is the proper action for this
1099 thread to include in the vCont packet. */
1100 struct resumed_pending_vcont_info
1101 {
1102 /* True if the last resume call for this thread was a step request, false
1103 if a continue request. */
1104 bool step;
1105
1106 /* The signal specified in the last resume call for this thread. */
1107 gdb_signal sig;
1108 };
1109
1110 /* Private data that we'll store in (struct thread_info)->priv. */
1111 struct remote_thread_info : public private_thread_info
1112 {
1113 std::string extra;
1114 std::string name;
1115 int core = -1;
1116
1117 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1118 sequence of bytes. */
1119 gdb::byte_vector thread_handle;
1120
1121 /* Whether the target stopped for a breakpoint/watchpoint. */
1122 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1123
1124 /* This is set to the data address of the access causing the target
1125 to stop for a watchpoint. */
1126 CORE_ADDR watch_data_address = 0;
1127
1128 /* Get the thread's resume state. */
1129 enum resume_state get_resume_state () const
1130 {
1131 return m_resume_state;
1132 }
1133
1134 /* Put the thread in the NOT_RESUMED state. */
1135 void set_not_resumed ()
1136 {
1137 m_resume_state = resume_state::NOT_RESUMED;
1138 }
1139
1140 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1141 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1142 {
1143 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1144 m_resumed_pending_vcont_info.step = step;
1145 m_resumed_pending_vcont_info.sig = sig;
1146 }
1147
1148 /* Get the information this thread's pending vCont-resumption.
1149
1150 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1151 state. */
1152 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1153 {
1154 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1155
1156 return m_resumed_pending_vcont_info;
1157 }
1158
1159 /* Put the thread in the VCONT_RESUMED state. */
1160 void set_resumed ()
1161 {
1162 m_resume_state = resume_state::RESUMED;
1163 }
1164
1165 private:
1166 /* Resume state for this thread. This is used to implement vCont action
1167 coalescing (only when the target operates in non-stop mode).
1168
1169 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1170 which notes that this thread must be considered in the next commit_resume
1171 call.
1172
1173 remote_target::commit_resume sends a vCont packet with actions for the
1174 threads in the RESUMED_PENDING_VCONT state and moves them to the
1175 VCONT_RESUMED state.
1176
1177 When reporting a stop to the core for a thread, that thread is moved back
1178 to the NOT_RESUMED state. */
1179 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1180
1181 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1182 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1183 };
1184
1185 remote_state::remote_state ()
1186 : buf (400)
1187 {
1188 }
1189
1190 remote_state::~remote_state ()
1191 {
1192 xfree (this->last_pass_packet);
1193 xfree (this->last_program_signals_packet);
1194 xfree (this->finished_object);
1195 xfree (this->finished_annex);
1196 }
1197
1198 /* Utility: generate error from an incoming stub packet. */
1199 static void
1200 trace_error (char *buf)
1201 {
1202 if (*buf++ != 'E')
1203 return; /* not an error msg */
1204 switch (*buf)
1205 {
1206 case '1': /* malformed packet error */
1207 if (*++buf == '0') /* general case: */
1208 error (_("remote.c: error in outgoing packet."));
1209 else
1210 error (_("remote.c: error in outgoing packet at field #%ld."),
1211 strtol (buf, NULL, 16));
1212 default:
1213 error (_("Target returns error code '%s'."), buf);
1214 }
1215 }
1216
1217 /* Utility: wait for reply from stub, while accepting "O" packets. */
1218
1219 char *
1220 remote_target::remote_get_noisy_reply ()
1221 {
1222 struct remote_state *rs = get_remote_state ();
1223
1224 do /* Loop on reply from remote stub. */
1225 {
1226 char *buf;
1227
1228 QUIT; /* Allow user to bail out with ^C. */
1229 getpkt (&rs->buf, 0);
1230 buf = rs->buf.data ();
1231 if (buf[0] == 'E')
1232 trace_error (buf);
1233 else if (startswith (buf, "qRelocInsn:"))
1234 {
1235 ULONGEST ul;
1236 CORE_ADDR from, to, org_to;
1237 const char *p, *pp;
1238 int adjusted_size = 0;
1239 int relocated = 0;
1240
1241 p = buf + strlen ("qRelocInsn:");
1242 pp = unpack_varlen_hex (p, &ul);
1243 if (*pp != ';')
1244 error (_("invalid qRelocInsn packet: %s"), buf);
1245 from = ul;
1246
1247 p = pp + 1;
1248 unpack_varlen_hex (p, &ul);
1249 to = ul;
1250
1251 org_to = to;
1252
1253 try
1254 {
1255 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1256 relocated = 1;
1257 }
1258 catch (const gdb_exception &ex)
1259 {
1260 if (ex.error == MEMORY_ERROR)
1261 {
1262 /* Propagate memory errors silently back to the
1263 target. The stub may have limited the range of
1264 addresses we can write to, for example. */
1265 }
1266 else
1267 {
1268 /* Something unexpectedly bad happened. Be verbose
1269 so we can tell what, and propagate the error back
1270 to the stub, so it doesn't get stuck waiting for
1271 a response. */
1272 exception_fprintf (gdb_stderr, ex,
1273 _("warning: relocating instruction: "));
1274 }
1275 putpkt ("E01");
1276 }
1277
1278 if (relocated)
1279 {
1280 adjusted_size = to - org_to;
1281
1282 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1283 putpkt (buf);
1284 }
1285 }
1286 else if (buf[0] == 'O' && buf[1] != 'K')
1287 remote_console_output (buf + 1); /* 'O' message from stub */
1288 else
1289 return buf; /* Here's the actual reply. */
1290 }
1291 while (1);
1292 }
1293
1294 struct remote_arch_state *
1295 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1296 {
1297 remote_arch_state *rsa;
1298
1299 auto it = this->m_arch_states.find (gdbarch);
1300 if (it == this->m_arch_states.end ())
1301 {
1302 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1303 std::forward_as_tuple (gdbarch),
1304 std::forward_as_tuple (gdbarch));
1305 rsa = &p.first->second;
1306
1307 /* Make sure that the packet buffer is plenty big enough for
1308 this architecture. */
1309 if (this->buf.size () < rsa->remote_packet_size)
1310 this->buf.resize (2 * rsa->remote_packet_size);
1311 }
1312 else
1313 rsa = &it->second;
1314
1315 return rsa;
1316 }
1317
1318 /* Fetch the global remote target state. */
1319
1320 remote_state *
1321 remote_target::get_remote_state ()
1322 {
1323 /* Make sure that the remote architecture state has been
1324 initialized, because doing so might reallocate rs->buf. Any
1325 function which calls getpkt also needs to be mindful of changes
1326 to rs->buf, but this call limits the number of places which run
1327 into trouble. */
1328 m_remote_state.get_remote_arch_state (target_gdbarch ());
1329
1330 return &m_remote_state;
1331 }
1332
1333 /* Fetch the remote exec-file from the current program space. */
1334
1335 static const char *
1336 get_remote_exec_file (void)
1337 {
1338 char *remote_exec_file;
1339
1340 remote_exec_file = remote_pspace_data.get (current_program_space);
1341 if (remote_exec_file == NULL)
1342 return "";
1343
1344 return remote_exec_file;
1345 }
1346
1347 /* Set the remote exec file for PSPACE. */
1348
1349 static void
1350 set_pspace_remote_exec_file (struct program_space *pspace,
1351 const char *remote_exec_file)
1352 {
1353 char *old_file = remote_pspace_data.get (pspace);
1354
1355 xfree (old_file);
1356 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1357 }
1358
1359 /* The "set/show remote exec-file" set command hook. */
1360
1361 static void
1362 set_remote_exec_file (const char *ignored, int from_tty,
1363 struct cmd_list_element *c)
1364 {
1365 set_pspace_remote_exec_file (current_program_space,
1366 remote_exec_file_var.c_str ());
1367 }
1368
1369 /* The "set/show remote exec-file" show command hook. */
1370
1371 static void
1372 show_remote_exec_file (struct ui_file *file, int from_tty,
1373 struct cmd_list_element *cmd, const char *value)
1374 {
1375 fprintf_filtered (file, "%s\n", get_remote_exec_file ());
1376 }
1377
1378 static int
1379 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1380 {
1381 int regnum, num_remote_regs, offset;
1382 struct packet_reg **remote_regs;
1383
1384 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1385 {
1386 struct packet_reg *r = &regs[regnum];
1387
1388 if (register_size (gdbarch, regnum) == 0)
1389 /* Do not try to fetch zero-sized (placeholder) registers. */
1390 r->pnum = -1;
1391 else
1392 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1393
1394 r->regnum = regnum;
1395 }
1396
1397 /* Define the g/G packet format as the contents of each register
1398 with a remote protocol number, in order of ascending protocol
1399 number. */
1400
1401 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1402 for (num_remote_regs = 0, regnum = 0;
1403 regnum < gdbarch_num_regs (gdbarch);
1404 regnum++)
1405 if (regs[regnum].pnum != -1)
1406 remote_regs[num_remote_regs++] = &regs[regnum];
1407
1408 std::sort (remote_regs, remote_regs + num_remote_regs,
1409 [] (const packet_reg *a, const packet_reg *b)
1410 { return a->pnum < b->pnum; });
1411
1412 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1413 {
1414 remote_regs[regnum]->in_g_packet = 1;
1415 remote_regs[regnum]->offset = offset;
1416 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1417 }
1418
1419 return offset;
1420 }
1421
1422 /* Given the architecture described by GDBARCH, return the remote
1423 protocol register's number and the register's offset in the g/G
1424 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1425 If the target does not have a mapping for REGNUM, return false,
1426 otherwise, return true. */
1427
1428 int
1429 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1430 int *pnum, int *poffset)
1431 {
1432 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1433
1434 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1435
1436 map_regcache_remote_table (gdbarch, regs.data ());
1437
1438 *pnum = regs[regnum].pnum;
1439 *poffset = regs[regnum].offset;
1440
1441 return *pnum != -1;
1442 }
1443
1444 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1445 {
1446 /* Use the architecture to build a regnum<->pnum table, which will be
1447 1:1 unless a feature set specifies otherwise. */
1448 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1449
1450 /* Record the maximum possible size of the g packet - it may turn out
1451 to be smaller. */
1452 this->sizeof_g_packet
1453 = map_regcache_remote_table (gdbarch, this->regs.get ());
1454
1455 /* Default maximum number of characters in a packet body. Many
1456 remote stubs have a hardwired buffer size of 400 bytes
1457 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1458 as the maximum packet-size to ensure that the packet and an extra
1459 NUL character can always fit in the buffer. This stops GDB
1460 trashing stubs that try to squeeze an extra NUL into what is
1461 already a full buffer (As of 1999-12-04 that was most stubs). */
1462 this->remote_packet_size = 400 - 1;
1463
1464 /* This one is filled in when a ``g'' packet is received. */
1465 this->actual_register_packet_size = 0;
1466
1467 /* Should rsa->sizeof_g_packet needs more space than the
1468 default, adjust the size accordingly. Remember that each byte is
1469 encoded as two characters. 32 is the overhead for the packet
1470 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1471 (``$NN:G...#NN'') is a better guess, the below has been padded a
1472 little. */
1473 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1474 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1475 }
1476
1477 /* Get a pointer to the current remote target. If not connected to a
1478 remote target, return NULL. */
1479
1480 static remote_target *
1481 get_current_remote_target ()
1482 {
1483 target_ops *proc_target = current_inferior ()->process_target ();
1484 return dynamic_cast<remote_target *> (proc_target);
1485 }
1486
1487 /* Return the current allowed size of a remote packet. This is
1488 inferred from the current architecture, and should be used to
1489 limit the length of outgoing packets. */
1490 long
1491 remote_target::get_remote_packet_size ()
1492 {
1493 struct remote_state *rs = get_remote_state ();
1494 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1495
1496 if (rs->explicit_packet_size)
1497 return rs->explicit_packet_size;
1498
1499 return rsa->remote_packet_size;
1500 }
1501
1502 static struct packet_reg *
1503 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1504 long regnum)
1505 {
1506 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1507 return NULL;
1508 else
1509 {
1510 struct packet_reg *r = &rsa->regs[regnum];
1511
1512 gdb_assert (r->regnum == regnum);
1513 return r;
1514 }
1515 }
1516
1517 static struct packet_reg *
1518 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1519 LONGEST pnum)
1520 {
1521 int i;
1522
1523 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1524 {
1525 struct packet_reg *r = &rsa->regs[i];
1526
1527 if (r->pnum == pnum)
1528 return r;
1529 }
1530 return NULL;
1531 }
1532
1533 /* Allow the user to specify what sequence to send to the remote
1534 when he requests a program interruption: Although ^C is usually
1535 what remote systems expect (this is the default, here), it is
1536 sometimes preferable to send a break. On other systems such
1537 as the Linux kernel, a break followed by g, which is Magic SysRq g
1538 is required in order to interrupt the execution. */
1539 const char interrupt_sequence_control_c[] = "Ctrl-C";
1540 const char interrupt_sequence_break[] = "BREAK";
1541 const char interrupt_sequence_break_g[] = "BREAK-g";
1542 static const char *const interrupt_sequence_modes[] =
1543 {
1544 interrupt_sequence_control_c,
1545 interrupt_sequence_break,
1546 interrupt_sequence_break_g,
1547 NULL
1548 };
1549 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1550
1551 static void
1552 show_interrupt_sequence (struct ui_file *file, int from_tty,
1553 struct cmd_list_element *c,
1554 const char *value)
1555 {
1556 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1557 fprintf_filtered (file,
1558 _("Send the ASCII ETX character (Ctrl-c) "
1559 "to the remote target to interrupt the "
1560 "execution of the program.\n"));
1561 else if (interrupt_sequence_mode == interrupt_sequence_break)
1562 fprintf_filtered (file,
1563 _("send a break signal to the remote target "
1564 "to interrupt the execution of the program.\n"));
1565 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1566 fprintf_filtered (file,
1567 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1568 "the remote target to interrupt the execution "
1569 "of Linux kernel.\n"));
1570 else
1571 internal_error (__FILE__, __LINE__,
1572 _("Invalid value for interrupt_sequence_mode: %s."),
1573 interrupt_sequence_mode);
1574 }
1575
1576 /* This boolean variable specifies whether interrupt_sequence is sent
1577 to the remote target when gdb connects to it.
1578 This is mostly needed when you debug the Linux kernel: The Linux kernel
1579 expects BREAK g which is Magic SysRq g for connecting gdb. */
1580 static bool interrupt_on_connect = false;
1581
1582 /* This variable is used to implement the "set/show remotebreak" commands.
1583 Since these commands are now deprecated in favor of "set/show remote
1584 interrupt-sequence", it no longer has any effect on the code. */
1585 static bool remote_break;
1586
1587 static void
1588 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1589 {
1590 if (remote_break)
1591 interrupt_sequence_mode = interrupt_sequence_break;
1592 else
1593 interrupt_sequence_mode = interrupt_sequence_control_c;
1594 }
1595
1596 static void
1597 show_remotebreak (struct ui_file *file, int from_tty,
1598 struct cmd_list_element *c,
1599 const char *value)
1600 {
1601 }
1602
1603 /* This variable sets the number of bits in an address that are to be
1604 sent in a memory ("M" or "m") packet. Normally, after stripping
1605 leading zeros, the entire address would be sent. This variable
1606 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1607 initial implementation of remote.c restricted the address sent in
1608 memory packets to ``host::sizeof long'' bytes - (typically 32
1609 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1610 address was never sent. Since fixing this bug may cause a break in
1611 some remote targets this variable is principally provided to
1612 facilitate backward compatibility. */
1613
1614 static unsigned int remote_address_size;
1615
1616 \f
1617 /* User configurable variables for the number of characters in a
1618 memory read/write packet. MIN (rsa->remote_packet_size,
1619 rsa->sizeof_g_packet) is the default. Some targets need smaller
1620 values (fifo overruns, et.al.) and some users need larger values
1621 (speed up transfers). The variables ``preferred_*'' (the user
1622 request), ``current_*'' (what was actually set) and ``forced_*''
1623 (Positive - a soft limit, negative - a hard limit). */
1624
1625 struct memory_packet_config
1626 {
1627 const char *name;
1628 long size;
1629 int fixed_p;
1630 };
1631
1632 /* The default max memory-write-packet-size, when the setting is
1633 "fixed". The 16k is historical. (It came from older GDB's using
1634 alloca for buffers and the knowledge (folklore?) that some hosts
1635 don't cope very well with large alloca calls.) */
1636 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1637
1638 /* The minimum remote packet size for memory transfers. Ensures we
1639 can write at least one byte. */
1640 #define MIN_MEMORY_PACKET_SIZE 20
1641
1642 /* Get the memory packet size, assuming it is fixed. */
1643
1644 static long
1645 get_fixed_memory_packet_size (struct memory_packet_config *config)
1646 {
1647 gdb_assert (config->fixed_p);
1648
1649 if (config->size <= 0)
1650 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1651 else
1652 return config->size;
1653 }
1654
1655 /* Compute the current size of a read/write packet. Since this makes
1656 use of ``actual_register_packet_size'' the computation is dynamic. */
1657
1658 long
1659 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1660 {
1661 struct remote_state *rs = get_remote_state ();
1662 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1663
1664 long what_they_get;
1665 if (config->fixed_p)
1666 what_they_get = get_fixed_memory_packet_size (config);
1667 else
1668 {
1669 what_they_get = get_remote_packet_size ();
1670 /* Limit the packet to the size specified by the user. */
1671 if (config->size > 0
1672 && what_they_get > config->size)
1673 what_they_get = config->size;
1674
1675 /* Limit it to the size of the targets ``g'' response unless we have
1676 permission from the stub to use a larger packet size. */
1677 if (rs->explicit_packet_size == 0
1678 && rsa->actual_register_packet_size > 0
1679 && what_they_get > rsa->actual_register_packet_size)
1680 what_they_get = rsa->actual_register_packet_size;
1681 }
1682 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1683 what_they_get = MIN_MEMORY_PACKET_SIZE;
1684
1685 /* Make sure there is room in the global buffer for this packet
1686 (including its trailing NUL byte). */
1687 if (rs->buf.size () < what_they_get + 1)
1688 rs->buf.resize (2 * what_they_get);
1689
1690 return what_they_get;
1691 }
1692
1693 /* Update the size of a read/write packet. If they user wants
1694 something really big then do a sanity check. */
1695
1696 static void
1697 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1698 {
1699 int fixed_p = config->fixed_p;
1700 long size = config->size;
1701
1702 if (args == NULL)
1703 error (_("Argument required (integer, `fixed' or `limited')."));
1704 else if (strcmp (args, "hard") == 0
1705 || strcmp (args, "fixed") == 0)
1706 fixed_p = 1;
1707 else if (strcmp (args, "soft") == 0
1708 || strcmp (args, "limit") == 0)
1709 fixed_p = 0;
1710 else
1711 {
1712 char *end;
1713
1714 size = strtoul (args, &end, 0);
1715 if (args == end)
1716 error (_("Invalid %s (bad syntax)."), config->name);
1717
1718 /* Instead of explicitly capping the size of a packet to or
1719 disallowing it, the user is allowed to set the size to
1720 something arbitrarily large. */
1721 }
1722
1723 /* Extra checks? */
1724 if (fixed_p && !config->fixed_p)
1725 {
1726 /* So that the query shows the correct value. */
1727 long query_size = (size <= 0
1728 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1729 : size);
1730
1731 if (! query (_("The target may not be able to correctly handle a %s\n"
1732 "of %ld bytes. Change the packet size? "),
1733 config->name, query_size))
1734 error (_("Packet size not changed."));
1735 }
1736 /* Update the config. */
1737 config->fixed_p = fixed_p;
1738 config->size = size;
1739 }
1740
1741 static void
1742 show_memory_packet_size (struct memory_packet_config *config)
1743 {
1744 if (config->size == 0)
1745 printf_filtered (_("The %s is 0 (default). "), config->name);
1746 else
1747 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1748 if (config->fixed_p)
1749 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1750 get_fixed_memory_packet_size (config));
1751 else
1752 {
1753 remote_target *remote = get_current_remote_target ();
1754
1755 if (remote != NULL)
1756 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1757 remote->get_memory_packet_size (config));
1758 else
1759 puts_filtered ("The actual limit will be further reduced "
1760 "dependent on the target.\n");
1761 }
1762 }
1763
1764 /* FIXME: needs to be per-remote-target. */
1765 static struct memory_packet_config memory_write_packet_config =
1766 {
1767 "memory-write-packet-size",
1768 };
1769
1770 static void
1771 set_memory_write_packet_size (const char *args, int from_tty)
1772 {
1773 set_memory_packet_size (args, &memory_write_packet_config);
1774 }
1775
1776 static void
1777 show_memory_write_packet_size (const char *args, int from_tty)
1778 {
1779 show_memory_packet_size (&memory_write_packet_config);
1780 }
1781
1782 /* Show the number of hardware watchpoints that can be used. */
1783
1784 static void
1785 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1786 struct cmd_list_element *c,
1787 const char *value)
1788 {
1789 fprintf_filtered (file, _("The maximum number of target hardware "
1790 "watchpoints is %s.\n"), value);
1791 }
1792
1793 /* Show the length limit (in bytes) for hardware watchpoints. */
1794
1795 static void
1796 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1797 struct cmd_list_element *c,
1798 const char *value)
1799 {
1800 fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1801 "hardware watchpoint is %s.\n"), value);
1802 }
1803
1804 /* Show the number of hardware breakpoints that can be used. */
1805
1806 static void
1807 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1808 struct cmd_list_element *c,
1809 const char *value)
1810 {
1811 fprintf_filtered (file, _("The maximum number of target hardware "
1812 "breakpoints is %s.\n"), value);
1813 }
1814
1815 /* Controls the maximum number of characters to display in the debug output
1816 for each remote packet. The remaining characters are omitted. */
1817
1818 static int remote_packet_max_chars = 512;
1819
1820 /* Show the maximum number of characters to display for each remote packet
1821 when remote debugging is enabled. */
1822
1823 static void
1824 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1825 struct cmd_list_element *c,
1826 const char *value)
1827 {
1828 fprintf_filtered (file, _("Number of remote packet characters to "
1829 "display is %s.\n"), value);
1830 }
1831
1832 long
1833 remote_target::get_memory_write_packet_size ()
1834 {
1835 return get_memory_packet_size (&memory_write_packet_config);
1836 }
1837
1838 /* FIXME: needs to be per-remote-target. */
1839 static struct memory_packet_config memory_read_packet_config =
1840 {
1841 "memory-read-packet-size",
1842 };
1843
1844 static void
1845 set_memory_read_packet_size (const char *args, int from_tty)
1846 {
1847 set_memory_packet_size (args, &memory_read_packet_config);
1848 }
1849
1850 static void
1851 show_memory_read_packet_size (const char *args, int from_tty)
1852 {
1853 show_memory_packet_size (&memory_read_packet_config);
1854 }
1855
1856 long
1857 remote_target::get_memory_read_packet_size ()
1858 {
1859 long size = get_memory_packet_size (&memory_read_packet_config);
1860
1861 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1862 extra buffer size argument before the memory read size can be
1863 increased beyond this. */
1864 if (size > get_remote_packet_size ())
1865 size = get_remote_packet_size ();
1866 return size;
1867 }
1868
1869 \f
1870
1871 struct packet_config
1872 {
1873 const char *name;
1874 const char *title;
1875
1876 /* If auto, GDB auto-detects support for this packet or feature,
1877 either through qSupported, or by trying the packet and looking
1878 at the response. If true, GDB assumes the target supports this
1879 packet. If false, the packet is disabled. Configs that don't
1880 have an associated command always have this set to auto. */
1881 enum auto_boolean detect;
1882
1883 /* The "show remote foo-packet" command created for this packet. */
1884 cmd_list_element *show_cmd;
1885
1886 /* Does the target support this packet? */
1887 enum packet_support support;
1888 };
1889
1890 static enum packet_support packet_config_support (struct packet_config *config);
1891 static enum packet_support packet_support (int packet);
1892
1893 static void
1894 show_packet_config_cmd (struct packet_config *config)
1895 {
1896 const char *support = "internal-error";
1897
1898 switch (packet_config_support (config))
1899 {
1900 case PACKET_ENABLE:
1901 support = "enabled";
1902 break;
1903 case PACKET_DISABLE:
1904 support = "disabled";
1905 break;
1906 case PACKET_SUPPORT_UNKNOWN:
1907 support = "unknown";
1908 break;
1909 }
1910 switch (config->detect)
1911 {
1912 case AUTO_BOOLEAN_AUTO:
1913 printf_filtered (_("Support for the `%s' packet "
1914 "is auto-detected, currently %s.\n"),
1915 config->name, support);
1916 break;
1917 case AUTO_BOOLEAN_TRUE:
1918 case AUTO_BOOLEAN_FALSE:
1919 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1920 config->name, support);
1921 break;
1922 }
1923 }
1924
1925 static void
1926 add_packet_config_cmd (struct packet_config *config, const char *name,
1927 const char *title, int legacy)
1928 {
1929 config->name = name;
1930 config->title = title;
1931 gdb::unique_xmalloc_ptr<char> set_doc
1932 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1933 name, title);
1934 gdb::unique_xmalloc_ptr<char> show_doc
1935 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
1936 name, title);
1937 /* set/show TITLE-packet {auto,on,off} */
1938 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
1939 set_show_commands cmds
1940 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
1941 &config->detect, set_doc.get (),
1942 show_doc.get (), NULL, /* help_doc */
1943 NULL,
1944 show_remote_protocol_packet_cmd,
1945 &remote_set_cmdlist, &remote_show_cmdlist);
1946 config->show_cmd = cmds.show;
1947
1948 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1949 if (legacy)
1950 {
1951 /* It's not clear who should take ownership of this string, so, for
1952 now, make it static, and give copies to each of the add_alias_cmd
1953 calls below. */
1954 static gdb::unique_xmalloc_ptr<char> legacy_name
1955 = xstrprintf ("%s-packet", name);
1956 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
1957 &remote_set_cmdlist);
1958 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
1959 &remote_show_cmdlist);
1960 }
1961 }
1962
1963 static enum packet_result
1964 packet_check_result (const char *buf)
1965 {
1966 if (buf[0] != '\0')
1967 {
1968 /* The stub recognized the packet request. Check that the
1969 operation succeeded. */
1970 if (buf[0] == 'E'
1971 && isxdigit (buf[1]) && isxdigit (buf[2])
1972 && buf[3] == '\0')
1973 /* "Enn" - definitely an error. */
1974 return PACKET_ERROR;
1975
1976 /* Always treat "E." as an error. This will be used for
1977 more verbose error messages, such as E.memtypes. */
1978 if (buf[0] == 'E' && buf[1] == '.')
1979 return PACKET_ERROR;
1980
1981 /* The packet may or may not be OK. Just assume it is. */
1982 return PACKET_OK;
1983 }
1984 else
1985 /* The stub does not support the packet. */
1986 return PACKET_UNKNOWN;
1987 }
1988
1989 static enum packet_result
1990 packet_check_result (const gdb::char_vector &buf)
1991 {
1992 return packet_check_result (buf.data ());
1993 }
1994
1995 static enum packet_result
1996 packet_ok (const char *buf, struct packet_config *config)
1997 {
1998 enum packet_result result;
1999
2000 if (config->detect != AUTO_BOOLEAN_TRUE
2001 && config->support == PACKET_DISABLE)
2002 internal_error (__FILE__, __LINE__,
2003 _("packet_ok: attempt to use a disabled packet"));
2004
2005 result = packet_check_result (buf);
2006 switch (result)
2007 {
2008 case PACKET_OK:
2009 case PACKET_ERROR:
2010 /* The stub recognized the packet request. */
2011 if (config->support == PACKET_SUPPORT_UNKNOWN)
2012 {
2013 remote_debug_printf ("Packet %s (%s) is supported",
2014 config->name, config->title);
2015 config->support = PACKET_ENABLE;
2016 }
2017 break;
2018 case PACKET_UNKNOWN:
2019 /* The stub does not support the packet. */
2020 if (config->detect == AUTO_BOOLEAN_AUTO
2021 && config->support == PACKET_ENABLE)
2022 {
2023 /* If the stub previously indicated that the packet was
2024 supported then there is a protocol error. */
2025 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2026 config->name, config->title);
2027 }
2028 else if (config->detect == AUTO_BOOLEAN_TRUE)
2029 {
2030 /* The user set it wrong. */
2031 error (_("Enabled packet %s (%s) not recognized by stub"),
2032 config->name, config->title);
2033 }
2034
2035 remote_debug_printf ("Packet %s (%s) is NOT supported",
2036 config->name, config->title);
2037 config->support = PACKET_DISABLE;
2038 break;
2039 }
2040
2041 return result;
2042 }
2043
2044 static enum packet_result
2045 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2046 {
2047 return packet_ok (buf.data (), config);
2048 }
2049
2050 enum {
2051 PACKET_vCont = 0,
2052 PACKET_X,
2053 PACKET_qSymbol,
2054 PACKET_P,
2055 PACKET_p,
2056 PACKET_Z0,
2057 PACKET_Z1,
2058 PACKET_Z2,
2059 PACKET_Z3,
2060 PACKET_Z4,
2061 PACKET_vFile_setfs,
2062 PACKET_vFile_open,
2063 PACKET_vFile_pread,
2064 PACKET_vFile_pwrite,
2065 PACKET_vFile_close,
2066 PACKET_vFile_unlink,
2067 PACKET_vFile_readlink,
2068 PACKET_vFile_fstat,
2069 PACKET_qXfer_auxv,
2070 PACKET_qXfer_features,
2071 PACKET_qXfer_exec_file,
2072 PACKET_qXfer_libraries,
2073 PACKET_qXfer_libraries_svr4,
2074 PACKET_qXfer_memory_map,
2075 PACKET_qXfer_osdata,
2076 PACKET_qXfer_threads,
2077 PACKET_qXfer_statictrace_read,
2078 PACKET_qXfer_traceframe_info,
2079 PACKET_qXfer_uib,
2080 PACKET_qGetTIBAddr,
2081 PACKET_qGetTLSAddr,
2082 PACKET_qSupported,
2083 PACKET_qTStatus,
2084 PACKET_QPassSignals,
2085 PACKET_QCatchSyscalls,
2086 PACKET_QProgramSignals,
2087 PACKET_QSetWorkingDir,
2088 PACKET_QStartupWithShell,
2089 PACKET_QEnvironmentHexEncoded,
2090 PACKET_QEnvironmentReset,
2091 PACKET_QEnvironmentUnset,
2092 PACKET_qCRC,
2093 PACKET_qSearch_memory,
2094 PACKET_vAttach,
2095 PACKET_vRun,
2096 PACKET_QStartNoAckMode,
2097 PACKET_vKill,
2098 PACKET_qXfer_siginfo_read,
2099 PACKET_qXfer_siginfo_write,
2100 PACKET_qAttached,
2101
2102 /* Support for conditional tracepoints. */
2103 PACKET_ConditionalTracepoints,
2104
2105 /* Support for target-side breakpoint conditions. */
2106 PACKET_ConditionalBreakpoints,
2107
2108 /* Support for target-side breakpoint commands. */
2109 PACKET_BreakpointCommands,
2110
2111 /* Support for fast tracepoints. */
2112 PACKET_FastTracepoints,
2113
2114 /* Support for static tracepoints. */
2115 PACKET_StaticTracepoints,
2116
2117 /* Support for installing tracepoints while a trace experiment is
2118 running. */
2119 PACKET_InstallInTrace,
2120
2121 PACKET_bc,
2122 PACKET_bs,
2123 PACKET_TracepointSource,
2124 PACKET_QAllow,
2125 PACKET_qXfer_fdpic,
2126 PACKET_QDisableRandomization,
2127 PACKET_QAgent,
2128 PACKET_QTBuffer_size,
2129 PACKET_Qbtrace_off,
2130 PACKET_Qbtrace_bts,
2131 PACKET_Qbtrace_pt,
2132 PACKET_qXfer_btrace,
2133
2134 /* Support for the QNonStop packet. */
2135 PACKET_QNonStop,
2136
2137 /* Support for the QThreadEvents packet. */
2138 PACKET_QThreadEvents,
2139
2140 /* Support for multi-process extensions. */
2141 PACKET_multiprocess_feature,
2142
2143 /* Support for enabling and disabling tracepoints while a trace
2144 experiment is running. */
2145 PACKET_EnableDisableTracepoints_feature,
2146
2147 /* Support for collecting strings using the tracenz bytecode. */
2148 PACKET_tracenz_feature,
2149
2150 /* Support for continuing to run a trace experiment while GDB is
2151 disconnected. */
2152 PACKET_DisconnectedTracing_feature,
2153
2154 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2155 PACKET_augmented_libraries_svr4_read_feature,
2156
2157 /* Support for the qXfer:btrace-conf:read packet. */
2158 PACKET_qXfer_btrace_conf,
2159
2160 /* Support for the Qbtrace-conf:bts:size packet. */
2161 PACKET_Qbtrace_conf_bts_size,
2162
2163 /* Support for swbreak+ feature. */
2164 PACKET_swbreak_feature,
2165
2166 /* Support for hwbreak+ feature. */
2167 PACKET_hwbreak_feature,
2168
2169 /* Support for fork events. */
2170 PACKET_fork_event_feature,
2171
2172 /* Support for vfork events. */
2173 PACKET_vfork_event_feature,
2174
2175 /* Support for the Qbtrace-conf:pt:size packet. */
2176 PACKET_Qbtrace_conf_pt_size,
2177
2178 /* Support for exec events. */
2179 PACKET_exec_event_feature,
2180
2181 /* Support for query supported vCont actions. */
2182 PACKET_vContSupported,
2183
2184 /* Support remote CTRL-C. */
2185 PACKET_vCtrlC,
2186
2187 /* Support TARGET_WAITKIND_NO_RESUMED. */
2188 PACKET_no_resumed,
2189
2190 /* Support for memory tagging, allocation tag fetch/store
2191 packets and the tag violation stop replies. */
2192 PACKET_memory_tagging_feature,
2193
2194 PACKET_MAX
2195 };
2196
2197 /* FIXME: needs to be per-remote-target. Ignoring this for now,
2198 assuming all remote targets are the same server (thus all support
2199 the same packets). */
2200 static struct packet_config remote_protocol_packets[PACKET_MAX];
2201
2202 /* Returns the packet's corresponding "set remote foo-packet" command
2203 state. See struct packet_config for more details. */
2204
2205 static enum auto_boolean
2206 packet_set_cmd_state (int packet)
2207 {
2208 return remote_protocol_packets[packet].detect;
2209 }
2210
2211 /* Returns whether a given packet or feature is supported. This takes
2212 into account the state of the corresponding "set remote foo-packet"
2213 command, which may be used to bypass auto-detection. */
2214
2215 static enum packet_support
2216 packet_config_support (struct packet_config *config)
2217 {
2218 switch (config->detect)
2219 {
2220 case AUTO_BOOLEAN_TRUE:
2221 return PACKET_ENABLE;
2222 case AUTO_BOOLEAN_FALSE:
2223 return PACKET_DISABLE;
2224 case AUTO_BOOLEAN_AUTO:
2225 return config->support;
2226 default:
2227 gdb_assert_not_reached ("bad switch");
2228 }
2229 }
2230
2231 /* Same as packet_config_support, but takes the packet's enum value as
2232 argument. */
2233
2234 static enum packet_support
2235 packet_support (int packet)
2236 {
2237 struct packet_config *config = &remote_protocol_packets[packet];
2238
2239 return packet_config_support (config);
2240 }
2241
2242 static void
2243 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2244 struct cmd_list_element *c,
2245 const char *value)
2246 {
2247 struct packet_config *packet;
2248 gdb_assert (c->var.has_value ());
2249
2250 for (packet = remote_protocol_packets;
2251 packet < &remote_protocol_packets[PACKET_MAX];
2252 packet++)
2253 {
2254 if (c == packet->show_cmd)
2255 {
2256 show_packet_config_cmd (packet);
2257 return;
2258 }
2259 }
2260 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2261 c->name);
2262 }
2263
2264 /* Should we try one of the 'Z' requests? */
2265
2266 enum Z_packet_type
2267 {
2268 Z_PACKET_SOFTWARE_BP,
2269 Z_PACKET_HARDWARE_BP,
2270 Z_PACKET_WRITE_WP,
2271 Z_PACKET_READ_WP,
2272 Z_PACKET_ACCESS_WP,
2273 NR_Z_PACKET_TYPES
2274 };
2275
2276 /* For compatibility with older distributions. Provide a ``set remote
2277 Z-packet ...'' command that updates all the Z packet types. */
2278
2279 static enum auto_boolean remote_Z_packet_detect;
2280
2281 static void
2282 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2283 struct cmd_list_element *c)
2284 {
2285 int i;
2286
2287 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2288 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2289 }
2290
2291 static void
2292 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2293 struct cmd_list_element *c,
2294 const char *value)
2295 {
2296 int i;
2297
2298 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2299 {
2300 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2301 }
2302 }
2303
2304 /* Returns true if the multi-process extensions are in effect. */
2305
2306 static int
2307 remote_multi_process_p (struct remote_state *rs)
2308 {
2309 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2310 }
2311
2312 /* Returns true if fork events are supported. */
2313
2314 static int
2315 remote_fork_event_p (struct remote_state *rs)
2316 {
2317 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2318 }
2319
2320 /* Returns true if vfork events are supported. */
2321
2322 static int
2323 remote_vfork_event_p (struct remote_state *rs)
2324 {
2325 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2326 }
2327
2328 /* Returns true if exec events are supported. */
2329
2330 static int
2331 remote_exec_event_p (struct remote_state *rs)
2332 {
2333 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2334 }
2335
2336 /* Returns true if memory tagging is supported, false otherwise. */
2337
2338 static bool
2339 remote_memory_tagging_p ()
2340 {
2341 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2342 }
2343
2344 /* Insert fork catchpoint target routine. If fork events are enabled
2345 then return success, nothing more to do. */
2346
2347 int
2348 remote_target::insert_fork_catchpoint (int pid)
2349 {
2350 struct remote_state *rs = get_remote_state ();
2351
2352 return !remote_fork_event_p (rs);
2353 }
2354
2355 /* Remove fork catchpoint target routine. Nothing to do, just
2356 return success. */
2357
2358 int
2359 remote_target::remove_fork_catchpoint (int pid)
2360 {
2361 return 0;
2362 }
2363
2364 /* Insert vfork catchpoint target routine. If vfork events are enabled
2365 then return success, nothing more to do. */
2366
2367 int
2368 remote_target::insert_vfork_catchpoint (int pid)
2369 {
2370 struct remote_state *rs = get_remote_state ();
2371
2372 return !remote_vfork_event_p (rs);
2373 }
2374
2375 /* Remove vfork catchpoint target routine. Nothing to do, just
2376 return success. */
2377
2378 int
2379 remote_target::remove_vfork_catchpoint (int pid)
2380 {
2381 return 0;
2382 }
2383
2384 /* Insert exec catchpoint target routine. If exec events are
2385 enabled, just return success. */
2386
2387 int
2388 remote_target::insert_exec_catchpoint (int pid)
2389 {
2390 struct remote_state *rs = get_remote_state ();
2391
2392 return !remote_exec_event_p (rs);
2393 }
2394
2395 /* Remove exec catchpoint target routine. Nothing to do, just
2396 return success. */
2397
2398 int
2399 remote_target::remove_exec_catchpoint (int pid)
2400 {
2401 return 0;
2402 }
2403
2404 \f
2405
2406 /* Take advantage of the fact that the TID field is not used, to tag
2407 special ptids with it set to != 0. */
2408 static const ptid_t magic_null_ptid (42000, -1, 1);
2409 static const ptid_t not_sent_ptid (42000, -2, 1);
2410 static const ptid_t any_thread_ptid (42000, 0, 1);
2411
2412 /* Find out if the stub attached to PID (and hence GDB should offer to
2413 detach instead of killing it when bailing out). */
2414
2415 int
2416 remote_target::remote_query_attached (int pid)
2417 {
2418 struct remote_state *rs = get_remote_state ();
2419 size_t size = get_remote_packet_size ();
2420
2421 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2422 return 0;
2423
2424 if (remote_multi_process_p (rs))
2425 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2426 else
2427 xsnprintf (rs->buf.data (), size, "qAttached");
2428
2429 putpkt (rs->buf);
2430 getpkt (&rs->buf, 0);
2431
2432 switch (packet_ok (rs->buf,
2433 &remote_protocol_packets[PACKET_qAttached]))
2434 {
2435 case PACKET_OK:
2436 if (strcmp (rs->buf.data (), "1") == 0)
2437 return 1;
2438 break;
2439 case PACKET_ERROR:
2440 warning (_("Remote failure reply: %s"), rs->buf.data ());
2441 break;
2442 case PACKET_UNKNOWN:
2443 break;
2444 }
2445
2446 return 0;
2447 }
2448
2449 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2450 has been invented by GDB, instead of reported by the target. Since
2451 we can be connected to a remote system before before knowing about
2452 any inferior, mark the target with execution when we find the first
2453 inferior. If ATTACHED is 1, then we had just attached to this
2454 inferior. If it is 0, then we just created this inferior. If it
2455 is -1, then try querying the remote stub to find out if it had
2456 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2457 attempt to open this inferior's executable as the main executable
2458 if no main executable is open already. */
2459
2460 inferior *
2461 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2462 int try_open_exec)
2463 {
2464 struct inferior *inf;
2465
2466 /* Check whether this process we're learning about is to be
2467 considered attached, or if is to be considered to have been
2468 spawned by the stub. */
2469 if (attached == -1)
2470 attached = remote_query_attached (pid);
2471
2472 if (gdbarch_has_global_solist (target_gdbarch ()))
2473 {
2474 /* If the target shares code across all inferiors, then every
2475 attach adds a new inferior. */
2476 inf = add_inferior (pid);
2477
2478 /* ... and every inferior is bound to the same program space.
2479 However, each inferior may still have its own address
2480 space. */
2481 inf->aspace = maybe_new_address_space ();
2482 inf->pspace = current_program_space;
2483 }
2484 else
2485 {
2486 /* In the traditional debugging scenario, there's a 1-1 match
2487 between program/address spaces. We simply bind the inferior
2488 to the program space's address space. */
2489 inf = current_inferior ();
2490
2491 /* However, if the current inferior is already bound to a
2492 process, find some other empty inferior. */
2493 if (inf->pid != 0)
2494 {
2495 inf = nullptr;
2496 for (inferior *it : all_inferiors ())
2497 if (it->pid == 0)
2498 {
2499 inf = it;
2500 break;
2501 }
2502 }
2503 if (inf == nullptr)
2504 {
2505 /* Since all inferiors were already bound to a process, add
2506 a new inferior. */
2507 inf = add_inferior_with_spaces ();
2508 }
2509 switch_to_inferior_no_thread (inf);
2510 inf->push_target (this);
2511 inferior_appeared (inf, pid);
2512 }
2513
2514 inf->attach_flag = attached;
2515 inf->fake_pid_p = fake_pid_p;
2516
2517 /* If no main executable is currently open then attempt to
2518 open the file that was executed to create this inferior. */
2519 if (try_open_exec && get_exec_file (0) == NULL)
2520 exec_file_locate_attach (pid, 0, 1);
2521
2522 /* Check for exec file mismatch, and let the user solve it. */
2523 validate_exec_file (1);
2524
2525 return inf;
2526 }
2527
2528 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2529 static remote_thread_info *get_remote_thread_info (remote_target *target,
2530 ptid_t ptid);
2531
2532 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2533 according to RUNNING. */
2534
2535 thread_info *
2536 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2537 {
2538 struct remote_state *rs = get_remote_state ();
2539 struct thread_info *thread;
2540
2541 /* GDB historically didn't pull threads in the initial connection
2542 setup. If the remote target doesn't even have a concept of
2543 threads (e.g., a bare-metal target), even if internally we
2544 consider that a single-threaded target, mentioning a new thread
2545 might be confusing to the user. Be silent then, preserving the
2546 age old behavior. */
2547 if (rs->starting_up)
2548 thread = add_thread_silent (this, ptid);
2549 else
2550 thread = add_thread (this, ptid);
2551
2552 /* We start by assuming threads are resumed. That state then gets updated
2553 when we process a matching stop reply. */
2554 get_remote_thread_info (thread)->set_resumed ();
2555
2556 set_executing (this, ptid, executing);
2557 set_running (this, ptid, running);
2558
2559 return thread;
2560 }
2561
2562 /* Come here when we learn about a thread id from the remote target.
2563 It may be the first time we hear about such thread, so take the
2564 opportunity to add it to GDB's thread list. In case this is the
2565 first time we're noticing its corresponding inferior, add it to
2566 GDB's inferior list as well. EXECUTING indicates whether the
2567 thread is (internally) executing or stopped. */
2568
2569 void
2570 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2571 {
2572 /* In non-stop mode, we assume new found threads are (externally)
2573 running until proven otherwise with a stop reply. In all-stop,
2574 we can only get here if all threads are stopped. */
2575 bool running = target_is_non_stop_p ();
2576
2577 /* If this is a new thread, add it to GDB's thread list.
2578 If we leave it up to WFI to do this, bad things will happen. */
2579
2580 thread_info *tp = find_thread_ptid (this, currthread);
2581 if (tp != NULL && tp->state == THREAD_EXITED)
2582 {
2583 /* We're seeing an event on a thread id we knew had exited.
2584 This has to be a new thread reusing the old id. Add it. */
2585 remote_add_thread (currthread, running, executing);
2586 return;
2587 }
2588
2589 if (!in_thread_list (this, currthread))
2590 {
2591 struct inferior *inf = NULL;
2592 int pid = currthread.pid ();
2593
2594 if (inferior_ptid.is_pid ()
2595 && pid == inferior_ptid.pid ())
2596 {
2597 /* inferior_ptid has no thread member yet. This can happen
2598 with the vAttach -> remote_wait,"TAAthread:" path if the
2599 stub doesn't support qC. This is the first stop reported
2600 after an attach, so this is the main thread. Update the
2601 ptid in the thread list. */
2602 if (in_thread_list (this, ptid_t (pid)))
2603 thread_change_ptid (this, inferior_ptid, currthread);
2604 else
2605 {
2606 thread_info *thr
2607 = remote_add_thread (currthread, running, executing);
2608 switch_to_thread (thr);
2609 }
2610 return;
2611 }
2612
2613 if (magic_null_ptid == inferior_ptid)
2614 {
2615 /* inferior_ptid is not set yet. This can happen with the
2616 vRun -> remote_wait,"TAAthread:" path if the stub
2617 doesn't support qC. This is the first stop reported
2618 after an attach, so this is the main thread. Update the
2619 ptid in the thread list. */
2620 thread_change_ptid (this, inferior_ptid, currthread);
2621 return;
2622 }
2623
2624 /* When connecting to a target remote, or to a target
2625 extended-remote which already was debugging an inferior, we
2626 may not know about it yet. Add it before adding its child
2627 thread, so notifications are emitted in a sensible order. */
2628 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2629 {
2630 struct remote_state *rs = get_remote_state ();
2631 bool fake_pid_p = !remote_multi_process_p (rs);
2632
2633 inf = remote_add_inferior (fake_pid_p,
2634 currthread.pid (), -1, 1);
2635 }
2636
2637 /* This is really a new thread. Add it. */
2638 thread_info *new_thr
2639 = remote_add_thread (currthread, running, executing);
2640
2641 /* If we found a new inferior, let the common code do whatever
2642 it needs to with it (e.g., read shared libraries, insert
2643 breakpoints), unless we're just setting up an all-stop
2644 connection. */
2645 if (inf != NULL)
2646 {
2647 struct remote_state *rs = get_remote_state ();
2648
2649 if (!rs->starting_up)
2650 notice_new_inferior (new_thr, executing, 0);
2651 }
2652 }
2653 }
2654
2655 /* Return THREAD's private thread data, creating it if necessary. */
2656
2657 static remote_thread_info *
2658 get_remote_thread_info (thread_info *thread)
2659 {
2660 gdb_assert (thread != NULL);
2661
2662 if (thread->priv == NULL)
2663 thread->priv.reset (new remote_thread_info);
2664
2665 return static_cast<remote_thread_info *> (thread->priv.get ());
2666 }
2667
2668 /* Return PTID's private thread data, creating it if necessary. */
2669
2670 static remote_thread_info *
2671 get_remote_thread_info (remote_target *target, ptid_t ptid)
2672 {
2673 thread_info *thr = find_thread_ptid (target, ptid);
2674 return get_remote_thread_info (thr);
2675 }
2676
2677 /* Call this function as a result of
2678 1) A halt indication (T packet) containing a thread id
2679 2) A direct query of currthread
2680 3) Successful execution of set thread */
2681
2682 static void
2683 record_currthread (struct remote_state *rs, ptid_t currthread)
2684 {
2685 rs->general_thread = currthread;
2686 }
2687
2688 /* If 'QPassSignals' is supported, tell the remote stub what signals
2689 it can simply pass through to the inferior without reporting. */
2690
2691 void
2692 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2693 {
2694 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2695 {
2696 char *pass_packet, *p;
2697 int count = 0;
2698 struct remote_state *rs = get_remote_state ();
2699
2700 gdb_assert (pass_signals.size () < 256);
2701 for (size_t i = 0; i < pass_signals.size (); i++)
2702 {
2703 if (pass_signals[i])
2704 count++;
2705 }
2706 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2707 strcpy (pass_packet, "QPassSignals:");
2708 p = pass_packet + strlen (pass_packet);
2709 for (size_t i = 0; i < pass_signals.size (); i++)
2710 {
2711 if (pass_signals[i])
2712 {
2713 if (i >= 16)
2714 *p++ = tohex (i >> 4);
2715 *p++ = tohex (i & 15);
2716 if (count)
2717 *p++ = ';';
2718 else
2719 break;
2720 count--;
2721 }
2722 }
2723 *p = 0;
2724 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2725 {
2726 putpkt (pass_packet);
2727 getpkt (&rs->buf, 0);
2728 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2729 xfree (rs->last_pass_packet);
2730 rs->last_pass_packet = pass_packet;
2731 }
2732 else
2733 xfree (pass_packet);
2734 }
2735 }
2736
2737 /* If 'QCatchSyscalls' is supported, tell the remote stub
2738 to report syscalls to GDB. */
2739
2740 int
2741 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2742 gdb::array_view<const int> syscall_counts)
2743 {
2744 const char *catch_packet;
2745 enum packet_result result;
2746 int n_sysno = 0;
2747
2748 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2749 {
2750 /* Not supported. */
2751 return 1;
2752 }
2753
2754 if (needed && any_count == 0)
2755 {
2756 /* Count how many syscalls are to be caught. */
2757 for (size_t i = 0; i < syscall_counts.size (); i++)
2758 {
2759 if (syscall_counts[i] != 0)
2760 n_sysno++;
2761 }
2762 }
2763
2764 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2765 pid, needed, any_count, n_sysno);
2766
2767 std::string built_packet;
2768 if (needed)
2769 {
2770 /* Prepare a packet with the sysno list, assuming max 8+1
2771 characters for a sysno. If the resulting packet size is too
2772 big, fallback on the non-selective packet. */
2773 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2774 built_packet.reserve (maxpktsz);
2775 built_packet = "QCatchSyscalls:1";
2776 if (any_count == 0)
2777 {
2778 /* Add in each syscall to be caught. */
2779 for (size_t i = 0; i < syscall_counts.size (); i++)
2780 {
2781 if (syscall_counts[i] != 0)
2782 string_appendf (built_packet, ";%zx", i);
2783 }
2784 }
2785 if (built_packet.size () > get_remote_packet_size ())
2786 {
2787 /* catch_packet too big. Fallback to less efficient
2788 non selective mode, with GDB doing the filtering. */
2789 catch_packet = "QCatchSyscalls:1";
2790 }
2791 else
2792 catch_packet = built_packet.c_str ();
2793 }
2794 else
2795 catch_packet = "QCatchSyscalls:0";
2796
2797 struct remote_state *rs = get_remote_state ();
2798
2799 putpkt (catch_packet);
2800 getpkt (&rs->buf, 0);
2801 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2802 if (result == PACKET_OK)
2803 return 0;
2804 else
2805 return -1;
2806 }
2807
2808 /* If 'QProgramSignals' is supported, tell the remote stub what
2809 signals it should pass through to the inferior when detaching. */
2810
2811 void
2812 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2813 {
2814 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2815 {
2816 char *packet, *p;
2817 int count = 0;
2818 struct remote_state *rs = get_remote_state ();
2819
2820 gdb_assert (signals.size () < 256);
2821 for (size_t i = 0; i < signals.size (); i++)
2822 {
2823 if (signals[i])
2824 count++;
2825 }
2826 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2827 strcpy (packet, "QProgramSignals:");
2828 p = packet + strlen (packet);
2829 for (size_t i = 0; i < signals.size (); i++)
2830 {
2831 if (signal_pass_state (i))
2832 {
2833 if (i >= 16)
2834 *p++ = tohex (i >> 4);
2835 *p++ = tohex (i & 15);
2836 if (count)
2837 *p++ = ';';
2838 else
2839 break;
2840 count--;
2841 }
2842 }
2843 *p = 0;
2844 if (!rs->last_program_signals_packet
2845 || strcmp (rs->last_program_signals_packet, packet) != 0)
2846 {
2847 putpkt (packet);
2848 getpkt (&rs->buf, 0);
2849 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2850 xfree (rs->last_program_signals_packet);
2851 rs->last_program_signals_packet = packet;
2852 }
2853 else
2854 xfree (packet);
2855 }
2856 }
2857
2858 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2859 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2860 thread. If GEN is set, set the general thread, if not, then set
2861 the step/continue thread. */
2862 void
2863 remote_target::set_thread (ptid_t ptid, int gen)
2864 {
2865 struct remote_state *rs = get_remote_state ();
2866 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2867 char *buf = rs->buf.data ();
2868 char *endbuf = buf + get_remote_packet_size ();
2869
2870 if (state == ptid)
2871 return;
2872
2873 *buf++ = 'H';
2874 *buf++ = gen ? 'g' : 'c';
2875 if (ptid == magic_null_ptid)
2876 xsnprintf (buf, endbuf - buf, "0");
2877 else if (ptid == any_thread_ptid)
2878 xsnprintf (buf, endbuf - buf, "0");
2879 else if (ptid == minus_one_ptid)
2880 xsnprintf (buf, endbuf - buf, "-1");
2881 else
2882 write_ptid (buf, endbuf, ptid);
2883 putpkt (rs->buf);
2884 getpkt (&rs->buf, 0);
2885 if (gen)
2886 rs->general_thread = ptid;
2887 else
2888 rs->continue_thread = ptid;
2889 }
2890
2891 void
2892 remote_target::set_general_thread (ptid_t ptid)
2893 {
2894 set_thread (ptid, 1);
2895 }
2896
2897 void
2898 remote_target::set_continue_thread (ptid_t ptid)
2899 {
2900 set_thread (ptid, 0);
2901 }
2902
2903 /* Change the remote current process. Which thread within the process
2904 ends up selected isn't important, as long as it is the same process
2905 as what INFERIOR_PTID points to.
2906
2907 This comes from that fact that there is no explicit notion of
2908 "selected process" in the protocol. The selected process for
2909 general operations is the process the selected general thread
2910 belongs to. */
2911
2912 void
2913 remote_target::set_general_process ()
2914 {
2915 struct remote_state *rs = get_remote_state ();
2916
2917 /* If the remote can't handle multiple processes, don't bother. */
2918 if (!remote_multi_process_p (rs))
2919 return;
2920
2921 /* We only need to change the remote current thread if it's pointing
2922 at some other process. */
2923 if (rs->general_thread.pid () != inferior_ptid.pid ())
2924 set_general_thread (inferior_ptid);
2925 }
2926
2927 \f
2928 /* Return nonzero if this is the main thread that we made up ourselves
2929 to model non-threaded targets as single-threaded. */
2930
2931 static int
2932 remote_thread_always_alive (ptid_t ptid)
2933 {
2934 if (ptid == magic_null_ptid)
2935 /* The main thread is always alive. */
2936 return 1;
2937
2938 if (ptid.pid () != 0 && ptid.lwp () == 0)
2939 /* The main thread is always alive. This can happen after a
2940 vAttach, if the remote side doesn't support
2941 multi-threading. */
2942 return 1;
2943
2944 return 0;
2945 }
2946
2947 /* Return nonzero if the thread PTID is still alive on the remote
2948 system. */
2949
2950 bool
2951 remote_target::thread_alive (ptid_t ptid)
2952 {
2953 struct remote_state *rs = get_remote_state ();
2954 char *p, *endp;
2955
2956 /* Check if this is a thread that we made up ourselves to model
2957 non-threaded targets as single-threaded. */
2958 if (remote_thread_always_alive (ptid))
2959 return 1;
2960
2961 p = rs->buf.data ();
2962 endp = p + get_remote_packet_size ();
2963
2964 *p++ = 'T';
2965 write_ptid (p, endp, ptid);
2966
2967 putpkt (rs->buf);
2968 getpkt (&rs->buf, 0);
2969 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2970 }
2971
2972 /* Return a pointer to a thread name if we know it and NULL otherwise.
2973 The thread_info object owns the memory for the name. */
2974
2975 const char *
2976 remote_target::thread_name (struct thread_info *info)
2977 {
2978 if (info->priv != NULL)
2979 {
2980 const std::string &name = get_remote_thread_info (info)->name;
2981 return !name.empty () ? name.c_str () : NULL;
2982 }
2983
2984 return NULL;
2985 }
2986
2987 /* About these extended threadlist and threadinfo packets. They are
2988 variable length packets but, the fields within them are often fixed
2989 length. They are redundant enough to send over UDP as is the
2990 remote protocol in general. There is a matching unit test module
2991 in libstub. */
2992
2993 /* WARNING: This threadref data structure comes from the remote O.S.,
2994 libstub protocol encoding, and remote.c. It is not particularly
2995 changable. */
2996
2997 /* Right now, the internal structure is int. We want it to be bigger.
2998 Plan to fix this. */
2999
3000 typedef int gdb_threadref; /* Internal GDB thread reference. */
3001
3002 /* gdb_ext_thread_info is an internal GDB data structure which is
3003 equivalent to the reply of the remote threadinfo packet. */
3004
3005 struct gdb_ext_thread_info
3006 {
3007 threadref threadid; /* External form of thread reference. */
3008 int active; /* Has state interesting to GDB?
3009 regs, stack. */
3010 char display[256]; /* Brief state display, name,
3011 blocked/suspended. */
3012 char shortname[32]; /* To be used to name threads. */
3013 char more_display[256]; /* Long info, statistics, queue depth,
3014 whatever. */
3015 };
3016
3017 /* The volume of remote transfers can be limited by submitting
3018 a mask containing bits specifying the desired information.
3019 Use a union of these values as the 'selection' parameter to
3020 get_thread_info. FIXME: Make these TAG names more thread specific. */
3021
3022 #define TAG_THREADID 1
3023 #define TAG_EXISTS 2
3024 #define TAG_DISPLAY 4
3025 #define TAG_THREADNAME 8
3026 #define TAG_MOREDISPLAY 16
3027
3028 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3029
3030 static const char *unpack_nibble (const char *buf, int *val);
3031
3032 static const char *unpack_byte (const char *buf, int *value);
3033
3034 static char *pack_int (char *buf, int value);
3035
3036 static const char *unpack_int (const char *buf, int *value);
3037
3038 static const char *unpack_string (const char *src, char *dest, int length);
3039
3040 static char *pack_threadid (char *pkt, threadref *id);
3041
3042 static const char *unpack_threadid (const char *inbuf, threadref *id);
3043
3044 void int_to_threadref (threadref *id, int value);
3045
3046 static int threadref_to_int (threadref *ref);
3047
3048 static void copy_threadref (threadref *dest, threadref *src);
3049
3050 static int threadmatch (threadref *dest, threadref *src);
3051
3052 static char *pack_threadinfo_request (char *pkt, int mode,
3053 threadref *id);
3054
3055 static char *pack_threadlist_request (char *pkt, int startflag,
3056 int threadcount,
3057 threadref *nextthread);
3058
3059 static int remote_newthread_step (threadref *ref, void *context);
3060
3061
3062 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3063 buffer we're allowed to write to. Returns
3064 BUF+CHARACTERS_WRITTEN. */
3065
3066 char *
3067 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3068 {
3069 int pid, tid;
3070 struct remote_state *rs = get_remote_state ();
3071
3072 if (remote_multi_process_p (rs))
3073 {
3074 pid = ptid.pid ();
3075 if (pid < 0)
3076 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3077 else
3078 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3079 }
3080 tid = ptid.lwp ();
3081 if (tid < 0)
3082 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3083 else
3084 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3085
3086 return buf;
3087 }
3088
3089 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3090 last parsed char. Returns null_ptid if no thread id is found, and
3091 throws an error if the thread id has an invalid format. */
3092
3093 static ptid_t
3094 read_ptid (const char *buf, const char **obuf)
3095 {
3096 const char *p = buf;
3097 const char *pp;
3098 ULONGEST pid = 0, tid = 0;
3099
3100 if (*p == 'p')
3101 {
3102 /* Multi-process ptid. */
3103 pp = unpack_varlen_hex (p + 1, &pid);
3104 if (*pp != '.')
3105 error (_("invalid remote ptid: %s"), p);
3106
3107 p = pp;
3108 pp = unpack_varlen_hex (p + 1, &tid);
3109 if (obuf)
3110 *obuf = pp;
3111 return ptid_t (pid, tid);
3112 }
3113
3114 /* No multi-process. Just a tid. */
3115 pp = unpack_varlen_hex (p, &tid);
3116
3117 /* Return null_ptid when no thread id is found. */
3118 if (p == pp)
3119 {
3120 if (obuf)
3121 *obuf = pp;
3122 return null_ptid;
3123 }
3124
3125 /* Since the stub is not sending a process id, then default to
3126 what's in inferior_ptid, unless it's null at this point. If so,
3127 then since there's no way to know the pid of the reported
3128 threads, use the magic number. */
3129 if (inferior_ptid == null_ptid)
3130 pid = magic_null_ptid.pid ();
3131 else
3132 pid = inferior_ptid.pid ();
3133
3134 if (obuf)
3135 *obuf = pp;
3136 return ptid_t (pid, tid);
3137 }
3138
3139 static int
3140 stubhex (int ch)
3141 {
3142 if (ch >= 'a' && ch <= 'f')
3143 return ch - 'a' + 10;
3144 if (ch >= '0' && ch <= '9')
3145 return ch - '0';
3146 if (ch >= 'A' && ch <= 'F')
3147 return ch - 'A' + 10;
3148 return -1;
3149 }
3150
3151 static int
3152 stub_unpack_int (const char *buff, int fieldlength)
3153 {
3154 int nibble;
3155 int retval = 0;
3156
3157 while (fieldlength)
3158 {
3159 nibble = stubhex (*buff++);
3160 retval |= nibble;
3161 fieldlength--;
3162 if (fieldlength)
3163 retval = retval << 4;
3164 }
3165 return retval;
3166 }
3167
3168 static const char *
3169 unpack_nibble (const char *buf, int *val)
3170 {
3171 *val = fromhex (*buf++);
3172 return buf;
3173 }
3174
3175 static const char *
3176 unpack_byte (const char *buf, int *value)
3177 {
3178 *value = stub_unpack_int (buf, 2);
3179 return buf + 2;
3180 }
3181
3182 static char *
3183 pack_int (char *buf, int value)
3184 {
3185 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3186 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3187 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3188 buf = pack_hex_byte (buf, (value & 0xff));
3189 return buf;
3190 }
3191
3192 static const char *
3193 unpack_int (const char *buf, int *value)
3194 {
3195 *value = stub_unpack_int (buf, 8);
3196 return buf + 8;
3197 }
3198
3199 #if 0 /* Currently unused, uncomment when needed. */
3200 static char *pack_string (char *pkt, char *string);
3201
3202 static char *
3203 pack_string (char *pkt, char *string)
3204 {
3205 char ch;
3206 int len;
3207
3208 len = strlen (string);
3209 if (len > 200)
3210 len = 200; /* Bigger than most GDB packets, junk??? */
3211 pkt = pack_hex_byte (pkt, len);
3212 while (len-- > 0)
3213 {
3214 ch = *string++;
3215 if ((ch == '\0') || (ch == '#'))
3216 ch = '*'; /* Protect encapsulation. */
3217 *pkt++ = ch;
3218 }
3219 return pkt;
3220 }
3221 #endif /* 0 (unused) */
3222
3223 static const char *
3224 unpack_string (const char *src, char *dest, int length)
3225 {
3226 while (length--)
3227 *dest++ = *src++;
3228 *dest = '\0';
3229 return src;
3230 }
3231
3232 static char *
3233 pack_threadid (char *pkt, threadref *id)
3234 {
3235 char *limit;
3236 unsigned char *altid;
3237
3238 altid = (unsigned char *) id;
3239 limit = pkt + BUF_THREAD_ID_SIZE;
3240 while (pkt < limit)
3241 pkt = pack_hex_byte (pkt, *altid++);
3242 return pkt;
3243 }
3244
3245
3246 static const char *
3247 unpack_threadid (const char *inbuf, threadref *id)
3248 {
3249 char *altref;
3250 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3251 int x, y;
3252
3253 altref = (char *) id;
3254
3255 while (inbuf < limit)
3256 {
3257 x = stubhex (*inbuf++);
3258 y = stubhex (*inbuf++);
3259 *altref++ = (x << 4) | y;
3260 }
3261 return inbuf;
3262 }
3263
3264 /* Externally, threadrefs are 64 bits but internally, they are still
3265 ints. This is due to a mismatch of specifications. We would like
3266 to use 64bit thread references internally. This is an adapter
3267 function. */
3268
3269 void
3270 int_to_threadref (threadref *id, int value)
3271 {
3272 unsigned char *scan;
3273
3274 scan = (unsigned char *) id;
3275 {
3276 int i = 4;
3277 while (i--)
3278 *scan++ = 0;
3279 }
3280 *scan++ = (value >> 24) & 0xff;
3281 *scan++ = (value >> 16) & 0xff;
3282 *scan++ = (value >> 8) & 0xff;
3283 *scan++ = (value & 0xff);
3284 }
3285
3286 static int
3287 threadref_to_int (threadref *ref)
3288 {
3289 int i, value = 0;
3290 unsigned char *scan;
3291
3292 scan = *ref;
3293 scan += 4;
3294 i = 4;
3295 while (i-- > 0)
3296 value = (value << 8) | ((*scan++) & 0xff);
3297 return value;
3298 }
3299
3300 static void
3301 copy_threadref (threadref *dest, threadref *src)
3302 {
3303 int i;
3304 unsigned char *csrc, *cdest;
3305
3306 csrc = (unsigned char *) src;
3307 cdest = (unsigned char *) dest;
3308 i = 8;
3309 while (i--)
3310 *cdest++ = *csrc++;
3311 }
3312
3313 static int
3314 threadmatch (threadref *dest, threadref *src)
3315 {
3316 /* Things are broken right now, so just assume we got a match. */
3317 #if 0
3318 unsigned char *srcp, *destp;
3319 int i, result;
3320 srcp = (char *) src;
3321 destp = (char *) dest;
3322
3323 result = 1;
3324 while (i-- > 0)
3325 result &= (*srcp++ == *destp++) ? 1 : 0;
3326 return result;
3327 #endif
3328 return 1;
3329 }
3330
3331 /*
3332 threadid:1, # always request threadid
3333 context_exists:2,
3334 display:4,
3335 unique_name:8,
3336 more_display:16
3337 */
3338
3339 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3340
3341 static char *
3342 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3343 {
3344 *pkt++ = 'q'; /* Info Query */
3345 *pkt++ = 'P'; /* process or thread info */
3346 pkt = pack_int (pkt, mode); /* mode */
3347 pkt = pack_threadid (pkt, id); /* threadid */
3348 *pkt = '\0'; /* terminate */
3349 return pkt;
3350 }
3351
3352 /* These values tag the fields in a thread info response packet. */
3353 /* Tagging the fields allows us to request specific fields and to
3354 add more fields as time goes by. */
3355
3356 #define TAG_THREADID 1 /* Echo the thread identifier. */
3357 #define TAG_EXISTS 2 /* Is this process defined enough to
3358 fetch registers and its stack? */
3359 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3360 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3361 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3362 the process. */
3363
3364 int
3365 remote_target::remote_unpack_thread_info_response (const char *pkt,
3366 threadref *expectedref,
3367 gdb_ext_thread_info *info)
3368 {
3369 struct remote_state *rs = get_remote_state ();
3370 int mask, length;
3371 int tag;
3372 threadref ref;
3373 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3374 int retval = 1;
3375
3376 /* info->threadid = 0; FIXME: implement zero_threadref. */
3377 info->active = 0;
3378 info->display[0] = '\0';
3379 info->shortname[0] = '\0';
3380 info->more_display[0] = '\0';
3381
3382 /* Assume the characters indicating the packet type have been
3383 stripped. */
3384 pkt = unpack_int (pkt, &mask); /* arg mask */
3385 pkt = unpack_threadid (pkt, &ref);
3386
3387 if (mask == 0)
3388 warning (_("Incomplete response to threadinfo request."));
3389 if (!threadmatch (&ref, expectedref))
3390 { /* This is an answer to a different request. */
3391 warning (_("ERROR RMT Thread info mismatch."));
3392 return 0;
3393 }
3394 copy_threadref (&info->threadid, &ref);
3395
3396 /* Loop on tagged fields , try to bail if something goes wrong. */
3397
3398 /* Packets are terminated with nulls. */
3399 while ((pkt < limit) && mask && *pkt)
3400 {
3401 pkt = unpack_int (pkt, &tag); /* tag */
3402 pkt = unpack_byte (pkt, &length); /* length */
3403 if (!(tag & mask)) /* Tags out of synch with mask. */
3404 {
3405 warning (_("ERROR RMT: threadinfo tag mismatch."));
3406 retval = 0;
3407 break;
3408 }
3409 if (tag == TAG_THREADID)
3410 {
3411 if (length != 16)
3412 {
3413 warning (_("ERROR RMT: length of threadid is not 16."));
3414 retval = 0;
3415 break;
3416 }
3417 pkt = unpack_threadid (pkt, &ref);
3418 mask = mask & ~TAG_THREADID;
3419 continue;
3420 }
3421 if (tag == TAG_EXISTS)
3422 {
3423 info->active = stub_unpack_int (pkt, length);
3424 pkt += length;
3425 mask = mask & ~(TAG_EXISTS);
3426 if (length > 8)
3427 {
3428 warning (_("ERROR RMT: 'exists' length too long."));
3429 retval = 0;
3430 break;
3431 }
3432 continue;
3433 }
3434 if (tag == TAG_THREADNAME)
3435 {
3436 pkt = unpack_string (pkt, &info->shortname[0], length);
3437 mask = mask & ~TAG_THREADNAME;
3438 continue;
3439 }
3440 if (tag == TAG_DISPLAY)
3441 {
3442 pkt = unpack_string (pkt, &info->display[0], length);
3443 mask = mask & ~TAG_DISPLAY;
3444 continue;
3445 }
3446 if (tag == TAG_MOREDISPLAY)
3447 {
3448 pkt = unpack_string (pkt, &info->more_display[0], length);
3449 mask = mask & ~TAG_MOREDISPLAY;
3450 continue;
3451 }
3452 warning (_("ERROR RMT: unknown thread info tag."));
3453 break; /* Not a tag we know about. */
3454 }
3455 return retval;
3456 }
3457
3458 int
3459 remote_target::remote_get_threadinfo (threadref *threadid,
3460 int fieldset,
3461 gdb_ext_thread_info *info)
3462 {
3463 struct remote_state *rs = get_remote_state ();
3464 int result;
3465
3466 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3467 putpkt (rs->buf);
3468 getpkt (&rs->buf, 0);
3469
3470 if (rs->buf[0] == '\0')
3471 return 0;
3472
3473 result = remote_unpack_thread_info_response (&rs->buf[2],
3474 threadid, info);
3475 return result;
3476 }
3477
3478 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3479
3480 static char *
3481 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3482 threadref *nextthread)
3483 {
3484 *pkt++ = 'q'; /* info query packet */
3485 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3486 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3487 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3488 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3489 *pkt = '\0';
3490 return pkt;
3491 }
3492
3493 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3494
3495 int
3496 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3497 threadref *original_echo,
3498 threadref *resultlist,
3499 int *doneflag)
3500 {
3501 struct remote_state *rs = get_remote_state ();
3502 int count, resultcount, done;
3503
3504 resultcount = 0;
3505 /* Assume the 'q' and 'M chars have been stripped. */
3506 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3507 /* done parse past here */
3508 pkt = unpack_byte (pkt, &count); /* count field */
3509 pkt = unpack_nibble (pkt, &done);
3510 /* The first threadid is the argument threadid. */
3511 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3512 while ((count-- > 0) && (pkt < limit))
3513 {
3514 pkt = unpack_threadid (pkt, resultlist++);
3515 if (resultcount++ >= result_limit)
3516 break;
3517 }
3518 if (doneflag)
3519 *doneflag = done;
3520 return resultcount;
3521 }
3522
3523 /* Fetch the next batch of threads from the remote. Returns -1 if the
3524 qL packet is not supported, 0 on error and 1 on success. */
3525
3526 int
3527 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3528 int result_limit, int *done, int *result_count,
3529 threadref *threadlist)
3530 {
3531 struct remote_state *rs = get_remote_state ();
3532 int result = 1;
3533
3534 /* Truncate result limit to be smaller than the packet size. */
3535 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3536 >= get_remote_packet_size ())
3537 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3538
3539 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3540 nextthread);
3541 putpkt (rs->buf);
3542 getpkt (&rs->buf, 0);
3543 if (rs->buf[0] == '\0')
3544 {
3545 /* Packet not supported. */
3546 return -1;
3547 }
3548
3549 *result_count =
3550 parse_threadlist_response (&rs->buf[2], result_limit,
3551 &rs->echo_nextthread, threadlist, done);
3552
3553 if (!threadmatch (&rs->echo_nextthread, nextthread))
3554 {
3555 /* FIXME: This is a good reason to drop the packet. */
3556 /* Possibly, there is a duplicate response. */
3557 /* Possibilities :
3558 retransmit immediatly - race conditions
3559 retransmit after timeout - yes
3560 exit
3561 wait for packet, then exit
3562 */
3563 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3564 return 0; /* I choose simply exiting. */
3565 }
3566 if (*result_count <= 0)
3567 {
3568 if (*done != 1)
3569 {
3570 warning (_("RMT ERROR : failed to get remote thread list."));
3571 result = 0;
3572 }
3573 return result; /* break; */
3574 }
3575 if (*result_count > result_limit)
3576 {
3577 *result_count = 0;
3578 warning (_("RMT ERROR: threadlist response longer than requested."));
3579 return 0;
3580 }
3581 return result;
3582 }
3583
3584 /* Fetch the list of remote threads, with the qL packet, and call
3585 STEPFUNCTION for each thread found. Stops iterating and returns 1
3586 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3587 STEPFUNCTION returns false. If the packet is not supported,
3588 returns -1. */
3589
3590 int
3591 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3592 void *context, int looplimit)
3593 {
3594 struct remote_state *rs = get_remote_state ();
3595 int done, i, result_count;
3596 int startflag = 1;
3597 int result = 1;
3598 int loopcount = 0;
3599
3600 done = 0;
3601 while (!done)
3602 {
3603 if (loopcount++ > looplimit)
3604 {
3605 result = 0;
3606 warning (_("Remote fetch threadlist -infinite loop-."));
3607 break;
3608 }
3609 result = remote_get_threadlist (startflag, &rs->nextthread,
3610 MAXTHREADLISTRESULTS,
3611 &done, &result_count,
3612 rs->resultthreadlist);
3613 if (result <= 0)
3614 break;
3615 /* Clear for later iterations. */
3616 startflag = 0;
3617 /* Setup to resume next batch of thread references, set nextthread. */
3618 if (result_count >= 1)
3619 copy_threadref (&rs->nextthread,
3620 &rs->resultthreadlist[result_count - 1]);
3621 i = 0;
3622 while (result_count--)
3623 {
3624 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3625 {
3626 result = 0;
3627 break;
3628 }
3629 }
3630 }
3631 return result;
3632 }
3633
3634 /* A thread found on the remote target. */
3635
3636 struct thread_item
3637 {
3638 explicit thread_item (ptid_t ptid_)
3639 : ptid (ptid_)
3640 {}
3641
3642 thread_item (thread_item &&other) = default;
3643 thread_item &operator= (thread_item &&other) = default;
3644
3645 DISABLE_COPY_AND_ASSIGN (thread_item);
3646
3647 /* The thread's PTID. */
3648 ptid_t ptid;
3649
3650 /* The thread's extra info. */
3651 std::string extra;
3652
3653 /* The thread's name. */
3654 std::string name;
3655
3656 /* The core the thread was running on. -1 if not known. */
3657 int core = -1;
3658
3659 /* The thread handle associated with the thread. */
3660 gdb::byte_vector thread_handle;
3661 };
3662
3663 /* Context passed around to the various methods listing remote
3664 threads. As new threads are found, they're added to the ITEMS
3665 vector. */
3666
3667 struct threads_listing_context
3668 {
3669 /* Return true if this object contains an entry for a thread with ptid
3670 PTID. */
3671
3672 bool contains_thread (ptid_t ptid) const
3673 {
3674 auto match_ptid = [&] (const thread_item &item)
3675 {
3676 return item.ptid == ptid;
3677 };
3678
3679 auto it = std::find_if (this->items.begin (),
3680 this->items.end (),
3681 match_ptid);
3682
3683 return it != this->items.end ();
3684 }
3685
3686 /* Remove the thread with ptid PTID. */
3687
3688 void remove_thread (ptid_t ptid)
3689 {
3690 auto match_ptid = [&] (const thread_item &item)
3691 {
3692 return item.ptid == ptid;
3693 };
3694
3695 auto it = std::remove_if (this->items.begin (),
3696 this->items.end (),
3697 match_ptid);
3698
3699 if (it != this->items.end ())
3700 this->items.erase (it);
3701 }
3702
3703 /* The threads found on the remote target. */
3704 std::vector<thread_item> items;
3705 };
3706
3707 static int
3708 remote_newthread_step (threadref *ref, void *data)
3709 {
3710 struct threads_listing_context *context
3711 = (struct threads_listing_context *) data;
3712 int pid = inferior_ptid.pid ();
3713 int lwp = threadref_to_int (ref);
3714 ptid_t ptid (pid, lwp);
3715
3716 context->items.emplace_back (ptid);
3717
3718 return 1; /* continue iterator */
3719 }
3720
3721 #define CRAZY_MAX_THREADS 1000
3722
3723 ptid_t
3724 remote_target::remote_current_thread (ptid_t oldpid)
3725 {
3726 struct remote_state *rs = get_remote_state ();
3727
3728 putpkt ("qC");
3729 getpkt (&rs->buf, 0);
3730 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3731 {
3732 const char *obuf;
3733 ptid_t result;
3734
3735 result = read_ptid (&rs->buf[2], &obuf);
3736 if (*obuf != '\0')
3737 remote_debug_printf ("warning: garbage in qC reply");
3738
3739 return result;
3740 }
3741 else
3742 return oldpid;
3743 }
3744
3745 /* List remote threads using the deprecated qL packet. */
3746
3747 int
3748 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3749 {
3750 if (remote_threadlist_iterator (remote_newthread_step, context,
3751 CRAZY_MAX_THREADS) >= 0)
3752 return 1;
3753
3754 return 0;
3755 }
3756
3757 #if defined(HAVE_LIBEXPAT)
3758
3759 static void
3760 start_thread (struct gdb_xml_parser *parser,
3761 const struct gdb_xml_element *element,
3762 void *user_data,
3763 std::vector<gdb_xml_value> &attributes)
3764 {
3765 struct threads_listing_context *data
3766 = (struct threads_listing_context *) user_data;
3767 struct gdb_xml_value *attr;
3768
3769 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3770 ptid_t ptid = read_ptid (id, NULL);
3771
3772 data->items.emplace_back (ptid);
3773 thread_item &item = data->items.back ();
3774
3775 attr = xml_find_attribute (attributes, "core");
3776 if (attr != NULL)
3777 item.core = *(ULONGEST *) attr->value.get ();
3778
3779 attr = xml_find_attribute (attributes, "name");
3780 if (attr != NULL)
3781 item.name = (const char *) attr->value.get ();
3782
3783 attr = xml_find_attribute (attributes, "handle");
3784 if (attr != NULL)
3785 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3786 }
3787
3788 static void
3789 end_thread (struct gdb_xml_parser *parser,
3790 const struct gdb_xml_element *element,
3791 void *user_data, const char *body_text)
3792 {
3793 struct threads_listing_context *data
3794 = (struct threads_listing_context *) user_data;
3795
3796 if (body_text != NULL && *body_text != '\0')
3797 data->items.back ().extra = body_text;
3798 }
3799
3800 const struct gdb_xml_attribute thread_attributes[] = {
3801 { "id", GDB_XML_AF_NONE, NULL, NULL },
3802 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3803 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3804 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3805 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3806 };
3807
3808 const struct gdb_xml_element thread_children[] = {
3809 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3810 };
3811
3812 const struct gdb_xml_element threads_children[] = {
3813 { "thread", thread_attributes, thread_children,
3814 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3815 start_thread, end_thread },
3816 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3817 };
3818
3819 const struct gdb_xml_element threads_elements[] = {
3820 { "threads", NULL, threads_children,
3821 GDB_XML_EF_NONE, NULL, NULL },
3822 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3823 };
3824
3825 #endif
3826
3827 /* List remote threads using qXfer:threads:read. */
3828
3829 int
3830 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3831 {
3832 #if defined(HAVE_LIBEXPAT)
3833 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3834 {
3835 gdb::optional<gdb::char_vector> xml
3836 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3837
3838 if (xml && (*xml)[0] != '\0')
3839 {
3840 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3841 threads_elements, xml->data (), context);
3842 }
3843
3844 return 1;
3845 }
3846 #endif
3847
3848 return 0;
3849 }
3850
3851 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3852
3853 int
3854 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3855 {
3856 struct remote_state *rs = get_remote_state ();
3857
3858 if (rs->use_threadinfo_query)
3859 {
3860 const char *bufp;
3861
3862 putpkt ("qfThreadInfo");
3863 getpkt (&rs->buf, 0);
3864 bufp = rs->buf.data ();
3865 if (bufp[0] != '\0') /* q packet recognized */
3866 {
3867 while (*bufp++ == 'm') /* reply contains one or more TID */
3868 {
3869 do
3870 {
3871 ptid_t ptid = read_ptid (bufp, &bufp);
3872 context->items.emplace_back (ptid);
3873 }
3874 while (*bufp++ == ','); /* comma-separated list */
3875 putpkt ("qsThreadInfo");
3876 getpkt (&rs->buf, 0);
3877 bufp = rs->buf.data ();
3878 }
3879 return 1;
3880 }
3881 else
3882 {
3883 /* Packet not recognized. */
3884 rs->use_threadinfo_query = 0;
3885 }
3886 }
3887
3888 return 0;
3889 }
3890
3891 /* Return true if INF only has one non-exited thread. */
3892
3893 static bool
3894 has_single_non_exited_thread (inferior *inf)
3895 {
3896 int count = 0;
3897 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3898 if (++count > 1)
3899 break;
3900 return count == 1;
3901 }
3902
3903 /* Implement the to_update_thread_list function for the remote
3904 targets. */
3905
3906 void
3907 remote_target::update_thread_list ()
3908 {
3909 struct threads_listing_context context;
3910 int got_list = 0;
3911
3912 /* We have a few different mechanisms to fetch the thread list. Try
3913 them all, starting with the most preferred one first, falling
3914 back to older methods. */
3915 if (remote_get_threads_with_qxfer (&context)
3916 || remote_get_threads_with_qthreadinfo (&context)
3917 || remote_get_threads_with_ql (&context))
3918 {
3919 got_list = 1;
3920
3921 if (context.items.empty ()
3922 && remote_thread_always_alive (inferior_ptid))
3923 {
3924 /* Some targets don't really support threads, but still
3925 reply an (empty) thread list in response to the thread
3926 listing packets, instead of replying "packet not
3927 supported". Exit early so we don't delete the main
3928 thread. */
3929 return;
3930 }
3931
3932 /* CONTEXT now holds the current thread list on the remote
3933 target end. Delete GDB-side threads no longer found on the
3934 target. */
3935 for (thread_info *tp : all_threads_safe ())
3936 {
3937 if (tp->inf->process_target () != this)
3938 continue;
3939
3940 if (!context.contains_thread (tp->ptid))
3941 {
3942 /* Do not remove the thread if it is the last thread in
3943 the inferior. This situation happens when we have a
3944 pending exit process status to process. Otherwise we
3945 may end up with a seemingly live inferior (i.e. pid
3946 != 0) that has no threads. */
3947 if (has_single_non_exited_thread (tp->inf))
3948 continue;
3949
3950 /* Not found. */
3951 delete_thread (tp);
3952 }
3953 }
3954
3955 /* Remove any unreported fork child threads from CONTEXT so
3956 that we don't interfere with follow fork, which is where
3957 creation of such threads is handled. */
3958 remove_new_fork_children (&context);
3959
3960 /* And now add threads we don't know about yet to our list. */
3961 for (thread_item &item : context.items)
3962 {
3963 if (item.ptid != null_ptid)
3964 {
3965 /* In non-stop mode, we assume new found threads are
3966 executing until proven otherwise with a stop reply.
3967 In all-stop, we can only get here if all threads are
3968 stopped. */
3969 bool executing = target_is_non_stop_p ();
3970
3971 remote_notice_new_inferior (item.ptid, executing);
3972
3973 thread_info *tp = find_thread_ptid (this, item.ptid);
3974 remote_thread_info *info = get_remote_thread_info (tp);
3975 info->core = item.core;
3976 info->extra = std::move (item.extra);
3977 info->name = std::move (item.name);
3978 info->thread_handle = std::move (item.thread_handle);
3979 }
3980 }
3981 }
3982
3983 if (!got_list)
3984 {
3985 /* If no thread listing method is supported, then query whether
3986 each known thread is alive, one by one, with the T packet.
3987 If the target doesn't support threads at all, then this is a
3988 no-op. See remote_thread_alive. */
3989 prune_threads ();
3990 }
3991 }
3992
3993 /*
3994 * Collect a descriptive string about the given thread.
3995 * The target may say anything it wants to about the thread
3996 * (typically info about its blocked / runnable state, name, etc.).
3997 * This string will appear in the info threads display.
3998 *
3999 * Optional: targets are not required to implement this function.
4000 */
4001
4002 const char *
4003 remote_target::extra_thread_info (thread_info *tp)
4004 {
4005 struct remote_state *rs = get_remote_state ();
4006 int set;
4007 threadref id;
4008 struct gdb_ext_thread_info threadinfo;
4009
4010 if (rs->remote_desc == 0) /* paranoia */
4011 internal_error (__FILE__, __LINE__,
4012 _("remote_threads_extra_info"));
4013
4014 if (tp->ptid == magic_null_ptid
4015 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4016 /* This is the main thread which was added by GDB. The remote
4017 server doesn't know about it. */
4018 return NULL;
4019
4020 std::string &extra = get_remote_thread_info (tp)->extra;
4021
4022 /* If already have cached info, use it. */
4023 if (!extra.empty ())
4024 return extra.c_str ();
4025
4026 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4027 {
4028 /* If we're using qXfer:threads:read, then the extra info is
4029 included in the XML. So if we didn't have anything cached,
4030 it's because there's really no extra info. */
4031 return NULL;
4032 }
4033
4034 if (rs->use_threadextra_query)
4035 {
4036 char *b = rs->buf.data ();
4037 char *endb = b + get_remote_packet_size ();
4038
4039 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4040 b += strlen (b);
4041 write_ptid (b, endb, tp->ptid);
4042
4043 putpkt (rs->buf);
4044 getpkt (&rs->buf, 0);
4045 if (rs->buf[0] != 0)
4046 {
4047 extra.resize (strlen (rs->buf.data ()) / 2);
4048 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4049 return extra.c_str ();
4050 }
4051 }
4052
4053 /* If the above query fails, fall back to the old method. */
4054 rs->use_threadextra_query = 0;
4055 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4056 | TAG_MOREDISPLAY | TAG_DISPLAY;
4057 int_to_threadref (&id, tp->ptid.lwp ());
4058 if (remote_get_threadinfo (&id, set, &threadinfo))
4059 if (threadinfo.active)
4060 {
4061 if (*threadinfo.shortname)
4062 string_appendf (extra, " Name: %s", threadinfo.shortname);
4063 if (*threadinfo.display)
4064 {
4065 if (!extra.empty ())
4066 extra += ',';
4067 string_appendf (extra, " State: %s", threadinfo.display);
4068 }
4069 if (*threadinfo.more_display)
4070 {
4071 if (!extra.empty ())
4072 extra += ',';
4073 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4074 }
4075 return extra.c_str ();
4076 }
4077 return NULL;
4078 }
4079 \f
4080
4081 bool
4082 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4083 struct static_tracepoint_marker *marker)
4084 {
4085 struct remote_state *rs = get_remote_state ();
4086 char *p = rs->buf.data ();
4087
4088 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4089 p += strlen (p);
4090 p += hexnumstr (p, addr);
4091 putpkt (rs->buf);
4092 getpkt (&rs->buf, 0);
4093 p = rs->buf.data ();
4094
4095 if (*p == 'E')
4096 error (_("Remote failure reply: %s"), p);
4097
4098 if (*p++ == 'm')
4099 {
4100 parse_static_tracepoint_marker_definition (p, NULL, marker);
4101 return true;
4102 }
4103
4104 return false;
4105 }
4106
4107 std::vector<static_tracepoint_marker>
4108 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4109 {
4110 struct remote_state *rs = get_remote_state ();
4111 std::vector<static_tracepoint_marker> markers;
4112 const char *p;
4113 static_tracepoint_marker marker;
4114
4115 /* Ask for a first packet of static tracepoint marker
4116 definition. */
4117 putpkt ("qTfSTM");
4118 getpkt (&rs->buf, 0);
4119 p = rs->buf.data ();
4120 if (*p == 'E')
4121 error (_("Remote failure reply: %s"), p);
4122
4123 while (*p++ == 'm')
4124 {
4125 do
4126 {
4127 parse_static_tracepoint_marker_definition (p, &p, &marker);
4128
4129 if (strid == NULL || marker.str_id == strid)
4130 markers.push_back (std::move (marker));
4131 }
4132 while (*p++ == ','); /* comma-separated list */
4133 /* Ask for another packet of static tracepoint definition. */
4134 putpkt ("qTsSTM");
4135 getpkt (&rs->buf, 0);
4136 p = rs->buf.data ();
4137 }
4138
4139 return markers;
4140 }
4141
4142 \f
4143 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4144
4145 ptid_t
4146 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4147 {
4148 return ptid_t (inferior_ptid.pid (), lwp);
4149 }
4150 \f
4151
4152 /* Restart the remote side; this is an extended protocol operation. */
4153
4154 void
4155 remote_target::extended_remote_restart ()
4156 {
4157 struct remote_state *rs = get_remote_state ();
4158
4159 /* Send the restart command; for reasons I don't understand the
4160 remote side really expects a number after the "R". */
4161 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4162 putpkt (rs->buf);
4163
4164 remote_fileio_reset ();
4165 }
4166 \f
4167 /* Clean up connection to a remote debugger. */
4168
4169 void
4170 remote_target::close ()
4171 {
4172 /* Make sure we leave stdin registered in the event loop. */
4173 terminal_ours ();
4174
4175 trace_reset_local_state ();
4176
4177 delete this;
4178 }
4179
4180 remote_target::~remote_target ()
4181 {
4182 struct remote_state *rs = get_remote_state ();
4183
4184 /* Check for NULL because we may get here with a partially
4185 constructed target/connection. */
4186 if (rs->remote_desc == nullptr)
4187 return;
4188
4189 serial_close (rs->remote_desc);
4190
4191 /* We are destroying the remote target, so we should discard
4192 everything of this target. */
4193 discard_pending_stop_replies_in_queue ();
4194
4195 if (rs->remote_async_inferior_event_token)
4196 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4197
4198 delete rs->notif_state;
4199 }
4200
4201 /* Query the remote side for the text, data and bss offsets. */
4202
4203 void
4204 remote_target::get_offsets ()
4205 {
4206 struct remote_state *rs = get_remote_state ();
4207 char *buf;
4208 char *ptr;
4209 int lose, num_segments = 0, do_sections, do_segments;
4210 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4211
4212 if (current_program_space->symfile_object_file == NULL)
4213 return;
4214
4215 putpkt ("qOffsets");
4216 getpkt (&rs->buf, 0);
4217 buf = rs->buf.data ();
4218
4219 if (buf[0] == '\000')
4220 return; /* Return silently. Stub doesn't support
4221 this command. */
4222 if (buf[0] == 'E')
4223 {
4224 warning (_("Remote failure reply: %s"), buf);
4225 return;
4226 }
4227
4228 /* Pick up each field in turn. This used to be done with scanf, but
4229 scanf will make trouble if CORE_ADDR size doesn't match
4230 conversion directives correctly. The following code will work
4231 with any size of CORE_ADDR. */
4232 text_addr = data_addr = bss_addr = 0;
4233 ptr = buf;
4234 lose = 0;
4235
4236 if (startswith (ptr, "Text="))
4237 {
4238 ptr += 5;
4239 /* Don't use strtol, could lose on big values. */
4240 while (*ptr && *ptr != ';')
4241 text_addr = (text_addr << 4) + fromhex (*ptr++);
4242
4243 if (startswith (ptr, ";Data="))
4244 {
4245 ptr += 6;
4246 while (*ptr && *ptr != ';')
4247 data_addr = (data_addr << 4) + fromhex (*ptr++);
4248 }
4249 else
4250 lose = 1;
4251
4252 if (!lose && startswith (ptr, ";Bss="))
4253 {
4254 ptr += 5;
4255 while (*ptr && *ptr != ';')
4256 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4257
4258 if (bss_addr != data_addr)
4259 warning (_("Target reported unsupported offsets: %s"), buf);
4260 }
4261 else
4262 lose = 1;
4263 }
4264 else if (startswith (ptr, "TextSeg="))
4265 {
4266 ptr += 8;
4267 /* Don't use strtol, could lose on big values. */
4268 while (*ptr && *ptr != ';')
4269 text_addr = (text_addr << 4) + fromhex (*ptr++);
4270 num_segments = 1;
4271
4272 if (startswith (ptr, ";DataSeg="))
4273 {
4274 ptr += 9;
4275 while (*ptr && *ptr != ';')
4276 data_addr = (data_addr << 4) + fromhex (*ptr++);
4277 num_segments++;
4278 }
4279 }
4280 else
4281 lose = 1;
4282
4283 if (lose)
4284 error (_("Malformed response to offset query, %s"), buf);
4285 else if (*ptr != '\0')
4286 warning (_("Target reported unsupported offsets: %s"), buf);
4287
4288 objfile *objf = current_program_space->symfile_object_file;
4289 section_offsets offs = objf->section_offsets;
4290
4291 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
4292 do_segments = (data != NULL);
4293 do_sections = num_segments == 0;
4294
4295 if (num_segments > 0)
4296 {
4297 segments[0] = text_addr;
4298 segments[1] = data_addr;
4299 }
4300 /* If we have two segments, we can still try to relocate everything
4301 by assuming that the .text and .data offsets apply to the whole
4302 text and data segments. Convert the offsets given in the packet
4303 to base addresses for symfile_map_offsets_to_segments. */
4304 else if (data != nullptr && data->segments.size () == 2)
4305 {
4306 segments[0] = data->segments[0].base + text_addr;
4307 segments[1] = data->segments[1].base + data_addr;
4308 num_segments = 2;
4309 }
4310 /* If the object file has only one segment, assume that it is text
4311 rather than data; main programs with no writable data are rare,
4312 but programs with no code are useless. Of course the code might
4313 have ended up in the data segment... to detect that we would need
4314 the permissions here. */
4315 else if (data && data->segments.size () == 1)
4316 {
4317 segments[0] = data->segments[0].base + text_addr;
4318 num_segments = 1;
4319 }
4320 /* There's no way to relocate by segment. */
4321 else
4322 do_segments = 0;
4323
4324 if (do_segments)
4325 {
4326 int ret = symfile_map_offsets_to_segments (objf->obfd,
4327 data.get (), offs,
4328 num_segments, segments);
4329
4330 if (ret == 0 && !do_sections)
4331 error (_("Can not handle qOffsets TextSeg "
4332 "response with this symbol file"));
4333
4334 if (ret > 0)
4335 do_sections = 0;
4336 }
4337
4338 if (do_sections)
4339 {
4340 offs[SECT_OFF_TEXT (objf)] = text_addr;
4341
4342 /* This is a temporary kludge to force data and bss to use the
4343 same offsets because that's what nlmconv does now. The real
4344 solution requires changes to the stub and remote.c that I
4345 don't have time to do right now. */
4346
4347 offs[SECT_OFF_DATA (objf)] = data_addr;
4348 offs[SECT_OFF_BSS (objf)] = data_addr;
4349 }
4350
4351 objfile_relocate (objf, offs);
4352 }
4353
4354 /* Send interrupt_sequence to remote target. */
4355
4356 void
4357 remote_target::send_interrupt_sequence ()
4358 {
4359 struct remote_state *rs = get_remote_state ();
4360
4361 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4362 remote_serial_write ("\x03", 1);
4363 else if (interrupt_sequence_mode == interrupt_sequence_break)
4364 serial_send_break (rs->remote_desc);
4365 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4366 {
4367 serial_send_break (rs->remote_desc);
4368 remote_serial_write ("g", 1);
4369 }
4370 else
4371 internal_error (__FILE__, __LINE__,
4372 _("Invalid value for interrupt_sequence_mode: %s."),
4373 interrupt_sequence_mode);
4374 }
4375
4376
4377 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4378 and extract the PTID. Returns NULL_PTID if not found. */
4379
4380 static ptid_t
4381 stop_reply_extract_thread (const char *stop_reply)
4382 {
4383 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4384 {
4385 const char *p;
4386
4387 /* Txx r:val ; r:val (...) */
4388 p = &stop_reply[3];
4389
4390 /* Look for "register" named "thread". */
4391 while (*p != '\0')
4392 {
4393 const char *p1;
4394
4395 p1 = strchr (p, ':');
4396 if (p1 == NULL)
4397 return null_ptid;
4398
4399 if (strncmp (p, "thread", p1 - p) == 0)
4400 return read_ptid (++p1, &p);
4401
4402 p1 = strchr (p, ';');
4403 if (p1 == NULL)
4404 return null_ptid;
4405 p1++;
4406
4407 p = p1;
4408 }
4409 }
4410
4411 return null_ptid;
4412 }
4413
4414 /* Determine the remote side's current thread. If we have a stop
4415 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4416 "thread" register we can extract the current thread from. If not,
4417 ask the remote which is the current thread with qC. The former
4418 method avoids a roundtrip. */
4419
4420 ptid_t
4421 remote_target::get_current_thread (const char *wait_status)
4422 {
4423 ptid_t ptid = null_ptid;
4424
4425 /* Note we don't use remote_parse_stop_reply as that makes use of
4426 the target architecture, which we haven't yet fully determined at
4427 this point. */
4428 if (wait_status != NULL)
4429 ptid = stop_reply_extract_thread (wait_status);
4430 if (ptid == null_ptid)
4431 ptid = remote_current_thread (inferior_ptid);
4432
4433 return ptid;
4434 }
4435
4436 /* Query the remote target for which is the current thread/process,
4437 add it to our tables, and update INFERIOR_PTID. The caller is
4438 responsible for setting the state such that the remote end is ready
4439 to return the current thread.
4440
4441 This function is called after handling the '?' or 'vRun' packets,
4442 whose response is a stop reply from which we can also try
4443 extracting the thread. If the target doesn't support the explicit
4444 qC query, we infer the current thread from that stop reply, passed
4445 in in WAIT_STATUS, which may be NULL.
4446
4447 The function returns pointer to the main thread of the inferior. */
4448
4449 thread_info *
4450 remote_target::add_current_inferior_and_thread (const char *wait_status)
4451 {
4452 struct remote_state *rs = get_remote_state ();
4453 bool fake_pid_p = false;
4454
4455 switch_to_no_thread ();
4456
4457 /* Now, if we have thread information, update the current thread's
4458 ptid. */
4459 ptid_t curr_ptid = get_current_thread (wait_status);
4460
4461 if (curr_ptid != null_ptid)
4462 {
4463 if (!remote_multi_process_p (rs))
4464 fake_pid_p = true;
4465 }
4466 else
4467 {
4468 /* Without this, some commands which require an active target
4469 (such as kill) won't work. This variable serves (at least)
4470 double duty as both the pid of the target process (if it has
4471 such), and as a flag indicating that a target is active. */
4472 curr_ptid = magic_null_ptid;
4473 fake_pid_p = true;
4474 }
4475
4476 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4477
4478 /* Add the main thread and switch to it. Don't try reading
4479 registers yet, since we haven't fetched the target description
4480 yet. */
4481 thread_info *tp = add_thread_silent (this, curr_ptid);
4482 switch_to_thread_no_regs (tp);
4483
4484 return tp;
4485 }
4486
4487 /* Print info about a thread that was found already stopped on
4488 connection. */
4489
4490 void
4491 remote_target::print_one_stopped_thread (thread_info *thread)
4492 {
4493 target_waitstatus ws;
4494
4495 /* If there is a pending waitstatus, use it. If there isn't it's because
4496 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4497 and process_initial_stop_replies decided it wasn't interesting to save
4498 and report to the core. */
4499 if (thread->has_pending_waitstatus ())
4500 {
4501 ws = thread->pending_waitstatus ();
4502 thread->clear_pending_waitstatus ();
4503 }
4504 else
4505 {
4506 ws.set_stopped (GDB_SIGNAL_0);
4507 }
4508
4509 switch_to_thread (thread);
4510 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4511 set_current_sal_from_frame (get_current_frame ());
4512
4513 /* For "info program". */
4514 set_last_target_status (this, thread->ptid, ws);
4515
4516 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4517 {
4518 enum gdb_signal sig = ws.sig ();
4519
4520 if (signal_print_state (sig))
4521 gdb::observers::signal_received.notify (sig);
4522 }
4523 gdb::observers::normal_stop.notify (NULL, 1);
4524 }
4525
4526 /* Process all initial stop replies the remote side sent in response
4527 to the ? packet. These indicate threads that were already stopped
4528 on initial connection. We mark these threads as stopped and print
4529 their current frame before giving the user the prompt. */
4530
4531 void
4532 remote_target::process_initial_stop_replies (int from_tty)
4533 {
4534 int pending_stop_replies = stop_reply_queue_length ();
4535 struct thread_info *selected = NULL;
4536 struct thread_info *lowest_stopped = NULL;
4537 struct thread_info *first = NULL;
4538
4539 /* This is only used when the target is non-stop. */
4540 gdb_assert (target_is_non_stop_p ());
4541
4542 /* Consume the initial pending events. */
4543 while (pending_stop_replies-- > 0)
4544 {
4545 ptid_t waiton_ptid = minus_one_ptid;
4546 ptid_t event_ptid;
4547 struct target_waitstatus ws;
4548 int ignore_event = 0;
4549
4550 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4551 if (remote_debug)
4552 print_target_wait_results (waiton_ptid, event_ptid, ws);
4553
4554 switch (ws.kind ())
4555 {
4556 case TARGET_WAITKIND_IGNORE:
4557 case TARGET_WAITKIND_NO_RESUMED:
4558 case TARGET_WAITKIND_SIGNALLED:
4559 case TARGET_WAITKIND_EXITED:
4560 /* We shouldn't see these, but if we do, just ignore. */
4561 remote_debug_printf ("event ignored");
4562 ignore_event = 1;
4563 break;
4564
4565 default:
4566 break;
4567 }
4568
4569 if (ignore_event)
4570 continue;
4571
4572 thread_info *evthread = find_thread_ptid (this, event_ptid);
4573
4574 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4575 {
4576 enum gdb_signal sig = ws.sig ();
4577
4578 /* Stubs traditionally report SIGTRAP as initial signal,
4579 instead of signal 0. Suppress it. */
4580 if (sig == GDB_SIGNAL_TRAP)
4581 sig = GDB_SIGNAL_0;
4582 evthread->set_stop_signal (sig);
4583 ws.set_stopped (sig);
4584 }
4585
4586 if (ws.kind () != TARGET_WAITKIND_STOPPED
4587 || ws.sig () != GDB_SIGNAL_0)
4588 evthread->set_pending_waitstatus (ws);
4589
4590 set_executing (this, event_ptid, false);
4591 set_running (this, event_ptid, false);
4592 get_remote_thread_info (evthread)->set_not_resumed ();
4593 }
4594
4595 /* "Notice" the new inferiors before anything related to
4596 registers/memory. */
4597 for (inferior *inf : all_non_exited_inferiors (this))
4598 {
4599 inf->needs_setup = 1;
4600
4601 if (non_stop)
4602 {
4603 thread_info *thread = any_live_thread_of_inferior (inf);
4604 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4605 from_tty);
4606 }
4607 }
4608
4609 /* If all-stop on top of non-stop, pause all threads. Note this
4610 records the threads' stop pc, so must be done after "noticing"
4611 the inferiors. */
4612 if (!non_stop)
4613 {
4614 {
4615 /* At this point, the remote target is not async. It needs to be for
4616 the poll in stop_all_threads to consider events from it, so enable
4617 it temporarily. */
4618 gdb_assert (!this->is_async_p ());
4619 SCOPE_EXIT { target_async (0); };
4620 target_async (1);
4621 stop_all_threads ();
4622 }
4623
4624 /* If all threads of an inferior were already stopped, we
4625 haven't setup the inferior yet. */
4626 for (inferior *inf : all_non_exited_inferiors (this))
4627 {
4628 if (inf->needs_setup)
4629 {
4630 thread_info *thread = any_live_thread_of_inferior (inf);
4631 switch_to_thread_no_regs (thread);
4632 setup_inferior (0);
4633 }
4634 }
4635 }
4636
4637 /* Now go over all threads that are stopped, and print their current
4638 frame. If all-stop, then if there's a signalled thread, pick
4639 that as current. */
4640 for (thread_info *thread : all_non_exited_threads (this))
4641 {
4642 if (first == NULL)
4643 first = thread;
4644
4645 if (!non_stop)
4646 thread->set_running (false);
4647 else if (thread->state != THREAD_STOPPED)
4648 continue;
4649
4650 if (selected == nullptr && thread->has_pending_waitstatus ())
4651 selected = thread;
4652
4653 if (lowest_stopped == NULL
4654 || thread->inf->num < lowest_stopped->inf->num
4655 || thread->per_inf_num < lowest_stopped->per_inf_num)
4656 lowest_stopped = thread;
4657
4658 if (non_stop)
4659 print_one_stopped_thread (thread);
4660 }
4661
4662 /* In all-stop, we only print the status of one thread, and leave
4663 others with their status pending. */
4664 if (!non_stop)
4665 {
4666 thread_info *thread = selected;
4667 if (thread == NULL)
4668 thread = lowest_stopped;
4669 if (thread == NULL)
4670 thread = first;
4671
4672 print_one_stopped_thread (thread);
4673 }
4674 }
4675
4676 /* Mark a remote_target as marking (by setting the starting_up flag within
4677 its remote_state) for the lifetime of this object. The reference count
4678 on the remote target is temporarily incremented, to prevent the target
4679 being deleted under our feet. */
4680
4681 struct scoped_mark_target_starting
4682 {
4683 /* Constructor, TARGET is the target to be marked as starting, its
4684 reference count will be incremented. */
4685 scoped_mark_target_starting (remote_target *target)
4686 : m_remote_target (target)
4687 {
4688 m_remote_target->incref ();
4689 remote_state *rs = m_remote_target->get_remote_state ();
4690 rs->starting_up = true;
4691 }
4692
4693 /* Destructor, mark the target being worked on as no longer starting, and
4694 decrement the reference count. */
4695 ~scoped_mark_target_starting ()
4696 {
4697 remote_state *rs = m_remote_target->get_remote_state ();
4698 rs->starting_up = false;
4699 decref_target (m_remote_target);
4700 }
4701
4702 private:
4703
4704 /* The target on which we are operating. */
4705 remote_target *m_remote_target;
4706 };
4707
4708 /* Helper for remote_target::start_remote, start the remote connection and
4709 sync state. Return true if everything goes OK, otherwise, return false.
4710 This function exists so that the scoped_restore created within it will
4711 expire before we return to remote_target::start_remote. */
4712
4713 bool
4714 remote_target::start_remote_1 (int from_tty, int extended_p)
4715 {
4716 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4717
4718 struct remote_state *rs = get_remote_state ();
4719 struct packet_config *noack_config;
4720
4721 /* Signal other parts that we're going through the initial setup,
4722 and so things may not be stable yet. E.g., we don't try to
4723 install tracepoints until we've relocated symbols. Also, a
4724 Ctrl-C before we're connected and synced up can't interrupt the
4725 target. Instead, it offers to drop the (potentially wedged)
4726 connection. */
4727 scoped_mark_target_starting target_is_starting (this);
4728
4729 QUIT;
4730
4731 if (interrupt_on_connect)
4732 send_interrupt_sequence ();
4733
4734 /* Ack any packet which the remote side has already sent. */
4735 remote_serial_write ("+", 1);
4736
4737 /* The first packet we send to the target is the optional "supported
4738 packets" request. If the target can answer this, it will tell us
4739 which later probes to skip. */
4740 remote_query_supported ();
4741
4742 /* If the stub wants to get a QAllow, compose one and send it. */
4743 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4744 set_permissions ();
4745
4746 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4747 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4748 as a reply to known packet. For packet "vFile:setfs:" it is an
4749 invalid reply and GDB would return error in
4750 remote_hostio_set_filesystem, making remote files access impossible.
4751 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4752 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4753 {
4754 const char v_mustreplyempty[] = "vMustReplyEmpty";
4755
4756 putpkt (v_mustreplyempty);
4757 getpkt (&rs->buf, 0);
4758 if (strcmp (rs->buf.data (), "OK") == 0)
4759 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4760 else if (strcmp (rs->buf.data (), "") != 0)
4761 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4762 rs->buf.data ());
4763 }
4764
4765 /* Next, we possibly activate noack mode.
4766
4767 If the QStartNoAckMode packet configuration is set to AUTO,
4768 enable noack mode if the stub reported a wish for it with
4769 qSupported.
4770
4771 If set to TRUE, then enable noack mode even if the stub didn't
4772 report it in qSupported. If the stub doesn't reply OK, the
4773 session ends with an error.
4774
4775 If FALSE, then don't activate noack mode, regardless of what the
4776 stub claimed should be the default with qSupported. */
4777
4778 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4779 if (packet_config_support (noack_config) != PACKET_DISABLE)
4780 {
4781 putpkt ("QStartNoAckMode");
4782 getpkt (&rs->buf, 0);
4783 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4784 rs->noack_mode = 1;
4785 }
4786
4787 if (extended_p)
4788 {
4789 /* Tell the remote that we are using the extended protocol. */
4790 putpkt ("!");
4791 getpkt (&rs->buf, 0);
4792 }
4793
4794 /* Let the target know which signals it is allowed to pass down to
4795 the program. */
4796 update_signals_program_target ();
4797
4798 /* Next, if the target can specify a description, read it. We do
4799 this before anything involving memory or registers. */
4800 target_find_description ();
4801
4802 /* Next, now that we know something about the target, update the
4803 address spaces in the program spaces. */
4804 update_address_spaces ();
4805
4806 /* On OSs where the list of libraries is global to all
4807 processes, we fetch them early. */
4808 if (gdbarch_has_global_solist (target_gdbarch ()))
4809 solib_add (NULL, from_tty, auto_solib_add);
4810
4811 if (target_is_non_stop_p ())
4812 {
4813 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4814 error (_("Non-stop mode requested, but remote "
4815 "does not support non-stop"));
4816
4817 putpkt ("QNonStop:1");
4818 getpkt (&rs->buf, 0);
4819
4820 if (strcmp (rs->buf.data (), "OK") != 0)
4821 error (_("Remote refused setting non-stop mode with: %s"),
4822 rs->buf.data ());
4823
4824 /* Find about threads and processes the stub is already
4825 controlling. We default to adding them in the running state.
4826 The '?' query below will then tell us about which threads are
4827 stopped. */
4828 this->update_thread_list ();
4829 }
4830 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4831 {
4832 /* Don't assume that the stub can operate in all-stop mode.
4833 Request it explicitly. */
4834 putpkt ("QNonStop:0");
4835 getpkt (&rs->buf, 0);
4836
4837 if (strcmp (rs->buf.data (), "OK") != 0)
4838 error (_("Remote refused setting all-stop mode with: %s"),
4839 rs->buf.data ());
4840 }
4841
4842 /* Upload TSVs regardless of whether the target is running or not. The
4843 remote stub, such as GDBserver, may have some predefined or builtin
4844 TSVs, even if the target is not running. */
4845 if (get_trace_status (current_trace_status ()) != -1)
4846 {
4847 struct uploaded_tsv *uploaded_tsvs = NULL;
4848
4849 upload_trace_state_variables (&uploaded_tsvs);
4850 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4851 }
4852
4853 /* Check whether the target is running now. */
4854 putpkt ("?");
4855 getpkt (&rs->buf, 0);
4856
4857 if (!target_is_non_stop_p ())
4858 {
4859 char *wait_status = NULL;
4860
4861 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4862 {
4863 if (!extended_p)
4864 error (_("The target is not running (try extended-remote?)"));
4865 return false;
4866 }
4867 else
4868 {
4869 /* Save the reply for later. */
4870 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4871 strcpy (wait_status, rs->buf.data ());
4872 }
4873
4874 /* Fetch thread list. */
4875 target_update_thread_list ();
4876
4877 /* Let the stub know that we want it to return the thread. */
4878 set_continue_thread (minus_one_ptid);
4879
4880 if (thread_count (this) == 0)
4881 {
4882 /* Target has no concept of threads at all. GDB treats
4883 non-threaded target as single-threaded; add a main
4884 thread. */
4885 thread_info *tp = add_current_inferior_and_thread (wait_status);
4886 get_remote_thread_info (tp)->set_resumed ();
4887 }
4888 else
4889 {
4890 /* We have thread information; select the thread the target
4891 says should be current. If we're reconnecting to a
4892 multi-threaded program, this will ideally be the thread
4893 that last reported an event before GDB disconnected. */
4894 ptid_t curr_thread = get_current_thread (wait_status);
4895 if (curr_thread == null_ptid)
4896 {
4897 /* Odd... The target was able to list threads, but not
4898 tell us which thread was current (no "thread"
4899 register in T stop reply?). Just pick the first
4900 thread in the thread list then. */
4901
4902 remote_debug_printf ("warning: couldn't determine remote "
4903 "current thread; picking first in list.");
4904
4905 for (thread_info *tp : all_non_exited_threads (this,
4906 minus_one_ptid))
4907 {
4908 switch_to_thread (tp);
4909 break;
4910 }
4911 }
4912 else
4913 switch_to_thread (find_thread_ptid (this, curr_thread));
4914 }
4915
4916 /* init_wait_for_inferior should be called before get_offsets in order
4917 to manage `inserted' flag in bp loc in a correct state.
4918 breakpoint_init_inferior, called from init_wait_for_inferior, set
4919 `inserted' flag to 0, while before breakpoint_re_set, called from
4920 start_remote, set `inserted' flag to 1. In the initialization of
4921 inferior, breakpoint_init_inferior should be called first, and then
4922 breakpoint_re_set can be called. If this order is broken, state of
4923 `inserted' flag is wrong, and cause some problems on breakpoint
4924 manipulation. */
4925 init_wait_for_inferior ();
4926
4927 get_offsets (); /* Get text, data & bss offsets. */
4928
4929 /* If we could not find a description using qXfer, and we know
4930 how to do it some other way, try again. This is not
4931 supported for non-stop; it could be, but it is tricky if
4932 there are no stopped threads when we connect. */
4933 if (remote_read_description_p (this)
4934 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4935 {
4936 target_clear_description ();
4937 target_find_description ();
4938 }
4939
4940 /* Use the previously fetched status. */
4941 gdb_assert (wait_status != NULL);
4942 strcpy (rs->buf.data (), wait_status);
4943 rs->cached_wait_status = 1;
4944
4945 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4946 }
4947 else
4948 {
4949 /* Clear WFI global state. Do this before finding about new
4950 threads and inferiors, and setting the current inferior.
4951 Otherwise we would clear the proceed status of the current
4952 inferior when we want its stop_soon state to be preserved
4953 (see notice_new_inferior). */
4954 init_wait_for_inferior ();
4955
4956 /* In non-stop, we will either get an "OK", meaning that there
4957 are no stopped threads at this time; or, a regular stop
4958 reply. In the latter case, there may be more than one thread
4959 stopped --- we pull them all out using the vStopped
4960 mechanism. */
4961 if (strcmp (rs->buf.data (), "OK") != 0)
4962 {
4963 struct notif_client *notif = &notif_client_stop;
4964
4965 /* remote_notif_get_pending_replies acks this one, and gets
4966 the rest out. */
4967 rs->notif_state->pending_event[notif_client_stop.id]
4968 = remote_notif_parse (this, notif, rs->buf.data ());
4969 remote_notif_get_pending_events (notif);
4970 }
4971
4972 if (thread_count (this) == 0)
4973 {
4974 if (!extended_p)
4975 error (_("The target is not running (try extended-remote?)"));
4976 return false;
4977 }
4978
4979 /* Report all signals during attach/startup. */
4980 pass_signals ({});
4981
4982 /* If there are already stopped threads, mark them stopped and
4983 report their stops before giving the prompt to the user. */
4984 process_initial_stop_replies (from_tty);
4985
4986 if (target_can_async_p ())
4987 target_async (1);
4988 }
4989
4990 /* If we connected to a live target, do some additional setup. */
4991 if (target_has_execution ())
4992 {
4993 /* No use without a symbol-file. */
4994 if (current_program_space->symfile_object_file)
4995 remote_check_symbols ();
4996 }
4997
4998 /* Possibly the target has been engaged in a trace run started
4999 previously; find out where things are at. */
5000 if (get_trace_status (current_trace_status ()) != -1)
5001 {
5002 struct uploaded_tp *uploaded_tps = NULL;
5003
5004 if (current_trace_status ()->running)
5005 printf_filtered (_("Trace is already running on the target.\n"));
5006
5007 upload_tracepoints (&uploaded_tps);
5008
5009 merge_uploaded_tracepoints (&uploaded_tps);
5010 }
5011
5012 /* Possibly the target has been engaged in a btrace record started
5013 previously; find out where things are at. */
5014 remote_btrace_maybe_reopen ();
5015
5016 return true;
5017 }
5018
5019 /* Start the remote connection and sync state. */
5020
5021 void
5022 remote_target::start_remote (int from_tty, int extended_p)
5023 {
5024 if (start_remote_1 (from_tty, extended_p)
5025 && breakpoints_should_be_inserted_now ())
5026 insert_breakpoints ();
5027 }
5028
5029 const char *
5030 remote_target::connection_string ()
5031 {
5032 remote_state *rs = get_remote_state ();
5033
5034 if (rs->remote_desc->name != NULL)
5035 return rs->remote_desc->name;
5036 else
5037 return NULL;
5038 }
5039
5040 /* Open a connection to a remote debugger.
5041 NAME is the filename used for communication. */
5042
5043 void
5044 remote_target::open (const char *name, int from_tty)
5045 {
5046 open_1 (name, from_tty, 0);
5047 }
5048
5049 /* Open a connection to a remote debugger using the extended
5050 remote gdb protocol. NAME is the filename used for communication. */
5051
5052 void
5053 extended_remote_target::open (const char *name, int from_tty)
5054 {
5055 open_1 (name, from_tty, 1 /*extended_p */);
5056 }
5057
5058 /* Reset all packets back to "unknown support". Called when opening a
5059 new connection to a remote target. */
5060
5061 static void
5062 reset_all_packet_configs_support (void)
5063 {
5064 int i;
5065
5066 for (i = 0; i < PACKET_MAX; i++)
5067 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5068 }
5069
5070 /* Initialize all packet configs. */
5071
5072 static void
5073 init_all_packet_configs (void)
5074 {
5075 int i;
5076
5077 for (i = 0; i < PACKET_MAX; i++)
5078 {
5079 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5080 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5081 }
5082 }
5083
5084 /* Symbol look-up. */
5085
5086 void
5087 remote_target::remote_check_symbols ()
5088 {
5089 char *tmp;
5090 int end;
5091
5092 /* The remote side has no concept of inferiors that aren't running
5093 yet, it only knows about running processes. If we're connected
5094 but our current inferior is not running, we should not invite the
5095 remote target to request symbol lookups related to its
5096 (unrelated) current process. */
5097 if (!target_has_execution ())
5098 return;
5099
5100 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5101 return;
5102
5103 /* Make sure the remote is pointing at the right process. Note
5104 there's no way to select "no process". */
5105 set_general_process ();
5106
5107 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5108 because we need both at the same time. */
5109 gdb::char_vector msg (get_remote_packet_size ());
5110 gdb::char_vector reply (get_remote_packet_size ());
5111
5112 /* Invite target to request symbol lookups. */
5113
5114 putpkt ("qSymbol::");
5115 getpkt (&reply, 0);
5116 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5117
5118 while (startswith (reply.data (), "qSymbol:"))
5119 {
5120 struct bound_minimal_symbol sym;
5121
5122 tmp = &reply[8];
5123 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5124 strlen (tmp) / 2);
5125 msg[end] = '\0';
5126 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5127 if (sym.minsym == NULL)
5128 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5129 &reply[8]);
5130 else
5131 {
5132 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5133 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
5134
5135 /* If this is a function address, return the start of code
5136 instead of any data function descriptor. */
5137 sym_addr = gdbarch_convert_from_func_ptr_addr
5138 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5139
5140 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5141 phex_nz (sym_addr, addr_size), &reply[8]);
5142 }
5143
5144 putpkt (msg.data ());
5145 getpkt (&reply, 0);
5146 }
5147 }
5148
5149 static struct serial *
5150 remote_serial_open (const char *name)
5151 {
5152 static int udp_warning = 0;
5153
5154 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5155 of in ser-tcp.c, because it is the remote protocol assuming that the
5156 serial connection is reliable and not the serial connection promising
5157 to be. */
5158 if (!udp_warning && startswith (name, "udp:"))
5159 {
5160 warning (_("The remote protocol may be unreliable over UDP.\n"
5161 "Some events may be lost, rendering further debugging "
5162 "impossible."));
5163 udp_warning = 1;
5164 }
5165
5166 return serial_open (name);
5167 }
5168
5169 /* Inform the target of our permission settings. The permission flags
5170 work without this, but if the target knows the settings, it can do
5171 a couple things. First, it can add its own check, to catch cases
5172 that somehow manage to get by the permissions checks in target
5173 methods. Second, if the target is wired to disallow particular
5174 settings (for instance, a system in the field that is not set up to
5175 be able to stop at a breakpoint), it can object to any unavailable
5176 permissions. */
5177
5178 void
5179 remote_target::set_permissions ()
5180 {
5181 struct remote_state *rs = get_remote_state ();
5182
5183 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5184 "WriteReg:%x;WriteMem:%x;"
5185 "InsertBreak:%x;InsertTrace:%x;"
5186 "InsertFastTrace:%x;Stop:%x",
5187 may_write_registers, may_write_memory,
5188 may_insert_breakpoints, may_insert_tracepoints,
5189 may_insert_fast_tracepoints, may_stop);
5190 putpkt (rs->buf);
5191 getpkt (&rs->buf, 0);
5192
5193 /* If the target didn't like the packet, warn the user. Do not try
5194 to undo the user's settings, that would just be maddening. */
5195 if (strcmp (rs->buf.data (), "OK") != 0)
5196 warning (_("Remote refused setting permissions with: %s"),
5197 rs->buf.data ());
5198 }
5199
5200 /* This type describes each known response to the qSupported
5201 packet. */
5202 struct protocol_feature
5203 {
5204 /* The name of this protocol feature. */
5205 const char *name;
5206
5207 /* The default for this protocol feature. */
5208 enum packet_support default_support;
5209
5210 /* The function to call when this feature is reported, or after
5211 qSupported processing if the feature is not supported.
5212 The first argument points to this structure. The second
5213 argument indicates whether the packet requested support be
5214 enabled, disabled, or probed (or the default, if this function
5215 is being called at the end of processing and this feature was
5216 not reported). The third argument may be NULL; if not NULL, it
5217 is a NUL-terminated string taken from the packet following
5218 this feature's name and an equals sign. */
5219 void (*func) (remote_target *remote, const struct protocol_feature *,
5220 enum packet_support, const char *);
5221
5222 /* The corresponding packet for this feature. Only used if
5223 FUNC is remote_supported_packet. */
5224 int packet;
5225 };
5226
5227 static void
5228 remote_supported_packet (remote_target *remote,
5229 const struct protocol_feature *feature,
5230 enum packet_support support,
5231 const char *argument)
5232 {
5233 if (argument)
5234 {
5235 warning (_("Remote qSupported response supplied an unexpected value for"
5236 " \"%s\"."), feature->name);
5237 return;
5238 }
5239
5240 remote_protocol_packets[feature->packet].support = support;
5241 }
5242
5243 void
5244 remote_target::remote_packet_size (const protocol_feature *feature,
5245 enum packet_support support, const char *value)
5246 {
5247 struct remote_state *rs = get_remote_state ();
5248
5249 int packet_size;
5250 char *value_end;
5251
5252 if (support != PACKET_ENABLE)
5253 return;
5254
5255 if (value == NULL || *value == '\0')
5256 {
5257 warning (_("Remote target reported \"%s\" without a size."),
5258 feature->name);
5259 return;
5260 }
5261
5262 errno = 0;
5263 packet_size = strtol (value, &value_end, 16);
5264 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5265 {
5266 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5267 feature->name, value);
5268 return;
5269 }
5270
5271 /* Record the new maximum packet size. */
5272 rs->explicit_packet_size = packet_size;
5273 }
5274
5275 static void
5276 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5277 enum packet_support support, const char *value)
5278 {
5279 remote->remote_packet_size (feature, support, value);
5280 }
5281
5282 static const struct protocol_feature remote_protocol_features[] = {
5283 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5284 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5285 PACKET_qXfer_auxv },
5286 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5287 PACKET_qXfer_exec_file },
5288 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5289 PACKET_qXfer_features },
5290 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5291 PACKET_qXfer_libraries },
5292 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5293 PACKET_qXfer_libraries_svr4 },
5294 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5295 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5296 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5297 PACKET_qXfer_memory_map },
5298 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5299 PACKET_qXfer_osdata },
5300 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5301 PACKET_qXfer_threads },
5302 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5303 PACKET_qXfer_traceframe_info },
5304 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5305 PACKET_QPassSignals },
5306 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5307 PACKET_QCatchSyscalls },
5308 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5309 PACKET_QProgramSignals },
5310 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5311 PACKET_QSetWorkingDir },
5312 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5313 PACKET_QStartupWithShell },
5314 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5315 PACKET_QEnvironmentHexEncoded },
5316 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5317 PACKET_QEnvironmentReset },
5318 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5319 PACKET_QEnvironmentUnset },
5320 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5321 PACKET_QStartNoAckMode },
5322 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5323 PACKET_multiprocess_feature },
5324 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5325 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5326 PACKET_qXfer_siginfo_read },
5327 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5328 PACKET_qXfer_siginfo_write },
5329 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5330 PACKET_ConditionalTracepoints },
5331 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5332 PACKET_ConditionalBreakpoints },
5333 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5334 PACKET_BreakpointCommands },
5335 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5336 PACKET_FastTracepoints },
5337 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5338 PACKET_StaticTracepoints },
5339 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5340 PACKET_InstallInTrace},
5341 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5342 PACKET_DisconnectedTracing_feature },
5343 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5344 PACKET_bc },
5345 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5346 PACKET_bs },
5347 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5348 PACKET_TracepointSource },
5349 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5350 PACKET_QAllow },
5351 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5352 PACKET_EnableDisableTracepoints_feature },
5353 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5354 PACKET_qXfer_fdpic },
5355 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5356 PACKET_qXfer_uib },
5357 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5358 PACKET_QDisableRandomization },
5359 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5360 { "QTBuffer:size", PACKET_DISABLE,
5361 remote_supported_packet, PACKET_QTBuffer_size},
5362 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5363 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5364 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5365 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5366 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5367 PACKET_qXfer_btrace },
5368 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5369 PACKET_qXfer_btrace_conf },
5370 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5371 PACKET_Qbtrace_conf_bts_size },
5372 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5373 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5374 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5375 PACKET_fork_event_feature },
5376 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5377 PACKET_vfork_event_feature },
5378 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5379 PACKET_exec_event_feature },
5380 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5381 PACKET_Qbtrace_conf_pt_size },
5382 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5383 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5384 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5385 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5386 PACKET_memory_tagging_feature },
5387 };
5388
5389 static char *remote_support_xml;
5390
5391 /* Register string appended to "xmlRegisters=" in qSupported query. */
5392
5393 void
5394 register_remote_support_xml (const char *xml)
5395 {
5396 #if defined(HAVE_LIBEXPAT)
5397 if (remote_support_xml == NULL)
5398 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5399 else
5400 {
5401 char *copy = xstrdup (remote_support_xml + 13);
5402 char *saveptr;
5403 char *p = strtok_r (copy, ",", &saveptr);
5404
5405 do
5406 {
5407 if (strcmp (p, xml) == 0)
5408 {
5409 /* already there */
5410 xfree (copy);
5411 return;
5412 }
5413 }
5414 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5415 xfree (copy);
5416
5417 remote_support_xml = reconcat (remote_support_xml,
5418 remote_support_xml, ",", xml,
5419 (char *) NULL);
5420 }
5421 #endif
5422 }
5423
5424 static void
5425 remote_query_supported_append (std::string *msg, const char *append)
5426 {
5427 if (!msg->empty ())
5428 msg->append (";");
5429 msg->append (append);
5430 }
5431
5432 void
5433 remote_target::remote_query_supported ()
5434 {
5435 struct remote_state *rs = get_remote_state ();
5436 char *next;
5437 int i;
5438 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5439
5440 /* The packet support flags are handled differently for this packet
5441 than for most others. We treat an error, a disabled packet, and
5442 an empty response identically: any features which must be reported
5443 to be used will be automatically disabled. An empty buffer
5444 accomplishes this, since that is also the representation for a list
5445 containing no features. */
5446
5447 rs->buf[0] = 0;
5448 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5449 {
5450 std::string q;
5451
5452 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5453 remote_query_supported_append (&q, "multiprocess+");
5454
5455 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5456 remote_query_supported_append (&q, "swbreak+");
5457 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5458 remote_query_supported_append (&q, "hwbreak+");
5459
5460 remote_query_supported_append (&q, "qRelocInsn+");
5461
5462 if (packet_set_cmd_state (PACKET_fork_event_feature)
5463 != AUTO_BOOLEAN_FALSE)
5464 remote_query_supported_append (&q, "fork-events+");
5465 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5466 != AUTO_BOOLEAN_FALSE)
5467 remote_query_supported_append (&q, "vfork-events+");
5468 if (packet_set_cmd_state (PACKET_exec_event_feature)
5469 != AUTO_BOOLEAN_FALSE)
5470 remote_query_supported_append (&q, "exec-events+");
5471
5472 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5473 remote_query_supported_append (&q, "vContSupported+");
5474
5475 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5476 remote_query_supported_append (&q, "QThreadEvents+");
5477
5478 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5479 remote_query_supported_append (&q, "no-resumed+");
5480
5481 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5482 != AUTO_BOOLEAN_FALSE)
5483 remote_query_supported_append (&q, "memory-tagging+");
5484
5485 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5486 the qSupported:xmlRegisters=i386 handling. */
5487 if (remote_support_xml != NULL
5488 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5489 remote_query_supported_append (&q, remote_support_xml);
5490
5491 q = "qSupported:" + q;
5492 putpkt (q.c_str ());
5493
5494 getpkt (&rs->buf, 0);
5495
5496 /* If an error occured, warn, but do not return - just reset the
5497 buffer to empty and go on to disable features. */
5498 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5499 == PACKET_ERROR)
5500 {
5501 warning (_("Remote failure reply: %s"), rs->buf.data ());
5502 rs->buf[0] = 0;
5503 }
5504 }
5505
5506 memset (seen, 0, sizeof (seen));
5507
5508 next = rs->buf.data ();
5509 while (*next)
5510 {
5511 enum packet_support is_supported;
5512 char *p, *end, *name_end, *value;
5513
5514 /* First separate out this item from the rest of the packet. If
5515 there's another item after this, we overwrite the separator
5516 (terminated strings are much easier to work with). */
5517 p = next;
5518 end = strchr (p, ';');
5519 if (end == NULL)
5520 {
5521 end = p + strlen (p);
5522 next = end;
5523 }
5524 else
5525 {
5526 *end = '\0';
5527 next = end + 1;
5528
5529 if (end == p)
5530 {
5531 warning (_("empty item in \"qSupported\" response"));
5532 continue;
5533 }
5534 }
5535
5536 name_end = strchr (p, '=');
5537 if (name_end)
5538 {
5539 /* This is a name=value entry. */
5540 is_supported = PACKET_ENABLE;
5541 value = name_end + 1;
5542 *name_end = '\0';
5543 }
5544 else
5545 {
5546 value = NULL;
5547 switch (end[-1])
5548 {
5549 case '+':
5550 is_supported = PACKET_ENABLE;
5551 break;
5552
5553 case '-':
5554 is_supported = PACKET_DISABLE;
5555 break;
5556
5557 case '?':
5558 is_supported = PACKET_SUPPORT_UNKNOWN;
5559 break;
5560
5561 default:
5562 warning (_("unrecognized item \"%s\" "
5563 "in \"qSupported\" response"), p);
5564 continue;
5565 }
5566 end[-1] = '\0';
5567 }
5568
5569 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5570 if (strcmp (remote_protocol_features[i].name, p) == 0)
5571 {
5572 const struct protocol_feature *feature;
5573
5574 seen[i] = 1;
5575 feature = &remote_protocol_features[i];
5576 feature->func (this, feature, is_supported, value);
5577 break;
5578 }
5579 }
5580
5581 /* If we increased the packet size, make sure to increase the global
5582 buffer size also. We delay this until after parsing the entire
5583 qSupported packet, because this is the same buffer we were
5584 parsing. */
5585 if (rs->buf.size () < rs->explicit_packet_size)
5586 rs->buf.resize (rs->explicit_packet_size);
5587
5588 /* Handle the defaults for unmentioned features. */
5589 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5590 if (!seen[i])
5591 {
5592 const struct protocol_feature *feature;
5593
5594 feature = &remote_protocol_features[i];
5595 feature->func (this, feature, feature->default_support, NULL);
5596 }
5597 }
5598
5599 /* Serial QUIT handler for the remote serial descriptor.
5600
5601 Defers handling a Ctrl-C until we're done with the current
5602 command/response packet sequence, unless:
5603
5604 - We're setting up the connection. Don't send a remote interrupt
5605 request, as we're not fully synced yet. Quit immediately
5606 instead.
5607
5608 - The target has been resumed in the foreground
5609 (target_terminal::is_ours is false) with a synchronous resume
5610 packet, and we're blocked waiting for the stop reply, thus a
5611 Ctrl-C should be immediately sent to the target.
5612
5613 - We get a second Ctrl-C while still within the same serial read or
5614 write. In that case the serial is seemingly wedged --- offer to
5615 quit/disconnect.
5616
5617 - We see a second Ctrl-C without target response, after having
5618 previously interrupted the target. In that case the target/stub
5619 is probably wedged --- offer to quit/disconnect.
5620 */
5621
5622 void
5623 remote_target::remote_serial_quit_handler ()
5624 {
5625 struct remote_state *rs = get_remote_state ();
5626
5627 if (check_quit_flag ())
5628 {
5629 /* If we're starting up, we're not fully synced yet. Quit
5630 immediately. */
5631 if (rs->starting_up)
5632 quit ();
5633 else if (rs->got_ctrlc_during_io)
5634 {
5635 if (query (_("The target is not responding to GDB commands.\n"
5636 "Stop debugging it? ")))
5637 remote_unpush_and_throw (this);
5638 }
5639 /* If ^C has already been sent once, offer to disconnect. */
5640 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5641 interrupt_query ();
5642 /* All-stop protocol, and blocked waiting for stop reply. Send
5643 an interrupt request. */
5644 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5645 target_interrupt ();
5646 else
5647 rs->got_ctrlc_during_io = 1;
5648 }
5649 }
5650
5651 /* The remote_target that is current while the quit handler is
5652 overridden with remote_serial_quit_handler. */
5653 static remote_target *curr_quit_handler_target;
5654
5655 static void
5656 remote_serial_quit_handler ()
5657 {
5658 curr_quit_handler_target->remote_serial_quit_handler ();
5659 }
5660
5661 /* Remove the remote target from the target stack of each inferior
5662 that is using it. Upper targets depend on it so remove them
5663 first. */
5664
5665 static void
5666 remote_unpush_target (remote_target *target)
5667 {
5668 /* We have to unpush the target from all inferiors, even those that
5669 aren't running. */
5670 scoped_restore_current_inferior restore_current_inferior;
5671
5672 for (inferior *inf : all_inferiors (target))
5673 {
5674 switch_to_inferior_no_thread (inf);
5675 pop_all_targets_at_and_above (process_stratum);
5676 generic_mourn_inferior ();
5677 }
5678
5679 /* Don't rely on target_close doing this when the target is popped
5680 from the last remote inferior above, because something may be
5681 holding a reference to the target higher up on the stack, meaning
5682 target_close won't be called yet. We lost the connection to the
5683 target, so clear these now, otherwise we may later throw
5684 TARGET_CLOSE_ERROR while trying to tell the remote target to
5685 close the file. */
5686 fileio_handles_invalidate_target (target);
5687 }
5688
5689 static void
5690 remote_unpush_and_throw (remote_target *target)
5691 {
5692 remote_unpush_target (target);
5693 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5694 }
5695
5696 void
5697 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5698 {
5699 remote_target *curr_remote = get_current_remote_target ();
5700
5701 if (name == 0)
5702 error (_("To open a remote debug connection, you need to specify what\n"
5703 "serial device is attached to the remote system\n"
5704 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5705
5706 /* If we're connected to a running target, target_preopen will kill it.
5707 Ask this question first, before target_preopen has a chance to kill
5708 anything. */
5709 if (curr_remote != NULL && !target_has_execution ())
5710 {
5711 if (from_tty
5712 && !query (_("Already connected to a remote target. Disconnect? ")))
5713 error (_("Still connected."));
5714 }
5715
5716 /* Here the possibly existing remote target gets unpushed. */
5717 target_preopen (from_tty);
5718
5719 remote_fileio_reset ();
5720 reopen_exec_file ();
5721 reread_symbols (from_tty);
5722
5723 remote_target *remote
5724 = (extended_p ? new extended_remote_target () : new remote_target ());
5725 target_ops_up target_holder (remote);
5726
5727 remote_state *rs = remote->get_remote_state ();
5728
5729 /* See FIXME above. */
5730 if (!target_async_permitted)
5731 rs->wait_forever_enabled_p = 1;
5732
5733 rs->remote_desc = remote_serial_open (name);
5734 if (!rs->remote_desc)
5735 perror_with_name (name);
5736
5737 if (baud_rate != -1)
5738 {
5739 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5740 {
5741 /* The requested speed could not be set. Error out to
5742 top level after closing remote_desc. Take care to
5743 set remote_desc to NULL to avoid closing remote_desc
5744 more than once. */
5745 serial_close (rs->remote_desc);
5746 rs->remote_desc = NULL;
5747 perror_with_name (name);
5748 }
5749 }
5750
5751 serial_setparity (rs->remote_desc, serial_parity);
5752 serial_raw (rs->remote_desc);
5753
5754 /* If there is something sitting in the buffer we might take it as a
5755 response to a command, which would be bad. */
5756 serial_flush_input (rs->remote_desc);
5757
5758 if (from_tty)
5759 {
5760 puts_filtered ("Remote debugging using ");
5761 puts_filtered (name);
5762 puts_filtered ("\n");
5763 }
5764
5765 /* Switch to using the remote target now. */
5766 current_inferior ()->push_target (std::move (target_holder));
5767
5768 /* Register extra event sources in the event loop. */
5769 rs->remote_async_inferior_event_token
5770 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5771 "remote");
5772 rs->notif_state = remote_notif_state_allocate (remote);
5773
5774 /* Reset the target state; these things will be queried either by
5775 remote_query_supported or as they are needed. */
5776 reset_all_packet_configs_support ();
5777 rs->cached_wait_status = 0;
5778 rs->explicit_packet_size = 0;
5779 rs->noack_mode = 0;
5780 rs->extended = extended_p;
5781 rs->waiting_for_stop_reply = 0;
5782 rs->ctrlc_pending_p = 0;
5783 rs->got_ctrlc_during_io = 0;
5784
5785 rs->general_thread = not_sent_ptid;
5786 rs->continue_thread = not_sent_ptid;
5787 rs->remote_traceframe_number = -1;
5788
5789 rs->last_resume_exec_dir = EXEC_FORWARD;
5790
5791 /* Probe for ability to use "ThreadInfo" query, as required. */
5792 rs->use_threadinfo_query = 1;
5793 rs->use_threadextra_query = 1;
5794
5795 rs->readahead_cache.invalidate ();
5796
5797 if (target_async_permitted)
5798 {
5799 /* FIXME: cagney/1999-09-23: During the initial connection it is
5800 assumed that the target is already ready and able to respond to
5801 requests. Unfortunately remote_start_remote() eventually calls
5802 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5803 around this. Eventually a mechanism that allows
5804 wait_for_inferior() to expect/get timeouts will be
5805 implemented. */
5806 rs->wait_forever_enabled_p = 0;
5807 }
5808
5809 /* First delete any symbols previously loaded from shared libraries. */
5810 no_shared_libraries (NULL, 0);
5811
5812 /* Start the remote connection. If error() or QUIT, discard this
5813 target (we'd otherwise be in an inconsistent state) and then
5814 propogate the error on up the exception chain. This ensures that
5815 the caller doesn't stumble along blindly assuming that the
5816 function succeeded. The CLI doesn't have this problem but other
5817 UI's, such as MI do.
5818
5819 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5820 this function should return an error indication letting the
5821 caller restore the previous state. Unfortunately the command
5822 ``target remote'' is directly wired to this function making that
5823 impossible. On a positive note, the CLI side of this problem has
5824 been fixed - the function set_cmd_context() makes it possible for
5825 all the ``target ....'' commands to share a common callback
5826 function. See cli-dump.c. */
5827 {
5828
5829 try
5830 {
5831 remote->start_remote (from_tty, extended_p);
5832 }
5833 catch (const gdb_exception &ex)
5834 {
5835 /* Pop the partially set up target - unless something else did
5836 already before throwing the exception. */
5837 if (ex.error != TARGET_CLOSE_ERROR)
5838 remote_unpush_target (remote);
5839 throw;
5840 }
5841 }
5842
5843 remote_btrace_reset (rs);
5844
5845 if (target_async_permitted)
5846 rs->wait_forever_enabled_p = 1;
5847 }
5848
5849 /* Detach the specified process. */
5850
5851 void
5852 remote_target::remote_detach_pid (int pid)
5853 {
5854 struct remote_state *rs = get_remote_state ();
5855
5856 /* This should not be necessary, but the handling for D;PID in
5857 GDBserver versions prior to 8.2 incorrectly assumes that the
5858 selected process points to the same process we're detaching,
5859 leading to misbehavior (and possibly GDBserver crashing) when it
5860 does not. Since it's easy and cheap, work around it by forcing
5861 GDBserver to select GDB's current process. */
5862 set_general_process ();
5863
5864 if (remote_multi_process_p (rs))
5865 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5866 else
5867 strcpy (rs->buf.data (), "D");
5868
5869 putpkt (rs->buf);
5870 getpkt (&rs->buf, 0);
5871
5872 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5873 ;
5874 else if (rs->buf[0] == '\0')
5875 error (_("Remote doesn't know how to detach"));
5876 else
5877 error (_("Can't detach process."));
5878 }
5879
5880 /* This detaches a program to which we previously attached, using
5881 inferior_ptid to identify the process. After this is done, GDB
5882 can be used to debug some other program. We better not have left
5883 any breakpoints in the target program or it'll die when it hits
5884 one. */
5885
5886 void
5887 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5888 {
5889 int pid = inferior_ptid.pid ();
5890 struct remote_state *rs = get_remote_state ();
5891 int is_fork_parent;
5892
5893 if (!target_has_execution ())
5894 error (_("No process to detach from."));
5895
5896 target_announce_detach (from_tty);
5897
5898 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5899 {
5900 /* If we're in breakpoints-always-inserted mode, or the inferior
5901 is running, we have to remove breakpoints before detaching.
5902 We don't do this in common code instead because not all
5903 targets support removing breakpoints while the target is
5904 running. The remote target / gdbserver does, though. */
5905 remove_breakpoints_inf (current_inferior ());
5906 }
5907
5908 /* Tell the remote target to detach. */
5909 remote_detach_pid (pid);
5910
5911 /* Exit only if this is the only active inferior. */
5912 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5913 puts_filtered (_("Ending remote debugging.\n"));
5914
5915 thread_info *tp = find_thread_ptid (this, inferior_ptid);
5916
5917 /* Check to see if we are detaching a fork parent. Note that if we
5918 are detaching a fork child, tp == NULL. */
5919 is_fork_parent = (tp != NULL
5920 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
5921
5922 /* If doing detach-on-fork, we don't mourn, because that will delete
5923 breakpoints that should be available for the followed inferior. */
5924 if (!is_fork_parent)
5925 {
5926 /* Save the pid as a string before mourning, since that will
5927 unpush the remote target, and we need the string after. */
5928 std::string infpid = target_pid_to_str (ptid_t (pid));
5929
5930 target_mourn_inferior (inferior_ptid);
5931 if (print_inferior_events)
5932 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5933 inf->num, infpid.c_str ());
5934 }
5935 else
5936 {
5937 switch_to_no_thread ();
5938 detach_inferior (current_inferior ());
5939 }
5940 }
5941
5942 void
5943 remote_target::detach (inferior *inf, int from_tty)
5944 {
5945 remote_detach_1 (inf, from_tty);
5946 }
5947
5948 void
5949 extended_remote_target::detach (inferior *inf, int from_tty)
5950 {
5951 remote_detach_1 (inf, from_tty);
5952 }
5953
5954 /* Target follow-fork function for remote targets. On entry, and
5955 at return, the current inferior is the fork parent.
5956
5957 Note that although this is currently only used for extended-remote,
5958 it is named remote_follow_fork in anticipation of using it for the
5959 remote target as well. */
5960
5961 void
5962 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
5963 target_waitkind fork_kind, bool follow_child,
5964 bool detach_fork)
5965 {
5966 process_stratum_target::follow_fork (child_inf, child_ptid,
5967 fork_kind, follow_child, detach_fork);
5968
5969 struct remote_state *rs = get_remote_state ();
5970
5971 if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5972 || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5973 {
5974 /* When following the parent and detaching the child, we detach
5975 the child here. For the case of following the child and
5976 detaching the parent, the detach is done in the target-
5977 independent follow fork code in infrun.c. We can't use
5978 target_detach when detaching an unfollowed child because
5979 the client side doesn't know anything about the child. */
5980 if (detach_fork && !follow_child)
5981 {
5982 /* Detach the fork child. */
5983 remote_detach_pid (child_ptid.pid ());
5984 }
5985 }
5986 }
5987
5988 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5989 in the program space of the new inferior. */
5990
5991 void
5992 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
5993 const char *execd_pathname)
5994 {
5995 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
5996
5997 /* We know that this is a target file name, so if it has the "target:"
5998 prefix we strip it off before saving it in the program space. */
5999 if (is_target_filename (execd_pathname))
6000 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6001
6002 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6003 }
6004
6005 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6006
6007 void
6008 remote_target::disconnect (const char *args, int from_tty)
6009 {
6010 if (args)
6011 error (_("Argument given to \"disconnect\" when remotely debugging."));
6012
6013 /* Make sure we unpush even the extended remote targets. Calling
6014 target_mourn_inferior won't unpush, and
6015 remote_target::mourn_inferior won't unpush if there is more than
6016 one inferior left. */
6017 remote_unpush_target (this);
6018
6019 if (from_tty)
6020 puts_filtered ("Ending remote debugging.\n");
6021 }
6022
6023 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6024 be chatty about it. */
6025
6026 void
6027 extended_remote_target::attach (const char *args, int from_tty)
6028 {
6029 struct remote_state *rs = get_remote_state ();
6030 int pid;
6031 char *wait_status = NULL;
6032
6033 pid = parse_pid_to_attach (args);
6034
6035 /* Remote PID can be freely equal to getpid, do not check it here the same
6036 way as in other targets. */
6037
6038 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
6039 error (_("This target does not support attaching to a process"));
6040
6041 if (from_tty)
6042 {
6043 const char *exec_file = get_exec_file (0);
6044
6045 if (exec_file)
6046 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
6047 target_pid_to_str (ptid_t (pid)).c_str ());
6048 else
6049 printf_unfiltered (_("Attaching to %s\n"),
6050 target_pid_to_str (ptid_t (pid)).c_str ());
6051 }
6052
6053 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6054 putpkt (rs->buf);
6055 getpkt (&rs->buf, 0);
6056
6057 switch (packet_ok (rs->buf,
6058 &remote_protocol_packets[PACKET_vAttach]))
6059 {
6060 case PACKET_OK:
6061 if (!target_is_non_stop_p ())
6062 {
6063 /* Save the reply for later. */
6064 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6065 strcpy (wait_status, rs->buf.data ());
6066 }
6067 else if (strcmp (rs->buf.data (), "OK") != 0)
6068 error (_("Attaching to %s failed with: %s"),
6069 target_pid_to_str (ptid_t (pid)).c_str (),
6070 rs->buf.data ());
6071 break;
6072 case PACKET_UNKNOWN:
6073 error (_("This target does not support attaching to a process"));
6074 default:
6075 error (_("Attaching to %s failed"),
6076 target_pid_to_str (ptid_t (pid)).c_str ());
6077 }
6078
6079 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6080
6081 inferior_ptid = ptid_t (pid);
6082
6083 if (target_is_non_stop_p ())
6084 {
6085 /* Get list of threads. */
6086 update_thread_list ();
6087
6088 thread_info *thread = first_thread_of_inferior (current_inferior ());
6089 if (thread != nullptr)
6090 switch_to_thread (thread);
6091
6092 /* Invalidate our notion of the remote current thread. */
6093 record_currthread (rs, minus_one_ptid);
6094 }
6095 else
6096 {
6097 /* Now, if we have thread information, update the main thread's
6098 ptid. */
6099 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6100
6101 /* Add the main thread to the thread list. */
6102 thread_info *thr = add_thread_silent (this, curr_ptid);
6103
6104 switch_to_thread (thr);
6105
6106 /* Don't consider the thread stopped until we've processed the
6107 saved stop reply. */
6108 set_executing (this, thr->ptid, true);
6109 }
6110
6111 /* Next, if the target can specify a description, read it. We do
6112 this before anything involving memory or registers. */
6113 target_find_description ();
6114
6115 if (!target_is_non_stop_p ())
6116 {
6117 /* Use the previously fetched status. */
6118 gdb_assert (wait_status != NULL);
6119
6120 if (target_can_async_p ())
6121 {
6122 struct notif_event *reply
6123 = remote_notif_parse (this, &notif_client_stop, wait_status);
6124
6125 push_stop_reply ((struct stop_reply *) reply);
6126
6127 target_async (1);
6128 }
6129 else
6130 {
6131 gdb_assert (wait_status != NULL);
6132 strcpy (rs->buf.data (), wait_status);
6133 rs->cached_wait_status = 1;
6134 }
6135 }
6136 else
6137 {
6138 gdb_assert (wait_status == NULL);
6139
6140 gdb_assert (target_can_async_p ());
6141 target_async (1);
6142 }
6143 }
6144
6145 /* Implementation of the to_post_attach method. */
6146
6147 void
6148 extended_remote_target::post_attach (int pid)
6149 {
6150 /* Get text, data & bss offsets. */
6151 get_offsets ();
6152
6153 /* In certain cases GDB might not have had the chance to start
6154 symbol lookup up until now. This could happen if the debugged
6155 binary is not using shared libraries, the vsyscall page is not
6156 present (on Linux) and the binary itself hadn't changed since the
6157 debugging process was started. */
6158 if (current_program_space->symfile_object_file != NULL)
6159 remote_check_symbols();
6160 }
6161
6162 \f
6163 /* Check for the availability of vCont. This function should also check
6164 the response. */
6165
6166 void
6167 remote_target::remote_vcont_probe ()
6168 {
6169 remote_state *rs = get_remote_state ();
6170 char *buf;
6171
6172 strcpy (rs->buf.data (), "vCont?");
6173 putpkt (rs->buf);
6174 getpkt (&rs->buf, 0);
6175 buf = rs->buf.data ();
6176
6177 /* Make sure that the features we assume are supported. */
6178 if (startswith (buf, "vCont"))
6179 {
6180 char *p = &buf[5];
6181 int support_c, support_C;
6182
6183 rs->supports_vCont.s = 0;
6184 rs->supports_vCont.S = 0;
6185 support_c = 0;
6186 support_C = 0;
6187 rs->supports_vCont.t = 0;
6188 rs->supports_vCont.r = 0;
6189 while (p && *p == ';')
6190 {
6191 p++;
6192 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6193 rs->supports_vCont.s = 1;
6194 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6195 rs->supports_vCont.S = 1;
6196 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6197 support_c = 1;
6198 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6199 support_C = 1;
6200 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6201 rs->supports_vCont.t = 1;
6202 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6203 rs->supports_vCont.r = 1;
6204
6205 p = strchr (p, ';');
6206 }
6207
6208 /* If c, and C are not all supported, we can't use vCont. Clearing
6209 BUF will make packet_ok disable the packet. */
6210 if (!support_c || !support_C)
6211 buf[0] = 0;
6212 }
6213
6214 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6215 rs->supports_vCont_probed = true;
6216 }
6217
6218 /* Helper function for building "vCont" resumptions. Write a
6219 resumption to P. ENDP points to one-passed-the-end of the buffer
6220 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6221 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6222 resumed thread should be single-stepped and/or signalled. If PTID
6223 equals minus_one_ptid, then all threads are resumed; if PTID
6224 represents a process, then all threads of the process are resumed;
6225 the thread to be stepped and/or signalled is given in the global
6226 INFERIOR_PTID. */
6227
6228 char *
6229 remote_target::append_resumption (char *p, char *endp,
6230 ptid_t ptid, int step, gdb_signal siggnal)
6231 {
6232 struct remote_state *rs = get_remote_state ();
6233
6234 if (step && siggnal != GDB_SIGNAL_0)
6235 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6236 else if (step
6237 /* GDB is willing to range step. */
6238 && use_range_stepping
6239 /* Target supports range stepping. */
6240 && rs->supports_vCont.r
6241 /* We don't currently support range stepping multiple
6242 threads with a wildcard (though the protocol allows it,
6243 so stubs shouldn't make an active effort to forbid
6244 it). */
6245 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6246 {
6247 struct thread_info *tp;
6248
6249 if (ptid == minus_one_ptid)
6250 {
6251 /* If we don't know about the target thread's tid, then
6252 we're resuming magic_null_ptid (see caller). */
6253 tp = find_thread_ptid (this, magic_null_ptid);
6254 }
6255 else
6256 tp = find_thread_ptid (this, ptid);
6257 gdb_assert (tp != NULL);
6258
6259 if (tp->control.may_range_step)
6260 {
6261 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6262
6263 p += xsnprintf (p, endp - p, ";r%s,%s",
6264 phex_nz (tp->control.step_range_start,
6265 addr_size),
6266 phex_nz (tp->control.step_range_end,
6267 addr_size));
6268 }
6269 else
6270 p += xsnprintf (p, endp - p, ";s");
6271 }
6272 else if (step)
6273 p += xsnprintf (p, endp - p, ";s");
6274 else if (siggnal != GDB_SIGNAL_0)
6275 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6276 else
6277 p += xsnprintf (p, endp - p, ";c");
6278
6279 if (remote_multi_process_p (rs) && ptid.is_pid ())
6280 {
6281 ptid_t nptid;
6282
6283 /* All (-1) threads of process. */
6284 nptid = ptid_t (ptid.pid (), -1);
6285
6286 p += xsnprintf (p, endp - p, ":");
6287 p = write_ptid (p, endp, nptid);
6288 }
6289 else if (ptid != minus_one_ptid)
6290 {
6291 p += xsnprintf (p, endp - p, ":");
6292 p = write_ptid (p, endp, ptid);
6293 }
6294
6295 return p;
6296 }
6297
6298 /* Clear the thread's private info on resume. */
6299
6300 static void
6301 resume_clear_thread_private_info (struct thread_info *thread)
6302 {
6303 if (thread->priv != NULL)
6304 {
6305 remote_thread_info *priv = get_remote_thread_info (thread);
6306
6307 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6308 priv->watch_data_address = 0;
6309 }
6310 }
6311
6312 /* Append a vCont continue-with-signal action for threads that have a
6313 non-zero stop signal. */
6314
6315 char *
6316 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6317 ptid_t ptid)
6318 {
6319 for (thread_info *thread : all_non_exited_threads (this, ptid))
6320 if (inferior_ptid != thread->ptid
6321 && thread->stop_signal () != GDB_SIGNAL_0)
6322 {
6323 p = append_resumption (p, endp, thread->ptid,
6324 0, thread->stop_signal ());
6325 thread->set_stop_signal (GDB_SIGNAL_0);
6326 resume_clear_thread_private_info (thread);
6327 }
6328
6329 return p;
6330 }
6331
6332 /* Set the target running, using the packets that use Hc
6333 (c/s/C/S). */
6334
6335 void
6336 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6337 gdb_signal siggnal)
6338 {
6339 struct remote_state *rs = get_remote_state ();
6340 char *buf;
6341
6342 rs->last_sent_signal = siggnal;
6343 rs->last_sent_step = step;
6344
6345 /* The c/s/C/S resume packets use Hc, so set the continue
6346 thread. */
6347 if (ptid == minus_one_ptid)
6348 set_continue_thread (any_thread_ptid);
6349 else
6350 set_continue_thread (ptid);
6351
6352 for (thread_info *thread : all_non_exited_threads (this))
6353 resume_clear_thread_private_info (thread);
6354
6355 buf = rs->buf.data ();
6356 if (::execution_direction == EXEC_REVERSE)
6357 {
6358 /* We don't pass signals to the target in reverse exec mode. */
6359 if (info_verbose && siggnal != GDB_SIGNAL_0)
6360 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6361 siggnal);
6362
6363 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6364 error (_("Remote reverse-step not supported."));
6365 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6366 error (_("Remote reverse-continue not supported."));
6367
6368 strcpy (buf, step ? "bs" : "bc");
6369 }
6370 else if (siggnal != GDB_SIGNAL_0)
6371 {
6372 buf[0] = step ? 'S' : 'C';
6373 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6374 buf[2] = tohex (((int) siggnal) & 0xf);
6375 buf[3] = '\0';
6376 }
6377 else
6378 strcpy (buf, step ? "s" : "c");
6379
6380 putpkt (buf);
6381 }
6382
6383 /* Resume the remote inferior by using a "vCont" packet. The thread
6384 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6385 resumed thread should be single-stepped and/or signalled. If PTID
6386 equals minus_one_ptid, then all threads are resumed; the thread to
6387 be stepped and/or signalled is given in the global INFERIOR_PTID.
6388 This function returns non-zero iff it resumes the inferior.
6389
6390 This function issues a strict subset of all possible vCont commands
6391 at the moment. */
6392
6393 int
6394 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6395 enum gdb_signal siggnal)
6396 {
6397 struct remote_state *rs = get_remote_state ();
6398 char *p;
6399 char *endp;
6400
6401 /* No reverse execution actions defined for vCont. */
6402 if (::execution_direction == EXEC_REVERSE)
6403 return 0;
6404
6405 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6406 remote_vcont_probe ();
6407
6408 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6409 return 0;
6410
6411 p = rs->buf.data ();
6412 endp = p + get_remote_packet_size ();
6413
6414 /* If we could generate a wider range of packets, we'd have to worry
6415 about overflowing BUF. Should there be a generic
6416 "multi-part-packet" packet? */
6417
6418 p += xsnprintf (p, endp - p, "vCont");
6419
6420 if (ptid == magic_null_ptid)
6421 {
6422 /* MAGIC_NULL_PTID means that we don't have any active threads,
6423 so we don't have any TID numbers the inferior will
6424 understand. Make sure to only send forms that do not specify
6425 a TID. */
6426 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6427 }
6428 else if (ptid == minus_one_ptid || ptid.is_pid ())
6429 {
6430 /* Resume all threads (of all processes, or of a single
6431 process), with preference for INFERIOR_PTID. This assumes
6432 inferior_ptid belongs to the set of all threads we are about
6433 to resume. */
6434 if (step || siggnal != GDB_SIGNAL_0)
6435 {
6436 /* Step inferior_ptid, with or without signal. */
6437 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6438 }
6439
6440 /* Also pass down any pending signaled resumption for other
6441 threads not the current. */
6442 p = append_pending_thread_resumptions (p, endp, ptid);
6443
6444 /* And continue others without a signal. */
6445 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6446 }
6447 else
6448 {
6449 /* Scheduler locking; resume only PTID. */
6450 append_resumption (p, endp, ptid, step, siggnal);
6451 }
6452
6453 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6454 putpkt (rs->buf);
6455
6456 if (target_is_non_stop_p ())
6457 {
6458 /* In non-stop, the stub replies to vCont with "OK". The stop
6459 reply will be reported asynchronously by means of a `%Stop'
6460 notification. */
6461 getpkt (&rs->buf, 0);
6462 if (strcmp (rs->buf.data (), "OK") != 0)
6463 error (_("Unexpected vCont reply in non-stop mode: %s"),
6464 rs->buf.data ());
6465 }
6466
6467 return 1;
6468 }
6469
6470 /* Tell the remote machine to resume. */
6471
6472 void
6473 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6474 {
6475 struct remote_state *rs = get_remote_state ();
6476
6477 /* When connected in non-stop mode, the core resumes threads
6478 individually. Resuming remote threads directly in target_resume
6479 would thus result in sending one packet per thread. Instead, to
6480 minimize roundtrip latency, here we just store the resume
6481 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6482 resumption will be done in remote_target::commit_resume, where we'll be
6483 able to do vCont action coalescing. */
6484 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6485 {
6486 remote_thread_info *remote_thr;
6487
6488 if (minus_one_ptid == ptid || ptid.is_pid ())
6489 remote_thr = get_remote_thread_info (this, inferior_ptid);
6490 else
6491 remote_thr = get_remote_thread_info (this, ptid);
6492
6493 /* We don't expect the core to ask to resume an already resumed (from
6494 its point of view) thread. */
6495 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6496
6497 remote_thr->set_resumed_pending_vcont (step, siggnal);
6498 return;
6499 }
6500
6501 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6502 (explained in remote-notif.c:handle_notification) so
6503 remote_notif_process is not called. We need find a place where
6504 it is safe to start a 'vNotif' sequence. It is good to do it
6505 before resuming inferior, because inferior was stopped and no RSP
6506 traffic at that moment. */
6507 if (!target_is_non_stop_p ())
6508 remote_notif_process (rs->notif_state, &notif_client_stop);
6509
6510 rs->last_resume_exec_dir = ::execution_direction;
6511
6512 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6513 if (!remote_resume_with_vcont (ptid, step, siggnal))
6514 remote_resume_with_hc (ptid, step, siggnal);
6515
6516 /* Update resumed state tracked by the remote target. */
6517 for (thread_info *tp : all_non_exited_threads (this, ptid))
6518 get_remote_thread_info (tp)->set_resumed ();
6519
6520 /* We are about to start executing the inferior, let's register it
6521 with the event loop. NOTE: this is the one place where all the
6522 execution commands end up. We could alternatively do this in each
6523 of the execution commands in infcmd.c. */
6524 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6525 into infcmd.c in order to allow inferior function calls to work
6526 NOT asynchronously. */
6527 if (target_can_async_p ())
6528 target_async (1);
6529
6530 /* We've just told the target to resume. The remote server will
6531 wait for the inferior to stop, and then send a stop reply. In
6532 the mean time, we can't start another command/query ourselves
6533 because the stub wouldn't be ready to process it. This applies
6534 only to the base all-stop protocol, however. In non-stop (which
6535 only supports vCont), the stub replies with an "OK", and is
6536 immediate able to process further serial input. */
6537 if (!target_is_non_stop_p ())
6538 rs->waiting_for_stop_reply = 1;
6539 }
6540
6541 static int is_pending_fork_parent_thread (struct thread_info *thread);
6542
6543 /* Private per-inferior info for target remote processes. */
6544
6545 struct remote_inferior : public private_inferior
6546 {
6547 /* Whether we can send a wildcard vCont for this process. */
6548 bool may_wildcard_vcont = true;
6549 };
6550
6551 /* Get the remote private inferior data associated to INF. */
6552
6553 static remote_inferior *
6554 get_remote_inferior (inferior *inf)
6555 {
6556 if (inf->priv == NULL)
6557 inf->priv.reset (new remote_inferior);
6558
6559 return static_cast<remote_inferior *> (inf->priv.get ());
6560 }
6561
6562 struct stop_reply : public notif_event
6563 {
6564 ~stop_reply ();
6565
6566 /* The identifier of the thread about this event */
6567 ptid_t ptid;
6568
6569 /* The remote state this event is associated with. When the remote
6570 connection, represented by a remote_state object, is closed,
6571 all the associated stop_reply events should be released. */
6572 struct remote_state *rs;
6573
6574 struct target_waitstatus ws;
6575
6576 /* The architecture associated with the expedited registers. */
6577 gdbarch *arch;
6578
6579 /* Expedited registers. This makes remote debugging a bit more
6580 efficient for those targets that provide critical registers as
6581 part of their normal status mechanism (as another roundtrip to
6582 fetch them is avoided). */
6583 std::vector<cached_reg_t> regcache;
6584
6585 enum target_stop_reason stop_reason;
6586
6587 CORE_ADDR watch_data_address;
6588
6589 int core;
6590 };
6591
6592 /* Class used to track the construction of a vCont packet in the
6593 outgoing packet buffer. This is used to send multiple vCont
6594 packets if we have more actions than would fit a single packet. */
6595
6596 class vcont_builder
6597 {
6598 public:
6599 explicit vcont_builder (remote_target *remote)
6600 : m_remote (remote)
6601 {
6602 restart ();
6603 }
6604
6605 void flush ();
6606 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6607
6608 private:
6609 void restart ();
6610
6611 /* The remote target. */
6612 remote_target *m_remote;
6613
6614 /* Pointer to the first action. P points here if no action has been
6615 appended yet. */
6616 char *m_first_action;
6617
6618 /* Where the next action will be appended. */
6619 char *m_p;
6620
6621 /* The end of the buffer. Must never write past this. */
6622 char *m_endp;
6623 };
6624
6625 /* Prepare the outgoing buffer for a new vCont packet. */
6626
6627 void
6628 vcont_builder::restart ()
6629 {
6630 struct remote_state *rs = m_remote->get_remote_state ();
6631
6632 m_p = rs->buf.data ();
6633 m_endp = m_p + m_remote->get_remote_packet_size ();
6634 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6635 m_first_action = m_p;
6636 }
6637
6638 /* If the vCont packet being built has any action, send it to the
6639 remote end. */
6640
6641 void
6642 vcont_builder::flush ()
6643 {
6644 struct remote_state *rs;
6645
6646 if (m_p == m_first_action)
6647 return;
6648
6649 rs = m_remote->get_remote_state ();
6650 m_remote->putpkt (rs->buf);
6651 m_remote->getpkt (&rs->buf, 0);
6652 if (strcmp (rs->buf.data (), "OK") != 0)
6653 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6654 }
6655
6656 /* The largest action is range-stepping, with its two addresses. This
6657 is more than sufficient. If a new, bigger action is created, it'll
6658 quickly trigger a failed assertion in append_resumption (and we'll
6659 just bump this). */
6660 #define MAX_ACTION_SIZE 200
6661
6662 /* Append a new vCont action in the outgoing packet being built. If
6663 the action doesn't fit the packet along with previous actions, push
6664 what we've got so far to the remote end and start over a new vCont
6665 packet (with the new action). */
6666
6667 void
6668 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6669 {
6670 char buf[MAX_ACTION_SIZE + 1];
6671
6672 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6673 ptid, step, siggnal);
6674
6675 /* Check whether this new action would fit in the vCont packet along
6676 with previous actions. If not, send what we've got so far and
6677 start a new vCont packet. */
6678 size_t rsize = endp - buf;
6679 if (rsize > m_endp - m_p)
6680 {
6681 flush ();
6682 restart ();
6683
6684 /* Should now fit. */
6685 gdb_assert (rsize <= m_endp - m_p);
6686 }
6687
6688 memcpy (m_p, buf, rsize);
6689 m_p += rsize;
6690 *m_p = '\0';
6691 }
6692
6693 /* to_commit_resume implementation. */
6694
6695 void
6696 remote_target::commit_resumed ()
6697 {
6698 /* If connected in all-stop mode, we'd send the remote resume
6699 request directly from remote_resume. Likewise if
6700 reverse-debugging, as there are no defined vCont actions for
6701 reverse execution. */
6702 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6703 return;
6704
6705 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6706 instead of resuming all threads of each process individually.
6707 However, if any thread of a process must remain halted, we can't
6708 send wildcard resumes and must send one action per thread.
6709
6710 Care must be taken to not resume threads/processes the server
6711 side already told us are stopped, but the core doesn't know about
6712 yet, because the events are still in the vStopped notification
6713 queue. For example:
6714
6715 #1 => vCont s:p1.1;c
6716 #2 <= OK
6717 #3 <= %Stopped T05 p1.1
6718 #4 => vStopped
6719 #5 <= T05 p1.2
6720 #6 => vStopped
6721 #7 <= OK
6722 #8 (infrun handles the stop for p1.1 and continues stepping)
6723 #9 => vCont s:p1.1;c
6724
6725 The last vCont above would resume thread p1.2 by mistake, because
6726 the server has no idea that the event for p1.2 had not been
6727 handled yet.
6728
6729 The server side must similarly ignore resume actions for the
6730 thread that has a pending %Stopped notification (and any other
6731 threads with events pending), until GDB acks the notification
6732 with vStopped. Otherwise, e.g., the following case is
6733 mishandled:
6734
6735 #1 => g (or any other packet)
6736 #2 <= [registers]
6737 #3 <= %Stopped T05 p1.2
6738 #4 => vCont s:p1.1;c
6739 #5 <= OK
6740
6741 Above, the server must not resume thread p1.2. GDB can't know
6742 that p1.2 stopped until it acks the %Stopped notification, and
6743 since from GDB's perspective all threads should be running, it
6744 sends a "c" action.
6745
6746 Finally, special care must also be given to handling fork/vfork
6747 events. A (v)fork event actually tells us that two processes
6748 stopped -- the parent and the child. Until we follow the fork,
6749 we must not resume the child. Therefore, if we have a pending
6750 fork follow, we must not send a global wildcard resume action
6751 (vCont;c). We can still send process-wide wildcards though. */
6752
6753 /* Start by assuming a global wildcard (vCont;c) is possible. */
6754 bool may_global_wildcard_vcont = true;
6755
6756 /* And assume every process is individually wildcard-able too. */
6757 for (inferior *inf : all_non_exited_inferiors (this))
6758 {
6759 remote_inferior *priv = get_remote_inferior (inf);
6760
6761 priv->may_wildcard_vcont = true;
6762 }
6763
6764 /* Check for any pending events (not reported or processed yet) and
6765 disable process and global wildcard resumes appropriately. */
6766 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6767
6768 bool any_pending_vcont_resume = false;
6769
6770 for (thread_info *tp : all_non_exited_threads (this))
6771 {
6772 remote_thread_info *priv = get_remote_thread_info (tp);
6773
6774 /* If a thread of a process is not meant to be resumed, then we
6775 can't wildcard that process. */
6776 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6777 {
6778 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6779
6780 /* And if we can't wildcard a process, we can't wildcard
6781 everything either. */
6782 may_global_wildcard_vcont = false;
6783 continue;
6784 }
6785
6786 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6787 any_pending_vcont_resume = true;
6788
6789 /* If a thread is the parent of an unfollowed fork, then we
6790 can't do a global wildcard, as that would resume the fork
6791 child. */
6792 if (is_pending_fork_parent_thread (tp))
6793 may_global_wildcard_vcont = false;
6794 }
6795
6796 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6797 do. */
6798 if (!any_pending_vcont_resume)
6799 return;
6800
6801 /* Now let's build the vCont packet(s). Actions must be appended
6802 from narrower to wider scopes (thread -> process -> global). If
6803 we end up with too many actions for a single packet vcont_builder
6804 flushes the current vCont packet to the remote side and starts a
6805 new one. */
6806 struct vcont_builder vcont_builder (this);
6807
6808 /* Threads first. */
6809 for (thread_info *tp : all_non_exited_threads (this))
6810 {
6811 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6812
6813 /* If the thread was previously vCont-resumed, no need to send a specific
6814 action for it. If we didn't receive a resume request for it, don't
6815 send an action for it either. */
6816 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6817 continue;
6818
6819 gdb_assert (!thread_is_in_step_over_chain (tp));
6820
6821 /* We should never be commit-resuming a thread that has a stop reply.
6822 Otherwise, we would end up reporting a stop event for a thread while
6823 it is running on the remote target. */
6824 remote_state *rs = get_remote_state ();
6825 for (const auto &stop_reply : rs->stop_reply_queue)
6826 gdb_assert (stop_reply->ptid != tp->ptid);
6827
6828 const resumed_pending_vcont_info &info
6829 = remote_thr->resumed_pending_vcont_info ();
6830
6831 /* Check if we need to send a specific action for this thread. If not,
6832 it will be included in a wildcard resume instead. */
6833 if (info.step || info.sig != GDB_SIGNAL_0
6834 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6835 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6836
6837 remote_thr->set_resumed ();
6838 }
6839
6840 /* Now check whether we can send any process-wide wildcard. This is
6841 to avoid sending a global wildcard in the case nothing is
6842 supposed to be resumed. */
6843 bool any_process_wildcard = false;
6844
6845 for (inferior *inf : all_non_exited_inferiors (this))
6846 {
6847 if (get_remote_inferior (inf)->may_wildcard_vcont)
6848 {
6849 any_process_wildcard = true;
6850 break;
6851 }
6852 }
6853
6854 if (any_process_wildcard)
6855 {
6856 /* If all processes are wildcard-able, then send a single "c"
6857 action, otherwise, send an "all (-1) threads of process"
6858 continue action for each running process, if any. */
6859 if (may_global_wildcard_vcont)
6860 {
6861 vcont_builder.push_action (minus_one_ptid,
6862 false, GDB_SIGNAL_0);
6863 }
6864 else
6865 {
6866 for (inferior *inf : all_non_exited_inferiors (this))
6867 {
6868 if (get_remote_inferior (inf)->may_wildcard_vcont)
6869 {
6870 vcont_builder.push_action (ptid_t (inf->pid),
6871 false, GDB_SIGNAL_0);
6872 }
6873 }
6874 }
6875 }
6876
6877 vcont_builder.flush ();
6878 }
6879
6880 /* Implementation of target_has_pending_events. */
6881
6882 bool
6883 remote_target::has_pending_events ()
6884 {
6885 if (target_can_async_p ())
6886 {
6887 remote_state *rs = get_remote_state ();
6888
6889 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6890 return true;
6891
6892 /* Note that BUFCNT can be negative, indicating sticky
6893 error. */
6894 if (rs->remote_desc->bufcnt != 0)
6895 return true;
6896 }
6897 return false;
6898 }
6899
6900 \f
6901
6902 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6903 thread, all threads of a remote process, or all threads of all
6904 processes. */
6905
6906 void
6907 remote_target::remote_stop_ns (ptid_t ptid)
6908 {
6909 struct remote_state *rs = get_remote_state ();
6910 char *p = rs->buf.data ();
6911 char *endp = p + get_remote_packet_size ();
6912
6913 /* If any thread that needs to stop was resumed but pending a vCont
6914 resume, generate a phony stop_reply. However, first check
6915 whether the thread wasn't resumed with a signal. Generating a
6916 phony stop in that case would result in losing the signal. */
6917 bool needs_commit = false;
6918 for (thread_info *tp : all_non_exited_threads (this, ptid))
6919 {
6920 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6921
6922 if (remote_thr->get_resume_state ()
6923 == resume_state::RESUMED_PENDING_VCONT)
6924 {
6925 const resumed_pending_vcont_info &info
6926 = remote_thr->resumed_pending_vcont_info ();
6927 if (info.sig != GDB_SIGNAL_0)
6928 {
6929 /* This signal must be forwarded to the inferior. We
6930 could commit-resume just this thread, but its simpler
6931 to just commit-resume everything. */
6932 needs_commit = true;
6933 break;
6934 }
6935 }
6936 }
6937
6938 if (needs_commit)
6939 commit_resumed ();
6940 else
6941 for (thread_info *tp : all_non_exited_threads (this, ptid))
6942 {
6943 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6944
6945 if (remote_thr->get_resume_state ()
6946 == resume_state::RESUMED_PENDING_VCONT)
6947 {
6948 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
6949 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
6950 tp->ptid.lwp (),
6951 pulongest (tp->ptid.tid ()));
6952
6953 /* Check that the thread wasn't resumed with a signal.
6954 Generating a phony stop would result in losing the
6955 signal. */
6956 const resumed_pending_vcont_info &info
6957 = remote_thr->resumed_pending_vcont_info ();
6958 gdb_assert (info.sig == GDB_SIGNAL_0);
6959
6960 stop_reply *sr = new stop_reply ();
6961 sr->ptid = tp->ptid;
6962 sr->rs = rs;
6963 sr->ws.set_stopped (GDB_SIGNAL_0);
6964 sr->arch = tp->inf->gdbarch;
6965 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6966 sr->watch_data_address = 0;
6967 sr->core = 0;
6968 this->push_stop_reply (sr);
6969
6970 /* Pretend that this thread was actually resumed on the
6971 remote target, then stopped. If we leave it in the
6972 RESUMED_PENDING_VCONT state and the commit_resumed
6973 method is called while the stop reply is still in the
6974 queue, we'll end up reporting a stop event to the core
6975 for that thread while it is running on the remote
6976 target... that would be bad. */
6977 remote_thr->set_resumed ();
6978 }
6979 }
6980
6981 /* FIXME: This supports_vCont_probed check is a workaround until
6982 packet_support is per-connection. */
6983 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
6984 || !rs->supports_vCont_probed)
6985 remote_vcont_probe ();
6986
6987 if (!rs->supports_vCont.t)
6988 error (_("Remote server does not support stopping threads"));
6989
6990 if (ptid == minus_one_ptid
6991 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
6992 p += xsnprintf (p, endp - p, "vCont;t");
6993 else
6994 {
6995 ptid_t nptid;
6996
6997 p += xsnprintf (p, endp - p, "vCont;t:");
6998
6999 if (ptid.is_pid ())
7000 /* All (-1) threads of process. */
7001 nptid = ptid_t (ptid.pid (), -1);
7002 else
7003 {
7004 /* Small optimization: if we already have a stop reply for
7005 this thread, no use in telling the stub we want this
7006 stopped. */
7007 if (peek_stop_reply (ptid))
7008 return;
7009
7010 nptid = ptid;
7011 }
7012
7013 write_ptid (p, endp, nptid);
7014 }
7015
7016 /* In non-stop, we get an immediate OK reply. The stop reply will
7017 come in asynchronously by notification. */
7018 putpkt (rs->buf);
7019 getpkt (&rs->buf, 0);
7020 if (strcmp (rs->buf.data (), "OK") != 0)
7021 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7022 rs->buf.data ());
7023 }
7024
7025 /* All-stop version of target_interrupt. Sends a break or a ^C to
7026 interrupt the remote target. It is undefined which thread of which
7027 process reports the interrupt. */
7028
7029 void
7030 remote_target::remote_interrupt_as ()
7031 {
7032 struct remote_state *rs = get_remote_state ();
7033
7034 rs->ctrlc_pending_p = 1;
7035
7036 /* If the inferior is stopped already, but the core didn't know
7037 about it yet, just ignore the request. The cached wait status
7038 will be collected in remote_wait. */
7039 if (rs->cached_wait_status)
7040 return;
7041
7042 /* Send interrupt_sequence to remote target. */
7043 send_interrupt_sequence ();
7044 }
7045
7046 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7047 the remote target. It is undefined which thread of which process
7048 reports the interrupt. Throws an error if the packet is not
7049 supported by the server. */
7050
7051 void
7052 remote_target::remote_interrupt_ns ()
7053 {
7054 struct remote_state *rs = get_remote_state ();
7055 char *p = rs->buf.data ();
7056 char *endp = p + get_remote_packet_size ();
7057
7058 xsnprintf (p, endp - p, "vCtrlC");
7059
7060 /* In non-stop, we get an immediate OK reply. The stop reply will
7061 come in asynchronously by notification. */
7062 putpkt (rs->buf);
7063 getpkt (&rs->buf, 0);
7064
7065 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7066 {
7067 case PACKET_OK:
7068 break;
7069 case PACKET_UNKNOWN:
7070 error (_("No support for interrupting the remote target."));
7071 case PACKET_ERROR:
7072 error (_("Interrupting target failed: %s"), rs->buf.data ());
7073 }
7074 }
7075
7076 /* Implement the to_stop function for the remote targets. */
7077
7078 void
7079 remote_target::stop (ptid_t ptid)
7080 {
7081 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7082
7083 if (target_is_non_stop_p ())
7084 remote_stop_ns (ptid);
7085 else
7086 {
7087 /* We don't currently have a way to transparently pause the
7088 remote target in all-stop mode. Interrupt it instead. */
7089 remote_interrupt_as ();
7090 }
7091 }
7092
7093 /* Implement the to_interrupt function for the remote targets. */
7094
7095 void
7096 remote_target::interrupt ()
7097 {
7098 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7099
7100 if (target_is_non_stop_p ())
7101 remote_interrupt_ns ();
7102 else
7103 remote_interrupt_as ();
7104 }
7105
7106 /* Implement the to_pass_ctrlc function for the remote targets. */
7107
7108 void
7109 remote_target::pass_ctrlc ()
7110 {
7111 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7112
7113 struct remote_state *rs = get_remote_state ();
7114
7115 /* If we're starting up, we're not fully synced yet. Quit
7116 immediately. */
7117 if (rs->starting_up)
7118 quit ();
7119 /* If ^C has already been sent once, offer to disconnect. */
7120 else if (rs->ctrlc_pending_p)
7121 interrupt_query ();
7122 else
7123 target_interrupt ();
7124 }
7125
7126 /* Ask the user what to do when an interrupt is received. */
7127
7128 void
7129 remote_target::interrupt_query ()
7130 {
7131 struct remote_state *rs = get_remote_state ();
7132
7133 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7134 {
7135 if (query (_("The target is not responding to interrupt requests.\n"
7136 "Stop debugging it? ")))
7137 {
7138 remote_unpush_target (this);
7139 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7140 }
7141 }
7142 else
7143 {
7144 if (query (_("Interrupted while waiting for the program.\n"
7145 "Give up waiting? ")))
7146 quit ();
7147 }
7148 }
7149
7150 /* Enable/disable target terminal ownership. Most targets can use
7151 terminal groups to control terminal ownership. Remote targets are
7152 different in that explicit transfer of ownership to/from GDB/target
7153 is required. */
7154
7155 void
7156 remote_target::terminal_inferior ()
7157 {
7158 /* NOTE: At this point we could also register our selves as the
7159 recipient of all input. Any characters typed could then be
7160 passed on down to the target. */
7161 }
7162
7163 void
7164 remote_target::terminal_ours ()
7165 {
7166 }
7167
7168 static void
7169 remote_console_output (const char *msg)
7170 {
7171 const char *p;
7172
7173 for (p = msg; p[0] && p[1]; p += 2)
7174 {
7175 char tb[2];
7176 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7177
7178 tb[0] = c;
7179 tb[1] = 0;
7180 gdb_stdtarg->puts (tb);
7181 }
7182 gdb_stdtarg->flush ();
7183 }
7184
7185 /* Return the length of the stop reply queue. */
7186
7187 int
7188 remote_target::stop_reply_queue_length ()
7189 {
7190 remote_state *rs = get_remote_state ();
7191 return rs->stop_reply_queue.size ();
7192 }
7193
7194 static void
7195 remote_notif_stop_parse (remote_target *remote,
7196 struct notif_client *self, const char *buf,
7197 struct notif_event *event)
7198 {
7199 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7200 }
7201
7202 static void
7203 remote_notif_stop_ack (remote_target *remote,
7204 struct notif_client *self, const char *buf,
7205 struct notif_event *event)
7206 {
7207 struct stop_reply *stop_reply = (struct stop_reply *) event;
7208
7209 /* acknowledge */
7210 putpkt (remote, self->ack_command);
7211
7212 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7213 the notification. It was left in the queue because we need to
7214 acknowledge it and pull the rest of the notifications out. */
7215 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7216 remote->push_stop_reply (stop_reply);
7217 }
7218
7219 static int
7220 remote_notif_stop_can_get_pending_events (remote_target *remote,
7221 struct notif_client *self)
7222 {
7223 /* We can't get pending events in remote_notif_process for
7224 notification stop, and we have to do this in remote_wait_ns
7225 instead. If we fetch all queued events from stub, remote stub
7226 may exit and we have no chance to process them back in
7227 remote_wait_ns. */
7228 remote_state *rs = remote->get_remote_state ();
7229 mark_async_event_handler (rs->remote_async_inferior_event_token);
7230 return 0;
7231 }
7232
7233 stop_reply::~stop_reply ()
7234 {
7235 for (cached_reg_t &reg : regcache)
7236 xfree (reg.data);
7237 }
7238
7239 static notif_event_up
7240 remote_notif_stop_alloc_reply ()
7241 {
7242 return notif_event_up (new struct stop_reply ());
7243 }
7244
7245 /* A client of notification Stop. */
7246
7247 struct notif_client notif_client_stop =
7248 {
7249 "Stop",
7250 "vStopped",
7251 remote_notif_stop_parse,
7252 remote_notif_stop_ack,
7253 remote_notif_stop_can_get_pending_events,
7254 remote_notif_stop_alloc_reply,
7255 REMOTE_NOTIF_STOP,
7256 };
7257
7258 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
7259 the pid of the process that owns the threads we want to check, or
7260 -1 if we want to check all threads. */
7261
7262 static int
7263 is_pending_fork_parent (const target_waitstatus &ws, int event_pid,
7264 ptid_t thread_ptid)
7265 {
7266 if (ws.kind () == TARGET_WAITKIND_FORKED
7267 || ws.kind () == TARGET_WAITKIND_VFORKED)
7268 {
7269 if (event_pid == -1 || event_pid == thread_ptid.pid ())
7270 return 1;
7271 }
7272
7273 return 0;
7274 }
7275
7276 /* Return the thread's pending status used to determine whether the
7277 thread is a fork parent stopped at a fork event. */
7278
7279 static const target_waitstatus &
7280 thread_pending_fork_status (struct thread_info *thread)
7281 {
7282 if (thread->has_pending_waitstatus ())
7283 return thread->pending_waitstatus ();
7284 else
7285 return thread->pending_follow;
7286 }
7287
7288 /* Determine if THREAD is a pending fork parent thread. */
7289
7290 static int
7291 is_pending_fork_parent_thread (struct thread_info *thread)
7292 {
7293 const target_waitstatus &ws = thread_pending_fork_status (thread);
7294 int pid = -1;
7295
7296 return is_pending_fork_parent (ws, pid, thread->ptid);
7297 }
7298
7299 /* If CONTEXT contains any fork child threads that have not been
7300 reported yet, remove them from the CONTEXT list. If such a
7301 thread exists it is because we are stopped at a fork catchpoint
7302 and have not yet called follow_fork, which will set up the
7303 host-side data structures for the new process. */
7304
7305 void
7306 remote_target::remove_new_fork_children (threads_listing_context *context)
7307 {
7308 int pid = -1;
7309 struct notif_client *notif = &notif_client_stop;
7310
7311 /* For any threads stopped at a fork event, remove the corresponding
7312 fork child threads from the CONTEXT list. */
7313 for (thread_info *thread : all_non_exited_threads (this))
7314 {
7315 const target_waitstatus &ws = thread_pending_fork_status (thread);
7316
7317 if (is_pending_fork_parent (ws, pid, thread->ptid))
7318 context->remove_thread (ws.child_ptid ());
7319 }
7320
7321 /* Check for any pending fork events (not reported or processed yet)
7322 in process PID and remove those fork child threads from the
7323 CONTEXT list as well. */
7324 remote_notif_get_pending_events (notif);
7325 for (auto &event : get_remote_state ()->stop_reply_queue)
7326 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7327 || event->ws.kind () == TARGET_WAITKIND_VFORKED
7328 || event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7329 context->remove_thread (event->ws.child_ptid ());
7330 }
7331
7332 /* Check whether any event pending in the vStopped queue would prevent a
7333 global or process wildcard vCont action. Set *may_global_wildcard to
7334 false if we can't do a global wildcard (vCont;c), and clear the event
7335 inferior's may_wildcard_vcont flag if we can't do a process-wide
7336 wildcard resume (vCont;c:pPID.-1). */
7337
7338 void
7339 remote_target::check_pending_events_prevent_wildcard_vcont
7340 (bool *may_global_wildcard)
7341 {
7342 struct notif_client *notif = &notif_client_stop;
7343
7344 remote_notif_get_pending_events (notif);
7345 for (auto &event : get_remote_state ()->stop_reply_queue)
7346 {
7347 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7348 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7349 continue;
7350
7351 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7352 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7353 *may_global_wildcard = false;
7354
7355 /* This may be the first time we heard about this process.
7356 Regardless, we must not do a global wildcard resume, otherwise
7357 we'd resume this process too. */
7358 *may_global_wildcard = false;
7359 if (event->ptid != null_ptid)
7360 {
7361 inferior *inf = find_inferior_ptid (this, event->ptid);
7362 if (inf != NULL)
7363 get_remote_inferior (inf)->may_wildcard_vcont = false;
7364 }
7365 }
7366 }
7367
7368 /* Discard all pending stop replies of inferior INF. */
7369
7370 void
7371 remote_target::discard_pending_stop_replies (struct inferior *inf)
7372 {
7373 struct stop_reply *reply;
7374 struct remote_state *rs = get_remote_state ();
7375 struct remote_notif_state *rns = rs->notif_state;
7376
7377 /* This function can be notified when an inferior exists. When the
7378 target is not remote, the notification state is NULL. */
7379 if (rs->remote_desc == NULL)
7380 return;
7381
7382 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7383
7384 /* Discard the in-flight notification. */
7385 if (reply != NULL && reply->ptid.pid () == inf->pid)
7386 {
7387 /* Leave the notification pending, since the server expects that
7388 we acknowledge it with vStopped. But clear its contents, so
7389 that later on when we acknowledge it, we also discard it. */
7390 reply->ws.set_ignore ();
7391
7392 if (remote_debug)
7393 fprintf_unfiltered (gdb_stdlog,
7394 "discarded in-flight notification\n");
7395 }
7396
7397 /* Discard the stop replies we have already pulled with
7398 vStopped. */
7399 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7400 rs->stop_reply_queue.end (),
7401 [=] (const stop_reply_up &event)
7402 {
7403 return event->ptid.pid () == inf->pid;
7404 });
7405 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7406 }
7407
7408 /* Discard the stop replies for RS in stop_reply_queue. */
7409
7410 void
7411 remote_target::discard_pending_stop_replies_in_queue ()
7412 {
7413 remote_state *rs = get_remote_state ();
7414
7415 /* Discard the stop replies we have already pulled with
7416 vStopped. */
7417 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7418 rs->stop_reply_queue.end (),
7419 [=] (const stop_reply_up &event)
7420 {
7421 return event->rs == rs;
7422 });
7423 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7424 }
7425
7426 /* Remove the first reply in 'stop_reply_queue' which matches
7427 PTID. */
7428
7429 struct stop_reply *
7430 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7431 {
7432 remote_state *rs = get_remote_state ();
7433
7434 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7435 rs->stop_reply_queue.end (),
7436 [=] (const stop_reply_up &event)
7437 {
7438 return event->ptid.matches (ptid);
7439 });
7440 struct stop_reply *result;
7441 if (iter == rs->stop_reply_queue.end ())
7442 result = nullptr;
7443 else
7444 {
7445 result = iter->release ();
7446 rs->stop_reply_queue.erase (iter);
7447 }
7448
7449 if (notif_debug)
7450 fprintf_unfiltered (gdb_stdlog,
7451 "notif: discard queued event: 'Stop' in %s\n",
7452 target_pid_to_str (ptid).c_str ());
7453
7454 return result;
7455 }
7456
7457 /* Look for a queued stop reply belonging to PTID. If one is found,
7458 remove it from the queue, and return it. Returns NULL if none is
7459 found. If there are still queued events left to process, tell the
7460 event loop to get back to target_wait soon. */
7461
7462 struct stop_reply *
7463 remote_target::queued_stop_reply (ptid_t ptid)
7464 {
7465 remote_state *rs = get_remote_state ();
7466 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7467
7468 if (!rs->stop_reply_queue.empty ())
7469 {
7470 /* There's still at least an event left. */
7471 mark_async_event_handler (rs->remote_async_inferior_event_token);
7472 }
7473
7474 return r;
7475 }
7476
7477 /* Push a fully parsed stop reply in the stop reply queue. Since we
7478 know that we now have at least one queued event left to pass to the
7479 core side, tell the event loop to get back to target_wait soon. */
7480
7481 void
7482 remote_target::push_stop_reply (struct stop_reply *new_event)
7483 {
7484 remote_state *rs = get_remote_state ();
7485 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7486
7487 if (notif_debug)
7488 fprintf_unfiltered (gdb_stdlog,
7489 "notif: push 'Stop' %s to queue %d\n",
7490 target_pid_to_str (new_event->ptid).c_str (),
7491 int (rs->stop_reply_queue.size ()));
7492
7493 mark_async_event_handler (rs->remote_async_inferior_event_token);
7494 }
7495
7496 /* Returns true if we have a stop reply for PTID. */
7497
7498 int
7499 remote_target::peek_stop_reply (ptid_t ptid)
7500 {
7501 remote_state *rs = get_remote_state ();
7502 for (auto &event : rs->stop_reply_queue)
7503 if (ptid == event->ptid
7504 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7505 return 1;
7506 return 0;
7507 }
7508
7509 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7510 starting with P and ending with PEND matches PREFIX. */
7511
7512 static int
7513 strprefix (const char *p, const char *pend, const char *prefix)
7514 {
7515 for ( ; p < pend; p++, prefix++)
7516 if (*p != *prefix)
7517 return 0;
7518 return *prefix == '\0';
7519 }
7520
7521 /* Parse the stop reply in BUF. Either the function succeeds, and the
7522 result is stored in EVENT, or throws an error. */
7523
7524 void
7525 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7526 {
7527 remote_arch_state *rsa = NULL;
7528 ULONGEST addr;
7529 const char *p;
7530 int skipregs = 0;
7531
7532 event->ptid = null_ptid;
7533 event->rs = get_remote_state ();
7534 event->ws.set_ignore ();
7535 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7536 event->regcache.clear ();
7537 event->core = -1;
7538
7539 switch (buf[0])
7540 {
7541 case 'T': /* Status with PC, SP, FP, ... */
7542 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7543 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7544 ss = signal number
7545 n... = register number
7546 r... = register contents
7547 */
7548
7549 p = &buf[3]; /* after Txx */
7550 while (*p)
7551 {
7552 const char *p1;
7553 int fieldsize;
7554
7555 p1 = strchr (p, ':');
7556 if (p1 == NULL)
7557 error (_("Malformed packet(a) (missing colon): %s\n\
7558 Packet: '%s'\n"),
7559 p, buf);
7560 if (p == p1)
7561 error (_("Malformed packet(a) (missing register number): %s\n\
7562 Packet: '%s'\n"),
7563 p, buf);
7564
7565 /* Some "registers" are actually extended stop information.
7566 Note if you're adding a new entry here: GDB 7.9 and
7567 earlier assume that all register "numbers" that start
7568 with an hex digit are real register numbers. Make sure
7569 the server only sends such a packet if it knows the
7570 client understands it. */
7571
7572 if (strprefix (p, p1, "thread"))
7573 event->ptid = read_ptid (++p1, &p);
7574 else if (strprefix (p, p1, "syscall_entry"))
7575 {
7576 ULONGEST sysno;
7577
7578 p = unpack_varlen_hex (++p1, &sysno);
7579 event->ws.set_syscall_entry ((int) sysno);
7580 }
7581 else if (strprefix (p, p1, "syscall_return"))
7582 {
7583 ULONGEST sysno;
7584
7585 p = unpack_varlen_hex (++p1, &sysno);
7586 event->ws.set_syscall_return ((int) sysno);
7587 }
7588 else if (strprefix (p, p1, "watch")
7589 || strprefix (p, p1, "rwatch")
7590 || strprefix (p, p1, "awatch"))
7591 {
7592 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7593 p = unpack_varlen_hex (++p1, &addr);
7594 event->watch_data_address = (CORE_ADDR) addr;
7595 }
7596 else if (strprefix (p, p1, "swbreak"))
7597 {
7598 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7599
7600 /* Make sure the stub doesn't forget to indicate support
7601 with qSupported. */
7602 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7603 error (_("Unexpected swbreak stop reason"));
7604
7605 /* The value part is documented as "must be empty",
7606 though we ignore it, in case we ever decide to make
7607 use of it in a backward compatible way. */
7608 p = strchrnul (p1 + 1, ';');
7609 }
7610 else if (strprefix (p, p1, "hwbreak"))
7611 {
7612 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7613
7614 /* Make sure the stub doesn't forget to indicate support
7615 with qSupported. */
7616 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7617 error (_("Unexpected hwbreak stop reason"));
7618
7619 /* See above. */
7620 p = strchrnul (p1 + 1, ';');
7621 }
7622 else if (strprefix (p, p1, "library"))
7623 {
7624 event->ws.set_loaded ();
7625 p = strchrnul (p1 + 1, ';');
7626 }
7627 else if (strprefix (p, p1, "replaylog"))
7628 {
7629 event->ws.set_no_history ();
7630 /* p1 will indicate "begin" or "end", but it makes
7631 no difference for now, so ignore it. */
7632 p = strchrnul (p1 + 1, ';');
7633 }
7634 else if (strprefix (p, p1, "core"))
7635 {
7636 ULONGEST c;
7637
7638 p = unpack_varlen_hex (++p1, &c);
7639 event->core = c;
7640 }
7641 else if (strprefix (p, p1, "fork"))
7642 event->ws.set_forked (read_ptid (++p1, &p));
7643 else if (strprefix (p, p1, "vfork"))
7644 event->ws.set_vforked (read_ptid (++p1, &p));
7645 else if (strprefix (p, p1, "vforkdone"))
7646 {
7647 event->ws.set_vfork_done ();
7648 p = strchrnul (p1 + 1, ';');
7649 }
7650 else if (strprefix (p, p1, "exec"))
7651 {
7652 ULONGEST ignored;
7653 int pathlen;
7654
7655 /* Determine the length of the execd pathname. */
7656 p = unpack_varlen_hex (++p1, &ignored);
7657 pathlen = (p - p1) / 2;
7658
7659 /* Save the pathname for event reporting and for
7660 the next run command. */
7661 gdb::unique_xmalloc_ptr<char> pathname
7662 ((char *) xmalloc (pathlen + 1));
7663 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7664 pathname.get ()[pathlen] = '\0';
7665
7666 /* This is freed during event handling. */
7667 event->ws.set_execd (std::move (pathname));
7668
7669 /* Skip the registers included in this packet, since
7670 they may be for an architecture different from the
7671 one used by the original program. */
7672 skipregs = 1;
7673 }
7674 else if (strprefix (p, p1, "create"))
7675 {
7676 event->ws.set_thread_created ();
7677 p = strchrnul (p1 + 1, ';');
7678 }
7679 else
7680 {
7681 ULONGEST pnum;
7682 const char *p_temp;
7683
7684 if (skipregs)
7685 {
7686 p = strchrnul (p1 + 1, ';');
7687 p++;
7688 continue;
7689 }
7690
7691 /* Maybe a real ``P'' register number. */
7692 p_temp = unpack_varlen_hex (p, &pnum);
7693 /* If the first invalid character is the colon, we got a
7694 register number. Otherwise, it's an unknown stop
7695 reason. */
7696 if (p_temp == p1)
7697 {
7698 /* If we haven't parsed the event's thread yet, find
7699 it now, in order to find the architecture of the
7700 reported expedited registers. */
7701 if (event->ptid == null_ptid)
7702 {
7703 /* If there is no thread-id information then leave
7704 the event->ptid as null_ptid. Later in
7705 process_stop_reply we will pick a suitable
7706 thread. */
7707 const char *thr = strstr (p1 + 1, ";thread:");
7708 if (thr != NULL)
7709 event->ptid = read_ptid (thr + strlen (";thread:"),
7710 NULL);
7711 }
7712
7713 if (rsa == NULL)
7714 {
7715 inferior *inf
7716 = (event->ptid == null_ptid
7717 ? NULL
7718 : find_inferior_ptid (this, event->ptid));
7719 /* If this is the first time we learn anything
7720 about this process, skip the registers
7721 included in this packet, since we don't yet
7722 know which architecture to use to parse them.
7723 We'll determine the architecture later when
7724 we process the stop reply and retrieve the
7725 target description, via
7726 remote_notice_new_inferior ->
7727 post_create_inferior. */
7728 if (inf == NULL)
7729 {
7730 p = strchrnul (p1 + 1, ';');
7731 p++;
7732 continue;
7733 }
7734
7735 event->arch = inf->gdbarch;
7736 rsa = event->rs->get_remote_arch_state (event->arch);
7737 }
7738
7739 packet_reg *reg
7740 = packet_reg_from_pnum (event->arch, rsa, pnum);
7741 cached_reg_t cached_reg;
7742
7743 if (reg == NULL)
7744 error (_("Remote sent bad register number %s: %s\n\
7745 Packet: '%s'\n"),
7746 hex_string (pnum), p, buf);
7747
7748 cached_reg.num = reg->regnum;
7749 cached_reg.data = (gdb_byte *)
7750 xmalloc (register_size (event->arch, reg->regnum));
7751
7752 p = p1 + 1;
7753 fieldsize = hex2bin (p, cached_reg.data,
7754 register_size (event->arch, reg->regnum));
7755 p += 2 * fieldsize;
7756 if (fieldsize < register_size (event->arch, reg->regnum))
7757 warning (_("Remote reply is too short: %s"), buf);
7758
7759 event->regcache.push_back (cached_reg);
7760 }
7761 else
7762 {
7763 /* Not a number. Silently skip unknown optional
7764 info. */
7765 p = strchrnul (p1 + 1, ';');
7766 }
7767 }
7768
7769 if (*p != ';')
7770 error (_("Remote register badly formatted: %s\nhere: %s"),
7771 buf, p);
7772 ++p;
7773 }
7774
7775 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7776 break;
7777
7778 /* fall through */
7779 case 'S': /* Old style status, just signal only. */
7780 {
7781 int sig;
7782
7783 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7784 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7785 event->ws.set_stopped ((enum gdb_signal) sig);
7786 else
7787 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7788 }
7789 break;
7790 case 'w': /* Thread exited. */
7791 {
7792 ULONGEST value;
7793
7794 p = unpack_varlen_hex (&buf[1], &value);
7795 event->ws.set_thread_exited (value);
7796 if (*p != ';')
7797 error (_("stop reply packet badly formatted: %s"), buf);
7798 event->ptid = read_ptid (++p, NULL);
7799 break;
7800 }
7801 case 'W': /* Target exited. */
7802 case 'X':
7803 {
7804 ULONGEST value;
7805
7806 /* GDB used to accept only 2 hex chars here. Stubs should
7807 only send more if they detect GDB supports multi-process
7808 support. */
7809 p = unpack_varlen_hex (&buf[1], &value);
7810
7811 if (buf[0] == 'W')
7812 {
7813 /* The remote process exited. */
7814 event->ws.set_exited (value);
7815 }
7816 else
7817 {
7818 /* The remote process exited with a signal. */
7819 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7820 event->ws.set_signalled ((enum gdb_signal) value);
7821 else
7822 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7823 }
7824
7825 /* If no process is specified, return null_ptid, and let the
7826 caller figure out the right process to use. */
7827 int pid = 0;
7828 if (*p == '\0')
7829 ;
7830 else if (*p == ';')
7831 {
7832 p++;
7833
7834 if (*p == '\0')
7835 ;
7836 else if (startswith (p, "process:"))
7837 {
7838 ULONGEST upid;
7839
7840 p += sizeof ("process:") - 1;
7841 unpack_varlen_hex (p, &upid);
7842 pid = upid;
7843 }
7844 else
7845 error (_("unknown stop reply packet: %s"), buf);
7846 }
7847 else
7848 error (_("unknown stop reply packet: %s"), buf);
7849 event->ptid = ptid_t (pid);
7850 }
7851 break;
7852 case 'N':
7853 event->ws.set_no_resumed ();
7854 event->ptid = minus_one_ptid;
7855 break;
7856 }
7857 }
7858
7859 /* When the stub wants to tell GDB about a new notification reply, it
7860 sends a notification (%Stop, for example). Those can come it at
7861 any time, hence, we have to make sure that any pending
7862 putpkt/getpkt sequence we're making is finished, before querying
7863 the stub for more events with the corresponding ack command
7864 (vStopped, for example). E.g., if we started a vStopped sequence
7865 immediately upon receiving the notification, something like this
7866 could happen:
7867
7868 1.1) --> Hg 1
7869 1.2) <-- OK
7870 1.3) --> g
7871 1.4) <-- %Stop
7872 1.5) --> vStopped
7873 1.6) <-- (registers reply to step #1.3)
7874
7875 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7876 query.
7877
7878 To solve this, whenever we parse a %Stop notification successfully,
7879 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7880 doing whatever we were doing:
7881
7882 2.1) --> Hg 1
7883 2.2) <-- OK
7884 2.3) --> g
7885 2.4) <-- %Stop
7886 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7887 2.5) <-- (registers reply to step #2.3)
7888
7889 Eventually after step #2.5, we return to the event loop, which
7890 notices there's an event on the
7891 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7892 associated callback --- the function below. At this point, we're
7893 always safe to start a vStopped sequence. :
7894
7895 2.6) --> vStopped
7896 2.7) <-- T05 thread:2
7897 2.8) --> vStopped
7898 2.9) --> OK
7899 */
7900
7901 void
7902 remote_target::remote_notif_get_pending_events (notif_client *nc)
7903 {
7904 struct remote_state *rs = get_remote_state ();
7905
7906 if (rs->notif_state->pending_event[nc->id] != NULL)
7907 {
7908 if (notif_debug)
7909 fprintf_unfiltered (gdb_stdlog,
7910 "notif: process: '%s' ack pending event\n",
7911 nc->name);
7912
7913 /* acknowledge */
7914 nc->ack (this, nc, rs->buf.data (),
7915 rs->notif_state->pending_event[nc->id]);
7916 rs->notif_state->pending_event[nc->id] = NULL;
7917
7918 while (1)
7919 {
7920 getpkt (&rs->buf, 0);
7921 if (strcmp (rs->buf.data (), "OK") == 0)
7922 break;
7923 else
7924 remote_notif_ack (this, nc, rs->buf.data ());
7925 }
7926 }
7927 else
7928 {
7929 if (notif_debug)
7930 fprintf_unfiltered (gdb_stdlog,
7931 "notif: process: '%s' no pending reply\n",
7932 nc->name);
7933 }
7934 }
7935
7936 /* Wrapper around remote_target::remote_notif_get_pending_events to
7937 avoid having to export the whole remote_target class. */
7938
7939 void
7940 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7941 {
7942 remote->remote_notif_get_pending_events (nc);
7943 }
7944
7945 /* Called from process_stop_reply when the stop packet we are responding
7946 to didn't include a process-id or thread-id. STATUS is the stop event
7947 we are responding to.
7948
7949 It is the task of this function to select a suitable thread (or process)
7950 and return its ptid, this is the thread (or process) we will assume the
7951 stop event came from.
7952
7953 In some cases there isn't really any choice about which thread (or
7954 process) is selected, a basic remote with a single process containing a
7955 single thread might choose not to send any process-id or thread-id in
7956 its stop packets, this function will select and return the one and only
7957 thread.
7958
7959 However, if a target supports multiple threads (or processes) and still
7960 doesn't include a thread-id (or process-id) in its stop packet then
7961 first, this is a badly behaving target, and second, we're going to have
7962 to select a thread (or process) at random and use that. This function
7963 will print a warning to the user if it detects that there is the
7964 possibility that GDB is guessing which thread (or process) to
7965 report.
7966
7967 Note that this is called before GDB fetches the updated thread list from the
7968 target. So it's possible for the stop reply to be ambiguous and for GDB to
7969 not realize it. For example, if there's initially one thread, the target
7970 spawns a second thread, and then sends a stop reply without an id that
7971 concerns the first thread. GDB will assume the stop reply is about the
7972 first thread - the only thread it knows about - without printing a warning.
7973 Anyway, if the remote meant for the stop reply to be about the second thread,
7974 then it would be really broken, because GDB doesn't know about that thread
7975 yet. */
7976
7977 ptid_t
7978 remote_target::select_thread_for_ambiguous_stop_reply
7979 (const target_waitstatus &status)
7980 {
7981 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7982
7983 /* Some stop events apply to all threads in an inferior, while others
7984 only apply to a single thread. */
7985 bool process_wide_stop
7986 = (status.kind () == TARGET_WAITKIND_EXITED
7987 || status.kind () == TARGET_WAITKIND_SIGNALLED);
7988
7989 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
7990
7991 thread_info *first_resumed_thread = nullptr;
7992 bool ambiguous = false;
7993
7994 /* Consider all non-exited threads of the target, find the first resumed
7995 one. */
7996 for (thread_info *thr : all_non_exited_threads (this))
7997 {
7998 remote_thread_info *remote_thr = get_remote_thread_info (thr);
7999
8000 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8001 continue;
8002
8003 if (first_resumed_thread == nullptr)
8004 first_resumed_thread = thr;
8005 else if (!process_wide_stop
8006 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8007 ambiguous = true;
8008 }
8009
8010 remote_debug_printf ("first resumed thread is %s",
8011 pid_to_str (first_resumed_thread->ptid).c_str ());
8012 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8013
8014 gdb_assert (first_resumed_thread != nullptr);
8015
8016 /* Warn if the remote target is sending ambiguous stop replies. */
8017 if (ambiguous)
8018 {
8019 static bool warned = false;
8020
8021 if (!warned)
8022 {
8023 /* If you are seeing this warning then the remote target has
8024 stopped without specifying a thread-id, but the target
8025 does have multiple threads (or inferiors), and so GDB is
8026 having to guess which thread stopped.
8027
8028 Examples of what might cause this are the target sending
8029 and 'S' stop packet, or a 'T' stop packet and not
8030 including a thread-id.
8031
8032 Additionally, the target might send a 'W' or 'X packet
8033 without including a process-id, when the target has
8034 multiple running inferiors. */
8035 if (process_wide_stop)
8036 warning (_("multi-inferior target stopped without "
8037 "sending a process-id, using first "
8038 "non-exited inferior"));
8039 else
8040 warning (_("multi-threaded target stopped without "
8041 "sending a thread-id, using first "
8042 "non-exited thread"));
8043 warned = true;
8044 }
8045 }
8046
8047 /* If this is a stop for all threads then don't use a particular threads
8048 ptid, instead create a new ptid where only the pid field is set. */
8049 if (process_wide_stop)
8050 return ptid_t (first_resumed_thread->ptid.pid ());
8051 else
8052 return first_resumed_thread->ptid;
8053 }
8054
8055 /* Called when it is decided that STOP_REPLY holds the info of the
8056 event that is to be returned to the core. This function always
8057 destroys STOP_REPLY. */
8058
8059 ptid_t
8060 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8061 struct target_waitstatus *status)
8062 {
8063 *status = stop_reply->ws;
8064 ptid_t ptid = stop_reply->ptid;
8065
8066 /* If no thread/process was reported by the stub then select a suitable
8067 thread/process. */
8068 if (ptid == null_ptid)
8069 ptid = select_thread_for_ambiguous_stop_reply (*status);
8070 gdb_assert (ptid != null_ptid);
8071
8072 if (status->kind () != TARGET_WAITKIND_EXITED
8073 && status->kind () != TARGET_WAITKIND_SIGNALLED
8074 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8075 {
8076 /* Expedited registers. */
8077 if (!stop_reply->regcache.empty ())
8078 {
8079 struct regcache *regcache
8080 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8081
8082 for (cached_reg_t &reg : stop_reply->regcache)
8083 {
8084 regcache->raw_supply (reg.num, reg.data);
8085 xfree (reg.data);
8086 }
8087
8088 stop_reply->regcache.clear ();
8089 }
8090
8091 remote_notice_new_inferior (ptid, false);
8092 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8093 remote_thr->core = stop_reply->core;
8094 remote_thr->stop_reason = stop_reply->stop_reason;
8095 remote_thr->watch_data_address = stop_reply->watch_data_address;
8096
8097 if (target_is_non_stop_p ())
8098 {
8099 /* If the target works in non-stop mode, a stop-reply indicates that
8100 only this thread stopped. */
8101 remote_thr->set_not_resumed ();
8102 }
8103 else
8104 {
8105 /* If the target works in all-stop mode, a stop-reply indicates that
8106 all the target's threads stopped. */
8107 for (thread_info *tp : all_non_exited_threads (this))
8108 get_remote_thread_info (tp)->set_not_resumed ();
8109 }
8110 }
8111
8112 delete stop_reply;
8113 return ptid;
8114 }
8115
8116 /* The non-stop mode version of target_wait. */
8117
8118 ptid_t
8119 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8120 target_wait_flags options)
8121 {
8122 struct remote_state *rs = get_remote_state ();
8123 struct stop_reply *stop_reply;
8124 int ret;
8125 int is_notif = 0;
8126
8127 /* If in non-stop mode, get out of getpkt even if a
8128 notification is received. */
8129
8130 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8131 while (1)
8132 {
8133 if (ret != -1 && !is_notif)
8134 switch (rs->buf[0])
8135 {
8136 case 'E': /* Error of some sort. */
8137 /* We're out of sync with the target now. Did it continue
8138 or not? We can't tell which thread it was in non-stop,
8139 so just ignore this. */
8140 warning (_("Remote failure reply: %s"), rs->buf.data ());
8141 break;
8142 case 'O': /* Console output. */
8143 remote_console_output (&rs->buf[1]);
8144 break;
8145 default:
8146 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8147 break;
8148 }
8149
8150 /* Acknowledge a pending stop reply that may have arrived in the
8151 mean time. */
8152 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8153 remote_notif_get_pending_events (&notif_client_stop);
8154
8155 /* If indeed we noticed a stop reply, we're done. */
8156 stop_reply = queued_stop_reply (ptid);
8157 if (stop_reply != NULL)
8158 return process_stop_reply (stop_reply, status);
8159
8160 /* Still no event. If we're just polling for an event, then
8161 return to the event loop. */
8162 if (options & TARGET_WNOHANG)
8163 {
8164 status->set_ignore ();
8165 return minus_one_ptid;
8166 }
8167
8168 /* Otherwise do a blocking wait. */
8169 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8170 }
8171 }
8172
8173 /* Return the first resumed thread. */
8174
8175 static ptid_t
8176 first_remote_resumed_thread (remote_target *target)
8177 {
8178 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8179 if (tp->resumed ())
8180 return tp->ptid;
8181 return null_ptid;
8182 }
8183
8184 /* Wait until the remote machine stops, then return, storing status in
8185 STATUS just as `wait' would. */
8186
8187 ptid_t
8188 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8189 target_wait_flags options)
8190 {
8191 struct remote_state *rs = get_remote_state ();
8192 ptid_t event_ptid = null_ptid;
8193 char *buf;
8194 struct stop_reply *stop_reply;
8195
8196 again:
8197
8198 status->set_ignore ();
8199
8200 stop_reply = queued_stop_reply (ptid);
8201 if (stop_reply != NULL)
8202 return process_stop_reply (stop_reply, status);
8203
8204 if (rs->cached_wait_status)
8205 /* Use the cached wait status, but only once. */
8206 rs->cached_wait_status = 0;
8207 else
8208 {
8209 int ret;
8210 int is_notif;
8211 int forever = ((options & TARGET_WNOHANG) == 0
8212 && rs->wait_forever_enabled_p);
8213
8214 if (!rs->waiting_for_stop_reply)
8215 {
8216 status->set_no_resumed ();
8217 return minus_one_ptid;
8218 }
8219
8220 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8221 _never_ wait for ever -> test on target_is_async_p().
8222 However, before we do that we need to ensure that the caller
8223 knows how to take the target into/out of async mode. */
8224 ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8225
8226 /* GDB gets a notification. Return to core as this event is
8227 not interesting. */
8228 if (ret != -1 && is_notif)
8229 return minus_one_ptid;
8230
8231 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8232 return minus_one_ptid;
8233 }
8234
8235 buf = rs->buf.data ();
8236
8237 /* Assume that the target has acknowledged Ctrl-C unless we receive
8238 an 'F' or 'O' packet. */
8239 if (buf[0] != 'F' && buf[0] != 'O')
8240 rs->ctrlc_pending_p = 0;
8241
8242 switch (buf[0])
8243 {
8244 case 'E': /* Error of some sort. */
8245 /* We're out of sync with the target now. Did it continue or
8246 not? Not is more likely, so report a stop. */
8247 rs->waiting_for_stop_reply = 0;
8248
8249 warning (_("Remote failure reply: %s"), buf);
8250 status->set_stopped (GDB_SIGNAL_0);
8251 break;
8252 case 'F': /* File-I/O request. */
8253 /* GDB may access the inferior memory while handling the File-I/O
8254 request, but we don't want GDB accessing memory while waiting
8255 for a stop reply. See the comments in putpkt_binary. Set
8256 waiting_for_stop_reply to 0 temporarily. */
8257 rs->waiting_for_stop_reply = 0;
8258 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8259 rs->ctrlc_pending_p = 0;
8260 /* GDB handled the File-I/O request, and the target is running
8261 again. Keep waiting for events. */
8262 rs->waiting_for_stop_reply = 1;
8263 break;
8264 case 'N': case 'T': case 'S': case 'X': case 'W':
8265 {
8266 /* There is a stop reply to handle. */
8267 rs->waiting_for_stop_reply = 0;
8268
8269 stop_reply
8270 = (struct stop_reply *) remote_notif_parse (this,
8271 &notif_client_stop,
8272 rs->buf.data ());
8273
8274 event_ptid = process_stop_reply (stop_reply, status);
8275 break;
8276 }
8277 case 'O': /* Console output. */
8278 remote_console_output (buf + 1);
8279 break;
8280 case '\0':
8281 if (rs->last_sent_signal != GDB_SIGNAL_0)
8282 {
8283 /* Zero length reply means that we tried 'S' or 'C' and the
8284 remote system doesn't support it. */
8285 target_terminal::ours_for_output ();
8286 printf_filtered
8287 ("Can't send signals to this remote system. %s not sent.\n",
8288 gdb_signal_to_name (rs->last_sent_signal));
8289 rs->last_sent_signal = GDB_SIGNAL_0;
8290 target_terminal::inferior ();
8291
8292 strcpy (buf, rs->last_sent_step ? "s" : "c");
8293 putpkt (buf);
8294 break;
8295 }
8296 /* fallthrough */
8297 default:
8298 warning (_("Invalid remote reply: %s"), buf);
8299 break;
8300 }
8301
8302 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8303 return minus_one_ptid;
8304 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8305 {
8306 /* Nothing interesting happened. If we're doing a non-blocking
8307 poll, we're done. Otherwise, go back to waiting. */
8308 if (options & TARGET_WNOHANG)
8309 return minus_one_ptid;
8310 else
8311 goto again;
8312 }
8313 else if (status->kind () != TARGET_WAITKIND_EXITED
8314 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8315 {
8316 if (event_ptid != null_ptid)
8317 record_currthread (rs, event_ptid);
8318 else
8319 event_ptid = first_remote_resumed_thread (this);
8320 }
8321 else
8322 {
8323 /* A process exit. Invalidate our notion of current thread. */
8324 record_currthread (rs, minus_one_ptid);
8325 /* It's possible that the packet did not include a pid. */
8326 if (event_ptid == null_ptid)
8327 event_ptid = first_remote_resumed_thread (this);
8328 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8329 if (event_ptid == null_ptid)
8330 event_ptid = magic_null_ptid;
8331 }
8332
8333 return event_ptid;
8334 }
8335
8336 /* Wait until the remote machine stops, then return, storing status in
8337 STATUS just as `wait' would. */
8338
8339 ptid_t
8340 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8341 target_wait_flags options)
8342 {
8343 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8344
8345 remote_state *rs = get_remote_state ();
8346
8347 /* Start by clearing the flag that asks for our wait method to be called,
8348 we'll mark it again at the end if needed. */
8349 if (target_is_async_p ())
8350 clear_async_event_handler (rs->remote_async_inferior_event_token);
8351
8352 ptid_t event_ptid;
8353
8354 if (target_is_non_stop_p ())
8355 event_ptid = wait_ns (ptid, status, options);
8356 else
8357 event_ptid = wait_as (ptid, status, options);
8358
8359 if (target_is_async_p ())
8360 {
8361 /* If there are events left in the queue, or unacknowledged
8362 notifications, then tell the event loop to call us again. */
8363 if (!rs->stop_reply_queue.empty ()
8364 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8365 mark_async_event_handler (rs->remote_async_inferior_event_token);
8366 }
8367
8368 return event_ptid;
8369 }
8370
8371 /* Fetch a single register using a 'p' packet. */
8372
8373 int
8374 remote_target::fetch_register_using_p (struct regcache *regcache,
8375 packet_reg *reg)
8376 {
8377 struct gdbarch *gdbarch = regcache->arch ();
8378 struct remote_state *rs = get_remote_state ();
8379 char *buf, *p;
8380 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8381 int i;
8382
8383 if (packet_support (PACKET_p) == PACKET_DISABLE)
8384 return 0;
8385
8386 if (reg->pnum == -1)
8387 return 0;
8388
8389 p = rs->buf.data ();
8390 *p++ = 'p';
8391 p += hexnumstr (p, reg->pnum);
8392 *p++ = '\0';
8393 putpkt (rs->buf);
8394 getpkt (&rs->buf, 0);
8395
8396 buf = rs->buf.data ();
8397
8398 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8399 {
8400 case PACKET_OK:
8401 break;
8402 case PACKET_UNKNOWN:
8403 return 0;
8404 case PACKET_ERROR:
8405 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8406 gdbarch_register_name (regcache->arch (),
8407 reg->regnum),
8408 buf);
8409 }
8410
8411 /* If this register is unfetchable, tell the regcache. */
8412 if (buf[0] == 'x')
8413 {
8414 regcache->raw_supply (reg->regnum, NULL);
8415 return 1;
8416 }
8417
8418 /* Otherwise, parse and supply the value. */
8419 p = buf;
8420 i = 0;
8421 while (p[0] != 0)
8422 {
8423 if (p[1] == 0)
8424 error (_("fetch_register_using_p: early buf termination"));
8425
8426 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8427 p += 2;
8428 }
8429 regcache->raw_supply (reg->regnum, regp);
8430 return 1;
8431 }
8432
8433 /* Fetch the registers included in the target's 'g' packet. */
8434
8435 int
8436 remote_target::send_g_packet ()
8437 {
8438 struct remote_state *rs = get_remote_state ();
8439 int buf_len;
8440
8441 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8442 putpkt (rs->buf);
8443 getpkt (&rs->buf, 0);
8444 if (packet_check_result (rs->buf) == PACKET_ERROR)
8445 error (_("Could not read registers; remote failure reply '%s'"),
8446 rs->buf.data ());
8447
8448 /* We can get out of synch in various cases. If the first character
8449 in the buffer is not a hex character, assume that has happened
8450 and try to fetch another packet to read. */
8451 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8452 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8453 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8454 && rs->buf[0] != 'x') /* New: unavailable register value. */
8455 {
8456 remote_debug_printf ("Bad register packet; fetching a new packet");
8457 getpkt (&rs->buf, 0);
8458 }
8459
8460 buf_len = strlen (rs->buf.data ());
8461
8462 /* Sanity check the received packet. */
8463 if (buf_len % 2 != 0)
8464 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8465
8466 return buf_len / 2;
8467 }
8468
8469 void
8470 remote_target::process_g_packet (struct regcache *regcache)
8471 {
8472 struct gdbarch *gdbarch = regcache->arch ();
8473 struct remote_state *rs = get_remote_state ();
8474 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8475 int i, buf_len;
8476 char *p;
8477 char *regs;
8478
8479 buf_len = strlen (rs->buf.data ());
8480
8481 /* Further sanity checks, with knowledge of the architecture. */
8482 if (buf_len > 2 * rsa->sizeof_g_packet)
8483 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8484 "bytes): %s"),
8485 rsa->sizeof_g_packet, buf_len / 2,
8486 rs->buf.data ());
8487
8488 /* Save the size of the packet sent to us by the target. It is used
8489 as a heuristic when determining the max size of packets that the
8490 target can safely receive. */
8491 if (rsa->actual_register_packet_size == 0)
8492 rsa->actual_register_packet_size = buf_len;
8493
8494 /* If this is smaller than we guessed the 'g' packet would be,
8495 update our records. A 'g' reply that doesn't include a register's
8496 value implies either that the register is not available, or that
8497 the 'p' packet must be used. */
8498 if (buf_len < 2 * rsa->sizeof_g_packet)
8499 {
8500 long sizeof_g_packet = buf_len / 2;
8501
8502 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8503 {
8504 long offset = rsa->regs[i].offset;
8505 long reg_size = register_size (gdbarch, i);
8506
8507 if (rsa->regs[i].pnum == -1)
8508 continue;
8509
8510 if (offset >= sizeof_g_packet)
8511 rsa->regs[i].in_g_packet = 0;
8512 else if (offset + reg_size > sizeof_g_packet)
8513 error (_("Truncated register %d in remote 'g' packet"), i);
8514 else
8515 rsa->regs[i].in_g_packet = 1;
8516 }
8517
8518 /* Looks valid enough, we can assume this is the correct length
8519 for a 'g' packet. It's important not to adjust
8520 rsa->sizeof_g_packet if we have truncated registers otherwise
8521 this "if" won't be run the next time the method is called
8522 with a packet of the same size and one of the internal errors
8523 below will trigger instead. */
8524 rsa->sizeof_g_packet = sizeof_g_packet;
8525 }
8526
8527 regs = (char *) alloca (rsa->sizeof_g_packet);
8528
8529 /* Unimplemented registers read as all bits zero. */
8530 memset (regs, 0, rsa->sizeof_g_packet);
8531
8532 /* Reply describes registers byte by byte, each byte encoded as two
8533 hex characters. Suck them all up, then supply them to the
8534 register cacheing/storage mechanism. */
8535
8536 p = rs->buf.data ();
8537 for (i = 0; i < rsa->sizeof_g_packet; i++)
8538 {
8539 if (p[0] == 0 || p[1] == 0)
8540 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8541 internal_error (__FILE__, __LINE__,
8542 _("unexpected end of 'g' packet reply"));
8543
8544 if (p[0] == 'x' && p[1] == 'x')
8545 regs[i] = 0; /* 'x' */
8546 else
8547 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8548 p += 2;
8549 }
8550
8551 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8552 {
8553 struct packet_reg *r = &rsa->regs[i];
8554 long reg_size = register_size (gdbarch, i);
8555
8556 if (r->in_g_packet)
8557 {
8558 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8559 /* This shouldn't happen - we adjusted in_g_packet above. */
8560 internal_error (__FILE__, __LINE__,
8561 _("unexpected end of 'g' packet reply"));
8562 else if (rs->buf[r->offset * 2] == 'x')
8563 {
8564 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8565 /* The register isn't available, mark it as such (at
8566 the same time setting the value to zero). */
8567 regcache->raw_supply (r->regnum, NULL);
8568 }
8569 else
8570 regcache->raw_supply (r->regnum, regs + r->offset);
8571 }
8572 }
8573 }
8574
8575 void
8576 remote_target::fetch_registers_using_g (struct regcache *regcache)
8577 {
8578 send_g_packet ();
8579 process_g_packet (regcache);
8580 }
8581
8582 /* Make the remote selected traceframe match GDB's selected
8583 traceframe. */
8584
8585 void
8586 remote_target::set_remote_traceframe ()
8587 {
8588 int newnum;
8589 struct remote_state *rs = get_remote_state ();
8590
8591 if (rs->remote_traceframe_number == get_traceframe_number ())
8592 return;
8593
8594 /* Avoid recursion, remote_trace_find calls us again. */
8595 rs->remote_traceframe_number = get_traceframe_number ();
8596
8597 newnum = target_trace_find (tfind_number,
8598 get_traceframe_number (), 0, 0, NULL);
8599
8600 /* Should not happen. If it does, all bets are off. */
8601 if (newnum != get_traceframe_number ())
8602 warning (_("could not set remote traceframe"));
8603 }
8604
8605 void
8606 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8607 {
8608 struct gdbarch *gdbarch = regcache->arch ();
8609 struct remote_state *rs = get_remote_state ();
8610 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8611 int i;
8612
8613 set_remote_traceframe ();
8614 set_general_thread (regcache->ptid ());
8615
8616 if (regnum >= 0)
8617 {
8618 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8619
8620 gdb_assert (reg != NULL);
8621
8622 /* If this register might be in the 'g' packet, try that first -
8623 we are likely to read more than one register. If this is the
8624 first 'g' packet, we might be overly optimistic about its
8625 contents, so fall back to 'p'. */
8626 if (reg->in_g_packet)
8627 {
8628 fetch_registers_using_g (regcache);
8629 if (reg->in_g_packet)
8630 return;
8631 }
8632
8633 if (fetch_register_using_p (regcache, reg))
8634 return;
8635
8636 /* This register is not available. */
8637 regcache->raw_supply (reg->regnum, NULL);
8638
8639 return;
8640 }
8641
8642 fetch_registers_using_g (regcache);
8643
8644 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8645 if (!rsa->regs[i].in_g_packet)
8646 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8647 {
8648 /* This register is not available. */
8649 regcache->raw_supply (i, NULL);
8650 }
8651 }
8652
8653 /* Prepare to store registers. Since we may send them all (using a
8654 'G' request), we have to read out the ones we don't want to change
8655 first. */
8656
8657 void
8658 remote_target::prepare_to_store (struct regcache *regcache)
8659 {
8660 struct remote_state *rs = get_remote_state ();
8661 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8662 int i;
8663
8664 /* Make sure the entire registers array is valid. */
8665 switch (packet_support (PACKET_P))
8666 {
8667 case PACKET_DISABLE:
8668 case PACKET_SUPPORT_UNKNOWN:
8669 /* Make sure all the necessary registers are cached. */
8670 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8671 if (rsa->regs[i].in_g_packet)
8672 regcache->raw_update (rsa->regs[i].regnum);
8673 break;
8674 case PACKET_ENABLE:
8675 break;
8676 }
8677 }
8678
8679 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8680 packet was not recognized. */
8681
8682 int
8683 remote_target::store_register_using_P (const struct regcache *regcache,
8684 packet_reg *reg)
8685 {
8686 struct gdbarch *gdbarch = regcache->arch ();
8687 struct remote_state *rs = get_remote_state ();
8688 /* Try storing a single register. */
8689 char *buf = rs->buf.data ();
8690 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8691 char *p;
8692
8693 if (packet_support (PACKET_P) == PACKET_DISABLE)
8694 return 0;
8695
8696 if (reg->pnum == -1)
8697 return 0;
8698
8699 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8700 p = buf + strlen (buf);
8701 regcache->raw_collect (reg->regnum, regp);
8702 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8703 putpkt (rs->buf);
8704 getpkt (&rs->buf, 0);
8705
8706 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8707 {
8708 case PACKET_OK:
8709 return 1;
8710 case PACKET_ERROR:
8711 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8712 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8713 case PACKET_UNKNOWN:
8714 return 0;
8715 default:
8716 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8717 }
8718 }
8719
8720 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8721 contents of the register cache buffer. FIXME: ignores errors. */
8722
8723 void
8724 remote_target::store_registers_using_G (const struct regcache *regcache)
8725 {
8726 struct remote_state *rs = get_remote_state ();
8727 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8728 gdb_byte *regs;
8729 char *p;
8730
8731 /* Extract all the registers in the regcache copying them into a
8732 local buffer. */
8733 {
8734 int i;
8735
8736 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8737 memset (regs, 0, rsa->sizeof_g_packet);
8738 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8739 {
8740 struct packet_reg *r = &rsa->regs[i];
8741
8742 if (r->in_g_packet)
8743 regcache->raw_collect (r->regnum, regs + r->offset);
8744 }
8745 }
8746
8747 /* Command describes registers byte by byte,
8748 each byte encoded as two hex characters. */
8749 p = rs->buf.data ();
8750 *p++ = 'G';
8751 bin2hex (regs, p, rsa->sizeof_g_packet);
8752 putpkt (rs->buf);
8753 getpkt (&rs->buf, 0);
8754 if (packet_check_result (rs->buf) == PACKET_ERROR)
8755 error (_("Could not write registers; remote failure reply '%s'"),
8756 rs->buf.data ());
8757 }
8758
8759 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8760 of the register cache buffer. FIXME: ignores errors. */
8761
8762 void
8763 remote_target::store_registers (struct regcache *regcache, int regnum)
8764 {
8765 struct gdbarch *gdbarch = regcache->arch ();
8766 struct remote_state *rs = get_remote_state ();
8767 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8768 int i;
8769
8770 set_remote_traceframe ();
8771 set_general_thread (regcache->ptid ());
8772
8773 if (regnum >= 0)
8774 {
8775 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8776
8777 gdb_assert (reg != NULL);
8778
8779 /* Always prefer to store registers using the 'P' packet if
8780 possible; we often change only a small number of registers.
8781 Sometimes we change a larger number; we'd need help from a
8782 higher layer to know to use 'G'. */
8783 if (store_register_using_P (regcache, reg))
8784 return;
8785
8786 /* For now, don't complain if we have no way to write the
8787 register. GDB loses track of unavailable registers too
8788 easily. Some day, this may be an error. We don't have
8789 any way to read the register, either... */
8790 if (!reg->in_g_packet)
8791 return;
8792
8793 store_registers_using_G (regcache);
8794 return;
8795 }
8796
8797 store_registers_using_G (regcache);
8798
8799 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8800 if (!rsa->regs[i].in_g_packet)
8801 if (!store_register_using_P (regcache, &rsa->regs[i]))
8802 /* See above for why we do not issue an error here. */
8803 continue;
8804 }
8805 \f
8806
8807 /* Return the number of hex digits in num. */
8808
8809 static int
8810 hexnumlen (ULONGEST num)
8811 {
8812 int i;
8813
8814 for (i = 0; num != 0; i++)
8815 num >>= 4;
8816
8817 return std::max (i, 1);
8818 }
8819
8820 /* Set BUF to the minimum number of hex digits representing NUM. */
8821
8822 static int
8823 hexnumstr (char *buf, ULONGEST num)
8824 {
8825 int len = hexnumlen (num);
8826
8827 return hexnumnstr (buf, num, len);
8828 }
8829
8830
8831 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8832
8833 static int
8834 hexnumnstr (char *buf, ULONGEST num, int width)
8835 {
8836 int i;
8837
8838 buf[width] = '\0';
8839
8840 for (i = width - 1; i >= 0; i--)
8841 {
8842 buf[i] = "0123456789abcdef"[(num & 0xf)];
8843 num >>= 4;
8844 }
8845
8846 return width;
8847 }
8848
8849 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8850
8851 static CORE_ADDR
8852 remote_address_masked (CORE_ADDR addr)
8853 {
8854 unsigned int address_size = remote_address_size;
8855
8856 /* If "remoteaddresssize" was not set, default to target address size. */
8857 if (!address_size)
8858 address_size = gdbarch_addr_bit (target_gdbarch ());
8859
8860 if (address_size > 0
8861 && address_size < (sizeof (ULONGEST) * 8))
8862 {
8863 /* Only create a mask when that mask can safely be constructed
8864 in a ULONGEST variable. */
8865 ULONGEST mask = 1;
8866
8867 mask = (mask << address_size) - 1;
8868 addr &= mask;
8869 }
8870 return addr;
8871 }
8872
8873 /* Determine whether the remote target supports binary downloading.
8874 This is accomplished by sending a no-op memory write of zero length
8875 to the target at the specified address. It does not suffice to send
8876 the whole packet, since many stubs strip the eighth bit and
8877 subsequently compute a wrong checksum, which causes real havoc with
8878 remote_write_bytes.
8879
8880 NOTE: This can still lose if the serial line is not eight-bit
8881 clean. In cases like this, the user should clear "remote
8882 X-packet". */
8883
8884 void
8885 remote_target::check_binary_download (CORE_ADDR addr)
8886 {
8887 struct remote_state *rs = get_remote_state ();
8888
8889 switch (packet_support (PACKET_X))
8890 {
8891 case PACKET_DISABLE:
8892 break;
8893 case PACKET_ENABLE:
8894 break;
8895 case PACKET_SUPPORT_UNKNOWN:
8896 {
8897 char *p;
8898
8899 p = rs->buf.data ();
8900 *p++ = 'X';
8901 p += hexnumstr (p, (ULONGEST) addr);
8902 *p++ = ',';
8903 p += hexnumstr (p, (ULONGEST) 0);
8904 *p++ = ':';
8905 *p = '\0';
8906
8907 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8908 getpkt (&rs->buf, 0);
8909
8910 if (rs->buf[0] == '\0')
8911 {
8912 remote_debug_printf ("binary downloading NOT supported by target");
8913 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8914 }
8915 else
8916 {
8917 remote_debug_printf ("binary downloading supported by target");
8918 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8919 }
8920 break;
8921 }
8922 }
8923 }
8924
8925 /* Helper function to resize the payload in order to try to get a good
8926 alignment. We try to write an amount of data such that the next write will
8927 start on an address aligned on REMOTE_ALIGN_WRITES. */
8928
8929 static int
8930 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8931 {
8932 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8933 }
8934
8935 /* Write memory data directly to the remote machine.
8936 This does not inform the data cache; the data cache uses this.
8937 HEADER is the starting part of the packet.
8938 MEMADDR is the address in the remote memory space.
8939 MYADDR is the address of the buffer in our space.
8940 LEN_UNITS is the number of addressable units to write.
8941 UNIT_SIZE is the length in bytes of an addressable unit.
8942 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8943 should send data as binary ('X'), or hex-encoded ('M').
8944
8945 The function creates packet of the form
8946 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8947
8948 where encoding of <DATA> is terminated by PACKET_FORMAT.
8949
8950 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8951 are omitted.
8952
8953 Return the transferred status, error or OK (an
8954 'enum target_xfer_status' value). Save the number of addressable units
8955 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8956
8957 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8958 exchange between gdb and the stub could look like (?? in place of the
8959 checksum):
8960
8961 -> $m1000,4#??
8962 <- aaaabbbbccccdddd
8963
8964 -> $M1000,3:eeeeffffeeee#??
8965 <- OK
8966
8967 -> $m1000,4#??
8968 <- eeeeffffeeeedddd */
8969
8970 target_xfer_status
8971 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8972 const gdb_byte *myaddr,
8973 ULONGEST len_units,
8974 int unit_size,
8975 ULONGEST *xfered_len_units,
8976 char packet_format, int use_length)
8977 {
8978 struct remote_state *rs = get_remote_state ();
8979 char *p;
8980 char *plen = NULL;
8981 int plenlen = 0;
8982 int todo_units;
8983 int units_written;
8984 int payload_capacity_bytes;
8985 int payload_length_bytes;
8986
8987 if (packet_format != 'X' && packet_format != 'M')
8988 internal_error (__FILE__, __LINE__,
8989 _("remote_write_bytes_aux: bad packet format"));
8990
8991 if (len_units == 0)
8992 return TARGET_XFER_EOF;
8993
8994 payload_capacity_bytes = get_memory_write_packet_size ();
8995
8996 /* The packet buffer will be large enough for the payload;
8997 get_memory_packet_size ensures this. */
8998 rs->buf[0] = '\0';
8999
9000 /* Compute the size of the actual payload by subtracting out the
9001 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9002
9003 payload_capacity_bytes -= strlen ("$,:#NN");
9004 if (!use_length)
9005 /* The comma won't be used. */
9006 payload_capacity_bytes += 1;
9007 payload_capacity_bytes -= strlen (header);
9008 payload_capacity_bytes -= hexnumlen (memaddr);
9009
9010 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9011
9012 strcat (rs->buf.data (), header);
9013 p = rs->buf.data () + strlen (header);
9014
9015 /* Compute a best guess of the number of bytes actually transfered. */
9016 if (packet_format == 'X')
9017 {
9018 /* Best guess at number of bytes that will fit. */
9019 todo_units = std::min (len_units,
9020 (ULONGEST) payload_capacity_bytes / unit_size);
9021 if (use_length)
9022 payload_capacity_bytes -= hexnumlen (todo_units);
9023 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9024 }
9025 else
9026 {
9027 /* Number of bytes that will fit. */
9028 todo_units
9029 = std::min (len_units,
9030 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9031 if (use_length)
9032 payload_capacity_bytes -= hexnumlen (todo_units);
9033 todo_units = std::min (todo_units,
9034 (payload_capacity_bytes / unit_size) / 2);
9035 }
9036
9037 if (todo_units <= 0)
9038 internal_error (__FILE__, __LINE__,
9039 _("minimum packet size too small to write data"));
9040
9041 /* If we already need another packet, then try to align the end
9042 of this packet to a useful boundary. */
9043 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9044 todo_units = align_for_efficient_write (todo_units, memaddr);
9045
9046 /* Append "<memaddr>". */
9047 memaddr = remote_address_masked (memaddr);
9048 p += hexnumstr (p, (ULONGEST) memaddr);
9049
9050 if (use_length)
9051 {
9052 /* Append ",". */
9053 *p++ = ',';
9054
9055 /* Append the length and retain its location and size. It may need to be
9056 adjusted once the packet body has been created. */
9057 plen = p;
9058 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9059 p += plenlen;
9060 }
9061
9062 /* Append ":". */
9063 *p++ = ':';
9064 *p = '\0';
9065
9066 /* Append the packet body. */
9067 if (packet_format == 'X')
9068 {
9069 /* Binary mode. Send target system values byte by byte, in
9070 increasing byte addresses. Only escape certain critical
9071 characters. */
9072 payload_length_bytes =
9073 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9074 &units_written, payload_capacity_bytes);
9075
9076 /* If not all TODO units fit, then we'll need another packet. Make
9077 a second try to keep the end of the packet aligned. Don't do
9078 this if the packet is tiny. */
9079 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9080 {
9081 int new_todo_units;
9082
9083 new_todo_units = align_for_efficient_write (units_written, memaddr);
9084
9085 if (new_todo_units != units_written)
9086 payload_length_bytes =
9087 remote_escape_output (myaddr, new_todo_units, unit_size,
9088 (gdb_byte *) p, &units_written,
9089 payload_capacity_bytes);
9090 }
9091
9092 p += payload_length_bytes;
9093 if (use_length && units_written < todo_units)
9094 {
9095 /* Escape chars have filled up the buffer prematurely,
9096 and we have actually sent fewer units than planned.
9097 Fix-up the length field of the packet. Use the same
9098 number of characters as before. */
9099 plen += hexnumnstr (plen, (ULONGEST) units_written,
9100 plenlen);
9101 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9102 }
9103 }
9104 else
9105 {
9106 /* Normal mode: Send target system values byte by byte, in
9107 increasing byte addresses. Each byte is encoded as a two hex
9108 value. */
9109 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9110 units_written = todo_units;
9111 }
9112
9113 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9114 getpkt (&rs->buf, 0);
9115
9116 if (rs->buf[0] == 'E')
9117 return TARGET_XFER_E_IO;
9118
9119 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9120 send fewer units than we'd planned. */
9121 *xfered_len_units = (ULONGEST) units_written;
9122 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9123 }
9124
9125 /* Write memory data directly to the remote machine.
9126 This does not inform the data cache; the data cache uses this.
9127 MEMADDR is the address in the remote memory space.
9128 MYADDR is the address of the buffer in our space.
9129 LEN is the number of bytes.
9130
9131 Return the transferred status, error or OK (an
9132 'enum target_xfer_status' value). Save the number of bytes
9133 transferred in *XFERED_LEN. Only transfer a single packet. */
9134
9135 target_xfer_status
9136 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9137 ULONGEST len, int unit_size,
9138 ULONGEST *xfered_len)
9139 {
9140 const char *packet_format = NULL;
9141
9142 /* Check whether the target supports binary download. */
9143 check_binary_download (memaddr);
9144
9145 switch (packet_support (PACKET_X))
9146 {
9147 case PACKET_ENABLE:
9148 packet_format = "X";
9149 break;
9150 case PACKET_DISABLE:
9151 packet_format = "M";
9152 break;
9153 case PACKET_SUPPORT_UNKNOWN:
9154 internal_error (__FILE__, __LINE__,
9155 _("remote_write_bytes: bad internal state"));
9156 default:
9157 internal_error (__FILE__, __LINE__, _("bad switch"));
9158 }
9159
9160 return remote_write_bytes_aux (packet_format,
9161 memaddr, myaddr, len, unit_size, xfered_len,
9162 packet_format[0], 1);
9163 }
9164
9165 /* Read memory data directly from the remote machine.
9166 This does not use the data cache; the data cache uses this.
9167 MEMADDR is the address in the remote memory space.
9168 MYADDR is the address of the buffer in our space.
9169 LEN_UNITS is the number of addressable memory units to read..
9170 UNIT_SIZE is the length in bytes of an addressable unit.
9171
9172 Return the transferred status, error or OK (an
9173 'enum target_xfer_status' value). Save the number of bytes
9174 transferred in *XFERED_LEN_UNITS.
9175
9176 See the comment of remote_write_bytes_aux for an example of
9177 memory read/write exchange between gdb and the stub. */
9178
9179 target_xfer_status
9180 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9181 ULONGEST len_units,
9182 int unit_size, ULONGEST *xfered_len_units)
9183 {
9184 struct remote_state *rs = get_remote_state ();
9185 int buf_size_bytes; /* Max size of packet output buffer. */
9186 char *p;
9187 int todo_units;
9188 int decoded_bytes;
9189
9190 buf_size_bytes = get_memory_read_packet_size ();
9191 /* The packet buffer will be large enough for the payload;
9192 get_memory_packet_size ensures this. */
9193
9194 /* Number of units that will fit. */
9195 todo_units = std::min (len_units,
9196 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9197
9198 /* Construct "m"<memaddr>","<len>". */
9199 memaddr = remote_address_masked (memaddr);
9200 p = rs->buf.data ();
9201 *p++ = 'm';
9202 p += hexnumstr (p, (ULONGEST) memaddr);
9203 *p++ = ',';
9204 p += hexnumstr (p, (ULONGEST) todo_units);
9205 *p = '\0';
9206 putpkt (rs->buf);
9207 getpkt (&rs->buf, 0);
9208 if (rs->buf[0] == 'E'
9209 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9210 && rs->buf[3] == '\0')
9211 return TARGET_XFER_E_IO;
9212 /* Reply describes memory byte by byte, each byte encoded as two hex
9213 characters. */
9214 p = rs->buf.data ();
9215 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9216 /* Return what we have. Let higher layers handle partial reads. */
9217 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9218 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9219 }
9220
9221 /* Using the set of read-only target sections of remote, read live
9222 read-only memory.
9223
9224 For interface/parameters/return description see target.h,
9225 to_xfer_partial. */
9226
9227 target_xfer_status
9228 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9229 ULONGEST memaddr,
9230 ULONGEST len,
9231 int unit_size,
9232 ULONGEST *xfered_len)
9233 {
9234 const struct target_section *secp;
9235
9236 secp = target_section_by_addr (this, memaddr);
9237 if (secp != NULL
9238 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9239 {
9240 ULONGEST memend = memaddr + len;
9241
9242 const target_section_table *table = target_get_section_table (this);
9243 for (const target_section &p : *table)
9244 {
9245 if (memaddr >= p.addr)
9246 {
9247 if (memend <= p.endaddr)
9248 {
9249 /* Entire transfer is within this section. */
9250 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9251 xfered_len);
9252 }
9253 else if (memaddr >= p.endaddr)
9254 {
9255 /* This section ends before the transfer starts. */
9256 continue;
9257 }
9258 else
9259 {
9260 /* This section overlaps the transfer. Just do half. */
9261 len = p.endaddr - memaddr;
9262 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9263 xfered_len);
9264 }
9265 }
9266 }
9267 }
9268
9269 return TARGET_XFER_EOF;
9270 }
9271
9272 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9273 first if the requested memory is unavailable in traceframe.
9274 Otherwise, fall back to remote_read_bytes_1. */
9275
9276 target_xfer_status
9277 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9278 gdb_byte *myaddr, ULONGEST len, int unit_size,
9279 ULONGEST *xfered_len)
9280 {
9281 if (len == 0)
9282 return TARGET_XFER_EOF;
9283
9284 if (get_traceframe_number () != -1)
9285 {
9286 std::vector<mem_range> available;
9287
9288 /* If we fail to get the set of available memory, then the
9289 target does not support querying traceframe info, and so we
9290 attempt reading from the traceframe anyway (assuming the
9291 target implements the old QTro packet then). */
9292 if (traceframe_available_memory (&available, memaddr, len))
9293 {
9294 if (available.empty () || available[0].start != memaddr)
9295 {
9296 enum target_xfer_status res;
9297
9298 /* Don't read into the traceframe's available
9299 memory. */
9300 if (!available.empty ())
9301 {
9302 LONGEST oldlen = len;
9303
9304 len = available[0].start - memaddr;
9305 gdb_assert (len <= oldlen);
9306 }
9307
9308 /* This goes through the topmost target again. */
9309 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9310 len, unit_size, xfered_len);
9311 if (res == TARGET_XFER_OK)
9312 return TARGET_XFER_OK;
9313 else
9314 {
9315 /* No use trying further, we know some memory starting
9316 at MEMADDR isn't available. */
9317 *xfered_len = len;
9318 return (*xfered_len != 0) ?
9319 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9320 }
9321 }
9322
9323 /* Don't try to read more than how much is available, in
9324 case the target implements the deprecated QTro packet to
9325 cater for older GDBs (the target's knowledge of read-only
9326 sections may be outdated by now). */
9327 len = available[0].length;
9328 }
9329 }
9330
9331 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9332 }
9333
9334 \f
9335
9336 /* Sends a packet with content determined by the printf format string
9337 FORMAT and the remaining arguments, then gets the reply. Returns
9338 whether the packet was a success, a failure, or unknown. */
9339
9340 packet_result
9341 remote_target::remote_send_printf (const char *format, ...)
9342 {
9343 struct remote_state *rs = get_remote_state ();
9344 int max_size = get_remote_packet_size ();
9345 va_list ap;
9346
9347 va_start (ap, format);
9348
9349 rs->buf[0] = '\0';
9350 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9351
9352 va_end (ap);
9353
9354 if (size >= max_size)
9355 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
9356
9357 if (putpkt (rs->buf) < 0)
9358 error (_("Communication problem with target."));
9359
9360 rs->buf[0] = '\0';
9361 getpkt (&rs->buf, 0);
9362
9363 return packet_check_result (rs->buf);
9364 }
9365
9366 /* Flash writing can take quite some time. We'll set
9367 effectively infinite timeout for flash operations.
9368 In future, we'll need to decide on a better approach. */
9369 static const int remote_flash_timeout = 1000;
9370
9371 void
9372 remote_target::flash_erase (ULONGEST address, LONGEST length)
9373 {
9374 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9375 enum packet_result ret;
9376 scoped_restore restore_timeout
9377 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9378
9379 ret = remote_send_printf ("vFlashErase:%s,%s",
9380 phex (address, addr_size),
9381 phex (length, 4));
9382 switch (ret)
9383 {
9384 case PACKET_UNKNOWN:
9385 error (_("Remote target does not support flash erase"));
9386 case PACKET_ERROR:
9387 error (_("Error erasing flash with vFlashErase packet"));
9388 default:
9389 break;
9390 }
9391 }
9392
9393 target_xfer_status
9394 remote_target::remote_flash_write (ULONGEST address,
9395 ULONGEST length, ULONGEST *xfered_len,
9396 const gdb_byte *data)
9397 {
9398 scoped_restore restore_timeout
9399 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9400 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9401 xfered_len,'X', 0);
9402 }
9403
9404 void
9405 remote_target::flash_done ()
9406 {
9407 int ret;
9408
9409 scoped_restore restore_timeout
9410 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9411
9412 ret = remote_send_printf ("vFlashDone");
9413
9414 switch (ret)
9415 {
9416 case PACKET_UNKNOWN:
9417 error (_("Remote target does not support vFlashDone"));
9418 case PACKET_ERROR:
9419 error (_("Error finishing flash operation"));
9420 default:
9421 break;
9422 }
9423 }
9424
9425 void
9426 remote_target::files_info ()
9427 {
9428 puts_filtered ("Debugging a target over a serial line.\n");
9429 }
9430 \f
9431 /* Stuff for dealing with the packets which are part of this protocol.
9432 See comment at top of file for details. */
9433
9434 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9435 error to higher layers. Called when a serial error is detected.
9436 The exception message is STRING, followed by a colon and a blank,
9437 the system error message for errno at function entry and final dot
9438 for output compatibility with throw_perror_with_name. */
9439
9440 static void
9441 unpush_and_perror (remote_target *target, const char *string)
9442 {
9443 int saved_errno = errno;
9444
9445 remote_unpush_target (target);
9446 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9447 safe_strerror (saved_errno));
9448 }
9449
9450 /* Read a single character from the remote end. The current quit
9451 handler is overridden to avoid quitting in the middle of packet
9452 sequence, as that would break communication with the remote server.
9453 See remote_serial_quit_handler for more detail. */
9454
9455 int
9456 remote_target::readchar (int timeout)
9457 {
9458 int ch;
9459 struct remote_state *rs = get_remote_state ();
9460
9461 {
9462 scoped_restore restore_quit_target
9463 = make_scoped_restore (&curr_quit_handler_target, this);
9464 scoped_restore restore_quit
9465 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9466
9467 rs->got_ctrlc_during_io = 0;
9468
9469 ch = serial_readchar (rs->remote_desc, timeout);
9470
9471 if (rs->got_ctrlc_during_io)
9472 set_quit_flag ();
9473 }
9474
9475 if (ch >= 0)
9476 return ch;
9477
9478 switch ((enum serial_rc) ch)
9479 {
9480 case SERIAL_EOF:
9481 remote_unpush_target (this);
9482 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9483 /* no return */
9484 case SERIAL_ERROR:
9485 unpush_and_perror (this, _("Remote communication error. "
9486 "Target disconnected."));
9487 /* no return */
9488 case SERIAL_TIMEOUT:
9489 break;
9490 }
9491 return ch;
9492 }
9493
9494 /* Wrapper for serial_write that closes the target and throws if
9495 writing fails. The current quit handler is overridden to avoid
9496 quitting in the middle of packet sequence, as that would break
9497 communication with the remote server. See
9498 remote_serial_quit_handler for more detail. */
9499
9500 void
9501 remote_target::remote_serial_write (const char *str, int len)
9502 {
9503 struct remote_state *rs = get_remote_state ();
9504
9505 scoped_restore restore_quit_target
9506 = make_scoped_restore (&curr_quit_handler_target, this);
9507 scoped_restore restore_quit
9508 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9509
9510 rs->got_ctrlc_during_io = 0;
9511
9512 if (serial_write (rs->remote_desc, str, len))
9513 {
9514 unpush_and_perror (this, _("Remote communication error. "
9515 "Target disconnected."));
9516 }
9517
9518 if (rs->got_ctrlc_during_io)
9519 set_quit_flag ();
9520 }
9521
9522 /* Return a string representing an escaped version of BUF, of len N.
9523 E.g. \n is converted to \\n, \t to \\t, etc. */
9524
9525 static std::string
9526 escape_buffer (const char *buf, int n)
9527 {
9528 string_file stb;
9529
9530 stb.putstrn (buf, n, '\\');
9531 return std::move (stb.string ());
9532 }
9533
9534 int
9535 remote_target::putpkt (const char *buf)
9536 {
9537 return putpkt_binary (buf, strlen (buf));
9538 }
9539
9540 /* Wrapper around remote_target::putpkt to avoid exporting
9541 remote_target. */
9542
9543 int
9544 putpkt (remote_target *remote, const char *buf)
9545 {
9546 return remote->putpkt (buf);
9547 }
9548
9549 /* Send a packet to the remote machine, with error checking. The data
9550 of the packet is in BUF. The string in BUF can be at most
9551 get_remote_packet_size () - 5 to account for the $, # and checksum,
9552 and for a possible /0 if we are debugging (remote_debug) and want
9553 to print the sent packet as a string. */
9554
9555 int
9556 remote_target::putpkt_binary (const char *buf, int cnt)
9557 {
9558 struct remote_state *rs = get_remote_state ();
9559 int i;
9560 unsigned char csum = 0;
9561 gdb::def_vector<char> data (cnt + 6);
9562 char *buf2 = data.data ();
9563
9564 int ch;
9565 int tcount = 0;
9566 char *p;
9567
9568 /* Catch cases like trying to read memory or listing threads while
9569 we're waiting for a stop reply. The remote server wouldn't be
9570 ready to handle this request, so we'd hang and timeout. We don't
9571 have to worry about this in synchronous mode, because in that
9572 case it's not possible to issue a command while the target is
9573 running. This is not a problem in non-stop mode, because in that
9574 case, the stub is always ready to process serial input. */
9575 if (!target_is_non_stop_p ()
9576 && target_is_async_p ()
9577 && rs->waiting_for_stop_reply)
9578 {
9579 error (_("Cannot execute this command while the target is running.\n"
9580 "Use the \"interrupt\" command to stop the target\n"
9581 "and then try again."));
9582 }
9583
9584 /* We're sending out a new packet. Make sure we don't look at a
9585 stale cached response. */
9586 rs->cached_wait_status = 0;
9587
9588 /* Copy the packet into buffer BUF2, encapsulating it
9589 and giving it a checksum. */
9590
9591 p = buf2;
9592 *p++ = '$';
9593
9594 for (i = 0; i < cnt; i++)
9595 {
9596 csum += buf[i];
9597 *p++ = buf[i];
9598 }
9599 *p++ = '#';
9600 *p++ = tohex ((csum >> 4) & 0xf);
9601 *p++ = tohex (csum & 0xf);
9602
9603 /* Send it over and over until we get a positive ack. */
9604
9605 while (1)
9606 {
9607 if (remote_debug)
9608 {
9609 *p = '\0';
9610
9611 int len = (int) (p - buf2);
9612 int max_chars;
9613
9614 if (remote_packet_max_chars < 0)
9615 max_chars = len;
9616 else
9617 max_chars = remote_packet_max_chars;
9618
9619 std::string str
9620 = escape_buffer (buf2, std::min (len, max_chars));
9621
9622 if (len > max_chars)
9623 remote_debug_printf_nofunc
9624 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9625 len - max_chars);
9626 else
9627 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9628 }
9629 remote_serial_write (buf2, p - buf2);
9630
9631 /* If this is a no acks version of the remote protocol, send the
9632 packet and move on. */
9633 if (rs->noack_mode)
9634 break;
9635
9636 /* Read until either a timeout occurs (-2) or '+' is read.
9637 Handle any notification that arrives in the mean time. */
9638 while (1)
9639 {
9640 ch = readchar (remote_timeout);
9641
9642 switch (ch)
9643 {
9644 case '+':
9645 remote_debug_printf_nofunc ("Received Ack");
9646 return 1;
9647 case '-':
9648 remote_debug_printf_nofunc ("Received Nak");
9649 /* FALLTHROUGH */
9650 case SERIAL_TIMEOUT:
9651 tcount++;
9652 if (tcount > 3)
9653 return 0;
9654 break; /* Retransmit buffer. */
9655 case '$':
9656 {
9657 remote_debug_printf ("Packet instead of Ack, ignoring it");
9658 /* It's probably an old response sent because an ACK
9659 was lost. Gobble up the packet and ack it so it
9660 doesn't get retransmitted when we resend this
9661 packet. */
9662 skip_frame ();
9663 remote_serial_write ("+", 1);
9664 continue; /* Now, go look for +. */
9665 }
9666
9667 case '%':
9668 {
9669 int val;
9670
9671 /* If we got a notification, handle it, and go back to looking
9672 for an ack. */
9673 /* We've found the start of a notification. Now
9674 collect the data. */
9675 val = read_frame (&rs->buf);
9676 if (val >= 0)
9677 {
9678 remote_debug_printf_nofunc
9679 (" Notification received: %s",
9680 escape_buffer (rs->buf.data (), val).c_str ());
9681
9682 handle_notification (rs->notif_state, rs->buf.data ());
9683 /* We're in sync now, rewait for the ack. */
9684 tcount = 0;
9685 }
9686 else
9687 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9688 rs->buf.data ());
9689 continue;
9690 }
9691 /* fall-through */
9692 default:
9693 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9694 rs->buf.data ());
9695 continue;
9696 }
9697 break; /* Here to retransmit. */
9698 }
9699
9700 #if 0
9701 /* This is wrong. If doing a long backtrace, the user should be
9702 able to get out next time we call QUIT, without anything as
9703 violent as interrupt_query. If we want to provide a way out of
9704 here without getting to the next QUIT, it should be based on
9705 hitting ^C twice as in remote_wait. */
9706 if (quit_flag)
9707 {
9708 quit_flag = 0;
9709 interrupt_query ();
9710 }
9711 #endif
9712 }
9713
9714 return 0;
9715 }
9716
9717 /* Come here after finding the start of a frame when we expected an
9718 ack. Do our best to discard the rest of this packet. */
9719
9720 void
9721 remote_target::skip_frame ()
9722 {
9723 int c;
9724
9725 while (1)
9726 {
9727 c = readchar (remote_timeout);
9728 switch (c)
9729 {
9730 case SERIAL_TIMEOUT:
9731 /* Nothing we can do. */
9732 return;
9733 case '#':
9734 /* Discard the two bytes of checksum and stop. */
9735 c = readchar (remote_timeout);
9736 if (c >= 0)
9737 c = readchar (remote_timeout);
9738
9739 return;
9740 case '*': /* Run length encoding. */
9741 /* Discard the repeat count. */
9742 c = readchar (remote_timeout);
9743 if (c < 0)
9744 return;
9745 break;
9746 default:
9747 /* A regular character. */
9748 break;
9749 }
9750 }
9751 }
9752
9753 /* Come here after finding the start of the frame. Collect the rest
9754 into *BUF, verifying the checksum, length, and handling run-length
9755 compression. NUL terminate the buffer. If there is not enough room,
9756 expand *BUF.
9757
9758 Returns -1 on error, number of characters in buffer (ignoring the
9759 trailing NULL) on success. (could be extended to return one of the
9760 SERIAL status indications). */
9761
9762 long
9763 remote_target::read_frame (gdb::char_vector *buf_p)
9764 {
9765 unsigned char csum;
9766 long bc;
9767 int c;
9768 char *buf = buf_p->data ();
9769 struct remote_state *rs = get_remote_state ();
9770
9771 csum = 0;
9772 bc = 0;
9773
9774 while (1)
9775 {
9776 c = readchar (remote_timeout);
9777 switch (c)
9778 {
9779 case SERIAL_TIMEOUT:
9780 remote_debug_printf ("Timeout in mid-packet, retrying");
9781 return -1;
9782
9783 case '$':
9784 remote_debug_printf ("Saw new packet start in middle of old one");
9785 return -1; /* Start a new packet, count retries. */
9786
9787 case '#':
9788 {
9789 unsigned char pktcsum;
9790 int check_0 = 0;
9791 int check_1 = 0;
9792
9793 buf[bc] = '\0';
9794
9795 check_0 = readchar (remote_timeout);
9796 if (check_0 >= 0)
9797 check_1 = readchar (remote_timeout);
9798
9799 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9800 {
9801 remote_debug_printf ("Timeout in checksum, retrying");
9802 return -1;
9803 }
9804 else if (check_0 < 0 || check_1 < 0)
9805 {
9806 remote_debug_printf ("Communication error in checksum");
9807 return -1;
9808 }
9809
9810 /* Don't recompute the checksum; with no ack packets we
9811 don't have any way to indicate a packet retransmission
9812 is necessary. */
9813 if (rs->noack_mode)
9814 return bc;
9815
9816 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9817 if (csum == pktcsum)
9818 return bc;
9819
9820 remote_debug_printf
9821 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9822 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9823
9824 /* Number of characters in buffer ignoring trailing
9825 NULL. */
9826 return -1;
9827 }
9828 case '*': /* Run length encoding. */
9829 {
9830 int repeat;
9831
9832 csum += c;
9833 c = readchar (remote_timeout);
9834 csum += c;
9835 repeat = c - ' ' + 3; /* Compute repeat count. */
9836
9837 /* The character before ``*'' is repeated. */
9838
9839 if (repeat > 0 && repeat <= 255 && bc > 0)
9840 {
9841 if (bc + repeat - 1 >= buf_p->size () - 1)
9842 {
9843 /* Make some more room in the buffer. */
9844 buf_p->resize (buf_p->size () + repeat);
9845 buf = buf_p->data ();
9846 }
9847
9848 memset (&buf[bc], buf[bc - 1], repeat);
9849 bc += repeat;
9850 continue;
9851 }
9852
9853 buf[bc] = '\0';
9854 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9855 return -1;
9856 }
9857 default:
9858 if (bc >= buf_p->size () - 1)
9859 {
9860 /* Make some more room in the buffer. */
9861 buf_p->resize (buf_p->size () * 2);
9862 buf = buf_p->data ();
9863 }
9864
9865 buf[bc++] = c;
9866 csum += c;
9867 continue;
9868 }
9869 }
9870 }
9871
9872 /* Set this to the maximum number of seconds to wait instead of waiting forever
9873 in target_wait(). If this timer times out, then it generates an error and
9874 the command is aborted. This replaces most of the need for timeouts in the
9875 GDB test suite, and makes it possible to distinguish between a hung target
9876 and one with slow communications. */
9877
9878 static int watchdog = 0;
9879 static void
9880 show_watchdog (struct ui_file *file, int from_tty,
9881 struct cmd_list_element *c, const char *value)
9882 {
9883 fprintf_filtered (file, _("Watchdog timer is %s.\n"), value);
9884 }
9885
9886 /* Read a packet from the remote machine, with error checking, and
9887 store it in *BUF. Resize *BUF if necessary to hold the result. If
9888 FOREVER, wait forever rather than timing out; this is used (in
9889 synchronous mode) to wait for a target that is is executing user
9890 code to stop. */
9891 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9892 don't have to change all the calls to getpkt to deal with the
9893 return value, because at the moment I don't know what the right
9894 thing to do it for those. */
9895
9896 void
9897 remote_target::getpkt (gdb::char_vector *buf, int forever)
9898 {
9899 getpkt_sane (buf, forever);
9900 }
9901
9902
9903 /* Read a packet from the remote machine, with error checking, and
9904 store it in *BUF. Resize *BUF if necessary to hold the result. If
9905 FOREVER, wait forever rather than timing out; this is used (in
9906 synchronous mode) to wait for a target that is is executing user
9907 code to stop. If FOREVER == 0, this function is allowed to time
9908 out gracefully and return an indication of this to the caller.
9909 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9910 consider receiving a notification enough reason to return to the
9911 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9912 holds a notification or not (a regular packet). */
9913
9914 int
9915 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9916 int forever, int expecting_notif,
9917 int *is_notif)
9918 {
9919 struct remote_state *rs = get_remote_state ();
9920 int c;
9921 int tries;
9922 int timeout;
9923 int val = -1;
9924
9925 /* We're reading a new response. Make sure we don't look at a
9926 previously cached response. */
9927 rs->cached_wait_status = 0;
9928
9929 strcpy (buf->data (), "timeout");
9930
9931 if (forever)
9932 timeout = watchdog > 0 ? watchdog : -1;
9933 else if (expecting_notif)
9934 timeout = 0; /* There should already be a char in the buffer. If
9935 not, bail out. */
9936 else
9937 timeout = remote_timeout;
9938
9939 #define MAX_TRIES 3
9940
9941 /* Process any number of notifications, and then return when
9942 we get a packet. */
9943 for (;;)
9944 {
9945 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9946 times. */
9947 for (tries = 1; tries <= MAX_TRIES; tries++)
9948 {
9949 /* This can loop forever if the remote side sends us
9950 characters continuously, but if it pauses, we'll get
9951 SERIAL_TIMEOUT from readchar because of timeout. Then
9952 we'll count that as a retry.
9953
9954 Note that even when forever is set, we will only wait
9955 forever prior to the start of a packet. After that, we
9956 expect characters to arrive at a brisk pace. They should
9957 show up within remote_timeout intervals. */
9958 do
9959 c = readchar (timeout);
9960 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9961
9962 if (c == SERIAL_TIMEOUT)
9963 {
9964 if (expecting_notif)
9965 return -1; /* Don't complain, it's normal to not get
9966 anything in this case. */
9967
9968 if (forever) /* Watchdog went off? Kill the target. */
9969 {
9970 remote_unpush_target (this);
9971 throw_error (TARGET_CLOSE_ERROR,
9972 _("Watchdog timeout has expired. "
9973 "Target detached."));
9974 }
9975
9976 remote_debug_printf ("Timed out.");
9977 }
9978 else
9979 {
9980 /* We've found the start of a packet or notification.
9981 Now collect the data. */
9982 val = read_frame (buf);
9983 if (val >= 0)
9984 break;
9985 }
9986
9987 remote_serial_write ("-", 1);
9988 }
9989
9990 if (tries > MAX_TRIES)
9991 {
9992 /* We have tried hard enough, and just can't receive the
9993 packet/notification. Give up. */
9994 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9995
9996 /* Skip the ack char if we're in no-ack mode. */
9997 if (!rs->noack_mode)
9998 remote_serial_write ("+", 1);
9999 return -1;
10000 }
10001
10002 /* If we got an ordinary packet, return that to our caller. */
10003 if (c == '$')
10004 {
10005 if (remote_debug)
10006 {
10007 int max_chars;
10008
10009 if (remote_packet_max_chars < 0)
10010 max_chars = val;
10011 else
10012 max_chars = remote_packet_max_chars;
10013
10014 std::string str
10015 = escape_buffer (buf->data (),
10016 std::min (val, max_chars));
10017
10018 if (val > max_chars)
10019 remote_debug_printf_nofunc
10020 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10021 val - max_chars);
10022 else
10023 remote_debug_printf_nofunc ("Packet received: %s",
10024 str.c_str ());
10025 }
10026
10027 /* Skip the ack char if we're in no-ack mode. */
10028 if (!rs->noack_mode)
10029 remote_serial_write ("+", 1);
10030 if (is_notif != NULL)
10031 *is_notif = 0;
10032 return val;
10033 }
10034
10035 /* If we got a notification, handle it, and go back to looking
10036 for a packet. */
10037 else
10038 {
10039 gdb_assert (c == '%');
10040
10041 remote_debug_printf_nofunc
10042 (" Notification received: %s",
10043 escape_buffer (buf->data (), val).c_str ());
10044
10045 if (is_notif != NULL)
10046 *is_notif = 1;
10047
10048 handle_notification (rs->notif_state, buf->data ());
10049
10050 /* Notifications require no acknowledgement. */
10051
10052 if (expecting_notif)
10053 return val;
10054 }
10055 }
10056 }
10057
10058 int
10059 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10060 {
10061 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10062 }
10063
10064 int
10065 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10066 int *is_notif)
10067 {
10068 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10069 }
10070
10071 /* Kill any new fork children of process PID that haven't been
10072 processed by follow_fork. */
10073
10074 void
10075 remote_target::kill_new_fork_children (int pid)
10076 {
10077 remote_state *rs = get_remote_state ();
10078 struct notif_client *notif = &notif_client_stop;
10079
10080 /* Kill the fork child threads of any threads in process PID
10081 that are stopped at a fork event. */
10082 for (thread_info *thread : all_non_exited_threads (this))
10083 {
10084 const target_waitstatus &ws = thread->pending_follow;
10085
10086 if (is_pending_fork_parent (ws, pid, thread->ptid))
10087 {
10088 int child_pid = ws.child_ptid ().pid ();
10089 int res;
10090
10091 res = remote_vkill (child_pid);
10092 if (res != 0)
10093 error (_("Can't kill fork child process %d"), child_pid);
10094 }
10095 }
10096
10097 /* Check for any pending fork events (not reported or processed yet)
10098 in process PID and kill those fork child threads as well. */
10099 remote_notif_get_pending_events (notif);
10100 for (auto &event : rs->stop_reply_queue)
10101 if (is_pending_fork_parent (event->ws, pid, event->ptid))
10102 {
10103 int child_pid = event->ws.child_ptid ().pid ();
10104 int res;
10105
10106 res = remote_vkill (child_pid);
10107 if (res != 0)
10108 error (_("Can't kill fork child process %d"), child_pid);
10109 }
10110 }
10111
10112 \f
10113 /* Target hook to kill the current inferior. */
10114
10115 void
10116 remote_target::kill ()
10117 {
10118 int res = -1;
10119 int pid = inferior_ptid.pid ();
10120 struct remote_state *rs = get_remote_state ();
10121
10122 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
10123 {
10124 /* If we're stopped while forking and we haven't followed yet,
10125 kill the child task. We need to do this before killing the
10126 parent task because if this is a vfork then the parent will
10127 be sleeping. */
10128 kill_new_fork_children (pid);
10129
10130 res = remote_vkill (pid);
10131 if (res == 0)
10132 {
10133 target_mourn_inferior (inferior_ptid);
10134 return;
10135 }
10136 }
10137
10138 /* If we are in 'target remote' mode and we are killing the only
10139 inferior, then we will tell gdbserver to exit and unpush the
10140 target. */
10141 if (res == -1 && !remote_multi_process_p (rs)
10142 && number_of_live_inferiors (this) == 1)
10143 {
10144 remote_kill_k ();
10145
10146 /* We've killed the remote end, we get to mourn it. If we are
10147 not in extended mode, mourning the inferior also unpushes
10148 remote_ops from the target stack, which closes the remote
10149 connection. */
10150 target_mourn_inferior (inferior_ptid);
10151
10152 return;
10153 }
10154
10155 error (_("Can't kill process"));
10156 }
10157
10158 /* Send a kill request to the target using the 'vKill' packet. */
10159
10160 int
10161 remote_target::remote_vkill (int pid)
10162 {
10163 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10164 return -1;
10165
10166 remote_state *rs = get_remote_state ();
10167
10168 /* Tell the remote target to detach. */
10169 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10170 putpkt (rs->buf);
10171 getpkt (&rs->buf, 0);
10172
10173 switch (packet_ok (rs->buf,
10174 &remote_protocol_packets[PACKET_vKill]))
10175 {
10176 case PACKET_OK:
10177 return 0;
10178 case PACKET_ERROR:
10179 return 1;
10180 case PACKET_UNKNOWN:
10181 return -1;
10182 default:
10183 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10184 }
10185 }
10186
10187 /* Send a kill request to the target using the 'k' packet. */
10188
10189 void
10190 remote_target::remote_kill_k ()
10191 {
10192 /* Catch errors so the user can quit from gdb even when we
10193 aren't on speaking terms with the remote system. */
10194 try
10195 {
10196 putpkt ("k");
10197 }
10198 catch (const gdb_exception_error &ex)
10199 {
10200 if (ex.error == TARGET_CLOSE_ERROR)
10201 {
10202 /* If we got an (EOF) error that caused the target
10203 to go away, then we're done, that's what we wanted.
10204 "k" is susceptible to cause a premature EOF, given
10205 that the remote server isn't actually required to
10206 reply to "k", and it can happen that it doesn't
10207 even get to reply ACK to the "k". */
10208 return;
10209 }
10210
10211 /* Otherwise, something went wrong. We didn't actually kill
10212 the target. Just propagate the exception, and let the
10213 user or higher layers decide what to do. */
10214 throw;
10215 }
10216 }
10217
10218 void
10219 remote_target::mourn_inferior ()
10220 {
10221 struct remote_state *rs = get_remote_state ();
10222
10223 /* We're no longer interested in notification events of an inferior
10224 that exited or was killed/detached. */
10225 discard_pending_stop_replies (current_inferior ());
10226
10227 /* In 'target remote' mode with one inferior, we close the connection. */
10228 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10229 {
10230 remote_unpush_target (this);
10231 return;
10232 }
10233
10234 /* In case we got here due to an error, but we're going to stay
10235 connected. */
10236 rs->waiting_for_stop_reply = 0;
10237
10238 /* If the current general thread belonged to the process we just
10239 detached from or has exited, the remote side current general
10240 thread becomes undefined. Considering a case like this:
10241
10242 - We just got here due to a detach.
10243 - The process that we're detaching from happens to immediately
10244 report a global breakpoint being hit in non-stop mode, in the
10245 same thread we had selected before.
10246 - GDB attaches to this process again.
10247 - This event happens to be the next event we handle.
10248
10249 GDB would consider that the current general thread didn't need to
10250 be set on the stub side (with Hg), since for all it knew,
10251 GENERAL_THREAD hadn't changed.
10252
10253 Notice that although in all-stop mode, the remote server always
10254 sets the current thread to the thread reporting the stop event,
10255 that doesn't happen in non-stop mode; in non-stop, the stub *must
10256 not* change the current thread when reporting a breakpoint hit,
10257 due to the decoupling of event reporting and event handling.
10258
10259 To keep things simple, we always invalidate our notion of the
10260 current thread. */
10261 record_currthread (rs, minus_one_ptid);
10262
10263 /* Call common code to mark the inferior as not running. */
10264 generic_mourn_inferior ();
10265 }
10266
10267 bool
10268 extended_remote_target::supports_disable_randomization ()
10269 {
10270 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10271 }
10272
10273 void
10274 remote_target::extended_remote_disable_randomization (int val)
10275 {
10276 struct remote_state *rs = get_remote_state ();
10277 char *reply;
10278
10279 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10280 "QDisableRandomization:%x", val);
10281 putpkt (rs->buf);
10282 reply = remote_get_noisy_reply ();
10283 if (*reply == '\0')
10284 error (_("Target does not support QDisableRandomization."));
10285 if (strcmp (reply, "OK") != 0)
10286 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10287 }
10288
10289 int
10290 remote_target::extended_remote_run (const std::string &args)
10291 {
10292 struct remote_state *rs = get_remote_state ();
10293 int len;
10294 const char *remote_exec_file = get_remote_exec_file ();
10295
10296 /* If the user has disabled vRun support, or we have detected that
10297 support is not available, do not try it. */
10298 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10299 return -1;
10300
10301 strcpy (rs->buf.data (), "vRun;");
10302 len = strlen (rs->buf.data ());
10303
10304 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10305 error (_("Remote file name too long for run packet"));
10306 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10307 strlen (remote_exec_file));
10308
10309 if (!args.empty ())
10310 {
10311 int i;
10312
10313 gdb_argv argv (args.c_str ());
10314 for (i = 0; argv[i] != NULL; i++)
10315 {
10316 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10317 error (_("Argument list too long for run packet"));
10318 rs->buf[len++] = ';';
10319 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10320 strlen (argv[i]));
10321 }
10322 }
10323
10324 rs->buf[len++] = '\0';
10325
10326 putpkt (rs->buf);
10327 getpkt (&rs->buf, 0);
10328
10329 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10330 {
10331 case PACKET_OK:
10332 /* We have a wait response. All is well. */
10333 return 0;
10334 case PACKET_UNKNOWN:
10335 return -1;
10336 case PACKET_ERROR:
10337 if (remote_exec_file[0] == '\0')
10338 error (_("Running the default executable on the remote target failed; "
10339 "try \"set remote exec-file\"?"));
10340 else
10341 error (_("Running \"%s\" on the remote target failed"),
10342 remote_exec_file);
10343 default:
10344 gdb_assert_not_reached ("bad switch");
10345 }
10346 }
10347
10348 /* Helper function to send set/unset environment packets. ACTION is
10349 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10350 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10351 sent. */
10352
10353 void
10354 remote_target::send_environment_packet (const char *action,
10355 const char *packet,
10356 const char *value)
10357 {
10358 remote_state *rs = get_remote_state ();
10359
10360 /* Convert the environment variable to an hex string, which
10361 is the best format to be transmitted over the wire. */
10362 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10363 strlen (value));
10364
10365 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10366 "%s:%s", packet, encoded_value.c_str ());
10367
10368 putpkt (rs->buf);
10369 getpkt (&rs->buf, 0);
10370 if (strcmp (rs->buf.data (), "OK") != 0)
10371 warning (_("Unable to %s environment variable '%s' on remote."),
10372 action, value);
10373 }
10374
10375 /* Helper function to handle the QEnvironment* packets. */
10376
10377 void
10378 remote_target::extended_remote_environment_support ()
10379 {
10380 remote_state *rs = get_remote_state ();
10381
10382 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10383 {
10384 putpkt ("QEnvironmentReset");
10385 getpkt (&rs->buf, 0);
10386 if (strcmp (rs->buf.data (), "OK") != 0)
10387 warning (_("Unable to reset environment on remote."));
10388 }
10389
10390 gdb_environ *e = &current_inferior ()->environment;
10391
10392 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10393 for (const std::string &el : e->user_set_env ())
10394 send_environment_packet ("set", "QEnvironmentHexEncoded",
10395 el.c_str ());
10396
10397 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10398 for (const std::string &el : e->user_unset_env ())
10399 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10400 }
10401
10402 /* Helper function to set the current working directory for the
10403 inferior in the remote target. */
10404
10405 void
10406 remote_target::extended_remote_set_inferior_cwd ()
10407 {
10408 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10409 {
10410 const std::string &inferior_cwd = current_inferior ()->cwd ();
10411 remote_state *rs = get_remote_state ();
10412
10413 if (!inferior_cwd.empty ())
10414 {
10415 std::string hexpath
10416 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10417 inferior_cwd.size ());
10418
10419 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10420 "QSetWorkingDir:%s", hexpath.c_str ());
10421 }
10422 else
10423 {
10424 /* An empty inferior_cwd means that the user wants us to
10425 reset the remote server's inferior's cwd. */
10426 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10427 "QSetWorkingDir:");
10428 }
10429
10430 putpkt (rs->buf);
10431 getpkt (&rs->buf, 0);
10432 if (packet_ok (rs->buf,
10433 &remote_protocol_packets[PACKET_QSetWorkingDir])
10434 != PACKET_OK)
10435 error (_("\
10436 Remote replied unexpectedly while setting the inferior's working\n\
10437 directory: %s"),
10438 rs->buf.data ());
10439
10440 }
10441 }
10442
10443 /* In the extended protocol we want to be able to do things like
10444 "run" and have them basically work as expected. So we need
10445 a special create_inferior function. We support changing the
10446 executable file and the command line arguments, but not the
10447 environment. */
10448
10449 void
10450 extended_remote_target::create_inferior (const char *exec_file,
10451 const std::string &args,
10452 char **env, int from_tty)
10453 {
10454 int run_worked;
10455 char *stop_reply;
10456 struct remote_state *rs = get_remote_state ();
10457 const char *remote_exec_file = get_remote_exec_file ();
10458
10459 /* If running asynchronously, register the target file descriptor
10460 with the event loop. */
10461 if (target_can_async_p ())
10462 target_async (1);
10463
10464 /* Disable address space randomization if requested (and supported). */
10465 if (supports_disable_randomization ())
10466 extended_remote_disable_randomization (disable_randomization);
10467
10468 /* If startup-with-shell is on, we inform gdbserver to start the
10469 remote inferior using a shell. */
10470 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10471 {
10472 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10473 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10474 putpkt (rs->buf);
10475 getpkt (&rs->buf, 0);
10476 if (strcmp (rs->buf.data (), "OK") != 0)
10477 error (_("\
10478 Remote replied unexpectedly while setting startup-with-shell: %s"),
10479 rs->buf.data ());
10480 }
10481
10482 extended_remote_environment_support ();
10483
10484 extended_remote_set_inferior_cwd ();
10485
10486 /* Now restart the remote server. */
10487 run_worked = extended_remote_run (args) != -1;
10488 if (!run_worked)
10489 {
10490 /* vRun was not supported. Fail if we need it to do what the
10491 user requested. */
10492 if (remote_exec_file[0])
10493 error (_("Remote target does not support \"set remote exec-file\""));
10494 if (!args.empty ())
10495 error (_("Remote target does not support \"set args\" or run ARGS"));
10496
10497 /* Fall back to "R". */
10498 extended_remote_restart ();
10499 }
10500
10501 /* vRun's success return is a stop reply. */
10502 stop_reply = run_worked ? rs->buf.data () : NULL;
10503 add_current_inferior_and_thread (stop_reply);
10504
10505 /* Get updated offsets, if the stub uses qOffsets. */
10506 get_offsets ();
10507 }
10508 \f
10509
10510 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10511 the list of conditions (in agent expression bytecode format), if any, the
10512 target needs to evaluate. The output is placed into the packet buffer
10513 started from BUF and ended at BUF_END. */
10514
10515 static int
10516 remote_add_target_side_condition (struct gdbarch *gdbarch,
10517 struct bp_target_info *bp_tgt, char *buf,
10518 char *buf_end)
10519 {
10520 if (bp_tgt->conditions.empty ())
10521 return 0;
10522
10523 buf += strlen (buf);
10524 xsnprintf (buf, buf_end - buf, "%s", ";");
10525 buf++;
10526
10527 /* Send conditions to the target. */
10528 for (agent_expr *aexpr : bp_tgt->conditions)
10529 {
10530 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10531 buf += strlen (buf);
10532 for (int i = 0; i < aexpr->len; ++i)
10533 buf = pack_hex_byte (buf, aexpr->buf[i]);
10534 *buf = '\0';
10535 }
10536 return 0;
10537 }
10538
10539 static void
10540 remote_add_target_side_commands (struct gdbarch *gdbarch,
10541 struct bp_target_info *bp_tgt, char *buf)
10542 {
10543 if (bp_tgt->tcommands.empty ())
10544 return;
10545
10546 buf += strlen (buf);
10547
10548 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10549 buf += strlen (buf);
10550
10551 /* Concatenate all the agent expressions that are commands into the
10552 cmds parameter. */
10553 for (agent_expr *aexpr : bp_tgt->tcommands)
10554 {
10555 sprintf (buf, "X%x,", aexpr->len);
10556 buf += strlen (buf);
10557 for (int i = 0; i < aexpr->len; ++i)
10558 buf = pack_hex_byte (buf, aexpr->buf[i]);
10559 *buf = '\0';
10560 }
10561 }
10562
10563 /* Insert a breakpoint. On targets that have software breakpoint
10564 support, we ask the remote target to do the work; on targets
10565 which don't, we insert a traditional memory breakpoint. */
10566
10567 int
10568 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10569 struct bp_target_info *bp_tgt)
10570 {
10571 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10572 If it succeeds, then set the support to PACKET_ENABLE. If it
10573 fails, and the user has explicitly requested the Z support then
10574 report an error, otherwise, mark it disabled and go on. */
10575
10576 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10577 {
10578 CORE_ADDR addr = bp_tgt->reqstd_address;
10579 struct remote_state *rs;
10580 char *p, *endbuf;
10581
10582 /* Make sure the remote is pointing at the right process, if
10583 necessary. */
10584 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10585 set_general_process ();
10586
10587 rs = get_remote_state ();
10588 p = rs->buf.data ();
10589 endbuf = p + get_remote_packet_size ();
10590
10591 *(p++) = 'Z';
10592 *(p++) = '0';
10593 *(p++) = ',';
10594 addr = (ULONGEST) remote_address_masked (addr);
10595 p += hexnumstr (p, addr);
10596 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10597
10598 if (supports_evaluation_of_breakpoint_conditions ())
10599 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10600
10601 if (can_run_breakpoint_commands ())
10602 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10603
10604 putpkt (rs->buf);
10605 getpkt (&rs->buf, 0);
10606
10607 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10608 {
10609 case PACKET_ERROR:
10610 return -1;
10611 case PACKET_OK:
10612 return 0;
10613 case PACKET_UNKNOWN:
10614 break;
10615 }
10616 }
10617
10618 /* If this breakpoint has target-side commands but this stub doesn't
10619 support Z0 packets, throw error. */
10620 if (!bp_tgt->tcommands.empty ())
10621 throw_error (NOT_SUPPORTED_ERROR, _("\
10622 Target doesn't support breakpoints that have target side commands."));
10623
10624 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10625 }
10626
10627 int
10628 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10629 struct bp_target_info *bp_tgt,
10630 enum remove_bp_reason reason)
10631 {
10632 CORE_ADDR addr = bp_tgt->placed_address;
10633 struct remote_state *rs = get_remote_state ();
10634
10635 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10636 {
10637 char *p = rs->buf.data ();
10638 char *endbuf = p + get_remote_packet_size ();
10639
10640 /* Make sure the remote is pointing at the right process, if
10641 necessary. */
10642 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10643 set_general_process ();
10644
10645 *(p++) = 'z';
10646 *(p++) = '0';
10647 *(p++) = ',';
10648
10649 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10650 p += hexnumstr (p, addr);
10651 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10652
10653 putpkt (rs->buf);
10654 getpkt (&rs->buf, 0);
10655
10656 return (rs->buf[0] == 'E');
10657 }
10658
10659 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10660 }
10661
10662 static enum Z_packet_type
10663 watchpoint_to_Z_packet (int type)
10664 {
10665 switch (type)
10666 {
10667 case hw_write:
10668 return Z_PACKET_WRITE_WP;
10669 break;
10670 case hw_read:
10671 return Z_PACKET_READ_WP;
10672 break;
10673 case hw_access:
10674 return Z_PACKET_ACCESS_WP;
10675 break;
10676 default:
10677 internal_error (__FILE__, __LINE__,
10678 _("hw_bp_to_z: bad watchpoint type %d"), type);
10679 }
10680 }
10681
10682 int
10683 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10684 enum target_hw_bp_type type, struct expression *cond)
10685 {
10686 struct remote_state *rs = get_remote_state ();
10687 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10688 char *p;
10689 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10690
10691 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10692 return 1;
10693
10694 /* Make sure the remote is pointing at the right process, if
10695 necessary. */
10696 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10697 set_general_process ();
10698
10699 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10700 p = strchr (rs->buf.data (), '\0');
10701 addr = remote_address_masked (addr);
10702 p += hexnumstr (p, (ULONGEST) addr);
10703 xsnprintf (p, endbuf - p, ",%x", len);
10704
10705 putpkt (rs->buf);
10706 getpkt (&rs->buf, 0);
10707
10708 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10709 {
10710 case PACKET_ERROR:
10711 return -1;
10712 case PACKET_UNKNOWN:
10713 return 1;
10714 case PACKET_OK:
10715 return 0;
10716 }
10717 internal_error (__FILE__, __LINE__,
10718 _("remote_insert_watchpoint: reached end of function"));
10719 }
10720
10721 bool
10722 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10723 CORE_ADDR start, int length)
10724 {
10725 CORE_ADDR diff = remote_address_masked (addr - start);
10726
10727 return diff < length;
10728 }
10729
10730
10731 int
10732 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10733 enum target_hw_bp_type type, struct expression *cond)
10734 {
10735 struct remote_state *rs = get_remote_state ();
10736 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10737 char *p;
10738 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10739
10740 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10741 return -1;
10742
10743 /* Make sure the remote is pointing at the right process, if
10744 necessary. */
10745 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10746 set_general_process ();
10747
10748 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10749 p = strchr (rs->buf.data (), '\0');
10750 addr = remote_address_masked (addr);
10751 p += hexnumstr (p, (ULONGEST) addr);
10752 xsnprintf (p, endbuf - p, ",%x", len);
10753 putpkt (rs->buf);
10754 getpkt (&rs->buf, 0);
10755
10756 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10757 {
10758 case PACKET_ERROR:
10759 case PACKET_UNKNOWN:
10760 return -1;
10761 case PACKET_OK:
10762 return 0;
10763 }
10764 internal_error (__FILE__, __LINE__,
10765 _("remote_remove_watchpoint: reached end of function"));
10766 }
10767
10768
10769 static int remote_hw_watchpoint_limit = -1;
10770 static int remote_hw_watchpoint_length_limit = -1;
10771 static int remote_hw_breakpoint_limit = -1;
10772
10773 int
10774 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10775 {
10776 if (remote_hw_watchpoint_length_limit == 0)
10777 return 0;
10778 else if (remote_hw_watchpoint_length_limit < 0)
10779 return 1;
10780 else if (len <= remote_hw_watchpoint_length_limit)
10781 return 1;
10782 else
10783 return 0;
10784 }
10785
10786 int
10787 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10788 {
10789 if (type == bp_hardware_breakpoint)
10790 {
10791 if (remote_hw_breakpoint_limit == 0)
10792 return 0;
10793 else if (remote_hw_breakpoint_limit < 0)
10794 return 1;
10795 else if (cnt <= remote_hw_breakpoint_limit)
10796 return 1;
10797 }
10798 else
10799 {
10800 if (remote_hw_watchpoint_limit == 0)
10801 return 0;
10802 else if (remote_hw_watchpoint_limit < 0)
10803 return 1;
10804 else if (ot)
10805 return -1;
10806 else if (cnt <= remote_hw_watchpoint_limit)
10807 return 1;
10808 }
10809 return -1;
10810 }
10811
10812 /* The to_stopped_by_sw_breakpoint method of target remote. */
10813
10814 bool
10815 remote_target::stopped_by_sw_breakpoint ()
10816 {
10817 struct thread_info *thread = inferior_thread ();
10818
10819 return (thread->priv != NULL
10820 && (get_remote_thread_info (thread)->stop_reason
10821 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10822 }
10823
10824 /* The to_supports_stopped_by_sw_breakpoint method of target
10825 remote. */
10826
10827 bool
10828 remote_target::supports_stopped_by_sw_breakpoint ()
10829 {
10830 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10831 }
10832
10833 /* The to_stopped_by_hw_breakpoint method of target remote. */
10834
10835 bool
10836 remote_target::stopped_by_hw_breakpoint ()
10837 {
10838 struct thread_info *thread = inferior_thread ();
10839
10840 return (thread->priv != NULL
10841 && (get_remote_thread_info (thread)->stop_reason
10842 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10843 }
10844
10845 /* The to_supports_stopped_by_hw_breakpoint method of target
10846 remote. */
10847
10848 bool
10849 remote_target::supports_stopped_by_hw_breakpoint ()
10850 {
10851 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10852 }
10853
10854 bool
10855 remote_target::stopped_by_watchpoint ()
10856 {
10857 struct thread_info *thread = inferior_thread ();
10858
10859 return (thread->priv != NULL
10860 && (get_remote_thread_info (thread)->stop_reason
10861 == TARGET_STOPPED_BY_WATCHPOINT));
10862 }
10863
10864 bool
10865 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10866 {
10867 struct thread_info *thread = inferior_thread ();
10868
10869 if (thread->priv != NULL
10870 && (get_remote_thread_info (thread)->stop_reason
10871 == TARGET_STOPPED_BY_WATCHPOINT))
10872 {
10873 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10874 return true;
10875 }
10876
10877 return false;
10878 }
10879
10880
10881 int
10882 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10883 struct bp_target_info *bp_tgt)
10884 {
10885 CORE_ADDR addr = bp_tgt->reqstd_address;
10886 struct remote_state *rs;
10887 char *p, *endbuf;
10888 char *message;
10889
10890 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10891 return -1;
10892
10893 /* Make sure the remote is pointing at the right process, if
10894 necessary. */
10895 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10896 set_general_process ();
10897
10898 rs = get_remote_state ();
10899 p = rs->buf.data ();
10900 endbuf = p + get_remote_packet_size ();
10901
10902 *(p++) = 'Z';
10903 *(p++) = '1';
10904 *(p++) = ',';
10905
10906 addr = remote_address_masked (addr);
10907 p += hexnumstr (p, (ULONGEST) addr);
10908 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10909
10910 if (supports_evaluation_of_breakpoint_conditions ())
10911 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10912
10913 if (can_run_breakpoint_commands ())
10914 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10915
10916 putpkt (rs->buf);
10917 getpkt (&rs->buf, 0);
10918
10919 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10920 {
10921 case PACKET_ERROR:
10922 if (rs->buf[1] == '.')
10923 {
10924 message = strchr (&rs->buf[2], '.');
10925 if (message)
10926 error (_("Remote failure reply: %s"), message + 1);
10927 }
10928 return -1;
10929 case PACKET_UNKNOWN:
10930 return -1;
10931 case PACKET_OK:
10932 return 0;
10933 }
10934 internal_error (__FILE__, __LINE__,
10935 _("remote_insert_hw_breakpoint: reached end of function"));
10936 }
10937
10938
10939 int
10940 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10941 struct bp_target_info *bp_tgt)
10942 {
10943 CORE_ADDR addr;
10944 struct remote_state *rs = get_remote_state ();
10945 char *p = rs->buf.data ();
10946 char *endbuf = p + get_remote_packet_size ();
10947
10948 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10949 return -1;
10950
10951 /* Make sure the remote is pointing at the right process, if
10952 necessary. */
10953 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10954 set_general_process ();
10955
10956 *(p++) = 'z';
10957 *(p++) = '1';
10958 *(p++) = ',';
10959
10960 addr = remote_address_masked (bp_tgt->placed_address);
10961 p += hexnumstr (p, (ULONGEST) addr);
10962 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10963
10964 putpkt (rs->buf);
10965 getpkt (&rs->buf, 0);
10966
10967 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10968 {
10969 case PACKET_ERROR:
10970 case PACKET_UNKNOWN:
10971 return -1;
10972 case PACKET_OK:
10973 return 0;
10974 }
10975 internal_error (__FILE__, __LINE__,
10976 _("remote_remove_hw_breakpoint: reached end of function"));
10977 }
10978
10979 /* Verify memory using the "qCRC:" request. */
10980
10981 int
10982 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10983 {
10984 struct remote_state *rs = get_remote_state ();
10985 unsigned long host_crc, target_crc;
10986 char *tmp;
10987
10988 /* It doesn't make sense to use qCRC if the remote target is
10989 connected but not running. */
10990 if (target_has_execution ()
10991 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10992 {
10993 enum packet_result result;
10994
10995 /* Make sure the remote is pointing at the right process. */
10996 set_general_process ();
10997
10998 /* FIXME: assumes lma can fit into long. */
10999 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11000 (long) lma, (long) size);
11001 putpkt (rs->buf);
11002
11003 /* Be clever; compute the host_crc before waiting for target
11004 reply. */
11005 host_crc = xcrc32 (data, size, 0xffffffff);
11006
11007 getpkt (&rs->buf, 0);
11008
11009 result = packet_ok (rs->buf,
11010 &remote_protocol_packets[PACKET_qCRC]);
11011 if (result == PACKET_ERROR)
11012 return -1;
11013 else if (result == PACKET_OK)
11014 {
11015 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11016 target_crc = target_crc * 16 + fromhex (*tmp);
11017
11018 return (host_crc == target_crc);
11019 }
11020 }
11021
11022 return simple_verify_memory (this, data, lma, size);
11023 }
11024
11025 /* compare-sections command
11026
11027 With no arguments, compares each loadable section in the exec bfd
11028 with the same memory range on the target, and reports mismatches.
11029 Useful for verifying the image on the target against the exec file. */
11030
11031 static void
11032 compare_sections_command (const char *args, int from_tty)
11033 {
11034 asection *s;
11035 const char *sectname;
11036 bfd_size_type size;
11037 bfd_vma lma;
11038 int matched = 0;
11039 int mismatched = 0;
11040 int res;
11041 int read_only = 0;
11042
11043 if (!current_program_space->exec_bfd ())
11044 error (_("command cannot be used without an exec file"));
11045
11046 if (args != NULL && strcmp (args, "-r") == 0)
11047 {
11048 read_only = 1;
11049 args = NULL;
11050 }
11051
11052 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11053 {
11054 if (!(s->flags & SEC_LOAD))
11055 continue; /* Skip non-loadable section. */
11056
11057 if (read_only && (s->flags & SEC_READONLY) == 0)
11058 continue; /* Skip writeable sections */
11059
11060 size = bfd_section_size (s);
11061 if (size == 0)
11062 continue; /* Skip zero-length section. */
11063
11064 sectname = bfd_section_name (s);
11065 if (args && strcmp (args, sectname) != 0)
11066 continue; /* Not the section selected by user. */
11067
11068 matched = 1; /* Do this section. */
11069 lma = s->lma;
11070
11071 gdb::byte_vector sectdata (size);
11072 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11073 sectdata.data (), 0, size);
11074
11075 res = target_verify_memory (sectdata.data (), lma, size);
11076
11077 if (res == -1)
11078 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11079 paddress (target_gdbarch (), lma),
11080 paddress (target_gdbarch (), lma + size));
11081
11082 printf_filtered ("Section %s, range %s -- %s: ", sectname,
11083 paddress (target_gdbarch (), lma),
11084 paddress (target_gdbarch (), lma + size));
11085 if (res)
11086 printf_filtered ("matched.\n");
11087 else
11088 {
11089 printf_filtered ("MIS-MATCHED!\n");
11090 mismatched++;
11091 }
11092 }
11093 if (mismatched > 0)
11094 warning (_("One or more sections of the target image does not match\n\
11095 the loaded file\n"));
11096 if (args && !matched)
11097 printf_filtered (_("No loaded section named '%s'.\n"), args);
11098 }
11099
11100 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11101 into remote target. The number of bytes written to the remote
11102 target is returned, or -1 for error. */
11103
11104 target_xfer_status
11105 remote_target::remote_write_qxfer (const char *object_name,
11106 const char *annex, const gdb_byte *writebuf,
11107 ULONGEST offset, LONGEST len,
11108 ULONGEST *xfered_len,
11109 struct packet_config *packet)
11110 {
11111 int i, buf_len;
11112 ULONGEST n;
11113 struct remote_state *rs = get_remote_state ();
11114 int max_size = get_memory_write_packet_size ();
11115
11116 if (packet_config_support (packet) == PACKET_DISABLE)
11117 return TARGET_XFER_E_IO;
11118
11119 /* Insert header. */
11120 i = snprintf (rs->buf.data (), max_size,
11121 "qXfer:%s:write:%s:%s:",
11122 object_name, annex ? annex : "",
11123 phex_nz (offset, sizeof offset));
11124 max_size -= (i + 1);
11125
11126 /* Escape as much data as fits into rs->buf. */
11127 buf_len = remote_escape_output
11128 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11129
11130 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11131 || getpkt_sane (&rs->buf, 0) < 0
11132 || packet_ok (rs->buf, packet) != PACKET_OK)
11133 return TARGET_XFER_E_IO;
11134
11135 unpack_varlen_hex (rs->buf.data (), &n);
11136
11137 *xfered_len = n;
11138 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11139 }
11140
11141 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11142 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11143 number of bytes read is returned, or 0 for EOF, or -1 for error.
11144 The number of bytes read may be less than LEN without indicating an
11145 EOF. PACKET is checked and updated to indicate whether the remote
11146 target supports this object. */
11147
11148 target_xfer_status
11149 remote_target::remote_read_qxfer (const char *object_name,
11150 const char *annex,
11151 gdb_byte *readbuf, ULONGEST offset,
11152 LONGEST len,
11153 ULONGEST *xfered_len,
11154 struct packet_config *packet)
11155 {
11156 struct remote_state *rs = get_remote_state ();
11157 LONGEST i, n, packet_len;
11158
11159 if (packet_config_support (packet) == PACKET_DISABLE)
11160 return TARGET_XFER_E_IO;
11161
11162 /* Check whether we've cached an end-of-object packet that matches
11163 this request. */
11164 if (rs->finished_object)
11165 {
11166 if (strcmp (object_name, rs->finished_object) == 0
11167 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11168 && offset == rs->finished_offset)
11169 return TARGET_XFER_EOF;
11170
11171
11172 /* Otherwise, we're now reading something different. Discard
11173 the cache. */
11174 xfree (rs->finished_object);
11175 xfree (rs->finished_annex);
11176 rs->finished_object = NULL;
11177 rs->finished_annex = NULL;
11178 }
11179
11180 /* Request only enough to fit in a single packet. The actual data
11181 may not, since we don't know how much of it will need to be escaped;
11182 the target is free to respond with slightly less data. We subtract
11183 five to account for the response type and the protocol frame. */
11184 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11185 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11186 "qXfer:%s:read:%s:%s,%s",
11187 object_name, annex ? annex : "",
11188 phex_nz (offset, sizeof offset),
11189 phex_nz (n, sizeof n));
11190 i = putpkt (rs->buf);
11191 if (i < 0)
11192 return TARGET_XFER_E_IO;
11193
11194 rs->buf[0] = '\0';
11195 packet_len = getpkt_sane (&rs->buf, 0);
11196 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
11197 return TARGET_XFER_E_IO;
11198
11199 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11200 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11201
11202 /* 'm' means there is (or at least might be) more data after this
11203 batch. That does not make sense unless there's at least one byte
11204 of data in this reply. */
11205 if (rs->buf[0] == 'm' && packet_len == 1)
11206 error (_("Remote qXfer reply contained no data."));
11207
11208 /* Got some data. */
11209 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11210 packet_len - 1, readbuf, n);
11211
11212 /* 'l' is an EOF marker, possibly including a final block of data,
11213 or possibly empty. If we have the final block of a non-empty
11214 object, record this fact to bypass a subsequent partial read. */
11215 if (rs->buf[0] == 'l' && offset + i > 0)
11216 {
11217 rs->finished_object = xstrdup (object_name);
11218 rs->finished_annex = xstrdup (annex ? annex : "");
11219 rs->finished_offset = offset + i;
11220 }
11221
11222 if (i == 0)
11223 return TARGET_XFER_EOF;
11224 else
11225 {
11226 *xfered_len = i;
11227 return TARGET_XFER_OK;
11228 }
11229 }
11230
11231 enum target_xfer_status
11232 remote_target::xfer_partial (enum target_object object,
11233 const char *annex, gdb_byte *readbuf,
11234 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11235 ULONGEST *xfered_len)
11236 {
11237 struct remote_state *rs;
11238 int i;
11239 char *p2;
11240 char query_type;
11241 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11242
11243 set_remote_traceframe ();
11244 set_general_thread (inferior_ptid);
11245
11246 rs = get_remote_state ();
11247
11248 /* Handle memory using the standard memory routines. */
11249 if (object == TARGET_OBJECT_MEMORY)
11250 {
11251 /* If the remote target is connected but not running, we should
11252 pass this request down to a lower stratum (e.g. the executable
11253 file). */
11254 if (!target_has_execution ())
11255 return TARGET_XFER_EOF;
11256
11257 if (writebuf != NULL)
11258 return remote_write_bytes (offset, writebuf, len, unit_size,
11259 xfered_len);
11260 else
11261 return remote_read_bytes (offset, readbuf, len, unit_size,
11262 xfered_len);
11263 }
11264
11265 /* Handle extra signal info using qxfer packets. */
11266 if (object == TARGET_OBJECT_SIGNAL_INFO)
11267 {
11268 if (readbuf)
11269 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11270 xfered_len, &remote_protocol_packets
11271 [PACKET_qXfer_siginfo_read]);
11272 else
11273 return remote_write_qxfer ("siginfo", annex,
11274 writebuf, offset, len, xfered_len,
11275 &remote_protocol_packets
11276 [PACKET_qXfer_siginfo_write]);
11277 }
11278
11279 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11280 {
11281 if (readbuf)
11282 return remote_read_qxfer ("statictrace", annex,
11283 readbuf, offset, len, xfered_len,
11284 &remote_protocol_packets
11285 [PACKET_qXfer_statictrace_read]);
11286 else
11287 return TARGET_XFER_E_IO;
11288 }
11289
11290 /* Only handle flash writes. */
11291 if (writebuf != NULL)
11292 {
11293 switch (object)
11294 {
11295 case TARGET_OBJECT_FLASH:
11296 return remote_flash_write (offset, len, xfered_len,
11297 writebuf);
11298
11299 default:
11300 return TARGET_XFER_E_IO;
11301 }
11302 }
11303
11304 /* Map pre-existing objects onto letters. DO NOT do this for new
11305 objects!!! Instead specify new query packets. */
11306 switch (object)
11307 {
11308 case TARGET_OBJECT_AVR:
11309 query_type = 'R';
11310 break;
11311
11312 case TARGET_OBJECT_AUXV:
11313 gdb_assert (annex == NULL);
11314 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11315 xfered_len,
11316 &remote_protocol_packets[PACKET_qXfer_auxv]);
11317
11318 case TARGET_OBJECT_AVAILABLE_FEATURES:
11319 return remote_read_qxfer
11320 ("features", annex, readbuf, offset, len, xfered_len,
11321 &remote_protocol_packets[PACKET_qXfer_features]);
11322
11323 case TARGET_OBJECT_LIBRARIES:
11324 return remote_read_qxfer
11325 ("libraries", annex, readbuf, offset, len, xfered_len,
11326 &remote_protocol_packets[PACKET_qXfer_libraries]);
11327
11328 case TARGET_OBJECT_LIBRARIES_SVR4:
11329 return remote_read_qxfer
11330 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11331 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11332
11333 case TARGET_OBJECT_MEMORY_MAP:
11334 gdb_assert (annex == NULL);
11335 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11336 xfered_len,
11337 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11338
11339 case TARGET_OBJECT_OSDATA:
11340 /* Should only get here if we're connected. */
11341 gdb_assert (rs->remote_desc);
11342 return remote_read_qxfer
11343 ("osdata", annex, readbuf, offset, len, xfered_len,
11344 &remote_protocol_packets[PACKET_qXfer_osdata]);
11345
11346 case TARGET_OBJECT_THREADS:
11347 gdb_assert (annex == NULL);
11348 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11349 xfered_len,
11350 &remote_protocol_packets[PACKET_qXfer_threads]);
11351
11352 case TARGET_OBJECT_TRACEFRAME_INFO:
11353 gdb_assert (annex == NULL);
11354 return remote_read_qxfer
11355 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11356 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11357
11358 case TARGET_OBJECT_FDPIC:
11359 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11360 xfered_len,
11361 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11362
11363 case TARGET_OBJECT_OPENVMS_UIB:
11364 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11365 xfered_len,
11366 &remote_protocol_packets[PACKET_qXfer_uib]);
11367
11368 case TARGET_OBJECT_BTRACE:
11369 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11370 xfered_len,
11371 &remote_protocol_packets[PACKET_qXfer_btrace]);
11372
11373 case TARGET_OBJECT_BTRACE_CONF:
11374 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11375 len, xfered_len,
11376 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11377
11378 case TARGET_OBJECT_EXEC_FILE:
11379 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11380 len, xfered_len,
11381 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11382
11383 default:
11384 return TARGET_XFER_E_IO;
11385 }
11386
11387 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11388 large enough let the caller deal with it. */
11389 if (len < get_remote_packet_size ())
11390 return TARGET_XFER_E_IO;
11391 len = get_remote_packet_size ();
11392
11393 /* Except for querying the minimum buffer size, target must be open. */
11394 if (!rs->remote_desc)
11395 error (_("remote query is only available after target open"));
11396
11397 gdb_assert (annex != NULL);
11398 gdb_assert (readbuf != NULL);
11399
11400 p2 = rs->buf.data ();
11401 *p2++ = 'q';
11402 *p2++ = query_type;
11403
11404 /* We used one buffer char for the remote protocol q command and
11405 another for the query type. As the remote protocol encapsulation
11406 uses 4 chars plus one extra in case we are debugging
11407 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11408 string. */
11409 i = 0;
11410 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11411 {
11412 /* Bad caller may have sent forbidden characters. */
11413 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11414 *p2++ = annex[i];
11415 i++;
11416 }
11417 *p2 = '\0';
11418 gdb_assert (annex[i] == '\0');
11419
11420 i = putpkt (rs->buf);
11421 if (i < 0)
11422 return TARGET_XFER_E_IO;
11423
11424 getpkt (&rs->buf, 0);
11425 strcpy ((char *) readbuf, rs->buf.data ());
11426
11427 *xfered_len = strlen ((char *) readbuf);
11428 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11429 }
11430
11431 /* Implementation of to_get_memory_xfer_limit. */
11432
11433 ULONGEST
11434 remote_target::get_memory_xfer_limit ()
11435 {
11436 return get_memory_write_packet_size ();
11437 }
11438
11439 int
11440 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11441 const gdb_byte *pattern, ULONGEST pattern_len,
11442 CORE_ADDR *found_addrp)
11443 {
11444 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11445 struct remote_state *rs = get_remote_state ();
11446 int max_size = get_memory_write_packet_size ();
11447 struct packet_config *packet =
11448 &remote_protocol_packets[PACKET_qSearch_memory];
11449 /* Number of packet bytes used to encode the pattern;
11450 this could be more than PATTERN_LEN due to escape characters. */
11451 int escaped_pattern_len;
11452 /* Amount of pattern that was encodable in the packet. */
11453 int used_pattern_len;
11454 int i;
11455 int found;
11456 ULONGEST found_addr;
11457
11458 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11459 {
11460 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11461 == len);
11462 };
11463
11464 /* Don't go to the target if we don't have to. This is done before
11465 checking packet_config_support to avoid the possibility that a
11466 success for this edge case means the facility works in
11467 general. */
11468 if (pattern_len > search_space_len)
11469 return 0;
11470 if (pattern_len == 0)
11471 {
11472 *found_addrp = start_addr;
11473 return 1;
11474 }
11475
11476 /* If we already know the packet isn't supported, fall back to the simple
11477 way of searching memory. */
11478
11479 if (packet_config_support (packet) == PACKET_DISABLE)
11480 {
11481 /* Target doesn't provided special support, fall back and use the
11482 standard support (copy memory and do the search here). */
11483 return simple_search_memory (read_memory, start_addr, search_space_len,
11484 pattern, pattern_len, found_addrp);
11485 }
11486
11487 /* Make sure the remote is pointing at the right process. */
11488 set_general_process ();
11489
11490 /* Insert header. */
11491 i = snprintf (rs->buf.data (), max_size,
11492 "qSearch:memory:%s;%s;",
11493 phex_nz (start_addr, addr_size),
11494 phex_nz (search_space_len, sizeof (search_space_len)));
11495 max_size -= (i + 1);
11496
11497 /* Escape as much data as fits into rs->buf. */
11498 escaped_pattern_len =
11499 remote_escape_output (pattern, pattern_len, 1,
11500 (gdb_byte *) rs->buf.data () + i,
11501 &used_pattern_len, max_size);
11502
11503 /* Bail if the pattern is too large. */
11504 if (used_pattern_len != pattern_len)
11505 error (_("Pattern is too large to transmit to remote target."));
11506
11507 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11508 || getpkt_sane (&rs->buf, 0) < 0
11509 || packet_ok (rs->buf, packet) != PACKET_OK)
11510 {
11511 /* The request may not have worked because the command is not
11512 supported. If so, fall back to the simple way. */
11513 if (packet_config_support (packet) == PACKET_DISABLE)
11514 {
11515 return simple_search_memory (read_memory, start_addr, search_space_len,
11516 pattern, pattern_len, found_addrp);
11517 }
11518 return -1;
11519 }
11520
11521 if (rs->buf[0] == '0')
11522 found = 0;
11523 else if (rs->buf[0] == '1')
11524 {
11525 found = 1;
11526 if (rs->buf[1] != ',')
11527 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11528 unpack_varlen_hex (&rs->buf[2], &found_addr);
11529 *found_addrp = found_addr;
11530 }
11531 else
11532 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11533
11534 return found;
11535 }
11536
11537 void
11538 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11539 {
11540 struct remote_state *rs = get_remote_state ();
11541 char *p = rs->buf.data ();
11542
11543 if (!rs->remote_desc)
11544 error (_("remote rcmd is only available after target open"));
11545
11546 /* Send a NULL command across as an empty command. */
11547 if (command == NULL)
11548 command = "";
11549
11550 /* The query prefix. */
11551 strcpy (rs->buf.data (), "qRcmd,");
11552 p = strchr (rs->buf.data (), '\0');
11553
11554 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11555 > get_remote_packet_size ())
11556 error (_("\"monitor\" command ``%s'' is too long."), command);
11557
11558 /* Encode the actual command. */
11559 bin2hex ((const gdb_byte *) command, p, strlen (command));
11560
11561 if (putpkt (rs->buf) < 0)
11562 error (_("Communication problem with target."));
11563
11564 /* get/display the response */
11565 while (1)
11566 {
11567 char *buf;
11568
11569 /* XXX - see also remote_get_noisy_reply(). */
11570 QUIT; /* Allow user to bail out with ^C. */
11571 rs->buf[0] = '\0';
11572 if (getpkt_sane (&rs->buf, 0) == -1)
11573 {
11574 /* Timeout. Continue to (try to) read responses.
11575 This is better than stopping with an error, assuming the stub
11576 is still executing the (long) monitor command.
11577 If needed, the user can interrupt gdb using C-c, obtaining
11578 an effect similar to stop on timeout. */
11579 continue;
11580 }
11581 buf = rs->buf.data ();
11582 if (buf[0] == '\0')
11583 error (_("Target does not support this command."));
11584 if (buf[0] == 'O' && buf[1] != 'K')
11585 {
11586 remote_console_output (buf + 1); /* 'O' message from stub. */
11587 continue;
11588 }
11589 if (strcmp (buf, "OK") == 0)
11590 break;
11591 if (strlen (buf) == 3 && buf[0] == 'E'
11592 && isdigit (buf[1]) && isdigit (buf[2]))
11593 {
11594 error (_("Protocol error with Rcmd"));
11595 }
11596 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11597 {
11598 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11599
11600 fputc_unfiltered (c, outbuf);
11601 }
11602 break;
11603 }
11604 }
11605
11606 std::vector<mem_region>
11607 remote_target::memory_map ()
11608 {
11609 std::vector<mem_region> result;
11610 gdb::optional<gdb::char_vector> text
11611 = target_read_stralloc (current_inferior ()->top_target (),
11612 TARGET_OBJECT_MEMORY_MAP, NULL);
11613
11614 if (text)
11615 result = parse_memory_map (text->data ());
11616
11617 return result;
11618 }
11619
11620 /* Set of callbacks used to implement the 'maint packet' command. */
11621
11622 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11623 {
11624 /* Called before the packet is sent. BUF is the packet content before
11625 the protocol specific prefix, suffix, and escaping is added. */
11626
11627 void sending (gdb::array_view<const char> &buf) override
11628 {
11629 puts_filtered ("sending: ");
11630 print_packet (buf);
11631 puts_filtered ("\n");
11632 }
11633
11634 /* Called with BUF, the reply from the remote target. */
11635
11636 void received (gdb::array_view<const char> &buf) override
11637 {
11638 puts_filtered ("received: \"");
11639 print_packet (buf);
11640 puts_filtered ("\"\n");
11641 }
11642
11643 private:
11644
11645 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11646 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11647
11648 static void
11649 print_packet (gdb::array_view<const char> &buf)
11650 {
11651 string_file stb;
11652
11653 for (int i = 0; i < buf.size (); ++i)
11654 {
11655 gdb_byte c = buf[i];
11656 if (isprint (c))
11657 fputc_unfiltered (c, &stb);
11658 else
11659 fprintf_unfiltered (&stb, "\\x%02x", (unsigned char) c);
11660 }
11661
11662 puts_filtered (stb.string ().c_str ());
11663 }
11664 };
11665
11666 /* See remote.h. */
11667
11668 void
11669 send_remote_packet (gdb::array_view<const char> &buf,
11670 send_remote_packet_callbacks *callbacks)
11671 {
11672 if (buf.size () == 0 || buf.data ()[0] == '\0')
11673 error (_("a remote packet must not be empty"));
11674
11675 remote_target *remote = get_current_remote_target ();
11676 if (remote == nullptr)
11677 error (_("packets can only be sent to a remote target"));
11678
11679 callbacks->sending (buf);
11680
11681 remote->putpkt_binary (buf.data (), buf.size ());
11682 remote_state *rs = remote->get_remote_state ();
11683 int bytes = remote->getpkt_sane (&rs->buf, 0);
11684
11685 if (bytes < 0)
11686 error (_("error while fetching packet from remote target"));
11687
11688 gdb::array_view<const char> view (&rs->buf[0], bytes);
11689 callbacks->received (view);
11690 }
11691
11692 /* Entry point for the 'maint packet' command. */
11693
11694 static void
11695 cli_packet_command (const char *args, int from_tty)
11696 {
11697 cli_packet_command_callbacks cb;
11698 gdb::array_view<const char> view
11699 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11700 send_remote_packet (view, &cb);
11701 }
11702
11703 #if 0
11704 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11705
11706 static void display_thread_info (struct gdb_ext_thread_info *info);
11707
11708 static void threadset_test_cmd (char *cmd, int tty);
11709
11710 static void threadalive_test (char *cmd, int tty);
11711
11712 static void threadlist_test_cmd (char *cmd, int tty);
11713
11714 int get_and_display_threadinfo (threadref *ref);
11715
11716 static void threadinfo_test_cmd (char *cmd, int tty);
11717
11718 static int thread_display_step (threadref *ref, void *context);
11719
11720 static void threadlist_update_test_cmd (char *cmd, int tty);
11721
11722 static void init_remote_threadtests (void);
11723
11724 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11725
11726 static void
11727 threadset_test_cmd (const char *cmd, int tty)
11728 {
11729 int sample_thread = SAMPLE_THREAD;
11730
11731 printf_filtered (_("Remote threadset test\n"));
11732 set_general_thread (sample_thread);
11733 }
11734
11735
11736 static void
11737 threadalive_test (const char *cmd, int tty)
11738 {
11739 int sample_thread = SAMPLE_THREAD;
11740 int pid = inferior_ptid.pid ();
11741 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11742
11743 if (remote_thread_alive (ptid))
11744 printf_filtered ("PASS: Thread alive test\n");
11745 else
11746 printf_filtered ("FAIL: Thread alive test\n");
11747 }
11748
11749 void output_threadid (char *title, threadref *ref);
11750
11751 void
11752 output_threadid (char *title, threadref *ref)
11753 {
11754 char hexid[20];
11755
11756 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11757 hexid[16] = 0;
11758 printf_filtered ("%s %s\n", title, (&hexid[0]));
11759 }
11760
11761 static void
11762 threadlist_test_cmd (const char *cmd, int tty)
11763 {
11764 int startflag = 1;
11765 threadref nextthread;
11766 int done, result_count;
11767 threadref threadlist[3];
11768
11769 printf_filtered ("Remote Threadlist test\n");
11770 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11771 &result_count, &threadlist[0]))
11772 printf_filtered ("FAIL: threadlist test\n");
11773 else
11774 {
11775 threadref *scan = threadlist;
11776 threadref *limit = scan + result_count;
11777
11778 while (scan < limit)
11779 output_threadid (" thread ", scan++);
11780 }
11781 }
11782
11783 void
11784 display_thread_info (struct gdb_ext_thread_info *info)
11785 {
11786 output_threadid ("Threadid: ", &info->threadid);
11787 printf_filtered ("Name: %s\n ", info->shortname);
11788 printf_filtered ("State: %s\n", info->display);
11789 printf_filtered ("other: %s\n\n", info->more_display);
11790 }
11791
11792 int
11793 get_and_display_threadinfo (threadref *ref)
11794 {
11795 int result;
11796 int set;
11797 struct gdb_ext_thread_info threadinfo;
11798
11799 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11800 | TAG_MOREDISPLAY | TAG_DISPLAY;
11801 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11802 display_thread_info (&threadinfo);
11803 return result;
11804 }
11805
11806 static void
11807 threadinfo_test_cmd (const char *cmd, int tty)
11808 {
11809 int athread = SAMPLE_THREAD;
11810 threadref thread;
11811 int set;
11812
11813 int_to_threadref (&thread, athread);
11814 printf_filtered ("Remote Threadinfo test\n");
11815 if (!get_and_display_threadinfo (&thread))
11816 printf_filtered ("FAIL cannot get thread info\n");
11817 }
11818
11819 static int
11820 thread_display_step (threadref *ref, void *context)
11821 {
11822 /* output_threadid(" threadstep ",ref); *//* simple test */
11823 return get_and_display_threadinfo (ref);
11824 }
11825
11826 static void
11827 threadlist_update_test_cmd (const char *cmd, int tty)
11828 {
11829 printf_filtered ("Remote Threadlist update test\n");
11830 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11831 }
11832
11833 static void
11834 init_remote_threadtests (void)
11835 {
11836 add_com ("tlist", class_obscure, threadlist_test_cmd,
11837 _("Fetch and print the remote list of "
11838 "thread identifiers, one pkt only."));
11839 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11840 _("Fetch and display info about one thread."));
11841 add_com ("tset", class_obscure, threadset_test_cmd,
11842 _("Test setting to a different thread."));
11843 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11844 _("Iterate through updating all remote thread info."));
11845 add_com ("talive", class_obscure, threadalive_test,
11846 _("Remote thread alive test."));
11847 }
11848
11849 #endif /* 0 */
11850
11851 /* Convert a thread ID to a string. */
11852
11853 std::string
11854 remote_target::pid_to_str (ptid_t ptid)
11855 {
11856 struct remote_state *rs = get_remote_state ();
11857
11858 if (ptid == null_ptid)
11859 return normal_pid_to_str (ptid);
11860 else if (ptid.is_pid ())
11861 {
11862 /* Printing an inferior target id. */
11863
11864 /* When multi-process extensions are off, there's no way in the
11865 remote protocol to know the remote process id, if there's any
11866 at all. There's one exception --- when we're connected with
11867 target extended-remote, and we manually attached to a process
11868 with "attach PID". We don't record anywhere a flag that
11869 allows us to distinguish that case from the case of
11870 connecting with extended-remote and the stub already being
11871 attached to a process, and reporting yes to qAttached, hence
11872 no smart special casing here. */
11873 if (!remote_multi_process_p (rs))
11874 return "Remote target";
11875
11876 return normal_pid_to_str (ptid);
11877 }
11878 else
11879 {
11880 if (magic_null_ptid == ptid)
11881 return "Thread <main>";
11882 else if (remote_multi_process_p (rs))
11883 if (ptid.lwp () == 0)
11884 return normal_pid_to_str (ptid);
11885 else
11886 return string_printf ("Thread %d.%ld",
11887 ptid.pid (), ptid.lwp ());
11888 else
11889 return string_printf ("Thread %ld", ptid.lwp ());
11890 }
11891 }
11892
11893 /* Get the address of the thread local variable in OBJFILE which is
11894 stored at OFFSET within the thread local storage for thread PTID. */
11895
11896 CORE_ADDR
11897 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11898 CORE_ADDR offset)
11899 {
11900 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11901 {
11902 struct remote_state *rs = get_remote_state ();
11903 char *p = rs->buf.data ();
11904 char *endp = p + get_remote_packet_size ();
11905 enum packet_result result;
11906
11907 strcpy (p, "qGetTLSAddr:");
11908 p += strlen (p);
11909 p = write_ptid (p, endp, ptid);
11910 *p++ = ',';
11911 p += hexnumstr (p, offset);
11912 *p++ = ',';
11913 p += hexnumstr (p, lm);
11914 *p++ = '\0';
11915
11916 putpkt (rs->buf);
11917 getpkt (&rs->buf, 0);
11918 result = packet_ok (rs->buf,
11919 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11920 if (result == PACKET_OK)
11921 {
11922 ULONGEST addr;
11923
11924 unpack_varlen_hex (rs->buf.data (), &addr);
11925 return addr;
11926 }
11927 else if (result == PACKET_UNKNOWN)
11928 throw_error (TLS_GENERIC_ERROR,
11929 _("Remote target doesn't support qGetTLSAddr packet"));
11930 else
11931 throw_error (TLS_GENERIC_ERROR,
11932 _("Remote target failed to process qGetTLSAddr request"));
11933 }
11934 else
11935 throw_error (TLS_GENERIC_ERROR,
11936 _("TLS not supported or disabled on this target"));
11937 /* Not reached. */
11938 return 0;
11939 }
11940
11941 /* Provide thread local base, i.e. Thread Information Block address.
11942 Returns 1 if ptid is found and thread_local_base is non zero. */
11943
11944 bool
11945 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11946 {
11947 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11948 {
11949 struct remote_state *rs = get_remote_state ();
11950 char *p = rs->buf.data ();
11951 char *endp = p + get_remote_packet_size ();
11952 enum packet_result result;
11953
11954 strcpy (p, "qGetTIBAddr:");
11955 p += strlen (p);
11956 p = write_ptid (p, endp, ptid);
11957 *p++ = '\0';
11958
11959 putpkt (rs->buf);
11960 getpkt (&rs->buf, 0);
11961 result = packet_ok (rs->buf,
11962 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11963 if (result == PACKET_OK)
11964 {
11965 ULONGEST val;
11966 unpack_varlen_hex (rs->buf.data (), &val);
11967 if (addr)
11968 *addr = (CORE_ADDR) val;
11969 return true;
11970 }
11971 else if (result == PACKET_UNKNOWN)
11972 error (_("Remote target doesn't support qGetTIBAddr packet"));
11973 else
11974 error (_("Remote target failed to process qGetTIBAddr request"));
11975 }
11976 else
11977 error (_("qGetTIBAddr not supported or disabled on this target"));
11978 /* Not reached. */
11979 return false;
11980 }
11981
11982 /* Support for inferring a target description based on the current
11983 architecture and the size of a 'g' packet. While the 'g' packet
11984 can have any size (since optional registers can be left off the
11985 end), some sizes are easily recognizable given knowledge of the
11986 approximate architecture. */
11987
11988 struct remote_g_packet_guess
11989 {
11990 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11991 : bytes (bytes_),
11992 tdesc (tdesc_)
11993 {
11994 }
11995
11996 int bytes;
11997 const struct target_desc *tdesc;
11998 };
11999
12000 struct remote_g_packet_data : public allocate_on_obstack
12001 {
12002 std::vector<remote_g_packet_guess> guesses;
12003 };
12004
12005 static struct gdbarch_data *remote_g_packet_data_handle;
12006
12007 static void *
12008 remote_g_packet_data_init (struct obstack *obstack)
12009 {
12010 return new (obstack) remote_g_packet_data;
12011 }
12012
12013 void
12014 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12015 const struct target_desc *tdesc)
12016 {
12017 struct remote_g_packet_data *data
12018 = ((struct remote_g_packet_data *)
12019 gdbarch_data (gdbarch, remote_g_packet_data_handle));
12020
12021 gdb_assert (tdesc != NULL);
12022
12023 for (const remote_g_packet_guess &guess : data->guesses)
12024 if (guess.bytes == bytes)
12025 internal_error (__FILE__, __LINE__,
12026 _("Duplicate g packet description added for size %d"),
12027 bytes);
12028
12029 data->guesses.emplace_back (bytes, tdesc);
12030 }
12031
12032 /* Return true if remote_read_description would do anything on this target
12033 and architecture, false otherwise. */
12034
12035 static bool
12036 remote_read_description_p (struct target_ops *target)
12037 {
12038 struct remote_g_packet_data *data
12039 = ((struct remote_g_packet_data *)
12040 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12041
12042 return !data->guesses.empty ();
12043 }
12044
12045 const struct target_desc *
12046 remote_target::read_description ()
12047 {
12048 struct remote_g_packet_data *data
12049 = ((struct remote_g_packet_data *)
12050 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12051
12052 /* Do not try this during initial connection, when we do not know
12053 whether there is a running but stopped thread. */
12054 if (!target_has_execution () || inferior_ptid == null_ptid)
12055 return beneath ()->read_description ();
12056
12057 if (!data->guesses.empty ())
12058 {
12059 int bytes = send_g_packet ();
12060
12061 for (const remote_g_packet_guess &guess : data->guesses)
12062 if (guess.bytes == bytes)
12063 return guess.tdesc;
12064
12065 /* We discard the g packet. A minor optimization would be to
12066 hold on to it, and fill the register cache once we have selected
12067 an architecture, but it's too tricky to do safely. */
12068 }
12069
12070 return beneath ()->read_description ();
12071 }
12072
12073 /* Remote file transfer support. This is host-initiated I/O, not
12074 target-initiated; for target-initiated, see remote-fileio.c. */
12075
12076 /* If *LEFT is at least the length of STRING, copy STRING to
12077 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12078 decrease *LEFT. Otherwise raise an error. */
12079
12080 static void
12081 remote_buffer_add_string (char **buffer, int *left, const char *string)
12082 {
12083 int len = strlen (string);
12084
12085 if (len > *left)
12086 error (_("Packet too long for target."));
12087
12088 memcpy (*buffer, string, len);
12089 *buffer += len;
12090 *left -= len;
12091
12092 /* NUL-terminate the buffer as a convenience, if there is
12093 room. */
12094 if (*left)
12095 **buffer = '\0';
12096 }
12097
12098 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12099 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12100 decrease *LEFT. Otherwise raise an error. */
12101
12102 static void
12103 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12104 int len)
12105 {
12106 if (2 * len > *left)
12107 error (_("Packet too long for target."));
12108
12109 bin2hex (bytes, *buffer, len);
12110 *buffer += 2 * len;
12111 *left -= 2 * len;
12112
12113 /* NUL-terminate the buffer as a convenience, if there is
12114 room. */
12115 if (*left)
12116 **buffer = '\0';
12117 }
12118
12119 /* If *LEFT is large enough, convert VALUE to hex and add it to
12120 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12121 decrease *LEFT. Otherwise raise an error. */
12122
12123 static void
12124 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12125 {
12126 int len = hexnumlen (value);
12127
12128 if (len > *left)
12129 error (_("Packet too long for target."));
12130
12131 hexnumstr (*buffer, value);
12132 *buffer += len;
12133 *left -= len;
12134
12135 /* NUL-terminate the buffer as a convenience, if there is
12136 room. */
12137 if (*left)
12138 **buffer = '\0';
12139 }
12140
12141 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12142 value, *REMOTE_ERRNO to the remote error number or zero if none
12143 was included, and *ATTACHMENT to point to the start of the annex
12144 if any. The length of the packet isn't needed here; there may
12145 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12146
12147 Return 0 if the packet could be parsed, -1 if it could not. If
12148 -1 is returned, the other variables may not be initialized. */
12149
12150 static int
12151 remote_hostio_parse_result (const char *buffer, int *retcode,
12152 int *remote_errno, const char **attachment)
12153 {
12154 char *p, *p2;
12155
12156 *remote_errno = 0;
12157 *attachment = NULL;
12158
12159 if (buffer[0] != 'F')
12160 return -1;
12161
12162 errno = 0;
12163 *retcode = strtol (&buffer[1], &p, 16);
12164 if (errno != 0 || p == &buffer[1])
12165 return -1;
12166
12167 /* Check for ",errno". */
12168 if (*p == ',')
12169 {
12170 errno = 0;
12171 *remote_errno = strtol (p + 1, &p2, 16);
12172 if (errno != 0 || p + 1 == p2)
12173 return -1;
12174 p = p2;
12175 }
12176
12177 /* Check for ";attachment". If there is no attachment, the
12178 packet should end here. */
12179 if (*p == ';')
12180 {
12181 *attachment = p + 1;
12182 return 0;
12183 }
12184 else if (*p == '\0')
12185 return 0;
12186 else
12187 return -1;
12188 }
12189
12190 /* Send a prepared I/O packet to the target and read its response.
12191 The prepared packet is in the global RS->BUF before this function
12192 is called, and the answer is there when we return.
12193
12194 COMMAND_BYTES is the length of the request to send, which may include
12195 binary data. WHICH_PACKET is the packet configuration to check
12196 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12197 is set to the error number and -1 is returned. Otherwise the value
12198 returned by the function is returned.
12199
12200 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12201 attachment is expected; an error will be reported if there's a
12202 mismatch. If one is found, *ATTACHMENT will be set to point into
12203 the packet buffer and *ATTACHMENT_LEN will be set to the
12204 attachment's length. */
12205
12206 int
12207 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12208 int *remote_errno, const char **attachment,
12209 int *attachment_len)
12210 {
12211 struct remote_state *rs = get_remote_state ();
12212 int ret, bytes_read;
12213 const char *attachment_tmp;
12214
12215 if (packet_support (which_packet) == PACKET_DISABLE)
12216 {
12217 *remote_errno = FILEIO_ENOSYS;
12218 return -1;
12219 }
12220
12221 putpkt_binary (rs->buf.data (), command_bytes);
12222 bytes_read = getpkt_sane (&rs->buf, 0);
12223
12224 /* If it timed out, something is wrong. Don't try to parse the
12225 buffer. */
12226 if (bytes_read < 0)
12227 {
12228 *remote_errno = FILEIO_EINVAL;
12229 return -1;
12230 }
12231
12232 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12233 {
12234 case PACKET_ERROR:
12235 *remote_errno = FILEIO_EINVAL;
12236 return -1;
12237 case PACKET_UNKNOWN:
12238 *remote_errno = FILEIO_ENOSYS;
12239 return -1;
12240 case PACKET_OK:
12241 break;
12242 }
12243
12244 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12245 &attachment_tmp))
12246 {
12247 *remote_errno = FILEIO_EINVAL;
12248 return -1;
12249 }
12250
12251 /* Make sure we saw an attachment if and only if we expected one. */
12252 if ((attachment_tmp == NULL && attachment != NULL)
12253 || (attachment_tmp != NULL && attachment == NULL))
12254 {
12255 *remote_errno = FILEIO_EINVAL;
12256 return -1;
12257 }
12258
12259 /* If an attachment was found, it must point into the packet buffer;
12260 work out how many bytes there were. */
12261 if (attachment_tmp != NULL)
12262 {
12263 *attachment = attachment_tmp;
12264 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12265 }
12266
12267 return ret;
12268 }
12269
12270 /* See declaration.h. */
12271
12272 void
12273 readahead_cache::invalidate ()
12274 {
12275 this->fd = -1;
12276 }
12277
12278 /* See declaration.h. */
12279
12280 void
12281 readahead_cache::invalidate_fd (int fd)
12282 {
12283 if (this->fd == fd)
12284 this->fd = -1;
12285 }
12286
12287 /* Set the filesystem remote_hostio functions that take FILENAME
12288 arguments will use. Return 0 on success, or -1 if an error
12289 occurs (and set *REMOTE_ERRNO). */
12290
12291 int
12292 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12293 int *remote_errno)
12294 {
12295 struct remote_state *rs = get_remote_state ();
12296 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12297 char *p = rs->buf.data ();
12298 int left = get_remote_packet_size () - 1;
12299 char arg[9];
12300 int ret;
12301
12302 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12303 return 0;
12304
12305 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12306 return 0;
12307
12308 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12309
12310 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12311 remote_buffer_add_string (&p, &left, arg);
12312
12313 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12314 remote_errno, NULL, NULL);
12315
12316 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12317 return 0;
12318
12319 if (ret == 0)
12320 rs->fs_pid = required_pid;
12321
12322 return ret;
12323 }
12324
12325 /* Implementation of to_fileio_open. */
12326
12327 int
12328 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12329 int flags, int mode, int warn_if_slow,
12330 int *remote_errno)
12331 {
12332 struct remote_state *rs = get_remote_state ();
12333 char *p = rs->buf.data ();
12334 int left = get_remote_packet_size () - 1;
12335
12336 if (warn_if_slow)
12337 {
12338 static int warning_issued = 0;
12339
12340 printf_unfiltered (_("Reading %s from remote target...\n"),
12341 filename);
12342
12343 if (!warning_issued)
12344 {
12345 warning (_("File transfers from remote targets can be slow."
12346 " Use \"set sysroot\" to access files locally"
12347 " instead."));
12348 warning_issued = 1;
12349 }
12350 }
12351
12352 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12353 return -1;
12354
12355 remote_buffer_add_string (&p, &left, "vFile:open:");
12356
12357 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12358 strlen (filename));
12359 remote_buffer_add_string (&p, &left, ",");
12360
12361 remote_buffer_add_int (&p, &left, flags);
12362 remote_buffer_add_string (&p, &left, ",");
12363
12364 remote_buffer_add_int (&p, &left, mode);
12365
12366 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12367 remote_errno, NULL, NULL);
12368 }
12369
12370 int
12371 remote_target::fileio_open (struct inferior *inf, const char *filename,
12372 int flags, int mode, int warn_if_slow,
12373 int *remote_errno)
12374 {
12375 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12376 remote_errno);
12377 }
12378
12379 /* Implementation of to_fileio_pwrite. */
12380
12381 int
12382 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12383 ULONGEST offset, int *remote_errno)
12384 {
12385 struct remote_state *rs = get_remote_state ();
12386 char *p = rs->buf.data ();
12387 int left = get_remote_packet_size ();
12388 int out_len;
12389
12390 rs->readahead_cache.invalidate_fd (fd);
12391
12392 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12393
12394 remote_buffer_add_int (&p, &left, fd);
12395 remote_buffer_add_string (&p, &left, ",");
12396
12397 remote_buffer_add_int (&p, &left, offset);
12398 remote_buffer_add_string (&p, &left, ",");
12399
12400 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12401 (get_remote_packet_size ()
12402 - (p - rs->buf.data ())));
12403
12404 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12405 remote_errno, NULL, NULL);
12406 }
12407
12408 int
12409 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12410 ULONGEST offset, int *remote_errno)
12411 {
12412 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12413 }
12414
12415 /* Helper for the implementation of to_fileio_pread. Read the file
12416 from the remote side with vFile:pread. */
12417
12418 int
12419 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12420 ULONGEST offset, int *remote_errno)
12421 {
12422 struct remote_state *rs = get_remote_state ();
12423 char *p = rs->buf.data ();
12424 const char *attachment;
12425 int left = get_remote_packet_size ();
12426 int ret, attachment_len;
12427 int read_len;
12428
12429 remote_buffer_add_string (&p, &left, "vFile:pread:");
12430
12431 remote_buffer_add_int (&p, &left, fd);
12432 remote_buffer_add_string (&p, &left, ",");
12433
12434 remote_buffer_add_int (&p, &left, len);
12435 remote_buffer_add_string (&p, &left, ",");
12436
12437 remote_buffer_add_int (&p, &left, offset);
12438
12439 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12440 remote_errno, &attachment,
12441 &attachment_len);
12442
12443 if (ret < 0)
12444 return ret;
12445
12446 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12447 read_buf, len);
12448 if (read_len != ret)
12449 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12450
12451 return ret;
12452 }
12453
12454 /* See declaration.h. */
12455
12456 int
12457 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12458 ULONGEST offset)
12459 {
12460 if (this->fd == fd
12461 && this->offset <= offset
12462 && offset < this->offset + this->bufsize)
12463 {
12464 ULONGEST max = this->offset + this->bufsize;
12465
12466 if (offset + len > max)
12467 len = max - offset;
12468
12469 memcpy (read_buf, this->buf + offset - this->offset, len);
12470 return len;
12471 }
12472
12473 return 0;
12474 }
12475
12476 /* Implementation of to_fileio_pread. */
12477
12478 int
12479 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12480 ULONGEST offset, int *remote_errno)
12481 {
12482 int ret;
12483 struct remote_state *rs = get_remote_state ();
12484 readahead_cache *cache = &rs->readahead_cache;
12485
12486 ret = cache->pread (fd, read_buf, len, offset);
12487 if (ret > 0)
12488 {
12489 cache->hit_count++;
12490
12491 remote_debug_printf ("readahead cache hit %s",
12492 pulongest (cache->hit_count));
12493 return ret;
12494 }
12495
12496 cache->miss_count++;
12497
12498 remote_debug_printf ("readahead cache miss %s",
12499 pulongest (cache->miss_count));
12500
12501 cache->fd = fd;
12502 cache->offset = offset;
12503 cache->bufsize = get_remote_packet_size ();
12504 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12505
12506 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12507 cache->offset, remote_errno);
12508 if (ret <= 0)
12509 {
12510 cache->invalidate_fd (fd);
12511 return ret;
12512 }
12513
12514 cache->bufsize = ret;
12515 return cache->pread (fd, read_buf, len, offset);
12516 }
12517
12518 int
12519 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12520 ULONGEST offset, int *remote_errno)
12521 {
12522 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12523 }
12524
12525 /* Implementation of to_fileio_close. */
12526
12527 int
12528 remote_target::remote_hostio_close (int fd, int *remote_errno)
12529 {
12530 struct remote_state *rs = get_remote_state ();
12531 char *p = rs->buf.data ();
12532 int left = get_remote_packet_size () - 1;
12533
12534 rs->readahead_cache.invalidate_fd (fd);
12535
12536 remote_buffer_add_string (&p, &left, "vFile:close:");
12537
12538 remote_buffer_add_int (&p, &left, fd);
12539
12540 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12541 remote_errno, NULL, NULL);
12542 }
12543
12544 int
12545 remote_target::fileio_close (int fd, int *remote_errno)
12546 {
12547 return remote_hostio_close (fd, remote_errno);
12548 }
12549
12550 /* Implementation of to_fileio_unlink. */
12551
12552 int
12553 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12554 int *remote_errno)
12555 {
12556 struct remote_state *rs = get_remote_state ();
12557 char *p = rs->buf.data ();
12558 int left = get_remote_packet_size () - 1;
12559
12560 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12561 return -1;
12562
12563 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12564
12565 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12566 strlen (filename));
12567
12568 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12569 remote_errno, NULL, NULL);
12570 }
12571
12572 int
12573 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12574 int *remote_errno)
12575 {
12576 return remote_hostio_unlink (inf, filename, remote_errno);
12577 }
12578
12579 /* Implementation of to_fileio_readlink. */
12580
12581 gdb::optional<std::string>
12582 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12583 int *remote_errno)
12584 {
12585 struct remote_state *rs = get_remote_state ();
12586 char *p = rs->buf.data ();
12587 const char *attachment;
12588 int left = get_remote_packet_size ();
12589 int len, attachment_len;
12590 int read_len;
12591
12592 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12593 return {};
12594
12595 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12596
12597 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12598 strlen (filename));
12599
12600 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12601 remote_errno, &attachment,
12602 &attachment_len);
12603
12604 if (len < 0)
12605 return {};
12606
12607 std::string ret (len, '\0');
12608
12609 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12610 (gdb_byte *) &ret[0], len);
12611 if (read_len != len)
12612 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12613
12614 return ret;
12615 }
12616
12617 /* Implementation of to_fileio_fstat. */
12618
12619 int
12620 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12621 {
12622 struct remote_state *rs = get_remote_state ();
12623 char *p = rs->buf.data ();
12624 int left = get_remote_packet_size ();
12625 int attachment_len, ret;
12626 const char *attachment;
12627 struct fio_stat fst;
12628 int read_len;
12629
12630 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12631
12632 remote_buffer_add_int (&p, &left, fd);
12633
12634 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12635 remote_errno, &attachment,
12636 &attachment_len);
12637 if (ret < 0)
12638 {
12639 if (*remote_errno != FILEIO_ENOSYS)
12640 return ret;
12641
12642 /* Strictly we should return -1, ENOSYS here, but when
12643 "set sysroot remote:" was implemented in August 2008
12644 BFD's need for a stat function was sidestepped with
12645 this hack. This was not remedied until March 2015
12646 so we retain the previous behavior to avoid breaking
12647 compatibility.
12648
12649 Note that the memset is a March 2015 addition; older
12650 GDBs set st_size *and nothing else* so the structure
12651 would have garbage in all other fields. This might
12652 break something but retaining the previous behavior
12653 here would be just too wrong. */
12654
12655 memset (st, 0, sizeof (struct stat));
12656 st->st_size = INT_MAX;
12657 return 0;
12658 }
12659
12660 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12661 (gdb_byte *) &fst, sizeof (fst));
12662
12663 if (read_len != ret)
12664 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12665
12666 if (read_len != sizeof (fst))
12667 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12668 read_len, (int) sizeof (fst));
12669
12670 remote_fileio_to_host_stat (&fst, st);
12671
12672 return 0;
12673 }
12674
12675 /* Implementation of to_filesystem_is_local. */
12676
12677 bool
12678 remote_target::filesystem_is_local ()
12679 {
12680 /* Valgrind GDB presents itself as a remote target but works
12681 on the local filesystem: it does not implement remote get
12682 and users are not expected to set a sysroot. To handle
12683 this case we treat the remote filesystem as local if the
12684 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12685 does not support vFile:open. */
12686 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12687 {
12688 enum packet_support ps = packet_support (PACKET_vFile_open);
12689
12690 if (ps == PACKET_SUPPORT_UNKNOWN)
12691 {
12692 int fd, remote_errno;
12693
12694 /* Try opening a file to probe support. The supplied
12695 filename is irrelevant, we only care about whether
12696 the stub recognizes the packet or not. */
12697 fd = remote_hostio_open (NULL, "just probing",
12698 FILEIO_O_RDONLY, 0700, 0,
12699 &remote_errno);
12700
12701 if (fd >= 0)
12702 remote_hostio_close (fd, &remote_errno);
12703
12704 ps = packet_support (PACKET_vFile_open);
12705 }
12706
12707 if (ps == PACKET_DISABLE)
12708 {
12709 static int warning_issued = 0;
12710
12711 if (!warning_issued)
12712 {
12713 warning (_("remote target does not support file"
12714 " transfer, attempting to access files"
12715 " from local filesystem."));
12716 warning_issued = 1;
12717 }
12718
12719 return true;
12720 }
12721 }
12722
12723 return false;
12724 }
12725
12726 static int
12727 remote_fileio_errno_to_host (int errnum)
12728 {
12729 switch (errnum)
12730 {
12731 case FILEIO_EPERM:
12732 return EPERM;
12733 case FILEIO_ENOENT:
12734 return ENOENT;
12735 case FILEIO_EINTR:
12736 return EINTR;
12737 case FILEIO_EIO:
12738 return EIO;
12739 case FILEIO_EBADF:
12740 return EBADF;
12741 case FILEIO_EACCES:
12742 return EACCES;
12743 case FILEIO_EFAULT:
12744 return EFAULT;
12745 case FILEIO_EBUSY:
12746 return EBUSY;
12747 case FILEIO_EEXIST:
12748 return EEXIST;
12749 case FILEIO_ENODEV:
12750 return ENODEV;
12751 case FILEIO_ENOTDIR:
12752 return ENOTDIR;
12753 case FILEIO_EISDIR:
12754 return EISDIR;
12755 case FILEIO_EINVAL:
12756 return EINVAL;
12757 case FILEIO_ENFILE:
12758 return ENFILE;
12759 case FILEIO_EMFILE:
12760 return EMFILE;
12761 case FILEIO_EFBIG:
12762 return EFBIG;
12763 case FILEIO_ENOSPC:
12764 return ENOSPC;
12765 case FILEIO_ESPIPE:
12766 return ESPIPE;
12767 case FILEIO_EROFS:
12768 return EROFS;
12769 case FILEIO_ENOSYS:
12770 return ENOSYS;
12771 case FILEIO_ENAMETOOLONG:
12772 return ENAMETOOLONG;
12773 }
12774 return -1;
12775 }
12776
12777 static char *
12778 remote_hostio_error (int errnum)
12779 {
12780 int host_error = remote_fileio_errno_to_host (errnum);
12781
12782 if (host_error == -1)
12783 error (_("Unknown remote I/O error %d"), errnum);
12784 else
12785 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12786 }
12787
12788 /* A RAII wrapper around a remote file descriptor. */
12789
12790 class scoped_remote_fd
12791 {
12792 public:
12793 scoped_remote_fd (remote_target *remote, int fd)
12794 : m_remote (remote), m_fd (fd)
12795 {
12796 }
12797
12798 ~scoped_remote_fd ()
12799 {
12800 if (m_fd != -1)
12801 {
12802 try
12803 {
12804 int remote_errno;
12805 m_remote->remote_hostio_close (m_fd, &remote_errno);
12806 }
12807 catch (...)
12808 {
12809 /* Swallow exception before it escapes the dtor. If
12810 something goes wrong, likely the connection is gone,
12811 and there's nothing else that can be done. */
12812 }
12813 }
12814 }
12815
12816 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12817
12818 /* Release ownership of the file descriptor, and return it. */
12819 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12820 {
12821 int fd = m_fd;
12822 m_fd = -1;
12823 return fd;
12824 }
12825
12826 /* Return the owned file descriptor. */
12827 int get () const noexcept
12828 {
12829 return m_fd;
12830 }
12831
12832 private:
12833 /* The remote target. */
12834 remote_target *m_remote;
12835
12836 /* The owned remote I/O file descriptor. */
12837 int m_fd;
12838 };
12839
12840 void
12841 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12842 {
12843 remote_target *remote = get_current_remote_target ();
12844
12845 if (remote == nullptr)
12846 error (_("command can only be used with remote target"));
12847
12848 remote->remote_file_put (local_file, remote_file, from_tty);
12849 }
12850
12851 void
12852 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12853 int from_tty)
12854 {
12855 int retcode, remote_errno, bytes, io_size;
12856 int bytes_in_buffer;
12857 int saw_eof;
12858 ULONGEST offset;
12859
12860 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12861 if (file == NULL)
12862 perror_with_name (local_file);
12863
12864 scoped_remote_fd fd
12865 (this, remote_hostio_open (NULL,
12866 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12867 | FILEIO_O_TRUNC),
12868 0700, 0, &remote_errno));
12869 if (fd.get () == -1)
12870 remote_hostio_error (remote_errno);
12871
12872 /* Send up to this many bytes at once. They won't all fit in the
12873 remote packet limit, so we'll transfer slightly fewer. */
12874 io_size = get_remote_packet_size ();
12875 gdb::byte_vector buffer (io_size);
12876
12877 bytes_in_buffer = 0;
12878 saw_eof = 0;
12879 offset = 0;
12880 while (bytes_in_buffer || !saw_eof)
12881 {
12882 if (!saw_eof)
12883 {
12884 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12885 io_size - bytes_in_buffer,
12886 file.get ());
12887 if (bytes == 0)
12888 {
12889 if (ferror (file.get ()))
12890 error (_("Error reading %s."), local_file);
12891 else
12892 {
12893 /* EOF. Unless there is something still in the
12894 buffer from the last iteration, we are done. */
12895 saw_eof = 1;
12896 if (bytes_in_buffer == 0)
12897 break;
12898 }
12899 }
12900 }
12901 else
12902 bytes = 0;
12903
12904 bytes += bytes_in_buffer;
12905 bytes_in_buffer = 0;
12906
12907 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12908 offset, &remote_errno);
12909
12910 if (retcode < 0)
12911 remote_hostio_error (remote_errno);
12912 else if (retcode == 0)
12913 error (_("Remote write of %d bytes returned 0!"), bytes);
12914 else if (retcode < bytes)
12915 {
12916 /* Short write. Save the rest of the read data for the next
12917 write. */
12918 bytes_in_buffer = bytes - retcode;
12919 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12920 }
12921
12922 offset += retcode;
12923 }
12924
12925 if (remote_hostio_close (fd.release (), &remote_errno))
12926 remote_hostio_error (remote_errno);
12927
12928 if (from_tty)
12929 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12930 }
12931
12932 void
12933 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12934 {
12935 remote_target *remote = get_current_remote_target ();
12936
12937 if (remote == nullptr)
12938 error (_("command can only be used with remote target"));
12939
12940 remote->remote_file_get (remote_file, local_file, from_tty);
12941 }
12942
12943 void
12944 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12945 int from_tty)
12946 {
12947 int remote_errno, bytes, io_size;
12948 ULONGEST offset;
12949
12950 scoped_remote_fd fd
12951 (this, remote_hostio_open (NULL,
12952 remote_file, FILEIO_O_RDONLY, 0, 0,
12953 &remote_errno));
12954 if (fd.get () == -1)
12955 remote_hostio_error (remote_errno);
12956
12957 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12958 if (file == NULL)
12959 perror_with_name (local_file);
12960
12961 /* Send up to this many bytes at once. They won't all fit in the
12962 remote packet limit, so we'll transfer slightly fewer. */
12963 io_size = get_remote_packet_size ();
12964 gdb::byte_vector buffer (io_size);
12965
12966 offset = 0;
12967 while (1)
12968 {
12969 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12970 &remote_errno);
12971 if (bytes == 0)
12972 /* Success, but no bytes, means end-of-file. */
12973 break;
12974 if (bytes == -1)
12975 remote_hostio_error (remote_errno);
12976
12977 offset += bytes;
12978
12979 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12980 if (bytes == 0)
12981 perror_with_name (local_file);
12982 }
12983
12984 if (remote_hostio_close (fd.release (), &remote_errno))
12985 remote_hostio_error (remote_errno);
12986
12987 if (from_tty)
12988 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12989 }
12990
12991 void
12992 remote_file_delete (const char *remote_file, int from_tty)
12993 {
12994 remote_target *remote = get_current_remote_target ();
12995
12996 if (remote == nullptr)
12997 error (_("command can only be used with remote target"));
12998
12999 remote->remote_file_delete (remote_file, from_tty);
13000 }
13001
13002 void
13003 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13004 {
13005 int retcode, remote_errno;
13006
13007 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13008 if (retcode == -1)
13009 remote_hostio_error (remote_errno);
13010
13011 if (from_tty)
13012 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
13013 }
13014
13015 static void
13016 remote_put_command (const char *args, int from_tty)
13017 {
13018 if (args == NULL)
13019 error_no_arg (_("file to put"));
13020
13021 gdb_argv argv (args);
13022 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13023 error (_("Invalid parameters to remote put"));
13024
13025 remote_file_put (argv[0], argv[1], from_tty);
13026 }
13027
13028 static void
13029 remote_get_command (const char *args, int from_tty)
13030 {
13031 if (args == NULL)
13032 error_no_arg (_("file to get"));
13033
13034 gdb_argv argv (args);
13035 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13036 error (_("Invalid parameters to remote get"));
13037
13038 remote_file_get (argv[0], argv[1], from_tty);
13039 }
13040
13041 static void
13042 remote_delete_command (const char *args, int from_tty)
13043 {
13044 if (args == NULL)
13045 error_no_arg (_("file to delete"));
13046
13047 gdb_argv argv (args);
13048 if (argv[0] == NULL || argv[1] != NULL)
13049 error (_("Invalid parameters to remote delete"));
13050
13051 remote_file_delete (argv[0], from_tty);
13052 }
13053
13054 bool
13055 remote_target::can_execute_reverse ()
13056 {
13057 if (packet_support (PACKET_bs) == PACKET_ENABLE
13058 || packet_support (PACKET_bc) == PACKET_ENABLE)
13059 return true;
13060 else
13061 return false;
13062 }
13063
13064 bool
13065 remote_target::supports_non_stop ()
13066 {
13067 return true;
13068 }
13069
13070 bool
13071 remote_target::supports_disable_randomization ()
13072 {
13073 /* Only supported in extended mode. */
13074 return false;
13075 }
13076
13077 bool
13078 remote_target::supports_multi_process ()
13079 {
13080 struct remote_state *rs = get_remote_state ();
13081
13082 return remote_multi_process_p (rs);
13083 }
13084
13085 static int
13086 remote_supports_cond_tracepoints ()
13087 {
13088 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
13089 }
13090
13091 bool
13092 remote_target::supports_evaluation_of_breakpoint_conditions ()
13093 {
13094 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
13095 }
13096
13097 static int
13098 remote_supports_fast_tracepoints ()
13099 {
13100 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13101 }
13102
13103 static int
13104 remote_supports_static_tracepoints ()
13105 {
13106 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13107 }
13108
13109 static int
13110 remote_supports_install_in_trace ()
13111 {
13112 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13113 }
13114
13115 bool
13116 remote_target::supports_enable_disable_tracepoint ()
13117 {
13118 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13119 == PACKET_ENABLE);
13120 }
13121
13122 bool
13123 remote_target::supports_string_tracing ()
13124 {
13125 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13126 }
13127
13128 bool
13129 remote_target::can_run_breakpoint_commands ()
13130 {
13131 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13132 }
13133
13134 void
13135 remote_target::trace_init ()
13136 {
13137 struct remote_state *rs = get_remote_state ();
13138
13139 putpkt ("QTinit");
13140 remote_get_noisy_reply ();
13141 if (strcmp (rs->buf.data (), "OK") != 0)
13142 error (_("Target does not support this command."));
13143 }
13144
13145 /* Recursive routine to walk through command list including loops, and
13146 download packets for each command. */
13147
13148 void
13149 remote_target::remote_download_command_source (int num, ULONGEST addr,
13150 struct command_line *cmds)
13151 {
13152 struct remote_state *rs = get_remote_state ();
13153 struct command_line *cmd;
13154
13155 for (cmd = cmds; cmd; cmd = cmd->next)
13156 {
13157 QUIT; /* Allow user to bail out with ^C. */
13158 strcpy (rs->buf.data (), "QTDPsrc:");
13159 encode_source_string (num, addr, "cmd", cmd->line,
13160 rs->buf.data () + strlen (rs->buf.data ()),
13161 rs->buf.size () - strlen (rs->buf.data ()));
13162 putpkt (rs->buf);
13163 remote_get_noisy_reply ();
13164 if (strcmp (rs->buf.data (), "OK"))
13165 warning (_("Target does not support source download."));
13166
13167 if (cmd->control_type == while_control
13168 || cmd->control_type == while_stepping_control)
13169 {
13170 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13171
13172 QUIT; /* Allow user to bail out with ^C. */
13173 strcpy (rs->buf.data (), "QTDPsrc:");
13174 encode_source_string (num, addr, "cmd", "end",
13175 rs->buf.data () + strlen (rs->buf.data ()),
13176 rs->buf.size () - strlen (rs->buf.data ()));
13177 putpkt (rs->buf);
13178 remote_get_noisy_reply ();
13179 if (strcmp (rs->buf.data (), "OK"))
13180 warning (_("Target does not support source download."));
13181 }
13182 }
13183 }
13184
13185 void
13186 remote_target::download_tracepoint (struct bp_location *loc)
13187 {
13188 CORE_ADDR tpaddr;
13189 char addrbuf[40];
13190 std::vector<std::string> tdp_actions;
13191 std::vector<std::string> stepping_actions;
13192 char *pkt;
13193 struct breakpoint *b = loc->owner;
13194 struct tracepoint *t = (struct tracepoint *) b;
13195 struct remote_state *rs = get_remote_state ();
13196 int ret;
13197 const char *err_msg = _("Tracepoint packet too large for target.");
13198 size_t size_left;
13199
13200 /* We use a buffer other than rs->buf because we'll build strings
13201 across multiple statements, and other statements in between could
13202 modify rs->buf. */
13203 gdb::char_vector buf (get_remote_packet_size ());
13204
13205 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13206
13207 tpaddr = loc->address;
13208 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13209 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13210 b->number, addrbuf, /* address */
13211 (b->enable_state == bp_enabled ? 'E' : 'D'),
13212 t->step_count, t->pass_count);
13213
13214 if (ret < 0 || ret >= buf.size ())
13215 error ("%s", err_msg);
13216
13217 /* Fast tracepoints are mostly handled by the target, but we can
13218 tell the target how big of an instruction block should be moved
13219 around. */
13220 if (b->type == bp_fast_tracepoint)
13221 {
13222 /* Only test for support at download time; we may not know
13223 target capabilities at definition time. */
13224 if (remote_supports_fast_tracepoints ())
13225 {
13226 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13227 NULL))
13228 {
13229 size_left = buf.size () - strlen (buf.data ());
13230 ret = snprintf (buf.data () + strlen (buf.data ()),
13231 size_left, ":F%x",
13232 gdb_insn_length (loc->gdbarch, tpaddr));
13233
13234 if (ret < 0 || ret >= size_left)
13235 error ("%s", err_msg);
13236 }
13237 else
13238 /* If it passed validation at definition but fails now,
13239 something is very wrong. */
13240 internal_error (__FILE__, __LINE__,
13241 _("Fast tracepoint not "
13242 "valid during download"));
13243 }
13244 else
13245 /* Fast tracepoints are functionally identical to regular
13246 tracepoints, so don't take lack of support as a reason to
13247 give up on the trace run. */
13248 warning (_("Target does not support fast tracepoints, "
13249 "downloading %d as regular tracepoint"), b->number);
13250 }
13251 else if (b->type == bp_static_tracepoint)
13252 {
13253 /* Only test for support at download time; we may not know
13254 target capabilities at definition time. */
13255 if (remote_supports_static_tracepoints ())
13256 {
13257 struct static_tracepoint_marker marker;
13258
13259 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13260 {
13261 size_left = buf.size () - strlen (buf.data ());
13262 ret = snprintf (buf.data () + strlen (buf.data ()),
13263 size_left, ":S");
13264
13265 if (ret < 0 || ret >= size_left)
13266 error ("%s", err_msg);
13267 }
13268 else
13269 error (_("Static tracepoint not valid during download"));
13270 }
13271 else
13272 /* Fast tracepoints are functionally identical to regular
13273 tracepoints, so don't take lack of support as a reason
13274 to give up on the trace run. */
13275 error (_("Target does not support static tracepoints"));
13276 }
13277 /* If the tracepoint has a conditional, make it into an agent
13278 expression and append to the definition. */
13279 if (loc->cond)
13280 {
13281 /* Only test support at download time, we may not know target
13282 capabilities at definition time. */
13283 if (remote_supports_cond_tracepoints ())
13284 {
13285 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13286 loc->cond.get ());
13287
13288 size_left = buf.size () - strlen (buf.data ());
13289
13290 ret = snprintf (buf.data () + strlen (buf.data ()),
13291 size_left, ":X%x,", aexpr->len);
13292
13293 if (ret < 0 || ret >= size_left)
13294 error ("%s", err_msg);
13295
13296 size_left = buf.size () - strlen (buf.data ());
13297
13298 /* Two bytes to encode each aexpr byte, plus the terminating
13299 null byte. */
13300 if (aexpr->len * 2 + 1 > size_left)
13301 error ("%s", err_msg);
13302
13303 pkt = buf.data () + strlen (buf.data ());
13304
13305 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13306 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13307 *pkt = '\0';
13308 }
13309 else
13310 warning (_("Target does not support conditional tracepoints, "
13311 "ignoring tp %d cond"), b->number);
13312 }
13313
13314 if (b->commands || !default_collect.empty ())
13315 {
13316 size_left = buf.size () - strlen (buf.data ());
13317
13318 ret = snprintf (buf.data () + strlen (buf.data ()),
13319 size_left, "-");
13320
13321 if (ret < 0 || ret >= size_left)
13322 error ("%s", err_msg);
13323 }
13324
13325 putpkt (buf.data ());
13326 remote_get_noisy_reply ();
13327 if (strcmp (rs->buf.data (), "OK"))
13328 error (_("Target does not support tracepoints."));
13329
13330 /* do_single_steps (t); */
13331 for (auto action_it = tdp_actions.begin ();
13332 action_it != tdp_actions.end (); action_it++)
13333 {
13334 QUIT; /* Allow user to bail out with ^C. */
13335
13336 bool has_more = ((action_it + 1) != tdp_actions.end ()
13337 || !stepping_actions.empty ());
13338
13339 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13340 b->number, addrbuf, /* address */
13341 action_it->c_str (),
13342 has_more ? '-' : 0);
13343
13344 if (ret < 0 || ret >= buf.size ())
13345 error ("%s", err_msg);
13346
13347 putpkt (buf.data ());
13348 remote_get_noisy_reply ();
13349 if (strcmp (rs->buf.data (), "OK"))
13350 error (_("Error on target while setting tracepoints."));
13351 }
13352
13353 for (auto action_it = stepping_actions.begin ();
13354 action_it != stepping_actions.end (); action_it++)
13355 {
13356 QUIT; /* Allow user to bail out with ^C. */
13357
13358 bool is_first = action_it == stepping_actions.begin ();
13359 bool has_more = (action_it + 1) != stepping_actions.end ();
13360
13361 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13362 b->number, addrbuf, /* address */
13363 is_first ? "S" : "",
13364 action_it->c_str (),
13365 has_more ? "-" : "");
13366
13367 if (ret < 0 || ret >= buf.size ())
13368 error ("%s", err_msg);
13369
13370 putpkt (buf.data ());
13371 remote_get_noisy_reply ();
13372 if (strcmp (rs->buf.data (), "OK"))
13373 error (_("Error on target while setting tracepoints."));
13374 }
13375
13376 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13377 {
13378 if (b->location != NULL)
13379 {
13380 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13381
13382 if (ret < 0 || ret >= buf.size ())
13383 error ("%s", err_msg);
13384
13385 encode_source_string (b->number, loc->address, "at",
13386 event_location_to_string (b->location.get ()),
13387 buf.data () + strlen (buf.data ()),
13388 buf.size () - strlen (buf.data ()));
13389 putpkt (buf.data ());
13390 remote_get_noisy_reply ();
13391 if (strcmp (rs->buf.data (), "OK"))
13392 warning (_("Target does not support source download."));
13393 }
13394 if (b->cond_string)
13395 {
13396 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13397
13398 if (ret < 0 || ret >= buf.size ())
13399 error ("%s", err_msg);
13400
13401 encode_source_string (b->number, loc->address,
13402 "cond", b->cond_string.get (),
13403 buf.data () + strlen (buf.data ()),
13404 buf.size () - strlen (buf.data ()));
13405 putpkt (buf.data ());
13406 remote_get_noisy_reply ();
13407 if (strcmp (rs->buf.data (), "OK"))
13408 warning (_("Target does not support source download."));
13409 }
13410 remote_download_command_source (b->number, loc->address,
13411 breakpoint_commands (b));
13412 }
13413 }
13414
13415 bool
13416 remote_target::can_download_tracepoint ()
13417 {
13418 struct remote_state *rs = get_remote_state ();
13419 struct trace_status *ts;
13420 int status;
13421
13422 /* Don't try to install tracepoints until we've relocated our
13423 symbols, and fetched and merged the target's tracepoint list with
13424 ours. */
13425 if (rs->starting_up)
13426 return false;
13427
13428 ts = current_trace_status ();
13429 status = get_trace_status (ts);
13430
13431 if (status == -1 || !ts->running_known || !ts->running)
13432 return false;
13433
13434 /* If we are in a tracing experiment, but remote stub doesn't support
13435 installing tracepoint in trace, we have to return. */
13436 if (!remote_supports_install_in_trace ())
13437 return false;
13438
13439 return true;
13440 }
13441
13442
13443 void
13444 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13445 {
13446 struct remote_state *rs = get_remote_state ();
13447 char *p;
13448
13449 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13450 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13451 tsv.builtin);
13452 p = rs->buf.data () + strlen (rs->buf.data ());
13453 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13454 >= get_remote_packet_size ())
13455 error (_("Trace state variable name too long for tsv definition packet"));
13456 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13457 *p++ = '\0';
13458 putpkt (rs->buf);
13459 remote_get_noisy_reply ();
13460 if (rs->buf[0] == '\0')
13461 error (_("Target does not support this command."));
13462 if (strcmp (rs->buf.data (), "OK") != 0)
13463 error (_("Error on target while downloading trace state variable."));
13464 }
13465
13466 void
13467 remote_target::enable_tracepoint (struct bp_location *location)
13468 {
13469 struct remote_state *rs = get_remote_state ();
13470
13471 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13472 location->owner->number,
13473 phex (location->address, sizeof (CORE_ADDR)));
13474 putpkt (rs->buf);
13475 remote_get_noisy_reply ();
13476 if (rs->buf[0] == '\0')
13477 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13478 if (strcmp (rs->buf.data (), "OK") != 0)
13479 error (_("Error on target while enabling tracepoint."));
13480 }
13481
13482 void
13483 remote_target::disable_tracepoint (struct bp_location *location)
13484 {
13485 struct remote_state *rs = get_remote_state ();
13486
13487 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13488 location->owner->number,
13489 phex (location->address, sizeof (CORE_ADDR)));
13490 putpkt (rs->buf);
13491 remote_get_noisy_reply ();
13492 if (rs->buf[0] == '\0')
13493 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13494 if (strcmp (rs->buf.data (), "OK") != 0)
13495 error (_("Error on target while disabling tracepoint."));
13496 }
13497
13498 void
13499 remote_target::trace_set_readonly_regions ()
13500 {
13501 asection *s;
13502 bfd_size_type size;
13503 bfd_vma vma;
13504 int anysecs = 0;
13505 int offset = 0;
13506
13507 if (!current_program_space->exec_bfd ())
13508 return; /* No information to give. */
13509
13510 struct remote_state *rs = get_remote_state ();
13511
13512 strcpy (rs->buf.data (), "QTro");
13513 offset = strlen (rs->buf.data ());
13514 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
13515 {
13516 char tmp1[40], tmp2[40];
13517 int sec_length;
13518
13519 if ((s->flags & SEC_LOAD) == 0 ||
13520 /* (s->flags & SEC_CODE) == 0 || */
13521 (s->flags & SEC_READONLY) == 0)
13522 continue;
13523
13524 anysecs = 1;
13525 vma = bfd_section_vma (s);
13526 size = bfd_section_size (s);
13527 sprintf_vma (tmp1, vma);
13528 sprintf_vma (tmp2, vma + size);
13529 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13530 if (offset + sec_length + 1 > rs->buf.size ())
13531 {
13532 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13533 warning (_("\
13534 Too many sections for read-only sections definition packet."));
13535 break;
13536 }
13537 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13538 tmp1, tmp2);
13539 offset += sec_length;
13540 }
13541 if (anysecs)
13542 {
13543 putpkt (rs->buf);
13544 getpkt (&rs->buf, 0);
13545 }
13546 }
13547
13548 void
13549 remote_target::trace_start ()
13550 {
13551 struct remote_state *rs = get_remote_state ();
13552
13553 putpkt ("QTStart");
13554 remote_get_noisy_reply ();
13555 if (rs->buf[0] == '\0')
13556 error (_("Target does not support this command."));
13557 if (strcmp (rs->buf.data (), "OK") != 0)
13558 error (_("Bogus reply from target: %s"), rs->buf.data ());
13559 }
13560
13561 int
13562 remote_target::get_trace_status (struct trace_status *ts)
13563 {
13564 /* Initialize it just to avoid a GCC false warning. */
13565 char *p = NULL;
13566 enum packet_result result;
13567 struct remote_state *rs = get_remote_state ();
13568
13569 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13570 return -1;
13571
13572 /* FIXME we need to get register block size some other way. */
13573 trace_regblock_size
13574 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13575
13576 putpkt ("qTStatus");
13577
13578 try
13579 {
13580 p = remote_get_noisy_reply ();
13581 }
13582 catch (const gdb_exception_error &ex)
13583 {
13584 if (ex.error != TARGET_CLOSE_ERROR)
13585 {
13586 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13587 return -1;
13588 }
13589 throw;
13590 }
13591
13592 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13593
13594 /* If the remote target doesn't do tracing, flag it. */
13595 if (result == PACKET_UNKNOWN)
13596 return -1;
13597
13598 /* We're working with a live target. */
13599 ts->filename = NULL;
13600
13601 if (*p++ != 'T')
13602 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13603
13604 /* Function 'parse_trace_status' sets default value of each field of
13605 'ts' at first, so we don't have to do it here. */
13606 parse_trace_status (p, ts);
13607
13608 return ts->running;
13609 }
13610
13611 void
13612 remote_target::get_tracepoint_status (struct breakpoint *bp,
13613 struct uploaded_tp *utp)
13614 {
13615 struct remote_state *rs = get_remote_state ();
13616 char *reply;
13617 struct tracepoint *tp = (struct tracepoint *) bp;
13618 size_t size = get_remote_packet_size ();
13619
13620 if (tp)
13621 {
13622 tp->hit_count = 0;
13623 tp->traceframe_usage = 0;
13624 for (bp_location *loc : tp->locations ())
13625 {
13626 /* If the tracepoint was never downloaded, don't go asking for
13627 any status. */
13628 if (tp->number_on_target == 0)
13629 continue;
13630 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13631 phex_nz (loc->address, 0));
13632 putpkt (rs->buf);
13633 reply = remote_get_noisy_reply ();
13634 if (reply && *reply)
13635 {
13636 if (*reply == 'V')
13637 parse_tracepoint_status (reply + 1, bp, utp);
13638 }
13639 }
13640 }
13641 else if (utp)
13642 {
13643 utp->hit_count = 0;
13644 utp->traceframe_usage = 0;
13645 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13646 phex_nz (utp->addr, 0));
13647 putpkt (rs->buf);
13648 reply = remote_get_noisy_reply ();
13649 if (reply && *reply)
13650 {
13651 if (*reply == 'V')
13652 parse_tracepoint_status (reply + 1, bp, utp);
13653 }
13654 }
13655 }
13656
13657 void
13658 remote_target::trace_stop ()
13659 {
13660 struct remote_state *rs = get_remote_state ();
13661
13662 putpkt ("QTStop");
13663 remote_get_noisy_reply ();
13664 if (rs->buf[0] == '\0')
13665 error (_("Target does not support this command."));
13666 if (strcmp (rs->buf.data (), "OK") != 0)
13667 error (_("Bogus reply from target: %s"), rs->buf.data ());
13668 }
13669
13670 int
13671 remote_target::trace_find (enum trace_find_type type, int num,
13672 CORE_ADDR addr1, CORE_ADDR addr2,
13673 int *tpp)
13674 {
13675 struct remote_state *rs = get_remote_state ();
13676 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13677 char *p, *reply;
13678 int target_frameno = -1, target_tracept = -1;
13679
13680 /* Lookups other than by absolute frame number depend on the current
13681 trace selected, so make sure it is correct on the remote end
13682 first. */
13683 if (type != tfind_number)
13684 set_remote_traceframe ();
13685
13686 p = rs->buf.data ();
13687 strcpy (p, "QTFrame:");
13688 p = strchr (p, '\0');
13689 switch (type)
13690 {
13691 case tfind_number:
13692 xsnprintf (p, endbuf - p, "%x", num);
13693 break;
13694 case tfind_pc:
13695 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13696 break;
13697 case tfind_tp:
13698 xsnprintf (p, endbuf - p, "tdp:%x", num);
13699 break;
13700 case tfind_range:
13701 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13702 phex_nz (addr2, 0));
13703 break;
13704 case tfind_outside:
13705 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13706 phex_nz (addr2, 0));
13707 break;
13708 default:
13709 error (_("Unknown trace find type %d"), type);
13710 }
13711
13712 putpkt (rs->buf);
13713 reply = remote_get_noisy_reply ();
13714 if (*reply == '\0')
13715 error (_("Target does not support this command."));
13716
13717 while (reply && *reply)
13718 switch (*reply)
13719 {
13720 case 'F':
13721 p = ++reply;
13722 target_frameno = (int) strtol (p, &reply, 16);
13723 if (reply == p)
13724 error (_("Unable to parse trace frame number"));
13725 /* Don't update our remote traceframe number cache on failure
13726 to select a remote traceframe. */
13727 if (target_frameno == -1)
13728 return -1;
13729 break;
13730 case 'T':
13731 p = ++reply;
13732 target_tracept = (int) strtol (p, &reply, 16);
13733 if (reply == p)
13734 error (_("Unable to parse tracepoint number"));
13735 break;
13736 case 'O': /* "OK"? */
13737 if (reply[1] == 'K' && reply[2] == '\0')
13738 reply += 2;
13739 else
13740 error (_("Bogus reply from target: %s"), reply);
13741 break;
13742 default:
13743 error (_("Bogus reply from target: %s"), reply);
13744 }
13745 if (tpp)
13746 *tpp = target_tracept;
13747
13748 rs->remote_traceframe_number = target_frameno;
13749 return target_frameno;
13750 }
13751
13752 bool
13753 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13754 {
13755 struct remote_state *rs = get_remote_state ();
13756 char *reply;
13757 ULONGEST uval;
13758
13759 set_remote_traceframe ();
13760
13761 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13762 putpkt (rs->buf);
13763 reply = remote_get_noisy_reply ();
13764 if (reply && *reply)
13765 {
13766 if (*reply == 'V')
13767 {
13768 unpack_varlen_hex (reply + 1, &uval);
13769 *val = (LONGEST) uval;
13770 return true;
13771 }
13772 }
13773 return false;
13774 }
13775
13776 int
13777 remote_target::save_trace_data (const char *filename)
13778 {
13779 struct remote_state *rs = get_remote_state ();
13780 char *p, *reply;
13781
13782 p = rs->buf.data ();
13783 strcpy (p, "QTSave:");
13784 p += strlen (p);
13785 if ((p - rs->buf.data ()) + strlen (filename) * 2
13786 >= get_remote_packet_size ())
13787 error (_("Remote file name too long for trace save packet"));
13788 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13789 *p++ = '\0';
13790 putpkt (rs->buf);
13791 reply = remote_get_noisy_reply ();
13792 if (*reply == '\0')
13793 error (_("Target does not support this command."));
13794 if (strcmp (reply, "OK") != 0)
13795 error (_("Bogus reply from target: %s"), reply);
13796 return 0;
13797 }
13798
13799 /* This is basically a memory transfer, but needs to be its own packet
13800 because we don't know how the target actually organizes its trace
13801 memory, plus we want to be able to ask for as much as possible, but
13802 not be unhappy if we don't get as much as we ask for. */
13803
13804 LONGEST
13805 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13806 {
13807 struct remote_state *rs = get_remote_state ();
13808 char *reply;
13809 char *p;
13810 int rslt;
13811
13812 p = rs->buf.data ();
13813 strcpy (p, "qTBuffer:");
13814 p += strlen (p);
13815 p += hexnumstr (p, offset);
13816 *p++ = ',';
13817 p += hexnumstr (p, len);
13818 *p++ = '\0';
13819
13820 putpkt (rs->buf);
13821 reply = remote_get_noisy_reply ();
13822 if (reply && *reply)
13823 {
13824 /* 'l' by itself means we're at the end of the buffer and
13825 there is nothing more to get. */
13826 if (*reply == 'l')
13827 return 0;
13828
13829 /* Convert the reply into binary. Limit the number of bytes to
13830 convert according to our passed-in buffer size, rather than
13831 what was returned in the packet; if the target is
13832 unexpectedly generous and gives us a bigger reply than we
13833 asked for, we don't want to crash. */
13834 rslt = hex2bin (reply, buf, len);
13835 return rslt;
13836 }
13837
13838 /* Something went wrong, flag as an error. */
13839 return -1;
13840 }
13841
13842 void
13843 remote_target::set_disconnected_tracing (int val)
13844 {
13845 struct remote_state *rs = get_remote_state ();
13846
13847 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13848 {
13849 char *reply;
13850
13851 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13852 "QTDisconnected:%x", val);
13853 putpkt (rs->buf);
13854 reply = remote_get_noisy_reply ();
13855 if (*reply == '\0')
13856 error (_("Target does not support this command."));
13857 if (strcmp (reply, "OK") != 0)
13858 error (_("Bogus reply from target: %s"), reply);
13859 }
13860 else if (val)
13861 warning (_("Target does not support disconnected tracing."));
13862 }
13863
13864 int
13865 remote_target::core_of_thread (ptid_t ptid)
13866 {
13867 thread_info *info = find_thread_ptid (this, ptid);
13868
13869 if (info != NULL && info->priv != NULL)
13870 return get_remote_thread_info (info)->core;
13871
13872 return -1;
13873 }
13874
13875 void
13876 remote_target::set_circular_trace_buffer (int val)
13877 {
13878 struct remote_state *rs = get_remote_state ();
13879 char *reply;
13880
13881 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13882 "QTBuffer:circular:%x", val);
13883 putpkt (rs->buf);
13884 reply = remote_get_noisy_reply ();
13885 if (*reply == '\0')
13886 error (_("Target does not support this command."));
13887 if (strcmp (reply, "OK") != 0)
13888 error (_("Bogus reply from target: %s"), reply);
13889 }
13890
13891 traceframe_info_up
13892 remote_target::traceframe_info ()
13893 {
13894 gdb::optional<gdb::char_vector> text
13895 = target_read_stralloc (current_inferior ()->top_target (),
13896 TARGET_OBJECT_TRACEFRAME_INFO,
13897 NULL);
13898 if (text)
13899 return parse_traceframe_info (text->data ());
13900
13901 return NULL;
13902 }
13903
13904 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13905 instruction on which a fast tracepoint may be placed. Returns -1
13906 if the packet is not supported, and 0 if the minimum instruction
13907 length is unknown. */
13908
13909 int
13910 remote_target::get_min_fast_tracepoint_insn_len ()
13911 {
13912 struct remote_state *rs = get_remote_state ();
13913 char *reply;
13914
13915 /* If we're not debugging a process yet, the IPA can't be
13916 loaded. */
13917 if (!target_has_execution ())
13918 return 0;
13919
13920 /* Make sure the remote is pointing at the right process. */
13921 set_general_process ();
13922
13923 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13924 putpkt (rs->buf);
13925 reply = remote_get_noisy_reply ();
13926 if (*reply == '\0')
13927 return -1;
13928 else
13929 {
13930 ULONGEST min_insn_len;
13931
13932 unpack_varlen_hex (reply, &min_insn_len);
13933
13934 return (int) min_insn_len;
13935 }
13936 }
13937
13938 void
13939 remote_target::set_trace_buffer_size (LONGEST val)
13940 {
13941 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13942 {
13943 struct remote_state *rs = get_remote_state ();
13944 char *buf = rs->buf.data ();
13945 char *endbuf = buf + get_remote_packet_size ();
13946 enum packet_result result;
13947
13948 gdb_assert (val >= 0 || val == -1);
13949 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13950 /* Send -1 as literal "-1" to avoid host size dependency. */
13951 if (val < 0)
13952 {
13953 *buf++ = '-';
13954 buf += hexnumstr (buf, (ULONGEST) -val);
13955 }
13956 else
13957 buf += hexnumstr (buf, (ULONGEST) val);
13958
13959 putpkt (rs->buf);
13960 remote_get_noisy_reply ();
13961 result = packet_ok (rs->buf,
13962 &remote_protocol_packets[PACKET_QTBuffer_size]);
13963
13964 if (result != PACKET_OK)
13965 warning (_("Bogus reply from target: %s"), rs->buf.data ());
13966 }
13967 }
13968
13969 bool
13970 remote_target::set_trace_notes (const char *user, const char *notes,
13971 const char *stop_notes)
13972 {
13973 struct remote_state *rs = get_remote_state ();
13974 char *reply;
13975 char *buf = rs->buf.data ();
13976 char *endbuf = buf + get_remote_packet_size ();
13977 int nbytes;
13978
13979 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13980 if (user)
13981 {
13982 buf += xsnprintf (buf, endbuf - buf, "user:");
13983 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13984 buf += 2 * nbytes;
13985 *buf++ = ';';
13986 }
13987 if (notes)
13988 {
13989 buf += xsnprintf (buf, endbuf - buf, "notes:");
13990 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13991 buf += 2 * nbytes;
13992 *buf++ = ';';
13993 }
13994 if (stop_notes)
13995 {
13996 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13997 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13998 buf += 2 * nbytes;
13999 *buf++ = ';';
14000 }
14001 /* Ensure the buffer is terminated. */
14002 *buf = '\0';
14003
14004 putpkt (rs->buf);
14005 reply = remote_get_noisy_reply ();
14006 if (*reply == '\0')
14007 return false;
14008
14009 if (strcmp (reply, "OK") != 0)
14010 error (_("Bogus reply from target: %s"), reply);
14011
14012 return true;
14013 }
14014
14015 bool
14016 remote_target::use_agent (bool use)
14017 {
14018 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
14019 {
14020 struct remote_state *rs = get_remote_state ();
14021
14022 /* If the stub supports QAgent. */
14023 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14024 putpkt (rs->buf);
14025 getpkt (&rs->buf, 0);
14026
14027 if (strcmp (rs->buf.data (), "OK") == 0)
14028 {
14029 ::use_agent = use;
14030 return true;
14031 }
14032 }
14033
14034 return false;
14035 }
14036
14037 bool
14038 remote_target::can_use_agent ()
14039 {
14040 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
14041 }
14042
14043 struct btrace_target_info
14044 {
14045 /* The ptid of the traced thread. */
14046 ptid_t ptid;
14047
14048 /* The obtained branch trace configuration. */
14049 struct btrace_config conf;
14050 };
14051
14052 /* Reset our idea of our target's btrace configuration. */
14053
14054 static void
14055 remote_btrace_reset (remote_state *rs)
14056 {
14057 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14058 }
14059
14060 /* Synchronize the configuration with the target. */
14061
14062 void
14063 remote_target::btrace_sync_conf (const btrace_config *conf)
14064 {
14065 struct packet_config *packet;
14066 struct remote_state *rs;
14067 char *buf, *pos, *endbuf;
14068
14069 rs = get_remote_state ();
14070 buf = rs->buf.data ();
14071 endbuf = buf + get_remote_packet_size ();
14072
14073 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
14074 if (packet_config_support (packet) == PACKET_ENABLE
14075 && conf->bts.size != rs->btrace_config.bts.size)
14076 {
14077 pos = buf;
14078 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14079 conf->bts.size);
14080
14081 putpkt (buf);
14082 getpkt (&rs->buf, 0);
14083
14084 if (packet_ok (buf, packet) == PACKET_ERROR)
14085 {
14086 if (buf[0] == 'E' && buf[1] == '.')
14087 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14088 else
14089 error (_("Failed to configure the BTS buffer size."));
14090 }
14091
14092 rs->btrace_config.bts.size = conf->bts.size;
14093 }
14094
14095 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14096 if (packet_config_support (packet) == PACKET_ENABLE
14097 && conf->pt.size != rs->btrace_config.pt.size)
14098 {
14099 pos = buf;
14100 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14101 conf->pt.size);
14102
14103 putpkt (buf);
14104 getpkt (&rs->buf, 0);
14105
14106 if (packet_ok (buf, packet) == PACKET_ERROR)
14107 {
14108 if (buf[0] == 'E' && buf[1] == '.')
14109 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14110 else
14111 error (_("Failed to configure the trace buffer size."));
14112 }
14113
14114 rs->btrace_config.pt.size = conf->pt.size;
14115 }
14116 }
14117
14118 /* Read the current thread's btrace configuration from the target and
14119 store it into CONF. */
14120
14121 static void
14122 btrace_read_config (struct btrace_config *conf)
14123 {
14124 gdb::optional<gdb::char_vector> xml
14125 = target_read_stralloc (current_inferior ()->top_target (),
14126 TARGET_OBJECT_BTRACE_CONF, "");
14127 if (xml)
14128 parse_xml_btrace_conf (conf, xml->data ());
14129 }
14130
14131 /* Maybe reopen target btrace. */
14132
14133 void
14134 remote_target::remote_btrace_maybe_reopen ()
14135 {
14136 struct remote_state *rs = get_remote_state ();
14137 int btrace_target_pushed = 0;
14138 #if !defined (HAVE_LIBIPT)
14139 int warned = 0;
14140 #endif
14141
14142 /* Don't bother walking the entirety of the remote thread list when
14143 we know the feature isn't supported by the remote. */
14144 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14145 return;
14146
14147 scoped_restore_current_thread restore_thread;
14148
14149 for (thread_info *tp : all_non_exited_threads (this))
14150 {
14151 set_general_thread (tp->ptid);
14152
14153 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14154 btrace_read_config (&rs->btrace_config);
14155
14156 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14157 continue;
14158
14159 #if !defined (HAVE_LIBIPT)
14160 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14161 {
14162 if (!warned)
14163 {
14164 warned = 1;
14165 warning (_("Target is recording using Intel Processor Trace "
14166 "but support was disabled at compile time."));
14167 }
14168
14169 continue;
14170 }
14171 #endif /* !defined (HAVE_LIBIPT) */
14172
14173 /* Push target, once, but before anything else happens. This way our
14174 changes to the threads will be cleaned up by unpushing the target
14175 in case btrace_read_config () throws. */
14176 if (!btrace_target_pushed)
14177 {
14178 btrace_target_pushed = 1;
14179 record_btrace_push_target ();
14180 printf_filtered (_("Target is recording using %s.\n"),
14181 btrace_format_string (rs->btrace_config.format));
14182 }
14183
14184 tp->btrace.target = XCNEW (struct btrace_target_info);
14185 tp->btrace.target->ptid = tp->ptid;
14186 tp->btrace.target->conf = rs->btrace_config;
14187 }
14188 }
14189
14190 /* Enable branch tracing. */
14191
14192 struct btrace_target_info *
14193 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
14194 {
14195 struct btrace_target_info *tinfo = NULL;
14196 struct packet_config *packet = NULL;
14197 struct remote_state *rs = get_remote_state ();
14198 char *buf = rs->buf.data ();
14199 char *endbuf = buf + get_remote_packet_size ();
14200
14201 switch (conf->format)
14202 {
14203 case BTRACE_FORMAT_BTS:
14204 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14205 break;
14206
14207 case BTRACE_FORMAT_PT:
14208 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14209 break;
14210 }
14211
14212 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14213 error (_("Target does not support branch tracing."));
14214
14215 btrace_sync_conf (conf);
14216
14217 set_general_thread (ptid);
14218
14219 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14220 putpkt (rs->buf);
14221 getpkt (&rs->buf, 0);
14222
14223 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14224 {
14225 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14226 error (_("Could not enable branch tracing for %s: %s"),
14227 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14228 else
14229 error (_("Could not enable branch tracing for %s."),
14230 target_pid_to_str (ptid).c_str ());
14231 }
14232
14233 tinfo = XCNEW (struct btrace_target_info);
14234 tinfo->ptid = ptid;
14235
14236 /* If we fail to read the configuration, we lose some information, but the
14237 tracing itself is not impacted. */
14238 try
14239 {
14240 btrace_read_config (&tinfo->conf);
14241 }
14242 catch (const gdb_exception_error &err)
14243 {
14244 if (err.message != NULL)
14245 warning ("%s", err.what ());
14246 }
14247
14248 return tinfo;
14249 }
14250
14251 /* Disable branch tracing. */
14252
14253 void
14254 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14255 {
14256 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14257 struct remote_state *rs = get_remote_state ();
14258 char *buf = rs->buf.data ();
14259 char *endbuf = buf + get_remote_packet_size ();
14260
14261 if (packet_config_support (packet) != PACKET_ENABLE)
14262 error (_("Target does not support branch tracing."));
14263
14264 set_general_thread (tinfo->ptid);
14265
14266 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14267 putpkt (rs->buf);
14268 getpkt (&rs->buf, 0);
14269
14270 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14271 {
14272 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14273 error (_("Could not disable branch tracing for %s: %s"),
14274 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14275 else
14276 error (_("Could not disable branch tracing for %s."),
14277 target_pid_to_str (tinfo->ptid).c_str ());
14278 }
14279
14280 xfree (tinfo);
14281 }
14282
14283 /* Teardown branch tracing. */
14284
14285 void
14286 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14287 {
14288 /* We must not talk to the target during teardown. */
14289 xfree (tinfo);
14290 }
14291
14292 /* Read the branch trace. */
14293
14294 enum btrace_error
14295 remote_target::read_btrace (struct btrace_data *btrace,
14296 struct btrace_target_info *tinfo,
14297 enum btrace_read_type type)
14298 {
14299 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14300 const char *annex;
14301
14302 if (packet_config_support (packet) != PACKET_ENABLE)
14303 error (_("Target does not support branch tracing."));
14304
14305 #if !defined(HAVE_LIBEXPAT)
14306 error (_("Cannot process branch tracing result. XML parsing not supported."));
14307 #endif
14308
14309 switch (type)
14310 {
14311 case BTRACE_READ_ALL:
14312 annex = "all";
14313 break;
14314 case BTRACE_READ_NEW:
14315 annex = "new";
14316 break;
14317 case BTRACE_READ_DELTA:
14318 annex = "delta";
14319 break;
14320 default:
14321 internal_error (__FILE__, __LINE__,
14322 _("Bad branch tracing read type: %u."),
14323 (unsigned int) type);
14324 }
14325
14326 gdb::optional<gdb::char_vector> xml
14327 = target_read_stralloc (current_inferior ()->top_target (),
14328 TARGET_OBJECT_BTRACE, annex);
14329 if (!xml)
14330 return BTRACE_ERR_UNKNOWN;
14331
14332 parse_xml_btrace (btrace, xml->data ());
14333
14334 return BTRACE_ERR_NONE;
14335 }
14336
14337 const struct btrace_config *
14338 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14339 {
14340 return &tinfo->conf;
14341 }
14342
14343 bool
14344 remote_target::augmented_libraries_svr4_read ()
14345 {
14346 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14347 == PACKET_ENABLE);
14348 }
14349
14350 /* Implementation of to_load. */
14351
14352 void
14353 remote_target::load (const char *name, int from_tty)
14354 {
14355 generic_load (name, from_tty);
14356 }
14357
14358 /* Accepts an integer PID; returns a string representing a file that
14359 can be opened on the remote side to get the symbols for the child
14360 process. Returns NULL if the operation is not supported. */
14361
14362 char *
14363 remote_target::pid_to_exec_file (int pid)
14364 {
14365 static gdb::optional<gdb::char_vector> filename;
14366 char *annex = NULL;
14367
14368 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14369 return NULL;
14370
14371 inferior *inf = find_inferior_pid (this, pid);
14372 if (inf == NULL)
14373 internal_error (__FILE__, __LINE__,
14374 _("not currently attached to process %d"), pid);
14375
14376 if (!inf->fake_pid_p)
14377 {
14378 const int annex_size = 9;
14379
14380 annex = (char *) alloca (annex_size);
14381 xsnprintf (annex, annex_size, "%x", pid);
14382 }
14383
14384 filename = target_read_stralloc (current_inferior ()->top_target (),
14385 TARGET_OBJECT_EXEC_FILE, annex);
14386
14387 return filename ? filename->data () : nullptr;
14388 }
14389
14390 /* Implement the to_can_do_single_step target_ops method. */
14391
14392 int
14393 remote_target::can_do_single_step ()
14394 {
14395 /* We can only tell whether target supports single step or not by
14396 supported s and S vCont actions if the stub supports vContSupported
14397 feature. If the stub doesn't support vContSupported feature,
14398 we have conservatively to think target doesn't supports single
14399 step. */
14400 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14401 {
14402 struct remote_state *rs = get_remote_state ();
14403
14404 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14405 remote_vcont_probe ();
14406
14407 return rs->supports_vCont.s && rs->supports_vCont.S;
14408 }
14409 else
14410 return 0;
14411 }
14412
14413 /* Implementation of the to_execution_direction method for the remote
14414 target. */
14415
14416 enum exec_direction_kind
14417 remote_target::execution_direction ()
14418 {
14419 struct remote_state *rs = get_remote_state ();
14420
14421 return rs->last_resume_exec_dir;
14422 }
14423
14424 /* Return pointer to the thread_info struct which corresponds to
14425 THREAD_HANDLE (having length HANDLE_LEN). */
14426
14427 thread_info *
14428 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14429 int handle_len,
14430 inferior *inf)
14431 {
14432 for (thread_info *tp : all_non_exited_threads (this))
14433 {
14434 remote_thread_info *priv = get_remote_thread_info (tp);
14435
14436 if (tp->inf == inf && priv != NULL)
14437 {
14438 if (handle_len != priv->thread_handle.size ())
14439 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14440 handle_len, priv->thread_handle.size ());
14441 if (memcmp (thread_handle, priv->thread_handle.data (),
14442 handle_len) == 0)
14443 return tp;
14444 }
14445 }
14446
14447 return NULL;
14448 }
14449
14450 gdb::byte_vector
14451 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14452 {
14453 remote_thread_info *priv = get_remote_thread_info (tp);
14454 return priv->thread_handle;
14455 }
14456
14457 bool
14458 remote_target::can_async_p ()
14459 {
14460 /* This flag should be checked in the common target.c code. */
14461 gdb_assert (target_async_permitted);
14462
14463 /* We're async whenever the serial device can. */
14464 struct remote_state *rs = get_remote_state ();
14465 return serial_can_async_p (rs->remote_desc);
14466 }
14467
14468 bool
14469 remote_target::is_async_p ()
14470 {
14471 /* We're async whenever the serial device is. */
14472 struct remote_state *rs = get_remote_state ();
14473 return serial_is_async_p (rs->remote_desc);
14474 }
14475
14476 /* Pass the SERIAL event on and up to the client. One day this code
14477 will be able to delay notifying the client of an event until the
14478 point where an entire packet has been received. */
14479
14480 static serial_event_ftype remote_async_serial_handler;
14481
14482 static void
14483 remote_async_serial_handler (struct serial *scb, void *context)
14484 {
14485 /* Don't propogate error information up to the client. Instead let
14486 the client find out about the error by querying the target. */
14487 inferior_event_handler (INF_REG_EVENT);
14488 }
14489
14490 static void
14491 remote_async_inferior_event_handler (gdb_client_data data)
14492 {
14493 inferior_event_handler (INF_REG_EVENT);
14494 }
14495
14496 int
14497 remote_target::async_wait_fd ()
14498 {
14499 struct remote_state *rs = get_remote_state ();
14500 return rs->remote_desc->fd;
14501 }
14502
14503 void
14504 remote_target::async (int enable)
14505 {
14506 struct remote_state *rs = get_remote_state ();
14507
14508 if (enable)
14509 {
14510 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14511
14512 /* If there are pending events in the stop reply queue tell the
14513 event loop to process them. */
14514 if (!rs->stop_reply_queue.empty ())
14515 mark_async_event_handler (rs->remote_async_inferior_event_token);
14516 /* For simplicity, below we clear the pending events token
14517 without remembering whether it is marked, so here we always
14518 mark it. If there's actually no pending notification to
14519 process, this ends up being a no-op (other than a spurious
14520 event-loop wakeup). */
14521 if (target_is_non_stop_p ())
14522 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14523 }
14524 else
14525 {
14526 serial_async (rs->remote_desc, NULL, NULL);
14527 /* If the core is disabling async, it doesn't want to be
14528 disturbed with target events. Clear all async event sources
14529 too. */
14530 clear_async_event_handler (rs->remote_async_inferior_event_token);
14531 if (target_is_non_stop_p ())
14532 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14533 }
14534 }
14535
14536 /* Implementation of the to_thread_events method. */
14537
14538 void
14539 remote_target::thread_events (int enable)
14540 {
14541 struct remote_state *rs = get_remote_state ();
14542 size_t size = get_remote_packet_size ();
14543
14544 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14545 return;
14546
14547 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14548 putpkt (rs->buf);
14549 getpkt (&rs->buf, 0);
14550
14551 switch (packet_ok (rs->buf,
14552 &remote_protocol_packets[PACKET_QThreadEvents]))
14553 {
14554 case PACKET_OK:
14555 if (strcmp (rs->buf.data (), "OK") != 0)
14556 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14557 break;
14558 case PACKET_ERROR:
14559 warning (_("Remote failure reply: %s"), rs->buf.data ());
14560 break;
14561 case PACKET_UNKNOWN:
14562 break;
14563 }
14564 }
14565
14566 static void
14567 show_remote_cmd (const char *args, int from_tty)
14568 {
14569 /* We can't just use cmd_show_list here, because we want to skip
14570 the redundant "show remote Z-packet" and the legacy aliases. */
14571 struct cmd_list_element *list = remote_show_cmdlist;
14572 struct ui_out *uiout = current_uiout;
14573
14574 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14575 for (; list != NULL; list = list->next)
14576 if (strcmp (list->name, "Z-packet") == 0)
14577 continue;
14578 else if (list->type == not_set_cmd)
14579 /* Alias commands are exactly like the original, except they
14580 don't have the normal type. */
14581 continue;
14582 else
14583 {
14584 ui_out_emit_tuple option_emitter (uiout, "option");
14585
14586 uiout->field_string ("name", list->name);
14587 uiout->text (": ");
14588 if (list->type == show_cmd)
14589 do_show_command (NULL, from_tty, list);
14590 else
14591 cmd_func (list, NULL, from_tty);
14592 }
14593 }
14594
14595
14596 /* Function to be called whenever a new objfile (shlib) is detected. */
14597 static void
14598 remote_new_objfile (struct objfile *objfile)
14599 {
14600 remote_target *remote = get_current_remote_target ();
14601
14602 /* First, check whether the current inferior's process target is a remote
14603 target. */
14604 if (remote == nullptr)
14605 return;
14606
14607 /* When we are attaching or handling a fork child and the shared library
14608 subsystem reads the list of loaded libraries, we receive new objfile
14609 events in between each found library. The libraries are read in an
14610 undefined order, so if we gave the remote side a chance to look up
14611 symbols between each objfile, we might give it an inconsistent picture
14612 of the inferior. It could appear that a library A appears loaded but
14613 a library B does not, even though library A requires library B. That
14614 would present a state that couldn't normally exist in the inferior.
14615
14616 So, skip these events, we'll give the remote a chance to look up symbols
14617 once all the loaded libraries and their symbols are known to GDB. */
14618 if (current_inferior ()->in_initial_library_scan)
14619 return;
14620
14621 remote->remote_check_symbols ();
14622 }
14623
14624 /* Pull all the tracepoints defined on the target and create local
14625 data structures representing them. We don't want to create real
14626 tracepoints yet, we don't want to mess up the user's existing
14627 collection. */
14628
14629 int
14630 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14631 {
14632 struct remote_state *rs = get_remote_state ();
14633 char *p;
14634
14635 /* Ask for a first packet of tracepoint definition. */
14636 putpkt ("qTfP");
14637 getpkt (&rs->buf, 0);
14638 p = rs->buf.data ();
14639 while (*p && *p != 'l')
14640 {
14641 parse_tracepoint_definition (p, utpp);
14642 /* Ask for another packet of tracepoint definition. */
14643 putpkt ("qTsP");
14644 getpkt (&rs->buf, 0);
14645 p = rs->buf.data ();
14646 }
14647 return 0;
14648 }
14649
14650 int
14651 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14652 {
14653 struct remote_state *rs = get_remote_state ();
14654 char *p;
14655
14656 /* Ask for a first packet of variable definition. */
14657 putpkt ("qTfV");
14658 getpkt (&rs->buf, 0);
14659 p = rs->buf.data ();
14660 while (*p && *p != 'l')
14661 {
14662 parse_tsv_definition (p, utsvp);
14663 /* Ask for another packet of variable definition. */
14664 putpkt ("qTsV");
14665 getpkt (&rs->buf, 0);
14666 p = rs->buf.data ();
14667 }
14668 return 0;
14669 }
14670
14671 /* The "set/show range-stepping" show hook. */
14672
14673 static void
14674 show_range_stepping (struct ui_file *file, int from_tty,
14675 struct cmd_list_element *c,
14676 const char *value)
14677 {
14678 fprintf_filtered (file,
14679 _("Debugger's willingness to use range stepping "
14680 "is %s.\n"), value);
14681 }
14682
14683 /* Return true if the vCont;r action is supported by the remote
14684 stub. */
14685
14686 bool
14687 remote_target::vcont_r_supported ()
14688 {
14689 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14690 remote_vcont_probe ();
14691
14692 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14693 && get_remote_state ()->supports_vCont.r);
14694 }
14695
14696 /* The "set/show range-stepping" set hook. */
14697
14698 static void
14699 set_range_stepping (const char *ignore_args, int from_tty,
14700 struct cmd_list_element *c)
14701 {
14702 /* When enabling, check whether range stepping is actually supported
14703 by the target, and warn if not. */
14704 if (use_range_stepping)
14705 {
14706 remote_target *remote = get_current_remote_target ();
14707 if (remote == NULL
14708 || !remote->vcont_r_supported ())
14709 warning (_("Range stepping is not supported by the current target"));
14710 }
14711 }
14712
14713 static void
14714 show_remote_debug (struct ui_file *file, int from_tty,
14715 struct cmd_list_element *c, const char *value)
14716 {
14717 fprintf_filtered (file, _("Debugging of remote protocol is %s.\n"),
14718 value);
14719 }
14720
14721 static void
14722 show_remote_timeout (struct ui_file *file, int from_tty,
14723 struct cmd_list_element *c, const char *value)
14724 {
14725 fprintf_filtered (file,
14726 _("Timeout limit to wait for target to respond is %s.\n"),
14727 value);
14728 }
14729
14730 /* Implement the "supports_memory_tagging" target_ops method. */
14731
14732 bool
14733 remote_target::supports_memory_tagging ()
14734 {
14735 return remote_memory_tagging_p ();
14736 }
14737
14738 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14739
14740 static void
14741 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14742 size_t len, int type)
14743 {
14744 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14745
14746 std::string request = string_printf ("qMemTags:%s,%s:%s",
14747 phex_nz (address, addr_size),
14748 phex_nz (len, sizeof (len)),
14749 phex_nz (type, sizeof (type)));
14750
14751 strcpy (packet.data (), request.c_str ());
14752 }
14753
14754 /* Parse the qMemTags packet reply into TAGS.
14755
14756 Return true if successful, false otherwise. */
14757
14758 static bool
14759 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14760 gdb::byte_vector &tags)
14761 {
14762 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14763 return false;
14764
14765 /* Copy the tag data. */
14766 tags = hex2bin (reply.data () + 1);
14767
14768 return true;
14769 }
14770
14771 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14772
14773 static void
14774 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14775 size_t len, int type,
14776 const gdb::byte_vector &tags)
14777 {
14778 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14779
14780 /* Put together the main packet, address and length. */
14781 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14782 phex_nz (address, addr_size),
14783 phex_nz (len, sizeof (len)),
14784 phex_nz (type, sizeof (type)));
14785 request += bin2hex (tags.data (), tags.size ());
14786
14787 /* Check if we have exceeded the maximum packet size. */
14788 if (packet.size () < request.length ())
14789 error (_("Contents too big for packet QMemTags."));
14790
14791 strcpy (packet.data (), request.c_str ());
14792 }
14793
14794 /* Implement the "fetch_memtags" target_ops method. */
14795
14796 bool
14797 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14798 gdb::byte_vector &tags, int type)
14799 {
14800 /* Make sure the qMemTags packet is supported. */
14801 if (!remote_memory_tagging_p ())
14802 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14803
14804 struct remote_state *rs = get_remote_state ();
14805
14806 create_fetch_memtags_request (rs->buf, address, len, type);
14807
14808 putpkt (rs->buf);
14809 getpkt (&rs->buf, 0);
14810
14811 return parse_fetch_memtags_reply (rs->buf, tags);
14812 }
14813
14814 /* Implement the "store_memtags" target_ops method. */
14815
14816 bool
14817 remote_target::store_memtags (CORE_ADDR address, size_t len,
14818 const gdb::byte_vector &tags, int type)
14819 {
14820 /* Make sure the QMemTags packet is supported. */
14821 if (!remote_memory_tagging_p ())
14822 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14823
14824 struct remote_state *rs = get_remote_state ();
14825
14826 create_store_memtags_request (rs->buf, address, len, type, tags);
14827
14828 putpkt (rs->buf);
14829 getpkt (&rs->buf, 0);
14830
14831 /* Verify if the request was successful. */
14832 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14833 }
14834
14835 /* Return true if remote target T is non-stop. */
14836
14837 bool
14838 remote_target_is_non_stop_p (remote_target *t)
14839 {
14840 scoped_restore_current_thread restore_thread;
14841 switch_to_target_no_thread (t);
14842
14843 return target_is_non_stop_p ();
14844 }
14845
14846 #if GDB_SELF_TEST
14847
14848 namespace selftests {
14849
14850 static void
14851 test_memory_tagging_functions ()
14852 {
14853 remote_target remote;
14854
14855 struct packet_config *config
14856 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14857
14858 scoped_restore restore_memtag_support_
14859 = make_scoped_restore (&config->support);
14860
14861 /* Test memory tagging packet support. */
14862 config->support = PACKET_SUPPORT_UNKNOWN;
14863 SELF_CHECK (remote.supports_memory_tagging () == false);
14864 config->support = PACKET_DISABLE;
14865 SELF_CHECK (remote.supports_memory_tagging () == false);
14866 config->support = PACKET_ENABLE;
14867 SELF_CHECK (remote.supports_memory_tagging () == true);
14868
14869 /* Setup testing. */
14870 gdb::char_vector packet;
14871 gdb::byte_vector tags, bv;
14872 std::string expected, reply;
14873 packet.resize (32000);
14874
14875 /* Test creating a qMemTags request. */
14876
14877 expected = "qMemTags:0,0:0";
14878 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14879 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14880
14881 expected = "qMemTags:deadbeef,10:1";
14882 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14883 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14884
14885 /* Test parsing a qMemTags reply. */
14886
14887 /* Error reply, tags vector unmodified. */
14888 reply = "E00";
14889 strcpy (packet.data (), reply.c_str ());
14890 tags.resize (0);
14891 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14892 SELF_CHECK (tags.size () == 0);
14893
14894 /* Valid reply, tags vector updated. */
14895 tags.resize (0);
14896 bv.resize (0);
14897
14898 for (int i = 0; i < 5; i++)
14899 bv.push_back (i);
14900
14901 reply = "m" + bin2hex (bv.data (), bv.size ());
14902 strcpy (packet.data (), reply.c_str ());
14903
14904 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14905 SELF_CHECK (tags.size () == 5);
14906
14907 for (int i = 0; i < 5; i++)
14908 SELF_CHECK (tags[i] == i);
14909
14910 /* Test creating a QMemTags request. */
14911
14912 /* Empty tag data. */
14913 tags.resize (0);
14914 expected = "QMemTags:0,0:0:";
14915 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14916 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14917 expected.length ()) == 0);
14918
14919 /* Non-empty tag data. */
14920 tags.resize (0);
14921 for (int i = 0; i < 5; i++)
14922 tags.push_back (i);
14923 expected = "QMemTags:deadbeef,ff:1:0001020304";
14924 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14925 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14926 expected.length ()) == 0);
14927 }
14928
14929 } // namespace selftests
14930 #endif /* GDB_SELF_TEST */
14931
14932 void _initialize_remote ();
14933 void
14934 _initialize_remote ()
14935 {
14936 /* architecture specific data */
14937 remote_g_packet_data_handle =
14938 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14939
14940 add_target (remote_target_info, remote_target::open);
14941 add_target (extended_remote_target_info, extended_remote_target::open);
14942
14943 /* Hook into new objfile notification. */
14944 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
14945
14946 #if 0
14947 init_remote_threadtests ();
14948 #endif
14949
14950 /* set/show remote ... */
14951
14952 add_basic_prefix_cmd ("remote", class_maintenance, _("\
14953 Remote protocol specific variables.\n\
14954 Configure various remote-protocol specific variables such as\n\
14955 the packets being used."),
14956 &remote_set_cmdlist,
14957 0 /* allow-unknown */, &setlist);
14958 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14959 Remote protocol specific variables.\n\
14960 Configure various remote-protocol specific variables such as\n\
14961 the packets being used."),
14962 &remote_show_cmdlist,
14963 0 /* allow-unknown */, &showlist);
14964
14965 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14966 Compare section data on target to the exec file.\n\
14967 Argument is a single section name (default: all loaded sections).\n\
14968 To compare only read-only loaded sections, specify the -r option."),
14969 &cmdlist);
14970
14971 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
14972 Send an arbitrary packet to a remote target.\n\
14973 maintenance packet TEXT\n\
14974 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14975 this command sends the string TEXT to the inferior, and displays the\n\
14976 response packet. GDB supplies the initial `$' character, and the\n\
14977 terminating `#' character and checksum."),
14978 &maintenancelist);
14979
14980 set_show_commands remotebreak_cmds
14981 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14982 Set whether to send break if interrupted."), _("\
14983 Show whether to send break if interrupted."), _("\
14984 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14985 set_remotebreak, show_remotebreak,
14986 &setlist, &showlist);
14987 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
14988 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
14989
14990 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14991 interrupt_sequence_modes, &interrupt_sequence_mode,
14992 _("\
14993 Set interrupt sequence to remote target."), _("\
14994 Show interrupt sequence to remote target."), _("\
14995 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14996 NULL, show_interrupt_sequence,
14997 &remote_set_cmdlist,
14998 &remote_show_cmdlist);
14999
15000 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15001 &interrupt_on_connect, _("\
15002 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15003 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15004 If set, interrupt sequence is sent to remote target."),
15005 NULL, NULL,
15006 &remote_set_cmdlist, &remote_show_cmdlist);
15007
15008 /* Install commands for configuring memory read/write packets. */
15009
15010 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15011 Set the maximum number of bytes per memory write packet (deprecated)."),
15012 &setlist);
15013 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15014 Show the maximum number of bytes per memory write packet (deprecated)."),
15015 &showlist);
15016 add_cmd ("memory-write-packet-size", no_class,
15017 set_memory_write_packet_size, _("\
15018 Set the maximum number of bytes per memory-write packet.\n\
15019 Specify the number of bytes in a packet or 0 (zero) for the\n\
15020 default packet size. The actual limit is further reduced\n\
15021 dependent on the target. Specify ``fixed'' to disable the\n\
15022 further restriction and ``limit'' to enable that restriction."),
15023 &remote_set_cmdlist);
15024 add_cmd ("memory-read-packet-size", no_class,
15025 set_memory_read_packet_size, _("\
15026 Set the maximum number of bytes per memory-read packet.\n\
15027 Specify the number of bytes in a packet or 0 (zero) for the\n\
15028 default packet size. The actual limit is further reduced\n\
15029 dependent on the target. Specify ``fixed'' to disable the\n\
15030 further restriction and ``limit'' to enable that restriction."),
15031 &remote_set_cmdlist);
15032 add_cmd ("memory-write-packet-size", no_class,
15033 show_memory_write_packet_size,
15034 _("Show the maximum number of bytes per memory-write packet."),
15035 &remote_show_cmdlist);
15036 add_cmd ("memory-read-packet-size", no_class,
15037 show_memory_read_packet_size,
15038 _("Show the maximum number of bytes per memory-read packet."),
15039 &remote_show_cmdlist);
15040
15041 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15042 &remote_hw_watchpoint_limit, _("\
15043 Set the maximum number of target hardware watchpoints."), _("\
15044 Show the maximum number of target hardware watchpoints."), _("\
15045 Specify \"unlimited\" for unlimited hardware watchpoints."),
15046 NULL, show_hardware_watchpoint_limit,
15047 &remote_set_cmdlist,
15048 &remote_show_cmdlist);
15049 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15050 no_class,
15051 &remote_hw_watchpoint_length_limit, _("\
15052 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15053 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15054 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15055 NULL, show_hardware_watchpoint_length_limit,
15056 &remote_set_cmdlist, &remote_show_cmdlist);
15057 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15058 &remote_hw_breakpoint_limit, _("\
15059 Set the maximum number of target hardware breakpoints."), _("\
15060 Show the maximum number of target hardware breakpoints."), _("\
15061 Specify \"unlimited\" for unlimited hardware breakpoints."),
15062 NULL, show_hardware_breakpoint_limit,
15063 &remote_set_cmdlist, &remote_show_cmdlist);
15064
15065 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15066 &remote_address_size, _("\
15067 Set the maximum size of the address (in bits) in a memory packet."), _("\
15068 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15069 NULL,
15070 NULL, /* FIXME: i18n: */
15071 &setlist, &showlist);
15072
15073 init_all_packet_configs ();
15074
15075 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
15076 "X", "binary-download", 1);
15077
15078 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
15079 "vCont", "verbose-resume", 0);
15080
15081 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
15082 "QPassSignals", "pass-signals", 0);
15083
15084 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
15085 "QCatchSyscalls", "catch-syscalls", 0);
15086
15087 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
15088 "QProgramSignals", "program-signals", 0);
15089
15090 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
15091 "QSetWorkingDir", "set-working-dir", 0);
15092
15093 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
15094 "QStartupWithShell", "startup-with-shell", 0);
15095
15096 add_packet_config_cmd (&remote_protocol_packets
15097 [PACKET_QEnvironmentHexEncoded],
15098 "QEnvironmentHexEncoded", "environment-hex-encoded",
15099 0);
15100
15101 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
15102 "QEnvironmentReset", "environment-reset",
15103 0);
15104
15105 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15106 "QEnvironmentUnset", "environment-unset",
15107 0);
15108
15109 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
15110 "qSymbol", "symbol-lookup", 0);
15111
15112 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
15113 "P", "set-register", 1);
15114
15115 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
15116 "p", "fetch-register", 1);
15117
15118 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
15119 "Z0", "software-breakpoint", 0);
15120
15121 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
15122 "Z1", "hardware-breakpoint", 0);
15123
15124 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
15125 "Z2", "write-watchpoint", 0);
15126
15127 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
15128 "Z3", "read-watchpoint", 0);
15129
15130 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
15131 "Z4", "access-watchpoint", 0);
15132
15133 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15134 "qXfer:auxv:read", "read-aux-vector", 0);
15135
15136 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15137 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15138
15139 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15140 "qXfer:features:read", "target-features", 0);
15141
15142 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15143 "qXfer:libraries:read", "library-info", 0);
15144
15145 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15146 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15147
15148 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15149 "qXfer:memory-map:read", "memory-map", 0);
15150
15151 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
15152 "qXfer:osdata:read", "osdata", 0);
15153
15154 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15155 "qXfer:threads:read", "threads", 0);
15156
15157 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
15158 "qXfer:siginfo:read", "read-siginfo-object", 0);
15159
15160 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
15161 "qXfer:siginfo:write", "write-siginfo-object", 0);
15162
15163 add_packet_config_cmd
15164 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
15165 "qXfer:traceframe-info:read", "traceframe-info", 0);
15166
15167 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15168 "qXfer:uib:read", "unwind-info-block", 0);
15169
15170 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
15171 "qGetTLSAddr", "get-thread-local-storage-address",
15172 0);
15173
15174 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15175 "qGetTIBAddr", "get-thread-information-block-address",
15176 0);
15177
15178 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15179 "bc", "reverse-continue", 0);
15180
15181 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15182 "bs", "reverse-step", 0);
15183
15184 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15185 "qSupported", "supported-packets", 0);
15186
15187 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15188 "qSearch:memory", "search-memory", 0);
15189
15190 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15191 "qTStatus", "trace-status", 0);
15192
15193 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15194 "vFile:setfs", "hostio-setfs", 0);
15195
15196 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15197 "vFile:open", "hostio-open", 0);
15198
15199 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15200 "vFile:pread", "hostio-pread", 0);
15201
15202 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15203 "vFile:pwrite", "hostio-pwrite", 0);
15204
15205 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15206 "vFile:close", "hostio-close", 0);
15207
15208 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15209 "vFile:unlink", "hostio-unlink", 0);
15210
15211 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15212 "vFile:readlink", "hostio-readlink", 0);
15213
15214 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15215 "vFile:fstat", "hostio-fstat", 0);
15216
15217 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15218 "vAttach", "attach", 0);
15219
15220 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15221 "vRun", "run", 0);
15222
15223 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15224 "QStartNoAckMode", "noack", 0);
15225
15226 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15227 "vKill", "kill", 0);
15228
15229 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15230 "qAttached", "query-attached", 0);
15231
15232 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15233 "ConditionalTracepoints",
15234 "conditional-tracepoints", 0);
15235
15236 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15237 "ConditionalBreakpoints",
15238 "conditional-breakpoints", 0);
15239
15240 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15241 "BreakpointCommands",
15242 "breakpoint-commands", 0);
15243
15244 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15245 "FastTracepoints", "fast-tracepoints", 0);
15246
15247 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15248 "TracepointSource", "TracepointSource", 0);
15249
15250 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15251 "QAllow", "allow", 0);
15252
15253 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15254 "StaticTracepoints", "static-tracepoints", 0);
15255
15256 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15257 "InstallInTrace", "install-in-trace", 0);
15258
15259 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15260 "qXfer:statictrace:read", "read-sdata-object", 0);
15261
15262 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15263 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15264
15265 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15266 "QDisableRandomization", "disable-randomization", 0);
15267
15268 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15269 "QAgent", "agent", 0);
15270
15271 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15272 "QTBuffer:size", "trace-buffer-size", 0);
15273
15274 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15275 "Qbtrace:off", "disable-btrace", 0);
15276
15277 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15278 "Qbtrace:bts", "enable-btrace-bts", 0);
15279
15280 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15281 "Qbtrace:pt", "enable-btrace-pt", 0);
15282
15283 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15284 "qXfer:btrace", "read-btrace", 0);
15285
15286 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15287 "qXfer:btrace-conf", "read-btrace-conf", 0);
15288
15289 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15290 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15291
15292 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15293 "multiprocess-feature", "multiprocess-feature", 0);
15294
15295 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15296 "swbreak-feature", "swbreak-feature", 0);
15297
15298 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15299 "hwbreak-feature", "hwbreak-feature", 0);
15300
15301 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15302 "fork-event-feature", "fork-event-feature", 0);
15303
15304 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15305 "vfork-event-feature", "vfork-event-feature", 0);
15306
15307 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15308 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15309
15310 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15311 "vContSupported", "verbose-resume-supported", 0);
15312
15313 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15314 "exec-event-feature", "exec-event-feature", 0);
15315
15316 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15317 "vCtrlC", "ctrl-c", 0);
15318
15319 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15320 "QThreadEvents", "thread-events", 0);
15321
15322 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15323 "N stop reply", "no-resumed-stop-reply", 0);
15324
15325 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15326 "memory-tagging-feature", "memory-tagging-feature", 0);
15327
15328 /* Assert that we've registered "set remote foo-packet" commands
15329 for all packet configs. */
15330 {
15331 int i;
15332
15333 for (i = 0; i < PACKET_MAX; i++)
15334 {
15335 /* Ideally all configs would have a command associated. Some
15336 still don't though. */
15337 int excepted;
15338
15339 switch (i)
15340 {
15341 case PACKET_QNonStop:
15342 case PACKET_EnableDisableTracepoints_feature:
15343 case PACKET_tracenz_feature:
15344 case PACKET_DisconnectedTracing_feature:
15345 case PACKET_augmented_libraries_svr4_read_feature:
15346 case PACKET_qCRC:
15347 /* Additions to this list need to be well justified:
15348 pre-existing packets are OK; new packets are not. */
15349 excepted = 1;
15350 break;
15351 default:
15352 excepted = 0;
15353 break;
15354 }
15355
15356 /* This catches both forgetting to add a config command, and
15357 forgetting to remove a packet from the exception list. */
15358 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15359 }
15360 }
15361
15362 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15363 Z sub-packet has its own set and show commands, but users may
15364 have sets to this variable in their .gdbinit files (or in their
15365 documentation). */
15366 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15367 &remote_Z_packet_detect, _("\
15368 Set use of remote protocol `Z' packets."), _("\
15369 Show use of remote protocol `Z' packets."), _("\
15370 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15371 packets."),
15372 set_remote_protocol_Z_packet_cmd,
15373 show_remote_protocol_Z_packet_cmd,
15374 /* FIXME: i18n: Use of remote protocol
15375 `Z' packets is %s. */
15376 &remote_set_cmdlist, &remote_show_cmdlist);
15377
15378 add_basic_prefix_cmd ("remote", class_files, _("\
15379 Manipulate files on the remote system.\n\
15380 Transfer files to and from the remote target system."),
15381 &remote_cmdlist,
15382 0 /* allow-unknown */, &cmdlist);
15383
15384 add_cmd ("put", class_files, remote_put_command,
15385 _("Copy a local file to the remote system."),
15386 &remote_cmdlist);
15387
15388 add_cmd ("get", class_files, remote_get_command,
15389 _("Copy a remote file to the local system."),
15390 &remote_cmdlist);
15391
15392 add_cmd ("delete", class_files, remote_delete_command,
15393 _("Delete a remote file."),
15394 &remote_cmdlist);
15395
15396 add_setshow_string_noescape_cmd ("exec-file", class_files,
15397 &remote_exec_file_var, _("\
15398 Set the remote pathname for \"run\"."), _("\
15399 Show the remote pathname for \"run\"."), NULL,
15400 set_remote_exec_file,
15401 show_remote_exec_file,
15402 &remote_set_cmdlist,
15403 &remote_show_cmdlist);
15404
15405 add_setshow_boolean_cmd ("range-stepping", class_run,
15406 &use_range_stepping, _("\
15407 Enable or disable range stepping."), _("\
15408 Show whether target-assisted range stepping is enabled."), _("\
15409 If on, and the target supports it, when stepping a source line, GDB\n\
15410 tells the target to step the corresponding range of addresses itself instead\n\
15411 of issuing multiple single-steps. This speeds up source level\n\
15412 stepping. If off, GDB always issues single-steps, even if range\n\
15413 stepping is supported by the target. The default is on."),
15414 set_range_stepping,
15415 show_range_stepping,
15416 &setlist,
15417 &showlist);
15418
15419 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15420 Set watchdog timer."), _("\
15421 Show watchdog timer."), _("\
15422 When non-zero, this timeout is used instead of waiting forever for a target\n\
15423 to finish a low-level step or continue operation. If the specified amount\n\
15424 of time passes without a response from the target, an error occurs."),
15425 NULL,
15426 show_watchdog,
15427 &setlist, &showlist);
15428
15429 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15430 &remote_packet_max_chars, _("\
15431 Set the maximum number of characters to display for each remote packet."), _("\
15432 Show the maximum number of characters to display for each remote packet."), _("\
15433 Specify \"unlimited\" to display all the characters."),
15434 NULL, show_remote_packet_max_chars,
15435 &setdebuglist, &showdebuglist);
15436
15437 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15438 _("Set debugging of remote protocol."),
15439 _("Show debugging of remote protocol."),
15440 _("\
15441 When enabled, each packet sent or received with the remote target\n\
15442 is displayed."),
15443 NULL,
15444 show_remote_debug,
15445 &setdebuglist, &showdebuglist);
15446
15447 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15448 &remote_timeout, _("\
15449 Set timeout limit to wait for target to respond."), _("\
15450 Show timeout limit to wait for target to respond."), _("\
15451 This value is used to set the time limit for gdb to wait for a response\n\
15452 from the target."),
15453 NULL,
15454 show_remote_timeout,
15455 &setlist, &showlist);
15456
15457 /* Eventually initialize fileio. See fileio.c */
15458 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15459
15460 #if GDB_SELF_TEST
15461 selftests::register_test ("remote_memory_tagging",
15462 selftests::test_memory_tagging_functions);
15463 #endif
15464 }