Remove use of queue from remote.c
[deliverable/binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2018 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* See the GDB User Guide for details of the GDB remote protocol. */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 /*#include "terminal.h" */
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observable.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "filestuff.h"
46 #include "rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdb_sys_time.h"
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "common/scoped_restore.h"
76 #include "environ.h"
77 #include "common/byte-vector.h"
78 #include <unordered_map>
79
80 /* The remote target. */
81
82 static const char remote_doc[] = N_("\
83 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
84 Specify the serial device it is connected to\n\
85 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
86
87 #define OPAQUETHREADBYTES 8
88
89 /* a 64 bit opaque identifier */
90 typedef unsigned char threadref[OPAQUETHREADBYTES];
91
92 struct gdb_ext_thread_info;
93 struct threads_listing_context;
94 typedef int (*rmt_thread_action) (threadref *ref, void *context);
95 struct protocol_feature;
96 struct packet_reg;
97
98 struct stop_reply;
99 static void stop_reply_xfree (struct stop_reply *);
100
101 struct stop_reply_deleter
102 {
103 void operator() (stop_reply *r) const
104 {
105 stop_reply_xfree (r);
106 }
107 };
108
109 typedef std::unique_ptr<stop_reply, stop_reply_deleter> stop_reply_up;
110
111 /* Generic configuration support for packets the stub optionally
112 supports. Allows the user to specify the use of the packet as well
113 as allowing GDB to auto-detect support in the remote stub. */
114
115 enum packet_support
116 {
117 PACKET_SUPPORT_UNKNOWN = 0,
118 PACKET_ENABLE,
119 PACKET_DISABLE
120 };
121
122 /* Analyze a packet's return value and update the packet config
123 accordingly. */
124
125 enum packet_result
126 {
127 PACKET_ERROR,
128 PACKET_OK,
129 PACKET_UNKNOWN
130 };
131
132 struct threads_listing_context;
133
134 /* Stub vCont actions support.
135
136 Each field is a boolean flag indicating whether the stub reports
137 support for the corresponding action. */
138
139 struct vCont_action_support
140 {
141 /* vCont;t */
142 bool t = false;
143
144 /* vCont;r */
145 bool r = false;
146
147 /* vCont;s */
148 bool s = false;
149
150 /* vCont;S */
151 bool S = false;
152 };
153
154 /* About this many threadisds fit in a packet. */
155
156 #define MAXTHREADLISTRESULTS 32
157
158 /* Data for the vFile:pread readahead cache. */
159
160 struct readahead_cache
161 {
162 /* Invalidate the readahead cache. */
163 void invalidate ();
164
165 /* Invalidate the readahead cache if it is holding data for FD. */
166 void invalidate_fd (int fd);
167
168 /* Serve pread from the readahead cache. Returns number of bytes
169 read, or 0 if the request can't be served from the cache. */
170 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
171
172 /* The file descriptor for the file that is being cached. -1 if the
173 cache is invalid. */
174 int fd = -1;
175
176 /* The offset into the file that the cache buffer corresponds
177 to. */
178 ULONGEST offset = 0;
179
180 /* The buffer holding the cache contents. */
181 gdb_byte *buf = nullptr;
182 /* The buffer's size. We try to read as much as fits into a packet
183 at a time. */
184 size_t bufsize = 0;
185
186 /* Cache hit and miss counters. */
187 ULONGEST hit_count = 0;
188 ULONGEST miss_count = 0;
189 };
190
191 /* Description of the remote protocol for a given architecture. */
192
193 struct packet_reg
194 {
195 long offset; /* Offset into G packet. */
196 long regnum; /* GDB's internal register number. */
197 LONGEST pnum; /* Remote protocol register number. */
198 int in_g_packet; /* Always part of G packet. */
199 /* long size in bytes; == register_size (target_gdbarch (), regnum);
200 at present. */
201 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
202 at present. */
203 };
204
205 struct remote_arch_state
206 {
207 explicit remote_arch_state (struct gdbarch *gdbarch);
208
209 /* Description of the remote protocol registers. */
210 long sizeof_g_packet;
211
212 /* Description of the remote protocol registers indexed by REGNUM
213 (making an array gdbarch_num_regs in size). */
214 std::unique_ptr<packet_reg[]> regs;
215
216 /* This is the size (in chars) of the first response to the ``g''
217 packet. It is used as a heuristic when determining the maximum
218 size of memory-read and memory-write packets. A target will
219 typically only reserve a buffer large enough to hold the ``g''
220 packet. The size does not include packet overhead (headers and
221 trailers). */
222 long actual_register_packet_size;
223
224 /* This is the maximum size (in chars) of a non read/write packet.
225 It is also used as a cap on the size of read/write packets. */
226 long remote_packet_size;
227 };
228
229 /* Description of the remote protocol state for the currently
230 connected target. This is per-target state, and independent of the
231 selected architecture. */
232
233 class remote_state
234 {
235 public:
236
237 remote_state ();
238 ~remote_state ();
239
240 /* Get the remote arch state for GDBARCH. */
241 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
242
243 public: /* data */
244
245 /* A buffer to use for incoming packets, and its current size. The
246 buffer is grown dynamically for larger incoming packets.
247 Outgoing packets may also be constructed in this buffer.
248 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
249 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
250 packets. */
251 char *buf;
252 long buf_size;
253
254 /* True if we're going through initial connection setup (finding out
255 about the remote side's threads, relocating symbols, etc.). */
256 bool starting_up = false;
257
258 /* If we negotiated packet size explicitly (and thus can bypass
259 heuristics for the largest packet size that will not overflow
260 a buffer in the stub), this will be set to that packet size.
261 Otherwise zero, meaning to use the guessed size. */
262 long explicit_packet_size = 0;
263
264 /* remote_wait is normally called when the target is running and
265 waits for a stop reply packet. But sometimes we need to call it
266 when the target is already stopped. We can send a "?" packet
267 and have remote_wait read the response. Or, if we already have
268 the response, we can stash it in BUF and tell remote_wait to
269 skip calling getpkt. This flag is set when BUF contains a
270 stop reply packet and the target is not waiting. */
271 int cached_wait_status = 0;
272
273 /* True, if in no ack mode. That is, neither GDB nor the stub will
274 expect acks from each other. The connection is assumed to be
275 reliable. */
276 bool noack_mode = false;
277
278 /* True if we're connected in extended remote mode. */
279 bool extended = false;
280
281 /* True if we resumed the target and we're waiting for the target to
282 stop. In the mean time, we can't start another command/query.
283 The remote server wouldn't be ready to process it, so we'd
284 timeout waiting for a reply that would never come and eventually
285 we'd close the connection. This can happen in asynchronous mode
286 because we allow GDB commands while the target is running. */
287 bool waiting_for_stop_reply = false;
288
289 /* The status of the stub support for the various vCont actions. */
290 vCont_action_support supports_vCont;
291
292 /* True if the user has pressed Ctrl-C, but the target hasn't
293 responded to that. */
294 bool ctrlc_pending_p = false;
295
296 /* True if we saw a Ctrl-C while reading or writing from/to the
297 remote descriptor. At that point it is not safe to send a remote
298 interrupt packet, so we instead remember we saw the Ctrl-C and
299 process it once we're done with sending/receiving the current
300 packet, which should be shortly. If however that takes too long,
301 and the user presses Ctrl-C again, we offer to disconnect. */
302 bool got_ctrlc_during_io = false;
303
304 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
305 remote_open knows that we don't have a file open when the program
306 starts. */
307 struct serial *remote_desc = nullptr;
308
309 /* These are the threads which we last sent to the remote system. The
310 TID member will be -1 for all or -2 for not sent yet. */
311 ptid_t general_thread = null_ptid;
312 ptid_t continue_thread = null_ptid;
313
314 /* This is the traceframe which we last selected on the remote system.
315 It will be -1 if no traceframe is selected. */
316 int remote_traceframe_number = -1;
317
318 char *last_pass_packet = nullptr;
319
320 /* The last QProgramSignals packet sent to the target. We bypass
321 sending a new program signals list down to the target if the new
322 packet is exactly the same as the last we sent. IOW, we only let
323 the target know about program signals list changes. */
324 char *last_program_signals_packet = nullptr;
325
326 gdb_signal last_sent_signal = GDB_SIGNAL_0;
327
328 bool last_sent_step = false;
329
330 /* The execution direction of the last resume we got. */
331 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
332
333 char *finished_object = nullptr;
334 char *finished_annex = nullptr;
335 ULONGEST finished_offset = 0;
336
337 /* Should we try the 'ThreadInfo' query packet?
338
339 This variable (NOT available to the user: auto-detect only!)
340 determines whether GDB will use the new, simpler "ThreadInfo"
341 query or the older, more complex syntax for thread queries.
342 This is an auto-detect variable (set to true at each connect,
343 and set to false when the target fails to recognize it). */
344 bool use_threadinfo_query = false;
345 bool use_threadextra_query = false;
346
347 threadref echo_nextthread {};
348 threadref nextthread {};
349 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
350
351 /* The state of remote notification. */
352 struct remote_notif_state *notif_state = nullptr;
353
354 /* The branch trace configuration. */
355 struct btrace_config btrace_config {};
356
357 /* The argument to the last "vFile:setfs:" packet we sent, used
358 to avoid sending repeated unnecessary "vFile:setfs:" packets.
359 Initialized to -1 to indicate that no "vFile:setfs:" packet
360 has yet been sent. */
361 int fs_pid = -1;
362
363 /* A readahead cache for vFile:pread. Often, reading a binary
364 involves a sequence of small reads. E.g., when parsing an ELF
365 file. A readahead cache helps mostly the case of remote
366 debugging on a connection with higher latency, due to the
367 request/reply nature of the RSP. We only cache data for a single
368 file descriptor at a time. */
369 struct readahead_cache readahead_cache;
370
371 /* The list of already fetched and acknowledged stop events. This
372 queue is used for notification Stop, and other notifications
373 don't need queue for their events, because the notification
374 events of Stop can't be consumed immediately, so that events
375 should be queued first, and be consumed by remote_wait_{ns,as}
376 one per time. Other notifications can consume their events
377 immediately, so queue is not needed for them. */
378 std::vector<stop_reply_up> stop_reply_queue;
379
380 /* Asynchronous signal handle registered as event loop source for
381 when we have pending events ready to be passed to the core. */
382 struct async_event_handler *remote_async_inferior_event_token = nullptr;
383
384 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
385 ``forever'' still use the normal timeout mechanism. This is
386 currently used by the ASYNC code to guarentee that target reads
387 during the initial connect always time-out. Once getpkt has been
388 modified to return a timeout indication and, in turn
389 remote_wait()/wait_for_inferior() have gained a timeout parameter
390 this can go away. */
391 int wait_forever_enabled_p = 1;
392
393 private:
394 /* Mapping of remote protocol data for each gdbarch. Usually there
395 is only one entry here, though we may see more with stubs that
396 support multi-process. */
397 std::unordered_map<struct gdbarch *, remote_arch_state>
398 m_arch_states;
399 };
400
401 static const target_info remote_target_info = {
402 "remote",
403 N_("Remote serial target in gdb-specific protocol"),
404 remote_doc
405 };
406
407 class remote_target : public target_ops
408 {
409 public:
410 remote_target ()
411 {
412 to_stratum = process_stratum;
413 }
414 ~remote_target () override;
415
416 const target_info &info () const override
417 { return remote_target_info; }
418
419 thread_control_capabilities get_thread_control_capabilities () override
420 { return tc_schedlock; }
421
422 /* Open a remote connection. */
423 static void open (const char *, int);
424
425 void close () override;
426
427 void detach (inferior *, int) override;
428 void disconnect (const char *, int) override;
429
430 void commit_resume () override;
431 void resume (ptid_t, int, enum gdb_signal) override;
432 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
433
434 void fetch_registers (struct regcache *, int) override;
435 void store_registers (struct regcache *, int) override;
436 void prepare_to_store (struct regcache *) override;
437
438 void files_info () override;
439
440 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
441
442 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
443 enum remove_bp_reason) override;
444
445
446 bool stopped_by_sw_breakpoint () override;
447 bool supports_stopped_by_sw_breakpoint () override;
448
449 bool stopped_by_hw_breakpoint () override;
450
451 bool supports_stopped_by_hw_breakpoint () override;
452
453 bool stopped_by_watchpoint () override;
454
455 bool stopped_data_address (CORE_ADDR *) override;
456
457 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
458
459 int can_use_hw_breakpoint (enum bptype, int, int) override;
460
461 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
462
463 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
464
465 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
466
467 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
468 struct expression *) override;
469
470 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
471 struct expression *) override;
472
473 void kill () override;
474
475 void load (const char *, int) override;
476
477 void mourn_inferior () override;
478
479 void pass_signals (int, unsigned char *) override;
480
481 int set_syscall_catchpoint (int, bool, int,
482 gdb::array_view<const int>) override;
483
484 void program_signals (int, unsigned char *) override;
485
486 bool thread_alive (ptid_t ptid) override;
487
488 const char *thread_name (struct thread_info *) override;
489
490 void update_thread_list () override;
491
492 const char *pid_to_str (ptid_t) override;
493
494 const char *extra_thread_info (struct thread_info *) override;
495
496 ptid_t get_ada_task_ptid (long lwp, long thread) override;
497
498 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
499 int handle_len,
500 inferior *inf) override;
501
502 void stop (ptid_t) override;
503
504 void interrupt () override;
505
506 void pass_ctrlc () override;
507
508 enum target_xfer_status xfer_partial (enum target_object object,
509 const char *annex,
510 gdb_byte *readbuf,
511 const gdb_byte *writebuf,
512 ULONGEST offset, ULONGEST len,
513 ULONGEST *xfered_len) override;
514
515 ULONGEST get_memory_xfer_limit () override;
516
517 void rcmd (const char *command, struct ui_file *output) override;
518
519 char *pid_to_exec_file (int pid) override;
520
521 void log_command (const char *cmd) override
522 {
523 serial_log_command (this, cmd);
524 }
525
526 CORE_ADDR get_thread_local_address (ptid_t ptid,
527 CORE_ADDR load_module_addr,
528 CORE_ADDR offset) override;
529
530 bool has_all_memory () override { return default_child_has_all_memory (); }
531 bool has_memory () override { return default_child_has_memory (); }
532 bool has_stack () override { return default_child_has_stack (); }
533 bool has_registers () override { return default_child_has_registers (); }
534 bool has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
535
536 bool can_execute_reverse () override;
537
538 std::vector<mem_region> memory_map () override;
539
540 void flash_erase (ULONGEST address, LONGEST length) override;
541
542 void flash_done () override;
543
544 const struct target_desc *read_description () override;
545
546 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
547 const gdb_byte *pattern, ULONGEST pattern_len,
548 CORE_ADDR *found_addrp) override;
549
550 bool can_async_p () override;
551
552 bool is_async_p () override;
553
554 void async (int) override;
555
556 void thread_events (int) override;
557
558 int can_do_single_step () override;
559
560 void terminal_inferior () override;
561
562 void terminal_ours () override;
563
564 bool supports_non_stop () override;
565
566 bool supports_multi_process () override;
567
568 bool supports_disable_randomization () override;
569
570 bool filesystem_is_local () override;
571
572
573 int fileio_open (struct inferior *inf, const char *filename,
574 int flags, int mode, int warn_if_slow,
575 int *target_errno) override;
576
577 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
578 ULONGEST offset, int *target_errno) override;
579
580 int fileio_pread (int fd, gdb_byte *read_buf, int len,
581 ULONGEST offset, int *target_errno) override;
582
583 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
584
585 int fileio_close (int fd, int *target_errno) override;
586
587 int fileio_unlink (struct inferior *inf,
588 const char *filename,
589 int *target_errno) override;
590
591 gdb::optional<std::string>
592 fileio_readlink (struct inferior *inf,
593 const char *filename,
594 int *target_errno) override;
595
596 bool supports_enable_disable_tracepoint () override;
597
598 bool supports_string_tracing () override;
599
600 bool supports_evaluation_of_breakpoint_conditions () override;
601
602 bool can_run_breakpoint_commands () override;
603
604 void trace_init () override;
605
606 void download_tracepoint (struct bp_location *location) override;
607
608 bool can_download_tracepoint () override;
609
610 void download_trace_state_variable (const trace_state_variable &tsv) override;
611
612 void enable_tracepoint (struct bp_location *location) override;
613
614 void disable_tracepoint (struct bp_location *location) override;
615
616 void trace_set_readonly_regions () override;
617
618 void trace_start () override;
619
620 int get_trace_status (struct trace_status *ts) override;
621
622 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
623 override;
624
625 void trace_stop () override;
626
627 int trace_find (enum trace_find_type type, int num,
628 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
629
630 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
631
632 int save_trace_data (const char *filename) override;
633
634 int upload_tracepoints (struct uploaded_tp **utpp) override;
635
636 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
637
638 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
639
640 int get_min_fast_tracepoint_insn_len () override;
641
642 void set_disconnected_tracing (int val) override;
643
644 void set_circular_trace_buffer (int val) override;
645
646 void set_trace_buffer_size (LONGEST val) override;
647
648 bool set_trace_notes (const char *user, const char *notes,
649 const char *stopnotes) override;
650
651 int core_of_thread (ptid_t ptid) override;
652
653 int verify_memory (const gdb_byte *data,
654 CORE_ADDR memaddr, ULONGEST size) override;
655
656
657 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
658
659 void set_permissions () override;
660
661 bool static_tracepoint_marker_at (CORE_ADDR,
662 struct static_tracepoint_marker *marker)
663 override;
664
665 std::vector<static_tracepoint_marker>
666 static_tracepoint_markers_by_strid (const char *id) override;
667
668 traceframe_info_up traceframe_info () override;
669
670 bool use_agent (bool use) override;
671 bool can_use_agent () override;
672
673 struct btrace_target_info *enable_btrace (ptid_t ptid,
674 const struct btrace_config *conf) override;
675
676 void disable_btrace (struct btrace_target_info *tinfo) override;
677
678 void teardown_btrace (struct btrace_target_info *tinfo) override;
679
680 enum btrace_error read_btrace (struct btrace_data *data,
681 struct btrace_target_info *btinfo,
682 enum btrace_read_type type) override;
683
684 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
685 bool augmented_libraries_svr4_read () override;
686 int follow_fork (int, int) override;
687 void follow_exec (struct inferior *, char *) override;
688 int insert_fork_catchpoint (int) override;
689 int remove_fork_catchpoint (int) override;
690 int insert_vfork_catchpoint (int) override;
691 int remove_vfork_catchpoint (int) override;
692 int insert_exec_catchpoint (int) override;
693 int remove_exec_catchpoint (int) override;
694 enum exec_direction_kind execution_direction () override;
695
696 public: /* Remote specific methods. */
697
698 void remote_download_command_source (int num, ULONGEST addr,
699 struct command_line *cmds);
700
701 void remote_file_put (const char *local_file, const char *remote_file,
702 int from_tty);
703 void remote_file_get (const char *remote_file, const char *local_file,
704 int from_tty);
705 void remote_file_delete (const char *remote_file, int from_tty);
706
707 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, int *remote_errno);
709 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
710 ULONGEST offset, int *remote_errno);
711 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
712 ULONGEST offset, int *remote_errno);
713
714 int remote_hostio_send_command (int command_bytes, int which_packet,
715 int *remote_errno, char **attachment,
716 int *attachment_len);
717 int remote_hostio_set_filesystem (struct inferior *inf,
718 int *remote_errno);
719 /* We should get rid of this and use fileio_open directly. */
720 int remote_hostio_open (struct inferior *inf, const char *filename,
721 int flags, int mode, int warn_if_slow,
722 int *remote_errno);
723 int remote_hostio_close (int fd, int *remote_errno);
724
725 int remote_hostio_unlink (inferior *inf, const char *filename,
726 int *remote_errno);
727
728 struct remote_state *get_remote_state ();
729
730 long get_remote_packet_size (void);
731 long get_memory_packet_size (struct memory_packet_config *config);
732
733 long get_memory_write_packet_size ();
734 long get_memory_read_packet_size ();
735
736 char *append_pending_thread_resumptions (char *p, char *endp,
737 ptid_t ptid);
738 static void open_1 (const char *name, int from_tty, int extended_p);
739 void start_remote (int from_tty, int extended_p);
740 void remote_detach_1 (int from_tty, struct inferior *inf);
741
742 char *append_resumption (char *p, char *endp,
743 ptid_t ptid, int step, gdb_signal siggnal);
744 int remote_resume_with_vcont (ptid_t ptid, int step,
745 gdb_signal siggnal);
746
747 void add_current_inferior_and_thread (char *wait_status);
748
749 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
750 int options);
751 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
752 int options);
753
754 ptid_t process_stop_reply (struct stop_reply *stop_reply,
755 target_waitstatus *status);
756
757 void remote_notice_new_inferior (ptid_t currthread, int executing);
758
759 void process_initial_stop_replies (int from_tty);
760
761 void remote_add_thread (ptid_t ptid, bool running, bool executing);
762
763 void btrace_sync_conf (const btrace_config *conf);
764
765 void remote_btrace_maybe_reopen ();
766
767 void remove_new_fork_children (threads_listing_context *context);
768 void kill_new_fork_children (int pid);
769 void discard_pending_stop_replies (struct inferior *inf);
770 int stop_reply_queue_length ();
771
772 void check_pending_events_prevent_wildcard_vcont
773 (int *may_global_wildcard_vcont);
774
775 void discard_pending_stop_replies_in_queue ();
776 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
777 struct stop_reply *queued_stop_reply (ptid_t ptid);
778 int peek_stop_reply (ptid_t ptid);
779 void remote_parse_stop_reply (char *buf, stop_reply *event);
780
781 void remote_stop_ns (ptid_t ptid);
782 void remote_interrupt_as ();
783 void remote_interrupt_ns ();
784
785 char *remote_get_noisy_reply ();
786 int remote_query_attached (int pid);
787 inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
788 int try_open_exec);
789
790 ptid_t remote_current_thread (ptid_t oldpid);
791 ptid_t get_current_thread (char *wait_status);
792
793 void set_thread (ptid_t ptid, int gen);
794 void set_general_thread (ptid_t ptid);
795 void set_continue_thread (ptid_t ptid);
796 void set_general_process ();
797
798 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
799
800 int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
801 gdb_ext_thread_info *info);
802 int remote_get_threadinfo (threadref *threadid, int fieldset,
803 gdb_ext_thread_info *info);
804
805 int parse_threadlist_response (char *pkt, int result_limit,
806 threadref *original_echo,
807 threadref *resultlist,
808 int *doneflag);
809 int remote_get_threadlist (int startflag, threadref *nextthread,
810 int result_limit, int *done, int *result_count,
811 threadref *threadlist);
812
813 int remote_threadlist_iterator (rmt_thread_action stepfunction,
814 void *context, int looplimit);
815
816 int remote_get_threads_with_ql (threads_listing_context *context);
817 int remote_get_threads_with_qxfer (threads_listing_context *context);
818 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
819
820 void extended_remote_restart ();
821
822 void get_offsets ();
823
824 void remote_check_symbols ();
825
826 void remote_supported_packet (const struct protocol_feature *feature,
827 enum packet_support support,
828 const char *argument);
829
830 void remote_query_supported ();
831
832 void remote_packet_size (const protocol_feature *feature,
833 packet_support support, const char *value);
834
835 void remote_serial_quit_handler ();
836
837 void remote_detach_pid (int pid);
838
839 void remote_vcont_probe ();
840
841 void remote_resume_with_hc (ptid_t ptid, int step,
842 gdb_signal siggnal);
843
844 void send_interrupt_sequence ();
845 void interrupt_query ();
846
847 void remote_notif_get_pending_events (notif_client *nc);
848
849 int fetch_register_using_p (struct regcache *regcache,
850 packet_reg *reg);
851 int send_g_packet ();
852 void process_g_packet (struct regcache *regcache);
853 void fetch_registers_using_g (struct regcache *regcache);
854 int store_register_using_P (const struct regcache *regcache,
855 packet_reg *reg);
856 void store_registers_using_G (const struct regcache *regcache);
857
858 void set_remote_traceframe ();
859
860 void check_binary_download (CORE_ADDR addr);
861
862 target_xfer_status remote_write_bytes_aux (const char *header,
863 CORE_ADDR memaddr,
864 const gdb_byte *myaddr,
865 ULONGEST len_units,
866 int unit_size,
867 ULONGEST *xfered_len_units,
868 char packet_format,
869 int use_length);
870
871 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
872 const gdb_byte *myaddr, ULONGEST len,
873 int unit_size, ULONGEST *xfered_len);
874
875 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
876 ULONGEST len_units,
877 int unit_size, ULONGEST *xfered_len_units);
878
879 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
880 ULONGEST memaddr,
881 ULONGEST len,
882 int unit_size,
883 ULONGEST *xfered_len);
884
885 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
886 gdb_byte *myaddr, ULONGEST len,
887 int unit_size,
888 ULONGEST *xfered_len);
889
890 packet_result remote_send_printf (const char *format, ...)
891 ATTRIBUTE_PRINTF (2, 3);
892
893 target_xfer_status remote_flash_write (ULONGEST address,
894 ULONGEST length, ULONGEST *xfered_len,
895 const gdb_byte *data);
896
897 int readchar (int timeout);
898
899 void remote_serial_write (const char *str, int len);
900
901 int putpkt (const char *buf);
902 int putpkt_binary (const char *buf, int cnt);
903
904 void skip_frame ();
905 long read_frame (char **buf_p, long *sizeof_buf);
906 void getpkt (char **buf, long *sizeof_buf, int forever);
907 int getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
908 int expecting_notif, int *is_notif);
909 int getpkt_sane (char **buf, long *sizeof_buf, int forever);
910 int getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
911 int *is_notif);
912 int remote_vkill (int pid);
913 void remote_kill_k ();
914
915 void extended_remote_disable_randomization (int val);
916 int extended_remote_run (const std::string &args);
917
918 void send_environment_packet (const char *action,
919 const char *packet,
920 const char *value);
921
922 void extended_remote_environment_support ();
923 void extended_remote_set_inferior_cwd ();
924
925 target_xfer_status remote_write_qxfer (const char *object_name,
926 const char *annex,
927 const gdb_byte *writebuf,
928 ULONGEST offset, LONGEST len,
929 ULONGEST *xfered_len,
930 struct packet_config *packet);
931
932 target_xfer_status remote_read_qxfer (const char *object_name,
933 const char *annex,
934 gdb_byte *readbuf, ULONGEST offset,
935 LONGEST len,
936 ULONGEST *xfered_len,
937 struct packet_config *packet);
938
939 void push_stop_reply (struct stop_reply *new_event);
940
941 bool vcont_r_supported ();
942
943 void packet_command (const char *args, int from_tty);
944
945 private: /* data fields */
946
947 /* The remote state. Don't reference this directly. Use the
948 get_remote_state method instead. */
949 remote_state m_remote_state;
950 };
951
952 static const target_info extended_remote_target_info = {
953 "extended-remote",
954 N_("Extended remote serial target in gdb-specific protocol"),
955 remote_doc
956 };
957
958 /* Set up the extended remote target by extending the standard remote
959 target and adding to it. */
960
961 class extended_remote_target final : public remote_target
962 {
963 public:
964 const target_info &info () const override
965 { return extended_remote_target_info; }
966
967 /* Open an extended-remote connection. */
968 static void open (const char *, int);
969
970 bool can_create_inferior () override { return true; }
971 void create_inferior (const char *, const std::string &,
972 char **, int) override;
973
974 void detach (inferior *, int) override;
975
976 bool can_attach () override { return true; }
977 void attach (const char *, int) override;
978
979 void post_attach (int) override;
980 bool supports_disable_randomization () override;
981 };
982
983 /* Per-program-space data key. */
984 static const struct program_space_data *remote_pspace_data;
985
986 /* The variable registered as the control variable used by the
987 remote exec-file commands. While the remote exec-file setting is
988 per-program-space, the set/show machinery uses this as the
989 location of the remote exec-file value. */
990 static char *remote_exec_file_var;
991
992 /* The size to align memory write packets, when practical. The protocol
993 does not guarantee any alignment, and gdb will generate short
994 writes and unaligned writes, but even as a best-effort attempt this
995 can improve bulk transfers. For instance, if a write is misaligned
996 relative to the target's data bus, the stub may need to make an extra
997 round trip fetching data from the target. This doesn't make a
998 huge difference, but it's easy to do, so we try to be helpful.
999
1000 The alignment chosen is arbitrary; usually data bus width is
1001 important here, not the possibly larger cache line size. */
1002 enum { REMOTE_ALIGN_WRITES = 16 };
1003
1004 /* Prototypes for local functions. */
1005
1006 static int hexnumlen (ULONGEST num);
1007
1008 static int stubhex (int ch);
1009
1010 static int hexnumstr (char *, ULONGEST);
1011
1012 static int hexnumnstr (char *, ULONGEST, int);
1013
1014 static CORE_ADDR remote_address_masked (CORE_ADDR);
1015
1016 static void print_packet (const char *);
1017
1018 static int stub_unpack_int (char *buff, int fieldlength);
1019
1020 struct packet_config;
1021
1022 static void show_packet_config_cmd (struct packet_config *config);
1023
1024 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1025 int from_tty,
1026 struct cmd_list_element *c,
1027 const char *value);
1028
1029 static ptid_t read_ptid (const char *buf, const char **obuf);
1030
1031 static void remote_async_inferior_event_handler (gdb_client_data);
1032
1033 static int remote_read_description_p (struct target_ops *target);
1034
1035 static void remote_console_output (char *msg);
1036
1037 static void remote_btrace_reset (remote_state *rs);
1038
1039 static void remote_unpush_and_throw (void);
1040
1041 /* For "remote". */
1042
1043 static struct cmd_list_element *remote_cmdlist;
1044
1045 /* For "set remote" and "show remote". */
1046
1047 static struct cmd_list_element *remote_set_cmdlist;
1048 static struct cmd_list_element *remote_show_cmdlist;
1049
1050 /* Controls whether GDB is willing to use range stepping. */
1051
1052 static int use_range_stepping = 1;
1053
1054 /* The max number of chars in debug output. The rest of chars are
1055 omitted. */
1056
1057 #define REMOTE_DEBUG_MAX_CHAR 512
1058
1059 /* Private data that we'll store in (struct thread_info)->priv. */
1060 struct remote_thread_info : public private_thread_info
1061 {
1062 std::string extra;
1063 std::string name;
1064 int core = -1;
1065
1066 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1067 sequence of bytes. */
1068 gdb::byte_vector thread_handle;
1069
1070 /* Whether the target stopped for a breakpoint/watchpoint. */
1071 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1072
1073 /* This is set to the data address of the access causing the target
1074 to stop for a watchpoint. */
1075 CORE_ADDR watch_data_address = 0;
1076
1077 /* Fields used by the vCont action coalescing implemented in
1078 remote_resume / remote_commit_resume. remote_resume stores each
1079 thread's last resume request in these fields, so that a later
1080 remote_commit_resume knows which is the proper action for this
1081 thread to include in the vCont packet. */
1082
1083 /* True if the last target_resume call for this thread was a step
1084 request, false if a continue request. */
1085 int last_resume_step = 0;
1086
1087 /* The signal specified in the last target_resume call for this
1088 thread. */
1089 gdb_signal last_resume_sig = GDB_SIGNAL_0;
1090
1091 /* Whether this thread was already vCont-resumed on the remote
1092 side. */
1093 int vcont_resumed = 0;
1094 };
1095
1096 remote_state::remote_state ()
1097 {
1098 /* The default buffer size is unimportant; it will be expanded
1099 whenever a larger buffer is needed. */
1100 this->buf_size = 400;
1101 this->buf = (char *) xmalloc (this->buf_size);
1102 }
1103
1104 remote_state::~remote_state ()
1105 {
1106 xfree (this->last_pass_packet);
1107 xfree (this->last_program_signals_packet);
1108 xfree (this->buf);
1109 xfree (this->finished_object);
1110 xfree (this->finished_annex);
1111 }
1112
1113 /* Utility: generate error from an incoming stub packet. */
1114 static void
1115 trace_error (char *buf)
1116 {
1117 if (*buf++ != 'E')
1118 return; /* not an error msg */
1119 switch (*buf)
1120 {
1121 case '1': /* malformed packet error */
1122 if (*++buf == '0') /* general case: */
1123 error (_("remote.c: error in outgoing packet."));
1124 else
1125 error (_("remote.c: error in outgoing packet at field #%ld."),
1126 strtol (buf, NULL, 16));
1127 default:
1128 error (_("Target returns error code '%s'."), buf);
1129 }
1130 }
1131
1132 /* Utility: wait for reply from stub, while accepting "O" packets. */
1133
1134 char *
1135 remote_target::remote_get_noisy_reply ()
1136 {
1137 struct remote_state *rs = get_remote_state ();
1138
1139 do /* Loop on reply from remote stub. */
1140 {
1141 char *buf;
1142
1143 QUIT; /* Allow user to bail out with ^C. */
1144 getpkt (&rs->buf, &rs->buf_size, 0);
1145 buf = rs->buf;
1146 if (buf[0] == 'E')
1147 trace_error (buf);
1148 else if (startswith (buf, "qRelocInsn:"))
1149 {
1150 ULONGEST ul;
1151 CORE_ADDR from, to, org_to;
1152 const char *p, *pp;
1153 int adjusted_size = 0;
1154 int relocated = 0;
1155
1156 p = buf + strlen ("qRelocInsn:");
1157 pp = unpack_varlen_hex (p, &ul);
1158 if (*pp != ';')
1159 error (_("invalid qRelocInsn packet: %s"), buf);
1160 from = ul;
1161
1162 p = pp + 1;
1163 unpack_varlen_hex (p, &ul);
1164 to = ul;
1165
1166 org_to = to;
1167
1168 TRY
1169 {
1170 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1171 relocated = 1;
1172 }
1173 CATCH (ex, RETURN_MASK_ALL)
1174 {
1175 if (ex.error == MEMORY_ERROR)
1176 {
1177 /* Propagate memory errors silently back to the
1178 target. The stub may have limited the range of
1179 addresses we can write to, for example. */
1180 }
1181 else
1182 {
1183 /* Something unexpectedly bad happened. Be verbose
1184 so we can tell what, and propagate the error back
1185 to the stub, so it doesn't get stuck waiting for
1186 a response. */
1187 exception_fprintf (gdb_stderr, ex,
1188 _("warning: relocating instruction: "));
1189 }
1190 putpkt ("E01");
1191 }
1192 END_CATCH
1193
1194 if (relocated)
1195 {
1196 adjusted_size = to - org_to;
1197
1198 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
1199 putpkt (buf);
1200 }
1201 }
1202 else if (buf[0] == 'O' && buf[1] != 'K')
1203 remote_console_output (buf + 1); /* 'O' message from stub */
1204 else
1205 return buf; /* Here's the actual reply. */
1206 }
1207 while (1);
1208 }
1209
1210 struct remote_arch_state *
1211 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1212 {
1213 remote_arch_state *rsa;
1214
1215 auto it = this->m_arch_states.find (gdbarch);
1216 if (it == this->m_arch_states.end ())
1217 {
1218 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1219 std::forward_as_tuple (gdbarch),
1220 std::forward_as_tuple (gdbarch));
1221 rsa = &p.first->second;
1222
1223 /* Make sure that the packet buffer is plenty big enough for
1224 this architecture. */
1225 if (this->buf_size < rsa->remote_packet_size)
1226 {
1227 this->buf_size = 2 * rsa->remote_packet_size;
1228 this->buf = (char *) xrealloc (this->buf, this->buf_size);
1229 }
1230 }
1231 else
1232 rsa = &it->second;
1233
1234 return rsa;
1235 }
1236
1237 /* Fetch the global remote target state. */
1238
1239 remote_state *
1240 remote_target::get_remote_state ()
1241 {
1242 /* Make sure that the remote architecture state has been
1243 initialized, because doing so might reallocate rs->buf. Any
1244 function which calls getpkt also needs to be mindful of changes
1245 to rs->buf, but this call limits the number of places which run
1246 into trouble. */
1247 m_remote_state.get_remote_arch_state (target_gdbarch ());
1248
1249 return &m_remote_state;
1250 }
1251
1252 /* Cleanup routine for the remote module's pspace data. */
1253
1254 static void
1255 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1256 {
1257 char *remote_exec_file = (char *) arg;
1258
1259 xfree (remote_exec_file);
1260 }
1261
1262 /* Fetch the remote exec-file from the current program space. */
1263
1264 static const char *
1265 get_remote_exec_file (void)
1266 {
1267 char *remote_exec_file;
1268
1269 remote_exec_file
1270 = (char *) program_space_data (current_program_space,
1271 remote_pspace_data);
1272 if (remote_exec_file == NULL)
1273 return "";
1274
1275 return remote_exec_file;
1276 }
1277
1278 /* Set the remote exec file for PSPACE. */
1279
1280 static void
1281 set_pspace_remote_exec_file (struct program_space *pspace,
1282 char *remote_exec_file)
1283 {
1284 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
1285
1286 xfree (old_file);
1287 set_program_space_data (pspace, remote_pspace_data,
1288 xstrdup (remote_exec_file));
1289 }
1290
1291 /* The "set/show remote exec-file" set command hook. */
1292
1293 static void
1294 set_remote_exec_file (const char *ignored, int from_tty,
1295 struct cmd_list_element *c)
1296 {
1297 gdb_assert (remote_exec_file_var != NULL);
1298 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1299 }
1300
1301 /* The "set/show remote exec-file" show command hook. */
1302
1303 static void
1304 show_remote_exec_file (struct ui_file *file, int from_tty,
1305 struct cmd_list_element *cmd, const char *value)
1306 {
1307 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1308 }
1309
1310 static int
1311 compare_pnums (const void *lhs_, const void *rhs_)
1312 {
1313 const struct packet_reg * const *lhs
1314 = (const struct packet_reg * const *) lhs_;
1315 const struct packet_reg * const *rhs
1316 = (const struct packet_reg * const *) rhs_;
1317
1318 if ((*lhs)->pnum < (*rhs)->pnum)
1319 return -1;
1320 else if ((*lhs)->pnum == (*rhs)->pnum)
1321 return 0;
1322 else
1323 return 1;
1324 }
1325
1326 static int
1327 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1328 {
1329 int regnum, num_remote_regs, offset;
1330 struct packet_reg **remote_regs;
1331
1332 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1333 {
1334 struct packet_reg *r = &regs[regnum];
1335
1336 if (register_size (gdbarch, regnum) == 0)
1337 /* Do not try to fetch zero-sized (placeholder) registers. */
1338 r->pnum = -1;
1339 else
1340 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1341
1342 r->regnum = regnum;
1343 }
1344
1345 /* Define the g/G packet format as the contents of each register
1346 with a remote protocol number, in order of ascending protocol
1347 number. */
1348
1349 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1350 for (num_remote_regs = 0, regnum = 0;
1351 regnum < gdbarch_num_regs (gdbarch);
1352 regnum++)
1353 if (regs[regnum].pnum != -1)
1354 remote_regs[num_remote_regs++] = &regs[regnum];
1355
1356 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1357 compare_pnums);
1358
1359 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1360 {
1361 remote_regs[regnum]->in_g_packet = 1;
1362 remote_regs[regnum]->offset = offset;
1363 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1364 }
1365
1366 return offset;
1367 }
1368
1369 /* Given the architecture described by GDBARCH, return the remote
1370 protocol register's number and the register's offset in the g/G
1371 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1372 If the target does not have a mapping for REGNUM, return false,
1373 otherwise, return true. */
1374
1375 int
1376 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1377 int *pnum, int *poffset)
1378 {
1379 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1380
1381 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1382
1383 map_regcache_remote_table (gdbarch, regs.data ());
1384
1385 *pnum = regs[regnum].pnum;
1386 *poffset = regs[regnum].offset;
1387
1388 return *pnum != -1;
1389 }
1390
1391 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1392 {
1393 /* Use the architecture to build a regnum<->pnum table, which will be
1394 1:1 unless a feature set specifies otherwise. */
1395 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1396
1397 /* Record the maximum possible size of the g packet - it may turn out
1398 to be smaller. */
1399 this->sizeof_g_packet
1400 = map_regcache_remote_table (gdbarch, this->regs.get ());
1401
1402 /* Default maximum number of characters in a packet body. Many
1403 remote stubs have a hardwired buffer size of 400 bytes
1404 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1405 as the maximum packet-size to ensure that the packet and an extra
1406 NUL character can always fit in the buffer. This stops GDB
1407 trashing stubs that try to squeeze an extra NUL into what is
1408 already a full buffer (As of 1999-12-04 that was most stubs). */
1409 this->remote_packet_size = 400 - 1;
1410
1411 /* This one is filled in when a ``g'' packet is received. */
1412 this->actual_register_packet_size = 0;
1413
1414 /* Should rsa->sizeof_g_packet needs more space than the
1415 default, adjust the size accordingly. Remember that each byte is
1416 encoded as two characters. 32 is the overhead for the packet
1417 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1418 (``$NN:G...#NN'') is a better guess, the below has been padded a
1419 little. */
1420 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1421 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1422 }
1423
1424 /* Get a pointer to the current remote target. If not connected to a
1425 remote target, return NULL. */
1426
1427 static remote_target *
1428 get_current_remote_target ()
1429 {
1430 target_ops *proc_target = find_target_at (process_stratum);
1431 return dynamic_cast<remote_target *> (proc_target);
1432 }
1433
1434 /* Return the current allowed size of a remote packet. This is
1435 inferred from the current architecture, and should be used to
1436 limit the length of outgoing packets. */
1437 long
1438 remote_target::get_remote_packet_size ()
1439 {
1440 struct remote_state *rs = get_remote_state ();
1441 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1442
1443 if (rs->explicit_packet_size)
1444 return rs->explicit_packet_size;
1445
1446 return rsa->remote_packet_size;
1447 }
1448
1449 static struct packet_reg *
1450 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1451 long regnum)
1452 {
1453 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1454 return NULL;
1455 else
1456 {
1457 struct packet_reg *r = &rsa->regs[regnum];
1458
1459 gdb_assert (r->regnum == regnum);
1460 return r;
1461 }
1462 }
1463
1464 static struct packet_reg *
1465 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1466 LONGEST pnum)
1467 {
1468 int i;
1469
1470 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1471 {
1472 struct packet_reg *r = &rsa->regs[i];
1473
1474 if (r->pnum == pnum)
1475 return r;
1476 }
1477 return NULL;
1478 }
1479
1480 /* Allow the user to specify what sequence to send to the remote
1481 when he requests a program interruption: Although ^C is usually
1482 what remote systems expect (this is the default, here), it is
1483 sometimes preferable to send a break. On other systems such
1484 as the Linux kernel, a break followed by g, which is Magic SysRq g
1485 is required in order to interrupt the execution. */
1486 const char interrupt_sequence_control_c[] = "Ctrl-C";
1487 const char interrupt_sequence_break[] = "BREAK";
1488 const char interrupt_sequence_break_g[] = "BREAK-g";
1489 static const char *const interrupt_sequence_modes[] =
1490 {
1491 interrupt_sequence_control_c,
1492 interrupt_sequence_break,
1493 interrupt_sequence_break_g,
1494 NULL
1495 };
1496 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1497
1498 static void
1499 show_interrupt_sequence (struct ui_file *file, int from_tty,
1500 struct cmd_list_element *c,
1501 const char *value)
1502 {
1503 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1504 fprintf_filtered (file,
1505 _("Send the ASCII ETX character (Ctrl-c) "
1506 "to the remote target to interrupt the "
1507 "execution of the program.\n"));
1508 else if (interrupt_sequence_mode == interrupt_sequence_break)
1509 fprintf_filtered (file,
1510 _("send a break signal to the remote target "
1511 "to interrupt the execution of the program.\n"));
1512 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1513 fprintf_filtered (file,
1514 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1515 "the remote target to interrupt the execution "
1516 "of Linux kernel.\n"));
1517 else
1518 internal_error (__FILE__, __LINE__,
1519 _("Invalid value for interrupt_sequence_mode: %s."),
1520 interrupt_sequence_mode);
1521 }
1522
1523 /* This boolean variable specifies whether interrupt_sequence is sent
1524 to the remote target when gdb connects to it.
1525 This is mostly needed when you debug the Linux kernel: The Linux kernel
1526 expects BREAK g which is Magic SysRq g for connecting gdb. */
1527 static int interrupt_on_connect = 0;
1528
1529 /* This variable is used to implement the "set/show remotebreak" commands.
1530 Since these commands are now deprecated in favor of "set/show remote
1531 interrupt-sequence", it no longer has any effect on the code. */
1532 static int remote_break;
1533
1534 static void
1535 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1536 {
1537 if (remote_break)
1538 interrupt_sequence_mode = interrupt_sequence_break;
1539 else
1540 interrupt_sequence_mode = interrupt_sequence_control_c;
1541 }
1542
1543 static void
1544 show_remotebreak (struct ui_file *file, int from_tty,
1545 struct cmd_list_element *c,
1546 const char *value)
1547 {
1548 }
1549
1550 /* This variable sets the number of bits in an address that are to be
1551 sent in a memory ("M" or "m") packet. Normally, after stripping
1552 leading zeros, the entire address would be sent. This variable
1553 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1554 initial implementation of remote.c restricted the address sent in
1555 memory packets to ``host::sizeof long'' bytes - (typically 32
1556 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1557 address was never sent. Since fixing this bug may cause a break in
1558 some remote targets this variable is principly provided to
1559 facilitate backward compatibility. */
1560
1561 static unsigned int remote_address_size;
1562
1563 \f
1564 /* User configurable variables for the number of characters in a
1565 memory read/write packet. MIN (rsa->remote_packet_size,
1566 rsa->sizeof_g_packet) is the default. Some targets need smaller
1567 values (fifo overruns, et.al.) and some users need larger values
1568 (speed up transfers). The variables ``preferred_*'' (the user
1569 request), ``current_*'' (what was actually set) and ``forced_*''
1570 (Positive - a soft limit, negative - a hard limit). */
1571
1572 struct memory_packet_config
1573 {
1574 const char *name;
1575 long size;
1576 int fixed_p;
1577 };
1578
1579 /* The default max memory-write-packet-size, when the setting is
1580 "fixed". The 16k is historical. (It came from older GDB's using
1581 alloca for buffers and the knowledge (folklore?) that some hosts
1582 don't cope very well with large alloca calls.) */
1583 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1584
1585 /* The minimum remote packet size for memory transfers. Ensures we
1586 can write at least one byte. */
1587 #define MIN_MEMORY_PACKET_SIZE 20
1588
1589 /* Get the memory packet size, assuming it is fixed. */
1590
1591 static long
1592 get_fixed_memory_packet_size (struct memory_packet_config *config)
1593 {
1594 gdb_assert (config->fixed_p);
1595
1596 if (config->size <= 0)
1597 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1598 else
1599 return config->size;
1600 }
1601
1602 /* Compute the current size of a read/write packet. Since this makes
1603 use of ``actual_register_packet_size'' the computation is dynamic. */
1604
1605 long
1606 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1607 {
1608 struct remote_state *rs = get_remote_state ();
1609 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1610
1611 long what_they_get;
1612 if (config->fixed_p)
1613 what_they_get = get_fixed_memory_packet_size (config);
1614 else
1615 {
1616 what_they_get = get_remote_packet_size ();
1617 /* Limit the packet to the size specified by the user. */
1618 if (config->size > 0
1619 && what_they_get > config->size)
1620 what_they_get = config->size;
1621
1622 /* Limit it to the size of the targets ``g'' response unless we have
1623 permission from the stub to use a larger packet size. */
1624 if (rs->explicit_packet_size == 0
1625 && rsa->actual_register_packet_size > 0
1626 && what_they_get > rsa->actual_register_packet_size)
1627 what_they_get = rsa->actual_register_packet_size;
1628 }
1629 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1630 what_they_get = MIN_MEMORY_PACKET_SIZE;
1631
1632 /* Make sure there is room in the global buffer for this packet
1633 (including its trailing NUL byte). */
1634 if (rs->buf_size < what_they_get + 1)
1635 {
1636 rs->buf_size = 2 * what_they_get;
1637 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1638 }
1639
1640 return what_they_get;
1641 }
1642
1643 /* Update the size of a read/write packet. If they user wants
1644 something really big then do a sanity check. */
1645
1646 static void
1647 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1648 {
1649 int fixed_p = config->fixed_p;
1650 long size = config->size;
1651
1652 if (args == NULL)
1653 error (_("Argument required (integer, `fixed' or `limited')."));
1654 else if (strcmp (args, "hard") == 0
1655 || strcmp (args, "fixed") == 0)
1656 fixed_p = 1;
1657 else if (strcmp (args, "soft") == 0
1658 || strcmp (args, "limit") == 0)
1659 fixed_p = 0;
1660 else
1661 {
1662 char *end;
1663
1664 size = strtoul (args, &end, 0);
1665 if (args == end)
1666 error (_("Invalid %s (bad syntax)."), config->name);
1667
1668 /* Instead of explicitly capping the size of a packet to or
1669 disallowing it, the user is allowed to set the size to
1670 something arbitrarily large. */
1671 }
1672
1673 /* Extra checks? */
1674 if (fixed_p && !config->fixed_p)
1675 {
1676 /* So that the query shows the correct value. */
1677 long query_size = (size <= 0
1678 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1679 : size);
1680
1681 if (! query (_("The target may not be able to correctly handle a %s\n"
1682 "of %ld bytes. Change the packet size? "),
1683 config->name, query_size))
1684 error (_("Packet size not changed."));
1685 }
1686 /* Update the config. */
1687 config->fixed_p = fixed_p;
1688 config->size = size;
1689 }
1690
1691 static void
1692 show_memory_packet_size (struct memory_packet_config *config)
1693 {
1694 if (config->size == 0)
1695 printf_filtered (_("The %s is 0 (default). "), config->name);
1696 else
1697 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1698 if (config->fixed_p)
1699 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1700 get_fixed_memory_packet_size (config));
1701 else
1702 {
1703 remote_target *remote = get_current_remote_target ();
1704
1705 if (remote != NULL)
1706 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1707 remote->get_memory_packet_size (config));
1708 else
1709 puts_filtered ("The actual limit will be further reduced "
1710 "dependent on the target.\n");
1711 }
1712 }
1713
1714 static struct memory_packet_config memory_write_packet_config =
1715 {
1716 "memory-write-packet-size",
1717 };
1718
1719 static void
1720 set_memory_write_packet_size (const char *args, int from_tty)
1721 {
1722 set_memory_packet_size (args, &memory_write_packet_config);
1723 }
1724
1725 static void
1726 show_memory_write_packet_size (const char *args, int from_tty)
1727 {
1728 show_memory_packet_size (&memory_write_packet_config);
1729 }
1730
1731 long
1732 remote_target::get_memory_write_packet_size ()
1733 {
1734 return get_memory_packet_size (&memory_write_packet_config);
1735 }
1736
1737 static struct memory_packet_config memory_read_packet_config =
1738 {
1739 "memory-read-packet-size",
1740 };
1741
1742 static void
1743 set_memory_read_packet_size (const char *args, int from_tty)
1744 {
1745 set_memory_packet_size (args, &memory_read_packet_config);
1746 }
1747
1748 static void
1749 show_memory_read_packet_size (const char *args, int from_tty)
1750 {
1751 show_memory_packet_size (&memory_read_packet_config);
1752 }
1753
1754 long
1755 remote_target::get_memory_read_packet_size ()
1756 {
1757 long size = get_memory_packet_size (&memory_read_packet_config);
1758
1759 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1760 extra buffer size argument before the memory read size can be
1761 increased beyond this. */
1762 if (size > get_remote_packet_size ())
1763 size = get_remote_packet_size ();
1764 return size;
1765 }
1766
1767 \f
1768
1769 struct packet_config
1770 {
1771 const char *name;
1772 const char *title;
1773
1774 /* If auto, GDB auto-detects support for this packet or feature,
1775 either through qSupported, or by trying the packet and looking
1776 at the response. If true, GDB assumes the target supports this
1777 packet. If false, the packet is disabled. Configs that don't
1778 have an associated command always have this set to auto. */
1779 enum auto_boolean detect;
1780
1781 /* Does the target support this packet? */
1782 enum packet_support support;
1783 };
1784
1785 static enum packet_support packet_config_support (struct packet_config *config);
1786 static enum packet_support packet_support (int packet);
1787
1788 static void
1789 show_packet_config_cmd (struct packet_config *config)
1790 {
1791 const char *support = "internal-error";
1792
1793 switch (packet_config_support (config))
1794 {
1795 case PACKET_ENABLE:
1796 support = "enabled";
1797 break;
1798 case PACKET_DISABLE:
1799 support = "disabled";
1800 break;
1801 case PACKET_SUPPORT_UNKNOWN:
1802 support = "unknown";
1803 break;
1804 }
1805 switch (config->detect)
1806 {
1807 case AUTO_BOOLEAN_AUTO:
1808 printf_filtered (_("Support for the `%s' packet "
1809 "is auto-detected, currently %s.\n"),
1810 config->name, support);
1811 break;
1812 case AUTO_BOOLEAN_TRUE:
1813 case AUTO_BOOLEAN_FALSE:
1814 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1815 config->name, support);
1816 break;
1817 }
1818 }
1819
1820 static void
1821 add_packet_config_cmd (struct packet_config *config, const char *name,
1822 const char *title, int legacy)
1823 {
1824 char *set_doc;
1825 char *show_doc;
1826 char *cmd_name;
1827
1828 config->name = name;
1829 config->title = title;
1830 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1831 name, title);
1832 show_doc = xstrprintf ("Show current use of remote "
1833 "protocol `%s' (%s) packet",
1834 name, title);
1835 /* set/show TITLE-packet {auto,on,off} */
1836 cmd_name = xstrprintf ("%s-packet", title);
1837 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1838 &config->detect, set_doc,
1839 show_doc, NULL, /* help_doc */
1840 NULL,
1841 show_remote_protocol_packet_cmd,
1842 &remote_set_cmdlist, &remote_show_cmdlist);
1843 /* The command code copies the documentation strings. */
1844 xfree (set_doc);
1845 xfree (show_doc);
1846 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1847 if (legacy)
1848 {
1849 char *legacy_name;
1850
1851 legacy_name = xstrprintf ("%s-packet", name);
1852 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1853 &remote_set_cmdlist);
1854 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1855 &remote_show_cmdlist);
1856 }
1857 }
1858
1859 static enum packet_result
1860 packet_check_result (const char *buf)
1861 {
1862 if (buf[0] != '\0')
1863 {
1864 /* The stub recognized the packet request. Check that the
1865 operation succeeded. */
1866 if (buf[0] == 'E'
1867 && isxdigit (buf[1]) && isxdigit (buf[2])
1868 && buf[3] == '\0')
1869 /* "Enn" - definitly an error. */
1870 return PACKET_ERROR;
1871
1872 /* Always treat "E." as an error. This will be used for
1873 more verbose error messages, such as E.memtypes. */
1874 if (buf[0] == 'E' && buf[1] == '.')
1875 return PACKET_ERROR;
1876
1877 /* The packet may or may not be OK. Just assume it is. */
1878 return PACKET_OK;
1879 }
1880 else
1881 /* The stub does not support the packet. */
1882 return PACKET_UNKNOWN;
1883 }
1884
1885 static enum packet_result
1886 packet_ok (const char *buf, struct packet_config *config)
1887 {
1888 enum packet_result result;
1889
1890 if (config->detect != AUTO_BOOLEAN_TRUE
1891 && config->support == PACKET_DISABLE)
1892 internal_error (__FILE__, __LINE__,
1893 _("packet_ok: attempt to use a disabled packet"));
1894
1895 result = packet_check_result (buf);
1896 switch (result)
1897 {
1898 case PACKET_OK:
1899 case PACKET_ERROR:
1900 /* The stub recognized the packet request. */
1901 if (config->support == PACKET_SUPPORT_UNKNOWN)
1902 {
1903 if (remote_debug)
1904 fprintf_unfiltered (gdb_stdlog,
1905 "Packet %s (%s) is supported\n",
1906 config->name, config->title);
1907 config->support = PACKET_ENABLE;
1908 }
1909 break;
1910 case PACKET_UNKNOWN:
1911 /* The stub does not support the packet. */
1912 if (config->detect == AUTO_BOOLEAN_AUTO
1913 && config->support == PACKET_ENABLE)
1914 {
1915 /* If the stub previously indicated that the packet was
1916 supported then there is a protocol error. */
1917 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1918 config->name, config->title);
1919 }
1920 else if (config->detect == AUTO_BOOLEAN_TRUE)
1921 {
1922 /* The user set it wrong. */
1923 error (_("Enabled packet %s (%s) not recognized by stub"),
1924 config->name, config->title);
1925 }
1926
1927 if (remote_debug)
1928 fprintf_unfiltered (gdb_stdlog,
1929 "Packet %s (%s) is NOT supported\n",
1930 config->name, config->title);
1931 config->support = PACKET_DISABLE;
1932 break;
1933 }
1934
1935 return result;
1936 }
1937
1938 enum {
1939 PACKET_vCont = 0,
1940 PACKET_X,
1941 PACKET_qSymbol,
1942 PACKET_P,
1943 PACKET_p,
1944 PACKET_Z0,
1945 PACKET_Z1,
1946 PACKET_Z2,
1947 PACKET_Z3,
1948 PACKET_Z4,
1949 PACKET_vFile_setfs,
1950 PACKET_vFile_open,
1951 PACKET_vFile_pread,
1952 PACKET_vFile_pwrite,
1953 PACKET_vFile_close,
1954 PACKET_vFile_unlink,
1955 PACKET_vFile_readlink,
1956 PACKET_vFile_fstat,
1957 PACKET_qXfer_auxv,
1958 PACKET_qXfer_features,
1959 PACKET_qXfer_exec_file,
1960 PACKET_qXfer_libraries,
1961 PACKET_qXfer_libraries_svr4,
1962 PACKET_qXfer_memory_map,
1963 PACKET_qXfer_spu_read,
1964 PACKET_qXfer_spu_write,
1965 PACKET_qXfer_osdata,
1966 PACKET_qXfer_threads,
1967 PACKET_qXfer_statictrace_read,
1968 PACKET_qXfer_traceframe_info,
1969 PACKET_qXfer_uib,
1970 PACKET_qGetTIBAddr,
1971 PACKET_qGetTLSAddr,
1972 PACKET_qSupported,
1973 PACKET_qTStatus,
1974 PACKET_QPassSignals,
1975 PACKET_QCatchSyscalls,
1976 PACKET_QProgramSignals,
1977 PACKET_QSetWorkingDir,
1978 PACKET_QStartupWithShell,
1979 PACKET_QEnvironmentHexEncoded,
1980 PACKET_QEnvironmentReset,
1981 PACKET_QEnvironmentUnset,
1982 PACKET_qCRC,
1983 PACKET_qSearch_memory,
1984 PACKET_vAttach,
1985 PACKET_vRun,
1986 PACKET_QStartNoAckMode,
1987 PACKET_vKill,
1988 PACKET_qXfer_siginfo_read,
1989 PACKET_qXfer_siginfo_write,
1990 PACKET_qAttached,
1991
1992 /* Support for conditional tracepoints. */
1993 PACKET_ConditionalTracepoints,
1994
1995 /* Support for target-side breakpoint conditions. */
1996 PACKET_ConditionalBreakpoints,
1997
1998 /* Support for target-side breakpoint commands. */
1999 PACKET_BreakpointCommands,
2000
2001 /* Support for fast tracepoints. */
2002 PACKET_FastTracepoints,
2003
2004 /* Support for static tracepoints. */
2005 PACKET_StaticTracepoints,
2006
2007 /* Support for installing tracepoints while a trace experiment is
2008 running. */
2009 PACKET_InstallInTrace,
2010
2011 PACKET_bc,
2012 PACKET_bs,
2013 PACKET_TracepointSource,
2014 PACKET_QAllow,
2015 PACKET_qXfer_fdpic,
2016 PACKET_QDisableRandomization,
2017 PACKET_QAgent,
2018 PACKET_QTBuffer_size,
2019 PACKET_Qbtrace_off,
2020 PACKET_Qbtrace_bts,
2021 PACKET_Qbtrace_pt,
2022 PACKET_qXfer_btrace,
2023
2024 /* Support for the QNonStop packet. */
2025 PACKET_QNonStop,
2026
2027 /* Support for the QThreadEvents packet. */
2028 PACKET_QThreadEvents,
2029
2030 /* Support for multi-process extensions. */
2031 PACKET_multiprocess_feature,
2032
2033 /* Support for enabling and disabling tracepoints while a trace
2034 experiment is running. */
2035 PACKET_EnableDisableTracepoints_feature,
2036
2037 /* Support for collecting strings using the tracenz bytecode. */
2038 PACKET_tracenz_feature,
2039
2040 /* Support for continuing to run a trace experiment while GDB is
2041 disconnected. */
2042 PACKET_DisconnectedTracing_feature,
2043
2044 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2045 PACKET_augmented_libraries_svr4_read_feature,
2046
2047 /* Support for the qXfer:btrace-conf:read packet. */
2048 PACKET_qXfer_btrace_conf,
2049
2050 /* Support for the Qbtrace-conf:bts:size packet. */
2051 PACKET_Qbtrace_conf_bts_size,
2052
2053 /* Support for swbreak+ feature. */
2054 PACKET_swbreak_feature,
2055
2056 /* Support for hwbreak+ feature. */
2057 PACKET_hwbreak_feature,
2058
2059 /* Support for fork events. */
2060 PACKET_fork_event_feature,
2061
2062 /* Support for vfork events. */
2063 PACKET_vfork_event_feature,
2064
2065 /* Support for the Qbtrace-conf:pt:size packet. */
2066 PACKET_Qbtrace_conf_pt_size,
2067
2068 /* Support for exec events. */
2069 PACKET_exec_event_feature,
2070
2071 /* Support for query supported vCont actions. */
2072 PACKET_vContSupported,
2073
2074 /* Support remote CTRL-C. */
2075 PACKET_vCtrlC,
2076
2077 /* Support TARGET_WAITKIND_NO_RESUMED. */
2078 PACKET_no_resumed,
2079
2080 PACKET_MAX
2081 };
2082
2083 static struct packet_config remote_protocol_packets[PACKET_MAX];
2084
2085 /* Returns the packet's corresponding "set remote foo-packet" command
2086 state. See struct packet_config for more details. */
2087
2088 static enum auto_boolean
2089 packet_set_cmd_state (int packet)
2090 {
2091 return remote_protocol_packets[packet].detect;
2092 }
2093
2094 /* Returns whether a given packet or feature is supported. This takes
2095 into account the state of the corresponding "set remote foo-packet"
2096 command, which may be used to bypass auto-detection. */
2097
2098 static enum packet_support
2099 packet_config_support (struct packet_config *config)
2100 {
2101 switch (config->detect)
2102 {
2103 case AUTO_BOOLEAN_TRUE:
2104 return PACKET_ENABLE;
2105 case AUTO_BOOLEAN_FALSE:
2106 return PACKET_DISABLE;
2107 case AUTO_BOOLEAN_AUTO:
2108 return config->support;
2109 default:
2110 gdb_assert_not_reached (_("bad switch"));
2111 }
2112 }
2113
2114 /* Same as packet_config_support, but takes the packet's enum value as
2115 argument. */
2116
2117 static enum packet_support
2118 packet_support (int packet)
2119 {
2120 struct packet_config *config = &remote_protocol_packets[packet];
2121
2122 return packet_config_support (config);
2123 }
2124
2125 static void
2126 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2127 struct cmd_list_element *c,
2128 const char *value)
2129 {
2130 struct packet_config *packet;
2131
2132 for (packet = remote_protocol_packets;
2133 packet < &remote_protocol_packets[PACKET_MAX];
2134 packet++)
2135 {
2136 if (&packet->detect == c->var)
2137 {
2138 show_packet_config_cmd (packet);
2139 return;
2140 }
2141 }
2142 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2143 c->name);
2144 }
2145
2146 /* Should we try one of the 'Z' requests? */
2147
2148 enum Z_packet_type
2149 {
2150 Z_PACKET_SOFTWARE_BP,
2151 Z_PACKET_HARDWARE_BP,
2152 Z_PACKET_WRITE_WP,
2153 Z_PACKET_READ_WP,
2154 Z_PACKET_ACCESS_WP,
2155 NR_Z_PACKET_TYPES
2156 };
2157
2158 /* For compatibility with older distributions. Provide a ``set remote
2159 Z-packet ...'' command that updates all the Z packet types. */
2160
2161 static enum auto_boolean remote_Z_packet_detect;
2162
2163 static void
2164 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2165 struct cmd_list_element *c)
2166 {
2167 int i;
2168
2169 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2170 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2171 }
2172
2173 static void
2174 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2175 struct cmd_list_element *c,
2176 const char *value)
2177 {
2178 int i;
2179
2180 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2181 {
2182 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2183 }
2184 }
2185
2186 /* Returns true if the multi-process extensions are in effect. */
2187
2188 static int
2189 remote_multi_process_p (struct remote_state *rs)
2190 {
2191 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2192 }
2193
2194 /* Returns true if fork events are supported. */
2195
2196 static int
2197 remote_fork_event_p (struct remote_state *rs)
2198 {
2199 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2200 }
2201
2202 /* Returns true if vfork events are supported. */
2203
2204 static int
2205 remote_vfork_event_p (struct remote_state *rs)
2206 {
2207 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2208 }
2209
2210 /* Returns true if exec events are supported. */
2211
2212 static int
2213 remote_exec_event_p (struct remote_state *rs)
2214 {
2215 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2216 }
2217
2218 /* Insert fork catchpoint target routine. If fork events are enabled
2219 then return success, nothing more to do. */
2220
2221 int
2222 remote_target::insert_fork_catchpoint (int pid)
2223 {
2224 struct remote_state *rs = get_remote_state ();
2225
2226 return !remote_fork_event_p (rs);
2227 }
2228
2229 /* Remove fork catchpoint target routine. Nothing to do, just
2230 return success. */
2231
2232 int
2233 remote_target::remove_fork_catchpoint (int pid)
2234 {
2235 return 0;
2236 }
2237
2238 /* Insert vfork catchpoint target routine. If vfork events are enabled
2239 then return success, nothing more to do. */
2240
2241 int
2242 remote_target::insert_vfork_catchpoint (int pid)
2243 {
2244 struct remote_state *rs = get_remote_state ();
2245
2246 return !remote_vfork_event_p (rs);
2247 }
2248
2249 /* Remove vfork catchpoint target routine. Nothing to do, just
2250 return success. */
2251
2252 int
2253 remote_target::remove_vfork_catchpoint (int pid)
2254 {
2255 return 0;
2256 }
2257
2258 /* Insert exec catchpoint target routine. If exec events are
2259 enabled, just return success. */
2260
2261 int
2262 remote_target::insert_exec_catchpoint (int pid)
2263 {
2264 struct remote_state *rs = get_remote_state ();
2265
2266 return !remote_exec_event_p (rs);
2267 }
2268
2269 /* Remove exec catchpoint target routine. Nothing to do, just
2270 return success. */
2271
2272 int
2273 remote_target::remove_exec_catchpoint (int pid)
2274 {
2275 return 0;
2276 }
2277
2278 \f
2279
2280 static ptid_t magic_null_ptid;
2281 static ptid_t not_sent_ptid;
2282 static ptid_t any_thread_ptid;
2283
2284 /* Find out if the stub attached to PID (and hence GDB should offer to
2285 detach instead of killing it when bailing out). */
2286
2287 int
2288 remote_target::remote_query_attached (int pid)
2289 {
2290 struct remote_state *rs = get_remote_state ();
2291 size_t size = get_remote_packet_size ();
2292
2293 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2294 return 0;
2295
2296 if (remote_multi_process_p (rs))
2297 xsnprintf (rs->buf, size, "qAttached:%x", pid);
2298 else
2299 xsnprintf (rs->buf, size, "qAttached");
2300
2301 putpkt (rs->buf);
2302 getpkt (&rs->buf, &rs->buf_size, 0);
2303
2304 switch (packet_ok (rs->buf,
2305 &remote_protocol_packets[PACKET_qAttached]))
2306 {
2307 case PACKET_OK:
2308 if (strcmp (rs->buf, "1") == 0)
2309 return 1;
2310 break;
2311 case PACKET_ERROR:
2312 warning (_("Remote failure reply: %s"), rs->buf);
2313 break;
2314 case PACKET_UNKNOWN:
2315 break;
2316 }
2317
2318 return 0;
2319 }
2320
2321 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2322 has been invented by GDB, instead of reported by the target. Since
2323 we can be connected to a remote system before before knowing about
2324 any inferior, mark the target with execution when we find the first
2325 inferior. If ATTACHED is 1, then we had just attached to this
2326 inferior. If it is 0, then we just created this inferior. If it
2327 is -1, then try querying the remote stub to find out if it had
2328 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2329 attempt to open this inferior's executable as the main executable
2330 if no main executable is open already. */
2331
2332 inferior *
2333 remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2334 int try_open_exec)
2335 {
2336 struct inferior *inf;
2337
2338 /* Check whether this process we're learning about is to be
2339 considered attached, or if is to be considered to have been
2340 spawned by the stub. */
2341 if (attached == -1)
2342 attached = remote_query_attached (pid);
2343
2344 if (gdbarch_has_global_solist (target_gdbarch ()))
2345 {
2346 /* If the target shares code across all inferiors, then every
2347 attach adds a new inferior. */
2348 inf = add_inferior (pid);
2349
2350 /* ... and every inferior is bound to the same program space.
2351 However, each inferior may still have its own address
2352 space. */
2353 inf->aspace = maybe_new_address_space ();
2354 inf->pspace = current_program_space;
2355 }
2356 else
2357 {
2358 /* In the traditional debugging scenario, there's a 1-1 match
2359 between program/address spaces. We simply bind the inferior
2360 to the program space's address space. */
2361 inf = current_inferior ();
2362 inferior_appeared (inf, pid);
2363 }
2364
2365 inf->attach_flag = attached;
2366 inf->fake_pid_p = fake_pid_p;
2367
2368 /* If no main executable is currently open then attempt to
2369 open the file that was executed to create this inferior. */
2370 if (try_open_exec && get_exec_file (0) == NULL)
2371 exec_file_locate_attach (pid, 0, 1);
2372
2373 return inf;
2374 }
2375
2376 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2377
2378 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2379 according to RUNNING. */
2380
2381 void
2382 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2383 {
2384 struct remote_state *rs = get_remote_state ();
2385 struct thread_info *thread;
2386
2387 /* GDB historically didn't pull threads in the initial connection
2388 setup. If the remote target doesn't even have a concept of
2389 threads (e.g., a bare-metal target), even if internally we
2390 consider that a single-threaded target, mentioning a new thread
2391 might be confusing to the user. Be silent then, preserving the
2392 age old behavior. */
2393 if (rs->starting_up)
2394 thread = add_thread_silent (ptid);
2395 else
2396 thread = add_thread (ptid);
2397
2398 get_remote_thread_info (thread)->vcont_resumed = executing;
2399 set_executing (ptid, executing);
2400 set_running (ptid, running);
2401 }
2402
2403 /* Come here when we learn about a thread id from the remote target.
2404 It may be the first time we hear about such thread, so take the
2405 opportunity to add it to GDB's thread list. In case this is the
2406 first time we're noticing its corresponding inferior, add it to
2407 GDB's inferior list as well. EXECUTING indicates whether the
2408 thread is (internally) executing or stopped. */
2409
2410 void
2411 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2412 {
2413 /* In non-stop mode, we assume new found threads are (externally)
2414 running until proven otherwise with a stop reply. In all-stop,
2415 we can only get here if all threads are stopped. */
2416 int running = target_is_non_stop_p () ? 1 : 0;
2417
2418 /* If this is a new thread, add it to GDB's thread list.
2419 If we leave it up to WFI to do this, bad things will happen. */
2420
2421 if (in_thread_list (currthread) && is_exited (currthread))
2422 {
2423 /* We're seeing an event on a thread id we knew had exited.
2424 This has to be a new thread reusing the old id. Add it. */
2425 remote_add_thread (currthread, running, executing);
2426 return;
2427 }
2428
2429 if (!in_thread_list (currthread))
2430 {
2431 struct inferior *inf = NULL;
2432 int pid = ptid_get_pid (currthread);
2433
2434 if (ptid_is_pid (inferior_ptid)
2435 && pid == ptid_get_pid (inferior_ptid))
2436 {
2437 /* inferior_ptid has no thread member yet. This can happen
2438 with the vAttach -> remote_wait,"TAAthread:" path if the
2439 stub doesn't support qC. This is the first stop reported
2440 after an attach, so this is the main thread. Update the
2441 ptid in the thread list. */
2442 if (in_thread_list (pid_to_ptid (pid)))
2443 thread_change_ptid (inferior_ptid, currthread);
2444 else
2445 {
2446 remote_add_thread (currthread, running, executing);
2447 inferior_ptid = currthread;
2448 }
2449 return;
2450 }
2451
2452 if (ptid_equal (magic_null_ptid, inferior_ptid))
2453 {
2454 /* inferior_ptid is not set yet. This can happen with the
2455 vRun -> remote_wait,"TAAthread:" path if the stub
2456 doesn't support qC. This is the first stop reported
2457 after an attach, so this is the main thread. Update the
2458 ptid in the thread list. */
2459 thread_change_ptid (inferior_ptid, currthread);
2460 return;
2461 }
2462
2463 /* When connecting to a target remote, or to a target
2464 extended-remote which already was debugging an inferior, we
2465 may not know about it yet. Add it before adding its child
2466 thread, so notifications are emitted in a sensible order. */
2467 if (!in_inferior_list (ptid_get_pid (currthread)))
2468 {
2469 struct remote_state *rs = get_remote_state ();
2470 int fake_pid_p = !remote_multi_process_p (rs);
2471
2472 inf = remote_add_inferior (fake_pid_p,
2473 ptid_get_pid (currthread), -1, 1);
2474 }
2475
2476 /* This is really a new thread. Add it. */
2477 remote_add_thread (currthread, running, executing);
2478
2479 /* If we found a new inferior, let the common code do whatever
2480 it needs to with it (e.g., read shared libraries, insert
2481 breakpoints), unless we're just setting up an all-stop
2482 connection. */
2483 if (inf != NULL)
2484 {
2485 struct remote_state *rs = get_remote_state ();
2486
2487 if (!rs->starting_up)
2488 notice_new_inferior (currthread, executing, 0);
2489 }
2490 }
2491 }
2492
2493 /* Return THREAD's private thread data, creating it if necessary. */
2494
2495 static remote_thread_info *
2496 get_remote_thread_info (thread_info *thread)
2497 {
2498 gdb_assert (thread != NULL);
2499
2500 if (thread->priv == NULL)
2501 thread->priv.reset (new remote_thread_info);
2502
2503 return static_cast<remote_thread_info *> (thread->priv.get ());
2504 }
2505
2506 /* Return PTID's private thread data, creating it if necessary. */
2507
2508 static remote_thread_info *
2509 get_remote_thread_info (ptid_t ptid)
2510 {
2511 struct thread_info *info = find_thread_ptid (ptid);
2512
2513 return get_remote_thread_info (info);
2514 }
2515
2516 /* Call this function as a result of
2517 1) A halt indication (T packet) containing a thread id
2518 2) A direct query of currthread
2519 3) Successful execution of set thread */
2520
2521 static void
2522 record_currthread (struct remote_state *rs, ptid_t currthread)
2523 {
2524 rs->general_thread = currthread;
2525 }
2526
2527 /* If 'QPassSignals' is supported, tell the remote stub what signals
2528 it can simply pass through to the inferior without reporting. */
2529
2530 void
2531 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2532 {
2533 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2534 {
2535 char *pass_packet, *p;
2536 int count = 0, i;
2537 struct remote_state *rs = get_remote_state ();
2538
2539 gdb_assert (numsigs < 256);
2540 for (i = 0; i < numsigs; i++)
2541 {
2542 if (pass_signals[i])
2543 count++;
2544 }
2545 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2546 strcpy (pass_packet, "QPassSignals:");
2547 p = pass_packet + strlen (pass_packet);
2548 for (i = 0; i < numsigs; i++)
2549 {
2550 if (pass_signals[i])
2551 {
2552 if (i >= 16)
2553 *p++ = tohex (i >> 4);
2554 *p++ = tohex (i & 15);
2555 if (count)
2556 *p++ = ';';
2557 else
2558 break;
2559 count--;
2560 }
2561 }
2562 *p = 0;
2563 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2564 {
2565 putpkt (pass_packet);
2566 getpkt (&rs->buf, &rs->buf_size, 0);
2567 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2568 if (rs->last_pass_packet)
2569 xfree (rs->last_pass_packet);
2570 rs->last_pass_packet = pass_packet;
2571 }
2572 else
2573 xfree (pass_packet);
2574 }
2575 }
2576
2577 /* If 'QCatchSyscalls' is supported, tell the remote stub
2578 to report syscalls to GDB. */
2579
2580 int
2581 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2582 gdb::array_view<const int> syscall_counts)
2583 {
2584 const char *catch_packet;
2585 enum packet_result result;
2586 int n_sysno = 0;
2587
2588 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2589 {
2590 /* Not supported. */
2591 return 1;
2592 }
2593
2594 if (needed && any_count == 0)
2595 {
2596 /* Count how many syscalls are to be caught. */
2597 for (size_t i = 0; i < syscall_counts.size (); i++)
2598 {
2599 if (syscall_counts[i] != 0)
2600 n_sysno++;
2601 }
2602 }
2603
2604 if (remote_debug)
2605 {
2606 fprintf_unfiltered (gdb_stdlog,
2607 "remote_set_syscall_catchpoint "
2608 "pid %d needed %d any_count %d n_sysno %d\n",
2609 pid, needed, any_count, n_sysno);
2610 }
2611
2612 std::string built_packet;
2613 if (needed)
2614 {
2615 /* Prepare a packet with the sysno list, assuming max 8+1
2616 characters for a sysno. If the resulting packet size is too
2617 big, fallback on the non-selective packet. */
2618 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2619 built_packet.reserve (maxpktsz);
2620 built_packet = "QCatchSyscalls:1";
2621 if (any_count == 0)
2622 {
2623 /* Add in each syscall to be caught. */
2624 for (size_t i = 0; i < syscall_counts.size (); i++)
2625 {
2626 if (syscall_counts[i] != 0)
2627 string_appendf (built_packet, ";%zx", i);
2628 }
2629 }
2630 if (built_packet.size () > get_remote_packet_size ())
2631 {
2632 /* catch_packet too big. Fallback to less efficient
2633 non selective mode, with GDB doing the filtering. */
2634 catch_packet = "QCatchSyscalls:1";
2635 }
2636 else
2637 catch_packet = built_packet.c_str ();
2638 }
2639 else
2640 catch_packet = "QCatchSyscalls:0";
2641
2642 struct remote_state *rs = get_remote_state ();
2643
2644 putpkt (catch_packet);
2645 getpkt (&rs->buf, &rs->buf_size, 0);
2646 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2647 if (result == PACKET_OK)
2648 return 0;
2649 else
2650 return -1;
2651 }
2652
2653 /* If 'QProgramSignals' is supported, tell the remote stub what
2654 signals it should pass through to the inferior when detaching. */
2655
2656 void
2657 remote_target::program_signals (int numsigs, unsigned char *signals)
2658 {
2659 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2660 {
2661 char *packet, *p;
2662 int count = 0, i;
2663 struct remote_state *rs = get_remote_state ();
2664
2665 gdb_assert (numsigs < 256);
2666 for (i = 0; i < numsigs; i++)
2667 {
2668 if (signals[i])
2669 count++;
2670 }
2671 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2672 strcpy (packet, "QProgramSignals:");
2673 p = packet + strlen (packet);
2674 for (i = 0; i < numsigs; i++)
2675 {
2676 if (signal_pass_state (i))
2677 {
2678 if (i >= 16)
2679 *p++ = tohex (i >> 4);
2680 *p++ = tohex (i & 15);
2681 if (count)
2682 *p++ = ';';
2683 else
2684 break;
2685 count--;
2686 }
2687 }
2688 *p = 0;
2689 if (!rs->last_program_signals_packet
2690 || strcmp (rs->last_program_signals_packet, packet) != 0)
2691 {
2692 putpkt (packet);
2693 getpkt (&rs->buf, &rs->buf_size, 0);
2694 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2695 xfree (rs->last_program_signals_packet);
2696 rs->last_program_signals_packet = packet;
2697 }
2698 else
2699 xfree (packet);
2700 }
2701 }
2702
2703 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2704 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2705 thread. If GEN is set, set the general thread, if not, then set
2706 the step/continue thread. */
2707 void
2708 remote_target::set_thread (ptid_t ptid, int gen)
2709 {
2710 struct remote_state *rs = get_remote_state ();
2711 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2712 char *buf = rs->buf;
2713 char *endbuf = rs->buf + get_remote_packet_size ();
2714
2715 if (ptid_equal (state, ptid))
2716 return;
2717
2718 *buf++ = 'H';
2719 *buf++ = gen ? 'g' : 'c';
2720 if (ptid_equal (ptid, magic_null_ptid))
2721 xsnprintf (buf, endbuf - buf, "0");
2722 else if (ptid_equal (ptid, any_thread_ptid))
2723 xsnprintf (buf, endbuf - buf, "0");
2724 else if (ptid_equal (ptid, minus_one_ptid))
2725 xsnprintf (buf, endbuf - buf, "-1");
2726 else
2727 write_ptid (buf, endbuf, ptid);
2728 putpkt (rs->buf);
2729 getpkt (&rs->buf, &rs->buf_size, 0);
2730 if (gen)
2731 rs->general_thread = ptid;
2732 else
2733 rs->continue_thread = ptid;
2734 }
2735
2736 void
2737 remote_target::set_general_thread (ptid_t ptid)
2738 {
2739 set_thread (ptid, 1);
2740 }
2741
2742 void
2743 remote_target::set_continue_thread (ptid_t ptid)
2744 {
2745 set_thread (ptid, 0);
2746 }
2747
2748 /* Change the remote current process. Which thread within the process
2749 ends up selected isn't important, as long as it is the same process
2750 as what INFERIOR_PTID points to.
2751
2752 This comes from that fact that there is no explicit notion of
2753 "selected process" in the protocol. The selected process for
2754 general operations is the process the selected general thread
2755 belongs to. */
2756
2757 void
2758 remote_target::set_general_process ()
2759 {
2760 struct remote_state *rs = get_remote_state ();
2761
2762 /* If the remote can't handle multiple processes, don't bother. */
2763 if (!remote_multi_process_p (rs))
2764 return;
2765
2766 /* We only need to change the remote current thread if it's pointing
2767 at some other process. */
2768 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2769 set_general_thread (inferior_ptid);
2770 }
2771
2772 \f
2773 /* Return nonzero if this is the main thread that we made up ourselves
2774 to model non-threaded targets as single-threaded. */
2775
2776 static int
2777 remote_thread_always_alive (ptid_t ptid)
2778 {
2779 if (ptid_equal (ptid, magic_null_ptid))
2780 /* The main thread is always alive. */
2781 return 1;
2782
2783 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2784 /* The main thread is always alive. This can happen after a
2785 vAttach, if the remote side doesn't support
2786 multi-threading. */
2787 return 1;
2788
2789 return 0;
2790 }
2791
2792 /* Return nonzero if the thread PTID is still alive on the remote
2793 system. */
2794
2795 bool
2796 remote_target::thread_alive (ptid_t ptid)
2797 {
2798 struct remote_state *rs = get_remote_state ();
2799 char *p, *endp;
2800
2801 /* Check if this is a thread that we made up ourselves to model
2802 non-threaded targets as single-threaded. */
2803 if (remote_thread_always_alive (ptid))
2804 return 1;
2805
2806 p = rs->buf;
2807 endp = rs->buf + get_remote_packet_size ();
2808
2809 *p++ = 'T';
2810 write_ptid (p, endp, ptid);
2811
2812 putpkt (rs->buf);
2813 getpkt (&rs->buf, &rs->buf_size, 0);
2814 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2815 }
2816
2817 /* Return a pointer to a thread name if we know it and NULL otherwise.
2818 The thread_info object owns the memory for the name. */
2819
2820 const char *
2821 remote_target::thread_name (struct thread_info *info)
2822 {
2823 if (info->priv != NULL)
2824 {
2825 const std::string &name = get_remote_thread_info (info)->name;
2826 return !name.empty () ? name.c_str () : NULL;
2827 }
2828
2829 return NULL;
2830 }
2831
2832 /* About these extended threadlist and threadinfo packets. They are
2833 variable length packets but, the fields within them are often fixed
2834 length. They are redundent enough to send over UDP as is the
2835 remote protocol in general. There is a matching unit test module
2836 in libstub. */
2837
2838 /* WARNING: This threadref data structure comes from the remote O.S.,
2839 libstub protocol encoding, and remote.c. It is not particularly
2840 changable. */
2841
2842 /* Right now, the internal structure is int. We want it to be bigger.
2843 Plan to fix this. */
2844
2845 typedef int gdb_threadref; /* Internal GDB thread reference. */
2846
2847 /* gdb_ext_thread_info is an internal GDB data structure which is
2848 equivalent to the reply of the remote threadinfo packet. */
2849
2850 struct gdb_ext_thread_info
2851 {
2852 threadref threadid; /* External form of thread reference. */
2853 int active; /* Has state interesting to GDB?
2854 regs, stack. */
2855 char display[256]; /* Brief state display, name,
2856 blocked/suspended. */
2857 char shortname[32]; /* To be used to name threads. */
2858 char more_display[256]; /* Long info, statistics, queue depth,
2859 whatever. */
2860 };
2861
2862 /* The volume of remote transfers can be limited by submitting
2863 a mask containing bits specifying the desired information.
2864 Use a union of these values as the 'selection' parameter to
2865 get_thread_info. FIXME: Make these TAG names more thread specific. */
2866
2867 #define TAG_THREADID 1
2868 #define TAG_EXISTS 2
2869 #define TAG_DISPLAY 4
2870 #define TAG_THREADNAME 8
2871 #define TAG_MOREDISPLAY 16
2872
2873 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2874
2875 static char *unpack_nibble (char *buf, int *val);
2876
2877 static char *unpack_byte (char *buf, int *value);
2878
2879 static char *pack_int (char *buf, int value);
2880
2881 static char *unpack_int (char *buf, int *value);
2882
2883 static char *unpack_string (char *src, char *dest, int length);
2884
2885 static char *pack_threadid (char *pkt, threadref *id);
2886
2887 static char *unpack_threadid (char *inbuf, threadref *id);
2888
2889 void int_to_threadref (threadref *id, int value);
2890
2891 static int threadref_to_int (threadref *ref);
2892
2893 static void copy_threadref (threadref *dest, threadref *src);
2894
2895 static int threadmatch (threadref *dest, threadref *src);
2896
2897 static char *pack_threadinfo_request (char *pkt, int mode,
2898 threadref *id);
2899
2900 static char *pack_threadlist_request (char *pkt, int startflag,
2901 int threadcount,
2902 threadref *nextthread);
2903
2904 static int remote_newthread_step (threadref *ref, void *context);
2905
2906
2907 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2908 buffer we're allowed to write to. Returns
2909 BUF+CHARACTERS_WRITTEN. */
2910
2911 char *
2912 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2913 {
2914 int pid, tid;
2915 struct remote_state *rs = get_remote_state ();
2916
2917 if (remote_multi_process_p (rs))
2918 {
2919 pid = ptid_get_pid (ptid);
2920 if (pid < 0)
2921 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2922 else
2923 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2924 }
2925 tid = ptid_get_lwp (ptid);
2926 if (tid < 0)
2927 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2928 else
2929 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2930
2931 return buf;
2932 }
2933
2934 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2935 last parsed char. Returns null_ptid if no thread id is found, and
2936 throws an error if the thread id has an invalid format. */
2937
2938 static ptid_t
2939 read_ptid (const char *buf, const char **obuf)
2940 {
2941 const char *p = buf;
2942 const char *pp;
2943 ULONGEST pid = 0, tid = 0;
2944
2945 if (*p == 'p')
2946 {
2947 /* Multi-process ptid. */
2948 pp = unpack_varlen_hex (p + 1, &pid);
2949 if (*pp != '.')
2950 error (_("invalid remote ptid: %s"), p);
2951
2952 p = pp;
2953 pp = unpack_varlen_hex (p + 1, &tid);
2954 if (obuf)
2955 *obuf = pp;
2956 return ptid_build (pid, tid, 0);
2957 }
2958
2959 /* No multi-process. Just a tid. */
2960 pp = unpack_varlen_hex (p, &tid);
2961
2962 /* Return null_ptid when no thread id is found. */
2963 if (p == pp)
2964 {
2965 if (obuf)
2966 *obuf = pp;
2967 return null_ptid;
2968 }
2969
2970 /* Since the stub is not sending a process id, then default to
2971 what's in inferior_ptid, unless it's null at this point. If so,
2972 then since there's no way to know the pid of the reported
2973 threads, use the magic number. */
2974 if (ptid_equal (inferior_ptid, null_ptid))
2975 pid = ptid_get_pid (magic_null_ptid);
2976 else
2977 pid = ptid_get_pid (inferior_ptid);
2978
2979 if (obuf)
2980 *obuf = pp;
2981 return ptid_build (pid, tid, 0);
2982 }
2983
2984 static int
2985 stubhex (int ch)
2986 {
2987 if (ch >= 'a' && ch <= 'f')
2988 return ch - 'a' + 10;
2989 if (ch >= '0' && ch <= '9')
2990 return ch - '0';
2991 if (ch >= 'A' && ch <= 'F')
2992 return ch - 'A' + 10;
2993 return -1;
2994 }
2995
2996 static int
2997 stub_unpack_int (char *buff, int fieldlength)
2998 {
2999 int nibble;
3000 int retval = 0;
3001
3002 while (fieldlength)
3003 {
3004 nibble = stubhex (*buff++);
3005 retval |= nibble;
3006 fieldlength--;
3007 if (fieldlength)
3008 retval = retval << 4;
3009 }
3010 return retval;
3011 }
3012
3013 static char *
3014 unpack_nibble (char *buf, int *val)
3015 {
3016 *val = fromhex (*buf++);
3017 return buf;
3018 }
3019
3020 static char *
3021 unpack_byte (char *buf, int *value)
3022 {
3023 *value = stub_unpack_int (buf, 2);
3024 return buf + 2;
3025 }
3026
3027 static char *
3028 pack_int (char *buf, int value)
3029 {
3030 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3031 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3032 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3033 buf = pack_hex_byte (buf, (value & 0xff));
3034 return buf;
3035 }
3036
3037 static char *
3038 unpack_int (char *buf, int *value)
3039 {
3040 *value = stub_unpack_int (buf, 8);
3041 return buf + 8;
3042 }
3043
3044 #if 0 /* Currently unused, uncomment when needed. */
3045 static char *pack_string (char *pkt, char *string);
3046
3047 static char *
3048 pack_string (char *pkt, char *string)
3049 {
3050 char ch;
3051 int len;
3052
3053 len = strlen (string);
3054 if (len > 200)
3055 len = 200; /* Bigger than most GDB packets, junk??? */
3056 pkt = pack_hex_byte (pkt, len);
3057 while (len-- > 0)
3058 {
3059 ch = *string++;
3060 if ((ch == '\0') || (ch == '#'))
3061 ch = '*'; /* Protect encapsulation. */
3062 *pkt++ = ch;
3063 }
3064 return pkt;
3065 }
3066 #endif /* 0 (unused) */
3067
3068 static char *
3069 unpack_string (char *src, char *dest, int length)
3070 {
3071 while (length--)
3072 *dest++ = *src++;
3073 *dest = '\0';
3074 return src;
3075 }
3076
3077 static char *
3078 pack_threadid (char *pkt, threadref *id)
3079 {
3080 char *limit;
3081 unsigned char *altid;
3082
3083 altid = (unsigned char *) id;
3084 limit = pkt + BUF_THREAD_ID_SIZE;
3085 while (pkt < limit)
3086 pkt = pack_hex_byte (pkt, *altid++);
3087 return pkt;
3088 }
3089
3090
3091 static char *
3092 unpack_threadid (char *inbuf, threadref *id)
3093 {
3094 char *altref;
3095 char *limit = inbuf + BUF_THREAD_ID_SIZE;
3096 int x, y;
3097
3098 altref = (char *) id;
3099
3100 while (inbuf < limit)
3101 {
3102 x = stubhex (*inbuf++);
3103 y = stubhex (*inbuf++);
3104 *altref++ = (x << 4) | y;
3105 }
3106 return inbuf;
3107 }
3108
3109 /* Externally, threadrefs are 64 bits but internally, they are still
3110 ints. This is due to a mismatch of specifications. We would like
3111 to use 64bit thread references internally. This is an adapter
3112 function. */
3113
3114 void
3115 int_to_threadref (threadref *id, int value)
3116 {
3117 unsigned char *scan;
3118
3119 scan = (unsigned char *) id;
3120 {
3121 int i = 4;
3122 while (i--)
3123 *scan++ = 0;
3124 }
3125 *scan++ = (value >> 24) & 0xff;
3126 *scan++ = (value >> 16) & 0xff;
3127 *scan++ = (value >> 8) & 0xff;
3128 *scan++ = (value & 0xff);
3129 }
3130
3131 static int
3132 threadref_to_int (threadref *ref)
3133 {
3134 int i, value = 0;
3135 unsigned char *scan;
3136
3137 scan = *ref;
3138 scan += 4;
3139 i = 4;
3140 while (i-- > 0)
3141 value = (value << 8) | ((*scan++) & 0xff);
3142 return value;
3143 }
3144
3145 static void
3146 copy_threadref (threadref *dest, threadref *src)
3147 {
3148 int i;
3149 unsigned char *csrc, *cdest;
3150
3151 csrc = (unsigned char *) src;
3152 cdest = (unsigned char *) dest;
3153 i = 8;
3154 while (i--)
3155 *cdest++ = *csrc++;
3156 }
3157
3158 static int
3159 threadmatch (threadref *dest, threadref *src)
3160 {
3161 /* Things are broken right now, so just assume we got a match. */
3162 #if 0
3163 unsigned char *srcp, *destp;
3164 int i, result;
3165 srcp = (char *) src;
3166 destp = (char *) dest;
3167
3168 result = 1;
3169 while (i-- > 0)
3170 result &= (*srcp++ == *destp++) ? 1 : 0;
3171 return result;
3172 #endif
3173 return 1;
3174 }
3175
3176 /*
3177 threadid:1, # always request threadid
3178 context_exists:2,
3179 display:4,
3180 unique_name:8,
3181 more_display:16
3182 */
3183
3184 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3185
3186 static char *
3187 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3188 {
3189 *pkt++ = 'q'; /* Info Query */
3190 *pkt++ = 'P'; /* process or thread info */
3191 pkt = pack_int (pkt, mode); /* mode */
3192 pkt = pack_threadid (pkt, id); /* threadid */
3193 *pkt = '\0'; /* terminate */
3194 return pkt;
3195 }
3196
3197 /* These values tag the fields in a thread info response packet. */
3198 /* Tagging the fields allows us to request specific fields and to
3199 add more fields as time goes by. */
3200
3201 #define TAG_THREADID 1 /* Echo the thread identifier. */
3202 #define TAG_EXISTS 2 /* Is this process defined enough to
3203 fetch registers and its stack? */
3204 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3205 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3206 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3207 the process. */
3208
3209 int
3210 remote_target::remote_unpack_thread_info_response (char *pkt,
3211 threadref *expectedref,
3212 gdb_ext_thread_info *info)
3213 {
3214 struct remote_state *rs = get_remote_state ();
3215 int mask, length;
3216 int tag;
3217 threadref ref;
3218 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
3219 int retval = 1;
3220
3221 /* info->threadid = 0; FIXME: implement zero_threadref. */
3222 info->active = 0;
3223 info->display[0] = '\0';
3224 info->shortname[0] = '\0';
3225 info->more_display[0] = '\0';
3226
3227 /* Assume the characters indicating the packet type have been
3228 stripped. */
3229 pkt = unpack_int (pkt, &mask); /* arg mask */
3230 pkt = unpack_threadid (pkt, &ref);
3231
3232 if (mask == 0)
3233 warning (_("Incomplete response to threadinfo request."));
3234 if (!threadmatch (&ref, expectedref))
3235 { /* This is an answer to a different request. */
3236 warning (_("ERROR RMT Thread info mismatch."));
3237 return 0;
3238 }
3239 copy_threadref (&info->threadid, &ref);
3240
3241 /* Loop on tagged fields , try to bail if somthing goes wrong. */
3242
3243 /* Packets are terminated with nulls. */
3244 while ((pkt < limit) && mask && *pkt)
3245 {
3246 pkt = unpack_int (pkt, &tag); /* tag */
3247 pkt = unpack_byte (pkt, &length); /* length */
3248 if (!(tag & mask)) /* Tags out of synch with mask. */
3249 {
3250 warning (_("ERROR RMT: threadinfo tag mismatch."));
3251 retval = 0;
3252 break;
3253 }
3254 if (tag == TAG_THREADID)
3255 {
3256 if (length != 16)
3257 {
3258 warning (_("ERROR RMT: length of threadid is not 16."));
3259 retval = 0;
3260 break;
3261 }
3262 pkt = unpack_threadid (pkt, &ref);
3263 mask = mask & ~TAG_THREADID;
3264 continue;
3265 }
3266 if (tag == TAG_EXISTS)
3267 {
3268 info->active = stub_unpack_int (pkt, length);
3269 pkt += length;
3270 mask = mask & ~(TAG_EXISTS);
3271 if (length > 8)
3272 {
3273 warning (_("ERROR RMT: 'exists' length too long."));
3274 retval = 0;
3275 break;
3276 }
3277 continue;
3278 }
3279 if (tag == TAG_THREADNAME)
3280 {
3281 pkt = unpack_string (pkt, &info->shortname[0], length);
3282 mask = mask & ~TAG_THREADNAME;
3283 continue;
3284 }
3285 if (tag == TAG_DISPLAY)
3286 {
3287 pkt = unpack_string (pkt, &info->display[0], length);
3288 mask = mask & ~TAG_DISPLAY;
3289 continue;
3290 }
3291 if (tag == TAG_MOREDISPLAY)
3292 {
3293 pkt = unpack_string (pkt, &info->more_display[0], length);
3294 mask = mask & ~TAG_MOREDISPLAY;
3295 continue;
3296 }
3297 warning (_("ERROR RMT: unknown thread info tag."));
3298 break; /* Not a tag we know about. */
3299 }
3300 return retval;
3301 }
3302
3303 int
3304 remote_target::remote_get_threadinfo (threadref *threadid,
3305 int fieldset,
3306 gdb_ext_thread_info *info)
3307 {
3308 struct remote_state *rs = get_remote_state ();
3309 int result;
3310
3311 pack_threadinfo_request (rs->buf, fieldset, threadid);
3312 putpkt (rs->buf);
3313 getpkt (&rs->buf, &rs->buf_size, 0);
3314
3315 if (rs->buf[0] == '\0')
3316 return 0;
3317
3318 result = remote_unpack_thread_info_response (rs->buf + 2,
3319 threadid, info);
3320 return result;
3321 }
3322
3323 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3324
3325 static char *
3326 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3327 threadref *nextthread)
3328 {
3329 *pkt++ = 'q'; /* info query packet */
3330 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3331 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3332 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3333 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3334 *pkt = '\0';
3335 return pkt;
3336 }
3337
3338 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3339
3340 int
3341 remote_target::parse_threadlist_response (char *pkt, int result_limit,
3342 threadref *original_echo,
3343 threadref *resultlist,
3344 int *doneflag)
3345 {
3346 struct remote_state *rs = get_remote_state ();
3347 char *limit;
3348 int count, resultcount, done;
3349
3350 resultcount = 0;
3351 /* Assume the 'q' and 'M chars have been stripped. */
3352 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3353 /* done parse past here */
3354 pkt = unpack_byte (pkt, &count); /* count field */
3355 pkt = unpack_nibble (pkt, &done);
3356 /* The first threadid is the argument threadid. */
3357 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3358 while ((count-- > 0) && (pkt < limit))
3359 {
3360 pkt = unpack_threadid (pkt, resultlist++);
3361 if (resultcount++ >= result_limit)
3362 break;
3363 }
3364 if (doneflag)
3365 *doneflag = done;
3366 return resultcount;
3367 }
3368
3369 /* Fetch the next batch of threads from the remote. Returns -1 if the
3370 qL packet is not supported, 0 on error and 1 on success. */
3371
3372 int
3373 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3374 int result_limit, int *done, int *result_count,
3375 threadref *threadlist)
3376 {
3377 struct remote_state *rs = get_remote_state ();
3378 int result = 1;
3379
3380 /* Trancate result limit to be smaller than the packet size. */
3381 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3382 >= get_remote_packet_size ())
3383 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3384
3385 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3386 putpkt (rs->buf);
3387 getpkt (&rs->buf, &rs->buf_size, 0);
3388 if (*rs->buf == '\0')
3389 {
3390 /* Packet not supported. */
3391 return -1;
3392 }
3393
3394 *result_count =
3395 parse_threadlist_response (rs->buf + 2, result_limit,
3396 &rs->echo_nextthread, threadlist, done);
3397
3398 if (!threadmatch (&rs->echo_nextthread, nextthread))
3399 {
3400 /* FIXME: This is a good reason to drop the packet. */
3401 /* Possably, there is a duplicate response. */
3402 /* Possabilities :
3403 retransmit immediatly - race conditions
3404 retransmit after timeout - yes
3405 exit
3406 wait for packet, then exit
3407 */
3408 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3409 return 0; /* I choose simply exiting. */
3410 }
3411 if (*result_count <= 0)
3412 {
3413 if (*done != 1)
3414 {
3415 warning (_("RMT ERROR : failed to get remote thread list."));
3416 result = 0;
3417 }
3418 return result; /* break; */
3419 }
3420 if (*result_count > result_limit)
3421 {
3422 *result_count = 0;
3423 warning (_("RMT ERROR: threadlist response longer than requested."));
3424 return 0;
3425 }
3426 return result;
3427 }
3428
3429 /* Fetch the list of remote threads, with the qL packet, and call
3430 STEPFUNCTION for each thread found. Stops iterating and returns 1
3431 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3432 STEPFUNCTION returns false. If the packet is not supported,
3433 returns -1. */
3434
3435 int
3436 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3437 void *context, int looplimit)
3438 {
3439 struct remote_state *rs = get_remote_state ();
3440 int done, i, result_count;
3441 int startflag = 1;
3442 int result = 1;
3443 int loopcount = 0;
3444
3445 done = 0;
3446 while (!done)
3447 {
3448 if (loopcount++ > looplimit)
3449 {
3450 result = 0;
3451 warning (_("Remote fetch threadlist -infinite loop-."));
3452 break;
3453 }
3454 result = remote_get_threadlist (startflag, &rs->nextthread,
3455 MAXTHREADLISTRESULTS,
3456 &done, &result_count,
3457 rs->resultthreadlist);
3458 if (result <= 0)
3459 break;
3460 /* Clear for later iterations. */
3461 startflag = 0;
3462 /* Setup to resume next batch of thread references, set nextthread. */
3463 if (result_count >= 1)
3464 copy_threadref (&rs->nextthread,
3465 &rs->resultthreadlist[result_count - 1]);
3466 i = 0;
3467 while (result_count--)
3468 {
3469 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3470 {
3471 result = 0;
3472 break;
3473 }
3474 }
3475 }
3476 return result;
3477 }
3478
3479 /* A thread found on the remote target. */
3480
3481 struct thread_item
3482 {
3483 explicit thread_item (ptid_t ptid_)
3484 : ptid (ptid_)
3485 {}
3486
3487 thread_item (thread_item &&other) = default;
3488 thread_item &operator= (thread_item &&other) = default;
3489
3490 DISABLE_COPY_AND_ASSIGN (thread_item);
3491
3492 /* The thread's PTID. */
3493 ptid_t ptid;
3494
3495 /* The thread's extra info. */
3496 std::string extra;
3497
3498 /* The thread's name. */
3499 std::string name;
3500
3501 /* The core the thread was running on. -1 if not known. */
3502 int core = -1;
3503
3504 /* The thread handle associated with the thread. */
3505 gdb::byte_vector thread_handle;
3506 };
3507
3508 /* Context passed around to the various methods listing remote
3509 threads. As new threads are found, they're added to the ITEMS
3510 vector. */
3511
3512 struct threads_listing_context
3513 {
3514 /* Return true if this object contains an entry for a thread with ptid
3515 PTID. */
3516
3517 bool contains_thread (ptid_t ptid) const
3518 {
3519 auto match_ptid = [&] (const thread_item &item)
3520 {
3521 return item.ptid == ptid;
3522 };
3523
3524 auto it = std::find_if (this->items.begin (),
3525 this->items.end (),
3526 match_ptid);
3527
3528 return it != this->items.end ();
3529 }
3530
3531 /* Remove the thread with ptid PTID. */
3532
3533 void remove_thread (ptid_t ptid)
3534 {
3535 auto match_ptid = [&] (const thread_item &item)
3536 {
3537 return item.ptid == ptid;
3538 };
3539
3540 auto it = std::remove_if (this->items.begin (),
3541 this->items.end (),
3542 match_ptid);
3543
3544 if (it != this->items.end ())
3545 this->items.erase (it);
3546 }
3547
3548 /* The threads found on the remote target. */
3549 std::vector<thread_item> items;
3550 };
3551
3552 static int
3553 remote_newthread_step (threadref *ref, void *data)
3554 {
3555 struct threads_listing_context *context
3556 = (struct threads_listing_context *) data;
3557 int pid = inferior_ptid.pid ();
3558 int lwp = threadref_to_int (ref);
3559 ptid_t ptid (pid, lwp);
3560
3561 context->items.emplace_back (ptid);
3562
3563 return 1; /* continue iterator */
3564 }
3565
3566 #define CRAZY_MAX_THREADS 1000
3567
3568 ptid_t
3569 remote_target::remote_current_thread (ptid_t oldpid)
3570 {
3571 struct remote_state *rs = get_remote_state ();
3572
3573 putpkt ("qC");
3574 getpkt (&rs->buf, &rs->buf_size, 0);
3575 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3576 {
3577 const char *obuf;
3578 ptid_t result;
3579
3580 result = read_ptid (&rs->buf[2], &obuf);
3581 if (*obuf != '\0' && remote_debug)
3582 fprintf_unfiltered (gdb_stdlog,
3583 "warning: garbage in qC reply\n");
3584
3585 return result;
3586 }
3587 else
3588 return oldpid;
3589 }
3590
3591 /* List remote threads using the deprecated qL packet. */
3592
3593 int
3594 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3595 {
3596 if (remote_threadlist_iterator (remote_newthread_step, context,
3597 CRAZY_MAX_THREADS) >= 0)
3598 return 1;
3599
3600 return 0;
3601 }
3602
3603 #if defined(HAVE_LIBEXPAT)
3604
3605 static void
3606 start_thread (struct gdb_xml_parser *parser,
3607 const struct gdb_xml_element *element,
3608 void *user_data,
3609 std::vector<gdb_xml_value> &attributes)
3610 {
3611 struct threads_listing_context *data
3612 = (struct threads_listing_context *) user_data;
3613 struct gdb_xml_value *attr;
3614
3615 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3616 ptid_t ptid = read_ptid (id, NULL);
3617
3618 data->items.emplace_back (ptid);
3619 thread_item &item = data->items.back ();
3620
3621 attr = xml_find_attribute (attributes, "core");
3622 if (attr != NULL)
3623 item.core = *(ULONGEST *) attr->value.get ();
3624
3625 attr = xml_find_attribute (attributes, "name");
3626 if (attr != NULL)
3627 item.name = (const char *) attr->value.get ();
3628
3629 attr = xml_find_attribute (attributes, "handle");
3630 if (attr != NULL)
3631 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3632 }
3633
3634 static void
3635 end_thread (struct gdb_xml_parser *parser,
3636 const struct gdb_xml_element *element,
3637 void *user_data, const char *body_text)
3638 {
3639 struct threads_listing_context *data
3640 = (struct threads_listing_context *) user_data;
3641
3642 if (body_text != NULL && *body_text != '\0')
3643 data->items.back ().extra = body_text;
3644 }
3645
3646 const struct gdb_xml_attribute thread_attributes[] = {
3647 { "id", GDB_XML_AF_NONE, NULL, NULL },
3648 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3649 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3650 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3651 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3652 };
3653
3654 const struct gdb_xml_element thread_children[] = {
3655 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3656 };
3657
3658 const struct gdb_xml_element threads_children[] = {
3659 { "thread", thread_attributes, thread_children,
3660 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3661 start_thread, end_thread },
3662 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3663 };
3664
3665 const struct gdb_xml_element threads_elements[] = {
3666 { "threads", NULL, threads_children,
3667 GDB_XML_EF_NONE, NULL, NULL },
3668 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3669 };
3670
3671 #endif
3672
3673 /* List remote threads using qXfer:threads:read. */
3674
3675 int
3676 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3677 {
3678 #if defined(HAVE_LIBEXPAT)
3679 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3680 {
3681 gdb::optional<gdb::char_vector> xml
3682 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3683
3684 if (xml && (*xml)[0] != '\0')
3685 {
3686 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3687 threads_elements, xml->data (), context);
3688 }
3689
3690 return 1;
3691 }
3692 #endif
3693
3694 return 0;
3695 }
3696
3697 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3698
3699 int
3700 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3701 {
3702 struct remote_state *rs = get_remote_state ();
3703
3704 if (rs->use_threadinfo_query)
3705 {
3706 const char *bufp;
3707
3708 putpkt ("qfThreadInfo");
3709 getpkt (&rs->buf, &rs->buf_size, 0);
3710 bufp = rs->buf;
3711 if (bufp[0] != '\0') /* q packet recognized */
3712 {
3713 while (*bufp++ == 'm') /* reply contains one or more TID */
3714 {
3715 do
3716 {
3717 ptid_t ptid = read_ptid (bufp, &bufp);
3718 context->items.emplace_back (ptid);
3719 }
3720 while (*bufp++ == ','); /* comma-separated list */
3721 putpkt ("qsThreadInfo");
3722 getpkt (&rs->buf, &rs->buf_size, 0);
3723 bufp = rs->buf;
3724 }
3725 return 1;
3726 }
3727 else
3728 {
3729 /* Packet not recognized. */
3730 rs->use_threadinfo_query = 0;
3731 }
3732 }
3733
3734 return 0;
3735 }
3736
3737 /* Implement the to_update_thread_list function for the remote
3738 targets. */
3739
3740 void
3741 remote_target::update_thread_list ()
3742 {
3743 struct threads_listing_context context;
3744 int got_list = 0;
3745
3746 /* We have a few different mechanisms to fetch the thread list. Try
3747 them all, starting with the most preferred one first, falling
3748 back to older methods. */
3749 if (remote_get_threads_with_qxfer (&context)
3750 || remote_get_threads_with_qthreadinfo (&context)
3751 || remote_get_threads_with_ql (&context))
3752 {
3753 struct thread_info *tp, *tmp;
3754
3755 got_list = 1;
3756
3757 if (context.items.empty ()
3758 && remote_thread_always_alive (inferior_ptid))
3759 {
3760 /* Some targets don't really support threads, but still
3761 reply an (empty) thread list in response to the thread
3762 listing packets, instead of replying "packet not
3763 supported". Exit early so we don't delete the main
3764 thread. */
3765 return;
3766 }
3767
3768 /* CONTEXT now holds the current thread list on the remote
3769 target end. Delete GDB-side threads no longer found on the
3770 target. */
3771 ALL_THREADS_SAFE (tp, tmp)
3772 {
3773 if (!context.contains_thread (tp->ptid))
3774 {
3775 /* Not found. */
3776 delete_thread (tp->ptid);
3777 }
3778 }
3779
3780 /* Remove any unreported fork child threads from CONTEXT so
3781 that we don't interfere with follow fork, which is where
3782 creation of such threads is handled. */
3783 remove_new_fork_children (&context);
3784
3785 /* And now add threads we don't know about yet to our list. */
3786 for (thread_item &item : context.items)
3787 {
3788 if (item.ptid != null_ptid)
3789 {
3790 /* In non-stop mode, we assume new found threads are
3791 executing until proven otherwise with a stop reply.
3792 In all-stop, we can only get here if all threads are
3793 stopped. */
3794 int executing = target_is_non_stop_p () ? 1 : 0;
3795
3796 remote_notice_new_inferior (item.ptid, executing);
3797
3798 remote_thread_info *info = get_remote_thread_info (item.ptid);
3799 info->core = item.core;
3800 info->extra = std::move (item.extra);
3801 info->name = std::move (item.name);
3802 info->thread_handle = std::move (item.thread_handle);
3803 }
3804 }
3805 }
3806
3807 if (!got_list)
3808 {
3809 /* If no thread listing method is supported, then query whether
3810 each known thread is alive, one by one, with the T packet.
3811 If the target doesn't support threads at all, then this is a
3812 no-op. See remote_thread_alive. */
3813 prune_threads ();
3814 }
3815 }
3816
3817 /*
3818 * Collect a descriptive string about the given thread.
3819 * The target may say anything it wants to about the thread
3820 * (typically info about its blocked / runnable state, name, etc.).
3821 * This string will appear in the info threads display.
3822 *
3823 * Optional: targets are not required to implement this function.
3824 */
3825
3826 const char *
3827 remote_target::extra_thread_info (thread_info *tp)
3828 {
3829 struct remote_state *rs = get_remote_state ();
3830 int result;
3831 int set;
3832 threadref id;
3833 struct gdb_ext_thread_info threadinfo;
3834 static char display_buf[100]; /* arbitrary... */
3835 int n = 0; /* position in display_buf */
3836
3837 if (rs->remote_desc == 0) /* paranoia */
3838 internal_error (__FILE__, __LINE__,
3839 _("remote_threads_extra_info"));
3840
3841 if (ptid_equal (tp->ptid, magic_null_ptid)
3842 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3843 /* This is the main thread which was added by GDB. The remote
3844 server doesn't know about it. */
3845 return NULL;
3846
3847 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3848 {
3849 struct thread_info *info = find_thread_ptid (tp->ptid);
3850
3851 if (info != NULL && info->priv != NULL)
3852 {
3853 const std::string &extra = get_remote_thread_info (info)->extra;
3854 return !extra.empty () ? extra.c_str () : NULL;
3855 }
3856 else
3857 return NULL;
3858 }
3859
3860 if (rs->use_threadextra_query)
3861 {
3862 char *b = rs->buf;
3863 char *endb = rs->buf + get_remote_packet_size ();
3864
3865 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3866 b += strlen (b);
3867 write_ptid (b, endb, tp->ptid);
3868
3869 putpkt (rs->buf);
3870 getpkt (&rs->buf, &rs->buf_size, 0);
3871 if (rs->buf[0] != 0)
3872 {
3873 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3874 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3875 display_buf [result] = '\0';
3876 return display_buf;
3877 }
3878 }
3879
3880 /* If the above query fails, fall back to the old method. */
3881 rs->use_threadextra_query = 0;
3882 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3883 | TAG_MOREDISPLAY | TAG_DISPLAY;
3884 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3885 if (remote_get_threadinfo (&id, set, &threadinfo))
3886 if (threadinfo.active)
3887 {
3888 if (*threadinfo.shortname)
3889 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3890 " Name: %s,", threadinfo.shortname);
3891 if (*threadinfo.display)
3892 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3893 " State: %s,", threadinfo.display);
3894 if (*threadinfo.more_display)
3895 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3896 " Priority: %s", threadinfo.more_display);
3897
3898 if (n > 0)
3899 {
3900 /* For purely cosmetic reasons, clear up trailing commas. */
3901 if (',' == display_buf[n-1])
3902 display_buf[n-1] = ' ';
3903 return display_buf;
3904 }
3905 }
3906 return NULL;
3907 }
3908 \f
3909
3910 bool
3911 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3912 struct static_tracepoint_marker *marker)
3913 {
3914 struct remote_state *rs = get_remote_state ();
3915 char *p = rs->buf;
3916
3917 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3918 p += strlen (p);
3919 p += hexnumstr (p, addr);
3920 putpkt (rs->buf);
3921 getpkt (&rs->buf, &rs->buf_size, 0);
3922 p = rs->buf;
3923
3924 if (*p == 'E')
3925 error (_("Remote failure reply: %s"), p);
3926
3927 if (*p++ == 'm')
3928 {
3929 parse_static_tracepoint_marker_definition (p, NULL, marker);
3930 return true;
3931 }
3932
3933 return false;
3934 }
3935
3936 std::vector<static_tracepoint_marker>
3937 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3938 {
3939 struct remote_state *rs = get_remote_state ();
3940 std::vector<static_tracepoint_marker> markers;
3941 const char *p;
3942 static_tracepoint_marker marker;
3943
3944 /* Ask for a first packet of static tracepoint marker
3945 definition. */
3946 putpkt ("qTfSTM");
3947 getpkt (&rs->buf, &rs->buf_size, 0);
3948 p = rs->buf;
3949 if (*p == 'E')
3950 error (_("Remote failure reply: %s"), p);
3951
3952 while (*p++ == 'm')
3953 {
3954 do
3955 {
3956 parse_static_tracepoint_marker_definition (p, &p, &marker);
3957
3958 if (strid == NULL || marker.str_id == strid)
3959 markers.push_back (std::move (marker));
3960 }
3961 while (*p++ == ','); /* comma-separated list */
3962 /* Ask for another packet of static tracepoint definition. */
3963 putpkt ("qTsSTM");
3964 getpkt (&rs->buf, &rs->buf_size, 0);
3965 p = rs->buf;
3966 }
3967
3968 return markers;
3969 }
3970
3971 \f
3972 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3973
3974 ptid_t
3975 remote_target::get_ada_task_ptid (long lwp, long thread)
3976 {
3977 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3978 }
3979 \f
3980
3981 /* Restart the remote side; this is an extended protocol operation. */
3982
3983 void
3984 remote_target::extended_remote_restart ()
3985 {
3986 struct remote_state *rs = get_remote_state ();
3987
3988 /* Send the restart command; for reasons I don't understand the
3989 remote side really expects a number after the "R". */
3990 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3991 putpkt (rs->buf);
3992
3993 remote_fileio_reset ();
3994 }
3995 \f
3996 /* Clean up connection to a remote debugger. */
3997
3998 void
3999 remote_target::close ()
4000 {
4001 /* Make sure we leave stdin registered in the event loop. */
4002 terminal_ours ();
4003
4004 /* We don't have a connection to the remote stub anymore. Get rid
4005 of all the inferiors and their threads we were controlling.
4006 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4007 will be unable to find the thread corresponding to (pid, 0, 0). */
4008 inferior_ptid = null_ptid;
4009 discard_all_inferiors ();
4010
4011 trace_reset_local_state ();
4012
4013 delete this;
4014 }
4015
4016 remote_target::~remote_target ()
4017 {
4018 struct remote_state *rs = get_remote_state ();
4019
4020 /* Check for NULL because we may get here with a partially
4021 constructed target/connection. */
4022 if (rs->remote_desc == nullptr)
4023 return;
4024
4025 serial_close (rs->remote_desc);
4026
4027 /* We are destroying the remote target, so we should discard
4028 everything of this target. */
4029 discard_pending_stop_replies_in_queue ();
4030
4031 if (rs->remote_async_inferior_event_token)
4032 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4033
4034 remote_notif_state_xfree (rs->notif_state);
4035 }
4036
4037 /* Query the remote side for the text, data and bss offsets. */
4038
4039 void
4040 remote_target::get_offsets ()
4041 {
4042 struct remote_state *rs = get_remote_state ();
4043 char *buf;
4044 char *ptr;
4045 int lose, num_segments = 0, do_sections, do_segments;
4046 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4047 struct section_offsets *offs;
4048 struct symfile_segment_data *data;
4049
4050 if (symfile_objfile == NULL)
4051 return;
4052
4053 putpkt ("qOffsets");
4054 getpkt (&rs->buf, &rs->buf_size, 0);
4055 buf = rs->buf;
4056
4057 if (buf[0] == '\000')
4058 return; /* Return silently. Stub doesn't support
4059 this command. */
4060 if (buf[0] == 'E')
4061 {
4062 warning (_("Remote failure reply: %s"), buf);
4063 return;
4064 }
4065
4066 /* Pick up each field in turn. This used to be done with scanf, but
4067 scanf will make trouble if CORE_ADDR size doesn't match
4068 conversion directives correctly. The following code will work
4069 with any size of CORE_ADDR. */
4070 text_addr = data_addr = bss_addr = 0;
4071 ptr = buf;
4072 lose = 0;
4073
4074 if (startswith (ptr, "Text="))
4075 {
4076 ptr += 5;
4077 /* Don't use strtol, could lose on big values. */
4078 while (*ptr && *ptr != ';')
4079 text_addr = (text_addr << 4) + fromhex (*ptr++);
4080
4081 if (startswith (ptr, ";Data="))
4082 {
4083 ptr += 6;
4084 while (*ptr && *ptr != ';')
4085 data_addr = (data_addr << 4) + fromhex (*ptr++);
4086 }
4087 else
4088 lose = 1;
4089
4090 if (!lose && startswith (ptr, ";Bss="))
4091 {
4092 ptr += 5;
4093 while (*ptr && *ptr != ';')
4094 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4095
4096 if (bss_addr != data_addr)
4097 warning (_("Target reported unsupported offsets: %s"), buf);
4098 }
4099 else
4100 lose = 1;
4101 }
4102 else if (startswith (ptr, "TextSeg="))
4103 {
4104 ptr += 8;
4105 /* Don't use strtol, could lose on big values. */
4106 while (*ptr && *ptr != ';')
4107 text_addr = (text_addr << 4) + fromhex (*ptr++);
4108 num_segments = 1;
4109
4110 if (startswith (ptr, ";DataSeg="))
4111 {
4112 ptr += 9;
4113 while (*ptr && *ptr != ';')
4114 data_addr = (data_addr << 4) + fromhex (*ptr++);
4115 num_segments++;
4116 }
4117 }
4118 else
4119 lose = 1;
4120
4121 if (lose)
4122 error (_("Malformed response to offset query, %s"), buf);
4123 else if (*ptr != '\0')
4124 warning (_("Target reported unsupported offsets: %s"), buf);
4125
4126 offs = ((struct section_offsets *)
4127 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
4128 memcpy (offs, symfile_objfile->section_offsets,
4129 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
4130
4131 data = get_symfile_segment_data (symfile_objfile->obfd);
4132 do_segments = (data != NULL);
4133 do_sections = num_segments == 0;
4134
4135 if (num_segments > 0)
4136 {
4137 segments[0] = text_addr;
4138 segments[1] = data_addr;
4139 }
4140 /* If we have two segments, we can still try to relocate everything
4141 by assuming that the .text and .data offsets apply to the whole
4142 text and data segments. Convert the offsets given in the packet
4143 to base addresses for symfile_map_offsets_to_segments. */
4144 else if (data && data->num_segments == 2)
4145 {
4146 segments[0] = data->segment_bases[0] + text_addr;
4147 segments[1] = data->segment_bases[1] + data_addr;
4148 num_segments = 2;
4149 }
4150 /* If the object file has only one segment, assume that it is text
4151 rather than data; main programs with no writable data are rare,
4152 but programs with no code are useless. Of course the code might
4153 have ended up in the data segment... to detect that we would need
4154 the permissions here. */
4155 else if (data && data->num_segments == 1)
4156 {
4157 segments[0] = data->segment_bases[0] + text_addr;
4158 num_segments = 1;
4159 }
4160 /* There's no way to relocate by segment. */
4161 else
4162 do_segments = 0;
4163
4164 if (do_segments)
4165 {
4166 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4167 offs, num_segments, segments);
4168
4169 if (ret == 0 && !do_sections)
4170 error (_("Can not handle qOffsets TextSeg "
4171 "response with this symbol file"));
4172
4173 if (ret > 0)
4174 do_sections = 0;
4175 }
4176
4177 if (data)
4178 free_symfile_segment_data (data);
4179
4180 if (do_sections)
4181 {
4182 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4183
4184 /* This is a temporary kludge to force data and bss to use the
4185 same offsets because that's what nlmconv does now. The real
4186 solution requires changes to the stub and remote.c that I
4187 don't have time to do right now. */
4188
4189 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4190 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4191 }
4192
4193 objfile_relocate (symfile_objfile, offs);
4194 }
4195
4196 /* Send interrupt_sequence to remote target. */
4197
4198 void
4199 remote_target::send_interrupt_sequence ()
4200 {
4201 struct remote_state *rs = get_remote_state ();
4202
4203 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4204 remote_serial_write ("\x03", 1);
4205 else if (interrupt_sequence_mode == interrupt_sequence_break)
4206 serial_send_break (rs->remote_desc);
4207 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4208 {
4209 serial_send_break (rs->remote_desc);
4210 remote_serial_write ("g", 1);
4211 }
4212 else
4213 internal_error (__FILE__, __LINE__,
4214 _("Invalid value for interrupt_sequence_mode: %s."),
4215 interrupt_sequence_mode);
4216 }
4217
4218
4219 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4220 and extract the PTID. Returns NULL_PTID if not found. */
4221
4222 static ptid_t
4223 stop_reply_extract_thread (char *stop_reply)
4224 {
4225 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4226 {
4227 const char *p;
4228
4229 /* Txx r:val ; r:val (...) */
4230 p = &stop_reply[3];
4231
4232 /* Look for "register" named "thread". */
4233 while (*p != '\0')
4234 {
4235 const char *p1;
4236
4237 p1 = strchr (p, ':');
4238 if (p1 == NULL)
4239 return null_ptid;
4240
4241 if (strncmp (p, "thread", p1 - p) == 0)
4242 return read_ptid (++p1, &p);
4243
4244 p1 = strchr (p, ';');
4245 if (p1 == NULL)
4246 return null_ptid;
4247 p1++;
4248
4249 p = p1;
4250 }
4251 }
4252
4253 return null_ptid;
4254 }
4255
4256 /* Determine the remote side's current thread. If we have a stop
4257 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4258 "thread" register we can extract the current thread from. If not,
4259 ask the remote which is the current thread with qC. The former
4260 method avoids a roundtrip. */
4261
4262 ptid_t
4263 remote_target::get_current_thread (char *wait_status)
4264 {
4265 ptid_t ptid = null_ptid;
4266
4267 /* Note we don't use remote_parse_stop_reply as that makes use of
4268 the target architecture, which we haven't yet fully determined at
4269 this point. */
4270 if (wait_status != NULL)
4271 ptid = stop_reply_extract_thread (wait_status);
4272 if (ptid_equal (ptid, null_ptid))
4273 ptid = remote_current_thread (inferior_ptid);
4274
4275 return ptid;
4276 }
4277
4278 /* Query the remote target for which is the current thread/process,
4279 add it to our tables, and update INFERIOR_PTID. The caller is
4280 responsible for setting the state such that the remote end is ready
4281 to return the current thread.
4282
4283 This function is called after handling the '?' or 'vRun' packets,
4284 whose response is a stop reply from which we can also try
4285 extracting the thread. If the target doesn't support the explicit
4286 qC query, we infer the current thread from that stop reply, passed
4287 in in WAIT_STATUS, which may be NULL. */
4288
4289 void
4290 remote_target::add_current_inferior_and_thread (char *wait_status)
4291 {
4292 struct remote_state *rs = get_remote_state ();
4293 int fake_pid_p = 0;
4294
4295 inferior_ptid = null_ptid;
4296
4297 /* Now, if we have thread information, update inferior_ptid. */
4298 ptid_t curr_ptid = get_current_thread (wait_status);
4299
4300 if (curr_ptid != null_ptid)
4301 {
4302 if (!remote_multi_process_p (rs))
4303 fake_pid_p = 1;
4304 }
4305 else
4306 {
4307 /* Without this, some commands which require an active target
4308 (such as kill) won't work. This variable serves (at least)
4309 double duty as both the pid of the target process (if it has
4310 such), and as a flag indicating that a target is active. */
4311 curr_ptid = magic_null_ptid;
4312 fake_pid_p = 1;
4313 }
4314
4315 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
4316
4317 /* Add the main thread and switch to it. Don't try reading
4318 registers yet, since we haven't fetched the target description
4319 yet. */
4320 thread_info *tp = add_thread_silent (curr_ptid);
4321 switch_to_thread_no_regs (tp);
4322 }
4323
4324 /* Print info about a thread that was found already stopped on
4325 connection. */
4326
4327 static void
4328 print_one_stopped_thread (struct thread_info *thread)
4329 {
4330 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4331
4332 switch_to_thread (thread->ptid);
4333 stop_pc = get_frame_pc (get_current_frame ());
4334 set_current_sal_from_frame (get_current_frame ());
4335
4336 thread->suspend.waitstatus_pending_p = 0;
4337
4338 if (ws->kind == TARGET_WAITKIND_STOPPED)
4339 {
4340 enum gdb_signal sig = ws->value.sig;
4341
4342 if (signal_print_state (sig))
4343 gdb::observers::signal_received.notify (sig);
4344 }
4345 gdb::observers::normal_stop.notify (NULL, 1);
4346 }
4347
4348 /* Process all initial stop replies the remote side sent in response
4349 to the ? packet. These indicate threads that were already stopped
4350 on initial connection. We mark these threads as stopped and print
4351 their current frame before giving the user the prompt. */
4352
4353 void
4354 remote_target::process_initial_stop_replies (int from_tty)
4355 {
4356 int pending_stop_replies = stop_reply_queue_length ();
4357 struct inferior *inf;
4358 struct thread_info *thread;
4359 struct thread_info *selected = NULL;
4360 struct thread_info *lowest_stopped = NULL;
4361 struct thread_info *first = NULL;
4362
4363 /* Consume the initial pending events. */
4364 while (pending_stop_replies-- > 0)
4365 {
4366 ptid_t waiton_ptid = minus_one_ptid;
4367 ptid_t event_ptid;
4368 struct target_waitstatus ws;
4369 int ignore_event = 0;
4370 struct thread_info *thread;
4371
4372 memset (&ws, 0, sizeof (ws));
4373 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4374 if (remote_debug)
4375 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4376
4377 switch (ws.kind)
4378 {
4379 case TARGET_WAITKIND_IGNORE:
4380 case TARGET_WAITKIND_NO_RESUMED:
4381 case TARGET_WAITKIND_SIGNALLED:
4382 case TARGET_WAITKIND_EXITED:
4383 /* We shouldn't see these, but if we do, just ignore. */
4384 if (remote_debug)
4385 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4386 ignore_event = 1;
4387 break;
4388
4389 case TARGET_WAITKIND_EXECD:
4390 xfree (ws.value.execd_pathname);
4391 break;
4392 default:
4393 break;
4394 }
4395
4396 if (ignore_event)
4397 continue;
4398
4399 thread = find_thread_ptid (event_ptid);
4400
4401 if (ws.kind == TARGET_WAITKIND_STOPPED)
4402 {
4403 enum gdb_signal sig = ws.value.sig;
4404
4405 /* Stubs traditionally report SIGTRAP as initial signal,
4406 instead of signal 0. Suppress it. */
4407 if (sig == GDB_SIGNAL_TRAP)
4408 sig = GDB_SIGNAL_0;
4409 thread->suspend.stop_signal = sig;
4410 ws.value.sig = sig;
4411 }
4412
4413 thread->suspend.waitstatus = ws;
4414
4415 if (ws.kind != TARGET_WAITKIND_STOPPED
4416 || ws.value.sig != GDB_SIGNAL_0)
4417 thread->suspend.waitstatus_pending_p = 1;
4418
4419 set_executing (event_ptid, 0);
4420 set_running (event_ptid, 0);
4421 get_remote_thread_info (thread)->vcont_resumed = 0;
4422 }
4423
4424 /* "Notice" the new inferiors before anything related to
4425 registers/memory. */
4426 ALL_INFERIORS (inf)
4427 {
4428 if (inf->pid == 0)
4429 continue;
4430
4431 inf->needs_setup = 1;
4432
4433 if (non_stop)
4434 {
4435 thread = any_live_thread_of_process (inf->pid);
4436 notice_new_inferior (thread->ptid,
4437 thread->state == THREAD_RUNNING,
4438 from_tty);
4439 }
4440 }
4441
4442 /* If all-stop on top of non-stop, pause all threads. Note this
4443 records the threads' stop pc, so must be done after "noticing"
4444 the inferiors. */
4445 if (!non_stop)
4446 {
4447 stop_all_threads ();
4448
4449 /* If all threads of an inferior were already stopped, we
4450 haven't setup the inferior yet. */
4451 ALL_INFERIORS (inf)
4452 {
4453 if (inf->pid == 0)
4454 continue;
4455
4456 if (inf->needs_setup)
4457 {
4458 thread = any_live_thread_of_process (inf->pid);
4459 switch_to_thread_no_regs (thread);
4460 setup_inferior (0);
4461 }
4462 }
4463 }
4464
4465 /* Now go over all threads that are stopped, and print their current
4466 frame. If all-stop, then if there's a signalled thread, pick
4467 that as current. */
4468 ALL_NON_EXITED_THREADS (thread)
4469 {
4470 if (first == NULL)
4471 first = thread;
4472
4473 if (!non_stop)
4474 set_running (thread->ptid, 0);
4475 else if (thread->state != THREAD_STOPPED)
4476 continue;
4477
4478 if (selected == NULL
4479 && thread->suspend.waitstatus_pending_p)
4480 selected = thread;
4481
4482 if (lowest_stopped == NULL
4483 || thread->inf->num < lowest_stopped->inf->num
4484 || thread->per_inf_num < lowest_stopped->per_inf_num)
4485 lowest_stopped = thread;
4486
4487 if (non_stop)
4488 print_one_stopped_thread (thread);
4489 }
4490
4491 /* In all-stop, we only print the status of one thread, and leave
4492 others with their status pending. */
4493 if (!non_stop)
4494 {
4495 thread = selected;
4496 if (thread == NULL)
4497 thread = lowest_stopped;
4498 if (thread == NULL)
4499 thread = first;
4500
4501 print_one_stopped_thread (thread);
4502 }
4503
4504 /* For "info program". */
4505 thread = inferior_thread ();
4506 if (thread->state == THREAD_STOPPED)
4507 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4508 }
4509
4510 /* Start the remote connection and sync state. */
4511
4512 void
4513 remote_target::start_remote (int from_tty, int extended_p)
4514 {
4515 struct remote_state *rs = get_remote_state ();
4516 struct packet_config *noack_config;
4517 char *wait_status = NULL;
4518
4519 /* Signal other parts that we're going through the initial setup,
4520 and so things may not be stable yet. E.g., we don't try to
4521 install tracepoints until we've relocated symbols. Also, a
4522 Ctrl-C before we're connected and synced up can't interrupt the
4523 target. Instead, it offers to drop the (potentially wedged)
4524 connection. */
4525 rs->starting_up = 1;
4526
4527 QUIT;
4528
4529 if (interrupt_on_connect)
4530 send_interrupt_sequence ();
4531
4532 /* Ack any packet which the remote side has already sent. */
4533 remote_serial_write ("+", 1);
4534
4535 /* The first packet we send to the target is the optional "supported
4536 packets" request. If the target can answer this, it will tell us
4537 which later probes to skip. */
4538 remote_query_supported ();
4539
4540 /* If the stub wants to get a QAllow, compose one and send it. */
4541 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4542 set_permissions ();
4543
4544 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4545 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4546 as a reply to known packet. For packet "vFile:setfs:" it is an
4547 invalid reply and GDB would return error in
4548 remote_hostio_set_filesystem, making remote files access impossible.
4549 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4550 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4551 {
4552 const char v_mustreplyempty[] = "vMustReplyEmpty";
4553
4554 putpkt (v_mustreplyempty);
4555 getpkt (&rs->buf, &rs->buf_size, 0);
4556 if (strcmp (rs->buf, "OK") == 0)
4557 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4558 else if (strcmp (rs->buf, "") != 0)
4559 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4560 rs->buf);
4561 }
4562
4563 /* Next, we possibly activate noack mode.
4564
4565 If the QStartNoAckMode packet configuration is set to AUTO,
4566 enable noack mode if the stub reported a wish for it with
4567 qSupported.
4568
4569 If set to TRUE, then enable noack mode even if the stub didn't
4570 report it in qSupported. If the stub doesn't reply OK, the
4571 session ends with an error.
4572
4573 If FALSE, then don't activate noack mode, regardless of what the
4574 stub claimed should be the default with qSupported. */
4575
4576 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4577 if (packet_config_support (noack_config) != PACKET_DISABLE)
4578 {
4579 putpkt ("QStartNoAckMode");
4580 getpkt (&rs->buf, &rs->buf_size, 0);
4581 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4582 rs->noack_mode = 1;
4583 }
4584
4585 if (extended_p)
4586 {
4587 /* Tell the remote that we are using the extended protocol. */
4588 putpkt ("!");
4589 getpkt (&rs->buf, &rs->buf_size, 0);
4590 }
4591
4592 /* Let the target know which signals it is allowed to pass down to
4593 the program. */
4594 update_signals_program_target ();
4595
4596 /* Next, if the target can specify a description, read it. We do
4597 this before anything involving memory or registers. */
4598 target_find_description ();
4599
4600 /* Next, now that we know something about the target, update the
4601 address spaces in the program spaces. */
4602 update_address_spaces ();
4603
4604 /* On OSs where the list of libraries is global to all
4605 processes, we fetch them early. */
4606 if (gdbarch_has_global_solist (target_gdbarch ()))
4607 solib_add (NULL, from_tty, auto_solib_add);
4608
4609 if (target_is_non_stop_p ())
4610 {
4611 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4612 error (_("Non-stop mode requested, but remote "
4613 "does not support non-stop"));
4614
4615 putpkt ("QNonStop:1");
4616 getpkt (&rs->buf, &rs->buf_size, 0);
4617
4618 if (strcmp (rs->buf, "OK") != 0)
4619 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4620
4621 /* Find about threads and processes the stub is already
4622 controlling. We default to adding them in the running state.
4623 The '?' query below will then tell us about which threads are
4624 stopped. */
4625 this->update_thread_list ();
4626 }
4627 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4628 {
4629 /* Don't assume that the stub can operate in all-stop mode.
4630 Request it explicitly. */
4631 putpkt ("QNonStop:0");
4632 getpkt (&rs->buf, &rs->buf_size, 0);
4633
4634 if (strcmp (rs->buf, "OK") != 0)
4635 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4636 }
4637
4638 /* Upload TSVs regardless of whether the target is running or not. The
4639 remote stub, such as GDBserver, may have some predefined or builtin
4640 TSVs, even if the target is not running. */
4641 if (get_trace_status (current_trace_status ()) != -1)
4642 {
4643 struct uploaded_tsv *uploaded_tsvs = NULL;
4644
4645 upload_trace_state_variables (&uploaded_tsvs);
4646 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4647 }
4648
4649 /* Check whether the target is running now. */
4650 putpkt ("?");
4651 getpkt (&rs->buf, &rs->buf_size, 0);
4652
4653 if (!target_is_non_stop_p ())
4654 {
4655 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4656 {
4657 if (!extended_p)
4658 error (_("The target is not running (try extended-remote?)"));
4659
4660 /* We're connected, but not running. Drop out before we
4661 call start_remote. */
4662 rs->starting_up = 0;
4663 return;
4664 }
4665 else
4666 {
4667 /* Save the reply for later. */
4668 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4669 strcpy (wait_status, rs->buf);
4670 }
4671
4672 /* Fetch thread list. */
4673 target_update_thread_list ();
4674
4675 /* Let the stub know that we want it to return the thread. */
4676 set_continue_thread (minus_one_ptid);
4677
4678 if (thread_count () == 0)
4679 {
4680 /* Target has no concept of threads at all. GDB treats
4681 non-threaded target as single-threaded; add a main
4682 thread. */
4683 add_current_inferior_and_thread (wait_status);
4684 }
4685 else
4686 {
4687 /* We have thread information; select the thread the target
4688 says should be current. If we're reconnecting to a
4689 multi-threaded program, this will ideally be the thread
4690 that last reported an event before GDB disconnected. */
4691 inferior_ptid = get_current_thread (wait_status);
4692 if (ptid_equal (inferior_ptid, null_ptid))
4693 {
4694 /* Odd... The target was able to list threads, but not
4695 tell us which thread was current (no "thread"
4696 register in T stop reply?). Just pick the first
4697 thread in the thread list then. */
4698
4699 if (remote_debug)
4700 fprintf_unfiltered (gdb_stdlog,
4701 "warning: couldn't determine remote "
4702 "current thread; picking first in list.\n");
4703
4704 inferior_ptid = thread_list->ptid;
4705 }
4706 }
4707
4708 /* init_wait_for_inferior should be called before get_offsets in order
4709 to manage `inserted' flag in bp loc in a correct state.
4710 breakpoint_init_inferior, called from init_wait_for_inferior, set
4711 `inserted' flag to 0, while before breakpoint_re_set, called from
4712 start_remote, set `inserted' flag to 1. In the initialization of
4713 inferior, breakpoint_init_inferior should be called first, and then
4714 breakpoint_re_set can be called. If this order is broken, state of
4715 `inserted' flag is wrong, and cause some problems on breakpoint
4716 manipulation. */
4717 init_wait_for_inferior ();
4718
4719 get_offsets (); /* Get text, data & bss offsets. */
4720
4721 /* If we could not find a description using qXfer, and we know
4722 how to do it some other way, try again. This is not
4723 supported for non-stop; it could be, but it is tricky if
4724 there are no stopped threads when we connect. */
4725 if (remote_read_description_p (this)
4726 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4727 {
4728 target_clear_description ();
4729 target_find_description ();
4730 }
4731
4732 /* Use the previously fetched status. */
4733 gdb_assert (wait_status != NULL);
4734 strcpy (rs->buf, wait_status);
4735 rs->cached_wait_status = 1;
4736
4737 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4738 }
4739 else
4740 {
4741 /* Clear WFI global state. Do this before finding about new
4742 threads and inferiors, and setting the current inferior.
4743 Otherwise we would clear the proceed status of the current
4744 inferior when we want its stop_soon state to be preserved
4745 (see notice_new_inferior). */
4746 init_wait_for_inferior ();
4747
4748 /* In non-stop, we will either get an "OK", meaning that there
4749 are no stopped threads at this time; or, a regular stop
4750 reply. In the latter case, there may be more than one thread
4751 stopped --- we pull them all out using the vStopped
4752 mechanism. */
4753 if (strcmp (rs->buf, "OK") != 0)
4754 {
4755 struct notif_client *notif = &notif_client_stop;
4756
4757 /* remote_notif_get_pending_replies acks this one, and gets
4758 the rest out. */
4759 rs->notif_state->pending_event[notif_client_stop.id]
4760 = remote_notif_parse (this, notif, rs->buf);
4761 remote_notif_get_pending_events (notif);
4762 }
4763
4764 if (thread_count () == 0)
4765 {
4766 if (!extended_p)
4767 error (_("The target is not running (try extended-remote?)"));
4768
4769 /* We're connected, but not running. Drop out before we
4770 call start_remote. */
4771 rs->starting_up = 0;
4772 return;
4773 }
4774
4775 /* In non-stop mode, any cached wait status will be stored in
4776 the stop reply queue. */
4777 gdb_assert (wait_status == NULL);
4778
4779 /* Report all signals during attach/startup. */
4780 pass_signals (0, NULL);
4781
4782 /* If there are already stopped threads, mark them stopped and
4783 report their stops before giving the prompt to the user. */
4784 process_initial_stop_replies (from_tty);
4785
4786 if (target_can_async_p ())
4787 target_async (1);
4788 }
4789
4790 /* If we connected to a live target, do some additional setup. */
4791 if (target_has_execution)
4792 {
4793 if (symfile_objfile) /* No use without a symbol-file. */
4794 remote_check_symbols ();
4795 }
4796
4797 /* Possibly the target has been engaged in a trace run started
4798 previously; find out where things are at. */
4799 if (get_trace_status (current_trace_status ()) != -1)
4800 {
4801 struct uploaded_tp *uploaded_tps = NULL;
4802
4803 if (current_trace_status ()->running)
4804 printf_filtered (_("Trace is already running on the target.\n"));
4805
4806 upload_tracepoints (&uploaded_tps);
4807
4808 merge_uploaded_tracepoints (&uploaded_tps);
4809 }
4810
4811 /* Possibly the target has been engaged in a btrace record started
4812 previously; find out where things are at. */
4813 remote_btrace_maybe_reopen ();
4814
4815 /* The thread and inferior lists are now synchronized with the
4816 target, our symbols have been relocated, and we're merged the
4817 target's tracepoints with ours. We're done with basic start
4818 up. */
4819 rs->starting_up = 0;
4820
4821 /* Maybe breakpoints are global and need to be inserted now. */
4822 if (breakpoints_should_be_inserted_now ())
4823 insert_breakpoints ();
4824 }
4825
4826 /* Open a connection to a remote debugger.
4827 NAME is the filename used for communication. */
4828
4829 void
4830 remote_target::open (const char *name, int from_tty)
4831 {
4832 open_1 (name, from_tty, 0);
4833 }
4834
4835 /* Open a connection to a remote debugger using the extended
4836 remote gdb protocol. NAME is the filename used for communication. */
4837
4838 void
4839 extended_remote_target::open (const char *name, int from_tty)
4840 {
4841 open_1 (name, from_tty, 1 /*extended_p */);
4842 }
4843
4844 /* Reset all packets back to "unknown support". Called when opening a
4845 new connection to a remote target. */
4846
4847 static void
4848 reset_all_packet_configs_support (void)
4849 {
4850 int i;
4851
4852 for (i = 0; i < PACKET_MAX; i++)
4853 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4854 }
4855
4856 /* Initialize all packet configs. */
4857
4858 static void
4859 init_all_packet_configs (void)
4860 {
4861 int i;
4862
4863 for (i = 0; i < PACKET_MAX; i++)
4864 {
4865 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4866 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4867 }
4868 }
4869
4870 /* Symbol look-up. */
4871
4872 void
4873 remote_target::remote_check_symbols ()
4874 {
4875 char *msg, *reply, *tmp;
4876 int end;
4877 long reply_size;
4878 struct cleanup *old_chain;
4879
4880 /* The remote side has no concept of inferiors that aren't running
4881 yet, it only knows about running processes. If we're connected
4882 but our current inferior is not running, we should not invite the
4883 remote target to request symbol lookups related to its
4884 (unrelated) current process. */
4885 if (!target_has_execution)
4886 return;
4887
4888 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4889 return;
4890
4891 /* Make sure the remote is pointing at the right process. Note
4892 there's no way to select "no process". */
4893 set_general_process ();
4894
4895 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4896 because we need both at the same time. */
4897 msg = (char *) xmalloc (get_remote_packet_size ());
4898 old_chain = make_cleanup (xfree, msg);
4899 reply = (char *) xmalloc (get_remote_packet_size ());
4900 make_cleanup (free_current_contents, &reply);
4901 reply_size = get_remote_packet_size ();
4902
4903 /* Invite target to request symbol lookups. */
4904
4905 putpkt ("qSymbol::");
4906 getpkt (&reply, &reply_size, 0);
4907 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4908
4909 while (startswith (reply, "qSymbol:"))
4910 {
4911 struct bound_minimal_symbol sym;
4912
4913 tmp = &reply[8];
4914 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4915 msg[end] = '\0';
4916 sym = lookup_minimal_symbol (msg, NULL, NULL);
4917 if (sym.minsym == NULL)
4918 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4919 else
4920 {
4921 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4922 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4923
4924 /* If this is a function address, return the start of code
4925 instead of any data function descriptor. */
4926 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4927 sym_addr,
4928 current_top_target ());
4929
4930 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4931 phex_nz (sym_addr, addr_size), &reply[8]);
4932 }
4933
4934 putpkt (msg);
4935 getpkt (&reply, &reply_size, 0);
4936 }
4937
4938 do_cleanups (old_chain);
4939 }
4940
4941 static struct serial *
4942 remote_serial_open (const char *name)
4943 {
4944 static int udp_warning = 0;
4945
4946 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4947 of in ser-tcp.c, because it is the remote protocol assuming that the
4948 serial connection is reliable and not the serial connection promising
4949 to be. */
4950 if (!udp_warning && startswith (name, "udp:"))
4951 {
4952 warning (_("The remote protocol may be unreliable over UDP.\n"
4953 "Some events may be lost, rendering further debugging "
4954 "impossible."));
4955 udp_warning = 1;
4956 }
4957
4958 return serial_open (name);
4959 }
4960
4961 /* Inform the target of our permission settings. The permission flags
4962 work without this, but if the target knows the settings, it can do
4963 a couple things. First, it can add its own check, to catch cases
4964 that somehow manage to get by the permissions checks in target
4965 methods. Second, if the target is wired to disallow particular
4966 settings (for instance, a system in the field that is not set up to
4967 be able to stop at a breakpoint), it can object to any unavailable
4968 permissions. */
4969
4970 void
4971 remote_target::set_permissions ()
4972 {
4973 struct remote_state *rs = get_remote_state ();
4974
4975 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4976 "WriteReg:%x;WriteMem:%x;"
4977 "InsertBreak:%x;InsertTrace:%x;"
4978 "InsertFastTrace:%x;Stop:%x",
4979 may_write_registers, may_write_memory,
4980 may_insert_breakpoints, may_insert_tracepoints,
4981 may_insert_fast_tracepoints, may_stop);
4982 putpkt (rs->buf);
4983 getpkt (&rs->buf, &rs->buf_size, 0);
4984
4985 /* If the target didn't like the packet, warn the user. Do not try
4986 to undo the user's settings, that would just be maddening. */
4987 if (strcmp (rs->buf, "OK") != 0)
4988 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4989 }
4990
4991 /* This type describes each known response to the qSupported
4992 packet. */
4993 struct protocol_feature
4994 {
4995 /* The name of this protocol feature. */
4996 const char *name;
4997
4998 /* The default for this protocol feature. */
4999 enum packet_support default_support;
5000
5001 /* The function to call when this feature is reported, or after
5002 qSupported processing if the feature is not supported.
5003 The first argument points to this structure. The second
5004 argument indicates whether the packet requested support be
5005 enabled, disabled, or probed (or the default, if this function
5006 is being called at the end of processing and this feature was
5007 not reported). The third argument may be NULL; if not NULL, it
5008 is a NUL-terminated string taken from the packet following
5009 this feature's name and an equals sign. */
5010 void (*func) (remote_target *remote, const struct protocol_feature *,
5011 enum packet_support, const char *);
5012
5013 /* The corresponding packet for this feature. Only used if
5014 FUNC is remote_supported_packet. */
5015 int packet;
5016 };
5017
5018 static void
5019 remote_supported_packet (remote_target *remote,
5020 const struct protocol_feature *feature,
5021 enum packet_support support,
5022 const char *argument)
5023 {
5024 if (argument)
5025 {
5026 warning (_("Remote qSupported response supplied an unexpected value for"
5027 " \"%s\"."), feature->name);
5028 return;
5029 }
5030
5031 remote_protocol_packets[feature->packet].support = support;
5032 }
5033
5034 void
5035 remote_target::remote_packet_size (const protocol_feature *feature,
5036 enum packet_support support, const char *value)
5037 {
5038 struct remote_state *rs = get_remote_state ();
5039
5040 int packet_size;
5041 char *value_end;
5042
5043 if (support != PACKET_ENABLE)
5044 return;
5045
5046 if (value == NULL || *value == '\0')
5047 {
5048 warning (_("Remote target reported \"%s\" without a size."),
5049 feature->name);
5050 return;
5051 }
5052
5053 errno = 0;
5054 packet_size = strtol (value, &value_end, 16);
5055 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5056 {
5057 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5058 feature->name, value);
5059 return;
5060 }
5061
5062 /* Record the new maximum packet size. */
5063 rs->explicit_packet_size = packet_size;
5064 }
5065
5066 void
5067 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5068 enum packet_support support, const char *value)
5069 {
5070 remote->remote_packet_size (feature, support, value);
5071 }
5072
5073 static const struct protocol_feature remote_protocol_features[] = {
5074 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5075 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5076 PACKET_qXfer_auxv },
5077 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5078 PACKET_qXfer_exec_file },
5079 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5080 PACKET_qXfer_features },
5081 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5082 PACKET_qXfer_libraries },
5083 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5084 PACKET_qXfer_libraries_svr4 },
5085 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5086 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5087 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5088 PACKET_qXfer_memory_map },
5089 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5090 PACKET_qXfer_spu_read },
5091 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5092 PACKET_qXfer_spu_write },
5093 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5094 PACKET_qXfer_osdata },
5095 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5096 PACKET_qXfer_threads },
5097 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5098 PACKET_qXfer_traceframe_info },
5099 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5100 PACKET_QPassSignals },
5101 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5102 PACKET_QCatchSyscalls },
5103 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5104 PACKET_QProgramSignals },
5105 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5106 PACKET_QSetWorkingDir },
5107 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5108 PACKET_QStartupWithShell },
5109 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5110 PACKET_QEnvironmentHexEncoded },
5111 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5112 PACKET_QEnvironmentReset },
5113 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5114 PACKET_QEnvironmentUnset },
5115 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5116 PACKET_QStartNoAckMode },
5117 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5118 PACKET_multiprocess_feature },
5119 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5120 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5121 PACKET_qXfer_siginfo_read },
5122 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5123 PACKET_qXfer_siginfo_write },
5124 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5125 PACKET_ConditionalTracepoints },
5126 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5127 PACKET_ConditionalBreakpoints },
5128 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5129 PACKET_BreakpointCommands },
5130 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5131 PACKET_FastTracepoints },
5132 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5133 PACKET_StaticTracepoints },
5134 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5135 PACKET_InstallInTrace},
5136 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5137 PACKET_DisconnectedTracing_feature },
5138 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5139 PACKET_bc },
5140 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5141 PACKET_bs },
5142 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5143 PACKET_TracepointSource },
5144 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5145 PACKET_QAllow },
5146 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5147 PACKET_EnableDisableTracepoints_feature },
5148 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5149 PACKET_qXfer_fdpic },
5150 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5151 PACKET_qXfer_uib },
5152 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5153 PACKET_QDisableRandomization },
5154 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5155 { "QTBuffer:size", PACKET_DISABLE,
5156 remote_supported_packet, PACKET_QTBuffer_size},
5157 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5158 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5159 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5160 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5161 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5162 PACKET_qXfer_btrace },
5163 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5164 PACKET_qXfer_btrace_conf },
5165 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5166 PACKET_Qbtrace_conf_bts_size },
5167 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5168 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5169 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5170 PACKET_fork_event_feature },
5171 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5172 PACKET_vfork_event_feature },
5173 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5174 PACKET_exec_event_feature },
5175 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5176 PACKET_Qbtrace_conf_pt_size },
5177 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5178 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5179 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5180 };
5181
5182 static char *remote_support_xml;
5183
5184 /* Register string appended to "xmlRegisters=" in qSupported query. */
5185
5186 void
5187 register_remote_support_xml (const char *xml)
5188 {
5189 #if defined(HAVE_LIBEXPAT)
5190 if (remote_support_xml == NULL)
5191 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5192 else
5193 {
5194 char *copy = xstrdup (remote_support_xml + 13);
5195 char *p = strtok (copy, ",");
5196
5197 do
5198 {
5199 if (strcmp (p, xml) == 0)
5200 {
5201 /* already there */
5202 xfree (copy);
5203 return;
5204 }
5205 }
5206 while ((p = strtok (NULL, ",")) != NULL);
5207 xfree (copy);
5208
5209 remote_support_xml = reconcat (remote_support_xml,
5210 remote_support_xml, ",", xml,
5211 (char *) NULL);
5212 }
5213 #endif
5214 }
5215
5216 static void
5217 remote_query_supported_append (std::string *msg, const char *append)
5218 {
5219 if (!msg->empty ())
5220 msg->append (";");
5221 msg->append (append);
5222 }
5223
5224 void
5225 remote_target::remote_query_supported ()
5226 {
5227 struct remote_state *rs = get_remote_state ();
5228 char *next;
5229 int i;
5230 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5231
5232 /* The packet support flags are handled differently for this packet
5233 than for most others. We treat an error, a disabled packet, and
5234 an empty response identically: any features which must be reported
5235 to be used will be automatically disabled. An empty buffer
5236 accomplishes this, since that is also the representation for a list
5237 containing no features. */
5238
5239 rs->buf[0] = 0;
5240 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5241 {
5242 std::string q;
5243
5244 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5245 remote_query_supported_append (&q, "multiprocess+");
5246
5247 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5248 remote_query_supported_append (&q, "swbreak+");
5249 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5250 remote_query_supported_append (&q, "hwbreak+");
5251
5252 remote_query_supported_append (&q, "qRelocInsn+");
5253
5254 if (packet_set_cmd_state (PACKET_fork_event_feature)
5255 != AUTO_BOOLEAN_FALSE)
5256 remote_query_supported_append (&q, "fork-events+");
5257 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5258 != AUTO_BOOLEAN_FALSE)
5259 remote_query_supported_append (&q, "vfork-events+");
5260 if (packet_set_cmd_state (PACKET_exec_event_feature)
5261 != AUTO_BOOLEAN_FALSE)
5262 remote_query_supported_append (&q, "exec-events+");
5263
5264 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5265 remote_query_supported_append (&q, "vContSupported+");
5266
5267 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5268 remote_query_supported_append (&q, "QThreadEvents+");
5269
5270 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5271 remote_query_supported_append (&q, "no-resumed+");
5272
5273 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5274 the qSupported:xmlRegisters=i386 handling. */
5275 if (remote_support_xml != NULL
5276 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5277 remote_query_supported_append (&q, remote_support_xml);
5278
5279 q = "qSupported:" + q;
5280 putpkt (q.c_str ());
5281
5282 getpkt (&rs->buf, &rs->buf_size, 0);
5283
5284 /* If an error occured, warn, but do not return - just reset the
5285 buffer to empty and go on to disable features. */
5286 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5287 == PACKET_ERROR)
5288 {
5289 warning (_("Remote failure reply: %s"), rs->buf);
5290 rs->buf[0] = 0;
5291 }
5292 }
5293
5294 memset (seen, 0, sizeof (seen));
5295
5296 next = rs->buf;
5297 while (*next)
5298 {
5299 enum packet_support is_supported;
5300 char *p, *end, *name_end, *value;
5301
5302 /* First separate out this item from the rest of the packet. If
5303 there's another item after this, we overwrite the separator
5304 (terminated strings are much easier to work with). */
5305 p = next;
5306 end = strchr (p, ';');
5307 if (end == NULL)
5308 {
5309 end = p + strlen (p);
5310 next = end;
5311 }
5312 else
5313 {
5314 *end = '\0';
5315 next = end + 1;
5316
5317 if (end == p)
5318 {
5319 warning (_("empty item in \"qSupported\" response"));
5320 continue;
5321 }
5322 }
5323
5324 name_end = strchr (p, '=');
5325 if (name_end)
5326 {
5327 /* This is a name=value entry. */
5328 is_supported = PACKET_ENABLE;
5329 value = name_end + 1;
5330 *name_end = '\0';
5331 }
5332 else
5333 {
5334 value = NULL;
5335 switch (end[-1])
5336 {
5337 case '+':
5338 is_supported = PACKET_ENABLE;
5339 break;
5340
5341 case '-':
5342 is_supported = PACKET_DISABLE;
5343 break;
5344
5345 case '?':
5346 is_supported = PACKET_SUPPORT_UNKNOWN;
5347 break;
5348
5349 default:
5350 warning (_("unrecognized item \"%s\" "
5351 "in \"qSupported\" response"), p);
5352 continue;
5353 }
5354 end[-1] = '\0';
5355 }
5356
5357 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5358 if (strcmp (remote_protocol_features[i].name, p) == 0)
5359 {
5360 const struct protocol_feature *feature;
5361
5362 seen[i] = 1;
5363 feature = &remote_protocol_features[i];
5364 feature->func (this, feature, is_supported, value);
5365 break;
5366 }
5367 }
5368
5369 /* If we increased the packet size, make sure to increase the global
5370 buffer size also. We delay this until after parsing the entire
5371 qSupported packet, because this is the same buffer we were
5372 parsing. */
5373 if (rs->buf_size < rs->explicit_packet_size)
5374 {
5375 rs->buf_size = rs->explicit_packet_size;
5376 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5377 }
5378
5379 /* Handle the defaults for unmentioned features. */
5380 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5381 if (!seen[i])
5382 {
5383 const struct protocol_feature *feature;
5384
5385 feature = &remote_protocol_features[i];
5386 feature->func (this, feature, feature->default_support, NULL);
5387 }
5388 }
5389
5390 /* Serial QUIT handler for the remote serial descriptor.
5391
5392 Defers handling a Ctrl-C until we're done with the current
5393 command/response packet sequence, unless:
5394
5395 - We're setting up the connection. Don't send a remote interrupt
5396 request, as we're not fully synced yet. Quit immediately
5397 instead.
5398
5399 - The target has been resumed in the foreground
5400 (target_terminal::is_ours is false) with a synchronous resume
5401 packet, and we're blocked waiting for the stop reply, thus a
5402 Ctrl-C should be immediately sent to the target.
5403
5404 - We get a second Ctrl-C while still within the same serial read or
5405 write. In that case the serial is seemingly wedged --- offer to
5406 quit/disconnect.
5407
5408 - We see a second Ctrl-C without target response, after having
5409 previously interrupted the target. In that case the target/stub
5410 is probably wedged --- offer to quit/disconnect.
5411 */
5412
5413 void
5414 remote_target::remote_serial_quit_handler ()
5415 {
5416 struct remote_state *rs = get_remote_state ();
5417
5418 if (check_quit_flag ())
5419 {
5420 /* If we're starting up, we're not fully synced yet. Quit
5421 immediately. */
5422 if (rs->starting_up)
5423 quit ();
5424 else if (rs->got_ctrlc_during_io)
5425 {
5426 if (query (_("The target is not responding to GDB commands.\n"
5427 "Stop debugging it? ")))
5428 remote_unpush_and_throw ();
5429 }
5430 /* If ^C has already been sent once, offer to disconnect. */
5431 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5432 interrupt_query ();
5433 /* All-stop protocol, and blocked waiting for stop reply. Send
5434 an interrupt request. */
5435 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5436 target_interrupt ();
5437 else
5438 rs->got_ctrlc_during_io = 1;
5439 }
5440 }
5441
5442 /* The remote_target that is current while the quit handler is
5443 overridden with remote_serial_quit_handler. */
5444 static remote_target *curr_quit_handler_target;
5445
5446 static void
5447 remote_serial_quit_handler ()
5448 {
5449 curr_quit_handler_target->remote_serial_quit_handler ();
5450 }
5451
5452 /* Remove any of the remote.c targets from target stack. Upper targets depend
5453 on it so remove them first. */
5454
5455 static void
5456 remote_unpush_target (void)
5457 {
5458 pop_all_targets_at_and_above (process_stratum);
5459 }
5460
5461 static void
5462 remote_unpush_and_throw (void)
5463 {
5464 remote_unpush_target ();
5465 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5466 }
5467
5468 void
5469 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5470 {
5471 remote_target *curr_remote = get_current_remote_target ();
5472
5473 if (name == 0)
5474 error (_("To open a remote debug connection, you need to specify what\n"
5475 "serial device is attached to the remote system\n"
5476 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5477
5478 /* If we're connected to a running target, target_preopen will kill it.
5479 Ask this question first, before target_preopen has a chance to kill
5480 anything. */
5481 if (curr_remote != NULL && !have_inferiors ())
5482 {
5483 if (from_tty
5484 && !query (_("Already connected to a remote target. Disconnect? ")))
5485 error (_("Still connected."));
5486 }
5487
5488 /* Here the possibly existing remote target gets unpushed. */
5489 target_preopen (from_tty);
5490
5491 remote_fileio_reset ();
5492 reopen_exec_file ();
5493 reread_symbols ();
5494
5495 remote_target *remote
5496 = (extended_p ? new extended_remote_target () : new remote_target ());
5497 target_ops_up target_holder (remote);
5498
5499 remote_state *rs = remote->get_remote_state ();
5500
5501 /* See FIXME above. */
5502 if (!target_async_permitted)
5503 rs->wait_forever_enabled_p = 1;
5504
5505 rs->remote_desc = remote_serial_open (name);
5506 if (!rs->remote_desc)
5507 perror_with_name (name);
5508
5509 if (baud_rate != -1)
5510 {
5511 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5512 {
5513 /* The requested speed could not be set. Error out to
5514 top level after closing remote_desc. Take care to
5515 set remote_desc to NULL to avoid closing remote_desc
5516 more than once. */
5517 serial_close (rs->remote_desc);
5518 rs->remote_desc = NULL;
5519 perror_with_name (name);
5520 }
5521 }
5522
5523 serial_setparity (rs->remote_desc, serial_parity);
5524 serial_raw (rs->remote_desc);
5525
5526 /* If there is something sitting in the buffer we might take it as a
5527 response to a command, which would be bad. */
5528 serial_flush_input (rs->remote_desc);
5529
5530 if (from_tty)
5531 {
5532 puts_filtered ("Remote debugging using ");
5533 puts_filtered (name);
5534 puts_filtered ("\n");
5535 }
5536
5537 /* Switch to using the remote target now. */
5538 push_target (remote);
5539 /* The target stack owns the target now. */
5540 target_holder.release ();
5541
5542 /* Register extra event sources in the event loop. */
5543 rs->remote_async_inferior_event_token
5544 = create_async_event_handler (remote_async_inferior_event_handler,
5545 remote);
5546 rs->notif_state = remote_notif_state_allocate (remote);
5547
5548 /* Reset the target state; these things will be queried either by
5549 remote_query_supported or as they are needed. */
5550 reset_all_packet_configs_support ();
5551 rs->cached_wait_status = 0;
5552 rs->explicit_packet_size = 0;
5553 rs->noack_mode = 0;
5554 rs->extended = extended_p;
5555 rs->waiting_for_stop_reply = 0;
5556 rs->ctrlc_pending_p = 0;
5557 rs->got_ctrlc_during_io = 0;
5558
5559 rs->general_thread = not_sent_ptid;
5560 rs->continue_thread = not_sent_ptid;
5561 rs->remote_traceframe_number = -1;
5562
5563 rs->last_resume_exec_dir = EXEC_FORWARD;
5564
5565 /* Probe for ability to use "ThreadInfo" query, as required. */
5566 rs->use_threadinfo_query = 1;
5567 rs->use_threadextra_query = 1;
5568
5569 rs->readahead_cache.invalidate ();
5570
5571 if (target_async_permitted)
5572 {
5573 /* FIXME: cagney/1999-09-23: During the initial connection it is
5574 assumed that the target is already ready and able to respond to
5575 requests. Unfortunately remote_start_remote() eventually calls
5576 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5577 around this. Eventually a mechanism that allows
5578 wait_for_inferior() to expect/get timeouts will be
5579 implemented. */
5580 rs->wait_forever_enabled_p = 0;
5581 }
5582
5583 /* First delete any symbols previously loaded from shared libraries. */
5584 no_shared_libraries (NULL, 0);
5585
5586 /* Start afresh. */
5587 init_thread_list ();
5588
5589 /* Start the remote connection. If error() or QUIT, discard this
5590 target (we'd otherwise be in an inconsistent state) and then
5591 propogate the error on up the exception chain. This ensures that
5592 the caller doesn't stumble along blindly assuming that the
5593 function succeeded. The CLI doesn't have this problem but other
5594 UI's, such as MI do.
5595
5596 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5597 this function should return an error indication letting the
5598 caller restore the previous state. Unfortunately the command
5599 ``target remote'' is directly wired to this function making that
5600 impossible. On a positive note, the CLI side of this problem has
5601 been fixed - the function set_cmd_context() makes it possible for
5602 all the ``target ....'' commands to share a common callback
5603 function. See cli-dump.c. */
5604 {
5605
5606 TRY
5607 {
5608 remote->start_remote (from_tty, extended_p);
5609 }
5610 CATCH (ex, RETURN_MASK_ALL)
5611 {
5612 /* Pop the partially set up target - unless something else did
5613 already before throwing the exception. */
5614 if (ex.error != TARGET_CLOSE_ERROR)
5615 remote_unpush_target ();
5616 throw_exception (ex);
5617 }
5618 END_CATCH
5619 }
5620
5621 remote_btrace_reset (rs);
5622
5623 if (target_async_permitted)
5624 rs->wait_forever_enabled_p = 1;
5625 }
5626
5627 /* Detach the specified process. */
5628
5629 void
5630 remote_target::remote_detach_pid (int pid)
5631 {
5632 struct remote_state *rs = get_remote_state ();
5633
5634 if (remote_multi_process_p (rs))
5635 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5636 else
5637 strcpy (rs->buf, "D");
5638
5639 putpkt (rs->buf);
5640 getpkt (&rs->buf, &rs->buf_size, 0);
5641
5642 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5643 ;
5644 else if (rs->buf[0] == '\0')
5645 error (_("Remote doesn't know how to detach"));
5646 else
5647 error (_("Can't detach process."));
5648 }
5649
5650 /* This detaches a program to which we previously attached, using
5651 inferior_ptid to identify the process. After this is done, GDB
5652 can be used to debug some other program. We better not have left
5653 any breakpoints in the target program or it'll die when it hits
5654 one. */
5655
5656 void
5657 remote_target::remote_detach_1 (int from_tty, inferior *inf)
5658 {
5659 int pid = ptid_get_pid (inferior_ptid);
5660 struct remote_state *rs = get_remote_state ();
5661 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5662 int is_fork_parent;
5663
5664 if (!target_has_execution)
5665 error (_("No process to detach from."));
5666
5667 target_announce_detach (from_tty);
5668
5669 /* Tell the remote target to detach. */
5670 remote_detach_pid (pid);
5671
5672 /* Exit only if this is the only active inferior. */
5673 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5674 puts_filtered (_("Ending remote debugging.\n"));
5675
5676 /* Check to see if we are detaching a fork parent. Note that if we
5677 are detaching a fork child, tp == NULL. */
5678 is_fork_parent = (tp != NULL
5679 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5680
5681 /* If doing detach-on-fork, we don't mourn, because that will delete
5682 breakpoints that should be available for the followed inferior. */
5683 if (!is_fork_parent)
5684 {
5685 /* Save the pid as a string before mourning, since that will
5686 unpush the remote target, and we need the string after. */
5687 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5688
5689 target_mourn_inferior (inferior_ptid);
5690 if (print_inferior_events)
5691 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5692 inf->num, infpid.c_str ());
5693 }
5694 else
5695 {
5696 inferior_ptid = null_ptid;
5697 detach_inferior (pid);
5698 }
5699 }
5700
5701 void
5702 remote_target::detach (inferior *inf, int from_tty)
5703 {
5704 remote_detach_1 (from_tty, inf);
5705 }
5706
5707 void
5708 extended_remote_target::detach (inferior *inf, int from_tty)
5709 {
5710 remote_detach_1 (from_tty, inf);
5711 }
5712
5713 /* Target follow-fork function for remote targets. On entry, and
5714 at return, the current inferior is the fork parent.
5715
5716 Note that although this is currently only used for extended-remote,
5717 it is named remote_follow_fork in anticipation of using it for the
5718 remote target as well. */
5719
5720 int
5721 remote_target::follow_fork (int follow_child, int detach_fork)
5722 {
5723 struct remote_state *rs = get_remote_state ();
5724 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5725
5726 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5727 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5728 {
5729 /* When following the parent and detaching the child, we detach
5730 the child here. For the case of following the child and
5731 detaching the parent, the detach is done in the target-
5732 independent follow fork code in infrun.c. We can't use
5733 target_detach when detaching an unfollowed child because
5734 the client side doesn't know anything about the child. */
5735 if (detach_fork && !follow_child)
5736 {
5737 /* Detach the fork child. */
5738 ptid_t child_ptid;
5739 pid_t child_pid;
5740
5741 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5742 child_pid = ptid_get_pid (child_ptid);
5743
5744 remote_detach_pid (child_pid);
5745 }
5746 }
5747 return 0;
5748 }
5749
5750 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5751 in the program space of the new inferior. On entry and at return the
5752 current inferior is the exec'ing inferior. INF is the new exec'd
5753 inferior, which may be the same as the exec'ing inferior unless
5754 follow-exec-mode is "new". */
5755
5756 void
5757 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5758 {
5759 /* We know that this is a target file name, so if it has the "target:"
5760 prefix we strip it off before saving it in the program space. */
5761 if (is_target_filename (execd_pathname))
5762 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5763
5764 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5765 }
5766
5767 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5768
5769 void
5770 remote_target::disconnect (const char *args, int from_tty)
5771 {
5772 if (args)
5773 error (_("Argument given to \"disconnect\" when remotely debugging."));
5774
5775 /* Make sure we unpush even the extended remote targets. Calling
5776 target_mourn_inferior won't unpush, and remote_mourn won't
5777 unpush if there is more than one inferior left. */
5778 unpush_target (this);
5779 generic_mourn_inferior ();
5780
5781 if (from_tty)
5782 puts_filtered ("Ending remote debugging.\n");
5783 }
5784
5785 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5786 be chatty about it. */
5787
5788 void
5789 extended_remote_target::attach (const char *args, int from_tty)
5790 {
5791 struct remote_state *rs = get_remote_state ();
5792 int pid;
5793 char *wait_status = NULL;
5794
5795 pid = parse_pid_to_attach (args);
5796
5797 /* Remote PID can be freely equal to getpid, do not check it here the same
5798 way as in other targets. */
5799
5800 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5801 error (_("This target does not support attaching to a process"));
5802
5803 if (from_tty)
5804 {
5805 char *exec_file = get_exec_file (0);
5806
5807 if (exec_file)
5808 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5809 target_pid_to_str (pid_to_ptid (pid)));
5810 else
5811 printf_unfiltered (_("Attaching to %s\n"),
5812 target_pid_to_str (pid_to_ptid (pid)));
5813
5814 gdb_flush (gdb_stdout);
5815 }
5816
5817 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5818 putpkt (rs->buf);
5819 getpkt (&rs->buf, &rs->buf_size, 0);
5820
5821 switch (packet_ok (rs->buf,
5822 &remote_protocol_packets[PACKET_vAttach]))
5823 {
5824 case PACKET_OK:
5825 if (!target_is_non_stop_p ())
5826 {
5827 /* Save the reply for later. */
5828 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5829 strcpy (wait_status, rs->buf);
5830 }
5831 else if (strcmp (rs->buf, "OK") != 0)
5832 error (_("Attaching to %s failed with: %s"),
5833 target_pid_to_str (pid_to_ptid (pid)),
5834 rs->buf);
5835 break;
5836 case PACKET_UNKNOWN:
5837 error (_("This target does not support attaching to a process"));
5838 default:
5839 error (_("Attaching to %s failed"),
5840 target_pid_to_str (pid_to_ptid (pid)));
5841 }
5842
5843 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5844
5845 inferior_ptid = pid_to_ptid (pid);
5846
5847 if (target_is_non_stop_p ())
5848 {
5849 struct thread_info *thread;
5850
5851 /* Get list of threads. */
5852 update_thread_list ();
5853
5854 thread = first_thread_of_process (pid);
5855 if (thread)
5856 inferior_ptid = thread->ptid;
5857 else
5858 inferior_ptid = pid_to_ptid (pid);
5859
5860 /* Invalidate our notion of the remote current thread. */
5861 record_currthread (rs, minus_one_ptid);
5862 }
5863 else
5864 {
5865 /* Now, if we have thread information, update inferior_ptid. */
5866 inferior_ptid = remote_current_thread (inferior_ptid);
5867
5868 /* Add the main thread to the thread list. */
5869 thread_info *thr = add_thread_silent (inferior_ptid);
5870 /* Don't consider the thread stopped until we've processed the
5871 saved stop reply. */
5872 set_executing (thr->ptid, true);
5873 }
5874
5875 /* Next, if the target can specify a description, read it. We do
5876 this before anything involving memory or registers. */
5877 target_find_description ();
5878
5879 if (!target_is_non_stop_p ())
5880 {
5881 /* Use the previously fetched status. */
5882 gdb_assert (wait_status != NULL);
5883
5884 if (target_can_async_p ())
5885 {
5886 struct notif_event *reply
5887 = remote_notif_parse (this, &notif_client_stop, wait_status);
5888
5889 push_stop_reply ((struct stop_reply *) reply);
5890
5891 target_async (1);
5892 }
5893 else
5894 {
5895 gdb_assert (wait_status != NULL);
5896 strcpy (rs->buf, wait_status);
5897 rs->cached_wait_status = 1;
5898 }
5899 }
5900 else
5901 gdb_assert (wait_status == NULL);
5902 }
5903
5904 /* Implementation of the to_post_attach method. */
5905
5906 void
5907 extended_remote_target::post_attach (int pid)
5908 {
5909 /* Get text, data & bss offsets. */
5910 get_offsets ();
5911
5912 /* In certain cases GDB might not have had the chance to start
5913 symbol lookup up until now. This could happen if the debugged
5914 binary is not using shared libraries, the vsyscall page is not
5915 present (on Linux) and the binary itself hadn't changed since the
5916 debugging process was started. */
5917 if (symfile_objfile != NULL)
5918 remote_check_symbols();
5919 }
5920
5921 \f
5922 /* Check for the availability of vCont. This function should also check
5923 the response. */
5924
5925 void
5926 remote_target::remote_vcont_probe ()
5927 {
5928 remote_state *rs = get_remote_state ();
5929 char *buf;
5930
5931 strcpy (rs->buf, "vCont?");
5932 putpkt (rs->buf);
5933 getpkt (&rs->buf, &rs->buf_size, 0);
5934 buf = rs->buf;
5935
5936 /* Make sure that the features we assume are supported. */
5937 if (startswith (buf, "vCont"))
5938 {
5939 char *p = &buf[5];
5940 int support_c, support_C;
5941
5942 rs->supports_vCont.s = 0;
5943 rs->supports_vCont.S = 0;
5944 support_c = 0;
5945 support_C = 0;
5946 rs->supports_vCont.t = 0;
5947 rs->supports_vCont.r = 0;
5948 while (p && *p == ';')
5949 {
5950 p++;
5951 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5952 rs->supports_vCont.s = 1;
5953 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5954 rs->supports_vCont.S = 1;
5955 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5956 support_c = 1;
5957 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5958 support_C = 1;
5959 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5960 rs->supports_vCont.t = 1;
5961 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5962 rs->supports_vCont.r = 1;
5963
5964 p = strchr (p, ';');
5965 }
5966
5967 /* If c, and C are not all supported, we can't use vCont. Clearing
5968 BUF will make packet_ok disable the packet. */
5969 if (!support_c || !support_C)
5970 buf[0] = 0;
5971 }
5972
5973 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5974 }
5975
5976 /* Helper function for building "vCont" resumptions. Write a
5977 resumption to P. ENDP points to one-passed-the-end of the buffer
5978 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5979 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5980 resumed thread should be single-stepped and/or signalled. If PTID
5981 equals minus_one_ptid, then all threads are resumed; if PTID
5982 represents a process, then all threads of the process are resumed;
5983 the thread to be stepped and/or signalled is given in the global
5984 INFERIOR_PTID. */
5985
5986 char *
5987 remote_target::append_resumption (char *p, char *endp,
5988 ptid_t ptid, int step, gdb_signal siggnal)
5989 {
5990 struct remote_state *rs = get_remote_state ();
5991
5992 if (step && siggnal != GDB_SIGNAL_0)
5993 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5994 else if (step
5995 /* GDB is willing to range step. */
5996 && use_range_stepping
5997 /* Target supports range stepping. */
5998 && rs->supports_vCont.r
5999 /* We don't currently support range stepping multiple
6000 threads with a wildcard (though the protocol allows it,
6001 so stubs shouldn't make an active effort to forbid
6002 it). */
6003 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6004 {
6005 struct thread_info *tp;
6006
6007 if (ptid_equal (ptid, minus_one_ptid))
6008 {
6009 /* If we don't know about the target thread's tid, then
6010 we're resuming magic_null_ptid (see caller). */
6011 tp = find_thread_ptid (magic_null_ptid);
6012 }
6013 else
6014 tp = find_thread_ptid (ptid);
6015 gdb_assert (tp != NULL);
6016
6017 if (tp->control.may_range_step)
6018 {
6019 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6020
6021 p += xsnprintf (p, endp - p, ";r%s,%s",
6022 phex_nz (tp->control.step_range_start,
6023 addr_size),
6024 phex_nz (tp->control.step_range_end,
6025 addr_size));
6026 }
6027 else
6028 p += xsnprintf (p, endp - p, ";s");
6029 }
6030 else if (step)
6031 p += xsnprintf (p, endp - p, ";s");
6032 else if (siggnal != GDB_SIGNAL_0)
6033 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6034 else
6035 p += xsnprintf (p, endp - p, ";c");
6036
6037 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
6038 {
6039 ptid_t nptid;
6040
6041 /* All (-1) threads of process. */
6042 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6043
6044 p += xsnprintf (p, endp - p, ":");
6045 p = write_ptid (p, endp, nptid);
6046 }
6047 else if (!ptid_equal (ptid, minus_one_ptid))
6048 {
6049 p += xsnprintf (p, endp - p, ":");
6050 p = write_ptid (p, endp, ptid);
6051 }
6052
6053 return p;
6054 }
6055
6056 /* Clear the thread's private info on resume. */
6057
6058 static void
6059 resume_clear_thread_private_info (struct thread_info *thread)
6060 {
6061 if (thread->priv != NULL)
6062 {
6063 remote_thread_info *priv = get_remote_thread_info (thread);
6064
6065 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6066 priv->watch_data_address = 0;
6067 }
6068 }
6069
6070 /* Append a vCont continue-with-signal action for threads that have a
6071 non-zero stop signal. */
6072
6073 char *
6074 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6075 ptid_t ptid)
6076 {
6077 struct thread_info *thread;
6078
6079 ALL_NON_EXITED_THREADS (thread)
6080 if (ptid_match (thread->ptid, ptid)
6081 && !ptid_equal (inferior_ptid, thread->ptid)
6082 && thread->suspend.stop_signal != GDB_SIGNAL_0)
6083 {
6084 p = append_resumption (p, endp, thread->ptid,
6085 0, thread->suspend.stop_signal);
6086 thread->suspend.stop_signal = GDB_SIGNAL_0;
6087 resume_clear_thread_private_info (thread);
6088 }
6089
6090 return p;
6091 }
6092
6093 /* Set the target running, using the packets that use Hc
6094 (c/s/C/S). */
6095
6096 void
6097 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6098 gdb_signal siggnal)
6099 {
6100 struct remote_state *rs = get_remote_state ();
6101 struct thread_info *thread;
6102 char *buf;
6103
6104 rs->last_sent_signal = siggnal;
6105 rs->last_sent_step = step;
6106
6107 /* The c/s/C/S resume packets use Hc, so set the continue
6108 thread. */
6109 if (ptid_equal (ptid, minus_one_ptid))
6110 set_continue_thread (any_thread_ptid);
6111 else
6112 set_continue_thread (ptid);
6113
6114 ALL_NON_EXITED_THREADS (thread)
6115 resume_clear_thread_private_info (thread);
6116
6117 buf = rs->buf;
6118 if (::execution_direction == EXEC_REVERSE)
6119 {
6120 /* We don't pass signals to the target in reverse exec mode. */
6121 if (info_verbose && siggnal != GDB_SIGNAL_0)
6122 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6123 siggnal);
6124
6125 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6126 error (_("Remote reverse-step not supported."));
6127 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6128 error (_("Remote reverse-continue not supported."));
6129
6130 strcpy (buf, step ? "bs" : "bc");
6131 }
6132 else if (siggnal != GDB_SIGNAL_0)
6133 {
6134 buf[0] = step ? 'S' : 'C';
6135 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6136 buf[2] = tohex (((int) siggnal) & 0xf);
6137 buf[3] = '\0';
6138 }
6139 else
6140 strcpy (buf, step ? "s" : "c");
6141
6142 putpkt (buf);
6143 }
6144
6145 /* Resume the remote inferior by using a "vCont" packet. The thread
6146 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6147 resumed thread should be single-stepped and/or signalled. If PTID
6148 equals minus_one_ptid, then all threads are resumed; the thread to
6149 be stepped and/or signalled is given in the global INFERIOR_PTID.
6150 This function returns non-zero iff it resumes the inferior.
6151
6152 This function issues a strict subset of all possible vCont commands
6153 at the moment. */
6154
6155 int
6156 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6157 enum gdb_signal siggnal)
6158 {
6159 struct remote_state *rs = get_remote_state ();
6160 char *p;
6161 char *endp;
6162
6163 /* No reverse execution actions defined for vCont. */
6164 if (::execution_direction == EXEC_REVERSE)
6165 return 0;
6166
6167 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6168 remote_vcont_probe ();
6169
6170 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6171 return 0;
6172
6173 p = rs->buf;
6174 endp = rs->buf + get_remote_packet_size ();
6175
6176 /* If we could generate a wider range of packets, we'd have to worry
6177 about overflowing BUF. Should there be a generic
6178 "multi-part-packet" packet? */
6179
6180 p += xsnprintf (p, endp - p, "vCont");
6181
6182 if (ptid_equal (ptid, magic_null_ptid))
6183 {
6184 /* MAGIC_NULL_PTID means that we don't have any active threads,
6185 so we don't have any TID numbers the inferior will
6186 understand. Make sure to only send forms that do not specify
6187 a TID. */
6188 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6189 }
6190 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
6191 {
6192 /* Resume all threads (of all processes, or of a single
6193 process), with preference for INFERIOR_PTID. This assumes
6194 inferior_ptid belongs to the set of all threads we are about
6195 to resume. */
6196 if (step || siggnal != GDB_SIGNAL_0)
6197 {
6198 /* Step inferior_ptid, with or without signal. */
6199 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6200 }
6201
6202 /* Also pass down any pending signaled resumption for other
6203 threads not the current. */
6204 p = append_pending_thread_resumptions (p, endp, ptid);
6205
6206 /* And continue others without a signal. */
6207 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6208 }
6209 else
6210 {
6211 /* Scheduler locking; resume only PTID. */
6212 append_resumption (p, endp, ptid, step, siggnal);
6213 }
6214
6215 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6216 putpkt (rs->buf);
6217
6218 if (target_is_non_stop_p ())
6219 {
6220 /* In non-stop, the stub replies to vCont with "OK". The stop
6221 reply will be reported asynchronously by means of a `%Stop'
6222 notification. */
6223 getpkt (&rs->buf, &rs->buf_size, 0);
6224 if (strcmp (rs->buf, "OK") != 0)
6225 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6226 }
6227
6228 return 1;
6229 }
6230
6231 /* Tell the remote machine to resume. */
6232
6233 void
6234 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6235 {
6236 struct remote_state *rs = get_remote_state ();
6237
6238 /* When connected in non-stop mode, the core resumes threads
6239 individually. Resuming remote threads directly in target_resume
6240 would thus result in sending one packet per thread. Instead, to
6241 minimize roundtrip latency, here we just store the resume
6242 request; the actual remote resumption will be done in
6243 target_commit_resume / remote_commit_resume, where we'll be able
6244 to do vCont action coalescing. */
6245 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6246 {
6247 remote_thread_info *remote_thr;
6248
6249 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
6250 remote_thr = get_remote_thread_info (inferior_ptid);
6251 else
6252 remote_thr = get_remote_thread_info (ptid);
6253
6254 remote_thr->last_resume_step = step;
6255 remote_thr->last_resume_sig = siggnal;
6256 return;
6257 }
6258
6259 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6260 (explained in remote-notif.c:handle_notification) so
6261 remote_notif_process is not called. We need find a place where
6262 it is safe to start a 'vNotif' sequence. It is good to do it
6263 before resuming inferior, because inferior was stopped and no RSP
6264 traffic at that moment. */
6265 if (!target_is_non_stop_p ())
6266 remote_notif_process (rs->notif_state, &notif_client_stop);
6267
6268 rs->last_resume_exec_dir = ::execution_direction;
6269
6270 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6271 if (!remote_resume_with_vcont (ptid, step, siggnal))
6272 remote_resume_with_hc (ptid, step, siggnal);
6273
6274 /* We are about to start executing the inferior, let's register it
6275 with the event loop. NOTE: this is the one place where all the
6276 execution commands end up. We could alternatively do this in each
6277 of the execution commands in infcmd.c. */
6278 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6279 into infcmd.c in order to allow inferior function calls to work
6280 NOT asynchronously. */
6281 if (target_can_async_p ())
6282 target_async (1);
6283
6284 /* We've just told the target to resume. The remote server will
6285 wait for the inferior to stop, and then send a stop reply. In
6286 the mean time, we can't start another command/query ourselves
6287 because the stub wouldn't be ready to process it. This applies
6288 only to the base all-stop protocol, however. In non-stop (which
6289 only supports vCont), the stub replies with an "OK", and is
6290 immediate able to process further serial input. */
6291 if (!target_is_non_stop_p ())
6292 rs->waiting_for_stop_reply = 1;
6293 }
6294
6295 static int is_pending_fork_parent_thread (struct thread_info *thread);
6296
6297 /* Private per-inferior info for target remote processes. */
6298
6299 struct remote_inferior : public private_inferior
6300 {
6301 /* Whether we can send a wildcard vCont for this process. */
6302 bool may_wildcard_vcont = true;
6303 };
6304
6305 /* Get the remote private inferior data associated to INF. */
6306
6307 static remote_inferior *
6308 get_remote_inferior (inferior *inf)
6309 {
6310 if (inf->priv == NULL)
6311 inf->priv.reset (new remote_inferior);
6312
6313 return static_cast<remote_inferior *> (inf->priv.get ());
6314 }
6315
6316 /* Class used to track the construction of a vCont packet in the
6317 outgoing packet buffer. This is used to send multiple vCont
6318 packets if we have more actions than would fit a single packet. */
6319
6320 class vcont_builder
6321 {
6322 public:
6323 explicit vcont_builder (remote_target *remote)
6324 : m_remote (remote)
6325 {
6326 restart ();
6327 }
6328
6329 void flush ();
6330 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6331
6332 private:
6333 void restart ();
6334
6335 /* The remote target. */
6336 remote_target *m_remote;
6337
6338 /* Pointer to the first action. P points here if no action has been
6339 appended yet. */
6340 char *m_first_action;
6341
6342 /* Where the next action will be appended. */
6343 char *m_p;
6344
6345 /* The end of the buffer. Must never write past this. */
6346 char *m_endp;
6347 };
6348
6349 /* Prepare the outgoing buffer for a new vCont packet. */
6350
6351 void
6352 vcont_builder::restart ()
6353 {
6354 struct remote_state *rs = m_remote->get_remote_state ();
6355
6356 m_p = rs->buf;
6357 m_endp = rs->buf + m_remote->get_remote_packet_size ();
6358 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6359 m_first_action = m_p;
6360 }
6361
6362 /* If the vCont packet being built has any action, send it to the
6363 remote end. */
6364
6365 void
6366 vcont_builder::flush ()
6367 {
6368 struct remote_state *rs;
6369
6370 if (m_p == m_first_action)
6371 return;
6372
6373 rs = m_remote->get_remote_state ();
6374 m_remote->putpkt (rs->buf);
6375 m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
6376 if (strcmp (rs->buf, "OK") != 0)
6377 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6378 }
6379
6380 /* The largest action is range-stepping, with its two addresses. This
6381 is more than sufficient. If a new, bigger action is created, it'll
6382 quickly trigger a failed assertion in append_resumption (and we'll
6383 just bump this). */
6384 #define MAX_ACTION_SIZE 200
6385
6386 /* Append a new vCont action in the outgoing packet being built. If
6387 the action doesn't fit the packet along with previous actions, push
6388 what we've got so far to the remote end and start over a new vCont
6389 packet (with the new action). */
6390
6391 void
6392 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6393 {
6394 char buf[MAX_ACTION_SIZE + 1];
6395
6396 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6397 ptid, step, siggnal);
6398
6399 /* Check whether this new action would fit in the vCont packet along
6400 with previous actions. If not, send what we've got so far and
6401 start a new vCont packet. */
6402 size_t rsize = endp - buf;
6403 if (rsize > m_endp - m_p)
6404 {
6405 flush ();
6406 restart ();
6407
6408 /* Should now fit. */
6409 gdb_assert (rsize <= m_endp - m_p);
6410 }
6411
6412 memcpy (m_p, buf, rsize);
6413 m_p += rsize;
6414 *m_p = '\0';
6415 }
6416
6417 /* to_commit_resume implementation. */
6418
6419 void
6420 remote_target::commit_resume ()
6421 {
6422 struct inferior *inf;
6423 struct thread_info *tp;
6424 int any_process_wildcard;
6425 int may_global_wildcard_vcont;
6426
6427 /* If connected in all-stop mode, we'd send the remote resume
6428 request directly from remote_resume. Likewise if
6429 reverse-debugging, as there are no defined vCont actions for
6430 reverse execution. */
6431 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6432 return;
6433
6434 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6435 instead of resuming all threads of each process individually.
6436 However, if any thread of a process must remain halted, we can't
6437 send wildcard resumes and must send one action per thread.
6438
6439 Care must be taken to not resume threads/processes the server
6440 side already told us are stopped, but the core doesn't know about
6441 yet, because the events are still in the vStopped notification
6442 queue. For example:
6443
6444 #1 => vCont s:p1.1;c
6445 #2 <= OK
6446 #3 <= %Stopped T05 p1.1
6447 #4 => vStopped
6448 #5 <= T05 p1.2
6449 #6 => vStopped
6450 #7 <= OK
6451 #8 (infrun handles the stop for p1.1 and continues stepping)
6452 #9 => vCont s:p1.1;c
6453
6454 The last vCont above would resume thread p1.2 by mistake, because
6455 the server has no idea that the event for p1.2 had not been
6456 handled yet.
6457
6458 The server side must similarly ignore resume actions for the
6459 thread that has a pending %Stopped notification (and any other
6460 threads with events pending), until GDB acks the notification
6461 with vStopped. Otherwise, e.g., the following case is
6462 mishandled:
6463
6464 #1 => g (or any other packet)
6465 #2 <= [registers]
6466 #3 <= %Stopped T05 p1.2
6467 #4 => vCont s:p1.1;c
6468 #5 <= OK
6469
6470 Above, the server must not resume thread p1.2. GDB can't know
6471 that p1.2 stopped until it acks the %Stopped notification, and
6472 since from GDB's perspective all threads should be running, it
6473 sends a "c" action.
6474
6475 Finally, special care must also be given to handling fork/vfork
6476 events. A (v)fork event actually tells us that two processes
6477 stopped -- the parent and the child. Until we follow the fork,
6478 we must not resume the child. Therefore, if we have a pending
6479 fork follow, we must not send a global wildcard resume action
6480 (vCont;c). We can still send process-wide wildcards though. */
6481
6482 /* Start by assuming a global wildcard (vCont;c) is possible. */
6483 may_global_wildcard_vcont = 1;
6484
6485 /* And assume every process is individually wildcard-able too. */
6486 ALL_NON_EXITED_INFERIORS (inf)
6487 {
6488 remote_inferior *priv = get_remote_inferior (inf);
6489
6490 priv->may_wildcard_vcont = true;
6491 }
6492
6493 /* Check for any pending events (not reported or processed yet) and
6494 disable process and global wildcard resumes appropriately. */
6495 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6496
6497 ALL_NON_EXITED_THREADS (tp)
6498 {
6499 /* If a thread of a process is not meant to be resumed, then we
6500 can't wildcard that process. */
6501 if (!tp->executing)
6502 {
6503 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6504
6505 /* And if we can't wildcard a process, we can't wildcard
6506 everything either. */
6507 may_global_wildcard_vcont = 0;
6508 continue;
6509 }
6510
6511 /* If a thread is the parent of an unfollowed fork, then we
6512 can't do a global wildcard, as that would resume the fork
6513 child. */
6514 if (is_pending_fork_parent_thread (tp))
6515 may_global_wildcard_vcont = 0;
6516 }
6517
6518 /* Now let's build the vCont packet(s). Actions must be appended
6519 from narrower to wider scopes (thread -> process -> global). If
6520 we end up with too many actions for a single packet vcont_builder
6521 flushes the current vCont packet to the remote side and starts a
6522 new one. */
6523 struct vcont_builder vcont_builder (this);
6524
6525 /* Threads first. */
6526 ALL_NON_EXITED_THREADS (tp)
6527 {
6528 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6529
6530 if (!tp->executing || remote_thr->vcont_resumed)
6531 continue;
6532
6533 gdb_assert (!thread_is_in_step_over_chain (tp));
6534
6535 if (!remote_thr->last_resume_step
6536 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6537 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6538 {
6539 /* We'll send a wildcard resume instead. */
6540 remote_thr->vcont_resumed = 1;
6541 continue;
6542 }
6543
6544 vcont_builder.push_action (tp->ptid,
6545 remote_thr->last_resume_step,
6546 remote_thr->last_resume_sig);
6547 remote_thr->vcont_resumed = 1;
6548 }
6549
6550 /* Now check whether we can send any process-wide wildcard. This is
6551 to avoid sending a global wildcard in the case nothing is
6552 supposed to be resumed. */
6553 any_process_wildcard = 0;
6554
6555 ALL_NON_EXITED_INFERIORS (inf)
6556 {
6557 if (get_remote_inferior (inf)->may_wildcard_vcont)
6558 {
6559 any_process_wildcard = 1;
6560 break;
6561 }
6562 }
6563
6564 if (any_process_wildcard)
6565 {
6566 /* If all processes are wildcard-able, then send a single "c"
6567 action, otherwise, send an "all (-1) threads of process"
6568 continue action for each running process, if any. */
6569 if (may_global_wildcard_vcont)
6570 {
6571 vcont_builder.push_action (minus_one_ptid,
6572 false, GDB_SIGNAL_0);
6573 }
6574 else
6575 {
6576 ALL_NON_EXITED_INFERIORS (inf)
6577 {
6578 if (get_remote_inferior (inf)->may_wildcard_vcont)
6579 {
6580 vcont_builder.push_action (pid_to_ptid (inf->pid),
6581 false, GDB_SIGNAL_0);
6582 }
6583 }
6584 }
6585 }
6586
6587 vcont_builder.flush ();
6588 }
6589
6590 \f
6591
6592 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6593 thread, all threads of a remote process, or all threads of all
6594 processes. */
6595
6596 void
6597 remote_target::remote_stop_ns (ptid_t ptid)
6598 {
6599 struct remote_state *rs = get_remote_state ();
6600 char *p = rs->buf;
6601 char *endp = rs->buf + get_remote_packet_size ();
6602
6603 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6604 remote_vcont_probe ();
6605
6606 if (!rs->supports_vCont.t)
6607 error (_("Remote server does not support stopping threads"));
6608
6609 if (ptid_equal (ptid, minus_one_ptid)
6610 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6611 p += xsnprintf (p, endp - p, "vCont;t");
6612 else
6613 {
6614 ptid_t nptid;
6615
6616 p += xsnprintf (p, endp - p, "vCont;t:");
6617
6618 if (ptid_is_pid (ptid))
6619 /* All (-1) threads of process. */
6620 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6621 else
6622 {
6623 /* Small optimization: if we already have a stop reply for
6624 this thread, no use in telling the stub we want this
6625 stopped. */
6626 if (peek_stop_reply (ptid))
6627 return;
6628
6629 nptid = ptid;
6630 }
6631
6632 write_ptid (p, endp, nptid);
6633 }
6634
6635 /* In non-stop, we get an immediate OK reply. The stop reply will
6636 come in asynchronously by notification. */
6637 putpkt (rs->buf);
6638 getpkt (&rs->buf, &rs->buf_size, 0);
6639 if (strcmp (rs->buf, "OK") != 0)
6640 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6641 }
6642
6643 /* All-stop version of target_interrupt. Sends a break or a ^C to
6644 interrupt the remote target. It is undefined which thread of which
6645 process reports the interrupt. */
6646
6647 void
6648 remote_target::remote_interrupt_as ()
6649 {
6650 struct remote_state *rs = get_remote_state ();
6651
6652 rs->ctrlc_pending_p = 1;
6653
6654 /* If the inferior is stopped already, but the core didn't know
6655 about it yet, just ignore the request. The cached wait status
6656 will be collected in remote_wait. */
6657 if (rs->cached_wait_status)
6658 return;
6659
6660 /* Send interrupt_sequence to remote target. */
6661 send_interrupt_sequence ();
6662 }
6663
6664 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6665 the remote target. It is undefined which thread of which process
6666 reports the interrupt. Throws an error if the packet is not
6667 supported by the server. */
6668
6669 void
6670 remote_target::remote_interrupt_ns ()
6671 {
6672 struct remote_state *rs = get_remote_state ();
6673 char *p = rs->buf;
6674 char *endp = rs->buf + get_remote_packet_size ();
6675
6676 xsnprintf (p, endp - p, "vCtrlC");
6677
6678 /* In non-stop, we get an immediate OK reply. The stop reply will
6679 come in asynchronously by notification. */
6680 putpkt (rs->buf);
6681 getpkt (&rs->buf, &rs->buf_size, 0);
6682
6683 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6684 {
6685 case PACKET_OK:
6686 break;
6687 case PACKET_UNKNOWN:
6688 error (_("No support for interrupting the remote target."));
6689 case PACKET_ERROR:
6690 error (_("Interrupting target failed: %s"), rs->buf);
6691 }
6692 }
6693
6694 /* Implement the to_stop function for the remote targets. */
6695
6696 void
6697 remote_target::stop (ptid_t ptid)
6698 {
6699 if (remote_debug)
6700 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6701
6702 if (target_is_non_stop_p ())
6703 remote_stop_ns (ptid);
6704 else
6705 {
6706 /* We don't currently have a way to transparently pause the
6707 remote target in all-stop mode. Interrupt it instead. */
6708 remote_interrupt_as ();
6709 }
6710 }
6711
6712 /* Implement the to_interrupt function for the remote targets. */
6713
6714 void
6715 remote_target::interrupt ()
6716 {
6717 if (remote_debug)
6718 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6719
6720 if (target_is_non_stop_p ())
6721 remote_interrupt_ns ();
6722 else
6723 remote_interrupt_as ();
6724 }
6725
6726 /* Implement the to_pass_ctrlc function for the remote targets. */
6727
6728 void
6729 remote_target::pass_ctrlc ()
6730 {
6731 struct remote_state *rs = get_remote_state ();
6732
6733 if (remote_debug)
6734 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6735
6736 /* If we're starting up, we're not fully synced yet. Quit
6737 immediately. */
6738 if (rs->starting_up)
6739 quit ();
6740 /* If ^C has already been sent once, offer to disconnect. */
6741 else if (rs->ctrlc_pending_p)
6742 interrupt_query ();
6743 else
6744 target_interrupt ();
6745 }
6746
6747 /* Ask the user what to do when an interrupt is received. */
6748
6749 void
6750 remote_target::interrupt_query ()
6751 {
6752 struct remote_state *rs = get_remote_state ();
6753
6754 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6755 {
6756 if (query (_("The target is not responding to interrupt requests.\n"
6757 "Stop debugging it? ")))
6758 {
6759 remote_unpush_target ();
6760 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6761 }
6762 }
6763 else
6764 {
6765 if (query (_("Interrupted while waiting for the program.\n"
6766 "Give up waiting? ")))
6767 quit ();
6768 }
6769 }
6770
6771 /* Enable/disable target terminal ownership. Most targets can use
6772 terminal groups to control terminal ownership. Remote targets are
6773 different in that explicit transfer of ownership to/from GDB/target
6774 is required. */
6775
6776 void
6777 remote_target::terminal_inferior ()
6778 {
6779 /* NOTE: At this point we could also register our selves as the
6780 recipient of all input. Any characters typed could then be
6781 passed on down to the target. */
6782 }
6783
6784 void
6785 remote_target::terminal_ours ()
6786 {
6787 }
6788
6789 static void
6790 remote_console_output (char *msg)
6791 {
6792 char *p;
6793
6794 for (p = msg; p[0] && p[1]; p += 2)
6795 {
6796 char tb[2];
6797 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6798
6799 tb[0] = c;
6800 tb[1] = 0;
6801 fputs_unfiltered (tb, gdb_stdtarg);
6802 }
6803 gdb_flush (gdb_stdtarg);
6804 }
6805
6806 DEF_VEC_O(cached_reg_t);
6807
6808 typedef struct stop_reply
6809 {
6810 struct notif_event base;
6811
6812 /* The identifier of the thread about this event */
6813 ptid_t ptid;
6814
6815 /* The remote state this event is associated with. When the remote
6816 connection, represented by a remote_state object, is closed,
6817 all the associated stop_reply events should be released. */
6818 struct remote_state *rs;
6819
6820 struct target_waitstatus ws;
6821
6822 /* The architecture associated with the expedited registers. */
6823 gdbarch *arch;
6824
6825 /* Expedited registers. This makes remote debugging a bit more
6826 efficient for those targets that provide critical registers as
6827 part of their normal status mechanism (as another roundtrip to
6828 fetch them is avoided). */
6829 VEC(cached_reg_t) *regcache;
6830
6831 enum target_stop_reason stop_reason;
6832
6833 CORE_ADDR watch_data_address;
6834
6835 int core;
6836 } *stop_reply_p;
6837
6838 static void
6839 stop_reply_xfree (struct stop_reply *r)
6840 {
6841 notif_event_xfree ((struct notif_event *) r);
6842 }
6843
6844 /* Return the length of the stop reply queue. */
6845
6846 int
6847 remote_target::stop_reply_queue_length ()
6848 {
6849 remote_state *rs = get_remote_state ();
6850 return rs->stop_reply_queue.size ();
6851 }
6852
6853 void
6854 remote_notif_stop_parse (remote_target *remote,
6855 struct notif_client *self, char *buf,
6856 struct notif_event *event)
6857 {
6858 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
6859 }
6860
6861 static void
6862 remote_notif_stop_ack (remote_target *remote,
6863 struct notif_client *self, char *buf,
6864 struct notif_event *event)
6865 {
6866 struct stop_reply *stop_reply = (struct stop_reply *) event;
6867
6868 /* acknowledge */
6869 putpkt (remote, self->ack_command);
6870
6871 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6872 {
6873 /* We got an unknown stop reply. */
6874 error (_("Unknown stop reply"));
6875 }
6876
6877 remote->push_stop_reply (stop_reply);
6878 }
6879
6880 static int
6881 remote_notif_stop_can_get_pending_events (remote_target *remote,
6882 struct notif_client *self)
6883 {
6884 /* We can't get pending events in remote_notif_process for
6885 notification stop, and we have to do this in remote_wait_ns
6886 instead. If we fetch all queued events from stub, remote stub
6887 may exit and we have no chance to process them back in
6888 remote_wait_ns. */
6889 remote_state *rs = remote->get_remote_state ();
6890 mark_async_event_handler (rs->remote_async_inferior_event_token);
6891 return 0;
6892 }
6893
6894 static void
6895 stop_reply_dtr (struct notif_event *event)
6896 {
6897 struct stop_reply *r = (struct stop_reply *) event;
6898 cached_reg_t *reg;
6899 int ix;
6900
6901 for (ix = 0;
6902 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6903 ix++)
6904 xfree (reg->data);
6905
6906 VEC_free (cached_reg_t, r->regcache);
6907 }
6908
6909 static struct notif_event *
6910 remote_notif_stop_alloc_reply (void)
6911 {
6912 /* We cast to a pointer to the "base class". */
6913 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6914
6915 r->dtr = stop_reply_dtr;
6916
6917 return r;
6918 }
6919
6920 /* A client of notification Stop. */
6921
6922 struct notif_client notif_client_stop =
6923 {
6924 "Stop",
6925 "vStopped",
6926 remote_notif_stop_parse,
6927 remote_notif_stop_ack,
6928 remote_notif_stop_can_get_pending_events,
6929 remote_notif_stop_alloc_reply,
6930 REMOTE_NOTIF_STOP,
6931 };
6932
6933 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6934 the pid of the process that owns the threads we want to check, or
6935 -1 if we want to check all threads. */
6936
6937 static int
6938 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6939 ptid_t thread_ptid)
6940 {
6941 if (ws->kind == TARGET_WAITKIND_FORKED
6942 || ws->kind == TARGET_WAITKIND_VFORKED)
6943 {
6944 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6945 return 1;
6946 }
6947
6948 return 0;
6949 }
6950
6951 /* Return the thread's pending status used to determine whether the
6952 thread is a fork parent stopped at a fork event. */
6953
6954 static struct target_waitstatus *
6955 thread_pending_fork_status (struct thread_info *thread)
6956 {
6957 if (thread->suspend.waitstatus_pending_p)
6958 return &thread->suspend.waitstatus;
6959 else
6960 return &thread->pending_follow;
6961 }
6962
6963 /* Determine if THREAD is a pending fork parent thread. */
6964
6965 static int
6966 is_pending_fork_parent_thread (struct thread_info *thread)
6967 {
6968 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6969 int pid = -1;
6970
6971 return is_pending_fork_parent (ws, pid, thread->ptid);
6972 }
6973
6974 /* If CONTEXT contains any fork child threads that have not been
6975 reported yet, remove them from the CONTEXT list. If such a
6976 thread exists it is because we are stopped at a fork catchpoint
6977 and have not yet called follow_fork, which will set up the
6978 host-side data structures for the new process. */
6979
6980 void
6981 remote_target::remove_new_fork_children (threads_listing_context *context)
6982 {
6983 struct thread_info * thread;
6984 int pid = -1;
6985 struct notif_client *notif = &notif_client_stop;
6986
6987 /* For any threads stopped at a fork event, remove the corresponding
6988 fork child threads from the CONTEXT list. */
6989 ALL_NON_EXITED_THREADS (thread)
6990 {
6991 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6992
6993 if (is_pending_fork_parent (ws, pid, thread->ptid))
6994 context->remove_thread (ws->value.related_pid);
6995 }
6996
6997 /* Check for any pending fork events (not reported or processed yet)
6998 in process PID and remove those fork child threads from the
6999 CONTEXT list as well. */
7000 remote_notif_get_pending_events (notif);
7001 for (auto &event : get_remote_state ()->stop_reply_queue)
7002 if (event->ws.kind == TARGET_WAITKIND_FORKED
7003 || event->ws.kind == TARGET_WAITKIND_VFORKED
7004 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7005 context->remove_thread (event->ws.value.related_pid);
7006 }
7007
7008 /* Check whether any event pending in the vStopped queue would prevent
7009 a global or process wildcard vCont action. Clear
7010 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7011 and clear the event inferior's may_wildcard_vcont flag if we can't
7012 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7013
7014 void
7015 remote_target::check_pending_events_prevent_wildcard_vcont
7016 (int *may_global_wildcard)
7017 {
7018 struct notif_client *notif = &notif_client_stop;
7019
7020 remote_notif_get_pending_events (notif);
7021 for (auto &event : get_remote_state ()->stop_reply_queue)
7022 {
7023 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7024 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7025 continue;
7026
7027 if (event->ws.kind == TARGET_WAITKIND_FORKED
7028 || event->ws.kind == TARGET_WAITKIND_VFORKED)
7029 *may_global_wildcard = 0;
7030
7031 struct inferior *inf = find_inferior_ptid (event->ptid);
7032
7033 /* This may be the first time we heard about this process.
7034 Regardless, we must not do a global wildcard resume, otherwise
7035 we'd resume this process too. */
7036 *may_global_wildcard = 0;
7037 if (inf != NULL)
7038 get_remote_inferior (inf)->may_wildcard_vcont = false;
7039 }
7040 }
7041
7042 /* Discard all pending stop replies of inferior INF. */
7043
7044 void
7045 remote_target::discard_pending_stop_replies (struct inferior *inf)
7046 {
7047 struct stop_reply *reply;
7048 struct remote_state *rs = get_remote_state ();
7049 struct remote_notif_state *rns = rs->notif_state;
7050
7051 /* This function can be notified when an inferior exists. When the
7052 target is not remote, the notification state is NULL. */
7053 if (rs->remote_desc == NULL)
7054 return;
7055
7056 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7057
7058 /* Discard the in-flight notification. */
7059 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
7060 {
7061 stop_reply_xfree (reply);
7062 rns->pending_event[notif_client_stop.id] = NULL;
7063 }
7064
7065 /* Discard the stop replies we have already pulled with
7066 vStopped. */
7067 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7068 rs->stop_reply_queue.end (),
7069 [=] (const stop_reply_up &event)
7070 {
7071 return event->ptid.pid () == inf->pid;
7072 });
7073 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7074 }
7075
7076 /* Discard the stop replies for RS in stop_reply_queue. */
7077
7078 void
7079 remote_target::discard_pending_stop_replies_in_queue ()
7080 {
7081 remote_state *rs = get_remote_state ();
7082
7083 /* Discard the stop replies we have already pulled with
7084 vStopped. */
7085 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7086 rs->stop_reply_queue.end (),
7087 [=] (const stop_reply_up &event)
7088 {
7089 return event->rs == rs;
7090 });
7091 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7092 }
7093
7094 /* Remove the first reply in 'stop_reply_queue' which matches
7095 PTID. */
7096
7097 struct stop_reply *
7098 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7099 {
7100 remote_state *rs = get_remote_state ();
7101
7102 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7103 rs->stop_reply_queue.end (),
7104 [=] (const stop_reply_up &event)
7105 {
7106 return event->ptid.matches (ptid);
7107 });
7108 struct stop_reply *result;
7109 if (iter == rs->stop_reply_queue.end ())
7110 result = nullptr;
7111 else
7112 {
7113 result = iter->release ();
7114 rs->stop_reply_queue.erase (iter);
7115 }
7116
7117 if (notif_debug)
7118 fprintf_unfiltered (gdb_stdlog,
7119 "notif: discard queued event: 'Stop' in %s\n",
7120 target_pid_to_str (ptid));
7121
7122 return result;
7123 }
7124
7125 /* Look for a queued stop reply belonging to PTID. If one is found,
7126 remove it from the queue, and return it. Returns NULL if none is
7127 found. If there are still queued events left to process, tell the
7128 event loop to get back to target_wait soon. */
7129
7130 struct stop_reply *
7131 remote_target::queued_stop_reply (ptid_t ptid)
7132 {
7133 remote_state *rs = get_remote_state ();
7134 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7135
7136 if (!rs->stop_reply_queue.empty ())
7137 {
7138 /* There's still at least an event left. */
7139 mark_async_event_handler (rs->remote_async_inferior_event_token);
7140 }
7141
7142 return r;
7143 }
7144
7145 /* Push a fully parsed stop reply in the stop reply queue. Since we
7146 know that we now have at least one queued event left to pass to the
7147 core side, tell the event loop to get back to target_wait soon. */
7148
7149 void
7150 remote_target::push_stop_reply (struct stop_reply *new_event)
7151 {
7152 remote_state *rs = get_remote_state ();
7153 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7154
7155 if (notif_debug)
7156 fprintf_unfiltered (gdb_stdlog,
7157 "notif: push 'Stop' %s to queue %d\n",
7158 target_pid_to_str (new_event->ptid),
7159 int (rs->stop_reply_queue.size ()));
7160
7161 mark_async_event_handler (rs->remote_async_inferior_event_token);
7162 }
7163
7164 /* Returns true if we have a stop reply for PTID. */
7165
7166 int
7167 remote_target::peek_stop_reply (ptid_t ptid)
7168 {
7169 remote_state *rs = get_remote_state ();
7170 for (auto &event : rs->stop_reply_queue)
7171 if (ptid == event->ptid
7172 && event->ws.kind == TARGET_WAITKIND_STOPPED)
7173 return 1;
7174 return 0;
7175 }
7176
7177 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7178 starting with P and ending with PEND matches PREFIX. */
7179
7180 static int
7181 strprefix (const char *p, const char *pend, const char *prefix)
7182 {
7183 for ( ; p < pend; p++, prefix++)
7184 if (*p != *prefix)
7185 return 0;
7186 return *prefix == '\0';
7187 }
7188
7189 /* Parse the stop reply in BUF. Either the function succeeds, and the
7190 result is stored in EVENT, or throws an error. */
7191
7192 void
7193 remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
7194 {
7195 remote_arch_state *rsa = NULL;
7196 ULONGEST addr;
7197 const char *p;
7198 int skipregs = 0;
7199
7200 event->ptid = null_ptid;
7201 event->rs = get_remote_state ();
7202 event->ws.kind = TARGET_WAITKIND_IGNORE;
7203 event->ws.value.integer = 0;
7204 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7205 event->regcache = NULL;
7206 event->core = -1;
7207
7208 switch (buf[0])
7209 {
7210 case 'T': /* Status with PC, SP, FP, ... */
7211 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7212 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7213 ss = signal number
7214 n... = register number
7215 r... = register contents
7216 */
7217
7218 p = &buf[3]; /* after Txx */
7219 while (*p)
7220 {
7221 const char *p1;
7222 int fieldsize;
7223
7224 p1 = strchr (p, ':');
7225 if (p1 == NULL)
7226 error (_("Malformed packet(a) (missing colon): %s\n\
7227 Packet: '%s'\n"),
7228 p, buf);
7229 if (p == p1)
7230 error (_("Malformed packet(a) (missing register number): %s\n\
7231 Packet: '%s'\n"),
7232 p, buf);
7233
7234 /* Some "registers" are actually extended stop information.
7235 Note if you're adding a new entry here: GDB 7.9 and
7236 earlier assume that all register "numbers" that start
7237 with an hex digit are real register numbers. Make sure
7238 the server only sends such a packet if it knows the
7239 client understands it. */
7240
7241 if (strprefix (p, p1, "thread"))
7242 event->ptid = read_ptid (++p1, &p);
7243 else if (strprefix (p, p1, "syscall_entry"))
7244 {
7245 ULONGEST sysno;
7246
7247 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7248 p = unpack_varlen_hex (++p1, &sysno);
7249 event->ws.value.syscall_number = (int) sysno;
7250 }
7251 else if (strprefix (p, p1, "syscall_return"))
7252 {
7253 ULONGEST sysno;
7254
7255 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7256 p = unpack_varlen_hex (++p1, &sysno);
7257 event->ws.value.syscall_number = (int) sysno;
7258 }
7259 else if (strprefix (p, p1, "watch")
7260 || strprefix (p, p1, "rwatch")
7261 || strprefix (p, p1, "awatch"))
7262 {
7263 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7264 p = unpack_varlen_hex (++p1, &addr);
7265 event->watch_data_address = (CORE_ADDR) addr;
7266 }
7267 else if (strprefix (p, p1, "swbreak"))
7268 {
7269 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7270
7271 /* Make sure the stub doesn't forget to indicate support
7272 with qSupported. */
7273 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7274 error (_("Unexpected swbreak stop reason"));
7275
7276 /* The value part is documented as "must be empty",
7277 though we ignore it, in case we ever decide to make
7278 use of it in a backward compatible way. */
7279 p = strchrnul (p1 + 1, ';');
7280 }
7281 else if (strprefix (p, p1, "hwbreak"))
7282 {
7283 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7284
7285 /* Make sure the stub doesn't forget to indicate support
7286 with qSupported. */
7287 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7288 error (_("Unexpected hwbreak stop reason"));
7289
7290 /* See above. */
7291 p = strchrnul (p1 + 1, ';');
7292 }
7293 else if (strprefix (p, p1, "library"))
7294 {
7295 event->ws.kind = TARGET_WAITKIND_LOADED;
7296 p = strchrnul (p1 + 1, ';');
7297 }
7298 else if (strprefix (p, p1, "replaylog"))
7299 {
7300 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7301 /* p1 will indicate "begin" or "end", but it makes
7302 no difference for now, so ignore it. */
7303 p = strchrnul (p1 + 1, ';');
7304 }
7305 else if (strprefix (p, p1, "core"))
7306 {
7307 ULONGEST c;
7308
7309 p = unpack_varlen_hex (++p1, &c);
7310 event->core = c;
7311 }
7312 else if (strprefix (p, p1, "fork"))
7313 {
7314 event->ws.value.related_pid = read_ptid (++p1, &p);
7315 event->ws.kind = TARGET_WAITKIND_FORKED;
7316 }
7317 else if (strprefix (p, p1, "vfork"))
7318 {
7319 event->ws.value.related_pid = read_ptid (++p1, &p);
7320 event->ws.kind = TARGET_WAITKIND_VFORKED;
7321 }
7322 else if (strprefix (p, p1, "vforkdone"))
7323 {
7324 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7325 p = strchrnul (p1 + 1, ';');
7326 }
7327 else if (strprefix (p, p1, "exec"))
7328 {
7329 ULONGEST ignored;
7330 char pathname[PATH_MAX];
7331 int pathlen;
7332
7333 /* Determine the length of the execd pathname. */
7334 p = unpack_varlen_hex (++p1, &ignored);
7335 pathlen = (p - p1) / 2;
7336
7337 /* Save the pathname for event reporting and for
7338 the next run command. */
7339 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7340 pathname[pathlen] = '\0';
7341
7342 /* This is freed during event handling. */
7343 event->ws.value.execd_pathname = xstrdup (pathname);
7344 event->ws.kind = TARGET_WAITKIND_EXECD;
7345
7346 /* Skip the registers included in this packet, since
7347 they may be for an architecture different from the
7348 one used by the original program. */
7349 skipregs = 1;
7350 }
7351 else if (strprefix (p, p1, "create"))
7352 {
7353 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7354 p = strchrnul (p1 + 1, ';');
7355 }
7356 else
7357 {
7358 ULONGEST pnum;
7359 const char *p_temp;
7360
7361 if (skipregs)
7362 {
7363 p = strchrnul (p1 + 1, ';');
7364 p++;
7365 continue;
7366 }
7367
7368 /* Maybe a real ``P'' register number. */
7369 p_temp = unpack_varlen_hex (p, &pnum);
7370 /* If the first invalid character is the colon, we got a
7371 register number. Otherwise, it's an unknown stop
7372 reason. */
7373 if (p_temp == p1)
7374 {
7375 /* If we haven't parsed the event's thread yet, find
7376 it now, in order to find the architecture of the
7377 reported expedited registers. */
7378 if (event->ptid == null_ptid)
7379 {
7380 const char *thr = strstr (p1 + 1, ";thread:");
7381 if (thr != NULL)
7382 event->ptid = read_ptid (thr + strlen (";thread:"),
7383 NULL);
7384 else
7385 {
7386 /* Either the current thread hasn't changed,
7387 or the inferior is not multi-threaded.
7388 The event must be for the thread we last
7389 set as (or learned as being) current. */
7390 event->ptid = event->rs->general_thread;
7391 }
7392 }
7393
7394 if (rsa == NULL)
7395 {
7396 inferior *inf = (event->ptid == null_ptid
7397 ? NULL
7398 : find_inferior_ptid (event->ptid));
7399 /* If this is the first time we learn anything
7400 about this process, skip the registers
7401 included in this packet, since we don't yet
7402 know which architecture to use to parse them.
7403 We'll determine the architecture later when
7404 we process the stop reply and retrieve the
7405 target description, via
7406 remote_notice_new_inferior ->
7407 post_create_inferior. */
7408 if (inf == NULL)
7409 {
7410 p = strchrnul (p1 + 1, ';');
7411 p++;
7412 continue;
7413 }
7414
7415 event->arch = inf->gdbarch;
7416 rsa = event->rs->get_remote_arch_state (event->arch);
7417 }
7418
7419 packet_reg *reg
7420 = packet_reg_from_pnum (event->arch, rsa, pnum);
7421 cached_reg_t cached_reg;
7422
7423 if (reg == NULL)
7424 error (_("Remote sent bad register number %s: %s\n\
7425 Packet: '%s'\n"),
7426 hex_string (pnum), p, buf);
7427
7428 cached_reg.num = reg->regnum;
7429 cached_reg.data = (gdb_byte *)
7430 xmalloc (register_size (event->arch, reg->regnum));
7431
7432 p = p1 + 1;
7433 fieldsize = hex2bin (p, cached_reg.data,
7434 register_size (event->arch, reg->regnum));
7435 p += 2 * fieldsize;
7436 if (fieldsize < register_size (event->arch, reg->regnum))
7437 warning (_("Remote reply is too short: %s"), buf);
7438
7439 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7440 }
7441 else
7442 {
7443 /* Not a number. Silently skip unknown optional
7444 info. */
7445 p = strchrnul (p1 + 1, ';');
7446 }
7447 }
7448
7449 if (*p != ';')
7450 error (_("Remote register badly formatted: %s\nhere: %s"),
7451 buf, p);
7452 ++p;
7453 }
7454
7455 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7456 break;
7457
7458 /* fall through */
7459 case 'S': /* Old style status, just signal only. */
7460 {
7461 int sig;
7462
7463 event->ws.kind = TARGET_WAITKIND_STOPPED;
7464 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7465 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7466 event->ws.value.sig = (enum gdb_signal) sig;
7467 else
7468 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7469 }
7470 break;
7471 case 'w': /* Thread exited. */
7472 {
7473 const char *p;
7474 ULONGEST value;
7475
7476 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7477 p = unpack_varlen_hex (&buf[1], &value);
7478 event->ws.value.integer = value;
7479 if (*p != ';')
7480 error (_("stop reply packet badly formatted: %s"), buf);
7481 event->ptid = read_ptid (++p, NULL);
7482 break;
7483 }
7484 case 'W': /* Target exited. */
7485 case 'X':
7486 {
7487 const char *p;
7488 int pid;
7489 ULONGEST value;
7490
7491 /* GDB used to accept only 2 hex chars here. Stubs should
7492 only send more if they detect GDB supports multi-process
7493 support. */
7494 p = unpack_varlen_hex (&buf[1], &value);
7495
7496 if (buf[0] == 'W')
7497 {
7498 /* The remote process exited. */
7499 event->ws.kind = TARGET_WAITKIND_EXITED;
7500 event->ws.value.integer = value;
7501 }
7502 else
7503 {
7504 /* The remote process exited with a signal. */
7505 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7506 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7507 event->ws.value.sig = (enum gdb_signal) value;
7508 else
7509 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7510 }
7511
7512 /* If no process is specified, assume inferior_ptid. */
7513 pid = ptid_get_pid (inferior_ptid);
7514 if (*p == '\0')
7515 ;
7516 else if (*p == ';')
7517 {
7518 p++;
7519
7520 if (*p == '\0')
7521 ;
7522 else if (startswith (p, "process:"))
7523 {
7524 ULONGEST upid;
7525
7526 p += sizeof ("process:") - 1;
7527 unpack_varlen_hex (p, &upid);
7528 pid = upid;
7529 }
7530 else
7531 error (_("unknown stop reply packet: %s"), buf);
7532 }
7533 else
7534 error (_("unknown stop reply packet: %s"), buf);
7535 event->ptid = pid_to_ptid (pid);
7536 }
7537 break;
7538 case 'N':
7539 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7540 event->ptid = minus_one_ptid;
7541 break;
7542 }
7543
7544 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7545 error (_("No process or thread specified in stop reply: %s"), buf);
7546 }
7547
7548 /* When the stub wants to tell GDB about a new notification reply, it
7549 sends a notification (%Stop, for example). Those can come it at
7550 any time, hence, we have to make sure that any pending
7551 putpkt/getpkt sequence we're making is finished, before querying
7552 the stub for more events with the corresponding ack command
7553 (vStopped, for example). E.g., if we started a vStopped sequence
7554 immediately upon receiving the notification, something like this
7555 could happen:
7556
7557 1.1) --> Hg 1
7558 1.2) <-- OK
7559 1.3) --> g
7560 1.4) <-- %Stop
7561 1.5) --> vStopped
7562 1.6) <-- (registers reply to step #1.3)
7563
7564 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7565 query.
7566
7567 To solve this, whenever we parse a %Stop notification successfully,
7568 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7569 doing whatever we were doing:
7570
7571 2.1) --> Hg 1
7572 2.2) <-- OK
7573 2.3) --> g
7574 2.4) <-- %Stop
7575 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7576 2.5) <-- (registers reply to step #2.3)
7577
7578 Eventualy after step #2.5, we return to the event loop, which
7579 notices there's an event on the
7580 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7581 associated callback --- the function below. At this point, we're
7582 always safe to start a vStopped sequence. :
7583
7584 2.6) --> vStopped
7585 2.7) <-- T05 thread:2
7586 2.8) --> vStopped
7587 2.9) --> OK
7588 */
7589
7590 void
7591 remote_target::remote_notif_get_pending_events (notif_client *nc)
7592 {
7593 struct remote_state *rs = get_remote_state ();
7594
7595 if (rs->notif_state->pending_event[nc->id] != NULL)
7596 {
7597 if (notif_debug)
7598 fprintf_unfiltered (gdb_stdlog,
7599 "notif: process: '%s' ack pending event\n",
7600 nc->name);
7601
7602 /* acknowledge */
7603 nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7604 rs->notif_state->pending_event[nc->id] = NULL;
7605
7606 while (1)
7607 {
7608 getpkt (&rs->buf, &rs->buf_size, 0);
7609 if (strcmp (rs->buf, "OK") == 0)
7610 break;
7611 else
7612 remote_notif_ack (this, nc, rs->buf);
7613 }
7614 }
7615 else
7616 {
7617 if (notif_debug)
7618 fprintf_unfiltered (gdb_stdlog,
7619 "notif: process: '%s' no pending reply\n",
7620 nc->name);
7621 }
7622 }
7623
7624 /* Wrapper around remote_target::remote_notif_get_pending_events to
7625 avoid having to export the whole remote_target class. */
7626
7627 void
7628 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7629 {
7630 remote->remote_notif_get_pending_events (nc);
7631 }
7632
7633 /* Called when it is decided that STOP_REPLY holds the info of the
7634 event that is to be returned to the core. This function always
7635 destroys STOP_REPLY. */
7636
7637 ptid_t
7638 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7639 struct target_waitstatus *status)
7640 {
7641 ptid_t ptid;
7642
7643 *status = stop_reply->ws;
7644 ptid = stop_reply->ptid;
7645
7646 /* If no thread/process was reported by the stub, assume the current
7647 inferior. */
7648 if (ptid_equal (ptid, null_ptid))
7649 ptid = inferior_ptid;
7650
7651 if (status->kind != TARGET_WAITKIND_EXITED
7652 && status->kind != TARGET_WAITKIND_SIGNALLED
7653 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7654 {
7655 /* Expedited registers. */
7656 if (stop_reply->regcache)
7657 {
7658 struct regcache *regcache
7659 = get_thread_arch_regcache (ptid, stop_reply->arch);
7660 cached_reg_t *reg;
7661 int ix;
7662
7663 for (ix = 0;
7664 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7665 ix++)
7666 {
7667 regcache->raw_supply (reg->num, reg->data);
7668 xfree (reg->data);
7669 }
7670
7671 VEC_free (cached_reg_t, stop_reply->regcache);
7672 }
7673
7674 remote_notice_new_inferior (ptid, 0);
7675 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7676 remote_thr->core = stop_reply->core;
7677 remote_thr->stop_reason = stop_reply->stop_reason;
7678 remote_thr->watch_data_address = stop_reply->watch_data_address;
7679 remote_thr->vcont_resumed = 0;
7680 }
7681
7682 stop_reply_xfree (stop_reply);
7683 return ptid;
7684 }
7685
7686 /* The non-stop mode version of target_wait. */
7687
7688 ptid_t
7689 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7690 {
7691 struct remote_state *rs = get_remote_state ();
7692 struct stop_reply *stop_reply;
7693 int ret;
7694 int is_notif = 0;
7695
7696 /* If in non-stop mode, get out of getpkt even if a
7697 notification is received. */
7698
7699 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7700 0 /* forever */, &is_notif);
7701 while (1)
7702 {
7703 if (ret != -1 && !is_notif)
7704 switch (rs->buf[0])
7705 {
7706 case 'E': /* Error of some sort. */
7707 /* We're out of sync with the target now. Did it continue
7708 or not? We can't tell which thread it was in non-stop,
7709 so just ignore this. */
7710 warning (_("Remote failure reply: %s"), rs->buf);
7711 break;
7712 case 'O': /* Console output. */
7713 remote_console_output (rs->buf + 1);
7714 break;
7715 default:
7716 warning (_("Invalid remote reply: %s"), rs->buf);
7717 break;
7718 }
7719
7720 /* Acknowledge a pending stop reply that may have arrived in the
7721 mean time. */
7722 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7723 remote_notif_get_pending_events (&notif_client_stop);
7724
7725 /* If indeed we noticed a stop reply, we're done. */
7726 stop_reply = queued_stop_reply (ptid);
7727 if (stop_reply != NULL)
7728 return process_stop_reply (stop_reply, status);
7729
7730 /* Still no event. If we're just polling for an event, then
7731 return to the event loop. */
7732 if (options & TARGET_WNOHANG)
7733 {
7734 status->kind = TARGET_WAITKIND_IGNORE;
7735 return minus_one_ptid;
7736 }
7737
7738 /* Otherwise do a blocking wait. */
7739 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7740 1 /* forever */, &is_notif);
7741 }
7742 }
7743
7744 /* Wait until the remote machine stops, then return, storing status in
7745 STATUS just as `wait' would. */
7746
7747 ptid_t
7748 remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
7749 {
7750 struct remote_state *rs = get_remote_state ();
7751 ptid_t event_ptid = null_ptid;
7752 char *buf;
7753 struct stop_reply *stop_reply;
7754
7755 again:
7756
7757 status->kind = TARGET_WAITKIND_IGNORE;
7758 status->value.integer = 0;
7759
7760 stop_reply = queued_stop_reply (ptid);
7761 if (stop_reply != NULL)
7762 return process_stop_reply (stop_reply, status);
7763
7764 if (rs->cached_wait_status)
7765 /* Use the cached wait status, but only once. */
7766 rs->cached_wait_status = 0;
7767 else
7768 {
7769 int ret;
7770 int is_notif;
7771 int forever = ((options & TARGET_WNOHANG) == 0
7772 && rs->wait_forever_enabled_p);
7773
7774 if (!rs->waiting_for_stop_reply)
7775 {
7776 status->kind = TARGET_WAITKIND_NO_RESUMED;
7777 return minus_one_ptid;
7778 }
7779
7780 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7781 _never_ wait for ever -> test on target_is_async_p().
7782 However, before we do that we need to ensure that the caller
7783 knows how to take the target into/out of async mode. */
7784 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7785 forever, &is_notif);
7786
7787 /* GDB gets a notification. Return to core as this event is
7788 not interesting. */
7789 if (ret != -1 && is_notif)
7790 return minus_one_ptid;
7791
7792 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7793 return minus_one_ptid;
7794 }
7795
7796 buf = rs->buf;
7797
7798 /* Assume that the target has acknowledged Ctrl-C unless we receive
7799 an 'F' or 'O' packet. */
7800 if (buf[0] != 'F' && buf[0] != 'O')
7801 rs->ctrlc_pending_p = 0;
7802
7803 switch (buf[0])
7804 {
7805 case 'E': /* Error of some sort. */
7806 /* We're out of sync with the target now. Did it continue or
7807 not? Not is more likely, so report a stop. */
7808 rs->waiting_for_stop_reply = 0;
7809
7810 warning (_("Remote failure reply: %s"), buf);
7811 status->kind = TARGET_WAITKIND_STOPPED;
7812 status->value.sig = GDB_SIGNAL_0;
7813 break;
7814 case 'F': /* File-I/O request. */
7815 /* GDB may access the inferior memory while handling the File-I/O
7816 request, but we don't want GDB accessing memory while waiting
7817 for a stop reply. See the comments in putpkt_binary. Set
7818 waiting_for_stop_reply to 0 temporarily. */
7819 rs->waiting_for_stop_reply = 0;
7820 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
7821 rs->ctrlc_pending_p = 0;
7822 /* GDB handled the File-I/O request, and the target is running
7823 again. Keep waiting for events. */
7824 rs->waiting_for_stop_reply = 1;
7825 break;
7826 case 'N': case 'T': case 'S': case 'X': case 'W':
7827 {
7828 struct stop_reply *stop_reply;
7829
7830 /* There is a stop reply to handle. */
7831 rs->waiting_for_stop_reply = 0;
7832
7833 stop_reply
7834 = (struct stop_reply *) remote_notif_parse (this,
7835 &notif_client_stop,
7836 rs->buf);
7837
7838 event_ptid = process_stop_reply (stop_reply, status);
7839 break;
7840 }
7841 case 'O': /* Console output. */
7842 remote_console_output (buf + 1);
7843 break;
7844 case '\0':
7845 if (rs->last_sent_signal != GDB_SIGNAL_0)
7846 {
7847 /* Zero length reply means that we tried 'S' or 'C' and the
7848 remote system doesn't support it. */
7849 target_terminal::ours_for_output ();
7850 printf_filtered
7851 ("Can't send signals to this remote system. %s not sent.\n",
7852 gdb_signal_to_name (rs->last_sent_signal));
7853 rs->last_sent_signal = GDB_SIGNAL_0;
7854 target_terminal::inferior ();
7855
7856 strcpy (buf, rs->last_sent_step ? "s" : "c");
7857 putpkt (buf);
7858 break;
7859 }
7860 /* fallthrough */
7861 default:
7862 warning (_("Invalid remote reply: %s"), buf);
7863 break;
7864 }
7865
7866 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7867 return minus_one_ptid;
7868 else if (status->kind == TARGET_WAITKIND_IGNORE)
7869 {
7870 /* Nothing interesting happened. If we're doing a non-blocking
7871 poll, we're done. Otherwise, go back to waiting. */
7872 if (options & TARGET_WNOHANG)
7873 return minus_one_ptid;
7874 else
7875 goto again;
7876 }
7877 else if (status->kind != TARGET_WAITKIND_EXITED
7878 && status->kind != TARGET_WAITKIND_SIGNALLED)
7879 {
7880 if (!ptid_equal (event_ptid, null_ptid))
7881 record_currthread (rs, event_ptid);
7882 else
7883 event_ptid = inferior_ptid;
7884 }
7885 else
7886 /* A process exit. Invalidate our notion of current thread. */
7887 record_currthread (rs, minus_one_ptid);
7888
7889 return event_ptid;
7890 }
7891
7892 /* Wait until the remote machine stops, then return, storing status in
7893 STATUS just as `wait' would. */
7894
7895 ptid_t
7896 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7897 {
7898 ptid_t event_ptid;
7899
7900 if (target_is_non_stop_p ())
7901 event_ptid = wait_ns (ptid, status, options);
7902 else
7903 event_ptid = wait_as (ptid, status, options);
7904
7905 if (target_is_async_p ())
7906 {
7907 remote_state *rs = get_remote_state ();
7908
7909 /* If there are are events left in the queue tell the event loop
7910 to return here. */
7911 if (!rs->stop_reply_queue.empty ())
7912 mark_async_event_handler (rs->remote_async_inferior_event_token);
7913 }
7914
7915 return event_ptid;
7916 }
7917
7918 /* Fetch a single register using a 'p' packet. */
7919
7920 int
7921 remote_target::fetch_register_using_p (struct regcache *regcache,
7922 packet_reg *reg)
7923 {
7924 struct gdbarch *gdbarch = regcache->arch ();
7925 struct remote_state *rs = get_remote_state ();
7926 char *buf, *p;
7927 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7928 int i;
7929
7930 if (packet_support (PACKET_p) == PACKET_DISABLE)
7931 return 0;
7932
7933 if (reg->pnum == -1)
7934 return 0;
7935
7936 p = rs->buf;
7937 *p++ = 'p';
7938 p += hexnumstr (p, reg->pnum);
7939 *p++ = '\0';
7940 putpkt (rs->buf);
7941 getpkt (&rs->buf, &rs->buf_size, 0);
7942
7943 buf = rs->buf;
7944
7945 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7946 {
7947 case PACKET_OK:
7948 break;
7949 case PACKET_UNKNOWN:
7950 return 0;
7951 case PACKET_ERROR:
7952 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7953 gdbarch_register_name (regcache->arch (),
7954 reg->regnum),
7955 buf);
7956 }
7957
7958 /* If this register is unfetchable, tell the regcache. */
7959 if (buf[0] == 'x')
7960 {
7961 regcache->raw_supply (reg->regnum, NULL);
7962 return 1;
7963 }
7964
7965 /* Otherwise, parse and supply the value. */
7966 p = buf;
7967 i = 0;
7968 while (p[0] != 0)
7969 {
7970 if (p[1] == 0)
7971 error (_("fetch_register_using_p: early buf termination"));
7972
7973 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7974 p += 2;
7975 }
7976 regcache->raw_supply (reg->regnum, regp);
7977 return 1;
7978 }
7979
7980 /* Fetch the registers included in the target's 'g' packet. */
7981
7982 int
7983 remote_target::send_g_packet ()
7984 {
7985 struct remote_state *rs = get_remote_state ();
7986 int buf_len;
7987
7988 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7989 putpkt (rs->buf);
7990 getpkt (&rs->buf, &rs->buf_size, 0);
7991 if (packet_check_result (rs->buf) == PACKET_ERROR)
7992 error (_("Could not read registers; remote failure reply '%s'"),
7993 rs->buf);
7994
7995 /* We can get out of synch in various cases. If the first character
7996 in the buffer is not a hex character, assume that has happened
7997 and try to fetch another packet to read. */
7998 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7999 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8000 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8001 && rs->buf[0] != 'x') /* New: unavailable register value. */
8002 {
8003 if (remote_debug)
8004 fprintf_unfiltered (gdb_stdlog,
8005 "Bad register packet; fetching a new packet\n");
8006 getpkt (&rs->buf, &rs->buf_size, 0);
8007 }
8008
8009 buf_len = strlen (rs->buf);
8010
8011 /* Sanity check the received packet. */
8012 if (buf_len % 2 != 0)
8013 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
8014
8015 return buf_len / 2;
8016 }
8017
8018 void
8019 remote_target::process_g_packet (struct regcache *regcache)
8020 {
8021 struct gdbarch *gdbarch = regcache->arch ();
8022 struct remote_state *rs = get_remote_state ();
8023 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8024 int i, buf_len;
8025 char *p;
8026 char *regs;
8027
8028 buf_len = strlen (rs->buf);
8029
8030 /* Further sanity checks, with knowledge of the architecture. */
8031 if (buf_len > 2 * rsa->sizeof_g_packet)
8032 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8033 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
8034
8035 /* Save the size of the packet sent to us by the target. It is used
8036 as a heuristic when determining the max size of packets that the
8037 target can safely receive. */
8038 if (rsa->actual_register_packet_size == 0)
8039 rsa->actual_register_packet_size = buf_len;
8040
8041 /* If this is smaller than we guessed the 'g' packet would be,
8042 update our records. A 'g' reply that doesn't include a register's
8043 value implies either that the register is not available, or that
8044 the 'p' packet must be used. */
8045 if (buf_len < 2 * rsa->sizeof_g_packet)
8046 {
8047 long sizeof_g_packet = buf_len / 2;
8048
8049 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8050 {
8051 long offset = rsa->regs[i].offset;
8052 long reg_size = register_size (gdbarch, i);
8053
8054 if (rsa->regs[i].pnum == -1)
8055 continue;
8056
8057 if (offset >= sizeof_g_packet)
8058 rsa->regs[i].in_g_packet = 0;
8059 else if (offset + reg_size > sizeof_g_packet)
8060 error (_("Truncated register %d in remote 'g' packet"), i);
8061 else
8062 rsa->regs[i].in_g_packet = 1;
8063 }
8064
8065 /* Looks valid enough, we can assume this is the correct length
8066 for a 'g' packet. It's important not to adjust
8067 rsa->sizeof_g_packet if we have truncated registers otherwise
8068 this "if" won't be run the next time the method is called
8069 with a packet of the same size and one of the internal errors
8070 below will trigger instead. */
8071 rsa->sizeof_g_packet = sizeof_g_packet;
8072 }
8073
8074 regs = (char *) alloca (rsa->sizeof_g_packet);
8075
8076 /* Unimplemented registers read as all bits zero. */
8077 memset (regs, 0, rsa->sizeof_g_packet);
8078
8079 /* Reply describes registers byte by byte, each byte encoded as two
8080 hex characters. Suck them all up, then supply them to the
8081 register cacheing/storage mechanism. */
8082
8083 p = rs->buf;
8084 for (i = 0; i < rsa->sizeof_g_packet; i++)
8085 {
8086 if (p[0] == 0 || p[1] == 0)
8087 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8088 internal_error (__FILE__, __LINE__,
8089 _("unexpected end of 'g' packet reply"));
8090
8091 if (p[0] == 'x' && p[1] == 'x')
8092 regs[i] = 0; /* 'x' */
8093 else
8094 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8095 p += 2;
8096 }
8097
8098 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8099 {
8100 struct packet_reg *r = &rsa->regs[i];
8101 long reg_size = register_size (gdbarch, i);
8102
8103 if (r->in_g_packet)
8104 {
8105 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
8106 /* This shouldn't happen - we adjusted in_g_packet above. */
8107 internal_error (__FILE__, __LINE__,
8108 _("unexpected end of 'g' packet reply"));
8109 else if (rs->buf[r->offset * 2] == 'x')
8110 {
8111 gdb_assert (r->offset * 2 < strlen (rs->buf));
8112 /* The register isn't available, mark it as such (at
8113 the same time setting the value to zero). */
8114 regcache->raw_supply (r->regnum, NULL);
8115 }
8116 else
8117 regcache->raw_supply (r->regnum, regs + r->offset);
8118 }
8119 }
8120 }
8121
8122 void
8123 remote_target::fetch_registers_using_g (struct regcache *regcache)
8124 {
8125 send_g_packet ();
8126 process_g_packet (regcache);
8127 }
8128
8129 /* Make the remote selected traceframe match GDB's selected
8130 traceframe. */
8131
8132 void
8133 remote_target::set_remote_traceframe ()
8134 {
8135 int newnum;
8136 struct remote_state *rs = get_remote_state ();
8137
8138 if (rs->remote_traceframe_number == get_traceframe_number ())
8139 return;
8140
8141 /* Avoid recursion, remote_trace_find calls us again. */
8142 rs->remote_traceframe_number = get_traceframe_number ();
8143
8144 newnum = target_trace_find (tfind_number,
8145 get_traceframe_number (), 0, 0, NULL);
8146
8147 /* Should not happen. If it does, all bets are off. */
8148 if (newnum != get_traceframe_number ())
8149 warning (_("could not set remote traceframe"));
8150 }
8151
8152 void
8153 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8154 {
8155 struct gdbarch *gdbarch = regcache->arch ();
8156 struct remote_state *rs = get_remote_state ();
8157 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8158 int i;
8159
8160 set_remote_traceframe ();
8161 set_general_thread (regcache->ptid ());
8162
8163 if (regnum >= 0)
8164 {
8165 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8166
8167 gdb_assert (reg != NULL);
8168
8169 /* If this register might be in the 'g' packet, try that first -
8170 we are likely to read more than one register. If this is the
8171 first 'g' packet, we might be overly optimistic about its
8172 contents, so fall back to 'p'. */
8173 if (reg->in_g_packet)
8174 {
8175 fetch_registers_using_g (regcache);
8176 if (reg->in_g_packet)
8177 return;
8178 }
8179
8180 if (fetch_register_using_p (regcache, reg))
8181 return;
8182
8183 /* This register is not available. */
8184 regcache->raw_supply (reg->regnum, NULL);
8185
8186 return;
8187 }
8188
8189 fetch_registers_using_g (regcache);
8190
8191 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8192 if (!rsa->regs[i].in_g_packet)
8193 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8194 {
8195 /* This register is not available. */
8196 regcache->raw_supply (i, NULL);
8197 }
8198 }
8199
8200 /* Prepare to store registers. Since we may send them all (using a
8201 'G' request), we have to read out the ones we don't want to change
8202 first. */
8203
8204 void
8205 remote_target::prepare_to_store (struct regcache *regcache)
8206 {
8207 struct remote_state *rs = get_remote_state ();
8208 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8209 int i;
8210
8211 /* Make sure the entire registers array is valid. */
8212 switch (packet_support (PACKET_P))
8213 {
8214 case PACKET_DISABLE:
8215 case PACKET_SUPPORT_UNKNOWN:
8216 /* Make sure all the necessary registers are cached. */
8217 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8218 if (rsa->regs[i].in_g_packet)
8219 regcache->raw_update (rsa->regs[i].regnum);
8220 break;
8221 case PACKET_ENABLE:
8222 break;
8223 }
8224 }
8225
8226 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8227 packet was not recognized. */
8228
8229 int
8230 remote_target::store_register_using_P (const struct regcache *regcache,
8231 packet_reg *reg)
8232 {
8233 struct gdbarch *gdbarch = regcache->arch ();
8234 struct remote_state *rs = get_remote_state ();
8235 /* Try storing a single register. */
8236 char *buf = rs->buf;
8237 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8238 char *p;
8239
8240 if (packet_support (PACKET_P) == PACKET_DISABLE)
8241 return 0;
8242
8243 if (reg->pnum == -1)
8244 return 0;
8245
8246 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8247 p = buf + strlen (buf);
8248 regcache->raw_collect (reg->regnum, regp);
8249 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8250 putpkt (rs->buf);
8251 getpkt (&rs->buf, &rs->buf_size, 0);
8252
8253 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8254 {
8255 case PACKET_OK:
8256 return 1;
8257 case PACKET_ERROR:
8258 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8259 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8260 case PACKET_UNKNOWN:
8261 return 0;
8262 default:
8263 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8264 }
8265 }
8266
8267 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8268 contents of the register cache buffer. FIXME: ignores errors. */
8269
8270 void
8271 remote_target::store_registers_using_G (const struct regcache *regcache)
8272 {
8273 struct remote_state *rs = get_remote_state ();
8274 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8275 gdb_byte *regs;
8276 char *p;
8277
8278 /* Extract all the registers in the regcache copying them into a
8279 local buffer. */
8280 {
8281 int i;
8282
8283 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8284 memset (regs, 0, rsa->sizeof_g_packet);
8285 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8286 {
8287 struct packet_reg *r = &rsa->regs[i];
8288
8289 if (r->in_g_packet)
8290 regcache->raw_collect (r->regnum, regs + r->offset);
8291 }
8292 }
8293
8294 /* Command describes registers byte by byte,
8295 each byte encoded as two hex characters. */
8296 p = rs->buf;
8297 *p++ = 'G';
8298 bin2hex (regs, p, rsa->sizeof_g_packet);
8299 putpkt (rs->buf);
8300 getpkt (&rs->buf, &rs->buf_size, 0);
8301 if (packet_check_result (rs->buf) == PACKET_ERROR)
8302 error (_("Could not write registers; remote failure reply '%s'"),
8303 rs->buf);
8304 }
8305
8306 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8307 of the register cache buffer. FIXME: ignores errors. */
8308
8309 void
8310 remote_target::store_registers (struct regcache *regcache, int regnum)
8311 {
8312 struct gdbarch *gdbarch = regcache->arch ();
8313 struct remote_state *rs = get_remote_state ();
8314 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8315 int i;
8316
8317 set_remote_traceframe ();
8318 set_general_thread (regcache->ptid ());
8319
8320 if (regnum >= 0)
8321 {
8322 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8323
8324 gdb_assert (reg != NULL);
8325
8326 /* Always prefer to store registers using the 'P' packet if
8327 possible; we often change only a small number of registers.
8328 Sometimes we change a larger number; we'd need help from a
8329 higher layer to know to use 'G'. */
8330 if (store_register_using_P (regcache, reg))
8331 return;
8332
8333 /* For now, don't complain if we have no way to write the
8334 register. GDB loses track of unavailable registers too
8335 easily. Some day, this may be an error. We don't have
8336 any way to read the register, either... */
8337 if (!reg->in_g_packet)
8338 return;
8339
8340 store_registers_using_G (regcache);
8341 return;
8342 }
8343
8344 store_registers_using_G (regcache);
8345
8346 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8347 if (!rsa->regs[i].in_g_packet)
8348 if (!store_register_using_P (regcache, &rsa->regs[i]))
8349 /* See above for why we do not issue an error here. */
8350 continue;
8351 }
8352 \f
8353
8354 /* Return the number of hex digits in num. */
8355
8356 static int
8357 hexnumlen (ULONGEST num)
8358 {
8359 int i;
8360
8361 for (i = 0; num != 0; i++)
8362 num >>= 4;
8363
8364 return std::max (i, 1);
8365 }
8366
8367 /* Set BUF to the minimum number of hex digits representing NUM. */
8368
8369 static int
8370 hexnumstr (char *buf, ULONGEST num)
8371 {
8372 int len = hexnumlen (num);
8373
8374 return hexnumnstr (buf, num, len);
8375 }
8376
8377
8378 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8379
8380 static int
8381 hexnumnstr (char *buf, ULONGEST num, int width)
8382 {
8383 int i;
8384
8385 buf[width] = '\0';
8386
8387 for (i = width - 1; i >= 0; i--)
8388 {
8389 buf[i] = "0123456789abcdef"[(num & 0xf)];
8390 num >>= 4;
8391 }
8392
8393 return width;
8394 }
8395
8396 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8397
8398 static CORE_ADDR
8399 remote_address_masked (CORE_ADDR addr)
8400 {
8401 unsigned int address_size = remote_address_size;
8402
8403 /* If "remoteaddresssize" was not set, default to target address size. */
8404 if (!address_size)
8405 address_size = gdbarch_addr_bit (target_gdbarch ());
8406
8407 if (address_size > 0
8408 && address_size < (sizeof (ULONGEST) * 8))
8409 {
8410 /* Only create a mask when that mask can safely be constructed
8411 in a ULONGEST variable. */
8412 ULONGEST mask = 1;
8413
8414 mask = (mask << address_size) - 1;
8415 addr &= mask;
8416 }
8417 return addr;
8418 }
8419
8420 /* Determine whether the remote target supports binary downloading.
8421 This is accomplished by sending a no-op memory write of zero length
8422 to the target at the specified address. It does not suffice to send
8423 the whole packet, since many stubs strip the eighth bit and
8424 subsequently compute a wrong checksum, which causes real havoc with
8425 remote_write_bytes.
8426
8427 NOTE: This can still lose if the serial line is not eight-bit
8428 clean. In cases like this, the user should clear "remote
8429 X-packet". */
8430
8431 void
8432 remote_target::check_binary_download (CORE_ADDR addr)
8433 {
8434 struct remote_state *rs = get_remote_state ();
8435
8436 switch (packet_support (PACKET_X))
8437 {
8438 case PACKET_DISABLE:
8439 break;
8440 case PACKET_ENABLE:
8441 break;
8442 case PACKET_SUPPORT_UNKNOWN:
8443 {
8444 char *p;
8445
8446 p = rs->buf;
8447 *p++ = 'X';
8448 p += hexnumstr (p, (ULONGEST) addr);
8449 *p++ = ',';
8450 p += hexnumstr (p, (ULONGEST) 0);
8451 *p++ = ':';
8452 *p = '\0';
8453
8454 putpkt_binary (rs->buf, (int) (p - rs->buf));
8455 getpkt (&rs->buf, &rs->buf_size, 0);
8456
8457 if (rs->buf[0] == '\0')
8458 {
8459 if (remote_debug)
8460 fprintf_unfiltered (gdb_stdlog,
8461 "binary downloading NOT "
8462 "supported by target\n");
8463 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8464 }
8465 else
8466 {
8467 if (remote_debug)
8468 fprintf_unfiltered (gdb_stdlog,
8469 "binary downloading supported by target\n");
8470 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8471 }
8472 break;
8473 }
8474 }
8475 }
8476
8477 /* Helper function to resize the payload in order to try to get a good
8478 alignment. We try to write an amount of data such that the next write will
8479 start on an address aligned on REMOTE_ALIGN_WRITES. */
8480
8481 static int
8482 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8483 {
8484 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8485 }
8486
8487 /* Write memory data directly to the remote machine.
8488 This does not inform the data cache; the data cache uses this.
8489 HEADER is the starting part of the packet.
8490 MEMADDR is the address in the remote memory space.
8491 MYADDR is the address of the buffer in our space.
8492 LEN_UNITS is the number of addressable units to write.
8493 UNIT_SIZE is the length in bytes of an addressable unit.
8494 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8495 should send data as binary ('X'), or hex-encoded ('M').
8496
8497 The function creates packet of the form
8498 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8499
8500 where encoding of <DATA> is terminated by PACKET_FORMAT.
8501
8502 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8503 are omitted.
8504
8505 Return the transferred status, error or OK (an
8506 'enum target_xfer_status' value). Save the number of addressable units
8507 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8508
8509 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8510 exchange between gdb and the stub could look like (?? in place of the
8511 checksum):
8512
8513 -> $m1000,4#??
8514 <- aaaabbbbccccdddd
8515
8516 -> $M1000,3:eeeeffffeeee#??
8517 <- OK
8518
8519 -> $m1000,4#??
8520 <- eeeeffffeeeedddd */
8521
8522 target_xfer_status
8523 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8524 const gdb_byte *myaddr,
8525 ULONGEST len_units,
8526 int unit_size,
8527 ULONGEST *xfered_len_units,
8528 char packet_format, int use_length)
8529 {
8530 struct remote_state *rs = get_remote_state ();
8531 char *p;
8532 char *plen = NULL;
8533 int plenlen = 0;
8534 int todo_units;
8535 int units_written;
8536 int payload_capacity_bytes;
8537 int payload_length_bytes;
8538
8539 if (packet_format != 'X' && packet_format != 'M')
8540 internal_error (__FILE__, __LINE__,
8541 _("remote_write_bytes_aux: bad packet format"));
8542
8543 if (len_units == 0)
8544 return TARGET_XFER_EOF;
8545
8546 payload_capacity_bytes = get_memory_write_packet_size ();
8547
8548 /* The packet buffer will be large enough for the payload;
8549 get_memory_packet_size ensures this. */
8550 rs->buf[0] = '\0';
8551
8552 /* Compute the size of the actual payload by subtracting out the
8553 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8554
8555 payload_capacity_bytes -= strlen ("$,:#NN");
8556 if (!use_length)
8557 /* The comma won't be used. */
8558 payload_capacity_bytes += 1;
8559 payload_capacity_bytes -= strlen (header);
8560 payload_capacity_bytes -= hexnumlen (memaddr);
8561
8562 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8563
8564 strcat (rs->buf, header);
8565 p = rs->buf + strlen (header);
8566
8567 /* Compute a best guess of the number of bytes actually transfered. */
8568 if (packet_format == 'X')
8569 {
8570 /* Best guess at number of bytes that will fit. */
8571 todo_units = std::min (len_units,
8572 (ULONGEST) payload_capacity_bytes / unit_size);
8573 if (use_length)
8574 payload_capacity_bytes -= hexnumlen (todo_units);
8575 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8576 }
8577 else
8578 {
8579 /* Number of bytes that will fit. */
8580 todo_units
8581 = std::min (len_units,
8582 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8583 if (use_length)
8584 payload_capacity_bytes -= hexnumlen (todo_units);
8585 todo_units = std::min (todo_units,
8586 (payload_capacity_bytes / unit_size) / 2);
8587 }
8588
8589 if (todo_units <= 0)
8590 internal_error (__FILE__, __LINE__,
8591 _("minimum packet size too small to write data"));
8592
8593 /* If we already need another packet, then try to align the end
8594 of this packet to a useful boundary. */
8595 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8596 todo_units = align_for_efficient_write (todo_units, memaddr);
8597
8598 /* Append "<memaddr>". */
8599 memaddr = remote_address_masked (memaddr);
8600 p += hexnumstr (p, (ULONGEST) memaddr);
8601
8602 if (use_length)
8603 {
8604 /* Append ",". */
8605 *p++ = ',';
8606
8607 /* Append the length and retain its location and size. It may need to be
8608 adjusted once the packet body has been created. */
8609 plen = p;
8610 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8611 p += plenlen;
8612 }
8613
8614 /* Append ":". */
8615 *p++ = ':';
8616 *p = '\0';
8617
8618 /* Append the packet body. */
8619 if (packet_format == 'X')
8620 {
8621 /* Binary mode. Send target system values byte by byte, in
8622 increasing byte addresses. Only escape certain critical
8623 characters. */
8624 payload_length_bytes =
8625 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8626 &units_written, payload_capacity_bytes);
8627
8628 /* If not all TODO units fit, then we'll need another packet. Make
8629 a second try to keep the end of the packet aligned. Don't do
8630 this if the packet is tiny. */
8631 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8632 {
8633 int new_todo_units;
8634
8635 new_todo_units = align_for_efficient_write (units_written, memaddr);
8636
8637 if (new_todo_units != units_written)
8638 payload_length_bytes =
8639 remote_escape_output (myaddr, new_todo_units, unit_size,
8640 (gdb_byte *) p, &units_written,
8641 payload_capacity_bytes);
8642 }
8643
8644 p += payload_length_bytes;
8645 if (use_length && units_written < todo_units)
8646 {
8647 /* Escape chars have filled up the buffer prematurely,
8648 and we have actually sent fewer units than planned.
8649 Fix-up the length field of the packet. Use the same
8650 number of characters as before. */
8651 plen += hexnumnstr (plen, (ULONGEST) units_written,
8652 plenlen);
8653 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8654 }
8655 }
8656 else
8657 {
8658 /* Normal mode: Send target system values byte by byte, in
8659 increasing byte addresses. Each byte is encoded as a two hex
8660 value. */
8661 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8662 units_written = todo_units;
8663 }
8664
8665 putpkt_binary (rs->buf, (int) (p - rs->buf));
8666 getpkt (&rs->buf, &rs->buf_size, 0);
8667
8668 if (rs->buf[0] == 'E')
8669 return TARGET_XFER_E_IO;
8670
8671 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8672 send fewer units than we'd planned. */
8673 *xfered_len_units = (ULONGEST) units_written;
8674 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8675 }
8676
8677 /* Write memory data directly to the remote machine.
8678 This does not inform the data cache; the data cache uses this.
8679 MEMADDR is the address in the remote memory space.
8680 MYADDR is the address of the buffer in our space.
8681 LEN is the number of bytes.
8682
8683 Return the transferred status, error or OK (an
8684 'enum target_xfer_status' value). Save the number of bytes
8685 transferred in *XFERED_LEN. Only transfer a single packet. */
8686
8687 target_xfer_status
8688 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8689 ULONGEST len, int unit_size,
8690 ULONGEST *xfered_len)
8691 {
8692 const char *packet_format = NULL;
8693
8694 /* Check whether the target supports binary download. */
8695 check_binary_download (memaddr);
8696
8697 switch (packet_support (PACKET_X))
8698 {
8699 case PACKET_ENABLE:
8700 packet_format = "X";
8701 break;
8702 case PACKET_DISABLE:
8703 packet_format = "M";
8704 break;
8705 case PACKET_SUPPORT_UNKNOWN:
8706 internal_error (__FILE__, __LINE__,
8707 _("remote_write_bytes: bad internal state"));
8708 default:
8709 internal_error (__FILE__, __LINE__, _("bad switch"));
8710 }
8711
8712 return remote_write_bytes_aux (packet_format,
8713 memaddr, myaddr, len, unit_size, xfered_len,
8714 packet_format[0], 1);
8715 }
8716
8717 /* Read memory data directly from the remote machine.
8718 This does not use the data cache; the data cache uses this.
8719 MEMADDR is the address in the remote memory space.
8720 MYADDR is the address of the buffer in our space.
8721 LEN_UNITS is the number of addressable memory units to read..
8722 UNIT_SIZE is the length in bytes of an addressable unit.
8723
8724 Return the transferred status, error or OK (an
8725 'enum target_xfer_status' value). Save the number of bytes
8726 transferred in *XFERED_LEN_UNITS.
8727
8728 See the comment of remote_write_bytes_aux for an example of
8729 memory read/write exchange between gdb and the stub. */
8730
8731 target_xfer_status
8732 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8733 ULONGEST len_units,
8734 int unit_size, ULONGEST *xfered_len_units)
8735 {
8736 struct remote_state *rs = get_remote_state ();
8737 int buf_size_bytes; /* Max size of packet output buffer. */
8738 char *p;
8739 int todo_units;
8740 int decoded_bytes;
8741
8742 buf_size_bytes = get_memory_read_packet_size ();
8743 /* The packet buffer will be large enough for the payload;
8744 get_memory_packet_size ensures this. */
8745
8746 /* Number of units that will fit. */
8747 todo_units = std::min (len_units,
8748 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8749
8750 /* Construct "m"<memaddr>","<len>". */
8751 memaddr = remote_address_masked (memaddr);
8752 p = rs->buf;
8753 *p++ = 'm';
8754 p += hexnumstr (p, (ULONGEST) memaddr);
8755 *p++ = ',';
8756 p += hexnumstr (p, (ULONGEST) todo_units);
8757 *p = '\0';
8758 putpkt (rs->buf);
8759 getpkt (&rs->buf, &rs->buf_size, 0);
8760 if (rs->buf[0] == 'E'
8761 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8762 && rs->buf[3] == '\0')
8763 return TARGET_XFER_E_IO;
8764 /* Reply describes memory byte by byte, each byte encoded as two hex
8765 characters. */
8766 p = rs->buf;
8767 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8768 /* Return what we have. Let higher layers handle partial reads. */
8769 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8770 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8771 }
8772
8773 /* Using the set of read-only target sections of remote, read live
8774 read-only memory.
8775
8776 For interface/parameters/return description see target.h,
8777 to_xfer_partial. */
8778
8779 target_xfer_status
8780 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8781 ULONGEST memaddr,
8782 ULONGEST len,
8783 int unit_size,
8784 ULONGEST *xfered_len)
8785 {
8786 struct target_section *secp;
8787 struct target_section_table *table;
8788
8789 secp = target_section_by_addr (this, memaddr);
8790 if (secp != NULL
8791 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8792 secp->the_bfd_section)
8793 & SEC_READONLY))
8794 {
8795 struct target_section *p;
8796 ULONGEST memend = memaddr + len;
8797
8798 table = target_get_section_table (this);
8799
8800 for (p = table->sections; p < table->sections_end; p++)
8801 {
8802 if (memaddr >= p->addr)
8803 {
8804 if (memend <= p->endaddr)
8805 {
8806 /* Entire transfer is within this section. */
8807 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8808 xfered_len);
8809 }
8810 else if (memaddr >= p->endaddr)
8811 {
8812 /* This section ends before the transfer starts. */
8813 continue;
8814 }
8815 else
8816 {
8817 /* This section overlaps the transfer. Just do half. */
8818 len = p->endaddr - memaddr;
8819 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8820 xfered_len);
8821 }
8822 }
8823 }
8824 }
8825
8826 return TARGET_XFER_EOF;
8827 }
8828
8829 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8830 first if the requested memory is unavailable in traceframe.
8831 Otherwise, fall back to remote_read_bytes_1. */
8832
8833 target_xfer_status
8834 remote_target::remote_read_bytes (CORE_ADDR memaddr,
8835 gdb_byte *myaddr, ULONGEST len, int unit_size,
8836 ULONGEST *xfered_len)
8837 {
8838 if (len == 0)
8839 return TARGET_XFER_EOF;
8840
8841 if (get_traceframe_number () != -1)
8842 {
8843 std::vector<mem_range> available;
8844
8845 /* If we fail to get the set of available memory, then the
8846 target does not support querying traceframe info, and so we
8847 attempt reading from the traceframe anyway (assuming the
8848 target implements the old QTro packet then). */
8849 if (traceframe_available_memory (&available, memaddr, len))
8850 {
8851 if (available.empty () || available[0].start != memaddr)
8852 {
8853 enum target_xfer_status res;
8854
8855 /* Don't read into the traceframe's available
8856 memory. */
8857 if (!available.empty ())
8858 {
8859 LONGEST oldlen = len;
8860
8861 len = available[0].start - memaddr;
8862 gdb_assert (len <= oldlen);
8863 }
8864
8865 /* This goes through the topmost target again. */
8866 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
8867 len, unit_size, xfered_len);
8868 if (res == TARGET_XFER_OK)
8869 return TARGET_XFER_OK;
8870 else
8871 {
8872 /* No use trying further, we know some memory starting
8873 at MEMADDR isn't available. */
8874 *xfered_len = len;
8875 return (*xfered_len != 0) ?
8876 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8877 }
8878 }
8879
8880 /* Don't try to read more than how much is available, in
8881 case the target implements the deprecated QTro packet to
8882 cater for older GDBs (the target's knowledge of read-only
8883 sections may be outdated by now). */
8884 len = available[0].length;
8885 }
8886 }
8887
8888 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8889 }
8890
8891 \f
8892
8893 /* Sends a packet with content determined by the printf format string
8894 FORMAT and the remaining arguments, then gets the reply. Returns
8895 whether the packet was a success, a failure, or unknown. */
8896
8897 packet_result
8898 remote_target::remote_send_printf (const char *format, ...)
8899 {
8900 struct remote_state *rs = get_remote_state ();
8901 int max_size = get_remote_packet_size ();
8902 va_list ap;
8903
8904 va_start (ap, format);
8905
8906 rs->buf[0] = '\0';
8907 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8908 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8909
8910 if (putpkt (rs->buf) < 0)
8911 error (_("Communication problem with target."));
8912
8913 rs->buf[0] = '\0';
8914 getpkt (&rs->buf, &rs->buf_size, 0);
8915
8916 return packet_check_result (rs->buf);
8917 }
8918
8919 /* Flash writing can take quite some time. We'll set
8920 effectively infinite timeout for flash operations.
8921 In future, we'll need to decide on a better approach. */
8922 static const int remote_flash_timeout = 1000;
8923
8924 void
8925 remote_target::flash_erase (ULONGEST address, LONGEST length)
8926 {
8927 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8928 enum packet_result ret;
8929 scoped_restore restore_timeout
8930 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8931
8932 ret = remote_send_printf ("vFlashErase:%s,%s",
8933 phex (address, addr_size),
8934 phex (length, 4));
8935 switch (ret)
8936 {
8937 case PACKET_UNKNOWN:
8938 error (_("Remote target does not support flash erase"));
8939 case PACKET_ERROR:
8940 error (_("Error erasing flash with vFlashErase packet"));
8941 default:
8942 break;
8943 }
8944 }
8945
8946 target_xfer_status
8947 remote_target::remote_flash_write (ULONGEST address,
8948 ULONGEST length, ULONGEST *xfered_len,
8949 const gdb_byte *data)
8950 {
8951 scoped_restore restore_timeout
8952 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8953 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8954 xfered_len,'X', 0);
8955 }
8956
8957 void
8958 remote_target::flash_done ()
8959 {
8960 int ret;
8961
8962 scoped_restore restore_timeout
8963 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8964
8965 ret = remote_send_printf ("vFlashDone");
8966
8967 switch (ret)
8968 {
8969 case PACKET_UNKNOWN:
8970 error (_("Remote target does not support vFlashDone"));
8971 case PACKET_ERROR:
8972 error (_("Error finishing flash operation"));
8973 default:
8974 break;
8975 }
8976 }
8977
8978 void
8979 remote_target::files_info ()
8980 {
8981 puts_filtered ("Debugging a target over a serial line.\n");
8982 }
8983 \f
8984 /* Stuff for dealing with the packets which are part of this protocol.
8985 See comment at top of file for details. */
8986
8987 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8988 error to higher layers. Called when a serial error is detected.
8989 The exception message is STRING, followed by a colon and a blank,
8990 the system error message for errno at function entry and final dot
8991 for output compatibility with throw_perror_with_name. */
8992
8993 static void
8994 unpush_and_perror (const char *string)
8995 {
8996 int saved_errno = errno;
8997
8998 remote_unpush_target ();
8999 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9000 safe_strerror (saved_errno));
9001 }
9002
9003 /* Read a single character from the remote end. The current quit
9004 handler is overridden to avoid quitting in the middle of packet
9005 sequence, as that would break communication with the remote server.
9006 See remote_serial_quit_handler for more detail. */
9007
9008 int
9009 remote_target::readchar (int timeout)
9010 {
9011 int ch;
9012 struct remote_state *rs = get_remote_state ();
9013
9014 {
9015 scoped_restore restore_quit_target
9016 = make_scoped_restore (&curr_quit_handler_target, this);
9017 scoped_restore restore_quit
9018 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9019
9020 rs->got_ctrlc_during_io = 0;
9021
9022 ch = serial_readchar (rs->remote_desc, timeout);
9023
9024 if (rs->got_ctrlc_during_io)
9025 set_quit_flag ();
9026 }
9027
9028 if (ch >= 0)
9029 return ch;
9030
9031 switch ((enum serial_rc) ch)
9032 {
9033 case SERIAL_EOF:
9034 remote_unpush_target ();
9035 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9036 /* no return */
9037 case SERIAL_ERROR:
9038 unpush_and_perror (_("Remote communication error. "
9039 "Target disconnected."));
9040 /* no return */
9041 case SERIAL_TIMEOUT:
9042 break;
9043 }
9044 return ch;
9045 }
9046
9047 /* Wrapper for serial_write that closes the target and throws if
9048 writing fails. The current quit handler is overridden to avoid
9049 quitting in the middle of packet sequence, as that would break
9050 communication with the remote server. See
9051 remote_serial_quit_handler for more detail. */
9052
9053 void
9054 remote_target::remote_serial_write (const char *str, int len)
9055 {
9056 struct remote_state *rs = get_remote_state ();
9057
9058 scoped_restore restore_quit_target
9059 = make_scoped_restore (&curr_quit_handler_target, this);
9060 scoped_restore restore_quit
9061 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9062
9063 rs->got_ctrlc_during_io = 0;
9064
9065 if (serial_write (rs->remote_desc, str, len))
9066 {
9067 unpush_and_perror (_("Remote communication error. "
9068 "Target disconnected."));
9069 }
9070
9071 if (rs->got_ctrlc_during_io)
9072 set_quit_flag ();
9073 }
9074
9075 /* Return a string representing an escaped version of BUF, of len N.
9076 E.g. \n is converted to \\n, \t to \\t, etc. */
9077
9078 static std::string
9079 escape_buffer (const char *buf, int n)
9080 {
9081 string_file stb;
9082
9083 stb.putstrn (buf, n, '\\');
9084 return std::move (stb.string ());
9085 }
9086
9087 /* Display a null-terminated packet on stdout, for debugging, using C
9088 string notation. */
9089
9090 static void
9091 print_packet (const char *buf)
9092 {
9093 puts_filtered ("\"");
9094 fputstr_filtered (buf, '"', gdb_stdout);
9095 puts_filtered ("\"");
9096 }
9097
9098 int
9099 remote_target::putpkt (const char *buf)
9100 {
9101 return putpkt_binary (buf, strlen (buf));
9102 }
9103
9104 /* Wrapper around remote_target::putpkt to avoid exporting
9105 remote_target. */
9106
9107 int
9108 putpkt (remote_target *remote, const char *buf)
9109 {
9110 return remote->putpkt (buf);
9111 }
9112
9113 /* Send a packet to the remote machine, with error checking. The data
9114 of the packet is in BUF. The string in BUF can be at most
9115 get_remote_packet_size () - 5 to account for the $, # and checksum,
9116 and for a possible /0 if we are debugging (remote_debug) and want
9117 to print the sent packet as a string. */
9118
9119 int
9120 remote_target::putpkt_binary (const char *buf, int cnt)
9121 {
9122 struct remote_state *rs = get_remote_state ();
9123 int i;
9124 unsigned char csum = 0;
9125 gdb::def_vector<char> data (cnt + 6);
9126 char *buf2 = data.data ();
9127
9128 int ch;
9129 int tcount = 0;
9130 char *p;
9131
9132 /* Catch cases like trying to read memory or listing threads while
9133 we're waiting for a stop reply. The remote server wouldn't be
9134 ready to handle this request, so we'd hang and timeout. We don't
9135 have to worry about this in synchronous mode, because in that
9136 case it's not possible to issue a command while the target is
9137 running. This is not a problem in non-stop mode, because in that
9138 case, the stub is always ready to process serial input. */
9139 if (!target_is_non_stop_p ()
9140 && target_is_async_p ()
9141 && rs->waiting_for_stop_reply)
9142 {
9143 error (_("Cannot execute this command while the target is running.\n"
9144 "Use the \"interrupt\" command to stop the target\n"
9145 "and then try again."));
9146 }
9147
9148 /* We're sending out a new packet. Make sure we don't look at a
9149 stale cached response. */
9150 rs->cached_wait_status = 0;
9151
9152 /* Copy the packet into buffer BUF2, encapsulating it
9153 and giving it a checksum. */
9154
9155 p = buf2;
9156 *p++ = '$';
9157
9158 for (i = 0; i < cnt; i++)
9159 {
9160 csum += buf[i];
9161 *p++ = buf[i];
9162 }
9163 *p++ = '#';
9164 *p++ = tohex ((csum >> 4) & 0xf);
9165 *p++ = tohex (csum & 0xf);
9166
9167 /* Send it over and over until we get a positive ack. */
9168
9169 while (1)
9170 {
9171 int started_error_output = 0;
9172
9173 if (remote_debug)
9174 {
9175 *p = '\0';
9176
9177 int len = (int) (p - buf2);
9178
9179 std::string str
9180 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9181
9182 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9183
9184 if (len > REMOTE_DEBUG_MAX_CHAR)
9185 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9186 len - REMOTE_DEBUG_MAX_CHAR);
9187
9188 fprintf_unfiltered (gdb_stdlog, "...");
9189
9190 gdb_flush (gdb_stdlog);
9191 }
9192 remote_serial_write (buf2, p - buf2);
9193
9194 /* If this is a no acks version of the remote protocol, send the
9195 packet and move on. */
9196 if (rs->noack_mode)
9197 break;
9198
9199 /* Read until either a timeout occurs (-2) or '+' is read.
9200 Handle any notification that arrives in the mean time. */
9201 while (1)
9202 {
9203 ch = readchar (remote_timeout);
9204
9205 if (remote_debug)
9206 {
9207 switch (ch)
9208 {
9209 case '+':
9210 case '-':
9211 case SERIAL_TIMEOUT:
9212 case '$':
9213 case '%':
9214 if (started_error_output)
9215 {
9216 putchar_unfiltered ('\n');
9217 started_error_output = 0;
9218 }
9219 }
9220 }
9221
9222 switch (ch)
9223 {
9224 case '+':
9225 if (remote_debug)
9226 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9227 return 1;
9228 case '-':
9229 if (remote_debug)
9230 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9231 /* FALLTHROUGH */
9232 case SERIAL_TIMEOUT:
9233 tcount++;
9234 if (tcount > 3)
9235 return 0;
9236 break; /* Retransmit buffer. */
9237 case '$':
9238 {
9239 if (remote_debug)
9240 fprintf_unfiltered (gdb_stdlog,
9241 "Packet instead of Ack, ignoring it\n");
9242 /* It's probably an old response sent because an ACK
9243 was lost. Gobble up the packet and ack it so it
9244 doesn't get retransmitted when we resend this
9245 packet. */
9246 skip_frame ();
9247 remote_serial_write ("+", 1);
9248 continue; /* Now, go look for +. */
9249 }
9250
9251 case '%':
9252 {
9253 int val;
9254
9255 /* If we got a notification, handle it, and go back to looking
9256 for an ack. */
9257 /* We've found the start of a notification. Now
9258 collect the data. */
9259 val = read_frame (&rs->buf, &rs->buf_size);
9260 if (val >= 0)
9261 {
9262 if (remote_debug)
9263 {
9264 std::string str = escape_buffer (rs->buf, val);
9265
9266 fprintf_unfiltered (gdb_stdlog,
9267 " Notification received: %s\n",
9268 str.c_str ());
9269 }
9270 handle_notification (rs->notif_state, rs->buf);
9271 /* We're in sync now, rewait for the ack. */
9272 tcount = 0;
9273 }
9274 else
9275 {
9276 if (remote_debug)
9277 {
9278 if (!started_error_output)
9279 {
9280 started_error_output = 1;
9281 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9282 }
9283 fputc_unfiltered (ch & 0177, gdb_stdlog);
9284 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9285 }
9286 }
9287 continue;
9288 }
9289 /* fall-through */
9290 default:
9291 if (remote_debug)
9292 {
9293 if (!started_error_output)
9294 {
9295 started_error_output = 1;
9296 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9297 }
9298 fputc_unfiltered (ch & 0177, gdb_stdlog);
9299 }
9300 continue;
9301 }
9302 break; /* Here to retransmit. */
9303 }
9304
9305 #if 0
9306 /* This is wrong. If doing a long backtrace, the user should be
9307 able to get out next time we call QUIT, without anything as
9308 violent as interrupt_query. If we want to provide a way out of
9309 here without getting to the next QUIT, it should be based on
9310 hitting ^C twice as in remote_wait. */
9311 if (quit_flag)
9312 {
9313 quit_flag = 0;
9314 interrupt_query ();
9315 }
9316 #endif
9317 }
9318
9319 return 0;
9320 }
9321
9322 /* Come here after finding the start of a frame when we expected an
9323 ack. Do our best to discard the rest of this packet. */
9324
9325 void
9326 remote_target::skip_frame ()
9327 {
9328 int c;
9329
9330 while (1)
9331 {
9332 c = readchar (remote_timeout);
9333 switch (c)
9334 {
9335 case SERIAL_TIMEOUT:
9336 /* Nothing we can do. */
9337 return;
9338 case '#':
9339 /* Discard the two bytes of checksum and stop. */
9340 c = readchar (remote_timeout);
9341 if (c >= 0)
9342 c = readchar (remote_timeout);
9343
9344 return;
9345 case '*': /* Run length encoding. */
9346 /* Discard the repeat count. */
9347 c = readchar (remote_timeout);
9348 if (c < 0)
9349 return;
9350 break;
9351 default:
9352 /* A regular character. */
9353 break;
9354 }
9355 }
9356 }
9357
9358 /* Come here after finding the start of the frame. Collect the rest
9359 into *BUF, verifying the checksum, length, and handling run-length
9360 compression. NUL terminate the buffer. If there is not enough room,
9361 expand *BUF using xrealloc.
9362
9363 Returns -1 on error, number of characters in buffer (ignoring the
9364 trailing NULL) on success. (could be extended to return one of the
9365 SERIAL status indications). */
9366
9367 long
9368 remote_target::read_frame (char **buf_p, long *sizeof_buf)
9369 {
9370 unsigned char csum;
9371 long bc;
9372 int c;
9373 char *buf = *buf_p;
9374 struct remote_state *rs = get_remote_state ();
9375
9376 csum = 0;
9377 bc = 0;
9378
9379 while (1)
9380 {
9381 c = readchar (remote_timeout);
9382 switch (c)
9383 {
9384 case SERIAL_TIMEOUT:
9385 if (remote_debug)
9386 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9387 return -1;
9388 case '$':
9389 if (remote_debug)
9390 fputs_filtered ("Saw new packet start in middle of old one\n",
9391 gdb_stdlog);
9392 return -1; /* Start a new packet, count retries. */
9393 case '#':
9394 {
9395 unsigned char pktcsum;
9396 int check_0 = 0;
9397 int check_1 = 0;
9398
9399 buf[bc] = '\0';
9400
9401 check_0 = readchar (remote_timeout);
9402 if (check_0 >= 0)
9403 check_1 = readchar (remote_timeout);
9404
9405 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9406 {
9407 if (remote_debug)
9408 fputs_filtered ("Timeout in checksum, retrying\n",
9409 gdb_stdlog);
9410 return -1;
9411 }
9412 else if (check_0 < 0 || check_1 < 0)
9413 {
9414 if (remote_debug)
9415 fputs_filtered ("Communication error in checksum\n",
9416 gdb_stdlog);
9417 return -1;
9418 }
9419
9420 /* Don't recompute the checksum; with no ack packets we
9421 don't have any way to indicate a packet retransmission
9422 is necessary. */
9423 if (rs->noack_mode)
9424 return bc;
9425
9426 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9427 if (csum == pktcsum)
9428 return bc;
9429
9430 if (remote_debug)
9431 {
9432 std::string str = escape_buffer (buf, bc);
9433
9434 fprintf_unfiltered (gdb_stdlog,
9435 "Bad checksum, sentsum=0x%x, "
9436 "csum=0x%x, buf=%s\n",
9437 pktcsum, csum, str.c_str ());
9438 }
9439 /* Number of characters in buffer ignoring trailing
9440 NULL. */
9441 return -1;
9442 }
9443 case '*': /* Run length encoding. */
9444 {
9445 int repeat;
9446
9447 csum += c;
9448 c = readchar (remote_timeout);
9449 csum += c;
9450 repeat = c - ' ' + 3; /* Compute repeat count. */
9451
9452 /* The character before ``*'' is repeated. */
9453
9454 if (repeat > 0 && repeat <= 255 && bc > 0)
9455 {
9456 if (bc + repeat - 1 >= *sizeof_buf - 1)
9457 {
9458 /* Make some more room in the buffer. */
9459 *sizeof_buf += repeat;
9460 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9461 buf = *buf_p;
9462 }
9463
9464 memset (&buf[bc], buf[bc - 1], repeat);
9465 bc += repeat;
9466 continue;
9467 }
9468
9469 buf[bc] = '\0';
9470 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9471 return -1;
9472 }
9473 default:
9474 if (bc >= *sizeof_buf - 1)
9475 {
9476 /* Make some more room in the buffer. */
9477 *sizeof_buf *= 2;
9478 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9479 buf = *buf_p;
9480 }
9481
9482 buf[bc++] = c;
9483 csum += c;
9484 continue;
9485 }
9486 }
9487 }
9488
9489 /* Read a packet from the remote machine, with error checking, and
9490 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9491 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9492 rather than timing out; this is used (in synchronous mode) to wait
9493 for a target that is is executing user code to stop. */
9494 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9495 don't have to change all the calls to getpkt to deal with the
9496 return value, because at the moment I don't know what the right
9497 thing to do it for those. */
9498
9499 void
9500 remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
9501 {
9502 getpkt_sane (buf, sizeof_buf, forever);
9503 }
9504
9505
9506 /* Read a packet from the remote machine, with error checking, and
9507 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9508 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9509 rather than timing out; this is used (in synchronous mode) to wait
9510 for a target that is is executing user code to stop. If FOREVER ==
9511 0, this function is allowed to time out gracefully and return an
9512 indication of this to the caller. Otherwise return the number of
9513 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9514 enough reason to return to the caller. *IS_NOTIF is an output
9515 boolean that indicates whether *BUF holds a notification or not
9516 (a regular packet). */
9517
9518 int
9519 remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9520 int forever, int expecting_notif,
9521 int *is_notif)
9522 {
9523 struct remote_state *rs = get_remote_state ();
9524 int c;
9525 int tries;
9526 int timeout;
9527 int val = -1;
9528
9529 /* We're reading a new response. Make sure we don't look at a
9530 previously cached response. */
9531 rs->cached_wait_status = 0;
9532
9533 strcpy (*buf, "timeout");
9534
9535 if (forever)
9536 timeout = watchdog > 0 ? watchdog : -1;
9537 else if (expecting_notif)
9538 timeout = 0; /* There should already be a char in the buffer. If
9539 not, bail out. */
9540 else
9541 timeout = remote_timeout;
9542
9543 #define MAX_TRIES 3
9544
9545 /* Process any number of notifications, and then return when
9546 we get a packet. */
9547 for (;;)
9548 {
9549 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9550 times. */
9551 for (tries = 1; tries <= MAX_TRIES; tries++)
9552 {
9553 /* This can loop forever if the remote side sends us
9554 characters continuously, but if it pauses, we'll get
9555 SERIAL_TIMEOUT from readchar because of timeout. Then
9556 we'll count that as a retry.
9557
9558 Note that even when forever is set, we will only wait
9559 forever prior to the start of a packet. After that, we
9560 expect characters to arrive at a brisk pace. They should
9561 show up within remote_timeout intervals. */
9562 do
9563 c = readchar (timeout);
9564 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9565
9566 if (c == SERIAL_TIMEOUT)
9567 {
9568 if (expecting_notif)
9569 return -1; /* Don't complain, it's normal to not get
9570 anything in this case. */
9571
9572 if (forever) /* Watchdog went off? Kill the target. */
9573 {
9574 remote_unpush_target ();
9575 throw_error (TARGET_CLOSE_ERROR,
9576 _("Watchdog timeout has expired. "
9577 "Target detached."));
9578 }
9579 if (remote_debug)
9580 fputs_filtered ("Timed out.\n", gdb_stdlog);
9581 }
9582 else
9583 {
9584 /* We've found the start of a packet or notification.
9585 Now collect the data. */
9586 val = read_frame (buf, sizeof_buf);
9587 if (val >= 0)
9588 break;
9589 }
9590
9591 remote_serial_write ("-", 1);
9592 }
9593
9594 if (tries > MAX_TRIES)
9595 {
9596 /* We have tried hard enough, and just can't receive the
9597 packet/notification. Give up. */
9598 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9599
9600 /* Skip the ack char if we're in no-ack mode. */
9601 if (!rs->noack_mode)
9602 remote_serial_write ("+", 1);
9603 return -1;
9604 }
9605
9606 /* If we got an ordinary packet, return that to our caller. */
9607 if (c == '$')
9608 {
9609 if (remote_debug)
9610 {
9611 std::string str
9612 = escape_buffer (*buf,
9613 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9614
9615 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9616 str.c_str ());
9617
9618 if (val > REMOTE_DEBUG_MAX_CHAR)
9619 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9620 val - REMOTE_DEBUG_MAX_CHAR);
9621
9622 fprintf_unfiltered (gdb_stdlog, "\n");
9623 }
9624
9625 /* Skip the ack char if we're in no-ack mode. */
9626 if (!rs->noack_mode)
9627 remote_serial_write ("+", 1);
9628 if (is_notif != NULL)
9629 *is_notif = 0;
9630 return val;
9631 }
9632
9633 /* If we got a notification, handle it, and go back to looking
9634 for a packet. */
9635 else
9636 {
9637 gdb_assert (c == '%');
9638
9639 if (remote_debug)
9640 {
9641 std::string str = escape_buffer (*buf, val);
9642
9643 fprintf_unfiltered (gdb_stdlog,
9644 " Notification received: %s\n",
9645 str.c_str ());
9646 }
9647 if (is_notif != NULL)
9648 *is_notif = 1;
9649
9650 handle_notification (rs->notif_state, *buf);
9651
9652 /* Notifications require no acknowledgement. */
9653
9654 if (expecting_notif)
9655 return val;
9656 }
9657 }
9658 }
9659
9660 int
9661 remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
9662 {
9663 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9664 }
9665
9666 int
9667 remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9668 int *is_notif)
9669 {
9670 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9671 is_notif);
9672 }
9673
9674 /* Kill any new fork children of process PID that haven't been
9675 processed by follow_fork. */
9676
9677 void
9678 remote_target::kill_new_fork_children (int pid)
9679 {
9680 remote_state *rs = get_remote_state ();
9681 struct thread_info *thread;
9682 struct notif_client *notif = &notif_client_stop;
9683
9684 /* Kill the fork child threads of any threads in process PID
9685 that are stopped at a fork event. */
9686 ALL_NON_EXITED_THREADS (thread)
9687 {
9688 struct target_waitstatus *ws = &thread->pending_follow;
9689
9690 if (is_pending_fork_parent (ws, pid, thread->ptid))
9691 {
9692 int child_pid = ws->value.related_pid.pid ();
9693 int res;
9694
9695 res = remote_vkill (child_pid);
9696 if (res != 0)
9697 error (_("Can't kill fork child process %d"), child_pid);
9698 }
9699 }
9700
9701 /* Check for any pending fork events (not reported or processed yet)
9702 in process PID and kill those fork child threads as well. */
9703 remote_notif_get_pending_events (notif);
9704 for (auto &event : rs->stop_reply_queue)
9705 if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9706 {
9707 int child_pid = event->ws.value.related_pid.pid ();
9708 int res;
9709
9710 res = remote_vkill (child_pid);
9711 if (res != 0)
9712 error (_("Can't kill fork child process %d"), child_pid);
9713 }
9714 }
9715
9716 \f
9717 /* Target hook to kill the current inferior. */
9718
9719 void
9720 remote_target::kill ()
9721 {
9722 int res = -1;
9723 int pid = ptid_get_pid (inferior_ptid);
9724 struct remote_state *rs = get_remote_state ();
9725
9726 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9727 {
9728 /* If we're stopped while forking and we haven't followed yet,
9729 kill the child task. We need to do this before killing the
9730 parent task because if this is a vfork then the parent will
9731 be sleeping. */
9732 kill_new_fork_children (pid);
9733
9734 res = remote_vkill (pid);
9735 if (res == 0)
9736 {
9737 target_mourn_inferior (inferior_ptid);
9738 return;
9739 }
9740 }
9741
9742 /* If we are in 'target remote' mode and we are killing the only
9743 inferior, then we will tell gdbserver to exit and unpush the
9744 target. */
9745 if (res == -1 && !remote_multi_process_p (rs)
9746 && number_of_live_inferiors () == 1)
9747 {
9748 remote_kill_k ();
9749
9750 /* We've killed the remote end, we get to mourn it. If we are
9751 not in extended mode, mourning the inferior also unpushes
9752 remote_ops from the target stack, which closes the remote
9753 connection. */
9754 target_mourn_inferior (inferior_ptid);
9755
9756 return;
9757 }
9758
9759 error (_("Can't kill process"));
9760 }
9761
9762 /* Send a kill request to the target using the 'vKill' packet. */
9763
9764 int
9765 remote_target::remote_vkill (int pid)
9766 {
9767 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9768 return -1;
9769
9770 remote_state *rs = get_remote_state ();
9771
9772 /* Tell the remote target to detach. */
9773 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9774 putpkt (rs->buf);
9775 getpkt (&rs->buf, &rs->buf_size, 0);
9776
9777 switch (packet_ok (rs->buf,
9778 &remote_protocol_packets[PACKET_vKill]))
9779 {
9780 case PACKET_OK:
9781 return 0;
9782 case PACKET_ERROR:
9783 return 1;
9784 case PACKET_UNKNOWN:
9785 return -1;
9786 default:
9787 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9788 }
9789 }
9790
9791 /* Send a kill request to the target using the 'k' packet. */
9792
9793 void
9794 remote_target::remote_kill_k ()
9795 {
9796 /* Catch errors so the user can quit from gdb even when we
9797 aren't on speaking terms with the remote system. */
9798 TRY
9799 {
9800 putpkt ("k");
9801 }
9802 CATCH (ex, RETURN_MASK_ERROR)
9803 {
9804 if (ex.error == TARGET_CLOSE_ERROR)
9805 {
9806 /* If we got an (EOF) error that caused the target
9807 to go away, then we're done, that's what we wanted.
9808 "k" is susceptible to cause a premature EOF, given
9809 that the remote server isn't actually required to
9810 reply to "k", and it can happen that it doesn't
9811 even get to reply ACK to the "k". */
9812 return;
9813 }
9814
9815 /* Otherwise, something went wrong. We didn't actually kill
9816 the target. Just propagate the exception, and let the
9817 user or higher layers decide what to do. */
9818 throw_exception (ex);
9819 }
9820 END_CATCH
9821 }
9822
9823 void
9824 remote_target::mourn_inferior ()
9825 {
9826 struct remote_state *rs = get_remote_state ();
9827
9828 /* We're no longer interested in notification events of an inferior
9829 that exited or was killed/detached. */
9830 discard_pending_stop_replies (current_inferior ());
9831
9832 /* In 'target remote' mode with one inferior, we close the connection. */
9833 if (!rs->extended && number_of_live_inferiors () <= 1)
9834 {
9835 unpush_target (this);
9836
9837 /* remote_close takes care of doing most of the clean up. */
9838 generic_mourn_inferior ();
9839 return;
9840 }
9841
9842 /* In case we got here due to an error, but we're going to stay
9843 connected. */
9844 rs->waiting_for_stop_reply = 0;
9845
9846 /* If the current general thread belonged to the process we just
9847 detached from or has exited, the remote side current general
9848 thread becomes undefined. Considering a case like this:
9849
9850 - We just got here due to a detach.
9851 - The process that we're detaching from happens to immediately
9852 report a global breakpoint being hit in non-stop mode, in the
9853 same thread we had selected before.
9854 - GDB attaches to this process again.
9855 - This event happens to be the next event we handle.
9856
9857 GDB would consider that the current general thread didn't need to
9858 be set on the stub side (with Hg), since for all it knew,
9859 GENERAL_THREAD hadn't changed.
9860
9861 Notice that although in all-stop mode, the remote server always
9862 sets the current thread to the thread reporting the stop event,
9863 that doesn't happen in non-stop mode; in non-stop, the stub *must
9864 not* change the current thread when reporting a breakpoint hit,
9865 due to the decoupling of event reporting and event handling.
9866
9867 To keep things simple, we always invalidate our notion of the
9868 current thread. */
9869 record_currthread (rs, minus_one_ptid);
9870
9871 /* Call common code to mark the inferior as not running. */
9872 generic_mourn_inferior ();
9873
9874 if (!have_inferiors ())
9875 {
9876 if (!remote_multi_process_p (rs))
9877 {
9878 /* Check whether the target is running now - some remote stubs
9879 automatically restart after kill. */
9880 putpkt ("?");
9881 getpkt (&rs->buf, &rs->buf_size, 0);
9882
9883 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9884 {
9885 /* Assume that the target has been restarted. Set
9886 inferior_ptid so that bits of core GDB realizes
9887 there's something here, e.g., so that the user can
9888 say "kill" again. */
9889 inferior_ptid = magic_null_ptid;
9890 }
9891 }
9892 }
9893 }
9894
9895 bool
9896 extended_remote_target::supports_disable_randomization ()
9897 {
9898 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9899 }
9900
9901 void
9902 remote_target::extended_remote_disable_randomization (int val)
9903 {
9904 struct remote_state *rs = get_remote_state ();
9905 char *reply;
9906
9907 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9908 val);
9909 putpkt (rs->buf);
9910 reply = remote_get_noisy_reply ();
9911 if (*reply == '\0')
9912 error (_("Target does not support QDisableRandomization."));
9913 if (strcmp (reply, "OK") != 0)
9914 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9915 }
9916
9917 int
9918 remote_target::extended_remote_run (const std::string &args)
9919 {
9920 struct remote_state *rs = get_remote_state ();
9921 int len;
9922 const char *remote_exec_file = get_remote_exec_file ();
9923
9924 /* If the user has disabled vRun support, or we have detected that
9925 support is not available, do not try it. */
9926 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9927 return -1;
9928
9929 strcpy (rs->buf, "vRun;");
9930 len = strlen (rs->buf);
9931
9932 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9933 error (_("Remote file name too long for run packet"));
9934 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9935 strlen (remote_exec_file));
9936
9937 if (!args.empty ())
9938 {
9939 int i;
9940
9941 gdb_argv argv (args.c_str ());
9942 for (i = 0; argv[i] != NULL; i++)
9943 {
9944 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9945 error (_("Argument list too long for run packet"));
9946 rs->buf[len++] = ';';
9947 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9948 strlen (argv[i]));
9949 }
9950 }
9951
9952 rs->buf[len++] = '\0';
9953
9954 putpkt (rs->buf);
9955 getpkt (&rs->buf, &rs->buf_size, 0);
9956
9957 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9958 {
9959 case PACKET_OK:
9960 /* We have a wait response. All is well. */
9961 return 0;
9962 case PACKET_UNKNOWN:
9963 return -1;
9964 case PACKET_ERROR:
9965 if (remote_exec_file[0] == '\0')
9966 error (_("Running the default executable on the remote target failed; "
9967 "try \"set remote exec-file\"?"));
9968 else
9969 error (_("Running \"%s\" on the remote target failed"),
9970 remote_exec_file);
9971 default:
9972 gdb_assert_not_reached (_("bad switch"));
9973 }
9974 }
9975
9976 /* Helper function to send set/unset environment packets. ACTION is
9977 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9978 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9979 sent. */
9980
9981 void
9982 remote_target::send_environment_packet (const char *action,
9983 const char *packet,
9984 const char *value)
9985 {
9986 remote_state *rs = get_remote_state ();
9987
9988 /* Convert the environment variable to an hex string, which
9989 is the best format to be transmitted over the wire. */
9990 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9991 strlen (value));
9992
9993 xsnprintf (rs->buf, get_remote_packet_size (),
9994 "%s:%s", packet, encoded_value.c_str ());
9995
9996 putpkt (rs->buf);
9997 getpkt (&rs->buf, &rs->buf_size, 0);
9998 if (strcmp (rs->buf, "OK") != 0)
9999 warning (_("Unable to %s environment variable '%s' on remote."),
10000 action, value);
10001 }
10002
10003 /* Helper function to handle the QEnvironment* packets. */
10004
10005 void
10006 remote_target::extended_remote_environment_support ()
10007 {
10008 remote_state *rs = get_remote_state ();
10009
10010 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10011 {
10012 putpkt ("QEnvironmentReset");
10013 getpkt (&rs->buf, &rs->buf_size, 0);
10014 if (strcmp (rs->buf, "OK") != 0)
10015 warning (_("Unable to reset environment on remote."));
10016 }
10017
10018 gdb_environ *e = &current_inferior ()->environment;
10019
10020 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10021 for (const std::string &el : e->user_set_env ())
10022 send_environment_packet ("set", "QEnvironmentHexEncoded",
10023 el.c_str ());
10024
10025 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10026 for (const std::string &el : e->user_unset_env ())
10027 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10028 }
10029
10030 /* Helper function to set the current working directory for the
10031 inferior in the remote target. */
10032
10033 void
10034 remote_target::extended_remote_set_inferior_cwd ()
10035 {
10036 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10037 {
10038 const char *inferior_cwd = get_inferior_cwd ();
10039 remote_state *rs = get_remote_state ();
10040
10041 if (inferior_cwd != NULL)
10042 {
10043 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10044 strlen (inferior_cwd));
10045
10046 xsnprintf (rs->buf, get_remote_packet_size (),
10047 "QSetWorkingDir:%s", hexpath.c_str ());
10048 }
10049 else
10050 {
10051 /* An empty inferior_cwd means that the user wants us to
10052 reset the remote server's inferior's cwd. */
10053 xsnprintf (rs->buf, get_remote_packet_size (),
10054 "QSetWorkingDir:");
10055 }
10056
10057 putpkt (rs->buf);
10058 getpkt (&rs->buf, &rs->buf_size, 0);
10059 if (packet_ok (rs->buf,
10060 &remote_protocol_packets[PACKET_QSetWorkingDir])
10061 != PACKET_OK)
10062 error (_("\
10063 Remote replied unexpectedly while setting the inferior's working\n\
10064 directory: %s"),
10065 rs->buf);
10066
10067 }
10068 }
10069
10070 /* In the extended protocol we want to be able to do things like
10071 "run" and have them basically work as expected. So we need
10072 a special create_inferior function. We support changing the
10073 executable file and the command line arguments, but not the
10074 environment. */
10075
10076 void
10077 extended_remote_target::create_inferior (const char *exec_file,
10078 const std::string &args,
10079 char **env, int from_tty)
10080 {
10081 int run_worked;
10082 char *stop_reply;
10083 struct remote_state *rs = get_remote_state ();
10084 const char *remote_exec_file = get_remote_exec_file ();
10085
10086 /* If running asynchronously, register the target file descriptor
10087 with the event loop. */
10088 if (target_can_async_p ())
10089 target_async (1);
10090
10091 /* Disable address space randomization if requested (and supported). */
10092 if (supports_disable_randomization ())
10093 extended_remote_disable_randomization (disable_randomization);
10094
10095 /* If startup-with-shell is on, we inform gdbserver to start the
10096 remote inferior using a shell. */
10097 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10098 {
10099 xsnprintf (rs->buf, get_remote_packet_size (),
10100 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10101 putpkt (rs->buf);
10102 getpkt (&rs->buf, &rs->buf_size, 0);
10103 if (strcmp (rs->buf, "OK") != 0)
10104 error (_("\
10105 Remote replied unexpectedly while setting startup-with-shell: %s"),
10106 rs->buf);
10107 }
10108
10109 extended_remote_environment_support ();
10110
10111 extended_remote_set_inferior_cwd ();
10112
10113 /* Now restart the remote server. */
10114 run_worked = extended_remote_run (args) != -1;
10115 if (!run_worked)
10116 {
10117 /* vRun was not supported. Fail if we need it to do what the
10118 user requested. */
10119 if (remote_exec_file[0])
10120 error (_("Remote target does not support \"set remote exec-file\""));
10121 if (!args.empty ())
10122 error (_("Remote target does not support \"set args\" or run <ARGS>"));
10123
10124 /* Fall back to "R". */
10125 extended_remote_restart ();
10126 }
10127
10128 if (!have_inferiors ())
10129 {
10130 /* Clean up from the last time we ran, before we mark the target
10131 running again. This will mark breakpoints uninserted, and
10132 get_offsets may insert breakpoints. */
10133 init_thread_list ();
10134 init_wait_for_inferior ();
10135 }
10136
10137 /* vRun's success return is a stop reply. */
10138 stop_reply = run_worked ? rs->buf : NULL;
10139 add_current_inferior_and_thread (stop_reply);
10140
10141 /* Get updated offsets, if the stub uses qOffsets. */
10142 get_offsets ();
10143 }
10144 \f
10145
10146 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10147 the list of conditions (in agent expression bytecode format), if any, the
10148 target needs to evaluate. The output is placed into the packet buffer
10149 started from BUF and ended at BUF_END. */
10150
10151 static int
10152 remote_add_target_side_condition (struct gdbarch *gdbarch,
10153 struct bp_target_info *bp_tgt, char *buf,
10154 char *buf_end)
10155 {
10156 if (bp_tgt->conditions.empty ())
10157 return 0;
10158
10159 buf += strlen (buf);
10160 xsnprintf (buf, buf_end - buf, "%s", ";");
10161 buf++;
10162
10163 /* Send conditions to the target. */
10164 for (agent_expr *aexpr : bp_tgt->conditions)
10165 {
10166 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10167 buf += strlen (buf);
10168 for (int i = 0; i < aexpr->len; ++i)
10169 buf = pack_hex_byte (buf, aexpr->buf[i]);
10170 *buf = '\0';
10171 }
10172 return 0;
10173 }
10174
10175 static void
10176 remote_add_target_side_commands (struct gdbarch *gdbarch,
10177 struct bp_target_info *bp_tgt, char *buf)
10178 {
10179 if (bp_tgt->tcommands.empty ())
10180 return;
10181
10182 buf += strlen (buf);
10183
10184 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10185 buf += strlen (buf);
10186
10187 /* Concatenate all the agent expressions that are commands into the
10188 cmds parameter. */
10189 for (agent_expr *aexpr : bp_tgt->tcommands)
10190 {
10191 sprintf (buf, "X%x,", aexpr->len);
10192 buf += strlen (buf);
10193 for (int i = 0; i < aexpr->len; ++i)
10194 buf = pack_hex_byte (buf, aexpr->buf[i]);
10195 *buf = '\0';
10196 }
10197 }
10198
10199 /* Insert a breakpoint. On targets that have software breakpoint
10200 support, we ask the remote target to do the work; on targets
10201 which don't, we insert a traditional memory breakpoint. */
10202
10203 int
10204 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10205 struct bp_target_info *bp_tgt)
10206 {
10207 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10208 If it succeeds, then set the support to PACKET_ENABLE. If it
10209 fails, and the user has explicitly requested the Z support then
10210 report an error, otherwise, mark it disabled and go on. */
10211
10212 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10213 {
10214 CORE_ADDR addr = bp_tgt->reqstd_address;
10215 struct remote_state *rs;
10216 char *p, *endbuf;
10217
10218 /* Make sure the remote is pointing at the right process, if
10219 necessary. */
10220 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10221 set_general_process ();
10222
10223 rs = get_remote_state ();
10224 p = rs->buf;
10225 endbuf = rs->buf + get_remote_packet_size ();
10226
10227 *(p++) = 'Z';
10228 *(p++) = '0';
10229 *(p++) = ',';
10230 addr = (ULONGEST) remote_address_masked (addr);
10231 p += hexnumstr (p, addr);
10232 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10233
10234 if (supports_evaluation_of_breakpoint_conditions ())
10235 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10236
10237 if (can_run_breakpoint_commands ())
10238 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10239
10240 putpkt (rs->buf);
10241 getpkt (&rs->buf, &rs->buf_size, 0);
10242
10243 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10244 {
10245 case PACKET_ERROR:
10246 return -1;
10247 case PACKET_OK:
10248 return 0;
10249 case PACKET_UNKNOWN:
10250 break;
10251 }
10252 }
10253
10254 /* If this breakpoint has target-side commands but this stub doesn't
10255 support Z0 packets, throw error. */
10256 if (!bp_tgt->tcommands.empty ())
10257 throw_error (NOT_SUPPORTED_ERROR, _("\
10258 Target doesn't support breakpoints that have target side commands."));
10259
10260 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10261 }
10262
10263 int
10264 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10265 struct bp_target_info *bp_tgt,
10266 enum remove_bp_reason reason)
10267 {
10268 CORE_ADDR addr = bp_tgt->placed_address;
10269 struct remote_state *rs = get_remote_state ();
10270
10271 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10272 {
10273 char *p = rs->buf;
10274 char *endbuf = rs->buf + get_remote_packet_size ();
10275
10276 /* Make sure the remote is pointing at the right process, if
10277 necessary. */
10278 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10279 set_general_process ();
10280
10281 *(p++) = 'z';
10282 *(p++) = '0';
10283 *(p++) = ',';
10284
10285 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10286 p += hexnumstr (p, addr);
10287 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10288
10289 putpkt (rs->buf);
10290 getpkt (&rs->buf, &rs->buf_size, 0);
10291
10292 return (rs->buf[0] == 'E');
10293 }
10294
10295 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10296 }
10297
10298 static enum Z_packet_type
10299 watchpoint_to_Z_packet (int type)
10300 {
10301 switch (type)
10302 {
10303 case hw_write:
10304 return Z_PACKET_WRITE_WP;
10305 break;
10306 case hw_read:
10307 return Z_PACKET_READ_WP;
10308 break;
10309 case hw_access:
10310 return Z_PACKET_ACCESS_WP;
10311 break;
10312 default:
10313 internal_error (__FILE__, __LINE__,
10314 _("hw_bp_to_z: bad watchpoint type %d"), type);
10315 }
10316 }
10317
10318 int
10319 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10320 enum target_hw_bp_type type, struct expression *cond)
10321 {
10322 struct remote_state *rs = get_remote_state ();
10323 char *endbuf = rs->buf + get_remote_packet_size ();
10324 char *p;
10325 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10326
10327 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10328 return 1;
10329
10330 /* Make sure the remote is pointing at the right process, if
10331 necessary. */
10332 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10333 set_general_process ();
10334
10335 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10336 p = strchr (rs->buf, '\0');
10337 addr = remote_address_masked (addr);
10338 p += hexnumstr (p, (ULONGEST) addr);
10339 xsnprintf (p, endbuf - p, ",%x", len);
10340
10341 putpkt (rs->buf);
10342 getpkt (&rs->buf, &rs->buf_size, 0);
10343
10344 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10345 {
10346 case PACKET_ERROR:
10347 return -1;
10348 case PACKET_UNKNOWN:
10349 return 1;
10350 case PACKET_OK:
10351 return 0;
10352 }
10353 internal_error (__FILE__, __LINE__,
10354 _("remote_insert_watchpoint: reached end of function"));
10355 }
10356
10357 bool
10358 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10359 CORE_ADDR start, int length)
10360 {
10361 CORE_ADDR diff = remote_address_masked (addr - start);
10362
10363 return diff < length;
10364 }
10365
10366
10367 int
10368 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10369 enum target_hw_bp_type type, struct expression *cond)
10370 {
10371 struct remote_state *rs = get_remote_state ();
10372 char *endbuf = rs->buf + get_remote_packet_size ();
10373 char *p;
10374 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10375
10376 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10377 return -1;
10378
10379 /* Make sure the remote is pointing at the right process, if
10380 necessary. */
10381 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10382 set_general_process ();
10383
10384 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10385 p = strchr (rs->buf, '\0');
10386 addr = remote_address_masked (addr);
10387 p += hexnumstr (p, (ULONGEST) addr);
10388 xsnprintf (p, endbuf - p, ",%x", len);
10389 putpkt (rs->buf);
10390 getpkt (&rs->buf, &rs->buf_size, 0);
10391
10392 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10393 {
10394 case PACKET_ERROR:
10395 case PACKET_UNKNOWN:
10396 return -1;
10397 case PACKET_OK:
10398 return 0;
10399 }
10400 internal_error (__FILE__, __LINE__,
10401 _("remote_remove_watchpoint: reached end of function"));
10402 }
10403
10404
10405 int remote_hw_watchpoint_limit = -1;
10406 int remote_hw_watchpoint_length_limit = -1;
10407 int remote_hw_breakpoint_limit = -1;
10408
10409 int
10410 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10411 {
10412 if (remote_hw_watchpoint_length_limit == 0)
10413 return 0;
10414 else if (remote_hw_watchpoint_length_limit < 0)
10415 return 1;
10416 else if (len <= remote_hw_watchpoint_length_limit)
10417 return 1;
10418 else
10419 return 0;
10420 }
10421
10422 int
10423 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10424 {
10425 if (type == bp_hardware_breakpoint)
10426 {
10427 if (remote_hw_breakpoint_limit == 0)
10428 return 0;
10429 else if (remote_hw_breakpoint_limit < 0)
10430 return 1;
10431 else if (cnt <= remote_hw_breakpoint_limit)
10432 return 1;
10433 }
10434 else
10435 {
10436 if (remote_hw_watchpoint_limit == 0)
10437 return 0;
10438 else if (remote_hw_watchpoint_limit < 0)
10439 return 1;
10440 else if (ot)
10441 return -1;
10442 else if (cnt <= remote_hw_watchpoint_limit)
10443 return 1;
10444 }
10445 return -1;
10446 }
10447
10448 /* The to_stopped_by_sw_breakpoint method of target remote. */
10449
10450 bool
10451 remote_target::stopped_by_sw_breakpoint ()
10452 {
10453 struct thread_info *thread = inferior_thread ();
10454
10455 return (thread->priv != NULL
10456 && (get_remote_thread_info (thread)->stop_reason
10457 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10458 }
10459
10460 /* The to_supports_stopped_by_sw_breakpoint method of target
10461 remote. */
10462
10463 bool
10464 remote_target::supports_stopped_by_sw_breakpoint ()
10465 {
10466 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10467 }
10468
10469 /* The to_stopped_by_hw_breakpoint method of target remote. */
10470
10471 bool
10472 remote_target::stopped_by_hw_breakpoint ()
10473 {
10474 struct thread_info *thread = inferior_thread ();
10475
10476 return (thread->priv != NULL
10477 && (get_remote_thread_info (thread)->stop_reason
10478 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10479 }
10480
10481 /* The to_supports_stopped_by_hw_breakpoint method of target
10482 remote. */
10483
10484 bool
10485 remote_target::supports_stopped_by_hw_breakpoint ()
10486 {
10487 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10488 }
10489
10490 bool
10491 remote_target::stopped_by_watchpoint ()
10492 {
10493 struct thread_info *thread = inferior_thread ();
10494
10495 return (thread->priv != NULL
10496 && (get_remote_thread_info (thread)->stop_reason
10497 == TARGET_STOPPED_BY_WATCHPOINT));
10498 }
10499
10500 bool
10501 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10502 {
10503 struct thread_info *thread = inferior_thread ();
10504
10505 if (thread->priv != NULL
10506 && (get_remote_thread_info (thread)->stop_reason
10507 == TARGET_STOPPED_BY_WATCHPOINT))
10508 {
10509 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10510 return true;
10511 }
10512
10513 return false;
10514 }
10515
10516
10517 int
10518 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10519 struct bp_target_info *bp_tgt)
10520 {
10521 CORE_ADDR addr = bp_tgt->reqstd_address;
10522 struct remote_state *rs;
10523 char *p, *endbuf;
10524 char *message;
10525
10526 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10527 return -1;
10528
10529 /* Make sure the remote is pointing at the right process, if
10530 necessary. */
10531 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10532 set_general_process ();
10533
10534 rs = get_remote_state ();
10535 p = rs->buf;
10536 endbuf = rs->buf + get_remote_packet_size ();
10537
10538 *(p++) = 'Z';
10539 *(p++) = '1';
10540 *(p++) = ',';
10541
10542 addr = remote_address_masked (addr);
10543 p += hexnumstr (p, (ULONGEST) addr);
10544 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10545
10546 if (supports_evaluation_of_breakpoint_conditions ())
10547 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10548
10549 if (can_run_breakpoint_commands ())
10550 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10551
10552 putpkt (rs->buf);
10553 getpkt (&rs->buf, &rs->buf_size, 0);
10554
10555 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10556 {
10557 case PACKET_ERROR:
10558 if (rs->buf[1] == '.')
10559 {
10560 message = strchr (rs->buf + 2, '.');
10561 if (message)
10562 error (_("Remote failure reply: %s"), message + 1);
10563 }
10564 return -1;
10565 case PACKET_UNKNOWN:
10566 return -1;
10567 case PACKET_OK:
10568 return 0;
10569 }
10570 internal_error (__FILE__, __LINE__,
10571 _("remote_insert_hw_breakpoint: reached end of function"));
10572 }
10573
10574
10575 int
10576 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10577 struct bp_target_info *bp_tgt)
10578 {
10579 CORE_ADDR addr;
10580 struct remote_state *rs = get_remote_state ();
10581 char *p = rs->buf;
10582 char *endbuf = rs->buf + get_remote_packet_size ();
10583
10584 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10585 return -1;
10586
10587 /* Make sure the remote is pointing at the right process, if
10588 necessary. */
10589 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10590 set_general_process ();
10591
10592 *(p++) = 'z';
10593 *(p++) = '1';
10594 *(p++) = ',';
10595
10596 addr = remote_address_masked (bp_tgt->placed_address);
10597 p += hexnumstr (p, (ULONGEST) addr);
10598 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10599
10600 putpkt (rs->buf);
10601 getpkt (&rs->buf, &rs->buf_size, 0);
10602
10603 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10604 {
10605 case PACKET_ERROR:
10606 case PACKET_UNKNOWN:
10607 return -1;
10608 case PACKET_OK:
10609 return 0;
10610 }
10611 internal_error (__FILE__, __LINE__,
10612 _("remote_remove_hw_breakpoint: reached end of function"));
10613 }
10614
10615 /* Verify memory using the "qCRC:" request. */
10616
10617 int
10618 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10619 {
10620 struct remote_state *rs = get_remote_state ();
10621 unsigned long host_crc, target_crc;
10622 char *tmp;
10623
10624 /* It doesn't make sense to use qCRC if the remote target is
10625 connected but not running. */
10626 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10627 {
10628 enum packet_result result;
10629
10630 /* Make sure the remote is pointing at the right process. */
10631 set_general_process ();
10632
10633 /* FIXME: assumes lma can fit into long. */
10634 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10635 (long) lma, (long) size);
10636 putpkt (rs->buf);
10637
10638 /* Be clever; compute the host_crc before waiting for target
10639 reply. */
10640 host_crc = xcrc32 (data, size, 0xffffffff);
10641
10642 getpkt (&rs->buf, &rs->buf_size, 0);
10643
10644 result = packet_ok (rs->buf,
10645 &remote_protocol_packets[PACKET_qCRC]);
10646 if (result == PACKET_ERROR)
10647 return -1;
10648 else if (result == PACKET_OK)
10649 {
10650 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10651 target_crc = target_crc * 16 + fromhex (*tmp);
10652
10653 return (host_crc == target_crc);
10654 }
10655 }
10656
10657 return simple_verify_memory (this, data, lma, size);
10658 }
10659
10660 /* compare-sections command
10661
10662 With no arguments, compares each loadable section in the exec bfd
10663 with the same memory range on the target, and reports mismatches.
10664 Useful for verifying the image on the target against the exec file. */
10665
10666 static void
10667 compare_sections_command (const char *args, int from_tty)
10668 {
10669 asection *s;
10670 const char *sectname;
10671 bfd_size_type size;
10672 bfd_vma lma;
10673 int matched = 0;
10674 int mismatched = 0;
10675 int res;
10676 int read_only = 0;
10677
10678 if (!exec_bfd)
10679 error (_("command cannot be used without an exec file"));
10680
10681 if (args != NULL && strcmp (args, "-r") == 0)
10682 {
10683 read_only = 1;
10684 args = NULL;
10685 }
10686
10687 for (s = exec_bfd->sections; s; s = s->next)
10688 {
10689 if (!(s->flags & SEC_LOAD))
10690 continue; /* Skip non-loadable section. */
10691
10692 if (read_only && (s->flags & SEC_READONLY) == 0)
10693 continue; /* Skip writeable sections */
10694
10695 size = bfd_get_section_size (s);
10696 if (size == 0)
10697 continue; /* Skip zero-length section. */
10698
10699 sectname = bfd_get_section_name (exec_bfd, s);
10700 if (args && strcmp (args, sectname) != 0)
10701 continue; /* Not the section selected by user. */
10702
10703 matched = 1; /* Do this section. */
10704 lma = s->lma;
10705
10706 gdb::byte_vector sectdata (size);
10707 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10708
10709 res = target_verify_memory (sectdata.data (), lma, size);
10710
10711 if (res == -1)
10712 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10713 paddress (target_gdbarch (), lma),
10714 paddress (target_gdbarch (), lma + size));
10715
10716 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10717 paddress (target_gdbarch (), lma),
10718 paddress (target_gdbarch (), lma + size));
10719 if (res)
10720 printf_filtered ("matched.\n");
10721 else
10722 {
10723 printf_filtered ("MIS-MATCHED!\n");
10724 mismatched++;
10725 }
10726 }
10727 if (mismatched > 0)
10728 warning (_("One or more sections of the target image does not match\n\
10729 the loaded file\n"));
10730 if (args && !matched)
10731 printf_filtered (_("No loaded section named '%s'.\n"), args);
10732 }
10733
10734 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10735 into remote target. The number of bytes written to the remote
10736 target is returned, or -1 for error. */
10737
10738 target_xfer_status
10739 remote_target::remote_write_qxfer (const char *object_name,
10740 const char *annex, const gdb_byte *writebuf,
10741 ULONGEST offset, LONGEST len,
10742 ULONGEST *xfered_len,
10743 struct packet_config *packet)
10744 {
10745 int i, buf_len;
10746 ULONGEST n;
10747 struct remote_state *rs = get_remote_state ();
10748 int max_size = get_memory_write_packet_size ();
10749
10750 if (packet_config_support (packet) == PACKET_DISABLE)
10751 return TARGET_XFER_E_IO;
10752
10753 /* Insert header. */
10754 i = snprintf (rs->buf, max_size,
10755 "qXfer:%s:write:%s:%s:",
10756 object_name, annex ? annex : "",
10757 phex_nz (offset, sizeof offset));
10758 max_size -= (i + 1);
10759
10760 /* Escape as much data as fits into rs->buf. */
10761 buf_len = remote_escape_output
10762 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10763
10764 if (putpkt_binary (rs->buf, i + buf_len) < 0
10765 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10766 || packet_ok (rs->buf, packet) != PACKET_OK)
10767 return TARGET_XFER_E_IO;
10768
10769 unpack_varlen_hex (rs->buf, &n);
10770
10771 *xfered_len = n;
10772 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10773 }
10774
10775 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10776 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10777 number of bytes read is returned, or 0 for EOF, or -1 for error.
10778 The number of bytes read may be less than LEN without indicating an
10779 EOF. PACKET is checked and updated to indicate whether the remote
10780 target supports this object. */
10781
10782 target_xfer_status
10783 remote_target::remote_read_qxfer (const char *object_name,
10784 const char *annex,
10785 gdb_byte *readbuf, ULONGEST offset,
10786 LONGEST len,
10787 ULONGEST *xfered_len,
10788 struct packet_config *packet)
10789 {
10790 struct remote_state *rs = get_remote_state ();
10791 LONGEST i, n, packet_len;
10792
10793 if (packet_config_support (packet) == PACKET_DISABLE)
10794 return TARGET_XFER_E_IO;
10795
10796 /* Check whether we've cached an end-of-object packet that matches
10797 this request. */
10798 if (rs->finished_object)
10799 {
10800 if (strcmp (object_name, rs->finished_object) == 0
10801 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10802 && offset == rs->finished_offset)
10803 return TARGET_XFER_EOF;
10804
10805
10806 /* Otherwise, we're now reading something different. Discard
10807 the cache. */
10808 xfree (rs->finished_object);
10809 xfree (rs->finished_annex);
10810 rs->finished_object = NULL;
10811 rs->finished_annex = NULL;
10812 }
10813
10814 /* Request only enough to fit in a single packet. The actual data
10815 may not, since we don't know how much of it will need to be escaped;
10816 the target is free to respond with slightly less data. We subtract
10817 five to account for the response type and the protocol frame. */
10818 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10819 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10820 object_name, annex ? annex : "",
10821 phex_nz (offset, sizeof offset),
10822 phex_nz (n, sizeof n));
10823 i = putpkt (rs->buf);
10824 if (i < 0)
10825 return TARGET_XFER_E_IO;
10826
10827 rs->buf[0] = '\0';
10828 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10829 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10830 return TARGET_XFER_E_IO;
10831
10832 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10833 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10834
10835 /* 'm' means there is (or at least might be) more data after this
10836 batch. That does not make sense unless there's at least one byte
10837 of data in this reply. */
10838 if (rs->buf[0] == 'm' && packet_len == 1)
10839 error (_("Remote qXfer reply contained no data."));
10840
10841 /* Got some data. */
10842 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10843 packet_len - 1, readbuf, n);
10844
10845 /* 'l' is an EOF marker, possibly including a final block of data,
10846 or possibly empty. If we have the final block of a non-empty
10847 object, record this fact to bypass a subsequent partial read. */
10848 if (rs->buf[0] == 'l' && offset + i > 0)
10849 {
10850 rs->finished_object = xstrdup (object_name);
10851 rs->finished_annex = xstrdup (annex ? annex : "");
10852 rs->finished_offset = offset + i;
10853 }
10854
10855 if (i == 0)
10856 return TARGET_XFER_EOF;
10857 else
10858 {
10859 *xfered_len = i;
10860 return TARGET_XFER_OK;
10861 }
10862 }
10863
10864 enum target_xfer_status
10865 remote_target::xfer_partial (enum target_object object,
10866 const char *annex, gdb_byte *readbuf,
10867 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10868 ULONGEST *xfered_len)
10869 {
10870 struct remote_state *rs;
10871 int i;
10872 char *p2;
10873 char query_type;
10874 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10875
10876 set_remote_traceframe ();
10877 set_general_thread (inferior_ptid);
10878
10879 rs = get_remote_state ();
10880
10881 /* Handle memory using the standard memory routines. */
10882 if (object == TARGET_OBJECT_MEMORY)
10883 {
10884 /* If the remote target is connected but not running, we should
10885 pass this request down to a lower stratum (e.g. the executable
10886 file). */
10887 if (!target_has_execution)
10888 return TARGET_XFER_EOF;
10889
10890 if (writebuf != NULL)
10891 return remote_write_bytes (offset, writebuf, len, unit_size,
10892 xfered_len);
10893 else
10894 return remote_read_bytes (offset, readbuf, len, unit_size,
10895 xfered_len);
10896 }
10897
10898 /* Handle SPU memory using qxfer packets. */
10899 if (object == TARGET_OBJECT_SPU)
10900 {
10901 if (readbuf)
10902 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10903 xfered_len, &remote_protocol_packets
10904 [PACKET_qXfer_spu_read]);
10905 else
10906 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10907 xfered_len, &remote_protocol_packets
10908 [PACKET_qXfer_spu_write]);
10909 }
10910
10911 /* Handle extra signal info using qxfer packets. */
10912 if (object == TARGET_OBJECT_SIGNAL_INFO)
10913 {
10914 if (readbuf)
10915 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10916 xfered_len, &remote_protocol_packets
10917 [PACKET_qXfer_siginfo_read]);
10918 else
10919 return remote_write_qxfer ("siginfo", annex,
10920 writebuf, offset, len, xfered_len,
10921 &remote_protocol_packets
10922 [PACKET_qXfer_siginfo_write]);
10923 }
10924
10925 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10926 {
10927 if (readbuf)
10928 return remote_read_qxfer ("statictrace", annex,
10929 readbuf, offset, len, xfered_len,
10930 &remote_protocol_packets
10931 [PACKET_qXfer_statictrace_read]);
10932 else
10933 return TARGET_XFER_E_IO;
10934 }
10935
10936 /* Only handle flash writes. */
10937 if (writebuf != NULL)
10938 {
10939 switch (object)
10940 {
10941 case TARGET_OBJECT_FLASH:
10942 return remote_flash_write (offset, len, xfered_len,
10943 writebuf);
10944
10945 default:
10946 return TARGET_XFER_E_IO;
10947 }
10948 }
10949
10950 /* Map pre-existing objects onto letters. DO NOT do this for new
10951 objects!!! Instead specify new query packets. */
10952 switch (object)
10953 {
10954 case TARGET_OBJECT_AVR:
10955 query_type = 'R';
10956 break;
10957
10958 case TARGET_OBJECT_AUXV:
10959 gdb_assert (annex == NULL);
10960 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10961 xfered_len,
10962 &remote_protocol_packets[PACKET_qXfer_auxv]);
10963
10964 case TARGET_OBJECT_AVAILABLE_FEATURES:
10965 return remote_read_qxfer
10966 ("features", annex, readbuf, offset, len, xfered_len,
10967 &remote_protocol_packets[PACKET_qXfer_features]);
10968
10969 case TARGET_OBJECT_LIBRARIES:
10970 return remote_read_qxfer
10971 ("libraries", annex, readbuf, offset, len, xfered_len,
10972 &remote_protocol_packets[PACKET_qXfer_libraries]);
10973
10974 case TARGET_OBJECT_LIBRARIES_SVR4:
10975 return remote_read_qxfer
10976 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10977 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10978
10979 case TARGET_OBJECT_MEMORY_MAP:
10980 gdb_assert (annex == NULL);
10981 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10982 xfered_len,
10983 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10984
10985 case TARGET_OBJECT_OSDATA:
10986 /* Should only get here if we're connected. */
10987 gdb_assert (rs->remote_desc);
10988 return remote_read_qxfer
10989 ("osdata", annex, readbuf, offset, len, xfered_len,
10990 &remote_protocol_packets[PACKET_qXfer_osdata]);
10991
10992 case TARGET_OBJECT_THREADS:
10993 gdb_assert (annex == NULL);
10994 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10995 xfered_len,
10996 &remote_protocol_packets[PACKET_qXfer_threads]);
10997
10998 case TARGET_OBJECT_TRACEFRAME_INFO:
10999 gdb_assert (annex == NULL);
11000 return remote_read_qxfer
11001 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11002 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11003
11004 case TARGET_OBJECT_FDPIC:
11005 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11006 xfered_len,
11007 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11008
11009 case TARGET_OBJECT_OPENVMS_UIB:
11010 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11011 xfered_len,
11012 &remote_protocol_packets[PACKET_qXfer_uib]);
11013
11014 case TARGET_OBJECT_BTRACE:
11015 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11016 xfered_len,
11017 &remote_protocol_packets[PACKET_qXfer_btrace]);
11018
11019 case TARGET_OBJECT_BTRACE_CONF:
11020 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11021 len, xfered_len,
11022 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11023
11024 case TARGET_OBJECT_EXEC_FILE:
11025 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11026 len, xfered_len,
11027 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11028
11029 default:
11030 return TARGET_XFER_E_IO;
11031 }
11032
11033 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11034 large enough let the caller deal with it. */
11035 if (len < get_remote_packet_size ())
11036 return TARGET_XFER_E_IO;
11037 len = get_remote_packet_size ();
11038
11039 /* Except for querying the minimum buffer size, target must be open. */
11040 if (!rs->remote_desc)
11041 error (_("remote query is only available after target open"));
11042
11043 gdb_assert (annex != NULL);
11044 gdb_assert (readbuf != NULL);
11045
11046 p2 = rs->buf;
11047 *p2++ = 'q';
11048 *p2++ = query_type;
11049
11050 /* We used one buffer char for the remote protocol q command and
11051 another for the query type. As the remote protocol encapsulation
11052 uses 4 chars plus one extra in case we are debugging
11053 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11054 string. */
11055 i = 0;
11056 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11057 {
11058 /* Bad caller may have sent forbidden characters. */
11059 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11060 *p2++ = annex[i];
11061 i++;
11062 }
11063 *p2 = '\0';
11064 gdb_assert (annex[i] == '\0');
11065
11066 i = putpkt (rs->buf);
11067 if (i < 0)
11068 return TARGET_XFER_E_IO;
11069
11070 getpkt (&rs->buf, &rs->buf_size, 0);
11071 strcpy ((char *) readbuf, rs->buf);
11072
11073 *xfered_len = strlen ((char *) readbuf);
11074 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11075 }
11076
11077 /* Implementation of to_get_memory_xfer_limit. */
11078
11079 ULONGEST
11080 remote_target::get_memory_xfer_limit ()
11081 {
11082 return get_memory_write_packet_size ();
11083 }
11084
11085 int
11086 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11087 const gdb_byte *pattern, ULONGEST pattern_len,
11088 CORE_ADDR *found_addrp)
11089 {
11090 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11091 struct remote_state *rs = get_remote_state ();
11092 int max_size = get_memory_write_packet_size ();
11093 struct packet_config *packet =
11094 &remote_protocol_packets[PACKET_qSearch_memory];
11095 /* Number of packet bytes used to encode the pattern;
11096 this could be more than PATTERN_LEN due to escape characters. */
11097 int escaped_pattern_len;
11098 /* Amount of pattern that was encodable in the packet. */
11099 int used_pattern_len;
11100 int i;
11101 int found;
11102 ULONGEST found_addr;
11103
11104 /* Don't go to the target if we don't have to. This is done before
11105 checking packet_config_support to avoid the possibility that a
11106 success for this edge case means the facility works in
11107 general. */
11108 if (pattern_len > search_space_len)
11109 return 0;
11110 if (pattern_len == 0)
11111 {
11112 *found_addrp = start_addr;
11113 return 1;
11114 }
11115
11116 /* If we already know the packet isn't supported, fall back to the simple
11117 way of searching memory. */
11118
11119 if (packet_config_support (packet) == PACKET_DISABLE)
11120 {
11121 /* Target doesn't provided special support, fall back and use the
11122 standard support (copy memory and do the search here). */
11123 return simple_search_memory (this, start_addr, search_space_len,
11124 pattern, pattern_len, found_addrp);
11125 }
11126
11127 /* Make sure the remote is pointing at the right process. */
11128 set_general_process ();
11129
11130 /* Insert header. */
11131 i = snprintf (rs->buf, max_size,
11132 "qSearch:memory:%s;%s;",
11133 phex_nz (start_addr, addr_size),
11134 phex_nz (search_space_len, sizeof (search_space_len)));
11135 max_size -= (i + 1);
11136
11137 /* Escape as much data as fits into rs->buf. */
11138 escaped_pattern_len =
11139 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
11140 &used_pattern_len, max_size);
11141
11142 /* Bail if the pattern is too large. */
11143 if (used_pattern_len != pattern_len)
11144 error (_("Pattern is too large to transmit to remote target."));
11145
11146 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11147 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11148 || packet_ok (rs->buf, packet) != PACKET_OK)
11149 {
11150 /* The request may not have worked because the command is not
11151 supported. If so, fall back to the simple way. */
11152 if (packet_config_support (packet) == PACKET_DISABLE)
11153 {
11154 return simple_search_memory (this, start_addr, search_space_len,
11155 pattern, pattern_len, found_addrp);
11156 }
11157 return -1;
11158 }
11159
11160 if (rs->buf[0] == '0')
11161 found = 0;
11162 else if (rs->buf[0] == '1')
11163 {
11164 found = 1;
11165 if (rs->buf[1] != ',')
11166 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11167 unpack_varlen_hex (rs->buf + 2, &found_addr);
11168 *found_addrp = found_addr;
11169 }
11170 else
11171 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11172
11173 return found;
11174 }
11175
11176 void
11177 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11178 {
11179 struct remote_state *rs = get_remote_state ();
11180 char *p = rs->buf;
11181
11182 if (!rs->remote_desc)
11183 error (_("remote rcmd is only available after target open"));
11184
11185 /* Send a NULL command across as an empty command. */
11186 if (command == NULL)
11187 command = "";
11188
11189 /* The query prefix. */
11190 strcpy (rs->buf, "qRcmd,");
11191 p = strchr (rs->buf, '\0');
11192
11193 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11194 > get_remote_packet_size ())
11195 error (_("\"monitor\" command ``%s'' is too long."), command);
11196
11197 /* Encode the actual command. */
11198 bin2hex ((const gdb_byte *) command, p, strlen (command));
11199
11200 if (putpkt (rs->buf) < 0)
11201 error (_("Communication problem with target."));
11202
11203 /* get/display the response */
11204 while (1)
11205 {
11206 char *buf;
11207
11208 /* XXX - see also remote_get_noisy_reply(). */
11209 QUIT; /* Allow user to bail out with ^C. */
11210 rs->buf[0] = '\0';
11211 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11212 {
11213 /* Timeout. Continue to (try to) read responses.
11214 This is better than stopping with an error, assuming the stub
11215 is still executing the (long) monitor command.
11216 If needed, the user can interrupt gdb using C-c, obtaining
11217 an effect similar to stop on timeout. */
11218 continue;
11219 }
11220 buf = rs->buf;
11221 if (buf[0] == '\0')
11222 error (_("Target does not support this command."));
11223 if (buf[0] == 'O' && buf[1] != 'K')
11224 {
11225 remote_console_output (buf + 1); /* 'O' message from stub. */
11226 continue;
11227 }
11228 if (strcmp (buf, "OK") == 0)
11229 break;
11230 if (strlen (buf) == 3 && buf[0] == 'E'
11231 && isdigit (buf[1]) && isdigit (buf[2]))
11232 {
11233 error (_("Protocol error with Rcmd"));
11234 }
11235 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11236 {
11237 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11238
11239 fputc_unfiltered (c, outbuf);
11240 }
11241 break;
11242 }
11243 }
11244
11245 std::vector<mem_region>
11246 remote_target::memory_map ()
11247 {
11248 std::vector<mem_region> result;
11249 gdb::optional<gdb::char_vector> text
11250 = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
11251
11252 if (text)
11253 result = parse_memory_map (text->data ());
11254
11255 return result;
11256 }
11257
11258 static void
11259 packet_command (const char *args, int from_tty)
11260 {
11261 remote_target *remote = get_current_remote_target ();
11262
11263 if (remote == nullptr)
11264 error (_("command can only be used with remote target"));
11265
11266 remote->packet_command (args, from_tty);
11267 }
11268
11269 void
11270 remote_target::packet_command (const char *args, int from_tty)
11271 {
11272 if (!args)
11273 error (_("remote-packet command requires packet text as argument"));
11274
11275 puts_filtered ("sending: ");
11276 print_packet (args);
11277 puts_filtered ("\n");
11278 putpkt (args);
11279
11280 remote_state *rs = get_remote_state ();
11281
11282 getpkt (&rs->buf, &rs->buf_size, 0);
11283 puts_filtered ("received: ");
11284 print_packet (rs->buf);
11285 puts_filtered ("\n");
11286 }
11287
11288 #if 0
11289 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11290
11291 static void display_thread_info (struct gdb_ext_thread_info *info);
11292
11293 static void threadset_test_cmd (char *cmd, int tty);
11294
11295 static void threadalive_test (char *cmd, int tty);
11296
11297 static void threadlist_test_cmd (char *cmd, int tty);
11298
11299 int get_and_display_threadinfo (threadref *ref);
11300
11301 static void threadinfo_test_cmd (char *cmd, int tty);
11302
11303 static int thread_display_step (threadref *ref, void *context);
11304
11305 static void threadlist_update_test_cmd (char *cmd, int tty);
11306
11307 static void init_remote_threadtests (void);
11308
11309 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11310
11311 static void
11312 threadset_test_cmd (const char *cmd, int tty)
11313 {
11314 int sample_thread = SAMPLE_THREAD;
11315
11316 printf_filtered (_("Remote threadset test\n"));
11317 set_general_thread (sample_thread);
11318 }
11319
11320
11321 static void
11322 threadalive_test (const char *cmd, int tty)
11323 {
11324 int sample_thread = SAMPLE_THREAD;
11325 int pid = ptid_get_pid (inferior_ptid);
11326 ptid_t ptid = ptid_build (pid, sample_thread, 0);
11327
11328 if (remote_thread_alive (ptid))
11329 printf_filtered ("PASS: Thread alive test\n");
11330 else
11331 printf_filtered ("FAIL: Thread alive test\n");
11332 }
11333
11334 void output_threadid (char *title, threadref *ref);
11335
11336 void
11337 output_threadid (char *title, threadref *ref)
11338 {
11339 char hexid[20];
11340
11341 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
11342 hexid[16] = 0;
11343 printf_filtered ("%s %s\n", title, (&hexid[0]));
11344 }
11345
11346 static void
11347 threadlist_test_cmd (const char *cmd, int tty)
11348 {
11349 int startflag = 1;
11350 threadref nextthread;
11351 int done, result_count;
11352 threadref threadlist[3];
11353
11354 printf_filtered ("Remote Threadlist test\n");
11355 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11356 &result_count, &threadlist[0]))
11357 printf_filtered ("FAIL: threadlist test\n");
11358 else
11359 {
11360 threadref *scan = threadlist;
11361 threadref *limit = scan + result_count;
11362
11363 while (scan < limit)
11364 output_threadid (" thread ", scan++);
11365 }
11366 }
11367
11368 void
11369 display_thread_info (struct gdb_ext_thread_info *info)
11370 {
11371 output_threadid ("Threadid: ", &info->threadid);
11372 printf_filtered ("Name: %s\n ", info->shortname);
11373 printf_filtered ("State: %s\n", info->display);
11374 printf_filtered ("other: %s\n\n", info->more_display);
11375 }
11376
11377 int
11378 get_and_display_threadinfo (threadref *ref)
11379 {
11380 int result;
11381 int set;
11382 struct gdb_ext_thread_info threadinfo;
11383
11384 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11385 | TAG_MOREDISPLAY | TAG_DISPLAY;
11386 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11387 display_thread_info (&threadinfo);
11388 return result;
11389 }
11390
11391 static void
11392 threadinfo_test_cmd (const char *cmd, int tty)
11393 {
11394 int athread = SAMPLE_THREAD;
11395 threadref thread;
11396 int set;
11397
11398 int_to_threadref (&thread, athread);
11399 printf_filtered ("Remote Threadinfo test\n");
11400 if (!get_and_display_threadinfo (&thread))
11401 printf_filtered ("FAIL cannot get thread info\n");
11402 }
11403
11404 static int
11405 thread_display_step (threadref *ref, void *context)
11406 {
11407 /* output_threadid(" threadstep ",ref); *//* simple test */
11408 return get_and_display_threadinfo (ref);
11409 }
11410
11411 static void
11412 threadlist_update_test_cmd (const char *cmd, int tty)
11413 {
11414 printf_filtered ("Remote Threadlist update test\n");
11415 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11416 }
11417
11418 static void
11419 init_remote_threadtests (void)
11420 {
11421 add_com ("tlist", class_obscure, threadlist_test_cmd,
11422 _("Fetch and print the remote list of "
11423 "thread identifiers, one pkt only"));
11424 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11425 _("Fetch and display info about one thread"));
11426 add_com ("tset", class_obscure, threadset_test_cmd,
11427 _("Test setting to a different thread"));
11428 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11429 _("Iterate through updating all remote thread info"));
11430 add_com ("talive", class_obscure, threadalive_test,
11431 _(" Remote thread alive test "));
11432 }
11433
11434 #endif /* 0 */
11435
11436 /* Convert a thread ID to a string. Returns the string in a static
11437 buffer. */
11438
11439 const char *
11440 remote_target::pid_to_str (ptid_t ptid)
11441 {
11442 static char buf[64];
11443 struct remote_state *rs = get_remote_state ();
11444
11445 if (ptid_equal (ptid, null_ptid))
11446 return normal_pid_to_str (ptid);
11447 else if (ptid_is_pid (ptid))
11448 {
11449 /* Printing an inferior target id. */
11450
11451 /* When multi-process extensions are off, there's no way in the
11452 remote protocol to know the remote process id, if there's any
11453 at all. There's one exception --- when we're connected with
11454 target extended-remote, and we manually attached to a process
11455 with "attach PID". We don't record anywhere a flag that
11456 allows us to distinguish that case from the case of
11457 connecting with extended-remote and the stub already being
11458 attached to a process, and reporting yes to qAttached, hence
11459 no smart special casing here. */
11460 if (!remote_multi_process_p (rs))
11461 {
11462 xsnprintf (buf, sizeof buf, "Remote target");
11463 return buf;
11464 }
11465
11466 return normal_pid_to_str (ptid);
11467 }
11468 else
11469 {
11470 if (ptid_equal (magic_null_ptid, ptid))
11471 xsnprintf (buf, sizeof buf, "Thread <main>");
11472 else if (remote_multi_process_p (rs))
11473 if (ptid_get_lwp (ptid) == 0)
11474 return normal_pid_to_str (ptid);
11475 else
11476 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11477 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11478 else
11479 xsnprintf (buf, sizeof buf, "Thread %ld",
11480 ptid_get_lwp (ptid));
11481 return buf;
11482 }
11483 }
11484
11485 /* Get the address of the thread local variable in OBJFILE which is
11486 stored at OFFSET within the thread local storage for thread PTID. */
11487
11488 CORE_ADDR
11489 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11490 CORE_ADDR offset)
11491 {
11492 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11493 {
11494 struct remote_state *rs = get_remote_state ();
11495 char *p = rs->buf;
11496 char *endp = rs->buf + get_remote_packet_size ();
11497 enum packet_result result;
11498
11499 strcpy (p, "qGetTLSAddr:");
11500 p += strlen (p);
11501 p = write_ptid (p, endp, ptid);
11502 *p++ = ',';
11503 p += hexnumstr (p, offset);
11504 *p++ = ',';
11505 p += hexnumstr (p, lm);
11506 *p++ = '\0';
11507
11508 putpkt (rs->buf);
11509 getpkt (&rs->buf, &rs->buf_size, 0);
11510 result = packet_ok (rs->buf,
11511 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11512 if (result == PACKET_OK)
11513 {
11514 ULONGEST result;
11515
11516 unpack_varlen_hex (rs->buf, &result);
11517 return result;
11518 }
11519 else if (result == PACKET_UNKNOWN)
11520 throw_error (TLS_GENERIC_ERROR,
11521 _("Remote target doesn't support qGetTLSAddr packet"));
11522 else
11523 throw_error (TLS_GENERIC_ERROR,
11524 _("Remote target failed to process qGetTLSAddr request"));
11525 }
11526 else
11527 throw_error (TLS_GENERIC_ERROR,
11528 _("TLS not supported or disabled on this target"));
11529 /* Not reached. */
11530 return 0;
11531 }
11532
11533 /* Provide thread local base, i.e. Thread Information Block address.
11534 Returns 1 if ptid is found and thread_local_base is non zero. */
11535
11536 bool
11537 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11538 {
11539 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11540 {
11541 struct remote_state *rs = get_remote_state ();
11542 char *p = rs->buf;
11543 char *endp = rs->buf + get_remote_packet_size ();
11544 enum packet_result result;
11545
11546 strcpy (p, "qGetTIBAddr:");
11547 p += strlen (p);
11548 p = write_ptid (p, endp, ptid);
11549 *p++ = '\0';
11550
11551 putpkt (rs->buf);
11552 getpkt (&rs->buf, &rs->buf_size, 0);
11553 result = packet_ok (rs->buf,
11554 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11555 if (result == PACKET_OK)
11556 {
11557 ULONGEST result;
11558
11559 unpack_varlen_hex (rs->buf, &result);
11560 if (addr)
11561 *addr = (CORE_ADDR) result;
11562 return true;
11563 }
11564 else if (result == PACKET_UNKNOWN)
11565 error (_("Remote target doesn't support qGetTIBAddr packet"));
11566 else
11567 error (_("Remote target failed to process qGetTIBAddr request"));
11568 }
11569 else
11570 error (_("qGetTIBAddr not supported or disabled on this target"));
11571 /* Not reached. */
11572 return false;
11573 }
11574
11575 /* Support for inferring a target description based on the current
11576 architecture and the size of a 'g' packet. While the 'g' packet
11577 can have any size (since optional registers can be left off the
11578 end), some sizes are easily recognizable given knowledge of the
11579 approximate architecture. */
11580
11581 struct remote_g_packet_guess
11582 {
11583 int bytes;
11584 const struct target_desc *tdesc;
11585 };
11586 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11587 DEF_VEC_O(remote_g_packet_guess_s);
11588
11589 struct remote_g_packet_data
11590 {
11591 VEC(remote_g_packet_guess_s) *guesses;
11592 };
11593
11594 static struct gdbarch_data *remote_g_packet_data_handle;
11595
11596 static void *
11597 remote_g_packet_data_init (struct obstack *obstack)
11598 {
11599 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11600 }
11601
11602 void
11603 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11604 const struct target_desc *tdesc)
11605 {
11606 struct remote_g_packet_data *data
11607 = ((struct remote_g_packet_data *)
11608 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11609 struct remote_g_packet_guess new_guess, *guess;
11610 int ix;
11611
11612 gdb_assert (tdesc != NULL);
11613
11614 for (ix = 0;
11615 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11616 ix++)
11617 if (guess->bytes == bytes)
11618 internal_error (__FILE__, __LINE__,
11619 _("Duplicate g packet description added for size %d"),
11620 bytes);
11621
11622 new_guess.bytes = bytes;
11623 new_guess.tdesc = tdesc;
11624 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11625 }
11626
11627 /* Return 1 if remote_read_description would do anything on this target
11628 and architecture, 0 otherwise. */
11629
11630 static int
11631 remote_read_description_p (struct target_ops *target)
11632 {
11633 struct remote_g_packet_data *data
11634 = ((struct remote_g_packet_data *)
11635 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11636
11637 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11638 return 1;
11639
11640 return 0;
11641 }
11642
11643 const struct target_desc *
11644 remote_target::read_description ()
11645 {
11646 struct remote_g_packet_data *data
11647 = ((struct remote_g_packet_data *)
11648 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11649
11650 /* Do not try this during initial connection, when we do not know
11651 whether there is a running but stopped thread. */
11652 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11653 return beneath ()->read_description ();
11654
11655 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11656 {
11657 struct remote_g_packet_guess *guess;
11658 int ix;
11659 int bytes = send_g_packet ();
11660
11661 for (ix = 0;
11662 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11663 ix++)
11664 if (guess->bytes == bytes)
11665 return guess->tdesc;
11666
11667 /* We discard the g packet. A minor optimization would be to
11668 hold on to it, and fill the register cache once we have selected
11669 an architecture, but it's too tricky to do safely. */
11670 }
11671
11672 return beneath ()->read_description ();
11673 }
11674
11675 /* Remote file transfer support. This is host-initiated I/O, not
11676 target-initiated; for target-initiated, see remote-fileio.c. */
11677
11678 /* If *LEFT is at least the length of STRING, copy STRING to
11679 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11680 decrease *LEFT. Otherwise raise an error. */
11681
11682 static void
11683 remote_buffer_add_string (char **buffer, int *left, const char *string)
11684 {
11685 int len = strlen (string);
11686
11687 if (len > *left)
11688 error (_("Packet too long for target."));
11689
11690 memcpy (*buffer, string, len);
11691 *buffer += len;
11692 *left -= len;
11693
11694 /* NUL-terminate the buffer as a convenience, if there is
11695 room. */
11696 if (*left)
11697 **buffer = '\0';
11698 }
11699
11700 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11701 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11702 decrease *LEFT. Otherwise raise an error. */
11703
11704 static void
11705 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11706 int len)
11707 {
11708 if (2 * len > *left)
11709 error (_("Packet too long for target."));
11710
11711 bin2hex (bytes, *buffer, len);
11712 *buffer += 2 * len;
11713 *left -= 2 * len;
11714
11715 /* NUL-terminate the buffer as a convenience, if there is
11716 room. */
11717 if (*left)
11718 **buffer = '\0';
11719 }
11720
11721 /* If *LEFT is large enough, convert VALUE to hex and add it to
11722 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11723 decrease *LEFT. Otherwise raise an error. */
11724
11725 static void
11726 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11727 {
11728 int len = hexnumlen (value);
11729
11730 if (len > *left)
11731 error (_("Packet too long for target."));
11732
11733 hexnumstr (*buffer, value);
11734 *buffer += len;
11735 *left -= len;
11736
11737 /* NUL-terminate the buffer as a convenience, if there is
11738 room. */
11739 if (*left)
11740 **buffer = '\0';
11741 }
11742
11743 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11744 value, *REMOTE_ERRNO to the remote error number or zero if none
11745 was included, and *ATTACHMENT to point to the start of the annex
11746 if any. The length of the packet isn't needed here; there may
11747 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11748
11749 Return 0 if the packet could be parsed, -1 if it could not. If
11750 -1 is returned, the other variables may not be initialized. */
11751
11752 static int
11753 remote_hostio_parse_result (char *buffer, int *retcode,
11754 int *remote_errno, char **attachment)
11755 {
11756 char *p, *p2;
11757
11758 *remote_errno = 0;
11759 *attachment = NULL;
11760
11761 if (buffer[0] != 'F')
11762 return -1;
11763
11764 errno = 0;
11765 *retcode = strtol (&buffer[1], &p, 16);
11766 if (errno != 0 || p == &buffer[1])
11767 return -1;
11768
11769 /* Check for ",errno". */
11770 if (*p == ',')
11771 {
11772 errno = 0;
11773 *remote_errno = strtol (p + 1, &p2, 16);
11774 if (errno != 0 || p + 1 == p2)
11775 return -1;
11776 p = p2;
11777 }
11778
11779 /* Check for ";attachment". If there is no attachment, the
11780 packet should end here. */
11781 if (*p == ';')
11782 {
11783 *attachment = p + 1;
11784 return 0;
11785 }
11786 else if (*p == '\0')
11787 return 0;
11788 else
11789 return -1;
11790 }
11791
11792 /* Send a prepared I/O packet to the target and read its response.
11793 The prepared packet is in the global RS->BUF before this function
11794 is called, and the answer is there when we return.
11795
11796 COMMAND_BYTES is the length of the request to send, which may include
11797 binary data. WHICH_PACKET is the packet configuration to check
11798 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11799 is set to the error number and -1 is returned. Otherwise the value
11800 returned by the function is returned.
11801
11802 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11803 attachment is expected; an error will be reported if there's a
11804 mismatch. If one is found, *ATTACHMENT will be set to point into
11805 the packet buffer and *ATTACHMENT_LEN will be set to the
11806 attachment's length. */
11807
11808 int
11809 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11810 int *remote_errno, char **attachment,
11811 int *attachment_len)
11812 {
11813 struct remote_state *rs = get_remote_state ();
11814 int ret, bytes_read;
11815 char *attachment_tmp;
11816
11817 if (packet_support (which_packet) == PACKET_DISABLE)
11818 {
11819 *remote_errno = FILEIO_ENOSYS;
11820 return -1;
11821 }
11822
11823 putpkt_binary (rs->buf, command_bytes);
11824 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11825
11826 /* If it timed out, something is wrong. Don't try to parse the
11827 buffer. */
11828 if (bytes_read < 0)
11829 {
11830 *remote_errno = FILEIO_EINVAL;
11831 return -1;
11832 }
11833
11834 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11835 {
11836 case PACKET_ERROR:
11837 *remote_errno = FILEIO_EINVAL;
11838 return -1;
11839 case PACKET_UNKNOWN:
11840 *remote_errno = FILEIO_ENOSYS;
11841 return -1;
11842 case PACKET_OK:
11843 break;
11844 }
11845
11846 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11847 &attachment_tmp))
11848 {
11849 *remote_errno = FILEIO_EINVAL;
11850 return -1;
11851 }
11852
11853 /* Make sure we saw an attachment if and only if we expected one. */
11854 if ((attachment_tmp == NULL && attachment != NULL)
11855 || (attachment_tmp != NULL && attachment == NULL))
11856 {
11857 *remote_errno = FILEIO_EINVAL;
11858 return -1;
11859 }
11860
11861 /* If an attachment was found, it must point into the packet buffer;
11862 work out how many bytes there were. */
11863 if (attachment_tmp != NULL)
11864 {
11865 *attachment = attachment_tmp;
11866 *attachment_len = bytes_read - (*attachment - rs->buf);
11867 }
11868
11869 return ret;
11870 }
11871
11872 /* See declaration.h. */
11873
11874 void
11875 readahead_cache::invalidate ()
11876 {
11877 this->fd = -1;
11878 }
11879
11880 /* See declaration.h. */
11881
11882 void
11883 readahead_cache::invalidate_fd (int fd)
11884 {
11885 if (this->fd == fd)
11886 this->fd = -1;
11887 }
11888
11889 /* Set the filesystem remote_hostio functions that take FILENAME
11890 arguments will use. Return 0 on success, or -1 if an error
11891 occurs (and set *REMOTE_ERRNO). */
11892
11893 int
11894 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11895 int *remote_errno)
11896 {
11897 struct remote_state *rs = get_remote_state ();
11898 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11899 char *p = rs->buf;
11900 int left = get_remote_packet_size () - 1;
11901 char arg[9];
11902 int ret;
11903
11904 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11905 return 0;
11906
11907 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11908 return 0;
11909
11910 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11911
11912 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11913 remote_buffer_add_string (&p, &left, arg);
11914
11915 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11916 remote_errno, NULL, NULL);
11917
11918 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11919 return 0;
11920
11921 if (ret == 0)
11922 rs->fs_pid = required_pid;
11923
11924 return ret;
11925 }
11926
11927 /* Implementation of to_fileio_open. */
11928
11929 int
11930 remote_target::remote_hostio_open (inferior *inf, const char *filename,
11931 int flags, int mode, int warn_if_slow,
11932 int *remote_errno)
11933 {
11934 struct remote_state *rs = get_remote_state ();
11935 char *p = rs->buf;
11936 int left = get_remote_packet_size () - 1;
11937
11938 if (warn_if_slow)
11939 {
11940 static int warning_issued = 0;
11941
11942 printf_unfiltered (_("Reading %s from remote target...\n"),
11943 filename);
11944
11945 if (!warning_issued)
11946 {
11947 warning (_("File transfers from remote targets can be slow."
11948 " Use \"set sysroot\" to access files locally"
11949 " instead."));
11950 warning_issued = 1;
11951 }
11952 }
11953
11954 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11955 return -1;
11956
11957 remote_buffer_add_string (&p, &left, "vFile:open:");
11958
11959 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11960 strlen (filename));
11961 remote_buffer_add_string (&p, &left, ",");
11962
11963 remote_buffer_add_int (&p, &left, flags);
11964 remote_buffer_add_string (&p, &left, ",");
11965
11966 remote_buffer_add_int (&p, &left, mode);
11967
11968 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11969 remote_errno, NULL, NULL);
11970 }
11971
11972 int
11973 remote_target::fileio_open (struct inferior *inf, const char *filename,
11974 int flags, int mode, int warn_if_slow,
11975 int *remote_errno)
11976 {
11977 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
11978 remote_errno);
11979 }
11980
11981 /* Implementation of to_fileio_pwrite. */
11982
11983 int
11984 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
11985 ULONGEST offset, int *remote_errno)
11986 {
11987 struct remote_state *rs = get_remote_state ();
11988 char *p = rs->buf;
11989 int left = get_remote_packet_size ();
11990 int out_len;
11991
11992 rs->readahead_cache.invalidate_fd (fd);
11993
11994 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11995
11996 remote_buffer_add_int (&p, &left, fd);
11997 remote_buffer_add_string (&p, &left, ",");
11998
11999 remote_buffer_add_int (&p, &left, offset);
12000 remote_buffer_add_string (&p, &left, ",");
12001
12002 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12003 get_remote_packet_size () - (p - rs->buf));
12004
12005 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12006 remote_errno, NULL, NULL);
12007 }
12008
12009 int
12010 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12011 ULONGEST offset, int *remote_errno)
12012 {
12013 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12014 }
12015
12016 /* Helper for the implementation of to_fileio_pread. Read the file
12017 from the remote side with vFile:pread. */
12018
12019 int
12020 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12021 ULONGEST offset, int *remote_errno)
12022 {
12023 struct remote_state *rs = get_remote_state ();
12024 char *p = rs->buf;
12025 char *attachment;
12026 int left = get_remote_packet_size ();
12027 int ret, attachment_len;
12028 int read_len;
12029
12030 remote_buffer_add_string (&p, &left, "vFile:pread:");
12031
12032 remote_buffer_add_int (&p, &left, fd);
12033 remote_buffer_add_string (&p, &left, ",");
12034
12035 remote_buffer_add_int (&p, &left, len);
12036 remote_buffer_add_string (&p, &left, ",");
12037
12038 remote_buffer_add_int (&p, &left, offset);
12039
12040 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12041 remote_errno, &attachment,
12042 &attachment_len);
12043
12044 if (ret < 0)
12045 return ret;
12046
12047 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12048 read_buf, len);
12049 if (read_len != ret)
12050 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12051
12052 return ret;
12053 }
12054
12055 /* See declaration.h. */
12056
12057 int
12058 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12059 ULONGEST offset)
12060 {
12061 if (this->fd == fd
12062 && this->offset <= offset
12063 && offset < this->offset + this->bufsize)
12064 {
12065 ULONGEST max = this->offset + this->bufsize;
12066
12067 if (offset + len > max)
12068 len = max - offset;
12069
12070 memcpy (read_buf, this->buf + offset - this->offset, len);
12071 return len;
12072 }
12073
12074 return 0;
12075 }
12076
12077 /* Implementation of to_fileio_pread. */
12078
12079 int
12080 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12081 ULONGEST offset, int *remote_errno)
12082 {
12083 int ret;
12084 struct remote_state *rs = get_remote_state ();
12085 readahead_cache *cache = &rs->readahead_cache;
12086
12087 ret = cache->pread (fd, read_buf, len, offset);
12088 if (ret > 0)
12089 {
12090 cache->hit_count++;
12091
12092 if (remote_debug)
12093 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12094 pulongest (cache->hit_count));
12095 return ret;
12096 }
12097
12098 cache->miss_count++;
12099 if (remote_debug)
12100 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12101 pulongest (cache->miss_count));
12102
12103 cache->fd = fd;
12104 cache->offset = offset;
12105 cache->bufsize = get_remote_packet_size ();
12106 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12107
12108 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12109 cache->offset, remote_errno);
12110 if (ret <= 0)
12111 {
12112 cache->invalidate_fd (fd);
12113 return ret;
12114 }
12115
12116 cache->bufsize = ret;
12117 return cache->pread (fd, read_buf, len, offset);
12118 }
12119
12120 int
12121 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12122 ULONGEST offset, int *remote_errno)
12123 {
12124 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12125 }
12126
12127 /* Implementation of to_fileio_close. */
12128
12129 int
12130 remote_target::remote_hostio_close (int fd, int *remote_errno)
12131 {
12132 struct remote_state *rs = get_remote_state ();
12133 char *p = rs->buf;
12134 int left = get_remote_packet_size () - 1;
12135
12136 rs->readahead_cache.invalidate_fd (fd);
12137
12138 remote_buffer_add_string (&p, &left, "vFile:close:");
12139
12140 remote_buffer_add_int (&p, &left, fd);
12141
12142 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12143 remote_errno, NULL, NULL);
12144 }
12145
12146 int
12147 remote_target::fileio_close (int fd, int *remote_errno)
12148 {
12149 return remote_hostio_close (fd, remote_errno);
12150 }
12151
12152 /* Implementation of to_fileio_unlink. */
12153
12154 int
12155 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12156 int *remote_errno)
12157 {
12158 struct remote_state *rs = get_remote_state ();
12159 char *p = rs->buf;
12160 int left = get_remote_packet_size () - 1;
12161
12162 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12163 return -1;
12164
12165 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12166
12167 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12168 strlen (filename));
12169
12170 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12171 remote_errno, NULL, NULL);
12172 }
12173
12174 int
12175 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12176 int *remote_errno)
12177 {
12178 return remote_hostio_unlink (inf, filename, remote_errno);
12179 }
12180
12181 /* Implementation of to_fileio_readlink. */
12182
12183 gdb::optional<std::string>
12184 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12185 int *remote_errno)
12186 {
12187 struct remote_state *rs = get_remote_state ();
12188 char *p = rs->buf;
12189 char *attachment;
12190 int left = get_remote_packet_size ();
12191 int len, attachment_len;
12192 int read_len;
12193
12194 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12195 return {};
12196
12197 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12198
12199 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12200 strlen (filename));
12201
12202 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12203 remote_errno, &attachment,
12204 &attachment_len);
12205
12206 if (len < 0)
12207 return {};
12208
12209 std::string ret (len, '\0');
12210
12211 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12212 (gdb_byte *) &ret[0], len);
12213 if (read_len != len)
12214 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12215
12216 return ret;
12217 }
12218
12219 /* Implementation of to_fileio_fstat. */
12220
12221 int
12222 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12223 {
12224 struct remote_state *rs = get_remote_state ();
12225 char *p = rs->buf;
12226 int left = get_remote_packet_size ();
12227 int attachment_len, ret;
12228 char *attachment;
12229 struct fio_stat fst;
12230 int read_len;
12231
12232 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12233
12234 remote_buffer_add_int (&p, &left, fd);
12235
12236 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12237 remote_errno, &attachment,
12238 &attachment_len);
12239 if (ret < 0)
12240 {
12241 if (*remote_errno != FILEIO_ENOSYS)
12242 return ret;
12243
12244 /* Strictly we should return -1, ENOSYS here, but when
12245 "set sysroot remote:" was implemented in August 2008
12246 BFD's need for a stat function was sidestepped with
12247 this hack. This was not remedied until March 2015
12248 so we retain the previous behavior to avoid breaking
12249 compatibility.
12250
12251 Note that the memset is a March 2015 addition; older
12252 GDBs set st_size *and nothing else* so the structure
12253 would have garbage in all other fields. This might
12254 break something but retaining the previous behavior
12255 here would be just too wrong. */
12256
12257 memset (st, 0, sizeof (struct stat));
12258 st->st_size = INT_MAX;
12259 return 0;
12260 }
12261
12262 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12263 (gdb_byte *) &fst, sizeof (fst));
12264
12265 if (read_len != ret)
12266 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12267
12268 if (read_len != sizeof (fst))
12269 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12270 read_len, (int) sizeof (fst));
12271
12272 remote_fileio_to_host_stat (&fst, st);
12273
12274 return 0;
12275 }
12276
12277 /* Implementation of to_filesystem_is_local. */
12278
12279 bool
12280 remote_target::filesystem_is_local ()
12281 {
12282 /* Valgrind GDB presents itself as a remote target but works
12283 on the local filesystem: it does not implement remote get
12284 and users are not expected to set a sysroot. To handle
12285 this case we treat the remote filesystem as local if the
12286 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12287 does not support vFile:open. */
12288 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12289 {
12290 enum packet_support ps = packet_support (PACKET_vFile_open);
12291
12292 if (ps == PACKET_SUPPORT_UNKNOWN)
12293 {
12294 int fd, remote_errno;
12295
12296 /* Try opening a file to probe support. The supplied
12297 filename is irrelevant, we only care about whether
12298 the stub recognizes the packet or not. */
12299 fd = remote_hostio_open (NULL, "just probing",
12300 FILEIO_O_RDONLY, 0700, 0,
12301 &remote_errno);
12302
12303 if (fd >= 0)
12304 remote_hostio_close (fd, &remote_errno);
12305
12306 ps = packet_support (PACKET_vFile_open);
12307 }
12308
12309 if (ps == PACKET_DISABLE)
12310 {
12311 static int warning_issued = 0;
12312
12313 if (!warning_issued)
12314 {
12315 warning (_("remote target does not support file"
12316 " transfer, attempting to access files"
12317 " from local filesystem."));
12318 warning_issued = 1;
12319 }
12320
12321 return true;
12322 }
12323 }
12324
12325 return false;
12326 }
12327
12328 static int
12329 remote_fileio_errno_to_host (int errnum)
12330 {
12331 switch (errnum)
12332 {
12333 case FILEIO_EPERM:
12334 return EPERM;
12335 case FILEIO_ENOENT:
12336 return ENOENT;
12337 case FILEIO_EINTR:
12338 return EINTR;
12339 case FILEIO_EIO:
12340 return EIO;
12341 case FILEIO_EBADF:
12342 return EBADF;
12343 case FILEIO_EACCES:
12344 return EACCES;
12345 case FILEIO_EFAULT:
12346 return EFAULT;
12347 case FILEIO_EBUSY:
12348 return EBUSY;
12349 case FILEIO_EEXIST:
12350 return EEXIST;
12351 case FILEIO_ENODEV:
12352 return ENODEV;
12353 case FILEIO_ENOTDIR:
12354 return ENOTDIR;
12355 case FILEIO_EISDIR:
12356 return EISDIR;
12357 case FILEIO_EINVAL:
12358 return EINVAL;
12359 case FILEIO_ENFILE:
12360 return ENFILE;
12361 case FILEIO_EMFILE:
12362 return EMFILE;
12363 case FILEIO_EFBIG:
12364 return EFBIG;
12365 case FILEIO_ENOSPC:
12366 return ENOSPC;
12367 case FILEIO_ESPIPE:
12368 return ESPIPE;
12369 case FILEIO_EROFS:
12370 return EROFS;
12371 case FILEIO_ENOSYS:
12372 return ENOSYS;
12373 case FILEIO_ENAMETOOLONG:
12374 return ENAMETOOLONG;
12375 }
12376 return -1;
12377 }
12378
12379 static char *
12380 remote_hostio_error (int errnum)
12381 {
12382 int host_error = remote_fileio_errno_to_host (errnum);
12383
12384 if (host_error == -1)
12385 error (_("Unknown remote I/O error %d"), errnum);
12386 else
12387 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12388 }
12389
12390 /* A RAII wrapper around a remote file descriptor. */
12391
12392 class scoped_remote_fd
12393 {
12394 public:
12395 scoped_remote_fd (remote_target *remote, int fd)
12396 : m_remote (remote), m_fd (fd)
12397 {
12398 }
12399
12400 ~scoped_remote_fd ()
12401 {
12402 if (m_fd != -1)
12403 {
12404 try
12405 {
12406 int remote_errno;
12407 m_remote->remote_hostio_close (m_fd, &remote_errno);
12408 }
12409 catch (...)
12410 {
12411 /* Swallow exception before it escapes the dtor. If
12412 something goes wrong, likely the connection is gone,
12413 and there's nothing else that can be done. */
12414 }
12415 }
12416 }
12417
12418 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12419
12420 /* Release ownership of the file descriptor, and return it. */
12421 int release () noexcept
12422 {
12423 int fd = m_fd;
12424 m_fd = -1;
12425 return fd;
12426 }
12427
12428 /* Return the owned file descriptor. */
12429 int get () const noexcept
12430 {
12431 return m_fd;
12432 }
12433
12434 private:
12435 /* The remote target. */
12436 remote_target *m_remote;
12437
12438 /* The owned remote I/O file descriptor. */
12439 int m_fd;
12440 };
12441
12442 void
12443 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12444 {
12445 remote_target *remote = get_current_remote_target ();
12446
12447 if (remote == nullptr)
12448 error (_("command can only be used with remote target"));
12449
12450 remote->remote_file_put (local_file, remote_file, from_tty);
12451 }
12452
12453 void
12454 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12455 int from_tty)
12456 {
12457 int retcode, remote_errno, bytes, io_size;
12458 int bytes_in_buffer;
12459 int saw_eof;
12460 ULONGEST offset;
12461
12462 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12463 if (file == NULL)
12464 perror_with_name (local_file);
12465
12466 scoped_remote_fd fd
12467 (this, remote_hostio_open (NULL,
12468 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12469 | FILEIO_O_TRUNC),
12470 0700, 0, &remote_errno));
12471 if (fd.get () == -1)
12472 remote_hostio_error (remote_errno);
12473
12474 /* Send up to this many bytes at once. They won't all fit in the
12475 remote packet limit, so we'll transfer slightly fewer. */
12476 io_size = get_remote_packet_size ();
12477 gdb::byte_vector buffer (io_size);
12478
12479 bytes_in_buffer = 0;
12480 saw_eof = 0;
12481 offset = 0;
12482 while (bytes_in_buffer || !saw_eof)
12483 {
12484 if (!saw_eof)
12485 {
12486 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12487 io_size - bytes_in_buffer,
12488 file.get ());
12489 if (bytes == 0)
12490 {
12491 if (ferror (file.get ()))
12492 error (_("Error reading %s."), local_file);
12493 else
12494 {
12495 /* EOF. Unless there is something still in the
12496 buffer from the last iteration, we are done. */
12497 saw_eof = 1;
12498 if (bytes_in_buffer == 0)
12499 break;
12500 }
12501 }
12502 }
12503 else
12504 bytes = 0;
12505
12506 bytes += bytes_in_buffer;
12507 bytes_in_buffer = 0;
12508
12509 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12510 offset, &remote_errno);
12511
12512 if (retcode < 0)
12513 remote_hostio_error (remote_errno);
12514 else if (retcode == 0)
12515 error (_("Remote write of %d bytes returned 0!"), bytes);
12516 else if (retcode < bytes)
12517 {
12518 /* Short write. Save the rest of the read data for the next
12519 write. */
12520 bytes_in_buffer = bytes - retcode;
12521 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12522 }
12523
12524 offset += retcode;
12525 }
12526
12527 if (remote_hostio_close (fd.release (), &remote_errno))
12528 remote_hostio_error (remote_errno);
12529
12530 if (from_tty)
12531 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12532 }
12533
12534 void
12535 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12536 {
12537 remote_target *remote = get_current_remote_target ();
12538
12539 if (remote == nullptr)
12540 error (_("command can only be used with remote target"));
12541
12542 remote->remote_file_get (remote_file, local_file, from_tty);
12543 }
12544
12545 void
12546 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12547 int from_tty)
12548 {
12549 int remote_errno, bytes, io_size;
12550 ULONGEST offset;
12551
12552 scoped_remote_fd fd
12553 (this, remote_hostio_open (NULL,
12554 remote_file, FILEIO_O_RDONLY, 0, 0,
12555 &remote_errno));
12556 if (fd.get () == -1)
12557 remote_hostio_error (remote_errno);
12558
12559 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12560 if (file == NULL)
12561 perror_with_name (local_file);
12562
12563 /* Send up to this many bytes at once. They won't all fit in the
12564 remote packet limit, so we'll transfer slightly fewer. */
12565 io_size = get_remote_packet_size ();
12566 gdb::byte_vector buffer (io_size);
12567
12568 offset = 0;
12569 while (1)
12570 {
12571 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12572 &remote_errno);
12573 if (bytes == 0)
12574 /* Success, but no bytes, means end-of-file. */
12575 break;
12576 if (bytes == -1)
12577 remote_hostio_error (remote_errno);
12578
12579 offset += bytes;
12580
12581 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12582 if (bytes == 0)
12583 perror_with_name (local_file);
12584 }
12585
12586 if (remote_hostio_close (fd.release (), &remote_errno))
12587 remote_hostio_error (remote_errno);
12588
12589 if (from_tty)
12590 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12591 }
12592
12593 void
12594 remote_file_delete (const char *remote_file, int from_tty)
12595 {
12596 remote_target *remote = get_current_remote_target ();
12597
12598 if (remote == nullptr)
12599 error (_("command can only be used with remote target"));
12600
12601 remote->remote_file_delete (remote_file, from_tty);
12602 }
12603
12604 void
12605 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12606 {
12607 int retcode, remote_errno;
12608
12609 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12610 if (retcode == -1)
12611 remote_hostio_error (remote_errno);
12612
12613 if (from_tty)
12614 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12615 }
12616
12617 static void
12618 remote_put_command (const char *args, int from_tty)
12619 {
12620 if (args == NULL)
12621 error_no_arg (_("file to put"));
12622
12623 gdb_argv argv (args);
12624 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12625 error (_("Invalid parameters to remote put"));
12626
12627 remote_file_put (argv[0], argv[1], from_tty);
12628 }
12629
12630 static void
12631 remote_get_command (const char *args, int from_tty)
12632 {
12633 if (args == NULL)
12634 error_no_arg (_("file to get"));
12635
12636 gdb_argv argv (args);
12637 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12638 error (_("Invalid parameters to remote get"));
12639
12640 remote_file_get (argv[0], argv[1], from_tty);
12641 }
12642
12643 static void
12644 remote_delete_command (const char *args, int from_tty)
12645 {
12646 if (args == NULL)
12647 error_no_arg (_("file to delete"));
12648
12649 gdb_argv argv (args);
12650 if (argv[0] == NULL || argv[1] != NULL)
12651 error (_("Invalid parameters to remote delete"));
12652
12653 remote_file_delete (argv[0], from_tty);
12654 }
12655
12656 static void
12657 remote_command (const char *args, int from_tty)
12658 {
12659 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12660 }
12661
12662 bool
12663 remote_target::can_execute_reverse ()
12664 {
12665 if (packet_support (PACKET_bs) == PACKET_ENABLE
12666 || packet_support (PACKET_bc) == PACKET_ENABLE)
12667 return true;
12668 else
12669 return false;
12670 }
12671
12672 bool
12673 remote_target::supports_non_stop ()
12674 {
12675 return true;
12676 }
12677
12678 bool
12679 remote_target::supports_disable_randomization ()
12680 {
12681 /* Only supported in extended mode. */
12682 return false;
12683 }
12684
12685 bool
12686 remote_target::supports_multi_process ()
12687 {
12688 struct remote_state *rs = get_remote_state ();
12689
12690 return remote_multi_process_p (rs);
12691 }
12692
12693 static int
12694 remote_supports_cond_tracepoints ()
12695 {
12696 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12697 }
12698
12699 bool
12700 remote_target::supports_evaluation_of_breakpoint_conditions ()
12701 {
12702 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12703 }
12704
12705 static int
12706 remote_supports_fast_tracepoints ()
12707 {
12708 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12709 }
12710
12711 static int
12712 remote_supports_static_tracepoints ()
12713 {
12714 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12715 }
12716
12717 static int
12718 remote_supports_install_in_trace ()
12719 {
12720 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12721 }
12722
12723 bool
12724 remote_target::supports_enable_disable_tracepoint ()
12725 {
12726 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12727 == PACKET_ENABLE);
12728 }
12729
12730 bool
12731 remote_target::supports_string_tracing ()
12732 {
12733 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12734 }
12735
12736 bool
12737 remote_target::can_run_breakpoint_commands ()
12738 {
12739 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12740 }
12741
12742 void
12743 remote_target::trace_init ()
12744 {
12745 struct remote_state *rs = get_remote_state ();
12746
12747 putpkt ("QTinit");
12748 remote_get_noisy_reply ();
12749 if (strcmp (rs->buf, "OK") != 0)
12750 error (_("Target does not support this command."));
12751 }
12752
12753 /* Recursive routine to walk through command list including loops, and
12754 download packets for each command. */
12755
12756 void
12757 remote_target::remote_download_command_source (int num, ULONGEST addr,
12758 struct command_line *cmds)
12759 {
12760 struct remote_state *rs = get_remote_state ();
12761 struct command_line *cmd;
12762
12763 for (cmd = cmds; cmd; cmd = cmd->next)
12764 {
12765 QUIT; /* Allow user to bail out with ^C. */
12766 strcpy (rs->buf, "QTDPsrc:");
12767 encode_source_string (num, addr, "cmd", cmd->line,
12768 rs->buf + strlen (rs->buf),
12769 rs->buf_size - strlen (rs->buf));
12770 putpkt (rs->buf);
12771 remote_get_noisy_reply ();
12772 if (strcmp (rs->buf, "OK"))
12773 warning (_("Target does not support source download."));
12774
12775 if (cmd->control_type == while_control
12776 || cmd->control_type == while_stepping_control)
12777 {
12778 remote_download_command_source (num, addr, cmd->body_list_0.get ());
12779
12780 QUIT; /* Allow user to bail out with ^C. */
12781 strcpy (rs->buf, "QTDPsrc:");
12782 encode_source_string (num, addr, "cmd", "end",
12783 rs->buf + strlen (rs->buf),
12784 rs->buf_size - strlen (rs->buf));
12785 putpkt (rs->buf);
12786 remote_get_noisy_reply ();
12787 if (strcmp (rs->buf, "OK"))
12788 warning (_("Target does not support source download."));
12789 }
12790 }
12791 }
12792
12793 void
12794 remote_target::download_tracepoint (struct bp_location *loc)
12795 {
12796 #define BUF_SIZE 2048
12797
12798 CORE_ADDR tpaddr;
12799 char addrbuf[40];
12800 char buf[BUF_SIZE];
12801 std::vector<std::string> tdp_actions;
12802 std::vector<std::string> stepping_actions;
12803 char *pkt;
12804 struct breakpoint *b = loc->owner;
12805 struct tracepoint *t = (struct tracepoint *) b;
12806 struct remote_state *rs = get_remote_state ();
12807
12808 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12809
12810 tpaddr = loc->address;
12811 sprintf_vma (addrbuf, tpaddr);
12812 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12813 addrbuf, /* address */
12814 (b->enable_state == bp_enabled ? 'E' : 'D'),
12815 t->step_count, t->pass_count);
12816 /* Fast tracepoints are mostly handled by the target, but we can
12817 tell the target how big of an instruction block should be moved
12818 around. */
12819 if (b->type == bp_fast_tracepoint)
12820 {
12821 /* Only test for support at download time; we may not know
12822 target capabilities at definition time. */
12823 if (remote_supports_fast_tracepoints ())
12824 {
12825 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12826 NULL))
12827 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12828 gdb_insn_length (loc->gdbarch, tpaddr));
12829 else
12830 /* If it passed validation at definition but fails now,
12831 something is very wrong. */
12832 internal_error (__FILE__, __LINE__,
12833 _("Fast tracepoint not "
12834 "valid during download"));
12835 }
12836 else
12837 /* Fast tracepoints are functionally identical to regular
12838 tracepoints, so don't take lack of support as a reason to
12839 give up on the trace run. */
12840 warning (_("Target does not support fast tracepoints, "
12841 "downloading %d as regular tracepoint"), b->number);
12842 }
12843 else if (b->type == bp_static_tracepoint)
12844 {
12845 /* Only test for support at download time; we may not know
12846 target capabilities at definition time. */
12847 if (remote_supports_static_tracepoints ())
12848 {
12849 struct static_tracepoint_marker marker;
12850
12851 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12852 strcat (buf, ":S");
12853 else
12854 error (_("Static tracepoint not valid during download"));
12855 }
12856 else
12857 /* Fast tracepoints are functionally identical to regular
12858 tracepoints, so don't take lack of support as a reason
12859 to give up on the trace run. */
12860 error (_("Target does not support static tracepoints"));
12861 }
12862 /* If the tracepoint has a conditional, make it into an agent
12863 expression and append to the definition. */
12864 if (loc->cond)
12865 {
12866 /* Only test support at download time, we may not know target
12867 capabilities at definition time. */
12868 if (remote_supports_cond_tracepoints ())
12869 {
12870 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12871 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12872 aexpr->len);
12873 pkt = buf + strlen (buf);
12874 for (int ndx = 0; ndx < aexpr->len; ++ndx)
12875 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12876 *pkt = '\0';
12877 }
12878 else
12879 warning (_("Target does not support conditional tracepoints, "
12880 "ignoring tp %d cond"), b->number);
12881 }
12882
12883 if (b->commands || *default_collect)
12884 strcat (buf, "-");
12885 putpkt (buf);
12886 remote_get_noisy_reply ();
12887 if (strcmp (rs->buf, "OK"))
12888 error (_("Target does not support tracepoints."));
12889
12890 /* do_single_steps (t); */
12891 for (auto action_it = tdp_actions.begin ();
12892 action_it != tdp_actions.end (); action_it++)
12893 {
12894 QUIT; /* Allow user to bail out with ^C. */
12895
12896 bool has_more = (action_it != tdp_actions.end ()
12897 || !stepping_actions.empty ());
12898
12899 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12900 b->number, addrbuf, /* address */
12901 action_it->c_str (),
12902 has_more ? '-' : 0);
12903 putpkt (buf);
12904 remote_get_noisy_reply ();
12905 if (strcmp (rs->buf, "OK"))
12906 error (_("Error on target while setting tracepoints."));
12907 }
12908
12909 for (auto action_it = stepping_actions.begin ();
12910 action_it != stepping_actions.end (); action_it++)
12911 {
12912 QUIT; /* Allow user to bail out with ^C. */
12913
12914 bool is_first = action_it == stepping_actions.begin ();
12915 bool has_more = action_it != stepping_actions.end ();
12916
12917 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12918 b->number, addrbuf, /* address */
12919 is_first ? "S" : "",
12920 action_it->c_str (),
12921 has_more ? "-" : "");
12922 putpkt (buf);
12923 remote_get_noisy_reply ();
12924 if (strcmp (rs->buf, "OK"))
12925 error (_("Error on target while setting tracepoints."));
12926 }
12927
12928 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12929 {
12930 if (b->location != NULL)
12931 {
12932 strcpy (buf, "QTDPsrc:");
12933 encode_source_string (b->number, loc->address, "at",
12934 event_location_to_string (b->location.get ()),
12935 buf + strlen (buf), 2048 - strlen (buf));
12936 putpkt (buf);
12937 remote_get_noisy_reply ();
12938 if (strcmp (rs->buf, "OK"))
12939 warning (_("Target does not support source download."));
12940 }
12941 if (b->cond_string)
12942 {
12943 strcpy (buf, "QTDPsrc:");
12944 encode_source_string (b->number, loc->address,
12945 "cond", b->cond_string, buf + strlen (buf),
12946 2048 - strlen (buf));
12947 putpkt (buf);
12948 remote_get_noisy_reply ();
12949 if (strcmp (rs->buf, "OK"))
12950 warning (_("Target does not support source download."));
12951 }
12952 remote_download_command_source (b->number, loc->address,
12953 breakpoint_commands (b));
12954 }
12955 }
12956
12957 bool
12958 remote_target::can_download_tracepoint ()
12959 {
12960 struct remote_state *rs = get_remote_state ();
12961 struct trace_status *ts;
12962 int status;
12963
12964 /* Don't try to install tracepoints until we've relocated our
12965 symbols, and fetched and merged the target's tracepoint list with
12966 ours. */
12967 if (rs->starting_up)
12968 return false;
12969
12970 ts = current_trace_status ();
12971 status = get_trace_status (ts);
12972
12973 if (status == -1 || !ts->running_known || !ts->running)
12974 return false;
12975
12976 /* If we are in a tracing experiment, but remote stub doesn't support
12977 installing tracepoint in trace, we have to return. */
12978 if (!remote_supports_install_in_trace ())
12979 return false;
12980
12981 return true;
12982 }
12983
12984
12985 void
12986 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12987 {
12988 struct remote_state *rs = get_remote_state ();
12989 char *p;
12990
12991 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12992 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12993 tsv.builtin);
12994 p = rs->buf + strlen (rs->buf);
12995 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12996 error (_("Trace state variable name too long for tsv definition packet"));
12997 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12998 *p++ = '\0';
12999 putpkt (rs->buf);
13000 remote_get_noisy_reply ();
13001 if (*rs->buf == '\0')
13002 error (_("Target does not support this command."));
13003 if (strcmp (rs->buf, "OK") != 0)
13004 error (_("Error on target while downloading trace state variable."));
13005 }
13006
13007 void
13008 remote_target::enable_tracepoint (struct bp_location *location)
13009 {
13010 struct remote_state *rs = get_remote_state ();
13011 char addr_buf[40];
13012
13013 sprintf_vma (addr_buf, location->address);
13014 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13015 location->owner->number, addr_buf);
13016 putpkt (rs->buf);
13017 remote_get_noisy_reply ();
13018 if (*rs->buf == '\0')
13019 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13020 if (strcmp (rs->buf, "OK") != 0)
13021 error (_("Error on target while enabling tracepoint."));
13022 }
13023
13024 void
13025 remote_target::disable_tracepoint (struct bp_location *location)
13026 {
13027 struct remote_state *rs = get_remote_state ();
13028 char addr_buf[40];
13029
13030 sprintf_vma (addr_buf, location->address);
13031 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13032 location->owner->number, addr_buf);
13033 putpkt (rs->buf);
13034 remote_get_noisy_reply ();
13035 if (*rs->buf == '\0')
13036 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13037 if (strcmp (rs->buf, "OK") != 0)
13038 error (_("Error on target while disabling tracepoint."));
13039 }
13040
13041 void
13042 remote_target::trace_set_readonly_regions ()
13043 {
13044 asection *s;
13045 bfd *abfd = NULL;
13046 bfd_size_type size;
13047 bfd_vma vma;
13048 int anysecs = 0;
13049 int offset = 0;
13050
13051 if (!exec_bfd)
13052 return; /* No information to give. */
13053
13054 struct remote_state *rs = get_remote_state ();
13055
13056 strcpy (rs->buf, "QTro");
13057 offset = strlen (rs->buf);
13058 for (s = exec_bfd->sections; s; s = s->next)
13059 {
13060 char tmp1[40], tmp2[40];
13061 int sec_length;
13062
13063 if ((s->flags & SEC_LOAD) == 0 ||
13064 /* (s->flags & SEC_CODE) == 0 || */
13065 (s->flags & SEC_READONLY) == 0)
13066 continue;
13067
13068 anysecs = 1;
13069 vma = bfd_get_section_vma (abfd, s);
13070 size = bfd_get_section_size (s);
13071 sprintf_vma (tmp1, vma);
13072 sprintf_vma (tmp2, vma + size);
13073 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13074 if (offset + sec_length + 1 > rs->buf_size)
13075 {
13076 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13077 warning (_("\
13078 Too many sections for read-only sections definition packet."));
13079 break;
13080 }
13081 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
13082 tmp1, tmp2);
13083 offset += sec_length;
13084 }
13085 if (anysecs)
13086 {
13087 putpkt (rs->buf);
13088 getpkt (&rs->buf, &rs->buf_size, 0);
13089 }
13090 }
13091
13092 void
13093 remote_target::trace_start ()
13094 {
13095 struct remote_state *rs = get_remote_state ();
13096
13097 putpkt ("QTStart");
13098 remote_get_noisy_reply ();
13099 if (*rs->buf == '\0')
13100 error (_("Target does not support this command."));
13101 if (strcmp (rs->buf, "OK") != 0)
13102 error (_("Bogus reply from target: %s"), rs->buf);
13103 }
13104
13105 int
13106 remote_target::get_trace_status (struct trace_status *ts)
13107 {
13108 /* Initialize it just to avoid a GCC false warning. */
13109 char *p = NULL;
13110 /* FIXME we need to get register block size some other way. */
13111 extern int trace_regblock_size;
13112 enum packet_result result;
13113 struct remote_state *rs = get_remote_state ();
13114
13115 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13116 return -1;
13117
13118 trace_regblock_size
13119 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13120
13121 putpkt ("qTStatus");
13122
13123 TRY
13124 {
13125 p = remote_get_noisy_reply ();
13126 }
13127 CATCH (ex, RETURN_MASK_ERROR)
13128 {
13129 if (ex.error != TARGET_CLOSE_ERROR)
13130 {
13131 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13132 return -1;
13133 }
13134 throw_exception (ex);
13135 }
13136 END_CATCH
13137
13138 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13139
13140 /* If the remote target doesn't do tracing, flag it. */
13141 if (result == PACKET_UNKNOWN)
13142 return -1;
13143
13144 /* We're working with a live target. */
13145 ts->filename = NULL;
13146
13147 if (*p++ != 'T')
13148 error (_("Bogus trace status reply from target: %s"), rs->buf);
13149
13150 /* Function 'parse_trace_status' sets default value of each field of
13151 'ts' at first, so we don't have to do it here. */
13152 parse_trace_status (p, ts);
13153
13154 return ts->running;
13155 }
13156
13157 void
13158 remote_target::get_tracepoint_status (struct breakpoint *bp,
13159 struct uploaded_tp *utp)
13160 {
13161 struct remote_state *rs = get_remote_state ();
13162 char *reply;
13163 struct bp_location *loc;
13164 struct tracepoint *tp = (struct tracepoint *) bp;
13165 size_t size = get_remote_packet_size ();
13166
13167 if (tp)
13168 {
13169 tp->hit_count = 0;
13170 tp->traceframe_usage = 0;
13171 for (loc = tp->loc; loc; loc = loc->next)
13172 {
13173 /* If the tracepoint was never downloaded, don't go asking for
13174 any status. */
13175 if (tp->number_on_target == 0)
13176 continue;
13177 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13178 phex_nz (loc->address, 0));
13179 putpkt (rs->buf);
13180 reply = remote_get_noisy_reply ();
13181 if (reply && *reply)
13182 {
13183 if (*reply == 'V')
13184 parse_tracepoint_status (reply + 1, bp, utp);
13185 }
13186 }
13187 }
13188 else if (utp)
13189 {
13190 utp->hit_count = 0;
13191 utp->traceframe_usage = 0;
13192 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13193 phex_nz (utp->addr, 0));
13194 putpkt (rs->buf);
13195 reply = remote_get_noisy_reply ();
13196 if (reply && *reply)
13197 {
13198 if (*reply == 'V')
13199 parse_tracepoint_status (reply + 1, bp, utp);
13200 }
13201 }
13202 }
13203
13204 void
13205 remote_target::trace_stop ()
13206 {
13207 struct remote_state *rs = get_remote_state ();
13208
13209 putpkt ("QTStop");
13210 remote_get_noisy_reply ();
13211 if (*rs->buf == '\0')
13212 error (_("Target does not support this command."));
13213 if (strcmp (rs->buf, "OK") != 0)
13214 error (_("Bogus reply from target: %s"), rs->buf);
13215 }
13216
13217 int
13218 remote_target::trace_find (enum trace_find_type type, int num,
13219 CORE_ADDR addr1, CORE_ADDR addr2,
13220 int *tpp)
13221 {
13222 struct remote_state *rs = get_remote_state ();
13223 char *endbuf = rs->buf + get_remote_packet_size ();
13224 char *p, *reply;
13225 int target_frameno = -1, target_tracept = -1;
13226
13227 /* Lookups other than by absolute frame number depend on the current
13228 trace selected, so make sure it is correct on the remote end
13229 first. */
13230 if (type != tfind_number)
13231 set_remote_traceframe ();
13232
13233 p = rs->buf;
13234 strcpy (p, "QTFrame:");
13235 p = strchr (p, '\0');
13236 switch (type)
13237 {
13238 case tfind_number:
13239 xsnprintf (p, endbuf - p, "%x", num);
13240 break;
13241 case tfind_pc:
13242 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13243 break;
13244 case tfind_tp:
13245 xsnprintf (p, endbuf - p, "tdp:%x", num);
13246 break;
13247 case tfind_range:
13248 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13249 phex_nz (addr2, 0));
13250 break;
13251 case tfind_outside:
13252 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13253 phex_nz (addr2, 0));
13254 break;
13255 default:
13256 error (_("Unknown trace find type %d"), type);
13257 }
13258
13259 putpkt (rs->buf);
13260 reply = remote_get_noisy_reply ();
13261 if (*reply == '\0')
13262 error (_("Target does not support this command."));
13263
13264 while (reply && *reply)
13265 switch (*reply)
13266 {
13267 case 'F':
13268 p = ++reply;
13269 target_frameno = (int) strtol (p, &reply, 16);
13270 if (reply == p)
13271 error (_("Unable to parse trace frame number"));
13272 /* Don't update our remote traceframe number cache on failure
13273 to select a remote traceframe. */
13274 if (target_frameno == -1)
13275 return -1;
13276 break;
13277 case 'T':
13278 p = ++reply;
13279 target_tracept = (int) strtol (p, &reply, 16);
13280 if (reply == p)
13281 error (_("Unable to parse tracepoint number"));
13282 break;
13283 case 'O': /* "OK"? */
13284 if (reply[1] == 'K' && reply[2] == '\0')
13285 reply += 2;
13286 else
13287 error (_("Bogus reply from target: %s"), reply);
13288 break;
13289 default:
13290 error (_("Bogus reply from target: %s"), reply);
13291 }
13292 if (tpp)
13293 *tpp = target_tracept;
13294
13295 rs->remote_traceframe_number = target_frameno;
13296 return target_frameno;
13297 }
13298
13299 bool
13300 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13301 {
13302 struct remote_state *rs = get_remote_state ();
13303 char *reply;
13304 ULONGEST uval;
13305
13306 set_remote_traceframe ();
13307
13308 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13309 putpkt (rs->buf);
13310 reply = remote_get_noisy_reply ();
13311 if (reply && *reply)
13312 {
13313 if (*reply == 'V')
13314 {
13315 unpack_varlen_hex (reply + 1, &uval);
13316 *val = (LONGEST) uval;
13317 return true;
13318 }
13319 }
13320 return false;
13321 }
13322
13323 int
13324 remote_target::save_trace_data (const char *filename)
13325 {
13326 struct remote_state *rs = get_remote_state ();
13327 char *p, *reply;
13328
13329 p = rs->buf;
13330 strcpy (p, "QTSave:");
13331 p += strlen (p);
13332 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13333 error (_("Remote file name too long for trace save packet"));
13334 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13335 *p++ = '\0';
13336 putpkt (rs->buf);
13337 reply = remote_get_noisy_reply ();
13338 if (*reply == '\0')
13339 error (_("Target does not support this command."));
13340 if (strcmp (reply, "OK") != 0)
13341 error (_("Bogus reply from target: %s"), reply);
13342 return 0;
13343 }
13344
13345 /* This is basically a memory transfer, but needs to be its own packet
13346 because we don't know how the target actually organizes its trace
13347 memory, plus we want to be able to ask for as much as possible, but
13348 not be unhappy if we don't get as much as we ask for. */
13349
13350 LONGEST
13351 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13352 {
13353 struct remote_state *rs = get_remote_state ();
13354 char *reply;
13355 char *p;
13356 int rslt;
13357
13358 p = rs->buf;
13359 strcpy (p, "qTBuffer:");
13360 p += strlen (p);
13361 p += hexnumstr (p, offset);
13362 *p++ = ',';
13363 p += hexnumstr (p, len);
13364 *p++ = '\0';
13365
13366 putpkt (rs->buf);
13367 reply = remote_get_noisy_reply ();
13368 if (reply && *reply)
13369 {
13370 /* 'l' by itself means we're at the end of the buffer and
13371 there is nothing more to get. */
13372 if (*reply == 'l')
13373 return 0;
13374
13375 /* Convert the reply into binary. Limit the number of bytes to
13376 convert according to our passed-in buffer size, rather than
13377 what was returned in the packet; if the target is
13378 unexpectedly generous and gives us a bigger reply than we
13379 asked for, we don't want to crash. */
13380 rslt = hex2bin (reply, buf, len);
13381 return rslt;
13382 }
13383
13384 /* Something went wrong, flag as an error. */
13385 return -1;
13386 }
13387
13388 void
13389 remote_target::set_disconnected_tracing (int val)
13390 {
13391 struct remote_state *rs = get_remote_state ();
13392
13393 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13394 {
13395 char *reply;
13396
13397 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13398 putpkt (rs->buf);
13399 reply = remote_get_noisy_reply ();
13400 if (*reply == '\0')
13401 error (_("Target does not support this command."));
13402 if (strcmp (reply, "OK") != 0)
13403 error (_("Bogus reply from target: %s"), reply);
13404 }
13405 else if (val)
13406 warning (_("Target does not support disconnected tracing."));
13407 }
13408
13409 int
13410 remote_target::core_of_thread (ptid_t ptid)
13411 {
13412 struct thread_info *info = find_thread_ptid (ptid);
13413
13414 if (info != NULL && info->priv != NULL)
13415 return get_remote_thread_info (info)->core;
13416
13417 return -1;
13418 }
13419
13420 void
13421 remote_target::set_circular_trace_buffer (int val)
13422 {
13423 struct remote_state *rs = get_remote_state ();
13424 char *reply;
13425
13426 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13427 putpkt (rs->buf);
13428 reply = remote_get_noisy_reply ();
13429 if (*reply == '\0')
13430 error (_("Target does not support this command."));
13431 if (strcmp (reply, "OK") != 0)
13432 error (_("Bogus reply from target: %s"), reply);
13433 }
13434
13435 traceframe_info_up
13436 remote_target::traceframe_info ()
13437 {
13438 gdb::optional<gdb::char_vector> text
13439 = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
13440 NULL);
13441 if (text)
13442 return parse_traceframe_info (text->data ());
13443
13444 return NULL;
13445 }
13446
13447 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13448 instruction on which a fast tracepoint may be placed. Returns -1
13449 if the packet is not supported, and 0 if the minimum instruction
13450 length is unknown. */
13451
13452 int
13453 remote_target::get_min_fast_tracepoint_insn_len ()
13454 {
13455 struct remote_state *rs = get_remote_state ();
13456 char *reply;
13457
13458 /* If we're not debugging a process yet, the IPA can't be
13459 loaded. */
13460 if (!target_has_execution)
13461 return 0;
13462
13463 /* Make sure the remote is pointing at the right process. */
13464 set_general_process ();
13465
13466 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13467 putpkt (rs->buf);
13468 reply = remote_get_noisy_reply ();
13469 if (*reply == '\0')
13470 return -1;
13471 else
13472 {
13473 ULONGEST min_insn_len;
13474
13475 unpack_varlen_hex (reply, &min_insn_len);
13476
13477 return (int) min_insn_len;
13478 }
13479 }
13480
13481 void
13482 remote_target::set_trace_buffer_size (LONGEST val)
13483 {
13484 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13485 {
13486 struct remote_state *rs = get_remote_state ();
13487 char *buf = rs->buf;
13488 char *endbuf = rs->buf + get_remote_packet_size ();
13489 enum packet_result result;
13490
13491 gdb_assert (val >= 0 || val == -1);
13492 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13493 /* Send -1 as literal "-1" to avoid host size dependency. */
13494 if (val < 0)
13495 {
13496 *buf++ = '-';
13497 buf += hexnumstr (buf, (ULONGEST) -val);
13498 }
13499 else
13500 buf += hexnumstr (buf, (ULONGEST) val);
13501
13502 putpkt (rs->buf);
13503 remote_get_noisy_reply ();
13504 result = packet_ok (rs->buf,
13505 &remote_protocol_packets[PACKET_QTBuffer_size]);
13506
13507 if (result != PACKET_OK)
13508 warning (_("Bogus reply from target: %s"), rs->buf);
13509 }
13510 }
13511
13512 bool
13513 remote_target::set_trace_notes (const char *user, const char *notes,
13514 const char *stop_notes)
13515 {
13516 struct remote_state *rs = get_remote_state ();
13517 char *reply;
13518 char *buf = rs->buf;
13519 char *endbuf = rs->buf + get_remote_packet_size ();
13520 int nbytes;
13521
13522 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13523 if (user)
13524 {
13525 buf += xsnprintf (buf, endbuf - buf, "user:");
13526 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13527 buf += 2 * nbytes;
13528 *buf++ = ';';
13529 }
13530 if (notes)
13531 {
13532 buf += xsnprintf (buf, endbuf - buf, "notes:");
13533 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13534 buf += 2 * nbytes;
13535 *buf++ = ';';
13536 }
13537 if (stop_notes)
13538 {
13539 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13540 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13541 buf += 2 * nbytes;
13542 *buf++ = ';';
13543 }
13544 /* Ensure the buffer is terminated. */
13545 *buf = '\0';
13546
13547 putpkt (rs->buf);
13548 reply = remote_get_noisy_reply ();
13549 if (*reply == '\0')
13550 return false;
13551
13552 if (strcmp (reply, "OK") != 0)
13553 error (_("Bogus reply from target: %s"), reply);
13554
13555 return true;
13556 }
13557
13558 bool
13559 remote_target::use_agent (bool use)
13560 {
13561 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13562 {
13563 struct remote_state *rs = get_remote_state ();
13564
13565 /* If the stub supports QAgent. */
13566 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13567 putpkt (rs->buf);
13568 getpkt (&rs->buf, &rs->buf_size, 0);
13569
13570 if (strcmp (rs->buf, "OK") == 0)
13571 {
13572 ::use_agent = use;
13573 return true;
13574 }
13575 }
13576
13577 return false;
13578 }
13579
13580 bool
13581 remote_target::can_use_agent ()
13582 {
13583 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13584 }
13585
13586 struct btrace_target_info
13587 {
13588 /* The ptid of the traced thread. */
13589 ptid_t ptid;
13590
13591 /* The obtained branch trace configuration. */
13592 struct btrace_config conf;
13593 };
13594
13595 /* Reset our idea of our target's btrace configuration. */
13596
13597 static void
13598 remote_btrace_reset (remote_state *rs)
13599 {
13600 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13601 }
13602
13603 /* Synchronize the configuration with the target. */
13604
13605 void
13606 remote_target::btrace_sync_conf (const btrace_config *conf)
13607 {
13608 struct packet_config *packet;
13609 struct remote_state *rs;
13610 char *buf, *pos, *endbuf;
13611
13612 rs = get_remote_state ();
13613 buf = rs->buf;
13614 endbuf = buf + get_remote_packet_size ();
13615
13616 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13617 if (packet_config_support (packet) == PACKET_ENABLE
13618 && conf->bts.size != rs->btrace_config.bts.size)
13619 {
13620 pos = buf;
13621 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13622 conf->bts.size);
13623
13624 putpkt (buf);
13625 getpkt (&buf, &rs->buf_size, 0);
13626
13627 if (packet_ok (buf, packet) == PACKET_ERROR)
13628 {
13629 if (buf[0] == 'E' && buf[1] == '.')
13630 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13631 else
13632 error (_("Failed to configure the BTS buffer size."));
13633 }
13634
13635 rs->btrace_config.bts.size = conf->bts.size;
13636 }
13637
13638 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13639 if (packet_config_support (packet) == PACKET_ENABLE
13640 && conf->pt.size != rs->btrace_config.pt.size)
13641 {
13642 pos = buf;
13643 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13644 conf->pt.size);
13645
13646 putpkt (buf);
13647 getpkt (&buf, &rs->buf_size, 0);
13648
13649 if (packet_ok (buf, packet) == PACKET_ERROR)
13650 {
13651 if (buf[0] == 'E' && buf[1] == '.')
13652 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13653 else
13654 error (_("Failed to configure the trace buffer size."));
13655 }
13656
13657 rs->btrace_config.pt.size = conf->pt.size;
13658 }
13659 }
13660
13661 /* Read the current thread's btrace configuration from the target and
13662 store it into CONF. */
13663
13664 static void
13665 btrace_read_config (struct btrace_config *conf)
13666 {
13667 gdb::optional<gdb::char_vector> xml
13668 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
13669 if (xml)
13670 parse_xml_btrace_conf (conf, xml->data ());
13671 }
13672
13673 /* Maybe reopen target btrace. */
13674
13675 void
13676 remote_target::remote_btrace_maybe_reopen ()
13677 {
13678 struct remote_state *rs = get_remote_state ();
13679 struct thread_info *tp;
13680 int btrace_target_pushed = 0;
13681 int warned = 0;
13682
13683 scoped_restore_current_thread restore_thread;
13684
13685 ALL_NON_EXITED_THREADS (tp)
13686 {
13687 set_general_thread (tp->ptid);
13688
13689 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13690 btrace_read_config (&rs->btrace_config);
13691
13692 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13693 continue;
13694
13695 #if !defined (HAVE_LIBIPT)
13696 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13697 {
13698 if (!warned)
13699 {
13700 warned = 1;
13701 warning (_("Target is recording using Intel Processor Trace "
13702 "but support was disabled at compile time."));
13703 }
13704
13705 continue;
13706 }
13707 #endif /* !defined (HAVE_LIBIPT) */
13708
13709 /* Push target, once, but before anything else happens. This way our
13710 changes to the threads will be cleaned up by unpushing the target
13711 in case btrace_read_config () throws. */
13712 if (!btrace_target_pushed)
13713 {
13714 btrace_target_pushed = 1;
13715 record_btrace_push_target ();
13716 printf_filtered (_("Target is recording using %s.\n"),
13717 btrace_format_string (rs->btrace_config.format));
13718 }
13719
13720 tp->btrace.target = XCNEW (struct btrace_target_info);
13721 tp->btrace.target->ptid = tp->ptid;
13722 tp->btrace.target->conf = rs->btrace_config;
13723 }
13724 }
13725
13726 /* Enable branch tracing. */
13727
13728 struct btrace_target_info *
13729 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13730 {
13731 struct btrace_target_info *tinfo = NULL;
13732 struct packet_config *packet = NULL;
13733 struct remote_state *rs = get_remote_state ();
13734 char *buf = rs->buf;
13735 char *endbuf = rs->buf + get_remote_packet_size ();
13736
13737 switch (conf->format)
13738 {
13739 case BTRACE_FORMAT_BTS:
13740 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13741 break;
13742
13743 case BTRACE_FORMAT_PT:
13744 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13745 break;
13746 }
13747
13748 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13749 error (_("Target does not support branch tracing."));
13750
13751 btrace_sync_conf (conf);
13752
13753 set_general_thread (ptid);
13754
13755 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13756 putpkt (rs->buf);
13757 getpkt (&rs->buf, &rs->buf_size, 0);
13758
13759 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13760 {
13761 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13762 error (_("Could not enable branch tracing for %s: %s"),
13763 target_pid_to_str (ptid), rs->buf + 2);
13764 else
13765 error (_("Could not enable branch tracing for %s."),
13766 target_pid_to_str (ptid));
13767 }
13768
13769 tinfo = XCNEW (struct btrace_target_info);
13770 tinfo->ptid = ptid;
13771
13772 /* If we fail to read the configuration, we lose some information, but the
13773 tracing itself is not impacted. */
13774 TRY
13775 {
13776 btrace_read_config (&tinfo->conf);
13777 }
13778 CATCH (err, RETURN_MASK_ERROR)
13779 {
13780 if (err.message != NULL)
13781 warning ("%s", err.message);
13782 }
13783 END_CATCH
13784
13785 return tinfo;
13786 }
13787
13788 /* Disable branch tracing. */
13789
13790 void
13791 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13792 {
13793 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13794 struct remote_state *rs = get_remote_state ();
13795 char *buf = rs->buf;
13796 char *endbuf = rs->buf + get_remote_packet_size ();
13797
13798 if (packet_config_support (packet) != PACKET_ENABLE)
13799 error (_("Target does not support branch tracing."));
13800
13801 set_general_thread (tinfo->ptid);
13802
13803 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13804 putpkt (rs->buf);
13805 getpkt (&rs->buf, &rs->buf_size, 0);
13806
13807 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13808 {
13809 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13810 error (_("Could not disable branch tracing for %s: %s"),
13811 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13812 else
13813 error (_("Could not disable branch tracing for %s."),
13814 target_pid_to_str (tinfo->ptid));
13815 }
13816
13817 xfree (tinfo);
13818 }
13819
13820 /* Teardown branch tracing. */
13821
13822 void
13823 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13824 {
13825 /* We must not talk to the target during teardown. */
13826 xfree (tinfo);
13827 }
13828
13829 /* Read the branch trace. */
13830
13831 enum btrace_error
13832 remote_target::read_btrace (struct btrace_data *btrace,
13833 struct btrace_target_info *tinfo,
13834 enum btrace_read_type type)
13835 {
13836 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13837 const char *annex;
13838
13839 if (packet_config_support (packet) != PACKET_ENABLE)
13840 error (_("Target does not support branch tracing."));
13841
13842 #if !defined(HAVE_LIBEXPAT)
13843 error (_("Cannot process branch tracing result. XML parsing not supported."));
13844 #endif
13845
13846 switch (type)
13847 {
13848 case BTRACE_READ_ALL:
13849 annex = "all";
13850 break;
13851 case BTRACE_READ_NEW:
13852 annex = "new";
13853 break;
13854 case BTRACE_READ_DELTA:
13855 annex = "delta";
13856 break;
13857 default:
13858 internal_error (__FILE__, __LINE__,
13859 _("Bad branch tracing read type: %u."),
13860 (unsigned int) type);
13861 }
13862
13863 gdb::optional<gdb::char_vector> xml
13864 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
13865 if (!xml)
13866 return BTRACE_ERR_UNKNOWN;
13867
13868 parse_xml_btrace (btrace, xml->data ());
13869
13870 return BTRACE_ERR_NONE;
13871 }
13872
13873 const struct btrace_config *
13874 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13875 {
13876 return &tinfo->conf;
13877 }
13878
13879 bool
13880 remote_target::augmented_libraries_svr4_read ()
13881 {
13882 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13883 == PACKET_ENABLE);
13884 }
13885
13886 /* Implementation of to_load. */
13887
13888 void
13889 remote_target::load (const char *name, int from_tty)
13890 {
13891 generic_load (name, from_tty);
13892 }
13893
13894 /* Accepts an integer PID; returns a string representing a file that
13895 can be opened on the remote side to get the symbols for the child
13896 process. Returns NULL if the operation is not supported. */
13897
13898 char *
13899 remote_target::pid_to_exec_file (int pid)
13900 {
13901 static gdb::optional<gdb::char_vector> filename;
13902 struct inferior *inf;
13903 char *annex = NULL;
13904
13905 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13906 return NULL;
13907
13908 inf = find_inferior_pid (pid);
13909 if (inf == NULL)
13910 internal_error (__FILE__, __LINE__,
13911 _("not currently attached to process %d"), pid);
13912
13913 if (!inf->fake_pid_p)
13914 {
13915 const int annex_size = 9;
13916
13917 annex = (char *) alloca (annex_size);
13918 xsnprintf (annex, annex_size, "%x", pid);
13919 }
13920
13921 filename = target_read_stralloc (current_top_target (),
13922 TARGET_OBJECT_EXEC_FILE, annex);
13923
13924 return filename ? filename->data () : nullptr;
13925 }
13926
13927 /* Implement the to_can_do_single_step target_ops method. */
13928
13929 int
13930 remote_target::can_do_single_step ()
13931 {
13932 /* We can only tell whether target supports single step or not by
13933 supported s and S vCont actions if the stub supports vContSupported
13934 feature. If the stub doesn't support vContSupported feature,
13935 we have conservatively to think target doesn't supports single
13936 step. */
13937 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13938 {
13939 struct remote_state *rs = get_remote_state ();
13940
13941 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13942 remote_vcont_probe ();
13943
13944 return rs->supports_vCont.s && rs->supports_vCont.S;
13945 }
13946 else
13947 return 0;
13948 }
13949
13950 /* Implementation of the to_execution_direction method for the remote
13951 target. */
13952
13953 enum exec_direction_kind
13954 remote_target::execution_direction ()
13955 {
13956 struct remote_state *rs = get_remote_state ();
13957
13958 return rs->last_resume_exec_dir;
13959 }
13960
13961 /* Return pointer to the thread_info struct which corresponds to
13962 THREAD_HANDLE (having length HANDLE_LEN). */
13963
13964 thread_info *
13965 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13966 int handle_len,
13967 inferior *inf)
13968 {
13969 struct thread_info *tp;
13970
13971 ALL_NON_EXITED_THREADS (tp)
13972 {
13973 remote_thread_info *priv = get_remote_thread_info (tp);
13974
13975 if (tp->inf == inf && priv != NULL)
13976 {
13977 if (handle_len != priv->thread_handle.size ())
13978 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13979 handle_len, priv->thread_handle.size ());
13980 if (memcmp (thread_handle, priv->thread_handle.data (),
13981 handle_len) == 0)
13982 return tp;
13983 }
13984 }
13985
13986 return NULL;
13987 }
13988
13989 bool
13990 remote_target::can_async_p ()
13991 {
13992 struct remote_state *rs = get_remote_state ();
13993
13994 /* We don't go async if the user has explicitly prevented it with the
13995 "maint set target-async" command. */
13996 if (!target_async_permitted)
13997 return false;
13998
13999 /* We're async whenever the serial device is. */
14000 return serial_can_async_p (rs->remote_desc);
14001 }
14002
14003 bool
14004 remote_target::is_async_p ()
14005 {
14006 struct remote_state *rs = get_remote_state ();
14007
14008 if (!target_async_permitted)
14009 /* We only enable async when the user specifically asks for it. */
14010 return false;
14011
14012 /* We're async whenever the serial device is. */
14013 return serial_is_async_p (rs->remote_desc);
14014 }
14015
14016 /* Pass the SERIAL event on and up to the client. One day this code
14017 will be able to delay notifying the client of an event until the
14018 point where an entire packet has been received. */
14019
14020 static serial_event_ftype remote_async_serial_handler;
14021
14022 static void
14023 remote_async_serial_handler (struct serial *scb, void *context)
14024 {
14025 /* Don't propogate error information up to the client. Instead let
14026 the client find out about the error by querying the target. */
14027 inferior_event_handler (INF_REG_EVENT, NULL);
14028 }
14029
14030 static void
14031 remote_async_inferior_event_handler (gdb_client_data data)
14032 {
14033 inferior_event_handler (INF_REG_EVENT, data);
14034 }
14035
14036 void
14037 remote_target::async (int enable)
14038 {
14039 struct remote_state *rs = get_remote_state ();
14040
14041 if (enable)
14042 {
14043 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14044
14045 /* If there are pending events in the stop reply queue tell the
14046 event loop to process them. */
14047 if (!rs->stop_reply_queue.empty ())
14048 mark_async_event_handler (rs->remote_async_inferior_event_token);
14049 /* For simplicity, below we clear the pending events token
14050 without remembering whether it is marked, so here we always
14051 mark it. If there's actually no pending notification to
14052 process, this ends up being a no-op (other than a spurious
14053 event-loop wakeup). */
14054 if (target_is_non_stop_p ())
14055 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14056 }
14057 else
14058 {
14059 serial_async (rs->remote_desc, NULL, NULL);
14060 /* If the core is disabling async, it doesn't want to be
14061 disturbed with target events. Clear all async event sources
14062 too. */
14063 clear_async_event_handler (rs->remote_async_inferior_event_token);
14064 if (target_is_non_stop_p ())
14065 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14066 }
14067 }
14068
14069 /* Implementation of the to_thread_events method. */
14070
14071 void
14072 remote_target::thread_events (int enable)
14073 {
14074 struct remote_state *rs = get_remote_state ();
14075 size_t size = get_remote_packet_size ();
14076
14077 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14078 return;
14079
14080 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14081 putpkt (rs->buf);
14082 getpkt (&rs->buf, &rs->buf_size, 0);
14083
14084 switch (packet_ok (rs->buf,
14085 &remote_protocol_packets[PACKET_QThreadEvents]))
14086 {
14087 case PACKET_OK:
14088 if (strcmp (rs->buf, "OK") != 0)
14089 error (_("Remote refused setting thread events: %s"), rs->buf);
14090 break;
14091 case PACKET_ERROR:
14092 warning (_("Remote failure reply: %s"), rs->buf);
14093 break;
14094 case PACKET_UNKNOWN:
14095 break;
14096 }
14097 }
14098
14099 static void
14100 set_remote_cmd (const char *args, int from_tty)
14101 {
14102 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
14103 }
14104
14105 static void
14106 show_remote_cmd (const char *args, int from_tty)
14107 {
14108 /* We can't just use cmd_show_list here, because we want to skip
14109 the redundant "show remote Z-packet" and the legacy aliases. */
14110 struct cmd_list_element *list = remote_show_cmdlist;
14111 struct ui_out *uiout = current_uiout;
14112
14113 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14114 for (; list != NULL; list = list->next)
14115 if (strcmp (list->name, "Z-packet") == 0)
14116 continue;
14117 else if (list->type == not_set_cmd)
14118 /* Alias commands are exactly like the original, except they
14119 don't have the normal type. */
14120 continue;
14121 else
14122 {
14123 ui_out_emit_tuple option_emitter (uiout, "option");
14124
14125 uiout->field_string ("name", list->name);
14126 uiout->text (": ");
14127 if (list->type == show_cmd)
14128 do_show_command (NULL, from_tty, list);
14129 else
14130 cmd_func (list, NULL, from_tty);
14131 }
14132 }
14133
14134
14135 /* Function to be called whenever a new objfile (shlib) is detected. */
14136 static void
14137 remote_new_objfile (struct objfile *objfile)
14138 {
14139 remote_target *remote = get_current_remote_target ();
14140
14141 if (remote != NULL) /* Have a remote connection. */
14142 remote->remote_check_symbols ();
14143 }
14144
14145 /* Pull all the tracepoints defined on the target and create local
14146 data structures representing them. We don't want to create real
14147 tracepoints yet, we don't want to mess up the user's existing
14148 collection. */
14149
14150 int
14151 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14152 {
14153 struct remote_state *rs = get_remote_state ();
14154 char *p;
14155
14156 /* Ask for a first packet of tracepoint definition. */
14157 putpkt ("qTfP");
14158 getpkt (&rs->buf, &rs->buf_size, 0);
14159 p = rs->buf;
14160 while (*p && *p != 'l')
14161 {
14162 parse_tracepoint_definition (p, utpp);
14163 /* Ask for another packet of tracepoint definition. */
14164 putpkt ("qTsP");
14165 getpkt (&rs->buf, &rs->buf_size, 0);
14166 p = rs->buf;
14167 }
14168 return 0;
14169 }
14170
14171 int
14172 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14173 {
14174 struct remote_state *rs = get_remote_state ();
14175 char *p;
14176
14177 /* Ask for a first packet of variable definition. */
14178 putpkt ("qTfV");
14179 getpkt (&rs->buf, &rs->buf_size, 0);
14180 p = rs->buf;
14181 while (*p && *p != 'l')
14182 {
14183 parse_tsv_definition (p, utsvp);
14184 /* Ask for another packet of variable definition. */
14185 putpkt ("qTsV");
14186 getpkt (&rs->buf, &rs->buf_size, 0);
14187 p = rs->buf;
14188 }
14189 return 0;
14190 }
14191
14192 /* The "set/show range-stepping" show hook. */
14193
14194 static void
14195 show_range_stepping (struct ui_file *file, int from_tty,
14196 struct cmd_list_element *c,
14197 const char *value)
14198 {
14199 fprintf_filtered (file,
14200 _("Debugger's willingness to use range stepping "
14201 "is %s.\n"), value);
14202 }
14203
14204 /* Return true if the vCont;r action is supported by the remote
14205 stub. */
14206
14207 bool
14208 remote_target::vcont_r_supported ()
14209 {
14210 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14211 remote_vcont_probe ();
14212
14213 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14214 && get_remote_state ()->supports_vCont.r);
14215 }
14216
14217 /* The "set/show range-stepping" set hook. */
14218
14219 static void
14220 set_range_stepping (const char *ignore_args, int from_tty,
14221 struct cmd_list_element *c)
14222 {
14223 /* When enabling, check whether range stepping is actually supported
14224 by the target, and warn if not. */
14225 if (use_range_stepping)
14226 {
14227 remote_target *remote = get_current_remote_target ();
14228 if (remote == NULL
14229 || !remote->vcont_r_supported ())
14230 warning (_("Range stepping is not supported by the current target"));
14231 }
14232 }
14233
14234 void
14235 _initialize_remote (void)
14236 {
14237 struct cmd_list_element *cmd;
14238 const char *cmd_name;
14239
14240 /* architecture specific data */
14241 remote_g_packet_data_handle =
14242 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14243
14244 remote_pspace_data
14245 = register_program_space_data_with_cleanup (NULL,
14246 remote_pspace_data_cleanup);
14247
14248 add_target (remote_target_info, remote_target::open);
14249 add_target (extended_remote_target_info, extended_remote_target::open);
14250
14251 /* Hook into new objfile notification. */
14252 gdb::observers::new_objfile.attach (remote_new_objfile);
14253
14254 #if 0
14255 init_remote_threadtests ();
14256 #endif
14257
14258 /* set/show remote ... */
14259
14260 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14261 Remote protocol specific variables\n\
14262 Configure various remote-protocol specific variables such as\n\
14263 the packets being used"),
14264 &remote_set_cmdlist, "set remote ",
14265 0 /* allow-unknown */, &setlist);
14266 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14267 Remote protocol specific variables\n\
14268 Configure various remote-protocol specific variables such as\n\
14269 the packets being used"),
14270 &remote_show_cmdlist, "show remote ",
14271 0 /* allow-unknown */, &showlist);
14272
14273 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14274 Compare section data on target to the exec file.\n\
14275 Argument is a single section name (default: all loaded sections).\n\
14276 To compare only read-only loaded sections, specify the -r option."),
14277 &cmdlist);
14278
14279 add_cmd ("packet", class_maintenance, packet_command, _("\
14280 Send an arbitrary packet to a remote target.\n\
14281 maintenance packet TEXT\n\
14282 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14283 this command sends the string TEXT to the inferior, and displays the\n\
14284 response packet. GDB supplies the initial `$' character, and the\n\
14285 terminating `#' character and checksum."),
14286 &maintenancelist);
14287
14288 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14289 Set whether to send break if interrupted."), _("\
14290 Show whether to send break if interrupted."), _("\
14291 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14292 set_remotebreak, show_remotebreak,
14293 &setlist, &showlist);
14294 cmd_name = "remotebreak";
14295 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14296 deprecate_cmd (cmd, "set remote interrupt-sequence");
14297 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14298 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14299 deprecate_cmd (cmd, "show remote interrupt-sequence");
14300
14301 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14302 interrupt_sequence_modes, &interrupt_sequence_mode,
14303 _("\
14304 Set interrupt sequence to remote target."), _("\
14305 Show interrupt sequence to remote target."), _("\
14306 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14307 NULL, show_interrupt_sequence,
14308 &remote_set_cmdlist,
14309 &remote_show_cmdlist);
14310
14311 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14312 &interrupt_on_connect, _("\
14313 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14314 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14315 If set, interrupt sequence is sent to remote target."),
14316 NULL, NULL,
14317 &remote_set_cmdlist, &remote_show_cmdlist);
14318
14319 /* Install commands for configuring memory read/write packets. */
14320
14321 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14322 Set the maximum number of bytes per memory write packet (deprecated)."),
14323 &setlist);
14324 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14325 Show the maximum number of bytes per memory write packet (deprecated)."),
14326 &showlist);
14327 add_cmd ("memory-write-packet-size", no_class,
14328 set_memory_write_packet_size, _("\
14329 Set the maximum number of bytes per memory-write packet.\n\
14330 Specify the number of bytes in a packet or 0 (zero) for the\n\
14331 default packet size. The actual limit is further reduced\n\
14332 dependent on the target. Specify ``fixed'' to disable the\n\
14333 further restriction and ``limit'' to enable that restriction."),
14334 &remote_set_cmdlist);
14335 add_cmd ("memory-read-packet-size", no_class,
14336 set_memory_read_packet_size, _("\
14337 Set the maximum number of bytes per memory-read packet.\n\
14338 Specify the number of bytes in a packet or 0 (zero) for the\n\
14339 default packet size. The actual limit is further reduced\n\
14340 dependent on the target. Specify ``fixed'' to disable the\n\
14341 further restriction and ``limit'' to enable that restriction."),
14342 &remote_set_cmdlist);
14343 add_cmd ("memory-write-packet-size", no_class,
14344 show_memory_write_packet_size,
14345 _("Show the maximum number of bytes per memory-write packet."),
14346 &remote_show_cmdlist);
14347 add_cmd ("memory-read-packet-size", no_class,
14348 show_memory_read_packet_size,
14349 _("Show the maximum number of bytes per memory-read packet."),
14350 &remote_show_cmdlist);
14351
14352 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14353 &remote_hw_watchpoint_limit, _("\
14354 Set the maximum number of target hardware watchpoints."), _("\
14355 Show the maximum number of target hardware watchpoints."), _("\
14356 Specify a negative limit for unlimited."),
14357 NULL, NULL, /* FIXME: i18n: The maximum
14358 number of target hardware
14359 watchpoints is %s. */
14360 &remote_set_cmdlist, &remote_show_cmdlist);
14361 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14362 &remote_hw_watchpoint_length_limit, _("\
14363 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14364 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14365 Specify a negative limit for unlimited."),
14366 NULL, NULL, /* FIXME: i18n: The maximum
14367 length (in bytes) of a target
14368 hardware watchpoint is %s. */
14369 &remote_set_cmdlist, &remote_show_cmdlist);
14370 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14371 &remote_hw_breakpoint_limit, _("\
14372 Set the maximum number of target hardware breakpoints."), _("\
14373 Show the maximum number of target hardware breakpoints."), _("\
14374 Specify a negative limit for unlimited."),
14375 NULL, NULL, /* FIXME: i18n: The maximum
14376 number of target hardware
14377 breakpoints is %s. */
14378 &remote_set_cmdlist, &remote_show_cmdlist);
14379
14380 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14381 &remote_address_size, _("\
14382 Set the maximum size of the address (in bits) in a memory packet."), _("\
14383 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14384 NULL,
14385 NULL, /* FIXME: i18n: */
14386 &setlist, &showlist);
14387
14388 init_all_packet_configs ();
14389
14390 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14391 "X", "binary-download", 1);
14392
14393 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14394 "vCont", "verbose-resume", 0);
14395
14396 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14397 "QPassSignals", "pass-signals", 0);
14398
14399 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14400 "QCatchSyscalls", "catch-syscalls", 0);
14401
14402 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14403 "QProgramSignals", "program-signals", 0);
14404
14405 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14406 "QSetWorkingDir", "set-working-dir", 0);
14407
14408 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14409 "QStartupWithShell", "startup-with-shell", 0);
14410
14411 add_packet_config_cmd (&remote_protocol_packets
14412 [PACKET_QEnvironmentHexEncoded],
14413 "QEnvironmentHexEncoded", "environment-hex-encoded",
14414 0);
14415
14416 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14417 "QEnvironmentReset", "environment-reset",
14418 0);
14419
14420 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14421 "QEnvironmentUnset", "environment-unset",
14422 0);
14423
14424 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14425 "qSymbol", "symbol-lookup", 0);
14426
14427 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14428 "P", "set-register", 1);
14429
14430 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14431 "p", "fetch-register", 1);
14432
14433 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14434 "Z0", "software-breakpoint", 0);
14435
14436 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14437 "Z1", "hardware-breakpoint", 0);
14438
14439 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14440 "Z2", "write-watchpoint", 0);
14441
14442 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14443 "Z3", "read-watchpoint", 0);
14444
14445 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14446 "Z4", "access-watchpoint", 0);
14447
14448 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14449 "qXfer:auxv:read", "read-aux-vector", 0);
14450
14451 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14452 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14453
14454 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14455 "qXfer:features:read", "target-features", 0);
14456
14457 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14458 "qXfer:libraries:read", "library-info", 0);
14459
14460 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14461 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14462
14463 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14464 "qXfer:memory-map:read", "memory-map", 0);
14465
14466 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14467 "qXfer:spu:read", "read-spu-object", 0);
14468
14469 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14470 "qXfer:spu:write", "write-spu-object", 0);
14471
14472 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14473 "qXfer:osdata:read", "osdata", 0);
14474
14475 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14476 "qXfer:threads:read", "threads", 0);
14477
14478 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14479 "qXfer:siginfo:read", "read-siginfo-object", 0);
14480
14481 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14482 "qXfer:siginfo:write", "write-siginfo-object", 0);
14483
14484 add_packet_config_cmd
14485 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14486 "qXfer:traceframe-info:read", "traceframe-info", 0);
14487
14488 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14489 "qXfer:uib:read", "unwind-info-block", 0);
14490
14491 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14492 "qGetTLSAddr", "get-thread-local-storage-address",
14493 0);
14494
14495 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14496 "qGetTIBAddr", "get-thread-information-block-address",
14497 0);
14498
14499 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14500 "bc", "reverse-continue", 0);
14501
14502 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14503 "bs", "reverse-step", 0);
14504
14505 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14506 "qSupported", "supported-packets", 0);
14507
14508 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14509 "qSearch:memory", "search-memory", 0);
14510
14511 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14512 "qTStatus", "trace-status", 0);
14513
14514 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14515 "vFile:setfs", "hostio-setfs", 0);
14516
14517 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14518 "vFile:open", "hostio-open", 0);
14519
14520 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14521 "vFile:pread", "hostio-pread", 0);
14522
14523 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14524 "vFile:pwrite", "hostio-pwrite", 0);
14525
14526 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14527 "vFile:close", "hostio-close", 0);
14528
14529 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14530 "vFile:unlink", "hostio-unlink", 0);
14531
14532 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14533 "vFile:readlink", "hostio-readlink", 0);
14534
14535 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14536 "vFile:fstat", "hostio-fstat", 0);
14537
14538 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14539 "vAttach", "attach", 0);
14540
14541 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14542 "vRun", "run", 0);
14543
14544 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14545 "QStartNoAckMode", "noack", 0);
14546
14547 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14548 "vKill", "kill", 0);
14549
14550 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14551 "qAttached", "query-attached", 0);
14552
14553 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14554 "ConditionalTracepoints",
14555 "conditional-tracepoints", 0);
14556
14557 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14558 "ConditionalBreakpoints",
14559 "conditional-breakpoints", 0);
14560
14561 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14562 "BreakpointCommands",
14563 "breakpoint-commands", 0);
14564
14565 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14566 "FastTracepoints", "fast-tracepoints", 0);
14567
14568 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14569 "TracepointSource", "TracepointSource", 0);
14570
14571 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14572 "QAllow", "allow", 0);
14573
14574 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14575 "StaticTracepoints", "static-tracepoints", 0);
14576
14577 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14578 "InstallInTrace", "install-in-trace", 0);
14579
14580 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14581 "qXfer:statictrace:read", "read-sdata-object", 0);
14582
14583 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14584 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14585
14586 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14587 "QDisableRandomization", "disable-randomization", 0);
14588
14589 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14590 "QAgent", "agent", 0);
14591
14592 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14593 "QTBuffer:size", "trace-buffer-size", 0);
14594
14595 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14596 "Qbtrace:off", "disable-btrace", 0);
14597
14598 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14599 "Qbtrace:bts", "enable-btrace-bts", 0);
14600
14601 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14602 "Qbtrace:pt", "enable-btrace-pt", 0);
14603
14604 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14605 "qXfer:btrace", "read-btrace", 0);
14606
14607 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14608 "qXfer:btrace-conf", "read-btrace-conf", 0);
14609
14610 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14611 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14612
14613 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14614 "multiprocess-feature", "multiprocess-feature", 0);
14615
14616 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14617 "swbreak-feature", "swbreak-feature", 0);
14618
14619 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14620 "hwbreak-feature", "hwbreak-feature", 0);
14621
14622 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14623 "fork-event-feature", "fork-event-feature", 0);
14624
14625 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14626 "vfork-event-feature", "vfork-event-feature", 0);
14627
14628 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14629 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14630
14631 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14632 "vContSupported", "verbose-resume-supported", 0);
14633
14634 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14635 "exec-event-feature", "exec-event-feature", 0);
14636
14637 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14638 "vCtrlC", "ctrl-c", 0);
14639
14640 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14641 "QThreadEvents", "thread-events", 0);
14642
14643 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14644 "N stop reply", "no-resumed-stop-reply", 0);
14645
14646 /* Assert that we've registered "set remote foo-packet" commands
14647 for all packet configs. */
14648 {
14649 int i;
14650
14651 for (i = 0; i < PACKET_MAX; i++)
14652 {
14653 /* Ideally all configs would have a command associated. Some
14654 still don't though. */
14655 int excepted;
14656
14657 switch (i)
14658 {
14659 case PACKET_QNonStop:
14660 case PACKET_EnableDisableTracepoints_feature:
14661 case PACKET_tracenz_feature:
14662 case PACKET_DisconnectedTracing_feature:
14663 case PACKET_augmented_libraries_svr4_read_feature:
14664 case PACKET_qCRC:
14665 /* Additions to this list need to be well justified:
14666 pre-existing packets are OK; new packets are not. */
14667 excepted = 1;
14668 break;
14669 default:
14670 excepted = 0;
14671 break;
14672 }
14673
14674 /* This catches both forgetting to add a config command, and
14675 forgetting to remove a packet from the exception list. */
14676 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14677 }
14678 }
14679
14680 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14681 Z sub-packet has its own set and show commands, but users may
14682 have sets to this variable in their .gdbinit files (or in their
14683 documentation). */
14684 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14685 &remote_Z_packet_detect, _("\
14686 Set use of remote protocol `Z' packets"), _("\
14687 Show use of remote protocol `Z' packets "), _("\
14688 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14689 packets."),
14690 set_remote_protocol_Z_packet_cmd,
14691 show_remote_protocol_Z_packet_cmd,
14692 /* FIXME: i18n: Use of remote protocol
14693 `Z' packets is %s. */
14694 &remote_set_cmdlist, &remote_show_cmdlist);
14695
14696 add_prefix_cmd ("remote", class_files, remote_command, _("\
14697 Manipulate files on the remote system\n\
14698 Transfer files to and from the remote target system."),
14699 &remote_cmdlist, "remote ",
14700 0 /* allow-unknown */, &cmdlist);
14701
14702 add_cmd ("put", class_files, remote_put_command,
14703 _("Copy a local file to the remote system."),
14704 &remote_cmdlist);
14705
14706 add_cmd ("get", class_files, remote_get_command,
14707 _("Copy a remote file to the local system."),
14708 &remote_cmdlist);
14709
14710 add_cmd ("delete", class_files, remote_delete_command,
14711 _("Delete a remote file."),
14712 &remote_cmdlist);
14713
14714 add_setshow_string_noescape_cmd ("exec-file", class_files,
14715 &remote_exec_file_var, _("\
14716 Set the remote pathname for \"run\""), _("\
14717 Show the remote pathname for \"run\""), NULL,
14718 set_remote_exec_file,
14719 show_remote_exec_file,
14720 &remote_set_cmdlist,
14721 &remote_show_cmdlist);
14722
14723 add_setshow_boolean_cmd ("range-stepping", class_run,
14724 &use_range_stepping, _("\
14725 Enable or disable range stepping."), _("\
14726 Show whether target-assisted range stepping is enabled."), _("\
14727 If on, and the target supports it, when stepping a source line, GDB\n\
14728 tells the target to step the corresponding range of addresses itself instead\n\
14729 of issuing multiple single-steps. This speeds up source level\n\
14730 stepping. If off, GDB always issues single-steps, even if range\n\
14731 stepping is supported by the target. The default is on."),
14732 set_range_stepping,
14733 show_range_stepping,
14734 &setlist,
14735 &showlist);
14736
14737 /* Eventually initialize fileio. See fileio.c */
14738 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14739
14740 /* Take advantage of the fact that the TID field is not used, to tag
14741 special ptids with it set to != 0. */
14742 magic_null_ptid = ptid_build (42000, -1, 1);
14743 not_sent_ptid = ptid_build (42000, -2, 1);
14744 any_thread_ptid = ptid_build (42000, 0, 1);
14745 }
This page took 0.332741 seconds and 5 git commands to generate.