Remove regcache_cooked_write_part
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
e2882c85 3 Copyright (C) 1988-2018 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
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
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
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
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
76727919 39#include "observable.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
c0272db5 73#include "record-btrace.h"
325fac50 74#include <algorithm>
2ec845e7 75#include "common/scoped_restore.h"
0a2dde4a 76#include "environ.h"
f6327dcb 77#include "common/byte-vector.h"
9d6eea31 78#include <unordered_map>
35b1e5cc 79
f6ac5f3d
PA
80/* The remote target. */
81
d9f719f1
PA
82static const char remote_doc[] = N_("\
83Use a remote computer via a serial line, using a gdb-specific protocol.\n\
84Specify the serial device it is connected to\n\
85(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
86
6b8edb51
PA
87#define OPAQUETHREADBYTES 8
88
89/* a 64 bit opaque identifier */
90typedef unsigned char threadref[OPAQUETHREADBYTES];
91
92struct gdb_ext_thread_info;
93struct threads_listing_context;
94typedef int (*rmt_thread_action) (threadref *ref, void *context);
95struct protocol_feature;
96struct packet_reg;
97
98struct stop_reply;
99typedef struct stop_reply *stop_reply_p;
100
101DECLARE_QUEUE_P (stop_reply_p);
102DEFINE_QUEUE_P (stop_reply_p);
103
104/* Generic configuration support for packets the stub optionally
105 supports. Allows the user to specify the use of the packet as well
106 as allowing GDB to auto-detect support in the remote stub. */
107
108enum packet_support
109 {
110 PACKET_SUPPORT_UNKNOWN = 0,
111 PACKET_ENABLE,
112 PACKET_DISABLE
113 };
114
115/* Analyze a packet's return value and update the packet config
116 accordingly. */
117
118enum packet_result
119{
120 PACKET_ERROR,
121 PACKET_OK,
122 PACKET_UNKNOWN
123};
124
125struct threads_listing_context;
3c69da40
PA
126
127/* Stub vCont actions support.
128
129 Each field is a boolean flag indicating whether the stub reports
130 support for the corresponding action. */
131
132struct vCont_action_support
133{
134 /* vCont;t */
135 bool t = false;
136
137 /* vCont;r */
138 bool r = false;
139
140 /* vCont;s */
141 bool s = false;
142
143 /* vCont;S */
144 bool S = false;
145};
146
147/* About this many threadisds fit in a packet. */
148
149#define MAXTHREADLISTRESULTS 32
150
151/* Data for the vFile:pread readahead cache. */
152
153struct readahead_cache
154{
155 /* Invalidate the readahead cache. */
156 void invalidate ();
157
158 /* Invalidate the readahead cache if it is holding data for FD. */
159 void invalidate_fd (int fd);
160
161 /* Serve pread from the readahead cache. Returns number of bytes
162 read, or 0 if the request can't be served from the cache. */
163 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
164
165 /* The file descriptor for the file that is being cached. -1 if the
166 cache is invalid. */
167 int fd = -1;
168
169 /* The offset into the file that the cache buffer corresponds
170 to. */
171 ULONGEST offset = 0;
172
173 /* The buffer holding the cache contents. */
174 gdb_byte *buf = nullptr;
175 /* The buffer's size. We try to read as much as fits into a packet
176 at a time. */
177 size_t bufsize = 0;
178
179 /* Cache hit and miss counters. */
180 ULONGEST hit_count = 0;
181 ULONGEST miss_count = 0;
182};
183
184/* Description of the remote protocol for a given architecture. */
185
186struct packet_reg
187{
188 long offset; /* Offset into G packet. */
189 long regnum; /* GDB's internal register number. */
190 LONGEST pnum; /* Remote protocol register number. */
191 int in_g_packet; /* Always part of G packet. */
192 /* long size in bytes; == register_size (target_gdbarch (), regnum);
193 at present. */
194 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
195 at present. */
196};
197
198struct remote_arch_state
199{
200 explicit remote_arch_state (struct gdbarch *gdbarch);
201
202 /* Description of the remote protocol registers. */
203 long sizeof_g_packet;
204
205 /* Description of the remote protocol registers indexed by REGNUM
206 (making an array gdbarch_num_regs in size). */
207 std::unique_ptr<packet_reg[]> regs;
208
209 /* This is the size (in chars) of the first response to the ``g''
210 packet. It is used as a heuristic when determining the maximum
211 size of memory-read and memory-write packets. A target will
212 typically only reserve a buffer large enough to hold the ``g''
213 packet. The size does not include packet overhead (headers and
214 trailers). */
215 long actual_register_packet_size;
216
217 /* This is the maximum size (in chars) of a non read/write packet.
218 It is also used as a cap on the size of read/write packets. */
219 long remote_packet_size;
220};
221
222/* Description of the remote protocol state for the currently
223 connected target. This is per-target state, and independent of the
224 selected architecture. */
225
226class remote_state
227{
228public:
229
230 remote_state ();
231 ~remote_state ();
232
233 /* Get the remote arch state for GDBARCH. */
234 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
235
236public: /* data */
237
238 /* A buffer to use for incoming packets, and its current size. The
239 buffer is grown dynamically for larger incoming packets.
240 Outgoing packets may also be constructed in this buffer.
241 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
242 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
243 packets. */
244 char *buf;
245 long buf_size;
246
247 /* True if we're going through initial connection setup (finding out
248 about the remote side's threads, relocating symbols, etc.). */
249 bool starting_up = false;
250
251 /* If we negotiated packet size explicitly (and thus can bypass
252 heuristics for the largest packet size that will not overflow
253 a buffer in the stub), this will be set to that packet size.
254 Otherwise zero, meaning to use the guessed size. */
255 long explicit_packet_size = 0;
256
257 /* remote_wait is normally called when the target is running and
258 waits for a stop reply packet. But sometimes we need to call it
259 when the target is already stopped. We can send a "?" packet
260 and have remote_wait read the response. Or, if we already have
261 the response, we can stash it in BUF and tell remote_wait to
262 skip calling getpkt. This flag is set when BUF contains a
263 stop reply packet and the target is not waiting. */
264 int cached_wait_status = 0;
265
266 /* True, if in no ack mode. That is, neither GDB nor the stub will
267 expect acks from each other. The connection is assumed to be
268 reliable. */
269 bool noack_mode = false;
270
271 /* True if we're connected in extended remote mode. */
272 bool extended = false;
273
274 /* True if we resumed the target and we're waiting for the target to
275 stop. In the mean time, we can't start another command/query.
276 The remote server wouldn't be ready to process it, so we'd
277 timeout waiting for a reply that would never come and eventually
278 we'd close the connection. This can happen in asynchronous mode
279 because we allow GDB commands while the target is running. */
280 bool waiting_for_stop_reply = false;
281
282 /* The status of the stub support for the various vCont actions. */
283 vCont_action_support supports_vCont;
284
285 /* True if the user has pressed Ctrl-C, but the target hasn't
286 responded to that. */
287 bool ctrlc_pending_p = false;
288
289 /* True if we saw a Ctrl-C while reading or writing from/to the
290 remote descriptor. At that point it is not safe to send a remote
291 interrupt packet, so we instead remember we saw the Ctrl-C and
292 process it once we're done with sending/receiving the current
293 packet, which should be shortly. If however that takes too long,
294 and the user presses Ctrl-C again, we offer to disconnect. */
295 bool got_ctrlc_during_io = false;
296
297 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
298 remote_open knows that we don't have a file open when the program
299 starts. */
300 struct serial *remote_desc = nullptr;
301
302 /* These are the threads which we last sent to the remote system. The
303 TID member will be -1 for all or -2 for not sent yet. */
304 ptid_t general_thread = null_ptid;
305 ptid_t continue_thread = null_ptid;
306
307 /* This is the traceframe which we last selected on the remote system.
308 It will be -1 if no traceframe is selected. */
309 int remote_traceframe_number = -1;
310
311 char *last_pass_packet = nullptr;
312
313 /* The last QProgramSignals packet sent to the target. We bypass
314 sending a new program signals list down to the target if the new
315 packet is exactly the same as the last we sent. IOW, we only let
316 the target know about program signals list changes. */
317 char *last_program_signals_packet = nullptr;
318
319 gdb_signal last_sent_signal = GDB_SIGNAL_0;
320
321 bool last_sent_step = false;
322
323 /* The execution direction of the last resume we got. */
324 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
325
326 char *finished_object = nullptr;
327 char *finished_annex = nullptr;
328 ULONGEST finished_offset = 0;
329
330 /* Should we try the 'ThreadInfo' query packet?
331
332 This variable (NOT available to the user: auto-detect only!)
333 determines whether GDB will use the new, simpler "ThreadInfo"
334 query or the older, more complex syntax for thread queries.
335 This is an auto-detect variable (set to true at each connect,
336 and set to false when the target fails to recognize it). */
337 bool use_threadinfo_query = false;
338 bool use_threadextra_query = false;
339
340 threadref echo_nextthread {};
341 threadref nextthread {};
342 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
343
344 /* The state of remote notification. */
345 struct remote_notif_state *notif_state = nullptr;
346
347 /* The branch trace configuration. */
348 struct btrace_config btrace_config {};
349
350 /* The argument to the last "vFile:setfs:" packet we sent, used
351 to avoid sending repeated unnecessary "vFile:setfs:" packets.
352 Initialized to -1 to indicate that no "vFile:setfs:" packet
353 has yet been sent. */
354 int fs_pid = -1;
355
356 /* A readahead cache for vFile:pread. Often, reading a binary
357 involves a sequence of small reads. E.g., when parsing an ELF
358 file. A readahead cache helps mostly the case of remote
359 debugging on a connection with higher latency, due to the
360 request/reply nature of the RSP. We only cache data for a single
361 file descriptor at a time. */
362 struct readahead_cache readahead_cache;
363
364 /* The list of already fetched and acknowledged stop events. This
365 queue is used for notification Stop, and other notifications
366 don't need queue for their events, because the notification
367 events of Stop can't be consumed immediately, so that events
368 should be queued first, and be consumed by remote_wait_{ns,as}
369 one per time. Other notifications can consume their events
370 immediately, so queue is not needed for them. */
371 QUEUE (stop_reply_p) *stop_reply_queue;
372
373 /* Asynchronous signal handle registered as event loop source for
374 when we have pending events ready to be passed to the core. */
375 struct async_event_handler *remote_async_inferior_event_token = nullptr;
376
377 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
378 ``forever'' still use the normal timeout mechanism. This is
379 currently used by the ASYNC code to guarentee that target reads
380 during the initial connect always time-out. Once getpkt has been
381 modified to return a timeout indication and, in turn
382 remote_wait()/wait_for_inferior() have gained a timeout parameter
383 this can go away. */
384 int wait_forever_enabled_p = 1;
385
386private:
387 /* Mapping of remote protocol data for each gdbarch. Usually there
388 is only one entry here, though we may see more with stubs that
389 support multi-process. */
390 std::unordered_map<struct gdbarch *, remote_arch_state>
391 m_arch_states;
392};
6b8edb51 393
d9f719f1
PA
394static const target_info remote_target_info = {
395 "remote",
396 N_("Remote serial target in gdb-specific protocol"),
397 remote_doc
398};
399
f6ac5f3d
PA
400class remote_target : public target_ops
401{
402public:
403 remote_target ()
404 {
405 to_stratum = process_stratum;
406 }
6b8edb51 407 ~remote_target () override;
f6ac5f3d 408
d9f719f1
PA
409 const target_info &info () const override
410 { return remote_target_info; }
f6ac5f3d
PA
411
412 thread_control_capabilities get_thread_control_capabilities () override
413 { return tc_schedlock; }
414
d9f719f1
PA
415 /* Open a remote connection. */
416 static void open (const char *, int);
417
f6ac5f3d
PA
418 void close () override;
419
420 void detach (inferior *, int) override;
421 void disconnect (const char *, int) override;
422
423 void commit_resume () override;
424 void resume (ptid_t, int, enum gdb_signal) override;
425 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
426
427 void fetch_registers (struct regcache *, int) override;
428 void store_registers (struct regcache *, int) override;
429 void prepare_to_store (struct regcache *) override;
430
431 void files_info () override;
432
433 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
434
435 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
436 enum remove_bp_reason) override;
437
438
57810aa7
PA
439 bool stopped_by_sw_breakpoint () override;
440 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 441
57810aa7 442 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 443
57810aa7 444 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 445
57810aa7 446 bool stopped_by_watchpoint () override;
f6ac5f3d 447
57810aa7 448 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 449
57810aa7 450 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
451
452 int can_use_hw_breakpoint (enum bptype, int, int) override;
453
454 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
455
456 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
457
458 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
459
460 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
461 struct expression *) override;
462
463 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
464 struct expression *) override;
465
466 void kill () override;
467
468 void load (const char *, int) override;
469
470 void mourn_inferior () override;
471
472 void pass_signals (int, unsigned char *) override;
473
474 int set_syscall_catchpoint (int, bool, int,
475 gdb::array_view<const int>) override;
476
477 void program_signals (int, unsigned char *) override;
478
57810aa7 479 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
480
481 const char *thread_name (struct thread_info *) override;
482
483 void update_thread_list () override;
484
485 const char *pid_to_str (ptid_t) override;
486
487 const char *extra_thread_info (struct thread_info *) override;
488
489 ptid_t get_ada_task_ptid (long lwp, long thread) override;
490
491 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
492 int handle_len,
493 inferior *inf) override;
494
495 void stop (ptid_t) override;
496
497 void interrupt () override;
498
499 void pass_ctrlc () override;
500
501 enum target_xfer_status xfer_partial (enum target_object object,
502 const char *annex,
503 gdb_byte *readbuf,
504 const gdb_byte *writebuf,
505 ULONGEST offset, ULONGEST len,
506 ULONGEST *xfered_len) override;
507
508 ULONGEST get_memory_xfer_limit () override;
509
510 void rcmd (const char *command, struct ui_file *output) override;
511
512 char *pid_to_exec_file (int pid) override;
513
514 void log_command (const char *cmd) override
515 {
516 serial_log_command (this, cmd);
517 }
518
519 CORE_ADDR get_thread_local_address (ptid_t ptid,
520 CORE_ADDR load_module_addr,
521 CORE_ADDR offset) override;
522
57810aa7
PA
523 bool has_all_memory () override { return default_child_has_all_memory (); }
524 bool has_memory () override { return default_child_has_memory (); }
525 bool has_stack () override { return default_child_has_stack (); }
526 bool has_registers () override { return default_child_has_registers (); }
527 bool has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
f6ac5f3d 528
57810aa7 529 bool can_execute_reverse () override;
f6ac5f3d
PA
530
531 std::vector<mem_region> memory_map () override;
532
533 void flash_erase (ULONGEST address, LONGEST length) override;
534
535 void flash_done () override;
536
537 const struct target_desc *read_description () override;
538
539 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
540 const gdb_byte *pattern, ULONGEST pattern_len,
541 CORE_ADDR *found_addrp) override;
542
57810aa7 543 bool can_async_p () override;
f6ac5f3d 544
57810aa7 545 bool is_async_p () override;
f6ac5f3d
PA
546
547 void async (int) override;
548
549 void thread_events (int) override;
550
551 int can_do_single_step () override;
552
553 void terminal_inferior () override;
554
555 void terminal_ours () override;
556
57810aa7 557 bool supports_non_stop () override;
f6ac5f3d 558
57810aa7 559 bool supports_multi_process () override;
f6ac5f3d 560
57810aa7 561 bool supports_disable_randomization () override;
f6ac5f3d 562
57810aa7 563 bool filesystem_is_local () override;
f6ac5f3d
PA
564
565
566 int fileio_open (struct inferior *inf, const char *filename,
567 int flags, int mode, int warn_if_slow,
568 int *target_errno) override;
569
570 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
571 ULONGEST offset, int *target_errno) override;
572
573 int fileio_pread (int fd, gdb_byte *read_buf, int len,
574 ULONGEST offset, int *target_errno) override;
575
576 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
577
578 int fileio_close (int fd, int *target_errno) override;
579
580 int fileio_unlink (struct inferior *inf,
581 const char *filename,
582 int *target_errno) override;
583
584 gdb::optional<std::string>
585 fileio_readlink (struct inferior *inf,
586 const char *filename,
587 int *target_errno) override;
588
57810aa7 589 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 590
57810aa7 591 bool supports_string_tracing () override;
f6ac5f3d 592
57810aa7 593 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 594
57810aa7 595 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
596
597 void trace_init () override;
598
599 void download_tracepoint (struct bp_location *location) override;
600
57810aa7 601 bool can_download_tracepoint () override;
f6ac5f3d
PA
602
603 void download_trace_state_variable (const trace_state_variable &tsv) override;
604
605 void enable_tracepoint (struct bp_location *location) override;
606
607 void disable_tracepoint (struct bp_location *location) override;
608
609 void trace_set_readonly_regions () override;
610
611 void trace_start () override;
612
613 int get_trace_status (struct trace_status *ts) override;
614
615 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
616 override;
617
618 void trace_stop () override;
619
620 int trace_find (enum trace_find_type type, int num,
621 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
622
57810aa7 623 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
624
625 int save_trace_data (const char *filename) override;
626
627 int upload_tracepoints (struct uploaded_tp **utpp) override;
628
629 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
630
631 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
632
633 int get_min_fast_tracepoint_insn_len () override;
634
635 void set_disconnected_tracing (int val) override;
636
637 void set_circular_trace_buffer (int val) override;
638
639 void set_trace_buffer_size (LONGEST val) override;
640
57810aa7
PA
641 bool set_trace_notes (const char *user, const char *notes,
642 const char *stopnotes) override;
f6ac5f3d
PA
643
644 int core_of_thread (ptid_t ptid) override;
645
646 int verify_memory (const gdb_byte *data,
647 CORE_ADDR memaddr, ULONGEST size) override;
648
649
57810aa7 650 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
651
652 void set_permissions () override;
653
654 bool static_tracepoint_marker_at (CORE_ADDR,
655 struct static_tracepoint_marker *marker)
656 override;
657
658 std::vector<static_tracepoint_marker>
659 static_tracepoint_markers_by_strid (const char *id) override;
660
661 traceframe_info_up traceframe_info () override;
662
57810aa7
PA
663 bool use_agent (bool use) override;
664 bool can_use_agent () override;
f6ac5f3d
PA
665
666 struct btrace_target_info *enable_btrace (ptid_t ptid,
667 const struct btrace_config *conf) override;
668
669 void disable_btrace (struct btrace_target_info *tinfo) override;
670
671 void teardown_btrace (struct btrace_target_info *tinfo) override;
672
673 enum btrace_error read_btrace (struct btrace_data *data,
674 struct btrace_target_info *btinfo,
675 enum btrace_read_type type) override;
676
677 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 678 bool augmented_libraries_svr4_read () override;
f6ac5f3d
PA
679 int follow_fork (int, int) override;
680 void follow_exec (struct inferior *, char *) override;
681 int insert_fork_catchpoint (int) override;
682 int remove_fork_catchpoint (int) override;
683 int insert_vfork_catchpoint (int) override;
684 int remove_vfork_catchpoint (int) override;
685 int insert_exec_catchpoint (int) override;
686 int remove_exec_catchpoint (int) override;
687 enum exec_direction_kind execution_direction () override;
688
6b8edb51
PA
689public: /* Remote specific methods. */
690
691 void remote_download_command_source (int num, ULONGEST addr,
692 struct command_line *cmds);
693
694 void remote_file_put (const char *local_file, const char *remote_file,
695 int from_tty);
696 void remote_file_get (const char *remote_file, const char *local_file,
697 int from_tty);
698 void remote_file_delete (const char *remote_file, int from_tty);
699
700 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
701 ULONGEST offset, int *remote_errno);
702 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
703 ULONGEST offset, int *remote_errno);
704 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
705 ULONGEST offset, int *remote_errno);
706
707 int remote_hostio_send_command (int command_bytes, int which_packet,
708 int *remote_errno, char **attachment,
709 int *attachment_len);
710 int remote_hostio_set_filesystem (struct inferior *inf,
711 int *remote_errno);
712 /* We should get rid of this and use fileio_open directly. */
713 int remote_hostio_open (struct inferior *inf, const char *filename,
714 int flags, int mode, int warn_if_slow,
715 int *remote_errno);
716 int remote_hostio_close (int fd, int *remote_errno);
717
718 int remote_hostio_unlink (inferior *inf, const char *filename,
719 int *remote_errno);
720
721 struct remote_state *get_remote_state ();
722
723 long get_remote_packet_size (void);
724 long get_memory_packet_size (struct memory_packet_config *config);
725
726 long get_memory_write_packet_size ();
727 long get_memory_read_packet_size ();
728
729 char *append_pending_thread_resumptions (char *p, char *endp,
730 ptid_t ptid);
d9f719f1 731 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d 732 void start_remote (int from_tty, int extended_p);
6b8edb51
PA
733 void remote_detach_1 (int from_tty, struct inferior *inf);
734
735 char *append_resumption (char *p, char *endp,
736 ptid_t ptid, int step, gdb_signal siggnal);
737 int remote_resume_with_vcont (ptid_t ptid, int step,
738 gdb_signal siggnal);
739
740 void add_current_inferior_and_thread (char *wait_status);
741
742 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
743 int options);
744 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
745 int options);
746
747 ptid_t process_stop_reply (struct stop_reply *stop_reply,
748 target_waitstatus *status);
749
750 void remote_notice_new_inferior (ptid_t currthread, int executing);
751
752 void process_initial_stop_replies (int from_tty);
753
754 void remote_add_thread (ptid_t ptid, bool running, bool executing);
755
756 void btrace_sync_conf (const btrace_config *conf);
757
758 void remote_btrace_maybe_reopen ();
759
760 void remove_new_fork_children (threads_listing_context *context);
761 void kill_new_fork_children (int pid);
762 void discard_pending_stop_replies (struct inferior *inf);
763 int stop_reply_queue_length ();
764
765 void check_pending_events_prevent_wildcard_vcont
766 (int *may_global_wildcard_vcont);
767
768 void discard_pending_stop_replies_in_queue ();
769 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
770 struct stop_reply *queued_stop_reply (ptid_t ptid);
771 int peek_stop_reply (ptid_t ptid);
772 void remote_parse_stop_reply (char *buf, stop_reply *event);
773
774 void remote_stop_ns (ptid_t ptid);
775 void remote_interrupt_as ();
776 void remote_interrupt_ns ();
777
778 char *remote_get_noisy_reply ();
779 int remote_query_attached (int pid);
780 inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
781 int try_open_exec);
782
783 ptid_t remote_current_thread (ptid_t oldpid);
784 ptid_t get_current_thread (char *wait_status);
785
786 void set_thread (ptid_t ptid, int gen);
787 void set_general_thread (ptid_t ptid);
788 void set_continue_thread (ptid_t ptid);
789 void set_general_process ();
790
791 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
792
793 int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
794 gdb_ext_thread_info *info);
795 int remote_get_threadinfo (threadref *threadid, int fieldset,
796 gdb_ext_thread_info *info);
797
798 int parse_threadlist_response (char *pkt, int result_limit,
799 threadref *original_echo,
800 threadref *resultlist,
801 int *doneflag);
802 int remote_get_threadlist (int startflag, threadref *nextthread,
803 int result_limit, int *done, int *result_count,
804 threadref *threadlist);
805
806 int remote_threadlist_iterator (rmt_thread_action stepfunction,
807 void *context, int looplimit);
808
809 int remote_get_threads_with_ql (threads_listing_context *context);
810 int remote_get_threads_with_qxfer (threads_listing_context *context);
811 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
812
813 void extended_remote_restart ();
814
815 void get_offsets ();
816
817 void remote_check_symbols ();
818
819 void remote_supported_packet (const struct protocol_feature *feature,
820 enum packet_support support,
821 const char *argument);
822
823 void remote_query_supported ();
824
825 void remote_packet_size (const protocol_feature *feature,
826 packet_support support, const char *value);
827
828 void remote_serial_quit_handler ();
829
830 void remote_detach_pid (int pid);
831
832 void remote_vcont_probe ();
833
834 void remote_resume_with_hc (ptid_t ptid, int step,
835 gdb_signal siggnal);
836
837 void send_interrupt_sequence ();
838 void interrupt_query ();
839
840 void remote_notif_get_pending_events (notif_client *nc);
841
842 int fetch_register_using_p (struct regcache *regcache,
843 packet_reg *reg);
844 int send_g_packet ();
845 void process_g_packet (struct regcache *regcache);
846 void fetch_registers_using_g (struct regcache *regcache);
847 int store_register_using_P (const struct regcache *regcache,
848 packet_reg *reg);
849 void store_registers_using_G (const struct regcache *regcache);
850
851 void set_remote_traceframe ();
852
853 void check_binary_download (CORE_ADDR addr);
854
855 target_xfer_status remote_write_bytes_aux (const char *header,
856 CORE_ADDR memaddr,
857 const gdb_byte *myaddr,
858 ULONGEST len_units,
859 int unit_size,
860 ULONGEST *xfered_len_units,
861 char packet_format,
862 int use_length);
863
864 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
865 const gdb_byte *myaddr, ULONGEST len,
866 int unit_size, ULONGEST *xfered_len);
867
868 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
869 ULONGEST len_units,
870 int unit_size, ULONGEST *xfered_len_units);
871
872 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
873 ULONGEST memaddr,
874 ULONGEST len,
875 int unit_size,
876 ULONGEST *xfered_len);
877
878 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
879 gdb_byte *myaddr, ULONGEST len,
880 int unit_size,
881 ULONGEST *xfered_len);
882
883 packet_result remote_send_printf (const char *format, ...)
884 ATTRIBUTE_PRINTF (2, 3);
885
886 target_xfer_status remote_flash_write (ULONGEST address,
887 ULONGEST length, ULONGEST *xfered_len,
888 const gdb_byte *data);
889
890 int readchar (int timeout);
891
892 void remote_serial_write (const char *str, int len);
893
894 int putpkt (const char *buf);
895 int putpkt_binary (const char *buf, int cnt);
896
897 void skip_frame ();
898 long read_frame (char **buf_p, long *sizeof_buf);
899 void getpkt (char **buf, long *sizeof_buf, int forever);
900 int getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
901 int expecting_notif, int *is_notif);
902 int getpkt_sane (char **buf, long *sizeof_buf, int forever);
903 int getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
904 int *is_notif);
905 int remote_vkill (int pid);
906 void remote_kill_k ();
907
908 void extended_remote_disable_randomization (int val);
909 int extended_remote_run (const std::string &args);
910
911 void send_environment_packet (const char *action,
912 const char *packet,
913 const char *value);
914
915 void extended_remote_environment_support ();
3c69da40 916 void extended_remote_set_inferior_cwd ();
80152258 917
3c69da40
PA
918 target_xfer_status remote_write_qxfer (const char *object_name,
919 const char *annex,
920 const gdb_byte *writebuf,
921 ULONGEST offset, LONGEST len,
922 ULONGEST *xfered_len,
923 struct packet_config *packet);
43c3a0e4 924
3c69da40
PA
925 target_xfer_status remote_read_qxfer (const char *object_name,
926 const char *annex,
927 gdb_byte *readbuf, ULONGEST offset,
928 LONGEST len,
929 ULONGEST *xfered_len,
930 struct packet_config *packet);
43c3a0e4 931
3c69da40 932 void push_stop_reply (struct stop_reply *new_event);
43c3a0e4 933
3c69da40 934 bool vcont_r_supported ();
43c3a0e4 935
3c69da40 936 void packet_command (const char *args, int from_tty);
43c3a0e4 937
3c69da40 938private: /* data fields */
43c3a0e4 939
3c69da40
PA
940 /* The remote state. Don't reference this directly. Use the
941 get_remote_state method instead. */
942 remote_state m_remote_state;
43c3a0e4
PA
943};
944
3c69da40
PA
945static const target_info extended_remote_target_info = {
946 "extended-remote",
947 N_("Extended remote serial target in gdb-specific protocol"),
948 remote_doc
949};
ea9c271d 950
3c69da40
PA
951/* Set up the extended remote target by extending the standard remote
952 target and adding to it. */
953
954class extended_remote_target final : public remote_target
ea9c271d 955{
9d6eea31 956public:
3c69da40
PA
957 const target_info &info () const override
958 { return extended_remote_target_info; }
9d6eea31 959
3c69da40
PA
960 /* Open an extended-remote connection. */
961 static void open (const char *, int);
de44f5a7 962
3c69da40
PA
963 bool can_create_inferior () override { return true; }
964 void create_inferior (const char *, const std::string &,
965 char **, int) override;
9d6eea31 966
3c69da40 967 void detach (inferior *, int) override;
9d6eea31 968
3c69da40
PA
969 bool can_attach () override { return true; }
970 void attach (const char *, int) override;
be2a5f71 971
3c69da40
PA
972 void post_attach (int) override;
973 bool supports_disable_randomization () override;
974};
1e51243a 975
3c69da40
PA
976/* Per-program-space data key. */
977static const struct program_space_data *remote_pspace_data;
2d717e4f 978
3c69da40
PA
979/* The variable registered as the control variable used by the
980 remote exec-file commands. While the remote exec-file setting is
981 per-program-space, the set/show machinery uses this as the
982 location of the remote exec-file value. */
983static char *remote_exec_file_var;
a6f3e723 984
3c69da40
PA
985/* The size to align memory write packets, when practical. The protocol
986 does not guarantee any alignment, and gdb will generate short
987 writes and unaligned writes, but even as a best-effort attempt this
988 can improve bulk transfers. For instance, if a write is misaligned
989 relative to the target's data bus, the stub may need to make an extra
990 round trip fetching data from the target. This doesn't make a
991 huge difference, but it's easy to do, so we try to be helpful.
82f73884 992
3c69da40
PA
993 The alignment chosen is arbitrary; usually data bus width is
994 important here, not the possibly larger cache line size. */
995enum { REMOTE_ALIGN_WRITES = 16 };
82f73884 996
3c69da40 997/* Prototypes for local functions. */
74531fed 998
3c69da40 999static int hexnumlen (ULONGEST num);
782b2b07 1000
3c69da40 1001static int stubhex (int ch);
5d93a237 1002
3c69da40 1003static int hexnumstr (char *, ULONGEST);
048094ac 1004
3c69da40 1005static int hexnumnstr (char *, ULONGEST, int);
47f8a51d 1006
3c69da40 1007static CORE_ADDR remote_address_masked (CORE_ADDR);
262e1174 1008
3c69da40 1009static void print_packet (const char *);
747dc59d 1010
3c69da40 1011static int stub_unpack_int (char *buff, int fieldlength);
5e4a05c4 1012
3c69da40 1013struct packet_config;
b73be471 1014
3c69da40 1015static void show_packet_config_cmd (struct packet_config *config);
280ceea3 1016
3c69da40
PA
1017static void show_remote_protocol_packet_cmd (struct ui_file *file,
1018 int from_tty,
1019 struct cmd_list_element *c,
1020 const char *value);
8e88304f 1021
3c69da40 1022static ptid_t read_ptid (const char *buf, const char **obuf);
3a00c802 1023
3c69da40
PA
1024struct stop_reply;
1025static void stop_reply_xfree (struct stop_reply *);
b80fafe3 1026
3c69da40 1027static void remote_async_inferior_event_handler (gdb_client_data);
b80fafe3 1028
3c69da40 1029static int remote_read_description_p (struct target_ops *target);
88b496c3 1030
3c69da40 1031static void remote_console_output (char *msg);
5965e028 1032
3c69da40 1033static void remote_btrace_reset (remote_state *rs);
f4abbc16 1034
3c69da40 1035static void remote_unpush_and_throw (void);
15a201c8 1036
3c69da40 1037/* For "remote". */
80152258 1038
3c69da40 1039static struct cmd_list_element *remote_cmdlist;
9d6eea31 1040
3c69da40 1041/* For "set remote" and "show remote". */
6b8edb51 1042
3c69da40
PA
1043static struct cmd_list_element *remote_set_cmdlist;
1044static struct cmd_list_element *remote_show_cmdlist;
6b8edb51 1045
3c69da40 1046/* Controls whether GDB is willing to use range stepping. */
6b8edb51 1047
3c69da40
PA
1048static int use_range_stepping = 1;
1049
1050/* The max number of chars in debug output. The rest of chars are
1051 omitted. */
1052
1053#define REMOTE_DEBUG_MAX_CHAR 512
ea9c271d 1054
7aabaf9d
SM
1055/* Private data that we'll store in (struct thread_info)->priv. */
1056struct remote_thread_info : public private_thread_info
dc146f7c 1057{
7aabaf9d
SM
1058 std::string extra;
1059 std::string name;
1060 int core = -1;
799a2abe 1061
f6327dcb
KB
1062 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1063 sequence of bytes. */
7aabaf9d 1064 gdb::byte_vector thread_handle;
f6327dcb 1065
799a2abe 1066 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1067 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1068
1069 /* This is set to the data address of the access causing the target
1070 to stop for a watchpoint. */
7aabaf9d 1071 CORE_ADDR watch_data_address = 0;
85ad3aaf
PA
1072
1073 /* Fields used by the vCont action coalescing implemented in
1074 remote_resume / remote_commit_resume. remote_resume stores each
1075 thread's last resume request in these fields, so that a later
1076 remote_commit_resume knows which is the proper action for this
1077 thread to include in the vCont packet. */
1078
1079 /* True if the last target_resume call for this thread was a step
1080 request, false if a continue request. */
7aabaf9d 1081 int last_resume_step = 0;
85ad3aaf
PA
1082
1083 /* The signal specified in the last target_resume call for this
1084 thread. */
7aabaf9d 1085 gdb_signal last_resume_sig = GDB_SIGNAL_0;
85ad3aaf
PA
1086
1087 /* Whether this thread was already vCont-resumed on the remote
1088 side. */
7aabaf9d 1089 int vcont_resumed = 0;
dc146f7c
VP
1090};
1091
de44f5a7
PA
1092remote_state::remote_state ()
1093{
1094 /* The default buffer size is unimportant; it will be expanded
1095 whenever a larger buffer is needed. */
1096 this->buf_size = 400;
1097 this->buf = (char *) xmalloc (this->buf_size);
6b8edb51
PA
1098
1099 this->stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
de44f5a7
PA
1100}
1101
1102remote_state::~remote_state ()
1103{
1104 xfree (this->last_pass_packet);
1105 xfree (this->last_program_signals_packet);
1106 xfree (this->buf);
1107 xfree (this->finished_object);
1108 xfree (this->finished_annex);
6b8edb51 1109 QUEUE_free (stop_reply_p, this->stop_reply_queue);
cf792862
TT
1110}
1111
35b1e5cc
SS
1112/* Utility: generate error from an incoming stub packet. */
1113static void
1114trace_error (char *buf)
1115{
1116 if (*buf++ != 'E')
1117 return; /* not an error msg */
1118 switch (*buf)
1119 {
1120 case '1': /* malformed packet error */
1121 if (*++buf == '0') /* general case: */
1122 error (_("remote.c: error in outgoing packet."));
1123 else
1124 error (_("remote.c: error in outgoing packet at field #%ld."),
1125 strtol (buf, NULL, 16));
35b1e5cc
SS
1126 default:
1127 error (_("Target returns error code '%s'."), buf);
1128 }
1129}
1130
1131/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1132
6b8edb51
PA
1133char *
1134remote_target::remote_get_noisy_reply ()
35b1e5cc 1135{
b6bb3468
PA
1136 struct remote_state *rs = get_remote_state ();
1137
35b1e5cc
SS
1138 do /* Loop on reply from remote stub. */
1139 {
1140 char *buf;
a744cf53 1141
0df8b418 1142 QUIT; /* Allow user to bail out with ^C. */
b6bb3468
PA
1143 getpkt (&rs->buf, &rs->buf_size, 0);
1144 buf = rs->buf;
ad91cd99 1145 if (buf[0] == 'E')
35b1e5cc 1146 trace_error (buf);
61012eef 1147 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1148 {
1149 ULONGEST ul;
1150 CORE_ADDR from, to, org_to;
256642e8 1151 const char *p, *pp;
dde08ee1 1152 int adjusted_size = 0;
7556d4a4 1153 int relocated = 0;
dde08ee1
PA
1154
1155 p = buf + strlen ("qRelocInsn:");
1156 pp = unpack_varlen_hex (p, &ul);
1157 if (*pp != ';')
cb91c06a 1158 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1159 from = ul;
1160
1161 p = pp + 1;
a9cbf802 1162 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1163 to = ul;
1164
1165 org_to = to;
1166
492d29ea 1167 TRY
dde08ee1 1168 {
f5656ead 1169 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 1170 relocated = 1;
dde08ee1 1171 }
492d29ea 1172 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
1173 {
1174 if (ex.error == MEMORY_ERROR)
1175 {
1176 /* Propagate memory errors silently back to the
1177 target. The stub may have limited the range of
1178 addresses we can write to, for example. */
1179 }
1180 else
1181 {
1182 /* Something unexpectedly bad happened. Be verbose
1183 so we can tell what, and propagate the error back
1184 to the stub, so it doesn't get stuck waiting for
1185 a response. */
1186 exception_fprintf (gdb_stderr, ex,
1187 _("warning: relocating instruction: "));
1188 }
1189 putpkt ("E01");
1190 }
492d29ea 1191 END_CATCH
7556d4a4
PA
1192
1193 if (relocated)
dde08ee1
PA
1194 {
1195 adjusted_size = to - org_to;
1196
b6bb3468 1197 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1198 putpkt (buf);
1199 }
dde08ee1 1200 }
ad91cd99 1201 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
1202 remote_console_output (buf + 1); /* 'O' message from stub */
1203 else
0df8b418 1204 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1205 }
1206 while (1);
1207}
3c3bea1c 1208
9d6eea31
PA
1209struct remote_arch_state *
1210remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1211{
43c3a0e4
PA
1212 remote_arch_state *rsa;
1213
1214 auto it = this->m_arch_states.find (gdbarch);
1215 if (it == this->m_arch_states.end ())
9d6eea31 1216 {
43c3a0e4
PA
1217 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1218 std::forward_as_tuple (gdbarch),
1219 std::forward_as_tuple (gdbarch));
1220 rsa = &p.first->second;
9d6eea31
PA
1221
1222 /* Make sure that the packet buffer is plenty big enough for
1223 this architecture. */
1224 if (this->buf_size < rsa->remote_packet_size)
1225 {
1226 this->buf_size = 2 * rsa->remote_packet_size;
1227 this->buf = (char *) xrealloc (this->buf, this->buf_size);
1228 }
1229 }
43c3a0e4
PA
1230 else
1231 rsa = &it->second;
1232
1233 return rsa;
d01949b6
AC
1234}
1235
0b83947e
DJ
1236/* Fetch the global remote target state. */
1237
6b8edb51
PA
1238remote_state *
1239remote_target::get_remote_state ()
0b83947e
DJ
1240{
1241 /* Make sure that the remote architecture state has been
1242 initialized, because doing so might reallocate rs->buf. Any
1243 function which calls getpkt also needs to be mindful of changes
1244 to rs->buf, but this call limits the number of places which run
1245 into trouble. */
3c69da40 1246 m_remote_state.get_remote_arch_state (target_gdbarch ());
0b83947e 1247
3c69da40 1248 return &m_remote_state;
0b83947e
DJ
1249}
1250
94585166
DB
1251/* Cleanup routine for the remote module's pspace data. */
1252
1253static void
1254remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1255{
19ba03f4 1256 char *remote_exec_file = (char *) arg;
94585166
DB
1257
1258 xfree (remote_exec_file);
1259}
1260
1261/* Fetch the remote exec-file from the current program space. */
1262
1263static const char *
1264get_remote_exec_file (void)
1265{
1266 char *remote_exec_file;
1267
19ba03f4
SM
1268 remote_exec_file
1269 = (char *) program_space_data (current_program_space,
1270 remote_pspace_data);
94585166
DB
1271 if (remote_exec_file == NULL)
1272 return "";
1273
1274 return remote_exec_file;
1275}
1276
1277/* Set the remote exec file for PSPACE. */
1278
1279static void
1280set_pspace_remote_exec_file (struct program_space *pspace,
1281 char *remote_exec_file)
1282{
19ba03f4 1283 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
1284
1285 xfree (old_file);
1286 set_program_space_data (pspace, remote_pspace_data,
1287 xstrdup (remote_exec_file));
1288}
1289
1290/* The "set/show remote exec-file" set command hook. */
1291
1292static void
eb4c3f4a 1293set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1294 struct cmd_list_element *c)
1295{
1296 gdb_assert (remote_exec_file_var != NULL);
1297 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1298}
1299
1300/* The "set/show remote exec-file" show command hook. */
1301
1302static void
1303show_remote_exec_file (struct ui_file *file, int from_tty,
1304 struct cmd_list_element *cmd, const char *value)
1305{
1306 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1307}
1308
74ca34ce
DJ
1309static int
1310compare_pnums (const void *lhs_, const void *rhs_)
1311{
19ba03f4
SM
1312 const struct packet_reg * const *lhs
1313 = (const struct packet_reg * const *) lhs_;
1314 const struct packet_reg * const *rhs
1315 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
1316
1317 if ((*lhs)->pnum < (*rhs)->pnum)
1318 return -1;
1319 else if ((*lhs)->pnum == (*rhs)->pnum)
1320 return 0;
1321 else
1322 return 1;
1323}
1324
c21236dc
PA
1325static int
1326map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1327{
74ca34ce 1328 int regnum, num_remote_regs, offset;
74ca34ce 1329 struct packet_reg **remote_regs;
ea9c271d 1330
4a22f64d 1331 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1332 {
c21236dc 1333 struct packet_reg *r = &regs[regnum];
baef701f 1334
4a22f64d 1335 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1336 /* Do not try to fetch zero-sized (placeholder) registers. */
1337 r->pnum = -1;
1338 else
1339 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1340
b323314b 1341 r->regnum = regnum;
74ca34ce
DJ
1342 }
1343
1344 /* Define the g/G packet format as the contents of each register
1345 with a remote protocol number, in order of ascending protocol
1346 number. */
1347
224c3ddb 1348 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1349 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1350 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1351 regnum++)
c21236dc
PA
1352 if (regs[regnum].pnum != -1)
1353 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1354
74ca34ce
DJ
1355 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1356 compare_pnums);
1357
1358 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1359 {
1360 remote_regs[regnum]->in_g_packet = 1;
1361 remote_regs[regnum]->offset = offset;
4a22f64d 1362 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1363 }
1364
c21236dc
PA
1365 return offset;
1366}
1367
1368/* Given the architecture described by GDBARCH, return the remote
1369 protocol register's number and the register's offset in the g/G
1370 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1371 If the target does not have a mapping for REGNUM, return false,
1372 otherwise, return true. */
1373
1374int
1375remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1376 int *pnum, int *poffset)
1377{
c21236dc
PA
1378 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1379
b80406ac 1380 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1381
b80406ac 1382 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1383
1384 *pnum = regs[regnum].pnum;
1385 *poffset = regs[regnum].offset;
1386
c21236dc
PA
1387 return *pnum != -1;
1388}
1389
9d6eea31 1390remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1391{
c21236dc
PA
1392 /* Use the architecture to build a regnum<->pnum table, which will be
1393 1:1 unless a feature set specifies otherwise. */
9d6eea31 1394 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1395
74ca34ce
DJ
1396 /* Record the maximum possible size of the g packet - it may turn out
1397 to be smaller. */
9d6eea31
PA
1398 this->sizeof_g_packet
1399 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1400
0df8b418 1401 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1402 remote stubs have a hardwired buffer size of 400 bytes
1403 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1404 as the maximum packet-size to ensure that the packet and an extra
1405 NUL character can always fit in the buffer. This stops GDB
1406 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1407 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1408 this->remote_packet_size = 400 - 1;
d01949b6 1409
ea9c271d 1410 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1411 this->actual_register_packet_size = 0;
ea9c271d
DJ
1412
1413 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1414 default, adjust the size accordingly. Remember that each byte is
1415 encoded as two characters. 32 is the overhead for the packet
1416 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1417 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1418 little. */
9d6eea31
PA
1419 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1420 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1421}
1422
6b8edb51
PA
1423/* Get a pointer to the current remote target. If not connected to a
1424 remote target, return NULL. */
1425
1426static remote_target *
1427get_current_remote_target ()
1428{
1429 target_ops *proc_target = find_target_at (process_stratum);
1430 return dynamic_cast<remote_target *> (proc_target);
1431}
1432
ea9c271d
DJ
1433/* Return the current allowed size of a remote packet. This is
1434 inferred from the current architecture, and should be used to
1435 limit the length of outgoing packets. */
6b8edb51
PA
1436long
1437remote_target::get_remote_packet_size ()
ea9c271d 1438{
be2a5f71 1439 struct remote_state *rs = get_remote_state ();
9d6eea31 1440 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1441
be2a5f71
DJ
1442 if (rs->explicit_packet_size)
1443 return rs->explicit_packet_size;
1444
ea9c271d 1445 return rsa->remote_packet_size;
d01949b6
AC
1446}
1447
ad10f812 1448static struct packet_reg *
5cd63fda
PA
1449packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1450 long regnum)
ad10f812 1451{
5cd63fda 1452 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1453 return NULL;
1454 else
ad10f812 1455 {
ea9c271d 1456 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1457
b323314b
AC
1458 gdb_assert (r->regnum == regnum);
1459 return r;
ad10f812 1460 }
ad10f812
AC
1461}
1462
1463static struct packet_reg *
5cd63fda
PA
1464packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1465 LONGEST pnum)
ad10f812 1466{
b323314b 1467 int i;
a744cf53 1468
5cd63fda 1469 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1470 {
ea9c271d 1471 struct packet_reg *r = &rsa->regs[i];
a744cf53 1472
b323314b
AC
1473 if (r->pnum == pnum)
1474 return r;
ad10f812
AC
1475 }
1476 return NULL;
d01949b6
AC
1477}
1478
9a7071a8
JB
1479/* Allow the user to specify what sequence to send to the remote
1480 when he requests a program interruption: Although ^C is usually
1481 what remote systems expect (this is the default, here), it is
1482 sometimes preferable to send a break. On other systems such
1483 as the Linux kernel, a break followed by g, which is Magic SysRq g
1484 is required in order to interrupt the execution. */
1485const char interrupt_sequence_control_c[] = "Ctrl-C";
1486const char interrupt_sequence_break[] = "BREAK";
1487const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1488static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1489 {
1490 interrupt_sequence_control_c,
1491 interrupt_sequence_break,
1492 interrupt_sequence_break_g,
1493 NULL
1494 };
1495static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1496
1497static void
1498show_interrupt_sequence (struct ui_file *file, int from_tty,
1499 struct cmd_list_element *c,
1500 const char *value)
1501{
1502 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1503 fprintf_filtered (file,
1504 _("Send the ASCII ETX character (Ctrl-c) "
1505 "to the remote target to interrupt the "
1506 "execution of the program.\n"));
1507 else if (interrupt_sequence_mode == interrupt_sequence_break)
1508 fprintf_filtered (file,
1509 _("send a break signal to the remote target "
1510 "to interrupt the execution of the program.\n"));
1511 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1512 fprintf_filtered (file,
1513 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1514 "the remote target to interrupt the execution "
1515 "of Linux kernel.\n"));
1516 else
1517 internal_error (__FILE__, __LINE__,
1518 _("Invalid value for interrupt_sequence_mode: %s."),
1519 interrupt_sequence_mode);
1520}
6426a772 1521
9a7071a8
JB
1522/* This boolean variable specifies whether interrupt_sequence is sent
1523 to the remote target when gdb connects to it.
1524 This is mostly needed when you debug the Linux kernel: The Linux kernel
1525 expects BREAK g which is Magic SysRq g for connecting gdb. */
1526static int interrupt_on_connect = 0;
c906108c 1527
9a7071a8
JB
1528/* This variable is used to implement the "set/show remotebreak" commands.
1529 Since these commands are now deprecated in favor of "set/show remote
1530 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
1531static int remote_break;
1532
9a7071a8 1533static void
eb4c3f4a 1534set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1535{
1536 if (remote_break)
1537 interrupt_sequence_mode = interrupt_sequence_break;
1538 else
1539 interrupt_sequence_mode = interrupt_sequence_control_c;
1540}
1541
1542static void
1543show_remotebreak (struct ui_file *file, int from_tty,
1544 struct cmd_list_element *c,
1545 const char *value)
1546{
1547}
1548
c906108c
SS
1549/* This variable sets the number of bits in an address that are to be
1550 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1551 leading zeros, the entire address would be sent. This variable
c906108c
SS
1552 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1553 initial implementation of remote.c restricted the address sent in
1554 memory packets to ``host::sizeof long'' bytes - (typically 32
1555 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1556 address was never sent. Since fixing this bug may cause a break in
1557 some remote targets this variable is principly provided to
23860348 1558 facilitate backward compatibility. */
c906108c 1559
883b9c6c 1560static unsigned int remote_address_size;
c906108c 1561
11cf8741 1562\f
11cf8741 1563/* User configurable variables for the number of characters in a
ea9c271d
DJ
1564 memory read/write packet. MIN (rsa->remote_packet_size,
1565 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1566 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1567 (speed up transfers). The variables ``preferred_*'' (the user
1568 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1569 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1570
1571struct memory_packet_config
1572{
a121b7c1 1573 const char *name;
11cf8741
JM
1574 long size;
1575 int fixed_p;
1576};
1577
cc0be08f
PA
1578/* The default max memory-write-packet-size, when the setting is
1579 "fixed". The 16k is historical. (It came from older GDB's using
1580 alloca for buffers and the knowledge (folklore?) that some hosts
1581 don't cope very well with large alloca calls.) */
1582#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
1583
1584/* The minimum remote packet size for memory transfers. Ensures we
1585 can write at least one byte. */
1586#define MIN_MEMORY_PACKET_SIZE 20
1587
cc0be08f
PA
1588/* Get the memory packet size, assuming it is fixed. */
1589
1590static long
1591get_fixed_memory_packet_size (struct memory_packet_config *config)
1592{
1593 gdb_assert (config->fixed_p);
1594
1595 if (config->size <= 0)
1596 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1597 else
1598 return config->size;
1599}
1600
11cf8741
JM
1601/* Compute the current size of a read/write packet. Since this makes
1602 use of ``actual_register_packet_size'' the computation is dynamic. */
1603
6b8edb51
PA
1604long
1605remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 1606{
d01949b6 1607 struct remote_state *rs = get_remote_state ();
9d6eea31 1608 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1609
11cf8741
JM
1610 long what_they_get;
1611 if (config->fixed_p)
cc0be08f 1612 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
1613 else
1614 {
ea9c271d 1615 what_they_get = get_remote_packet_size ();
23860348 1616 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1617 if (config->size > 0
1618 && what_they_get > config->size)
1619 what_they_get = config->size;
be2a5f71
DJ
1620
1621 /* Limit it to the size of the targets ``g'' response unless we have
1622 permission from the stub to use a larger packet size. */
1623 if (rs->explicit_packet_size == 0
1624 && rsa->actual_register_packet_size > 0
1625 && what_they_get > rsa->actual_register_packet_size)
1626 what_they_get = rsa->actual_register_packet_size;
11cf8741 1627 }
a5c0808e
PA
1628 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1629 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1630
1631 /* Make sure there is room in the global buffer for this packet
1632 (including its trailing NUL byte). */
1633 if (rs->buf_size < what_they_get + 1)
1634 {
1635 rs->buf_size = 2 * what_they_get;
224c3ddb 1636 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1637 }
1638
11cf8741
JM
1639 return what_they_get;
1640}
1641
0df8b418 1642/* Update the size of a read/write packet. If they user wants
23860348 1643 something really big then do a sanity check. */
11cf8741
JM
1644
1645static void
ac88e2de 1646set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1647{
1648 int fixed_p = config->fixed_p;
1649 long size = config->size;
a744cf53 1650
11cf8741 1651 if (args == NULL)
8a3fe4f8 1652 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1653 else if (strcmp (args, "hard") == 0
1654 || strcmp (args, "fixed") == 0)
1655 fixed_p = 1;
1656 else if (strcmp (args, "soft") == 0
1657 || strcmp (args, "limit") == 0)
1658 fixed_p = 0;
1659 else
1660 {
1661 char *end;
a744cf53 1662
11cf8741
JM
1663 size = strtoul (args, &end, 0);
1664 if (args == end)
8a3fe4f8 1665 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1666
1667 /* Instead of explicitly capping the size of a packet to or
1668 disallowing it, the user is allowed to set the size to
1669 something arbitrarily large. */
11cf8741 1670 }
a5c0808e 1671
23860348 1672 /* Extra checks? */
11cf8741
JM
1673 if (fixed_p && !config->fixed_p)
1674 {
cc0be08f
PA
1675 /* So that the query shows the correct value. */
1676 long query_size = (size <= 0
1677 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1678 : size);
1679
e2e0b3e5
AC
1680 if (! query (_("The target may not be able to correctly handle a %s\n"
1681 "of %ld bytes. Change the packet size? "),
cc0be08f 1682 config->name, query_size))
8a3fe4f8 1683 error (_("Packet size not changed."));
11cf8741 1684 }
23860348 1685 /* Update the config. */
11cf8741
JM
1686 config->fixed_p = fixed_p;
1687 config->size = size;
1688}
1689
1690static void
1691show_memory_packet_size (struct memory_packet_config *config)
1692{
cc0be08f
PA
1693 if (config->size == 0)
1694 printf_filtered (_("The %s is 0 (default). "), config->name);
1695 else
1696 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1697 if (config->fixed_p)
a3f17187 1698 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
cc0be08f 1699 get_fixed_memory_packet_size (config));
11cf8741 1700 else
cc0be08f 1701 {
6b8edb51 1702 remote_target *remote = get_current_remote_target ();
cc0be08f 1703
6b8edb51 1704 if (remote != NULL)
cc0be08f 1705 printf_filtered (_("Packets are limited to %ld bytes.\n"),
6b8edb51 1706 remote->get_memory_packet_size (config));
cc0be08f
PA
1707 else
1708 puts_filtered ("The actual limit will be further reduced "
1709 "dependent on the target.\n");
1710 }
11cf8741
JM
1711}
1712
1713static struct memory_packet_config memory_write_packet_config =
1714{
1715 "memory-write-packet-size",
1716};
1717
1718static void
ac88e2de 1719set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1720{
1721 set_memory_packet_size (args, &memory_write_packet_config);
1722}
1723
1724static void
ac88e2de 1725show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1726{
1727 show_memory_packet_size (&memory_write_packet_config);
1728}
1729
6b8edb51
PA
1730long
1731remote_target::get_memory_write_packet_size ()
11cf8741
JM
1732{
1733 return get_memory_packet_size (&memory_write_packet_config);
1734}
1735
1736static struct memory_packet_config memory_read_packet_config =
1737{
1738 "memory-read-packet-size",
1739};
1740
1741static void
ac88e2de 1742set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1743{
1744 set_memory_packet_size (args, &memory_read_packet_config);
1745}
1746
1747static void
ac88e2de 1748show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1749{
1750 show_memory_packet_size (&memory_read_packet_config);
1751}
1752
6b8edb51
PA
1753long
1754remote_target::get_memory_read_packet_size ()
11cf8741
JM
1755{
1756 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1757
11cf8741
JM
1758 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1759 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1760 increased beyond this. */
1761 if (size > get_remote_packet_size ())
1762 size = get_remote_packet_size ();
11cf8741
JM
1763 return size;
1764}
1765
11cf8741 1766\f
5a2468f5 1767
5a2468f5
JM
1768struct packet_config
1769 {
bb572ddd
DJ
1770 const char *name;
1771 const char *title;
4082afcc
PA
1772
1773 /* If auto, GDB auto-detects support for this packet or feature,
1774 either through qSupported, or by trying the packet and looking
1775 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1776 packet. If false, the packet is disabled. Configs that don't
1777 have an associated command always have this set to auto. */
7f19b9a2 1778 enum auto_boolean detect;
4082afcc
PA
1779
1780 /* Does the target support this packet? */
5a2468f5
JM
1781 enum packet_support support;
1782 };
1783
4082afcc
PA
1784static enum packet_support packet_config_support (struct packet_config *config);
1785static enum packet_support packet_support (int packet);
5a2468f5
JM
1786
1787static void
fba45db2 1788show_packet_config_cmd (struct packet_config *config)
5a2468f5 1789{
a121b7c1 1790 const char *support = "internal-error";
a744cf53 1791
4082afcc 1792 switch (packet_config_support (config))
5a2468f5
JM
1793 {
1794 case PACKET_ENABLE:
1795 support = "enabled";
1796 break;
1797 case PACKET_DISABLE:
1798 support = "disabled";
1799 break;
1800 case PACKET_SUPPORT_UNKNOWN:
1801 support = "unknown";
1802 break;
1803 }
1804 switch (config->detect)
1805 {
7f19b9a2 1806 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1807 printf_filtered (_("Support for the `%s' packet "
1808 "is auto-detected, currently %s.\n"),
37a105a1 1809 config->name, support);
5a2468f5 1810 break;
7f19b9a2
AC
1811 case AUTO_BOOLEAN_TRUE:
1812 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1813 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1814 config->name, support);
8e248173 1815 break;
5a2468f5
JM
1816 }
1817}
1818
1819static void
bb572ddd
DJ
1820add_packet_config_cmd (struct packet_config *config, const char *name,
1821 const char *title, int legacy)
d471ea57 1822{
5a2468f5
JM
1823 char *set_doc;
1824 char *show_doc;
d471ea57 1825 char *cmd_name;
3ed07be4 1826
5a2468f5
JM
1827 config->name = name;
1828 config->title = title;
b435e160
AC
1829 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1830 name, title);
3e43a32a
MS
1831 show_doc = xstrprintf ("Show current use of remote "
1832 "protocol `%s' (%s) packet",
b435e160 1833 name, title);
d471ea57 1834 /* set/show TITLE-packet {auto,on,off} */
b435e160 1835 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1836 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1837 &config->detect, set_doc,
1838 show_doc, NULL, /* help_doc */
4082afcc 1839 NULL,
bb572ddd
DJ
1840 show_remote_protocol_packet_cmd,
1841 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1842 /* The command code copies the documentation strings. */
1843 xfree (set_doc);
1844 xfree (show_doc);
23860348 1845 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1846 if (legacy)
1847 {
1848 char *legacy_name;
a744cf53 1849
b435e160 1850 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1851 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1852 &remote_set_cmdlist);
d471ea57 1853 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1854 &remote_show_cmdlist);
d471ea57 1855 }
5a2468f5
JM
1856}
1857
d471ea57 1858static enum packet_result
a76d924d 1859packet_check_result (const char *buf)
5a2468f5 1860{
d471ea57 1861 if (buf[0] != '\0')
5a2468f5 1862 {
d471ea57 1863 /* The stub recognized the packet request. Check that the
23860348 1864 operation succeeded. */
a76d924d
DJ
1865 if (buf[0] == 'E'
1866 && isxdigit (buf[1]) && isxdigit (buf[2])
1867 && buf[3] == '\0')
1868 /* "Enn" - definitly an error. */
1869 return PACKET_ERROR;
1870
1871 /* Always treat "E." as an error. This will be used for
1872 more verbose error messages, such as E.memtypes. */
1873 if (buf[0] == 'E' && buf[1] == '.')
1874 return PACKET_ERROR;
1875
1876 /* The packet may or may not be OK. Just assume it is. */
1877 return PACKET_OK;
1878 }
1879 else
1880 /* The stub does not support the packet. */
1881 return PACKET_UNKNOWN;
1882}
1883
1884static enum packet_result
1885packet_ok (const char *buf, struct packet_config *config)
1886{
1887 enum packet_result result;
1888
4082afcc
PA
1889 if (config->detect != AUTO_BOOLEAN_TRUE
1890 && config->support == PACKET_DISABLE)
1891 internal_error (__FILE__, __LINE__,
1892 _("packet_ok: attempt to use a disabled packet"));
1893
a76d924d
DJ
1894 result = packet_check_result (buf);
1895 switch (result)
1896 {
1897 case PACKET_OK:
1898 case PACKET_ERROR:
1899 /* The stub recognized the packet request. */
4082afcc 1900 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1901 {
d471ea57
AC
1902 if (remote_debug)
1903 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1904 "Packet %s (%s) is supported\n",
1905 config->name, config->title);
d471ea57 1906 config->support = PACKET_ENABLE;
d471ea57 1907 }
a76d924d
DJ
1908 break;
1909 case PACKET_UNKNOWN:
23860348 1910 /* The stub does not support the packet. */
4082afcc
PA
1911 if (config->detect == AUTO_BOOLEAN_AUTO
1912 && config->support == PACKET_ENABLE)
d471ea57 1913 {
4082afcc
PA
1914 /* If the stub previously indicated that the packet was
1915 supported then there is a protocol error. */
1916 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1917 config->name, config->title);
1918 }
1919 else if (config->detect == AUTO_BOOLEAN_TRUE)
1920 {
1921 /* The user set it wrong. */
1922 error (_("Enabled packet %s (%s) not recognized by stub"),
1923 config->name, config->title);
d471ea57 1924 }
4082afcc
PA
1925
1926 if (remote_debug)
1927 fprintf_unfiltered (gdb_stdlog,
1928 "Packet %s (%s) is NOT supported\n",
1929 config->name, config->title);
1930 config->support = PACKET_DISABLE;
a76d924d 1931 break;
5a2468f5 1932 }
a76d924d
DJ
1933
1934 return result;
5a2468f5
JM
1935}
1936
444abaca
DJ
1937enum {
1938 PACKET_vCont = 0,
1939 PACKET_X,
1940 PACKET_qSymbol,
1941 PACKET_P,
1942 PACKET_p,
1943 PACKET_Z0,
1944 PACKET_Z1,
1945 PACKET_Z2,
1946 PACKET_Z3,
1947 PACKET_Z4,
15a201c8 1948 PACKET_vFile_setfs,
a6b151f1
DJ
1949 PACKET_vFile_open,
1950 PACKET_vFile_pread,
1951 PACKET_vFile_pwrite,
1952 PACKET_vFile_close,
1953 PACKET_vFile_unlink,
b9e7b9c3 1954 PACKET_vFile_readlink,
0a93529c 1955 PACKET_vFile_fstat,
0876f84a 1956 PACKET_qXfer_auxv,
23181151 1957 PACKET_qXfer_features,
c78fa86a 1958 PACKET_qXfer_exec_file,
cfa9d6d9 1959 PACKET_qXfer_libraries,
2268b414 1960 PACKET_qXfer_libraries_svr4,
fd79ecee 1961 PACKET_qXfer_memory_map,
0e7f50da
UW
1962 PACKET_qXfer_spu_read,
1963 PACKET_qXfer_spu_write,
07e059b5 1964 PACKET_qXfer_osdata,
dc146f7c 1965 PACKET_qXfer_threads,
0fb4aa4b 1966 PACKET_qXfer_statictrace_read,
b3b9301e 1967 PACKET_qXfer_traceframe_info,
169081d0 1968 PACKET_qXfer_uib,
711e434b 1969 PACKET_qGetTIBAddr,
444abaca 1970 PACKET_qGetTLSAddr,
be2a5f71 1971 PACKET_qSupported,
bd3eecc3 1972 PACKET_qTStatus,
89be2091 1973 PACKET_QPassSignals,
82075af2 1974 PACKET_QCatchSyscalls,
9b224c5e 1975 PACKET_QProgramSignals,
bc3b087d 1976 PACKET_QSetWorkingDir,
aefd8b33 1977 PACKET_QStartupWithShell,
0a2dde4a
SDJ
1978 PACKET_QEnvironmentHexEncoded,
1979 PACKET_QEnvironmentReset,
1980 PACKET_QEnvironmentUnset,
936d2992 1981 PACKET_qCRC,
08388c79 1982 PACKET_qSearch_memory,
2d717e4f
DJ
1983 PACKET_vAttach,
1984 PACKET_vRun,
a6f3e723 1985 PACKET_QStartNoAckMode,
82f73884 1986 PACKET_vKill,
4aa995e1
PA
1987 PACKET_qXfer_siginfo_read,
1988 PACKET_qXfer_siginfo_write,
0b16c5cf 1989 PACKET_qAttached,
4082afcc
PA
1990
1991 /* Support for conditional tracepoints. */
782b2b07 1992 PACKET_ConditionalTracepoints,
4082afcc
PA
1993
1994 /* Support for target-side breakpoint conditions. */
3788aec7 1995 PACKET_ConditionalBreakpoints,
4082afcc
PA
1996
1997 /* Support for target-side breakpoint commands. */
d3ce09f5 1998 PACKET_BreakpointCommands,
4082afcc
PA
1999
2000 /* Support for fast tracepoints. */
7a697b8d 2001 PACKET_FastTracepoints,
4082afcc
PA
2002
2003 /* Support for static tracepoints. */
0fb4aa4b 2004 PACKET_StaticTracepoints,
4082afcc
PA
2005
2006 /* Support for installing tracepoints while a trace experiment is
2007 running. */
1e4d1764 2008 PACKET_InstallInTrace,
4082afcc 2009
40ab02ce
MS
2010 PACKET_bc,
2011 PACKET_bs,
409873ef 2012 PACKET_TracepointSource,
d914c394 2013 PACKET_QAllow,
78d85199 2014 PACKET_qXfer_fdpic,
03583c20 2015 PACKET_QDisableRandomization,
d1feda86 2016 PACKET_QAgent,
f6f899bf 2017 PACKET_QTBuffer_size,
9accd112
MM
2018 PACKET_Qbtrace_off,
2019 PACKET_Qbtrace_bts,
b20a6524 2020 PACKET_Qbtrace_pt,
9accd112 2021 PACKET_qXfer_btrace,
4082afcc
PA
2022
2023 /* Support for the QNonStop packet. */
2024 PACKET_QNonStop,
2025
65706a29
PA
2026 /* Support for the QThreadEvents packet. */
2027 PACKET_QThreadEvents,
2028
4082afcc
PA
2029 /* Support for multi-process extensions. */
2030 PACKET_multiprocess_feature,
2031
2032 /* Support for enabling and disabling tracepoints while a trace
2033 experiment is running. */
2034 PACKET_EnableDisableTracepoints_feature,
2035
2036 /* Support for collecting strings using the tracenz bytecode. */
2037 PACKET_tracenz_feature,
2038
2039 /* Support for continuing to run a trace experiment while GDB is
2040 disconnected. */
2041 PACKET_DisconnectedTracing_feature,
2042
2043 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2044 PACKET_augmented_libraries_svr4_read_feature,
2045
f4abbc16
MM
2046 /* Support for the qXfer:btrace-conf:read packet. */
2047 PACKET_qXfer_btrace_conf,
2048
d33501a5
MM
2049 /* Support for the Qbtrace-conf:bts:size packet. */
2050 PACKET_Qbtrace_conf_bts_size,
2051
f7e6eed5
PA
2052 /* Support for swbreak+ feature. */
2053 PACKET_swbreak_feature,
2054
2055 /* Support for hwbreak+ feature. */
2056 PACKET_hwbreak_feature,
2057
89245bc0
DB
2058 /* Support for fork events. */
2059 PACKET_fork_event_feature,
2060
2061 /* Support for vfork events. */
2062 PACKET_vfork_event_feature,
2063
b20a6524
MM
2064 /* Support for the Qbtrace-conf:pt:size packet. */
2065 PACKET_Qbtrace_conf_pt_size,
2066
94585166
DB
2067 /* Support for exec events. */
2068 PACKET_exec_event_feature,
2069
750ce8d1
YQ
2070 /* Support for query supported vCont actions. */
2071 PACKET_vContSupported,
2072
de979965
PA
2073 /* Support remote CTRL-C. */
2074 PACKET_vCtrlC,
2075
f2faf941
PA
2076 /* Support TARGET_WAITKIND_NO_RESUMED. */
2077 PACKET_no_resumed,
2078
444abaca
DJ
2079 PACKET_MAX
2080};
506fb367 2081
444abaca 2082static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 2083
f7e6eed5
PA
2084/* Returns the packet's corresponding "set remote foo-packet" command
2085 state. See struct packet_config for more details. */
2086
2087static enum auto_boolean
2088packet_set_cmd_state (int packet)
2089{
2090 return remote_protocol_packets[packet].detect;
2091}
2092
4082afcc
PA
2093/* Returns whether a given packet or feature is supported. This takes
2094 into account the state of the corresponding "set remote foo-packet"
2095 command, which may be used to bypass auto-detection. */
dc8acb97 2096
4082afcc
PA
2097static enum packet_support
2098packet_config_support (struct packet_config *config)
2099{
2100 switch (config->detect)
444abaca 2101 {
4082afcc
PA
2102 case AUTO_BOOLEAN_TRUE:
2103 return PACKET_ENABLE;
2104 case AUTO_BOOLEAN_FALSE:
2105 return PACKET_DISABLE;
2106 case AUTO_BOOLEAN_AUTO:
2107 return config->support;
2108 default:
2109 gdb_assert_not_reached (_("bad switch"));
444abaca 2110 }
4082afcc
PA
2111}
2112
2113/* Same as packet_config_support, but takes the packet's enum value as
2114 argument. */
2115
2116static enum packet_support
2117packet_support (int packet)
2118{
2119 struct packet_config *config = &remote_protocol_packets[packet];
2120
2121 return packet_config_support (config);
dc8acb97
MS
2122}
2123
5a2468f5 2124static void
444abaca
DJ
2125show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2126 struct cmd_list_element *c,
2127 const char *value)
5a2468f5 2128{
444abaca 2129 struct packet_config *packet;
5a2468f5 2130
444abaca
DJ
2131 for (packet = remote_protocol_packets;
2132 packet < &remote_protocol_packets[PACKET_MAX];
2133 packet++)
2134 {
2135 if (&packet->detect == c->var)
2136 {
2137 show_packet_config_cmd (packet);
2138 return;
2139 }
2140 }
9b20d036 2141 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 2142 c->name);
5a2468f5
JM
2143}
2144
d471ea57
AC
2145/* Should we try one of the 'Z' requests? */
2146
2147enum Z_packet_type
2148{
2149 Z_PACKET_SOFTWARE_BP,
2150 Z_PACKET_HARDWARE_BP,
2151 Z_PACKET_WRITE_WP,
2152 Z_PACKET_READ_WP,
2153 Z_PACKET_ACCESS_WP,
2154 NR_Z_PACKET_TYPES
2155};
96baa820 2156
d471ea57 2157/* For compatibility with older distributions. Provide a ``set remote
23860348 2158 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2159
7f19b9a2 2160static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2161
2162static void
eb4c3f4a 2163set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2164 struct cmd_list_element *c)
96baa820 2165{
d471ea57 2166 int i;
a744cf53 2167
d471ea57 2168 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 2169 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
2170}
2171
2172static void
08546159
AC
2173show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2174 struct cmd_list_element *c,
2175 const char *value)
96baa820 2176{
d471ea57 2177 int i;
a744cf53 2178
d471ea57
AC
2179 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2180 {
444abaca 2181 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 2182 }
96baa820
JM
2183}
2184
4082afcc
PA
2185/* Returns true if the multi-process extensions are in effect. */
2186
2187static int
2188remote_multi_process_p (struct remote_state *rs)
2189{
2190 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2191}
2192
de0d863e
DB
2193/* Returns true if fork events are supported. */
2194
2195static int
2196remote_fork_event_p (struct remote_state *rs)
2197{
2198 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2199}
2200
c269dbdb
DB
2201/* Returns true if vfork events are supported. */
2202
2203static int
2204remote_vfork_event_p (struct remote_state *rs)
2205{
2206 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2207}
2208
d46addbb
DB
2209/* Returns true if exec events are supported. */
2210
2211static int
2212remote_exec_event_p (struct remote_state *rs)
2213{
2214 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2215}
2216
cbb8991c
DB
2217/* Insert fork catchpoint target routine. If fork events are enabled
2218 then return success, nothing more to do. */
2219
f6ac5f3d
PA
2220int
2221remote_target::insert_fork_catchpoint (int pid)
cbb8991c
DB
2222{
2223 struct remote_state *rs = get_remote_state ();
2224
2225 return !remote_fork_event_p (rs);
2226}
2227
2228/* Remove fork catchpoint target routine. Nothing to do, just
2229 return success. */
2230
f6ac5f3d
PA
2231int
2232remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2233{
2234 return 0;
2235}
2236
2237/* Insert vfork catchpoint target routine. If vfork events are enabled
2238 then return success, nothing more to do. */
2239
f6ac5f3d
PA
2240int
2241remote_target::insert_vfork_catchpoint (int pid)
cbb8991c
DB
2242{
2243 struct remote_state *rs = get_remote_state ();
2244
2245 return !remote_vfork_event_p (rs);
2246}
2247
2248/* Remove vfork catchpoint target routine. Nothing to do, just
2249 return success. */
2250
f6ac5f3d
PA
2251int
2252remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2253{
2254 return 0;
2255}
2256
d46addbb
DB
2257/* Insert exec catchpoint target routine. If exec events are
2258 enabled, just return success. */
2259
f6ac5f3d
PA
2260int
2261remote_target::insert_exec_catchpoint (int pid)
d46addbb
DB
2262{
2263 struct remote_state *rs = get_remote_state ();
2264
2265 return !remote_exec_event_p (rs);
2266}
2267
2268/* Remove exec catchpoint target routine. Nothing to do, just
2269 return success. */
2270
f6ac5f3d
PA
2271int
2272remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2273{
2274 return 0;
2275}
2276
c906108c
SS
2277\f
2278
79d7f229
PA
2279static ptid_t magic_null_ptid;
2280static ptid_t not_sent_ptid;
2281static ptid_t any_thread_ptid;
2282
0b16c5cf
PA
2283/* Find out if the stub attached to PID (and hence GDB should offer to
2284 detach instead of killing it when bailing out). */
2285
6b8edb51
PA
2286int
2287remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2288{
2289 struct remote_state *rs = get_remote_state ();
bba74b36 2290 size_t size = get_remote_packet_size ();
0b16c5cf 2291
4082afcc 2292 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2293 return 0;
2294
2295 if (remote_multi_process_p (rs))
bba74b36 2296 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 2297 else
bba74b36 2298 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
2299
2300 putpkt (rs->buf);
2301 getpkt (&rs->buf, &rs->buf_size, 0);
2302
2303 switch (packet_ok (rs->buf,
1554e9be 2304 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
2305 {
2306 case PACKET_OK:
2307 if (strcmp (rs->buf, "1") == 0)
2308 return 1;
2309 break;
2310 case PACKET_ERROR:
2311 warning (_("Remote failure reply: %s"), rs->buf);
2312 break;
2313 case PACKET_UNKNOWN:
2314 break;
2315 }
2316
2317 return 0;
2318}
2319
49c62f2e
PA
2320/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2321 has been invented by GDB, instead of reported by the target. Since
2322 we can be connected to a remote system before before knowing about
2323 any inferior, mark the target with execution when we find the first
2324 inferior. If ATTACHED is 1, then we had just attached to this
2325 inferior. If it is 0, then we just created this inferior. If it
2326 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2327 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2328 attempt to open this inferior's executable as the main executable
2329 if no main executable is open already. */
1941c569 2330
6b8edb51
PA
2331inferior *
2332remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2333 int try_open_exec)
1941c569 2334{
1941c569
PA
2335 struct inferior *inf;
2336
0b16c5cf
PA
2337 /* Check whether this process we're learning about is to be
2338 considered attached, or if is to be considered to have been
2339 spawned by the stub. */
2340 if (attached == -1)
2341 attached = remote_query_attached (pid);
2342
f5656ead 2343 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2344 {
2345 /* If the target shares code across all inferiors, then every
2346 attach adds a new inferior. */
2347 inf = add_inferior (pid);
2348
2349 /* ... and every inferior is bound to the same program space.
2350 However, each inferior may still have its own address
2351 space. */
2352 inf->aspace = maybe_new_address_space ();
2353 inf->pspace = current_program_space;
2354 }
2355 else
2356 {
2357 /* In the traditional debugging scenario, there's a 1-1 match
2358 between program/address spaces. We simply bind the inferior
2359 to the program space's address space. */
2360 inf = current_inferior ();
2361 inferior_appeared (inf, pid);
2362 }
1941c569 2363
0b16c5cf 2364 inf->attach_flag = attached;
49c62f2e 2365 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2366
1b6e6f5c
GB
2367 /* If no main executable is currently open then attempt to
2368 open the file that was executed to create this inferior. */
835205d0 2369 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2370 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2371
1941c569
PA
2372 return inf;
2373}
2374
7aabaf9d 2375static remote_thread_info *get_remote_thread_info (thread_info *thread);
85ad3aaf 2376
1941c569
PA
2377/* Add thread PTID to GDB's thread list. Tag it as executing/running
2378 according to RUNNING. */
2379
6b8edb51
PA
2380void
2381remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
c906108c 2382{
b7ea362b 2383 struct remote_state *rs = get_remote_state ();
85ad3aaf 2384 struct thread_info *thread;
b7ea362b
PA
2385
2386 /* GDB historically didn't pull threads in the initial connection
2387 setup. If the remote target doesn't even have a concept of
2388 threads (e.g., a bare-metal target), even if internally we
2389 consider that a single-threaded target, mentioning a new thread
2390 might be confusing to the user. Be silent then, preserving the
2391 age old behavior. */
2392 if (rs->starting_up)
85ad3aaf 2393 thread = add_thread_silent (ptid);
b7ea362b 2394 else
85ad3aaf 2395 thread = add_thread (ptid);
1941c569 2396
7aabaf9d 2397 get_remote_thread_info (thread)->vcont_resumed = executing;
0d5b594f 2398 set_executing (ptid, executing);
1941c569
PA
2399 set_running (ptid, running);
2400}
2401
2402/* Come here when we learn about a thread id from the remote target.
2403 It may be the first time we hear about such thread, so take the
2404 opportunity to add it to GDB's thread list. In case this is the
2405 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2406 GDB's inferior list as well. EXECUTING indicates whether the
2407 thread is (internally) executing or stopped. */
1941c569 2408
6b8edb51
PA
2409void
2410remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 2411{
0d5b594f
PA
2412 /* In non-stop mode, we assume new found threads are (externally)
2413 running until proven otherwise with a stop reply. In all-stop,
2414 we can only get here if all threads are stopped. */
2415 int running = target_is_non_stop_p () ? 1 : 0;
2416
c906108c
SS
2417 /* If this is a new thread, add it to GDB's thread list.
2418 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
2419
2420 if (in_thread_list (currthread) && is_exited (currthread))
2421 {
2422 /* We're seeing an event on a thread id we knew had exited.
2423 This has to be a new thread reusing the old id. Add it. */
0d5b594f 2424 remote_add_thread (currthread, running, executing);
82f73884
PA
2425 return;
2426 }
2427
79d7f229 2428 if (!in_thread_list (currthread))
c0a2216e 2429 {
1941c569 2430 struct inferior *inf = NULL;
bad34192 2431 int pid = ptid_get_pid (currthread);
1941c569 2432
bad34192
PA
2433 if (ptid_is_pid (inferior_ptid)
2434 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
2435 {
2436 /* inferior_ptid has no thread member yet. This can happen
2437 with the vAttach -> remote_wait,"TAAthread:" path if the
2438 stub doesn't support qC. This is the first stop reported
2439 after an attach, so this is the main thread. Update the
2440 ptid in the thread list. */
bad34192
PA
2441 if (in_thread_list (pid_to_ptid (pid)))
2442 thread_change_ptid (inferior_ptid, currthread);
2443 else
2444 {
0d5b594f 2445 remote_add_thread (currthread, running, executing);
bad34192
PA
2446 inferior_ptid = currthread;
2447 }
dc146f7c 2448 return;
c0a2216e 2449 }
82f73884
PA
2450
2451 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
2452 {
2453 /* inferior_ptid is not set yet. This can happen with the
2454 vRun -> remote_wait,"TAAthread:" path if the stub
2455 doesn't support qC. This is the first stop reported
2456 after an attach, so this is the main thread. Update the
2457 ptid in the thread list. */
dc146f7c 2458 thread_change_ptid (inferior_ptid, currthread);
82f73884 2459 return;
c0a2216e 2460 }
82f73884 2461
29c87f7f
PA
2462 /* When connecting to a target remote, or to a target
2463 extended-remote which already was debugging an inferior, we
2464 may not know about it yet. Add it before adding its child
2465 thread, so notifications are emitted in a sensible order. */
2466 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
2467 {
2468 struct remote_state *rs = get_remote_state ();
2469 int fake_pid_p = !remote_multi_process_p (rs);
2470
2471 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 2472 ptid_get_pid (currthread), -1, 1);
49c62f2e 2473 }
29c87f7f 2474
82f73884 2475 /* This is really a new thread. Add it. */
0d5b594f 2476 remote_add_thread (currthread, running, executing);
1941c569
PA
2477
2478 /* If we found a new inferior, let the common code do whatever
2479 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2480 breakpoints), unless we're just setting up an all-stop
2481 connection. */
1941c569 2482 if (inf != NULL)
b7ea362b
PA
2483 {
2484 struct remote_state *rs = get_remote_state ();
2485
6efcd9a8 2486 if (!rs->starting_up)
0d5b594f 2487 notice_new_inferior (currthread, executing, 0);
b7ea362b 2488 }
c0a2216e 2489 }
c906108c
SS
2490}
2491
85ad3aaf 2492/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2493
7aabaf9d
SM
2494static remote_thread_info *
2495get_remote_thread_info (thread_info *thread)
dc146f7c 2496{
85ad3aaf 2497 gdb_assert (thread != NULL);
dc146f7c 2498
85ad3aaf 2499 if (thread->priv == NULL)
7aabaf9d 2500 thread->priv.reset (new remote_thread_info);
dc146f7c 2501
7aabaf9d 2502 return static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2503}
2504
2505/* Return PTID's private thread data, creating it if necessary. */
2506
7aabaf9d
SM
2507static remote_thread_info *
2508get_remote_thread_info (ptid_t ptid)
85ad3aaf
PA
2509{
2510 struct thread_info *info = find_thread_ptid (ptid);
2511
7aabaf9d 2512 return get_remote_thread_info (info);
dc146f7c
VP
2513}
2514
74531fed
PA
2515/* Call this function as a result of
2516 1) A halt indication (T packet) containing a thread id
2517 2) A direct query of currthread
0df8b418 2518 3) Successful execution of set thread */
74531fed
PA
2519
2520static void
47f8a51d 2521record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2522{
47f8a51d 2523 rs->general_thread = currthread;
74531fed
PA
2524}
2525
89be2091
DJ
2526/* If 'QPassSignals' is supported, tell the remote stub what signals
2527 it can simply pass through to the inferior without reporting. */
2528
f6ac5f3d
PA
2529void
2530remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
89be2091 2531{
4082afcc 2532 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2533 {
2534 char *pass_packet, *p;
89be2091 2535 int count = 0, i;
747dc59d 2536 struct remote_state *rs = get_remote_state ();
89be2091
DJ
2537
2538 gdb_assert (numsigs < 256);
2539 for (i = 0; i < numsigs; i++)
2540 {
2455069d 2541 if (pass_signals[i])
89be2091
DJ
2542 count++;
2543 }
224c3ddb 2544 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2545 strcpy (pass_packet, "QPassSignals:");
2546 p = pass_packet + strlen (pass_packet);
2547 for (i = 0; i < numsigs; i++)
2548 {
2455069d 2549 if (pass_signals[i])
89be2091
DJ
2550 {
2551 if (i >= 16)
2552 *p++ = tohex (i >> 4);
2553 *p++ = tohex (i & 15);
2554 if (count)
2555 *p++ = ';';
2556 else
2557 break;
2558 count--;
2559 }
2560 }
2561 *p = 0;
747dc59d 2562 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2563 {
89be2091
DJ
2564 putpkt (pass_packet);
2565 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2566 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2567 if (rs->last_pass_packet)
2568 xfree (rs->last_pass_packet);
2569 rs->last_pass_packet = pass_packet;
89be2091
DJ
2570 }
2571 else
2572 xfree (pass_packet);
2573 }
2574}
2575
82075af2
JS
2576/* If 'QCatchSyscalls' is supported, tell the remote stub
2577 to report syscalls to GDB. */
2578
f6ac5f3d
PA
2579int
2580remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2581 gdb::array_view<const int> syscall_counts)
82075af2 2582{
b80406ac 2583 const char *catch_packet;
82075af2
JS
2584 enum packet_result result;
2585 int n_sysno = 0;
2586
2587 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2588 {
2589 /* Not supported. */
2590 return 1;
2591 }
2592
649a140c 2593 if (needed && any_count == 0)
82075af2 2594 {
649a140c
PA
2595 /* Count how many syscalls are to be caught. */
2596 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2597 {
649a140c 2598 if (syscall_counts[i] != 0)
82075af2
JS
2599 n_sysno++;
2600 }
2601 }
2602
2603 if (remote_debug)
2604 {
2605 fprintf_unfiltered (gdb_stdlog,
2606 "remote_set_syscall_catchpoint "
2607 "pid %d needed %d any_count %d n_sysno %d\n",
2608 pid, needed, any_count, n_sysno);
2609 }
2610
1b81856f 2611 std::string built_packet;
82075af2
JS
2612 if (needed)
2613 {
2614 /* Prepare a packet with the sysno list, assuming max 8+1
2615 characters for a sysno. If the resulting packet size is too
2616 big, fallback on the non-selective packet. */
2617 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2618 built_packet.reserve (maxpktsz);
2619 built_packet = "QCatchSyscalls:1";
649a140c 2620 if (any_count == 0)
82075af2 2621 {
649a140c
PA
2622 /* Add in each syscall to be caught. */
2623 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2624 {
649a140c
PA
2625 if (syscall_counts[i] != 0)
2626 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2627 }
2628 }
1b81856f 2629 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2630 {
2631 /* catch_packet too big. Fallback to less efficient
2632 non selective mode, with GDB doing the filtering. */
b80406ac 2633 catch_packet = "QCatchSyscalls:1";
82075af2 2634 }
b80406ac 2635 else
1b81856f 2636 catch_packet = built_packet.c_str ();
82075af2
JS
2637 }
2638 else
b80406ac 2639 catch_packet = "QCatchSyscalls:0";
82075af2 2640
b80406ac 2641 struct remote_state *rs = get_remote_state ();
82075af2 2642
b80406ac
TT
2643 putpkt (catch_packet);
2644 getpkt (&rs->buf, &rs->buf_size, 0);
2645 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2646 if (result == PACKET_OK)
2647 return 0;
2648 else
2649 return -1;
82075af2
JS
2650}
2651
9b224c5e
PA
2652/* If 'QProgramSignals' is supported, tell the remote stub what
2653 signals it should pass through to the inferior when detaching. */
2654
f6ac5f3d
PA
2655void
2656remote_target::program_signals (int numsigs, unsigned char *signals)
9b224c5e 2657{
4082afcc 2658 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2659 {
2660 char *packet, *p;
2661 int count = 0, i;
5e4a05c4 2662 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2663
2664 gdb_assert (numsigs < 256);
2665 for (i = 0; i < numsigs; i++)
2666 {
2667 if (signals[i])
2668 count++;
2669 }
224c3ddb 2670 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2671 strcpy (packet, "QProgramSignals:");
2672 p = packet + strlen (packet);
2673 for (i = 0; i < numsigs; i++)
2674 {
2675 if (signal_pass_state (i))
2676 {
2677 if (i >= 16)
2678 *p++ = tohex (i >> 4);
2679 *p++ = tohex (i & 15);
2680 if (count)
2681 *p++ = ';';
2682 else
2683 break;
2684 count--;
2685 }
2686 }
2687 *p = 0;
5e4a05c4
TT
2688 if (!rs->last_program_signals_packet
2689 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2690 {
9b224c5e
PA
2691 putpkt (packet);
2692 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2693 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2694 xfree (rs->last_program_signals_packet);
2695 rs->last_program_signals_packet = packet;
9b224c5e
PA
2696 }
2697 else
2698 xfree (packet);
2699 }
2700}
2701
79d7f229
PA
2702/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2703 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2704 thread. If GEN is set, set the general thread, if not, then set
2705 the step/continue thread. */
6b8edb51
PA
2706void
2707remote_target::set_thread (ptid_t ptid, int gen)
c906108c 2708{
d01949b6 2709 struct remote_state *rs = get_remote_state ();
47f8a51d 2710 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2711 char *buf = rs->buf;
79d7f229 2712 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2713
79d7f229 2714 if (ptid_equal (state, ptid))
c906108c
SS
2715 return;
2716
79d7f229
PA
2717 *buf++ = 'H';
2718 *buf++ = gen ? 'g' : 'c';
2719 if (ptid_equal (ptid, magic_null_ptid))
2720 xsnprintf (buf, endbuf - buf, "0");
2721 else if (ptid_equal (ptid, any_thread_ptid))
2722 xsnprintf (buf, endbuf - buf, "0");
2723 else if (ptid_equal (ptid, minus_one_ptid))
2724 xsnprintf (buf, endbuf - buf, "-1");
2725 else
82f73884 2726 write_ptid (buf, endbuf, ptid);
79d7f229 2727 putpkt (rs->buf);
6d820c5c 2728 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2729 if (gen)
47f8a51d 2730 rs->general_thread = ptid;
c906108c 2731 else
47f8a51d 2732 rs->continue_thread = ptid;
c906108c 2733}
79d7f229 2734
6b8edb51
PA
2735void
2736remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
2737{
2738 set_thread (ptid, 1);
2739}
2740
6b8edb51
PA
2741void
2742remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
2743{
2744 set_thread (ptid, 0);
2745}
2746
3c9c4b83
PA
2747/* Change the remote current process. Which thread within the process
2748 ends up selected isn't important, as long as it is the same process
2749 as what INFERIOR_PTID points to.
2750
2751 This comes from that fact that there is no explicit notion of
2752 "selected process" in the protocol. The selected process for
2753 general operations is the process the selected general thread
2754 belongs to. */
2755
6b8edb51
PA
2756void
2757remote_target::set_general_process ()
3c9c4b83
PA
2758{
2759 struct remote_state *rs = get_remote_state ();
2760
2761 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2762 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2763 return;
2764
2765 /* We only need to change the remote current thread if it's pointing
2766 at some other process. */
47f8a51d 2767 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2768 set_general_thread (inferior_ptid);
2769}
2770
c906108c 2771\f
7d1a114c
PA
2772/* Return nonzero if this is the main thread that we made up ourselves
2773 to model non-threaded targets as single-threaded. */
c906108c
SS
2774
2775static int
f6ac5f3d 2776remote_thread_always_alive (ptid_t ptid)
c906108c 2777{
c0a2216e
PA
2778 if (ptid_equal (ptid, magic_null_ptid))
2779 /* The main thread is always alive. */
2780 return 1;
2781
ba348170 2782 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2783 /* The main thread is always alive. This can happen after a
2784 vAttach, if the remote side doesn't support
2785 multi-threading. */
2786 return 1;
2787
7d1a114c
PA
2788 return 0;
2789}
2790
2791/* Return nonzero if the thread PTID is still alive on the remote
2792 system. */
2793
57810aa7 2794bool
f6ac5f3d 2795remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
2796{
2797 struct remote_state *rs = get_remote_state ();
2798 char *p, *endp;
2799
2800 /* Check if this is a thread that we made up ourselves to model
2801 non-threaded targets as single-threaded. */
f6ac5f3d 2802 if (remote_thread_always_alive (ptid))
7d1a114c
PA
2803 return 1;
2804
82f73884
PA
2805 p = rs->buf;
2806 endp = rs->buf + get_remote_packet_size ();
2807
2808 *p++ = 'T';
2809 write_ptid (p, endp, ptid);
2810
2e9f7625 2811 putpkt (rs->buf);
6d820c5c 2812 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2813 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2814}
2815
79efa585
SM
2816/* Return a pointer to a thread name if we know it and NULL otherwise.
2817 The thread_info object owns the memory for the name. */
2818
f6ac5f3d
PA
2819const char *
2820remote_target::thread_name (struct thread_info *info)
79efa585
SM
2821{
2822 if (info->priv != NULL)
a9334058
SM
2823 {
2824 const std::string &name = get_remote_thread_info (info)->name;
2825 return !name.empty () ? name.c_str () : NULL;
2826 }
79efa585
SM
2827
2828 return NULL;
2829}
2830
c906108c
SS
2831/* About these extended threadlist and threadinfo packets. They are
2832 variable length packets but, the fields within them are often fixed
2833 length. They are redundent enough to send over UDP as is the
2834 remote protocol in general. There is a matching unit test module
2835 in libstub. */
2836
23860348 2837/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2838 libstub protocol encoding, and remote.c. It is not particularly
23860348 2839 changable. */
cce74817
JM
2840
2841/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2842 Plan to fix this. */
cce74817 2843
23860348 2844typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2845
9d1f7ab2 2846/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2847 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2848
2849struct gdb_ext_thread_info
c5aa993b 2850 {
23860348 2851 threadref threadid; /* External form of thread reference. */
2bc416ba 2852 int active; /* Has state interesting to GDB?
23860348 2853 regs, stack. */
2bc416ba 2854 char display[256]; /* Brief state display, name,
cedea757 2855 blocked/suspended. */
23860348 2856 char shortname[32]; /* To be used to name threads. */
2bc416ba 2857 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2858 whatever. */
c5aa993b 2859 };
cce74817
JM
2860
2861/* The volume of remote transfers can be limited by submitting
2862 a mask containing bits specifying the desired information.
2863 Use a union of these values as the 'selection' parameter to
0df8b418 2864 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2865
2866#define TAG_THREADID 1
2867#define TAG_EXISTS 2
2868#define TAG_DISPLAY 4
2869#define TAG_THREADNAME 8
c5aa993b 2870#define TAG_MOREDISPLAY 16
cce74817 2871
23860348 2872#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2873
a14ed312 2874static char *unpack_nibble (char *buf, int *val);
cce74817 2875
a14ed312 2876static char *unpack_byte (char *buf, int *value);
cce74817 2877
a14ed312 2878static char *pack_int (char *buf, int value);
cce74817 2879
a14ed312 2880static char *unpack_int (char *buf, int *value);
cce74817 2881
a14ed312 2882static char *unpack_string (char *src, char *dest, int length);
cce74817 2883
23860348 2884static char *pack_threadid (char *pkt, threadref *id);
cce74817 2885
23860348 2886static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2887
23860348 2888void int_to_threadref (threadref *id, int value);
cce74817 2889
23860348 2890static int threadref_to_int (threadref *ref);
cce74817 2891
23860348 2892static void copy_threadref (threadref *dest, threadref *src);
cce74817 2893
23860348 2894static int threadmatch (threadref *dest, threadref *src);
cce74817 2895
2bc416ba 2896static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2897 threadref *id);
cce74817 2898
a14ed312
KB
2899static char *pack_threadlist_request (char *pkt, int startflag,
2900 int threadcount,
23860348 2901 threadref *nextthread);
cce74817 2902
23860348 2903static int remote_newthread_step (threadref *ref, void *context);
cce74817 2904
82f73884
PA
2905
2906/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2907 buffer we're allowed to write to. Returns
2908 BUF+CHARACTERS_WRITTEN. */
2909
6b8edb51
PA
2910char *
2911remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
2912{
2913 int pid, tid;
2914 struct remote_state *rs = get_remote_state ();
2915
2916 if (remote_multi_process_p (rs))
2917 {
2918 pid = ptid_get_pid (ptid);
2919 if (pid < 0)
2920 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2921 else
2922 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2923 }
ba348170 2924 tid = ptid_get_lwp (ptid);
82f73884
PA
2925 if (tid < 0)
2926 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2927 else
2928 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2929
2930 return buf;
2931}
2932
256642e8
PA
2933/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2934 last parsed char. Returns null_ptid if no thread id is found, and
2935 throws an error if the thread id has an invalid format. */
82f73884
PA
2936
2937static ptid_t
256642e8 2938read_ptid (const char *buf, const char **obuf)
82f73884 2939{
256642e8
PA
2940 const char *p = buf;
2941 const char *pp;
82f73884 2942 ULONGEST pid = 0, tid = 0;
82f73884
PA
2943
2944 if (*p == 'p')
2945 {
2946 /* Multi-process ptid. */
2947 pp = unpack_varlen_hex (p + 1, &pid);
2948 if (*pp != '.')
b37520b6 2949 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2950
2951 p = pp;
2952 pp = unpack_varlen_hex (p + 1, &tid);
2953 if (obuf)
2954 *obuf = pp;
ba348170 2955 return ptid_build (pid, tid, 0);
82f73884
PA
2956 }
2957
2958 /* No multi-process. Just a tid. */
2959 pp = unpack_varlen_hex (p, &tid);
2960
c9f35b34
KB
2961 /* Return null_ptid when no thread id is found. */
2962 if (p == pp)
2963 {
2964 if (obuf)
2965 *obuf = pp;
2966 return null_ptid;
2967 }
2968
82f73884 2969 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2970 what's in inferior_ptid, unless it's null at this point. If so,
2971 then since there's no way to know the pid of the reported
2972 threads, use the magic number. */
2973 if (ptid_equal (inferior_ptid, null_ptid))
2974 pid = ptid_get_pid (magic_null_ptid);
2975 else
2976 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2977
2978 if (obuf)
2979 *obuf = pp;
ba348170 2980 return ptid_build (pid, tid, 0);
82f73884
PA
2981}
2982
c906108c 2983static int
fba45db2 2984stubhex (int ch)
c906108c
SS
2985{
2986 if (ch >= 'a' && ch <= 'f')
2987 return ch - 'a' + 10;
2988 if (ch >= '0' && ch <= '9')
2989 return ch - '0';
2990 if (ch >= 'A' && ch <= 'F')
2991 return ch - 'A' + 10;
2992 return -1;
2993}
2994
2995static int
fba45db2 2996stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2997{
2998 int nibble;
2999 int retval = 0;
3000
3001 while (fieldlength)
3002 {
3003 nibble = stubhex (*buff++);
3004 retval |= nibble;
3005 fieldlength--;
3006 if (fieldlength)
3007 retval = retval << 4;
3008 }
3009 return retval;
3010}
3011
c906108c 3012static char *
fba45db2 3013unpack_nibble (char *buf, int *val)
c906108c 3014{
b7589f7d 3015 *val = fromhex (*buf++);
c906108c
SS
3016 return buf;
3017}
3018
c906108c 3019static char *
fba45db2 3020unpack_byte (char *buf, int *value)
c906108c
SS
3021{
3022 *value = stub_unpack_int (buf, 2);
3023 return buf + 2;
3024}
3025
3026static char *
fba45db2 3027pack_int (char *buf, int value)
c906108c
SS
3028{
3029 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3030 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3031 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3032 buf = pack_hex_byte (buf, (value & 0xff));
3033 return buf;
3034}
3035
3036static char *
fba45db2 3037unpack_int (char *buf, int *value)
c906108c
SS
3038{
3039 *value = stub_unpack_int (buf, 8);
3040 return buf + 8;
3041}
3042
23860348 3043#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3044static char *pack_string (char *pkt, char *string);
c906108c
SS
3045
3046static char *
fba45db2 3047pack_string (char *pkt, char *string)
c906108c
SS
3048{
3049 char ch;
3050 int len;
3051
3052 len = strlen (string);
3053 if (len > 200)
23860348 3054 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3055 pkt = pack_hex_byte (pkt, len);
3056 while (len-- > 0)
3057 {
3058 ch = *string++;
3059 if ((ch == '\0') || (ch == '#'))
23860348 3060 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3061 *pkt++ = ch;
3062 }
3063 return pkt;
3064}
3065#endif /* 0 (unused) */
3066
3067static char *
fba45db2 3068unpack_string (char *src, char *dest, int length)
c906108c
SS
3069{
3070 while (length--)
3071 *dest++ = *src++;
3072 *dest = '\0';
3073 return src;
3074}
3075
3076static char *
fba45db2 3077pack_threadid (char *pkt, threadref *id)
c906108c
SS
3078{
3079 char *limit;
3080 unsigned char *altid;
3081
3082 altid = (unsigned char *) id;
3083 limit = pkt + BUF_THREAD_ID_SIZE;
3084 while (pkt < limit)
3085 pkt = pack_hex_byte (pkt, *altid++);
3086 return pkt;
3087}
3088
3089
3090static char *
fba45db2 3091unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
3092{
3093 char *altref;
3094 char *limit = inbuf + BUF_THREAD_ID_SIZE;
3095 int x, y;
3096
3097 altref = (char *) id;
3098
3099 while (inbuf < limit)
3100 {
3101 x = stubhex (*inbuf++);
3102 y = stubhex (*inbuf++);
3103 *altref++ = (x << 4) | y;
3104 }
3105 return inbuf;
3106}
3107
3108/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3109 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3110 to use 64bit thread references internally. This is an adapter
3111 function. */
3112
3113void
fba45db2 3114int_to_threadref (threadref *id, int value)
c906108c
SS
3115{
3116 unsigned char *scan;
3117
3118 scan = (unsigned char *) id;
3119 {
3120 int i = 4;
3121 while (i--)
3122 *scan++ = 0;
3123 }
3124 *scan++ = (value >> 24) & 0xff;
3125 *scan++ = (value >> 16) & 0xff;
3126 *scan++ = (value >> 8) & 0xff;
3127 *scan++ = (value & 0xff);
3128}
3129
3130static int
fba45db2 3131threadref_to_int (threadref *ref)
c906108c
SS
3132{
3133 int i, value = 0;
3134 unsigned char *scan;
3135
cfd77fa1 3136 scan = *ref;
c906108c
SS
3137 scan += 4;
3138 i = 4;
3139 while (i-- > 0)
3140 value = (value << 8) | ((*scan++) & 0xff);
3141 return value;
3142}
3143
3144static void
fba45db2 3145copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3146{
3147 int i;
3148 unsigned char *csrc, *cdest;
3149
3150 csrc = (unsigned char *) src;
3151 cdest = (unsigned char *) dest;
3152 i = 8;
3153 while (i--)
3154 *cdest++ = *csrc++;
3155}
3156
3157static int
fba45db2 3158threadmatch (threadref *dest, threadref *src)
c906108c 3159{
23860348 3160 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3161#if 0
3162 unsigned char *srcp, *destp;
3163 int i, result;
3164 srcp = (char *) src;
3165 destp = (char *) dest;
3166
3167 result = 1;
3168 while (i-- > 0)
3169 result &= (*srcp++ == *destp++) ? 1 : 0;
3170 return result;
3171#endif
3172 return 1;
3173}
3174
3175/*
c5aa993b
JM
3176 threadid:1, # always request threadid
3177 context_exists:2,
3178 display:4,
3179 unique_name:8,
3180 more_display:16
3181 */
c906108c
SS
3182
3183/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3184
3185static char *
fba45db2 3186pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3187{
23860348
MS
3188 *pkt++ = 'q'; /* Info Query */
3189 *pkt++ = 'P'; /* process or thread info */
3190 pkt = pack_int (pkt, mode); /* mode */
c906108c 3191 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3192 *pkt = '\0'; /* terminate */
c906108c
SS
3193 return pkt;
3194}
3195
23860348 3196/* These values tag the fields in a thread info response packet. */
c906108c 3197/* Tagging the fields allows us to request specific fields and to
23860348 3198 add more fields as time goes by. */
c906108c 3199
23860348 3200#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3201#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3202 fetch registers and its stack? */
c5aa993b 3203#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3204#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3205#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3206 the process. */
c906108c 3207
6b8edb51
PA
3208int
3209remote_target::remote_unpack_thread_info_response (char *pkt,
3210 threadref *expectedref,
3211 gdb_ext_thread_info *info)
c906108c 3212{
d01949b6 3213 struct remote_state *rs = get_remote_state ();
c906108c 3214 int mask, length;
cfd77fa1 3215 int tag;
c906108c 3216 threadref ref;
6d820c5c 3217 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
3218 int retval = 1;
3219
23860348 3220 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3221 info->active = 0;
3222 info->display[0] = '\0';
3223 info->shortname[0] = '\0';
3224 info->more_display[0] = '\0';
3225
23860348
MS
3226 /* Assume the characters indicating the packet type have been
3227 stripped. */
c906108c
SS
3228 pkt = unpack_int (pkt, &mask); /* arg mask */
3229 pkt = unpack_threadid (pkt, &ref);
3230
3231 if (mask == 0)
8a3fe4f8 3232 warning (_("Incomplete response to threadinfo request."));
c906108c 3233 if (!threadmatch (&ref, expectedref))
23860348 3234 { /* This is an answer to a different request. */
8a3fe4f8 3235 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3236 return 0;
3237 }
3238 copy_threadref (&info->threadid, &ref);
3239
23860348 3240 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 3241
23860348
MS
3242 /* Packets are terminated with nulls. */
3243 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3244 {
3245 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3246 pkt = unpack_byte (pkt, &length); /* length */
3247 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3248 {
8a3fe4f8 3249 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3250 retval = 0;
3251 break;
3252 }
3253 if (tag == TAG_THREADID)
3254 {
3255 if (length != 16)
3256 {
8a3fe4f8 3257 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3258 retval = 0;
3259 break;
3260 }
3261 pkt = unpack_threadid (pkt, &ref);
3262 mask = mask & ~TAG_THREADID;
3263 continue;
3264 }
3265 if (tag == TAG_EXISTS)
3266 {
3267 info->active = stub_unpack_int (pkt, length);
3268 pkt += length;
3269 mask = mask & ~(TAG_EXISTS);
3270 if (length > 8)
3271 {
8a3fe4f8 3272 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3273 retval = 0;
3274 break;
3275 }
3276 continue;
3277 }
3278 if (tag == TAG_THREADNAME)
3279 {
3280 pkt = unpack_string (pkt, &info->shortname[0], length);
3281 mask = mask & ~TAG_THREADNAME;
3282 continue;
3283 }
3284 if (tag == TAG_DISPLAY)
3285 {
3286 pkt = unpack_string (pkt, &info->display[0], length);
3287 mask = mask & ~TAG_DISPLAY;
3288 continue;
3289 }
3290 if (tag == TAG_MOREDISPLAY)
3291 {
3292 pkt = unpack_string (pkt, &info->more_display[0], length);
3293 mask = mask & ~TAG_MOREDISPLAY;
3294 continue;
3295 }
8a3fe4f8 3296 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3297 break; /* Not a tag we know about. */
c906108c
SS
3298 }
3299 return retval;
3300}
3301
6b8edb51
PA
3302int
3303remote_target::remote_get_threadinfo (threadref *threadid,
3304 int fieldset,
3305 gdb_ext_thread_info *info)
c906108c 3306{
d01949b6 3307 struct remote_state *rs = get_remote_state ();
c906108c 3308 int result;
c906108c 3309
2e9f7625
DJ
3310 pack_threadinfo_request (rs->buf, fieldset, threadid);
3311 putpkt (rs->buf);
6d820c5c 3312 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
3313
3314 if (rs->buf[0] == '\0')
3315 return 0;
3316
2e9f7625 3317 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 3318 threadid, info);
c906108c
SS
3319 return result;
3320}
3321
c906108c
SS
3322/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3323
3324static char *
fba45db2
KB
3325pack_threadlist_request (char *pkt, int startflag, int threadcount,
3326 threadref *nextthread)
c906108c
SS
3327{
3328 *pkt++ = 'q'; /* info query packet */
3329 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3330 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3331 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3332 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3333 *pkt = '\0';
3334 return pkt;
3335}
3336
3337/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3338
6b8edb51
PA
3339int
3340remote_target::parse_threadlist_response (char *pkt, int result_limit,
3341 threadref *original_echo,
3342 threadref *resultlist,
3343 int *doneflag)
c906108c 3344{
d01949b6 3345 struct remote_state *rs = get_remote_state ();
c906108c
SS
3346 char *limit;
3347 int count, resultcount, done;
3348
3349 resultcount = 0;
3350 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 3351 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 3352 /* done parse past here */
c906108c
SS
3353 pkt = unpack_byte (pkt, &count); /* count field */
3354 pkt = unpack_nibble (pkt, &done);
3355 /* The first threadid is the argument threadid. */
3356 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3357 while ((count-- > 0) && (pkt < limit))
3358 {
3359 pkt = unpack_threadid (pkt, resultlist++);
3360 if (resultcount++ >= result_limit)
3361 break;
3362 }
3363 if (doneflag)
3364 *doneflag = done;
3365 return resultcount;
3366}
3367
6dc54d91
PA
3368/* Fetch the next batch of threads from the remote. Returns -1 if the
3369 qL packet is not supported, 0 on error and 1 on success. */
3370
6b8edb51
PA
3371int
3372remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3373 int result_limit, int *done, int *result_count,
3374 threadref *threadlist)
c906108c 3375{
d01949b6 3376 struct remote_state *rs = get_remote_state ();
c906108c
SS
3377 int result = 1;
3378
23860348 3379 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
3380 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3381 >= get_remote_packet_size ())
ea9c271d 3382 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3383
6d820c5c
DJ
3384 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3385 putpkt (rs->buf);
3386 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 3387 if (*rs->buf == '\0')
6dc54d91
PA
3388 {
3389 /* Packet not supported. */
3390 return -1;
3391 }
3392
3393 *result_count =
3394 parse_threadlist_response (rs->buf + 2, result_limit,
3395 &rs->echo_nextthread, threadlist, done);
c906108c 3396
0d031856 3397 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3398 {
23860348
MS
3399 /* FIXME: This is a good reason to drop the packet. */
3400 /* Possably, there is a duplicate response. */
c906108c
SS
3401 /* Possabilities :
3402 retransmit immediatly - race conditions
3403 retransmit after timeout - yes
3404 exit
3405 wait for packet, then exit
3406 */
8a3fe4f8 3407 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3408 return 0; /* I choose simply exiting. */
c906108c
SS
3409 }
3410 if (*result_count <= 0)
3411 {
3412 if (*done != 1)
3413 {
8a3fe4f8 3414 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3415 result = 0;
3416 }
3417 return result; /* break; */
3418 }
3419 if (*result_count > result_limit)
3420 {
3421 *result_count = 0;
8a3fe4f8 3422 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3423 return 0;
3424 }
3425 return result;
3426}
3427
6dc54d91
PA
3428/* Fetch the list of remote threads, with the qL packet, and call
3429 STEPFUNCTION for each thread found. Stops iterating and returns 1
3430 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3431 STEPFUNCTION returns false. If the packet is not supported,
3432 returns -1. */
c906108c 3433
6b8edb51
PA
3434int
3435remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3436 void *context, int looplimit)
c906108c 3437{
0d031856 3438 struct remote_state *rs = get_remote_state ();
c906108c
SS
3439 int done, i, result_count;
3440 int startflag = 1;
3441 int result = 1;
3442 int loopcount = 0;
c906108c
SS
3443
3444 done = 0;
3445 while (!done)
3446 {
3447 if (loopcount++ > looplimit)
3448 {
3449 result = 0;
8a3fe4f8 3450 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3451 break;
3452 }
6dc54d91
PA
3453 result = remote_get_threadlist (startflag, &rs->nextthread,
3454 MAXTHREADLISTRESULTS,
3455 &done, &result_count,
3456 rs->resultthreadlist);
3457 if (result <= 0)
3458 break;
23860348 3459 /* Clear for later iterations. */
c906108c
SS
3460 startflag = 0;
3461 /* Setup to resume next batch of thread references, set nextthread. */
3462 if (result_count >= 1)
0d031856
TT
3463 copy_threadref (&rs->nextthread,
3464 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3465 i = 0;
3466 while (result_count--)
6dc54d91
PA
3467 {
3468 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3469 {
3470 result = 0;
3471 break;
3472 }
3473 }
c906108c
SS
3474 }
3475 return result;
3476}
3477
6dc54d91
PA
3478/* A thread found on the remote target. */
3479
21fe1c75 3480struct thread_item
6dc54d91 3481{
21fe1c75
SM
3482 explicit thread_item (ptid_t ptid_)
3483 : ptid (ptid_)
3484 {}
3485
3486 thread_item (thread_item &&other) = default;
3487 thread_item &operator= (thread_item &&other) = default;
3488
3489 DISABLE_COPY_AND_ASSIGN (thread_item);
3490
6dc54d91
PA
3491 /* The thread's PTID. */
3492 ptid_t ptid;
3493
21fe1c75
SM
3494 /* The thread's extra info. */
3495 std::string extra;
6dc54d91 3496
21fe1c75
SM
3497 /* The thread's name. */
3498 std::string name;
79efa585 3499
6dc54d91 3500 /* The core the thread was running on. -1 if not known. */
21fe1c75 3501 int core = -1;
f6327dcb
KB
3502
3503 /* The thread handle associated with the thread. */
21fe1c75 3504 gdb::byte_vector thread_handle;
21fe1c75 3505};
6dc54d91
PA
3506
3507/* Context passed around to the various methods listing remote
3508 threads. As new threads are found, they're added to the ITEMS
3509 vector. */
3510
3511struct threads_listing_context
3512{
21fe1c75
SM
3513 /* Return true if this object contains an entry for a thread with ptid
3514 PTID. */
6dc54d91 3515
21fe1c75
SM
3516 bool contains_thread (ptid_t ptid) const
3517 {
3518 auto match_ptid = [&] (const thread_item &item)
3519 {
3520 return item.ptid == ptid;
3521 };
80134cf5 3522
21fe1c75
SM
3523 auto it = std::find_if (this->items.begin (),
3524 this->items.end (),
3525 match_ptid);
80134cf5 3526
21fe1c75
SM
3527 return it != this->items.end ();
3528 }
80134cf5 3529
21fe1c75 3530 /* Remove the thread with ptid PTID. */
80134cf5 3531
21fe1c75
SM
3532 void remove_thread (ptid_t ptid)
3533 {
3534 auto match_ptid = [&] (const thread_item &item)
3535 {
3536 return item.ptid == ptid;
3537 };
cbb8991c 3538
21fe1c75
SM
3539 auto it = std::remove_if (this->items.begin (),
3540 this->items.end (),
3541 match_ptid);
cbb8991c 3542
21fe1c75
SM
3543 if (it != this->items.end ())
3544 this->items.erase (it);
3545 }
3546
3547 /* The threads found on the remote target. */
3548 std::vector<thread_item> items;
3549};
cbb8991c 3550
c906108c 3551static int
6dc54d91 3552remote_newthread_step (threadref *ref, void *data)
c906108c 3553{
19ba03f4
SM
3554 struct threads_listing_context *context
3555 = (struct threads_listing_context *) data;
21fe1c75
SM
3556 int pid = inferior_ptid.pid ();
3557 int lwp = threadref_to_int (ref);
3558 ptid_t ptid (pid, lwp);
6dc54d91 3559
21fe1c75 3560 context->items.emplace_back (ptid);
6dc54d91 3561
c906108c
SS
3562 return 1; /* continue iterator */
3563}
3564
3565#define CRAZY_MAX_THREADS 1000
3566
6b8edb51
PA
3567ptid_t
3568remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3569{
d01949b6 3570 struct remote_state *rs = get_remote_state ();
c906108c
SS
3571
3572 putpkt ("qC");
6d820c5c 3573 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3574 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3575 {
256642e8 3576 const char *obuf;
c9f35b34
KB
3577 ptid_t result;
3578
3579 result = read_ptid (&rs->buf[2], &obuf);
3580 if (*obuf != '\0' && remote_debug)
3581 fprintf_unfiltered (gdb_stdlog,
3582 "warning: garbage in qC reply\n");
3583
3584 return result;
3585 }
c906108c
SS
3586 else
3587 return oldpid;
3588}
3589
6dc54d91 3590/* List remote threads using the deprecated qL packet. */
cce74817 3591
6b8edb51
PA
3592int
3593remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3594{
6dc54d91
PA
3595 if (remote_threadlist_iterator (remote_newthread_step, context,
3596 CRAZY_MAX_THREADS) >= 0)
3597 return 1;
3598
3599 return 0;
c906108c
SS
3600}
3601
dc146f7c
VP
3602#if defined(HAVE_LIBEXPAT)
3603
dc146f7c
VP
3604static void
3605start_thread (struct gdb_xml_parser *parser,
3606 const struct gdb_xml_element *element,
4d0fdd9b
SM
3607 void *user_data,
3608 std::vector<gdb_xml_value> &attributes)
dc146f7c 3609{
19ba03f4
SM
3610 struct threads_listing_context *data
3611 = (struct threads_listing_context *) user_data;
3d2c1d41 3612 struct gdb_xml_value *attr;
dc146f7c 3613
4d0fdd9b 3614 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3615 ptid_t ptid = read_ptid (id, NULL);
3616
3617 data->items.emplace_back (ptid);
3618 thread_item &item = data->items.back ();
dc146f7c 3619
3d2c1d41
PA
3620 attr = xml_find_attribute (attributes, "core");
3621 if (attr != NULL)
4d0fdd9b 3622 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3623
79efa585 3624 attr = xml_find_attribute (attributes, "name");
21fe1c75 3625 if (attr != NULL)
4d0fdd9b 3626 item.name = (const char *) attr->value.get ();
79efa585 3627
f6327dcb
KB
3628 attr = xml_find_attribute (attributes, "handle");
3629 if (attr != NULL)
4d0fdd9b 3630 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3631}
3632
3633static void
3634end_thread (struct gdb_xml_parser *parser,
3635 const struct gdb_xml_element *element,
3636 void *user_data, const char *body_text)
3637{
19ba03f4
SM
3638 struct threads_listing_context *data
3639 = (struct threads_listing_context *) user_data;
dc146f7c 3640
21fe1c75
SM
3641 if (body_text != NULL && *body_text != '\0')
3642 data->items.back ().extra = body_text;
dc146f7c
VP
3643}
3644
3645const struct gdb_xml_attribute thread_attributes[] = {
3646 { "id", GDB_XML_AF_NONE, NULL, NULL },
3647 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3648 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3649 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3650 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3651};
3652
3653const struct gdb_xml_element thread_children[] = {
3654 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3655};
3656
3657const struct gdb_xml_element threads_children[] = {
3658 { "thread", thread_attributes, thread_children,
3659 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3660 start_thread, end_thread },
3661 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3662};
3663
3664const struct gdb_xml_element threads_elements[] = {
3665 { "threads", NULL, threads_children,
3666 GDB_XML_EF_NONE, NULL, NULL },
3667 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3668};
3669
3670#endif
3671
6dc54d91 3672/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3673
6b8edb51
PA
3674int
3675remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 3676{
dc146f7c 3677#if defined(HAVE_LIBEXPAT)
4082afcc 3678 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3679 {
9018be22 3680 gdb::optional<gdb::char_vector> xml
6b8edb51 3681 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3682
9018be22 3683 if (xml && (*xml)[0] != '\0')
dc146f7c 3684 {
6dc54d91 3685 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3686 threads_elements, xml->data (), context);
dc146f7c
VP
3687 }
3688
6dc54d91 3689 return 1;
dc146f7c
VP
3690 }
3691#endif
3692
6dc54d91
PA
3693 return 0;
3694}
3695
3696/* List remote threads using qfThreadInfo/qsThreadInfo. */
3697
6b8edb51
PA
3698int
3699remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
3700{
3701 struct remote_state *rs = get_remote_state ();
3702
b80fafe3 3703 if (rs->use_threadinfo_query)
9d1f7ab2 3704 {
256642e8 3705 const char *bufp;
6dc54d91 3706
9d1f7ab2 3707 putpkt ("qfThreadInfo");
6d820c5c 3708 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3709 bufp = rs->buf;
9d1f7ab2 3710 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3711 {
9d1f7ab2
MS
3712 while (*bufp++ == 'm') /* reply contains one or more TID */
3713 {
3714 do
3715 {
21fe1c75
SM
3716 ptid_t ptid = read_ptid (bufp, &bufp);
3717 context->items.emplace_back (ptid);
9d1f7ab2
MS
3718 }
3719 while (*bufp++ == ','); /* comma-separated list */
3720 putpkt ("qsThreadInfo");
6d820c5c 3721 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3722 bufp = rs->buf;
9d1f7ab2 3723 }
6dc54d91
PA
3724 return 1;
3725 }
3726 else
3727 {
3728 /* Packet not recognized. */
3729 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3730 }
3731 }
3732
6dc54d91
PA
3733 return 0;
3734}
3735
e8032dde 3736/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3737 targets. */
3738
f6ac5f3d
PA
3739void
3740remote_target::update_thread_list ()
6dc54d91 3741{
6dc54d91 3742 struct threads_listing_context context;
ab970af1 3743 int got_list = 0;
e8032dde 3744
6dc54d91
PA
3745 /* We have a few different mechanisms to fetch the thread list. Try
3746 them all, starting with the most preferred one first, falling
3747 back to older methods. */
6b8edb51
PA
3748 if (remote_get_threads_with_qxfer (&context)
3749 || remote_get_threads_with_qthreadinfo (&context)
3750 || remote_get_threads_with_ql (&context))
6dc54d91 3751 {
ab970af1
PA
3752 struct thread_info *tp, *tmp;
3753
3754 got_list = 1;
3755
21fe1c75 3756 if (context.items.empty ()
f6ac5f3d 3757 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
3758 {
3759 /* Some targets don't really support threads, but still
3760 reply an (empty) thread list in response to the thread
3761 listing packets, instead of replying "packet not
3762 supported". Exit early so we don't delete the main
3763 thread. */
7d1a114c
PA
3764 return;
3765 }
3766
ab970af1
PA
3767 /* CONTEXT now holds the current thread list on the remote
3768 target end. Delete GDB-side threads no longer found on the
3769 target. */
8a06aea7 3770 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3771 {
21fe1c75 3772 if (!context.contains_thread (tp->ptid))
ab970af1
PA
3773 {
3774 /* Not found. */
3775 delete_thread (tp->ptid);
3776 }
cbb8991c
DB
3777 }
3778
3779 /* Remove any unreported fork child threads from CONTEXT so
3780 that we don't interfere with follow fork, which is where
3781 creation of such threads is handled. */
3782 remove_new_fork_children (&context);
74531fed 3783
ab970af1 3784 /* And now add threads we don't know about yet to our list. */
21fe1c75 3785 for (thread_item &item : context.items)
6dc54d91 3786 {
21fe1c75 3787 if (item.ptid != null_ptid)
6dc54d91 3788 {
6dc54d91 3789 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3790 executing until proven otherwise with a stop reply.
3791 In all-stop, we can only get here if all threads are
6dc54d91 3792 stopped. */
0d5b594f 3793 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3794
21fe1c75 3795 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 3796
7aabaf9d 3797 remote_thread_info *info = get_remote_thread_info (item.ptid);
21fe1c75 3798 info->core = item.core;
7aabaf9d
SM
3799 info->extra = std::move (item.extra);
3800 info->name = std::move (item.name);
3801 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
3802 }
3803 }
3804 }
3805
ab970af1
PA
3806 if (!got_list)
3807 {
3808 /* If no thread listing method is supported, then query whether
3809 each known thread is alive, one by one, with the T packet.
3810 If the target doesn't support threads at all, then this is a
3811 no-op. See remote_thread_alive. */
3812 prune_threads ();
3813 }
9d1f7ab2
MS
3814}
3815
802188a7 3816/*
9d1f7ab2
MS
3817 * Collect a descriptive string about the given thread.
3818 * The target may say anything it wants to about the thread
3819 * (typically info about its blocked / runnable state, name, etc.).
3820 * This string will appear in the info threads display.
802188a7 3821 *
9d1f7ab2
MS
3822 * Optional: targets are not required to implement this function.
3823 */
3824
f6ac5f3d
PA
3825const char *
3826remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 3827{
d01949b6 3828 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3829 int result;
3830 int set;
3831 threadref id;
3832 struct gdb_ext_thread_info threadinfo;
23860348 3833 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3834 int n = 0; /* position in display_buf */
3835
5d93a237 3836 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3837 internal_error (__FILE__, __LINE__,
e2e0b3e5 3838 _("remote_threads_extra_info"));
9d1f7ab2 3839
60e569b9 3840 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3841 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3842 /* This is the main thread which was added by GDB. The remote
3843 server doesn't know about it. */
3844 return NULL;
3845
4082afcc 3846 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3847 {
3848 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3849
7aabaf9d 3850 if (info != NULL && info->priv != NULL)
a9334058
SM
3851 {
3852 const std::string &extra = get_remote_thread_info (info)->extra;
3853 return !extra.empty () ? extra.c_str () : NULL;
3854 }
dc146f7c
VP
3855 else
3856 return NULL;
3857 }
3858
b80fafe3 3859 if (rs->use_threadextra_query)
9d1f7ab2 3860 {
82f73884
PA
3861 char *b = rs->buf;
3862 char *endb = rs->buf + get_remote_packet_size ();
3863
3864 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3865 b += strlen (b);
3866 write_ptid (b, endb, tp->ptid);
3867
2e9f7625 3868 putpkt (rs->buf);
6d820c5c 3869 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3870 if (rs->buf[0] != 0)
9d1f7ab2 3871 {
325fac50 3872 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
2e9f7625 3873 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3874 display_buf [result] = '\0';
9d1f7ab2
MS
3875 return display_buf;
3876 }
0f71a2f6 3877 }
9d1f7ab2
MS
3878
3879 /* If the above query fails, fall back to the old method. */
b80fafe3 3880 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3881 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3882 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3883 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3884 if (remote_get_threadinfo (&id, set, &threadinfo))
3885 if (threadinfo.active)
0f71a2f6 3886 {
9d1f7ab2 3887 if (*threadinfo.shortname)
2bc416ba 3888 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3889 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3890 if (*threadinfo.display)
2bc416ba 3891 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3892 " State: %s,", threadinfo.display);
9d1f7ab2 3893 if (*threadinfo.more_display)
2bc416ba 3894 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3895 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3896
3897 if (n > 0)
c5aa993b 3898 {
23860348 3899 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3900 if (',' == display_buf[n-1])
3901 display_buf[n-1] = ' ';
3902 return display_buf;
c5aa993b 3903 }
0f71a2f6 3904 }
9d1f7ab2 3905 return NULL;
0f71a2f6 3906}
c906108c 3907\f
c5aa993b 3908
f6ac5f3d
PA
3909bool
3910remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3911 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
3912{
3913 struct remote_state *rs = get_remote_state ();
3914 char *p = rs->buf;
3915
bba74b36 3916 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3917 p += strlen (p);
3918 p += hexnumstr (p, addr);
3919 putpkt (rs->buf);
3920 getpkt (&rs->buf, &rs->buf_size, 0);
3921 p = rs->buf;
3922
3923 if (*p == 'E')
3924 error (_("Remote failure reply: %s"), p);
3925
3926 if (*p++ == 'm')
3927 {
256642e8 3928 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 3929 return true;
0fb4aa4b
PA
3930 }
3931
5d9310c4 3932 return false;
0fb4aa4b
PA
3933}
3934
f6ac5f3d
PA
3935std::vector<static_tracepoint_marker>
3936remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
3937{
3938 struct remote_state *rs = get_remote_state ();
5d9310c4 3939 std::vector<static_tracepoint_marker> markers;
256642e8 3940 const char *p;
5d9310c4 3941 static_tracepoint_marker marker;
0fb4aa4b
PA
3942
3943 /* Ask for a first packet of static tracepoint marker
3944 definition. */
3945 putpkt ("qTfSTM");
3946 getpkt (&rs->buf, &rs->buf_size, 0);
3947 p = rs->buf;
3948 if (*p == 'E')
3949 error (_("Remote failure reply: %s"), p);
3950
0fb4aa4b
PA
3951 while (*p++ == 'm')
3952 {
0fb4aa4b
PA
3953 do
3954 {
5d9310c4 3955 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 3956
5d9310c4
SM
3957 if (strid == NULL || marker.str_id == strid)
3958 markers.push_back (std::move (marker));
0fb4aa4b
PA
3959 }
3960 while (*p++ == ','); /* comma-separated list */
3961 /* Ask for another packet of static tracepoint definition. */
3962 putpkt ("qTsSTM");
3963 getpkt (&rs->buf, &rs->buf_size, 0);
3964 p = rs->buf;
3965 }
3966
0fb4aa4b
PA
3967 return markers;
3968}
3969
3970\f
10760264
JB
3971/* Implement the to_get_ada_task_ptid function for the remote targets. */
3972
f6ac5f3d
PA
3973ptid_t
3974remote_target::get_ada_task_ptid (long lwp, long thread)
10760264 3975{
ba348170 3976 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3977}
3978\f
3979
24b06219 3980/* Restart the remote side; this is an extended protocol operation. */
c906108c 3981
6b8edb51
PA
3982void
3983remote_target::extended_remote_restart ()
c906108c 3984{
d01949b6 3985 struct remote_state *rs = get_remote_state ();
c906108c
SS
3986
3987 /* Send the restart command; for reasons I don't understand the
3988 remote side really expects a number after the "R". */
ea9c271d 3989 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3990 putpkt (rs->buf);
c906108c 3991
ad9a8f3f 3992 remote_fileio_reset ();
c906108c
SS
3993}
3994\f
3995/* Clean up connection to a remote debugger. */
3996
f6ac5f3d
PA
3997void
3998remote_target::close ()
c906108c 3999{
048094ac 4000 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4001 terminal_ours ();
ce5ce7ed 4002
ce5ce7ed 4003 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
4004 of all the inferiors and their threads we were controlling.
4005 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4006 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 4007 inferior_ptid = null_ptid;
f67fd822 4008 discard_all_inferiors ();
ce5ce7ed 4009
6b8edb51
PA
4010 trace_reset_local_state ();
4011
4012 delete this;
4013}
4014
4015remote_target::~remote_target ()
4016{
4017 struct remote_state *rs = get_remote_state ();
4018
4019 /* Check for NULL because we may get here with a partially
4020 constructed target/connection. */
4021 if (rs->remote_desc == nullptr)
4022 return;
4023
4024 serial_close (rs->remote_desc);
4025
4026 /* We are destroying the remote target, so we should discard
f48ff2a7 4027 everything of this target. */
6b8edb51 4028 discard_pending_stop_replies_in_queue ();
74531fed 4029
6b8edb51
PA
4030 if (rs->remote_async_inferior_event_token)
4031 delete_async_event_handler (&rs->remote_async_inferior_event_token);
722247f1 4032
5965e028 4033 remote_notif_state_xfree (rs->notif_state);
c906108c
SS
4034}
4035
23860348 4036/* Query the remote side for the text, data and bss offsets. */
c906108c 4037
6b8edb51
PA
4038void
4039remote_target::get_offsets ()
c906108c 4040{
d01949b6 4041 struct remote_state *rs = get_remote_state ();
2e9f7625 4042 char *buf;
085dd6e6 4043 char *ptr;
31d99776
DJ
4044 int lose, num_segments = 0, do_sections, do_segments;
4045 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 4046 struct section_offsets *offs;
31d99776
DJ
4047 struct symfile_segment_data *data;
4048
4049 if (symfile_objfile == NULL)
4050 return;
c906108c
SS
4051
4052 putpkt ("qOffsets");
6d820c5c 4053 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4054 buf = rs->buf;
c906108c
SS
4055
4056 if (buf[0] == '\000')
4057 return; /* Return silently. Stub doesn't support
23860348 4058 this command. */
c906108c
SS
4059 if (buf[0] == 'E')
4060 {
8a3fe4f8 4061 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4062 return;
4063 }
4064
4065 /* Pick up each field in turn. This used to be done with scanf, but
4066 scanf will make trouble if CORE_ADDR size doesn't match
4067 conversion directives correctly. The following code will work
4068 with any size of CORE_ADDR. */
4069 text_addr = data_addr = bss_addr = 0;
4070 ptr = buf;
4071 lose = 0;
4072
61012eef 4073 if (startswith (ptr, "Text="))
c906108c
SS
4074 {
4075 ptr += 5;
4076 /* Don't use strtol, could lose on big values. */
4077 while (*ptr && *ptr != ';')
4078 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4079
61012eef 4080 if (startswith (ptr, ";Data="))
31d99776
DJ
4081 {
4082 ptr += 6;
4083 while (*ptr && *ptr != ';')
4084 data_addr = (data_addr << 4) + fromhex (*ptr++);
4085 }
4086 else
4087 lose = 1;
4088
61012eef 4089 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4090 {
4091 ptr += 5;
4092 while (*ptr && *ptr != ';')
4093 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4094
31d99776
DJ
4095 if (bss_addr != data_addr)
4096 warning (_("Target reported unsupported offsets: %s"), buf);
4097 }
4098 else
4099 lose = 1;
4100 }
61012eef 4101 else if (startswith (ptr, "TextSeg="))
c906108c 4102 {
31d99776
DJ
4103 ptr += 8;
4104 /* Don't use strtol, could lose on big values. */
c906108c 4105 while (*ptr && *ptr != ';')
31d99776
DJ
4106 text_addr = (text_addr << 4) + fromhex (*ptr++);
4107 num_segments = 1;
4108
61012eef 4109 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4110 {
4111 ptr += 9;
4112 while (*ptr && *ptr != ';')
4113 data_addr = (data_addr << 4) + fromhex (*ptr++);
4114 num_segments++;
4115 }
c906108c
SS
4116 }
4117 else
4118 lose = 1;
4119
4120 if (lose)
8a3fe4f8 4121 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4122 else if (*ptr != '\0')
4123 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4124
802188a7 4125 offs = ((struct section_offsets *)
a39a16c4 4126 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 4127 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 4128 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 4129
31d99776
DJ
4130 data = get_symfile_segment_data (symfile_objfile->obfd);
4131 do_segments = (data != NULL);
4132 do_sections = num_segments == 0;
c906108c 4133
28c32713 4134 if (num_segments > 0)
31d99776 4135 {
31d99776
DJ
4136 segments[0] = text_addr;
4137 segments[1] = data_addr;
4138 }
28c32713
JB
4139 /* If we have two segments, we can still try to relocate everything
4140 by assuming that the .text and .data offsets apply to the whole
4141 text and data segments. Convert the offsets given in the packet
4142 to base addresses for symfile_map_offsets_to_segments. */
4143 else if (data && data->num_segments == 2)
4144 {
4145 segments[0] = data->segment_bases[0] + text_addr;
4146 segments[1] = data->segment_bases[1] + data_addr;
4147 num_segments = 2;
4148 }
8d385431
DJ
4149 /* If the object file has only one segment, assume that it is text
4150 rather than data; main programs with no writable data are rare,
4151 but programs with no code are useless. Of course the code might
4152 have ended up in the data segment... to detect that we would need
4153 the permissions here. */
4154 else if (data && data->num_segments == 1)
4155 {
4156 segments[0] = data->segment_bases[0] + text_addr;
4157 num_segments = 1;
4158 }
28c32713
JB
4159 /* There's no way to relocate by segment. */
4160 else
4161 do_segments = 0;
31d99776
DJ
4162
4163 if (do_segments)
4164 {
4165 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4166 offs, num_segments, segments);
4167
4168 if (ret == 0 && !do_sections)
3e43a32a
MS
4169 error (_("Can not handle qOffsets TextSeg "
4170 "response with this symbol file"));
31d99776
DJ
4171
4172 if (ret > 0)
4173 do_sections = 0;
4174 }
c906108c 4175
9ef895d6
DJ
4176 if (data)
4177 free_symfile_segment_data (data);
31d99776
DJ
4178
4179 if (do_sections)
4180 {
4181 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4182
3e43a32a
MS
4183 /* This is a temporary kludge to force data and bss to use the
4184 same offsets because that's what nlmconv does now. The real
4185 solution requires changes to the stub and remote.c that I
4186 don't have time to do right now. */
31d99776
DJ
4187
4188 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4189 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4190 }
c906108c
SS
4191
4192 objfile_relocate (symfile_objfile, offs);
4193}
4194
9a7071a8 4195/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4196
4197void
4198remote_target::send_interrupt_sequence ()
9a7071a8 4199{
5d93a237
TT
4200 struct remote_state *rs = get_remote_state ();
4201
9a7071a8 4202 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4203 remote_serial_write ("\x03", 1);
9a7071a8 4204 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4205 serial_send_break (rs->remote_desc);
9a7071a8
JB
4206 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4207 {
5d93a237 4208 serial_send_break (rs->remote_desc);
c33e31fd 4209 remote_serial_write ("g", 1);
9a7071a8
JB
4210 }
4211 else
4212 internal_error (__FILE__, __LINE__,
4213 _("Invalid value for interrupt_sequence_mode: %s."),
4214 interrupt_sequence_mode);
4215}
4216
3405876a
PA
4217
4218/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4219 and extract the PTID. Returns NULL_PTID if not found. */
4220
4221static ptid_t
4222stop_reply_extract_thread (char *stop_reply)
4223{
4224 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4225 {
256642e8 4226 const char *p;
3405876a
PA
4227
4228 /* Txx r:val ; r:val (...) */
4229 p = &stop_reply[3];
4230
4231 /* Look for "register" named "thread". */
4232 while (*p != '\0')
4233 {
256642e8 4234 const char *p1;
3405876a
PA
4235
4236 p1 = strchr (p, ':');
4237 if (p1 == NULL)
4238 return null_ptid;
4239
4240 if (strncmp (p, "thread", p1 - p) == 0)
4241 return read_ptid (++p1, &p);
4242
4243 p1 = strchr (p, ';');
4244 if (p1 == NULL)
4245 return null_ptid;
4246 p1++;
4247
4248 p = p1;
4249 }
4250 }
4251
4252 return null_ptid;
4253}
4254
b7ea362b
PA
4255/* Determine the remote side's current thread. If we have a stop
4256 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4257 "thread" register we can extract the current thread from. If not,
4258 ask the remote which is the current thread with qC. The former
4259 method avoids a roundtrip. */
4260
6b8edb51
PA
4261ptid_t
4262remote_target::get_current_thread (char *wait_status)
b7ea362b 4263{
6a49a997 4264 ptid_t ptid = null_ptid;
b7ea362b
PA
4265
4266 /* Note we don't use remote_parse_stop_reply as that makes use of
4267 the target architecture, which we haven't yet fully determined at
4268 this point. */
4269 if (wait_status != NULL)
4270 ptid = stop_reply_extract_thread (wait_status);
4271 if (ptid_equal (ptid, null_ptid))
4272 ptid = remote_current_thread (inferior_ptid);
4273
4274 return ptid;
4275}
4276
49c62f2e
PA
4277/* Query the remote target for which is the current thread/process,
4278 add it to our tables, and update INFERIOR_PTID. The caller is
4279 responsible for setting the state such that the remote end is ready
3405876a
PA
4280 to return the current thread.
4281
4282 This function is called after handling the '?' or 'vRun' packets,
4283 whose response is a stop reply from which we can also try
4284 extracting the thread. If the target doesn't support the explicit
4285 qC query, we infer the current thread from that stop reply, passed
4286 in in WAIT_STATUS, which may be NULL. */
49c62f2e 4287
6b8edb51
PA
4288void
4289remote_target::add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
4290{
4291 struct remote_state *rs = get_remote_state ();
4292 int fake_pid_p = 0;
49c62f2e
PA
4293
4294 inferior_ptid = null_ptid;
4295
b7ea362b 4296 /* Now, if we have thread information, update inferior_ptid. */
87215ad1 4297 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4298
87215ad1 4299 if (curr_ptid != null_ptid)
49c62f2e
PA
4300 {
4301 if (!remote_multi_process_p (rs))
4302 fake_pid_p = 1;
49c62f2e
PA
4303 }
4304 else
4305 {
4306 /* Without this, some commands which require an active target
4307 (such as kill) won't work. This variable serves (at least)
4308 double duty as both the pid of the target process (if it has
4309 such), and as a flag indicating that a target is active. */
87215ad1 4310 curr_ptid = magic_null_ptid;
49c62f2e
PA
4311 fake_pid_p = 1;
4312 }
4313
87215ad1 4314 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
49c62f2e 4315
87215ad1
SDJ
4316 /* Add the main thread and switch to it. Don't try reading
4317 registers yet, since we haven't fetched the target description
4318 yet. */
4319 thread_info *tp = add_thread_silent (curr_ptid);
4320 switch_to_thread_no_regs (tp);
49c62f2e
PA
4321}
4322
6efcd9a8
PA
4323/* Print info about a thread that was found already stopped on
4324 connection. */
4325
4326static void
4327print_one_stopped_thread (struct thread_info *thread)
4328{
4329 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4330
4331 switch_to_thread (thread->ptid);
4332 stop_pc = get_frame_pc (get_current_frame ());
4333 set_current_sal_from_frame (get_current_frame ());
4334
4335 thread->suspend.waitstatus_pending_p = 0;
4336
4337 if (ws->kind == TARGET_WAITKIND_STOPPED)
4338 {
4339 enum gdb_signal sig = ws->value.sig;
4340
4341 if (signal_print_state (sig))
76727919 4342 gdb::observers::signal_received.notify (sig);
6efcd9a8 4343 }
76727919 4344 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4345}
4346
221e1a37
PA
4347/* Process all initial stop replies the remote side sent in response
4348 to the ? packet. These indicate threads that were already stopped
4349 on initial connection. We mark these threads as stopped and print
4350 their current frame before giving the user the prompt. */
4351
6b8edb51
PA
4352void
4353remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4354{
4355 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4356 struct inferior *inf;
4357 struct thread_info *thread;
4358 struct thread_info *selected = NULL;
4359 struct thread_info *lowest_stopped = NULL;
4360 struct thread_info *first = NULL;
221e1a37
PA
4361
4362 /* Consume the initial pending events. */
4363 while (pending_stop_replies-- > 0)
4364 {
4365 ptid_t waiton_ptid = minus_one_ptid;
4366 ptid_t event_ptid;
4367 struct target_waitstatus ws;
4368 int ignore_event = 0;
6efcd9a8 4369 struct thread_info *thread;
221e1a37
PA
4370
4371 memset (&ws, 0, sizeof (ws));
4372 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4373 if (remote_debug)
4374 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4375
4376 switch (ws.kind)
4377 {
4378 case TARGET_WAITKIND_IGNORE:
4379 case TARGET_WAITKIND_NO_RESUMED:
4380 case TARGET_WAITKIND_SIGNALLED:
4381 case TARGET_WAITKIND_EXITED:
4382 /* We shouldn't see these, but if we do, just ignore. */
4383 if (remote_debug)
4384 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4385 ignore_event = 1;
4386 break;
4387
4388 case TARGET_WAITKIND_EXECD:
4389 xfree (ws.value.execd_pathname);
4390 break;
4391 default:
4392 break;
4393 }
4394
4395 if (ignore_event)
4396 continue;
4397
6efcd9a8 4398 thread = find_thread_ptid (event_ptid);
221e1a37
PA
4399
4400 if (ws.kind == TARGET_WAITKIND_STOPPED)
4401 {
4402 enum gdb_signal sig = ws.value.sig;
4403
4404 /* Stubs traditionally report SIGTRAP as initial signal,
4405 instead of signal 0. Suppress it. */
4406 if (sig == GDB_SIGNAL_TRAP)
4407 sig = GDB_SIGNAL_0;
6efcd9a8
PA
4408 thread->suspend.stop_signal = sig;
4409 ws.value.sig = sig;
4410 }
221e1a37 4411
6efcd9a8
PA
4412 thread->suspend.waitstatus = ws;
4413
4414 if (ws.kind != TARGET_WAITKIND_STOPPED
4415 || ws.value.sig != GDB_SIGNAL_0)
4416 thread->suspend.waitstatus_pending_p = 1;
4417
4418 set_executing (event_ptid, 0);
4419 set_running (event_ptid, 0);
7aabaf9d 4420 get_remote_thread_info (thread)->vcont_resumed = 0;
6efcd9a8
PA
4421 }
4422
4423 /* "Notice" the new inferiors before anything related to
4424 registers/memory. */
4425 ALL_INFERIORS (inf)
4426 {
4427 if (inf->pid == 0)
4428 continue;
4429
4430 inf->needs_setup = 1;
4431
4432 if (non_stop)
4433 {
4434 thread = any_live_thread_of_process (inf->pid);
4435 notice_new_inferior (thread->ptid,
4436 thread->state == THREAD_RUNNING,
4437 from_tty);
4438 }
4439 }
4440
4441 /* If all-stop on top of non-stop, pause all threads. Note this
4442 records the threads' stop pc, so must be done after "noticing"
4443 the inferiors. */
4444 if (!non_stop)
4445 {
4446 stop_all_threads ();
4447
4448 /* If all threads of an inferior were already stopped, we
4449 haven't setup the inferior yet. */
4450 ALL_INFERIORS (inf)
4451 {
4452 if (inf->pid == 0)
4453 continue;
221e1a37 4454
6efcd9a8
PA
4455 if (inf->needs_setup)
4456 {
4457 thread = any_live_thread_of_process (inf->pid);
4458 switch_to_thread_no_regs (thread);
4459 setup_inferior (0);
4460 }
4461 }
221e1a37 4462 }
6efcd9a8
PA
4463
4464 /* Now go over all threads that are stopped, and print their current
4465 frame. If all-stop, then if there's a signalled thread, pick
4466 that as current. */
4467 ALL_NON_EXITED_THREADS (thread)
4468 {
6efcd9a8
PA
4469 if (first == NULL)
4470 first = thread;
4471
4472 if (!non_stop)
4473 set_running (thread->ptid, 0);
4474 else if (thread->state != THREAD_STOPPED)
4475 continue;
4476
6efcd9a8
PA
4477 if (selected == NULL
4478 && thread->suspend.waitstatus_pending_p)
4479 selected = thread;
4480
5d5658a1
PA
4481 if (lowest_stopped == NULL
4482 || thread->inf->num < lowest_stopped->inf->num
4483 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4484 lowest_stopped = thread;
4485
4486 if (non_stop)
4487 print_one_stopped_thread (thread);
4488 }
4489
4490 /* In all-stop, we only print the status of one thread, and leave
4491 others with their status pending. */
4492 if (!non_stop)
4493 {
4494 thread = selected;
4495 if (thread == NULL)
4496 thread = lowest_stopped;
4497 if (thread == NULL)
4498 thread = first;
4499
4500 print_one_stopped_thread (thread);
4501 }
4502
4503 /* For "info program". */
4504 thread = inferior_thread ();
4505 if (thread->state == THREAD_STOPPED)
4506 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4507}
4508
048094ac
PA
4509/* Start the remote connection and sync state. */
4510
f6ac5f3d
PA
4511void
4512remote_target::start_remote (int from_tty, int extended_p)
c906108c 4513{
c8d104ad
PA
4514 struct remote_state *rs = get_remote_state ();
4515 struct packet_config *noack_config;
2d717e4f 4516 char *wait_status = NULL;
8621d6a9 4517
048094ac
PA
4518 /* Signal other parts that we're going through the initial setup,
4519 and so things may not be stable yet. E.g., we don't try to
4520 install tracepoints until we've relocated symbols. Also, a
4521 Ctrl-C before we're connected and synced up can't interrupt the
4522 target. Instead, it offers to drop the (potentially wedged)
4523 connection. */
4524 rs->starting_up = 1;
4525
522002f9 4526 QUIT;
c906108c 4527
9a7071a8
JB
4528 if (interrupt_on_connect)
4529 send_interrupt_sequence ();
4530
57e12211 4531 /* Ack any packet which the remote side has already sent. */
048094ac 4532 remote_serial_write ("+", 1);
1e51243a 4533
c8d104ad
PA
4534 /* The first packet we send to the target is the optional "supported
4535 packets" request. If the target can answer this, it will tell us
4536 which later probes to skip. */
4537 remote_query_supported ();
4538
d914c394 4539 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4540 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4541 set_permissions ();
d914c394 4542
57809e5e
JK
4543 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4544 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4545 as a reply to known packet. For packet "vFile:setfs:" it is an
4546 invalid reply and GDB would return error in
4547 remote_hostio_set_filesystem, making remote files access impossible.
4548 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4549 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4550 {
4551 const char v_mustreplyempty[] = "vMustReplyEmpty";
4552
4553 putpkt (v_mustreplyempty);
4554 getpkt (&rs->buf, &rs->buf_size, 0);
4555 if (strcmp (rs->buf, "OK") == 0)
4556 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4557 else if (strcmp (rs->buf, "") != 0)
4558 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4559 rs->buf);
4560 }
4561
c8d104ad
PA
4562 /* Next, we possibly activate noack mode.
4563
4564 If the QStartNoAckMode packet configuration is set to AUTO,
4565 enable noack mode if the stub reported a wish for it with
4566 qSupported.
4567
4568 If set to TRUE, then enable noack mode even if the stub didn't
4569 report it in qSupported. If the stub doesn't reply OK, the
4570 session ends with an error.
4571
4572 If FALSE, then don't activate noack mode, regardless of what the
4573 stub claimed should be the default with qSupported. */
4574
4575 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4576 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4577 {
4578 putpkt ("QStartNoAckMode");
4579 getpkt (&rs->buf, &rs->buf_size, 0);
4580 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4581 rs->noack_mode = 1;
4582 }
4583
04bd08de 4584 if (extended_p)
5fe04517
PA
4585 {
4586 /* Tell the remote that we are using the extended protocol. */
4587 putpkt ("!");
4588 getpkt (&rs->buf, &rs->buf_size, 0);
4589 }
4590
9b224c5e
PA
4591 /* Let the target know which signals it is allowed to pass down to
4592 the program. */
4593 update_signals_program_target ();
4594
d962ef82
DJ
4595 /* Next, if the target can specify a description, read it. We do
4596 this before anything involving memory or registers. */
4597 target_find_description ();
4598
6c95b8df
PA
4599 /* Next, now that we know something about the target, update the
4600 address spaces in the program spaces. */
4601 update_address_spaces ();
4602
50c71eaf
PA
4603 /* On OSs where the list of libraries is global to all
4604 processes, we fetch them early. */
f5656ead 4605 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4606 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4607
6efcd9a8 4608 if (target_is_non_stop_p ())
74531fed 4609 {
4082afcc 4610 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4611 error (_("Non-stop mode requested, but remote "
4612 "does not support non-stop"));
74531fed
PA
4613
4614 putpkt ("QNonStop:1");
4615 getpkt (&rs->buf, &rs->buf_size, 0);
4616
4617 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4618 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4619
4620 /* Find about threads and processes the stub is already
4621 controlling. We default to adding them in the running state.
4622 The '?' query below will then tell us about which threads are
4623 stopped. */
f6ac5f3d 4624 this->update_thread_list ();
74531fed 4625 }
4082afcc 4626 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4627 {
4628 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4629 Request it explicitly. */
74531fed
PA
4630 putpkt ("QNonStop:0");
4631 getpkt (&rs->buf, &rs->buf_size, 0);
4632
4633 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4634 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4635 }
4636
a0743c90
YQ
4637 /* Upload TSVs regardless of whether the target is running or not. The
4638 remote stub, such as GDBserver, may have some predefined or builtin
4639 TSVs, even if the target is not running. */
f6ac5f3d 4640 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4641 {
4642 struct uploaded_tsv *uploaded_tsvs = NULL;
4643
f6ac5f3d 4644 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4645 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4646 }
4647
2d717e4f
DJ
4648 /* Check whether the target is running now. */
4649 putpkt ("?");
4650 getpkt (&rs->buf, &rs->buf_size, 0);
4651
6efcd9a8 4652 if (!target_is_non_stop_p ())
2d717e4f 4653 {
74531fed 4654 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4655 {
04bd08de 4656 if (!extended_p)
74531fed 4657 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4658
4659 /* We're connected, but not running. Drop out before we
4660 call start_remote. */
e278ad5b 4661 rs->starting_up = 0;
c35b1492 4662 return;
2d717e4f
DJ
4663 }
4664 else
74531fed 4665 {
74531fed 4666 /* Save the reply for later. */
224c3ddb 4667 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4668 strcpy (wait_status, rs->buf);
4669 }
4670
b7ea362b 4671 /* Fetch thread list. */
e8032dde 4672 target_update_thread_list ();
b7ea362b 4673
74531fed
PA
4674 /* Let the stub know that we want it to return the thread. */
4675 set_continue_thread (minus_one_ptid);
4676
b7ea362b
PA
4677 if (thread_count () == 0)
4678 {
4679 /* Target has no concept of threads at all. GDB treats
4680 non-threaded target as single-threaded; add a main
4681 thread. */
4682 add_current_inferior_and_thread (wait_status);
4683 }
4684 else
4685 {
4686 /* We have thread information; select the thread the target
4687 says should be current. If we're reconnecting to a
4688 multi-threaded program, this will ideally be the thread
4689 that last reported an event before GDB disconnected. */
4690 inferior_ptid = get_current_thread (wait_status);
4691 if (ptid_equal (inferior_ptid, null_ptid))
4692 {
4693 /* Odd... The target was able to list threads, but not
4694 tell us which thread was current (no "thread"
4695 register in T stop reply?). Just pick the first
4696 thread in the thread list then. */
c9f35b34
KB
4697
4698 if (remote_debug)
4699 fprintf_unfiltered (gdb_stdlog,
4700 "warning: couldn't determine remote "
4701 "current thread; picking first in list.\n");
4702
b7ea362b
PA
4703 inferior_ptid = thread_list->ptid;
4704 }
4705 }
74531fed 4706
6e586cc5
YQ
4707 /* init_wait_for_inferior should be called before get_offsets in order
4708 to manage `inserted' flag in bp loc in a correct state.
4709 breakpoint_init_inferior, called from init_wait_for_inferior, set
4710 `inserted' flag to 0, while before breakpoint_re_set, called from
4711 start_remote, set `inserted' flag to 1. In the initialization of
4712 inferior, breakpoint_init_inferior should be called first, and then
4713 breakpoint_re_set can be called. If this order is broken, state of
4714 `inserted' flag is wrong, and cause some problems on breakpoint
4715 manipulation. */
4716 init_wait_for_inferior ();
4717
74531fed
PA
4718 get_offsets (); /* Get text, data & bss offsets. */
4719
d962ef82
DJ
4720 /* If we could not find a description using qXfer, and we know
4721 how to do it some other way, try again. This is not
4722 supported for non-stop; it could be, but it is tricky if
4723 there are no stopped threads when we connect. */
f6ac5f3d 4724 if (remote_read_description_p (this)
f5656ead 4725 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4726 {
4727 target_clear_description ();
4728 target_find_description ();
4729 }
4730
74531fed
PA
4731 /* Use the previously fetched status. */
4732 gdb_assert (wait_status != NULL);
4733 strcpy (rs->buf, wait_status);
4734 rs->cached_wait_status = 1;
4735
f6ac5f3d 4736 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4737 }
4738 else
4739 {
68c97600
PA
4740 /* Clear WFI global state. Do this before finding about new
4741 threads and inferiors, and setting the current inferior.
4742 Otherwise we would clear the proceed status of the current
4743 inferior when we want its stop_soon state to be preserved
4744 (see notice_new_inferior). */
4745 init_wait_for_inferior ();
4746
74531fed
PA
4747 /* In non-stop, we will either get an "OK", meaning that there
4748 are no stopped threads at this time; or, a regular stop
4749 reply. In the latter case, there may be more than one thread
4750 stopped --- we pull them all out using the vStopped
4751 mechanism. */
4752 if (strcmp (rs->buf, "OK") != 0)
4753 {
722247f1 4754 struct notif_client *notif = &notif_client_stop;
2d717e4f 4755
722247f1
YQ
4756 /* remote_notif_get_pending_replies acks this one, and gets
4757 the rest out. */
f48ff2a7 4758 rs->notif_state->pending_event[notif_client_stop.id]
6b8edb51 4759 = remote_notif_parse (this, notif, rs->buf);
722247f1 4760 remote_notif_get_pending_events (notif);
74531fed 4761 }
2d717e4f 4762
74531fed
PA
4763 if (thread_count () == 0)
4764 {
04bd08de 4765 if (!extended_p)
74531fed 4766 error (_("The target is not running (try extended-remote?)"));
82f73884 4767
c35b1492
PA
4768 /* We're connected, but not running. Drop out before we
4769 call start_remote. */
e278ad5b 4770 rs->starting_up = 0;
c35b1492
PA
4771 return;
4772 }
74531fed 4773
74531fed
PA
4774 /* In non-stop mode, any cached wait status will be stored in
4775 the stop reply queue. */
4776 gdb_assert (wait_status == NULL);
f0223081 4777
2455069d 4778 /* Report all signals during attach/startup. */
f6ac5f3d 4779 pass_signals (0, NULL);
221e1a37
PA
4780
4781 /* If there are already stopped threads, mark them stopped and
4782 report their stops before giving the prompt to the user. */
6efcd9a8 4783 process_initial_stop_replies (from_tty);
221e1a37
PA
4784
4785 if (target_can_async_p ())
4786 target_async (1);
74531fed 4787 }
c8d104ad 4788
c8d104ad
PA
4789 /* If we connected to a live target, do some additional setup. */
4790 if (target_has_execution)
4791 {
f4ccffad 4792 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4793 remote_check_symbols ();
c8d104ad 4794 }
50c71eaf 4795
d5551862
SS
4796 /* Possibly the target has been engaged in a trace run started
4797 previously; find out where things are at. */
f6ac5f3d 4798 if (get_trace_status (current_trace_status ()) != -1)
d5551862 4799 {
00bf0b85 4800 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4801
00bf0b85
SS
4802 if (current_trace_status ()->running)
4803 printf_filtered (_("Trace is already running on the target.\n"));
4804
f6ac5f3d 4805 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
4806
4807 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4808 }
4809
c0272db5
TW
4810 /* Possibly the target has been engaged in a btrace record started
4811 previously; find out where things are at. */
4812 remote_btrace_maybe_reopen ();
4813
1e51243a
PA
4814 /* The thread and inferior lists are now synchronized with the
4815 target, our symbols have been relocated, and we're merged the
4816 target's tracepoints with ours. We're done with basic start
4817 up. */
4818 rs->starting_up = 0;
4819
a25a5a45
PA
4820 /* Maybe breakpoints are global and need to be inserted now. */
4821 if (breakpoints_should_be_inserted_now ())
50c71eaf 4822 insert_breakpoints ();
c906108c
SS
4823}
4824
4825/* Open a connection to a remote debugger.
4826 NAME is the filename used for communication. */
4827
f6ac5f3d
PA
4828void
4829remote_target::open (const char *name, int from_tty)
c906108c 4830{
f6ac5f3d 4831 open_1 (name, from_tty, 0);
43ff13b4
JM
4832}
4833
c906108c
SS
4834/* Open a connection to a remote debugger using the extended
4835 remote gdb protocol. NAME is the filename used for communication. */
4836
f6ac5f3d
PA
4837void
4838extended_remote_target::open (const char *name, int from_tty)
c906108c 4839{
f6ac5f3d 4840 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
4841}
4842
ca4f7f8b
PA
4843/* Reset all packets back to "unknown support". Called when opening a
4844 new connection to a remote target. */
c906108c 4845
d471ea57 4846static void
ca4f7f8b 4847reset_all_packet_configs_support (void)
d471ea57
AC
4848{
4849 int i;
a744cf53 4850
444abaca 4851 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4852 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4853}
4854
ca4f7f8b
PA
4855/* Initialize all packet configs. */
4856
4857static void
4858init_all_packet_configs (void)
4859{
4860 int i;
4861
4862 for (i = 0; i < PACKET_MAX; i++)
4863 {
4864 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4865 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4866 }
4867}
4868
23860348 4869/* Symbol look-up. */
dc8acb97 4870
6b8edb51
PA
4871void
4872remote_target::remote_check_symbols ()
dc8acb97
MS
4873{
4874 char *msg, *reply, *tmp;
dc8acb97 4875 int end;
28170b88 4876 long reply_size;
a5c0808e 4877 struct cleanup *old_chain;
dc8acb97 4878
63154eca
PA
4879 /* The remote side has no concept of inferiors that aren't running
4880 yet, it only knows about running processes. If we're connected
4881 but our current inferior is not running, we should not invite the
4882 remote target to request symbol lookups related to its
4883 (unrelated) current process. */
4884 if (!target_has_execution)
4885 return;
4886
4082afcc 4887 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4888 return;
4889
63154eca
PA
4890 /* Make sure the remote is pointing at the right process. Note
4891 there's no way to select "no process". */
3c9c4b83
PA
4892 set_general_process ();
4893
6d820c5c
DJ
4894 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4895 because we need both at the same time. */
224c3ddb 4896 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4897 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4898 reply = (char *) xmalloc (get_remote_packet_size ());
4899 make_cleanup (free_current_contents, &reply);
4900 reply_size = get_remote_packet_size ();
6d820c5c 4901
23860348 4902 /* Invite target to request symbol lookups. */
dc8acb97
MS
4903
4904 putpkt ("qSymbol::");
28170b88
MK
4905 getpkt (&reply, &reply_size, 0);
4906 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4907
61012eef 4908 while (startswith (reply, "qSymbol:"))
dc8acb97 4909 {
77e371c0
TT
4910 struct bound_minimal_symbol sym;
4911
dc8acb97 4912 tmp = &reply[8];
cfd77fa1 4913 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4914 msg[end] = '\0';
4915 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4916 if (sym.minsym == NULL)
ea9c271d 4917 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4918 else
2bbe3cc1 4919 {
f5656ead 4920 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4921 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4922
4923 /* If this is a function address, return the start of code
4924 instead of any data function descriptor. */
f5656ead 4925 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1 4926 sym_addr,
f6ac5f3d 4927 target_stack);
2bbe3cc1
DJ
4928
4929 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4930 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4931 }
4932
dc8acb97 4933 putpkt (msg);
28170b88 4934 getpkt (&reply, &reply_size, 0);
dc8acb97 4935 }
a5c0808e
PA
4936
4937 do_cleanups (old_chain);
dc8acb97
MS
4938}
4939
9db8d71f 4940static struct serial *
baa336ce 4941remote_serial_open (const char *name)
9db8d71f
DJ
4942{
4943 static int udp_warning = 0;
4944
4945 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4946 of in ser-tcp.c, because it is the remote protocol assuming that the
4947 serial connection is reliable and not the serial connection promising
4948 to be. */
61012eef 4949 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4950 {
3e43a32a
MS
4951 warning (_("The remote protocol may be unreliable over UDP.\n"
4952 "Some events may be lost, rendering further debugging "
4953 "impossible."));
9db8d71f
DJ
4954 udp_warning = 1;
4955 }
4956
4957 return serial_open (name);
4958}
4959
d914c394
SS
4960/* Inform the target of our permission settings. The permission flags
4961 work without this, but if the target knows the settings, it can do
4962 a couple things. First, it can add its own check, to catch cases
4963 that somehow manage to get by the permissions checks in target
4964 methods. Second, if the target is wired to disallow particular
4965 settings (for instance, a system in the field that is not set up to
4966 be able to stop at a breakpoint), it can object to any unavailable
4967 permissions. */
4968
4969void
f6ac5f3d 4970remote_target::set_permissions ()
d914c394
SS
4971{
4972 struct remote_state *rs = get_remote_state ();
4973
bba74b36
YQ
4974 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4975 "WriteReg:%x;WriteMem:%x;"
4976 "InsertBreak:%x;InsertTrace:%x;"
4977 "InsertFastTrace:%x;Stop:%x",
4978 may_write_registers, may_write_memory,
4979 may_insert_breakpoints, may_insert_tracepoints,
4980 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4981 putpkt (rs->buf);
4982 getpkt (&rs->buf, &rs->buf_size, 0);
4983
4984 /* If the target didn't like the packet, warn the user. Do not try
4985 to undo the user's settings, that would just be maddening. */
4986 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4987 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4988}
4989
be2a5f71
DJ
4990/* This type describes each known response to the qSupported
4991 packet. */
4992struct protocol_feature
4993{
4994 /* The name of this protocol feature. */
4995 const char *name;
4996
4997 /* The default for this protocol feature. */
4998 enum packet_support default_support;
4999
5000 /* The function to call when this feature is reported, or after
5001 qSupported processing if the feature is not supported.
5002 The first argument points to this structure. The second
5003 argument indicates whether the packet requested support be
5004 enabled, disabled, or probed (or the default, if this function
5005 is being called at the end of processing and this feature was
5006 not reported). The third argument may be NULL; if not NULL, it
5007 is a NUL-terminated string taken from the packet following
5008 this feature's name and an equals sign. */
6b8edb51
PA
5009 void (*func) (remote_target *remote, const struct protocol_feature *,
5010 enum packet_support, const char *);
be2a5f71
DJ
5011
5012 /* The corresponding packet for this feature. Only used if
5013 FUNC is remote_supported_packet. */
5014 int packet;
5015};
5016
be2a5f71 5017static void
6b8edb51
PA
5018remote_supported_packet (remote_target *remote,
5019 const struct protocol_feature *feature,
be2a5f71
DJ
5020 enum packet_support support,
5021 const char *argument)
5022{
5023 if (argument)
5024 {
5025 warning (_("Remote qSupported response supplied an unexpected value for"
5026 " \"%s\"."), feature->name);
5027 return;
5028 }
5029
4082afcc 5030 remote_protocol_packets[feature->packet].support = support;
be2a5f71 5031}
be2a5f71 5032
6b8edb51
PA
5033void
5034remote_target::remote_packet_size (const protocol_feature *feature,
5035 enum packet_support support, const char *value)
be2a5f71
DJ
5036{
5037 struct remote_state *rs = get_remote_state ();
5038
5039 int packet_size;
5040 char *value_end;
5041
5042 if (support != PACKET_ENABLE)
5043 return;
5044
5045 if (value == NULL || *value == '\0')
5046 {
5047 warning (_("Remote target reported \"%s\" without a size."),
5048 feature->name);
5049 return;
5050 }
5051
5052 errno = 0;
5053 packet_size = strtol (value, &value_end, 16);
5054 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5055 {
5056 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5057 feature->name, value);
5058 return;
5059 }
5060
be2a5f71
DJ
5061 /* Record the new maximum packet size. */
5062 rs->explicit_packet_size = packet_size;
5063}
5064
6b8edb51
PA
5065void
5066remote_packet_size (remote_target *remote, const protocol_feature *feature,
5067 enum packet_support support, const char *value)
5068{
5069 remote->remote_packet_size (feature, support, value);
5070}
5071
dc473cfb 5072static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5073 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5074 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5075 PACKET_qXfer_auxv },
c78fa86a
GB
5076 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5077 PACKET_qXfer_exec_file },
23181151
DJ
5078 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5079 PACKET_qXfer_features },
cfa9d6d9
DJ
5080 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5081 PACKET_qXfer_libraries },
2268b414
JK
5082 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5083 PACKET_qXfer_libraries_svr4 },
ced63ec0 5084 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5085 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5086 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5087 PACKET_qXfer_memory_map },
4de6483e
UW
5088 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5089 PACKET_qXfer_spu_read },
5090 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5091 PACKET_qXfer_spu_write },
07e059b5
VP
5092 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5093 PACKET_qXfer_osdata },
dc146f7c
VP
5094 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5095 PACKET_qXfer_threads },
b3b9301e
PA
5096 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5097 PACKET_qXfer_traceframe_info },
89be2091
DJ
5098 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5099 PACKET_QPassSignals },
82075af2
JS
5100 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5101 PACKET_QCatchSyscalls },
9b224c5e
PA
5102 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5103 PACKET_QProgramSignals },
bc3b087d
SDJ
5104 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5105 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5106 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5107 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5108 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5109 PACKET_QEnvironmentHexEncoded },
5110 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5111 PACKET_QEnvironmentReset },
5112 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5113 PACKET_QEnvironmentUnset },
a6f3e723
SL
5114 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5115 PACKET_QStartNoAckMode },
4082afcc
PA
5116 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5117 PACKET_multiprocess_feature },
5118 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5119 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5120 PACKET_qXfer_siginfo_read },
5121 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5122 PACKET_qXfer_siginfo_write },
4082afcc 5123 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5124 PACKET_ConditionalTracepoints },
4082afcc 5125 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5126 PACKET_ConditionalBreakpoints },
4082afcc 5127 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5128 PACKET_BreakpointCommands },
4082afcc 5129 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5130 PACKET_FastTracepoints },
4082afcc 5131 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5132 PACKET_StaticTracepoints },
4082afcc 5133 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5134 PACKET_InstallInTrace},
4082afcc
PA
5135 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5136 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5137 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5138 PACKET_bc },
5139 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5140 PACKET_bs },
409873ef
SS
5141 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5142 PACKET_TracepointSource },
d914c394
SS
5143 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5144 PACKET_QAllow },
4082afcc
PA
5145 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5146 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5147 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5148 PACKET_qXfer_fdpic },
169081d0
TG
5149 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5150 PACKET_qXfer_uib },
03583c20
UW
5151 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5152 PACKET_QDisableRandomization },
d1feda86 5153 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5154 { "QTBuffer:size", PACKET_DISABLE,
5155 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5156 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5157 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5158 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5159 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5160 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5161 PACKET_qXfer_btrace },
5162 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5163 PACKET_qXfer_btrace_conf },
5164 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5165 PACKET_Qbtrace_conf_bts_size },
5166 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5167 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5168 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5169 PACKET_fork_event_feature },
5170 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5171 PACKET_vfork_event_feature },
94585166
DB
5172 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5173 PACKET_exec_event_feature },
b20a6524 5174 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5175 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5176 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5177 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5178 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
5179};
5180
c8d5aac9
L
5181static char *remote_support_xml;
5182
5183/* Register string appended to "xmlRegisters=" in qSupported query. */
5184
5185void
6e39997a 5186register_remote_support_xml (const char *xml)
c8d5aac9
L
5187{
5188#if defined(HAVE_LIBEXPAT)
5189 if (remote_support_xml == NULL)
c4f7c687 5190 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5191 else
5192 {
5193 char *copy = xstrdup (remote_support_xml + 13);
5194 char *p = strtok (copy, ",");
5195
5196 do
5197 {
5198 if (strcmp (p, xml) == 0)
5199 {
5200 /* already there */
5201 xfree (copy);
5202 return;
5203 }
5204 }
5205 while ((p = strtok (NULL, ",")) != NULL);
5206 xfree (copy);
5207
94b0dee1
PA
5208 remote_support_xml = reconcat (remote_support_xml,
5209 remote_support_xml, ",", xml,
5210 (char *) NULL);
c8d5aac9
L
5211 }
5212#endif
5213}
5214
69b6ecb0
TT
5215static void
5216remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5217{
69b6ecb0
TT
5218 if (!msg->empty ())
5219 msg->append (";");
5220 msg->append (append);
c8d5aac9
L
5221}
5222
6b8edb51
PA
5223void
5224remote_target::remote_query_supported ()
be2a5f71
DJ
5225{
5226 struct remote_state *rs = get_remote_state ();
5227 char *next;
5228 int i;
5229 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5230
5231 /* The packet support flags are handled differently for this packet
5232 than for most others. We treat an error, a disabled packet, and
5233 an empty response identically: any features which must be reported
5234 to be used will be automatically disabled. An empty buffer
5235 accomplishes this, since that is also the representation for a list
5236 containing no features. */
5237
5238 rs->buf[0] = 0;
4082afcc 5239 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5240 {
69b6ecb0 5241 std::string q;
c8d5aac9 5242
73b8c1fd 5243 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5244 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5245
f7e6eed5 5246 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5247 remote_query_supported_append (&q, "swbreak+");
f7e6eed5 5248 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5249 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5250
69b6ecb0 5251 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5252
8020350c
DB
5253 if (packet_set_cmd_state (PACKET_fork_event_feature)
5254 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5255 remote_query_supported_append (&q, "fork-events+");
8020350c
DB
5256 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5257 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5258 remote_query_supported_append (&q, "vfork-events+");
8020350c
DB
5259 if (packet_set_cmd_state (PACKET_exec_event_feature)
5260 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5261 remote_query_supported_append (&q, "exec-events+");
89245bc0 5262
750ce8d1 5263 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5264 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5265
65706a29 5266 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5267 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5268
f2faf941 5269 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5270 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5271
b35d5edb
PA
5272 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5273 the qSupported:xmlRegisters=i386 handling. */
7cc244de
PA
5274 if (remote_support_xml != NULL
5275 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
69b6ecb0 5276 remote_query_supported_append (&q, remote_support_xml);
82f73884 5277
69b6ecb0
TT
5278 q = "qSupported:" + q;
5279 putpkt (q.c_str ());
94b0dee1 5280
be2a5f71
DJ
5281 getpkt (&rs->buf, &rs->buf_size, 0);
5282
5283 /* If an error occured, warn, but do not return - just reset the
5284 buffer to empty and go on to disable features. */
5285 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5286 == PACKET_ERROR)
5287 {
5288 warning (_("Remote failure reply: %s"), rs->buf);
5289 rs->buf[0] = 0;
5290 }
5291 }
5292
5293 memset (seen, 0, sizeof (seen));
5294
5295 next = rs->buf;
5296 while (*next)
5297 {
5298 enum packet_support is_supported;
5299 char *p, *end, *name_end, *value;
5300
5301 /* First separate out this item from the rest of the packet. If
5302 there's another item after this, we overwrite the separator
5303 (terminated strings are much easier to work with). */
5304 p = next;
5305 end = strchr (p, ';');
5306 if (end == NULL)
5307 {
5308 end = p + strlen (p);
5309 next = end;
5310 }
5311 else
5312 {
89be2091
DJ
5313 *end = '\0';
5314 next = end + 1;
5315
be2a5f71
DJ
5316 if (end == p)
5317 {
5318 warning (_("empty item in \"qSupported\" response"));
5319 continue;
5320 }
be2a5f71
DJ
5321 }
5322
5323 name_end = strchr (p, '=');
5324 if (name_end)
5325 {
5326 /* This is a name=value entry. */
5327 is_supported = PACKET_ENABLE;
5328 value = name_end + 1;
5329 *name_end = '\0';
5330 }
5331 else
5332 {
5333 value = NULL;
5334 switch (end[-1])
5335 {
5336 case '+':
5337 is_supported = PACKET_ENABLE;
5338 break;
5339
5340 case '-':
5341 is_supported = PACKET_DISABLE;
5342 break;
5343
5344 case '?':
5345 is_supported = PACKET_SUPPORT_UNKNOWN;
5346 break;
5347
5348 default:
3e43a32a
MS
5349 warning (_("unrecognized item \"%s\" "
5350 "in \"qSupported\" response"), p);
be2a5f71
DJ
5351 continue;
5352 }
5353 end[-1] = '\0';
5354 }
5355
5356 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5357 if (strcmp (remote_protocol_features[i].name, p) == 0)
5358 {
5359 const struct protocol_feature *feature;
5360
5361 seen[i] = 1;
5362 feature = &remote_protocol_features[i];
6b8edb51 5363 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5364 break;
5365 }
5366 }
5367
5368 /* If we increased the packet size, make sure to increase the global
5369 buffer size also. We delay this until after parsing the entire
5370 qSupported packet, because this is the same buffer we were
5371 parsing. */
5372 if (rs->buf_size < rs->explicit_packet_size)
5373 {
5374 rs->buf_size = rs->explicit_packet_size;
224c3ddb 5375 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
5376 }
5377
5378 /* Handle the defaults for unmentioned features. */
5379 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5380 if (!seen[i])
5381 {
5382 const struct protocol_feature *feature;
5383
5384 feature = &remote_protocol_features[i];
6b8edb51 5385 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5386 }
5387}
5388
048094ac
PA
5389/* Serial QUIT handler for the remote serial descriptor.
5390
5391 Defers handling a Ctrl-C until we're done with the current
5392 command/response packet sequence, unless:
5393
5394 - We're setting up the connection. Don't send a remote interrupt
5395 request, as we're not fully synced yet. Quit immediately
5396 instead.
5397
5398 - The target has been resumed in the foreground
223ffa71 5399 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5400 packet, and we're blocked waiting for the stop reply, thus a
5401 Ctrl-C should be immediately sent to the target.
5402
5403 - We get a second Ctrl-C while still within the same serial read or
5404 write. In that case the serial is seemingly wedged --- offer to
5405 quit/disconnect.
5406
5407 - We see a second Ctrl-C without target response, after having
5408 previously interrupted the target. In that case the target/stub
5409 is probably wedged --- offer to quit/disconnect.
5410*/
5411
6b8edb51
PA
5412void
5413remote_target::remote_serial_quit_handler ()
048094ac
PA
5414{
5415 struct remote_state *rs = get_remote_state ();
5416
5417 if (check_quit_flag ())
5418 {
5419 /* If we're starting up, we're not fully synced yet. Quit
5420 immediately. */
5421 if (rs->starting_up)
5422 quit ();
5423 else if (rs->got_ctrlc_during_io)
5424 {
5425 if (query (_("The target is not responding to GDB commands.\n"
5426 "Stop debugging it? ")))
5427 remote_unpush_and_throw ();
5428 }
5429 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5430 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5431 interrupt_query ();
5432 /* All-stop protocol, and blocked waiting for stop reply. Send
5433 an interrupt request. */
223ffa71 5434 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5435 target_interrupt ();
048094ac
PA
5436 else
5437 rs->got_ctrlc_during_io = 1;
5438 }
5439}
5440
6b8edb51
PA
5441/* The remote_target that is current while the quit handler is
5442 overridden with remote_serial_quit_handler. */
5443static remote_target *curr_quit_handler_target;
5444
5445static void
5446remote_serial_quit_handler ()
5447{
5448 curr_quit_handler_target->remote_serial_quit_handler ();
5449}
5450
78a095c3
JK
5451/* Remove any of the remote.c targets from target stack. Upper targets depend
5452 on it so remove them first. */
5453
5454static void
5455remote_unpush_target (void)
5456{
915ef8b1 5457 pop_all_targets_at_and_above (process_stratum);
78a095c3 5458}
be2a5f71 5459
048094ac
PA
5460static void
5461remote_unpush_and_throw (void)
5462{
5463 remote_unpush_target ();
5464 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5465}
5466
f6ac5f3d
PA
5467void
5468remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5469{
6b8edb51 5470 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5471
c906108c 5472 if (name == 0)
8a3fe4f8 5473 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5474 "serial device is attached to the remote system\n"
8a3fe4f8 5475 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5476
2d717e4f 5477 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5478 Ask this question first, before target_preopen has a chance to kill
5479 anything. */
6b8edb51 5480 if (curr_remote != NULL && !have_inferiors ())
2d717e4f 5481 {
78a095c3
JK
5482 if (from_tty
5483 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5484 error (_("Still connected."));
5485 }
5486
78a095c3 5487 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5488 target_preopen (from_tty);
5489
ad9a8f3f 5490 remote_fileio_reset ();
1dd41f16
NS
5491 reopen_exec_file ();
5492 reread_symbols ();
5493
6b8edb51
PA
5494 remote_target *remote
5495 = (extended_p ? new extended_remote_target () : new remote_target ());
5496 target_ops_up target_holder (remote);
5497
5498 remote_state *rs = remote->get_remote_state ();
5499
5500 /* See FIXME above. */
5501 if (!target_async_permitted)
5502 rs->wait_forever_enabled_p = 1;
5503
5d93a237
TT
5504 rs->remote_desc = remote_serial_open (name);
5505 if (!rs->remote_desc)
c906108c
SS
5506 perror_with_name (name);
5507
5508 if (baud_rate != -1)
5509 {
5d93a237 5510 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5511 {
9b74d5d3
KB
5512 /* The requested speed could not be set. Error out to
5513 top level after closing remote_desc. Take care to
5514 set remote_desc to NULL to avoid closing remote_desc
5515 more than once. */
5d93a237
TT
5516 serial_close (rs->remote_desc);
5517 rs->remote_desc = NULL;
c906108c
SS
5518 perror_with_name (name);
5519 }
5520 }
5521
236af5e3 5522 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5523 serial_raw (rs->remote_desc);
c906108c
SS
5524
5525 /* If there is something sitting in the buffer we might take it as a
5526 response to a command, which would be bad. */
5d93a237 5527 serial_flush_input (rs->remote_desc);
c906108c
SS
5528
5529 if (from_tty)
5530 {
5531 puts_filtered ("Remote debugging using ");
5532 puts_filtered (name);
5533 puts_filtered ("\n");
5534 }
d9f719f1 5535
6b8edb51
PA
5536 /* Switch to using the remote target now. */
5537 push_target (remote);
5538 /* The target stack owns the target now. */
5539 target_holder.release ();
c906108c 5540
74531fed 5541 /* Register extra event sources in the event loop. */
6b8edb51 5542 rs->remote_async_inferior_event_token
74531fed 5543 = create_async_event_handler (remote_async_inferior_event_handler,
6b8edb51
PA
5544 remote);
5545 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 5546
be2a5f71
DJ
5547 /* Reset the target state; these things will be queried either by
5548 remote_query_supported or as they are needed. */
ca4f7f8b 5549 reset_all_packet_configs_support ();
74531fed 5550 rs->cached_wait_status = 0;
be2a5f71 5551 rs->explicit_packet_size = 0;
a6f3e723 5552 rs->noack_mode = 0;
82f73884 5553 rs->extended = extended_p;
e24a49d8 5554 rs->waiting_for_stop_reply = 0;
3a29589a 5555 rs->ctrlc_pending_p = 0;
048094ac 5556 rs->got_ctrlc_during_io = 0;
802188a7 5557
47f8a51d
TT
5558 rs->general_thread = not_sent_ptid;
5559 rs->continue_thread = not_sent_ptid;
262e1174 5560 rs->remote_traceframe_number = -1;
c906108c 5561
3a00c802
PA
5562 rs->last_resume_exec_dir = EXEC_FORWARD;
5563
9d1f7ab2 5564 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5565 rs->use_threadinfo_query = 1;
5566 rs->use_threadextra_query = 1;
9d1f7ab2 5567
dd194f6b 5568 rs->readahead_cache.invalidate ();
80152258 5569
c6ebd6cf 5570 if (target_async_permitted)
92d1e331 5571 {
92d1e331
DJ
5572 /* FIXME: cagney/1999-09-23: During the initial connection it is
5573 assumed that the target is already ready and able to respond to
0df8b418 5574 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5575 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5576 around this. Eventually a mechanism that allows
92d1e331 5577 wait_for_inferior() to expect/get timeouts will be
23860348 5578 implemented. */
6b8edb51 5579 rs->wait_forever_enabled_p = 0;
92d1e331
DJ
5580 }
5581
23860348 5582 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5583 no_shared_libraries (NULL, 0);
f78f6cf1 5584
74531fed
PA
5585 /* Start afresh. */
5586 init_thread_list ();
5587
36918e70 5588 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5589 target (we'd otherwise be in an inconsistent state) and then
5590 propogate the error on up the exception chain. This ensures that
5591 the caller doesn't stumble along blindly assuming that the
5592 function succeeded. The CLI doesn't have this problem but other
5593 UI's, such as MI do.
36918e70
AC
5594
5595 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5596 this function should return an error indication letting the
ce2826aa 5597 caller restore the previous state. Unfortunately the command
36918e70
AC
5598 ``target remote'' is directly wired to this function making that
5599 impossible. On a positive note, the CLI side of this problem has
5600 been fixed - the function set_cmd_context() makes it possible for
5601 all the ``target ....'' commands to share a common callback
5602 function. See cli-dump.c. */
109c3e39 5603 {
2d717e4f 5604
492d29ea 5605 TRY
04bd08de 5606 {
6b8edb51 5607 remote->start_remote (from_tty, extended_p);
04bd08de 5608 }
492d29ea 5609 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5610 {
c8d104ad
PA
5611 /* Pop the partially set up target - unless something else did
5612 already before throwing the exception. */
6b8edb51 5613 if (ex.error != TARGET_CLOSE_ERROR)
78a095c3 5614 remote_unpush_target ();
109c3e39
AC
5615 throw_exception (ex);
5616 }
492d29ea 5617 END_CATCH
109c3e39 5618 }
c906108c 5619
6b8edb51 5620 remote_btrace_reset (rs);
f4abbc16 5621
c6ebd6cf 5622 if (target_async_permitted)
6b8edb51 5623 rs->wait_forever_enabled_p = 1;
43ff13b4
JM
5624}
5625
de0d863e
DB
5626/* Detach the specified process. */
5627
6b8edb51
PA
5628void
5629remote_target::remote_detach_pid (int pid)
de0d863e
DB
5630{
5631 struct remote_state *rs = get_remote_state ();
5632
5633 if (remote_multi_process_p (rs))
5634 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5635 else
5636 strcpy (rs->buf, "D");
5637
5638 putpkt (rs->buf);
5639 getpkt (&rs->buf, &rs->buf_size, 0);
5640
5641 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5642 ;
5643 else if (rs->buf[0] == '\0')
5644 error (_("Remote doesn't know how to detach"));
5645 else
5646 error (_("Can't detach process."));
5647}
5648
5649/* This detaches a program to which we previously attached, using
5650 inferior_ptid to identify the process. After this is done, GDB
5651 can be used to debug some other program. We better not have left
5652 any breakpoints in the target program or it'll die when it hits
5653 one. */
c906108c 5654
6b8edb51
PA
5655void
5656remote_target::remote_detach_1 (int from_tty, inferior *inf)
c906108c 5657{
82f73884 5658 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5659 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5660 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5661 int is_fork_parent;
c906108c 5662
2d717e4f
DJ
5663 if (!target_has_execution)
5664 error (_("No process to detach from."));
5665
0f48b757 5666 target_announce_detach (from_tty);
7cee1e54 5667
c906108c 5668 /* Tell the remote target to detach. */
de0d863e 5669 remote_detach_pid (pid);
82f73884 5670
8020350c
DB
5671 /* Exit only if this is the only active inferior. */
5672 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5673 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5674
de0d863e
DB
5675 /* Check to see if we are detaching a fork parent. Note that if we
5676 are detaching a fork child, tp == NULL. */
5677 is_fork_parent = (tp != NULL
5678 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5679
5680 /* If doing detach-on-fork, we don't mourn, because that will delete
5681 breakpoints that should be available for the followed inferior. */
5682 if (!is_fork_parent)
f67c0c91 5683 {
249b5733
PA
5684 /* Save the pid as a string before mourning, since that will
5685 unpush the remote target, and we need the string after. */
5686 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
f67c0c91
SDJ
5687
5688 target_mourn_inferior (inferior_ptid);
5689 if (print_inferior_events)
5690 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5691 inf->num, infpid.c_str ());
5692 }
de0d863e
DB
5693 else
5694 {
5695 inferior_ptid = null_ptid;
5696 detach_inferior (pid);
5697 }
2d717e4f
DJ
5698}
5699
f6ac5f3d
PA
5700void
5701remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5702{
6e1e1966 5703 remote_detach_1 (from_tty, inf);
2d717e4f
DJ
5704}
5705
f6ac5f3d
PA
5706void
5707extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5708{
6e1e1966 5709 remote_detach_1 (from_tty, inf);
de0d863e
DB
5710}
5711
5712/* Target follow-fork function for remote targets. On entry, and
5713 at return, the current inferior is the fork parent.
5714
5715 Note that although this is currently only used for extended-remote,
5716 it is named remote_follow_fork in anticipation of using it for the
5717 remote target as well. */
5718
f6ac5f3d
PA
5719int
5720remote_target::follow_fork (int follow_child, int detach_fork)
de0d863e
DB
5721{
5722 struct remote_state *rs = get_remote_state ();
c269dbdb 5723 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5724
c269dbdb
DB
5725 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5726 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5727 {
5728 /* When following the parent and detaching the child, we detach
5729 the child here. For the case of following the child and
5730 detaching the parent, the detach is done in the target-
5731 independent follow fork code in infrun.c. We can't use
5732 target_detach when detaching an unfollowed child because
5733 the client side doesn't know anything about the child. */
5734 if (detach_fork && !follow_child)
5735 {
5736 /* Detach the fork child. */
5737 ptid_t child_ptid;
5738 pid_t child_pid;
5739
5740 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5741 child_pid = ptid_get_pid (child_ptid);
5742
5743 remote_detach_pid (child_pid);
de0d863e
DB
5744 }
5745 }
5746 return 0;
c906108c
SS
5747}
5748
94585166
DB
5749/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5750 in the program space of the new inferior. On entry and at return the
5751 current inferior is the exec'ing inferior. INF is the new exec'd
5752 inferior, which may be the same as the exec'ing inferior unless
5753 follow-exec-mode is "new". */
5754
f6ac5f3d
PA
5755void
5756remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
94585166
DB
5757{
5758 /* We know that this is a target file name, so if it has the "target:"
5759 prefix we strip it off before saving it in the program space. */
5760 if (is_target_filename (execd_pathname))
5761 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5762
5763 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5764}
5765
6ad8ae5c
DJ
5766/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5767
f6ac5f3d
PA
5768void
5769remote_target::disconnect (const char *args, int from_tty)
43ff13b4 5770{
43ff13b4 5771 if (args)
2d717e4f 5772 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5773
8020350c
DB
5774 /* Make sure we unpush even the extended remote targets. Calling
5775 target_mourn_inferior won't unpush, and remote_mourn won't
5776 unpush if there is more than one inferior left. */
f6ac5f3d 5777 unpush_target (this);
8020350c 5778 generic_mourn_inferior ();
2d717e4f 5779
43ff13b4
JM
5780 if (from_tty)
5781 puts_filtered ("Ending remote debugging.\n");
5782}
5783
2d717e4f
DJ
5784/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5785 be chatty about it. */
5786
f6ac5f3d
PA
5787void
5788extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
5789{
5790 struct remote_state *rs = get_remote_state ();
be86555c 5791 int pid;
96ef3384 5792 char *wait_status = NULL;
2d717e4f 5793
74164c56 5794 pid = parse_pid_to_attach (args);
2d717e4f 5795
74164c56
JK
5796 /* Remote PID can be freely equal to getpid, do not check it here the same
5797 way as in other targets. */
2d717e4f 5798
4082afcc 5799 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5800 error (_("This target does not support attaching to a process"));
5801
7cee1e54
PA
5802 if (from_tty)
5803 {
5804 char *exec_file = get_exec_file (0);
5805
5806 if (exec_file)
5807 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5808 target_pid_to_str (pid_to_ptid (pid)));
5809 else
5810 printf_unfiltered (_("Attaching to %s\n"),
5811 target_pid_to_str (pid_to_ptid (pid)));
5812
5813 gdb_flush (gdb_stdout);
5814 }
5815
bba74b36 5816 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5817 putpkt (rs->buf);
5818 getpkt (&rs->buf, &rs->buf_size, 0);
5819
4082afcc
PA
5820 switch (packet_ok (rs->buf,
5821 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5822 {
4082afcc 5823 case PACKET_OK:
6efcd9a8 5824 if (!target_is_non_stop_p ())
74531fed
PA
5825 {
5826 /* Save the reply for later. */
224c3ddb 5827 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5828 strcpy (wait_status, rs->buf);
5829 }
5830 else if (strcmp (rs->buf, "OK") != 0)
5831 error (_("Attaching to %s failed with: %s"),
5832 target_pid_to_str (pid_to_ptid (pid)),
5833 rs->buf);
4082afcc
PA
5834 break;
5835 case PACKET_UNKNOWN:
5836 error (_("This target does not support attaching to a process"));
5837 default:
5838 error (_("Attaching to %s failed"),
5839 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5840 }
2d717e4f 5841
1b6e6f5c 5842 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5843
2d717e4f 5844 inferior_ptid = pid_to_ptid (pid);
79d7f229 5845
6efcd9a8 5846 if (target_is_non_stop_p ())
bad34192
PA
5847 {
5848 struct thread_info *thread;
79d7f229 5849
bad34192 5850 /* Get list of threads. */
f6ac5f3d 5851 update_thread_list ();
82f73884 5852
bad34192
PA
5853 thread = first_thread_of_process (pid);
5854 if (thread)
5855 inferior_ptid = thread->ptid;
5856 else
5857 inferior_ptid = pid_to_ptid (pid);
5858
5859 /* Invalidate our notion of the remote current thread. */
47f8a51d 5860 record_currthread (rs, minus_one_ptid);
bad34192 5861 }
74531fed 5862 else
bad34192
PA
5863 {
5864 /* Now, if we have thread information, update inferior_ptid. */
5865 inferior_ptid = remote_current_thread (inferior_ptid);
5866
5867 /* Add the main thread to the thread list. */
00aecdcf
PA
5868 thread_info *thr = add_thread_silent (inferior_ptid);
5869 /* Don't consider the thread stopped until we've processed the
5870 saved stop reply. */
5871 set_executing (thr->ptid, true);
bad34192 5872 }
c0a2216e 5873
96ef3384
UW
5874 /* Next, if the target can specify a description, read it. We do
5875 this before anything involving memory or registers. */
5876 target_find_description ();
5877
6efcd9a8 5878 if (!target_is_non_stop_p ())
74531fed
PA
5879 {
5880 /* Use the previously fetched status. */
5881 gdb_assert (wait_status != NULL);
5882
5883 if (target_can_async_p ())
5884 {
722247f1 5885 struct notif_event *reply
6b8edb51 5886 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 5887
722247f1 5888 push_stop_reply ((struct stop_reply *) reply);
74531fed 5889
6a3753b3 5890 target_async (1);
74531fed
PA
5891 }
5892 else
5893 {
5894 gdb_assert (wait_status != NULL);
5895 strcpy (rs->buf, wait_status);
5896 rs->cached_wait_status = 1;
5897 }
5898 }
5899 else
5900 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5901}
5902
b9c1d481
AS
5903/* Implementation of the to_post_attach method. */
5904
f6ac5f3d
PA
5905void
5906extended_remote_target::post_attach (int pid)
b9c1d481 5907{
6efcd9a8
PA
5908 /* Get text, data & bss offsets. */
5909 get_offsets ();
5910
b9c1d481
AS
5911 /* In certain cases GDB might not have had the chance to start
5912 symbol lookup up until now. This could happen if the debugged
5913 binary is not using shared libraries, the vsyscall page is not
5914 present (on Linux) and the binary itself hadn't changed since the
5915 debugging process was started. */
5916 if (symfile_objfile != NULL)
5917 remote_check_symbols();
5918}
5919
c906108c 5920\f
506fb367
DJ
5921/* Check for the availability of vCont. This function should also check
5922 the response. */
c906108c 5923
6b8edb51
PA
5924void
5925remote_target::remote_vcont_probe ()
c906108c 5926{
6b8edb51 5927 remote_state *rs = get_remote_state ();
2e9f7625 5928 char *buf;
6d820c5c 5929
2e9f7625
DJ
5930 strcpy (rs->buf, "vCont?");
5931 putpkt (rs->buf);
6d820c5c 5932 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5933 buf = rs->buf;
c906108c 5934
506fb367 5935 /* Make sure that the features we assume are supported. */
61012eef 5936 if (startswith (buf, "vCont"))
506fb367
DJ
5937 {
5938 char *p = &buf[5];
750ce8d1 5939 int support_c, support_C;
506fb367 5940
750ce8d1
YQ
5941 rs->supports_vCont.s = 0;
5942 rs->supports_vCont.S = 0;
506fb367
DJ
5943 support_c = 0;
5944 support_C = 0;
d458bd84 5945 rs->supports_vCont.t = 0;
c1e36e3e 5946 rs->supports_vCont.r = 0;
506fb367
DJ
5947 while (p && *p == ';')
5948 {
5949 p++;
5950 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5951 rs->supports_vCont.s = 1;
506fb367 5952 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5953 rs->supports_vCont.S = 1;
506fb367
DJ
5954 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5955 support_c = 1;
5956 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5957 support_C = 1;
74531fed 5958 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5959 rs->supports_vCont.t = 1;
c1e36e3e
PA
5960 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5961 rs->supports_vCont.r = 1;
506fb367
DJ
5962
5963 p = strchr (p, ';');
5964 }
c906108c 5965
750ce8d1
YQ
5966 /* If c, and C are not all supported, we can't use vCont. Clearing
5967 BUF will make packet_ok disable the packet. */
5968 if (!support_c || !support_C)
506fb367
DJ
5969 buf[0] = 0;
5970 }
c906108c 5971
444abaca 5972 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5973}
c906108c 5974
0d8f58ca
PA
5975/* Helper function for building "vCont" resumptions. Write a
5976 resumption to P. ENDP points to one-passed-the-end of the buffer
5977 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5978 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5979 resumed thread should be single-stepped and/or signalled. If PTID
5980 equals minus_one_ptid, then all threads are resumed; if PTID
5981 represents a process, then all threads of the process are resumed;
5982 the thread to be stepped and/or signalled is given in the global
5983 INFERIOR_PTID. */
5984
6b8edb51
PA
5985char *
5986remote_target::append_resumption (char *p, char *endp,
5987 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
5988{
5989 struct remote_state *rs = get_remote_state ();
5990
a493e3e2 5991 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5992 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5993 else if (step
5994 /* GDB is willing to range step. */
5995 && use_range_stepping
5996 /* Target supports range stepping. */
5997 && rs->supports_vCont.r
5998 /* We don't currently support range stepping multiple
5999 threads with a wildcard (though the protocol allows it,
6000 so stubs shouldn't make an active effort to forbid
6001 it). */
6002 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6003 {
6004 struct thread_info *tp;
6005
6006 if (ptid_equal (ptid, minus_one_ptid))
6007 {
6008 /* If we don't know about the target thread's tid, then
6009 we're resuming magic_null_ptid (see caller). */
6010 tp = find_thread_ptid (magic_null_ptid);
6011 }
6012 else
6013 tp = find_thread_ptid (ptid);
6014 gdb_assert (tp != NULL);
6015
6016 if (tp->control.may_range_step)
6017 {
6018 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6019
6020 p += xsnprintf (p, endp - p, ";r%s,%s",
6021 phex_nz (tp->control.step_range_start,
6022 addr_size),
6023 phex_nz (tp->control.step_range_end,
6024 addr_size));
6025 }
6026 else
6027 p += xsnprintf (p, endp - p, ";s");
6028 }
0d8f58ca
PA
6029 else if (step)
6030 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6031 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6032 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6033 else
6034 p += xsnprintf (p, endp - p, ";c");
6035
6036 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
6037 {
6038 ptid_t nptid;
6039
6040 /* All (-1) threads of process. */
ba348170 6041 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
6042
6043 p += xsnprintf (p, endp - p, ":");
6044 p = write_ptid (p, endp, nptid);
6045 }
6046 else if (!ptid_equal (ptid, minus_one_ptid))
6047 {
6048 p += xsnprintf (p, endp - p, ":");
6049 p = write_ptid (p, endp, ptid);
6050 }
6051
6052 return p;
6053}
6054
799a2abe
PA
6055/* Clear the thread's private info on resume. */
6056
6057static void
6058resume_clear_thread_private_info (struct thread_info *thread)
6059{
6060 if (thread->priv != NULL)
6061 {
7aabaf9d
SM
6062 remote_thread_info *priv = get_remote_thread_info (thread);
6063
6064 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6065 priv->watch_data_address = 0;
799a2abe
PA
6066 }
6067}
6068
e5ef252a
PA
6069/* Append a vCont continue-with-signal action for threads that have a
6070 non-zero stop signal. */
6071
6b8edb51
PA
6072char *
6073remote_target::append_pending_thread_resumptions (char *p, char *endp,
6074 ptid_t ptid)
e5ef252a
PA
6075{
6076 struct thread_info *thread;
6077
034f788c 6078 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
6079 if (ptid_match (thread->ptid, ptid)
6080 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 6081 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
6082 {
6083 p = append_resumption (p, endp, thread->ptid,
6084 0, thread->suspend.stop_signal);
6085 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 6086 resume_clear_thread_private_info (thread);
e5ef252a
PA
6087 }
6088
6089 return p;
6090}
6091
7b68ffbb
PA
6092/* Set the target running, using the packets that use Hc
6093 (c/s/C/S). */
6094
6b8edb51
PA
6095void
6096remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6097 gdb_signal siggnal)
7b68ffbb
PA
6098{
6099 struct remote_state *rs = get_remote_state ();
6100 struct thread_info *thread;
6101 char *buf;
6102
6103 rs->last_sent_signal = siggnal;
6104 rs->last_sent_step = step;
6105
6106 /* The c/s/C/S resume packets use Hc, so set the continue
6107 thread. */
6108 if (ptid_equal (ptid, minus_one_ptid))
6109 set_continue_thread (any_thread_ptid);
6110 else
6111 set_continue_thread (ptid);
6112
6113 ALL_NON_EXITED_THREADS (thread)
6114 resume_clear_thread_private_info (thread);
6115
6116 buf = rs->buf;
6b8edb51 6117 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6118 {
6119 /* We don't pass signals to the target in reverse exec mode. */
6120 if (info_verbose && siggnal != GDB_SIGNAL_0)
6121 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6122 siggnal);
6123
6124 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6125 error (_("Remote reverse-step not supported."));
6126 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6127 error (_("Remote reverse-continue not supported."));
6128
6129 strcpy (buf, step ? "bs" : "bc");
6130 }
6131 else if (siggnal != GDB_SIGNAL_0)
6132 {
6133 buf[0] = step ? 'S' : 'C';
6134 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6135 buf[2] = tohex (((int) siggnal) & 0xf);
6136 buf[3] = '\0';
6137 }
6138 else
6139 strcpy (buf, step ? "s" : "c");
6140
6141 putpkt (buf);
6142}
6143
506fb367
DJ
6144/* Resume the remote inferior by using a "vCont" packet. The thread
6145 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
6146 resumed thread should be single-stepped and/or signalled. If PTID
6147 equals minus_one_ptid, then all threads are resumed; the thread to
6148 be stepped and/or signalled is given in the global INFERIOR_PTID.
6149 This function returns non-zero iff it resumes the inferior.
44eaed12 6150
7b68ffbb
PA
6151 This function issues a strict subset of all possible vCont commands
6152 at the moment. */
44eaed12 6153
6b8edb51
PA
6154int
6155remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6156 enum gdb_signal siggnal)
506fb367
DJ
6157{
6158 struct remote_state *rs = get_remote_state ();
82f73884
PA
6159 char *p;
6160 char *endp;
44eaed12 6161
7b68ffbb 6162 /* No reverse execution actions defined for vCont. */
6b8edb51 6163 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6164 return 0;
6165
4082afcc 6166 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6167 remote_vcont_probe ();
44eaed12 6168
4082afcc 6169 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6170 return 0;
44eaed12 6171
82f73884
PA
6172 p = rs->buf;
6173 endp = rs->buf + get_remote_packet_size ();
6174
506fb367
DJ
6175 /* If we could generate a wider range of packets, we'd have to worry
6176 about overflowing BUF. Should there be a generic
6177 "multi-part-packet" packet? */
6178
0d8f58ca
PA
6179 p += xsnprintf (p, endp - p, "vCont");
6180
79d7f229 6181 if (ptid_equal (ptid, magic_null_ptid))
c906108c 6182 {
79d7f229
PA
6183 /* MAGIC_NULL_PTID means that we don't have any active threads,
6184 so we don't have any TID numbers the inferior will
6185 understand. Make sure to only send forms that do not specify
6186 a TID. */
a9cbf802 6187 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6188 }
0d8f58ca 6189 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 6190 {
0d8f58ca
PA
6191 /* Resume all threads (of all processes, or of a single
6192 process), with preference for INFERIOR_PTID. This assumes
6193 inferior_ptid belongs to the set of all threads we are about
6194 to resume. */
a493e3e2 6195 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6196 {
0d8f58ca
PA
6197 /* Step inferior_ptid, with or without signal. */
6198 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6199 }
0d8f58ca 6200
e5ef252a
PA
6201 /* Also pass down any pending signaled resumption for other
6202 threads not the current. */
6203 p = append_pending_thread_resumptions (p, endp, ptid);
6204
0d8f58ca 6205 /* And continue others without a signal. */
a493e3e2 6206 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6207 }
6208 else
506fb367
DJ
6209 {
6210 /* Scheduler locking; resume only PTID. */
a9cbf802 6211 append_resumption (p, endp, ptid, step, siggnal);
506fb367 6212 }
c906108c 6213
82f73884
PA
6214 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6215 putpkt (rs->buf);
506fb367 6216
6efcd9a8 6217 if (target_is_non_stop_p ())
74531fed
PA
6218 {
6219 /* In non-stop, the stub replies to vCont with "OK". The stop
6220 reply will be reported asynchronously by means of a `%Stop'
6221 notification. */
6222 getpkt (&rs->buf, &rs->buf_size, 0);
6223 if (strcmp (rs->buf, "OK") != 0)
6224 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6225 }
6226
506fb367 6227 return 1;
c906108c 6228}
43ff13b4 6229
506fb367
DJ
6230/* Tell the remote machine to resume. */
6231
f6ac5f3d
PA
6232void
6233remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 6234{
d01949b6 6235 struct remote_state *rs = get_remote_state ();
43ff13b4 6236
85ad3aaf
PA
6237 /* When connected in non-stop mode, the core resumes threads
6238 individually. Resuming remote threads directly in target_resume
6239 would thus result in sending one packet per thread. Instead, to
6240 minimize roundtrip latency, here we just store the resume
6241 request; the actual remote resumption will be done in
6242 target_commit_resume / remote_commit_resume, where we'll be able
6243 to do vCont action coalescing. */
f6ac5f3d 6244 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6245 {
7aabaf9d 6246 remote_thread_info *remote_thr;
85ad3aaf
PA
6247
6248 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
7aabaf9d 6249 remote_thr = get_remote_thread_info (inferior_ptid);
85ad3aaf 6250 else
7aabaf9d
SM
6251 remote_thr = get_remote_thread_info (ptid);
6252
85ad3aaf
PA
6253 remote_thr->last_resume_step = step;
6254 remote_thr->last_resume_sig = siggnal;
6255 return;
6256 }
6257
722247f1
YQ
6258 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6259 (explained in remote-notif.c:handle_notification) so
6260 remote_notif_process is not called. We need find a place where
6261 it is safe to start a 'vNotif' sequence. It is good to do it
6262 before resuming inferior, because inferior was stopped and no RSP
6263 traffic at that moment. */
6efcd9a8 6264 if (!target_is_non_stop_p ())
5965e028 6265 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6266
f6ac5f3d 6267 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6268
7b68ffbb
PA
6269 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6270 if (!remote_resume_with_vcont (ptid, step, siggnal))
6b8edb51 6271 remote_resume_with_hc (ptid, step, siggnal);
43ff13b4 6272
2acceee2 6273 /* We are about to start executing the inferior, let's register it
0df8b418
MS
6274 with the event loop. NOTE: this is the one place where all the
6275 execution commands end up. We could alternatively do this in each
23860348 6276 of the execution commands in infcmd.c. */
2acceee2
JM
6277 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6278 into infcmd.c in order to allow inferior function calls to work
23860348 6279 NOT asynchronously. */
362646f5 6280 if (target_can_async_p ())
6a3753b3 6281 target_async (1);
e24a49d8
PA
6282
6283 /* We've just told the target to resume. The remote server will
6284 wait for the inferior to stop, and then send a stop reply. In
6285 the mean time, we can't start another command/query ourselves
74531fed
PA
6286 because the stub wouldn't be ready to process it. This applies
6287 only to the base all-stop protocol, however. In non-stop (which
6288 only supports vCont), the stub replies with an "OK", and is
6289 immediate able to process further serial input. */
6efcd9a8 6290 if (!target_is_non_stop_p ())
74531fed 6291 rs->waiting_for_stop_reply = 1;
43ff13b4 6292}
85ad3aaf 6293
85ad3aaf
PA
6294static int is_pending_fork_parent_thread (struct thread_info *thread);
6295
6296/* Private per-inferior info for target remote processes. */
6297
089354bb 6298struct remote_inferior : public private_inferior
85ad3aaf
PA
6299{
6300 /* Whether we can send a wildcard vCont for this process. */
089354bb 6301 bool may_wildcard_vcont = true;
85ad3aaf
PA
6302};
6303
089354bb
SM
6304/* Get the remote private inferior data associated to INF. */
6305
6306static remote_inferior *
6307get_remote_inferior (inferior *inf)
6308{
6309 if (inf->priv == NULL)
6310 inf->priv.reset (new remote_inferior);
6311
6312 return static_cast<remote_inferior *> (inf->priv.get ());
6313}
6314
f5db4863 6315/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6316 outgoing packet buffer. This is used to send multiple vCont
6317 packets if we have more actions than would fit a single packet. */
6318
f5db4863 6319class vcont_builder
85ad3aaf 6320{
f5db4863 6321public:
6b8edb51
PA
6322 explicit vcont_builder (remote_target *remote)
6323 : m_remote (remote)
f5db4863
PA
6324 {
6325 restart ();
6326 }
6327
6328 void flush ();
6329 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6330
6331private:
6332 void restart ();
6333
6b8edb51
PA
6334 /* The remote target. */
6335 remote_target *m_remote;
6336
85ad3aaf
PA
6337 /* Pointer to the first action. P points here if no action has been
6338 appended yet. */
f5db4863 6339 char *m_first_action;
85ad3aaf
PA
6340
6341 /* Where the next action will be appended. */
f5db4863 6342 char *m_p;
85ad3aaf
PA
6343
6344 /* The end of the buffer. Must never write past this. */
f5db4863 6345 char *m_endp;
85ad3aaf
PA
6346};
6347
6348/* Prepare the outgoing buffer for a new vCont packet. */
6349
f5db4863
PA
6350void
6351vcont_builder::restart ()
85ad3aaf 6352{
6b8edb51 6353 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6354
f5db4863 6355 m_p = rs->buf;
6b8edb51 6356 m_endp = rs->buf + m_remote->get_remote_packet_size ();
f5db4863
PA
6357 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6358 m_first_action = m_p;
85ad3aaf
PA
6359}
6360
6361/* If the vCont packet being built has any action, send it to the
6362 remote end. */
6363
f5db4863
PA
6364void
6365vcont_builder::flush ()
85ad3aaf
PA
6366{
6367 struct remote_state *rs;
6368
f5db4863 6369 if (m_p == m_first_action)
85ad3aaf
PA
6370 return;
6371
6b8edb51
PA
6372 rs = m_remote->get_remote_state ();
6373 m_remote->putpkt (rs->buf);
6374 m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
85ad3aaf
PA
6375 if (strcmp (rs->buf, "OK") != 0)
6376 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6377}
6378
6379/* The largest action is range-stepping, with its two addresses. This
6380 is more than sufficient. If a new, bigger action is created, it'll
6381 quickly trigger a failed assertion in append_resumption (and we'll
6382 just bump this). */
6383#define MAX_ACTION_SIZE 200
6384
6385/* Append a new vCont action in the outgoing packet being built. If
6386 the action doesn't fit the packet along with previous actions, push
6387 what we've got so far to the remote end and start over a new vCont
6388 packet (with the new action). */
6389
f5db4863
PA
6390void
6391vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6392{
6393 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6394
6b8edb51
PA
6395 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6396 ptid, step, siggnal);
85ad3aaf
PA
6397
6398 /* Check whether this new action would fit in the vCont packet along
6399 with previous actions. If not, send what we've got so far and
6400 start a new vCont packet. */
f5db4863
PA
6401 size_t rsize = endp - buf;
6402 if (rsize > m_endp - m_p)
85ad3aaf 6403 {
f5db4863
PA
6404 flush ();
6405 restart ();
85ad3aaf
PA
6406
6407 /* Should now fit. */
f5db4863 6408 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6409 }
6410
f5db4863
PA
6411 memcpy (m_p, buf, rsize);
6412 m_p += rsize;
6413 *m_p = '\0';
85ad3aaf
PA
6414}
6415
6416/* to_commit_resume implementation. */
6417
f6ac5f3d
PA
6418void
6419remote_target::commit_resume ()
85ad3aaf 6420{
85ad3aaf
PA
6421 struct inferior *inf;
6422 struct thread_info *tp;
6423 int any_process_wildcard;
6424 int may_global_wildcard_vcont;
85ad3aaf
PA
6425
6426 /* If connected in all-stop mode, we'd send the remote resume
6427 request directly from remote_resume. Likewise if
6428 reverse-debugging, as there are no defined vCont actions for
6429 reverse execution. */
f6ac5f3d 6430 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6431 return;
6432
6433 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6434 instead of resuming all threads of each process individually.
6435 However, if any thread of a process must remain halted, we can't
6436 send wildcard resumes and must send one action per thread.
6437
6438 Care must be taken to not resume threads/processes the server
6439 side already told us are stopped, but the core doesn't know about
6440 yet, because the events are still in the vStopped notification
6441 queue. For example:
6442
6443 #1 => vCont s:p1.1;c
6444 #2 <= OK
6445 #3 <= %Stopped T05 p1.1
6446 #4 => vStopped
6447 #5 <= T05 p1.2
6448 #6 => vStopped
6449 #7 <= OK
6450 #8 (infrun handles the stop for p1.1 and continues stepping)
6451 #9 => vCont s:p1.1;c
6452
6453 The last vCont above would resume thread p1.2 by mistake, because
6454 the server has no idea that the event for p1.2 had not been
6455 handled yet.
6456
6457 The server side must similarly ignore resume actions for the
6458 thread that has a pending %Stopped notification (and any other
6459 threads with events pending), until GDB acks the notification
6460 with vStopped. Otherwise, e.g., the following case is
6461 mishandled:
6462
6463 #1 => g (or any other packet)
6464 #2 <= [registers]
6465 #3 <= %Stopped T05 p1.2
6466 #4 => vCont s:p1.1;c
6467 #5 <= OK
6468
6469 Above, the server must not resume thread p1.2. GDB can't know
6470 that p1.2 stopped until it acks the %Stopped notification, and
6471 since from GDB's perspective all threads should be running, it
6472 sends a "c" action.
6473
6474 Finally, special care must also be given to handling fork/vfork
6475 events. A (v)fork event actually tells us that two processes
6476 stopped -- the parent and the child. Until we follow the fork,
6477 we must not resume the child. Therefore, if we have a pending
6478 fork follow, we must not send a global wildcard resume action
6479 (vCont;c). We can still send process-wide wildcards though. */
6480
6481 /* Start by assuming a global wildcard (vCont;c) is possible. */
6482 may_global_wildcard_vcont = 1;
6483
6484 /* And assume every process is individually wildcard-able too. */
6485 ALL_NON_EXITED_INFERIORS (inf)
6486 {
089354bb
SM
6487 remote_inferior *priv = get_remote_inferior (inf);
6488
6489 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6490 }
6491
6492 /* Check for any pending events (not reported or processed yet) and
6493 disable process and global wildcard resumes appropriately. */
6494 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6495
6496 ALL_NON_EXITED_THREADS (tp)
6497 {
6498 /* If a thread of a process is not meant to be resumed, then we
6499 can't wildcard that process. */
6500 if (!tp->executing)
6501 {
089354bb 6502 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6503
6504 /* And if we can't wildcard a process, we can't wildcard
6505 everything either. */
6506 may_global_wildcard_vcont = 0;
6507 continue;
6508 }
6509
6510 /* If a thread is the parent of an unfollowed fork, then we
6511 can't do a global wildcard, as that would resume the fork
6512 child. */
6513 if (is_pending_fork_parent_thread (tp))
6514 may_global_wildcard_vcont = 0;
6515 }
6516
6517 /* Now let's build the vCont packet(s). Actions must be appended
6518 from narrower to wider scopes (thread -> process -> global). If
6519 we end up with too many actions for a single packet vcont_builder
6520 flushes the current vCont packet to the remote side and starts a
6521 new one. */
6b8edb51 6522 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
6523
6524 /* Threads first. */
6525 ALL_NON_EXITED_THREADS (tp)
6526 {
7aabaf9d 6527 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf
PA
6528
6529 if (!tp->executing || remote_thr->vcont_resumed)
6530 continue;
6531
6532 gdb_assert (!thread_is_in_step_over_chain (tp));
6533
6534 if (!remote_thr->last_resume_step
6535 && remote_thr->last_resume_sig == GDB_SIGNAL_0
089354bb 6536 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
85ad3aaf
PA
6537 {
6538 /* We'll send a wildcard resume instead. */
6539 remote_thr->vcont_resumed = 1;
6540 continue;
6541 }
6542
f5db4863 6543 vcont_builder.push_action (tp->ptid,
85ad3aaf
PA
6544 remote_thr->last_resume_step,
6545 remote_thr->last_resume_sig);
6546 remote_thr->vcont_resumed = 1;
6547 }
6548
6549 /* Now check whether we can send any process-wide wildcard. This is
6550 to avoid sending a global wildcard in the case nothing is
6551 supposed to be resumed. */
6552 any_process_wildcard = 0;
6553
6554 ALL_NON_EXITED_INFERIORS (inf)
6555 {
089354bb 6556 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf
PA
6557 {
6558 any_process_wildcard = 1;
6559 break;
6560 }
6561 }
6562
6563 if (any_process_wildcard)
6564 {
6565 /* If all processes are wildcard-able, then send a single "c"
6566 action, otherwise, send an "all (-1) threads of process"
6567 continue action for each running process, if any. */
6568 if (may_global_wildcard_vcont)
6569 {
f5db4863
PA
6570 vcont_builder.push_action (minus_one_ptid,
6571 false, GDB_SIGNAL_0);
85ad3aaf
PA
6572 }
6573 else
6574 {
6575 ALL_NON_EXITED_INFERIORS (inf)
6576 {
089354bb 6577 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6578 {
f5db4863
PA
6579 vcont_builder.push_action (pid_to_ptid (inf->pid),
6580 false, GDB_SIGNAL_0);
85ad3aaf
PA
6581 }
6582 }
6583 }
6584 }
6585
f5db4863 6586 vcont_builder.flush ();
85ad3aaf
PA
6587}
6588
c906108c 6589\f
43ff13b4 6590
74531fed
PA
6591/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6592 thread, all threads of a remote process, or all threads of all
6593 processes. */
6594
6b8edb51
PA
6595void
6596remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
6597{
6598 struct remote_state *rs = get_remote_state ();
6599 char *p = rs->buf;
6600 char *endp = rs->buf + get_remote_packet_size ();
74531fed 6601
4082afcc 6602 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6603 remote_vcont_probe ();
74531fed 6604
d458bd84 6605 if (!rs->supports_vCont.t)
74531fed
PA
6606 error (_("Remote server does not support stopping threads"));
6607
f91d3df5
PA
6608 if (ptid_equal (ptid, minus_one_ptid)
6609 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
6610 p += xsnprintf (p, endp - p, "vCont;t");
6611 else
6612 {
6613 ptid_t nptid;
6614
74531fed
PA
6615 p += xsnprintf (p, endp - p, "vCont;t:");
6616
6617 if (ptid_is_pid (ptid))
6618 /* All (-1) threads of process. */
ba348170 6619 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
6620 else
6621 {
6622 /* Small optimization: if we already have a stop reply for
6623 this thread, no use in telling the stub we want this
6624 stopped. */
6625 if (peek_stop_reply (ptid))
6626 return;
6627
6628 nptid = ptid;
6629 }
6630
a9cbf802 6631 write_ptid (p, endp, nptid);
74531fed
PA
6632 }
6633
6634 /* In non-stop, we get an immediate OK reply. The stop reply will
6635 come in asynchronously by notification. */
6636 putpkt (rs->buf);
6637 getpkt (&rs->buf, &rs->buf_size, 0);
6638 if (strcmp (rs->buf, "OK") != 0)
6639 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6640}
6641
bfedc46a
PA
6642/* All-stop version of target_interrupt. Sends a break or a ^C to
6643 interrupt the remote target. It is undefined which thread of which
6644 process reports the interrupt. */
74531fed 6645
6b8edb51
PA
6646void
6647remote_target::remote_interrupt_as ()
74531fed
PA
6648{
6649 struct remote_state *rs = get_remote_state ();
6650
3a29589a
DJ
6651 rs->ctrlc_pending_p = 1;
6652
74531fed
PA
6653 /* If the inferior is stopped already, but the core didn't know
6654 about it yet, just ignore the request. The cached wait status
6655 will be collected in remote_wait. */
6656 if (rs->cached_wait_status)
6657 return;
6658
9a7071a8
JB
6659 /* Send interrupt_sequence to remote target. */
6660 send_interrupt_sequence ();
74531fed
PA
6661}
6662
de979965
PA
6663/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6664 the remote target. It is undefined which thread of which process
e42de8c7
PA
6665 reports the interrupt. Throws an error if the packet is not
6666 supported by the server. */
de979965 6667
6b8edb51
PA
6668void
6669remote_target::remote_interrupt_ns ()
de979965
PA
6670{
6671 struct remote_state *rs = get_remote_state ();
6672 char *p = rs->buf;
6673 char *endp = rs->buf + get_remote_packet_size ();
6674
6675 xsnprintf (p, endp - p, "vCtrlC");
6676
6677 /* In non-stop, we get an immediate OK reply. The stop reply will
6678 come in asynchronously by notification. */
6679 putpkt (rs->buf);
6680 getpkt (&rs->buf, &rs->buf_size, 0);
6681
6682 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6683 {
6684 case PACKET_OK:
6685 break;
6686 case PACKET_UNKNOWN:
e42de8c7 6687 error (_("No support for interrupting the remote target."));
de979965
PA
6688 case PACKET_ERROR:
6689 error (_("Interrupting target failed: %s"), rs->buf);
6690 }
de979965
PA
6691}
6692
bfedc46a 6693/* Implement the to_stop function for the remote targets. */
74531fed 6694
f6ac5f3d
PA
6695void
6696remote_target::stop (ptid_t ptid)
c906108c 6697{
7a292a7a 6698 if (remote_debug)
0f71a2f6 6699 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6700
6efcd9a8 6701 if (target_is_non_stop_p ())
74531fed 6702 remote_stop_ns (ptid);
c906108c 6703 else
bfedc46a
PA
6704 {
6705 /* We don't currently have a way to transparently pause the
6706 remote target in all-stop mode. Interrupt it instead. */
de979965 6707 remote_interrupt_as ();
bfedc46a
PA
6708 }
6709}
6710
6711/* Implement the to_interrupt function for the remote targets. */
6712
f6ac5f3d
PA
6713void
6714remote_target::interrupt ()
bfedc46a
PA
6715{
6716 if (remote_debug)
6717 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6718
e42de8c7
PA
6719 if (target_is_non_stop_p ())
6720 remote_interrupt_ns ();
bfedc46a 6721 else
e42de8c7 6722 remote_interrupt_as ();
c906108c
SS
6723}
6724
93692b58
PA
6725/* Implement the to_pass_ctrlc function for the remote targets. */
6726
f6ac5f3d
PA
6727void
6728remote_target::pass_ctrlc ()
93692b58
PA
6729{
6730 struct remote_state *rs = get_remote_state ();
6731
6732 if (remote_debug)
6733 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6734
6735 /* If we're starting up, we're not fully synced yet. Quit
6736 immediately. */
6737 if (rs->starting_up)
6738 quit ();
6739 /* If ^C has already been sent once, offer to disconnect. */
6740 else if (rs->ctrlc_pending_p)
6741 interrupt_query ();
6742 else
e671cd59 6743 target_interrupt ();
93692b58
PA
6744}
6745
c906108c
SS
6746/* Ask the user what to do when an interrupt is received. */
6747
6b8edb51
PA
6748void
6749remote_target::interrupt_query ()
c906108c 6750{
abc56d60 6751 struct remote_state *rs = get_remote_state ();
c906108c 6752
abc56d60 6753 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6754 {
abc56d60
PA
6755 if (query (_("The target is not responding to interrupt requests.\n"
6756 "Stop debugging it? ")))
74531fed 6757 {
78a095c3 6758 remote_unpush_target ();
abc56d60 6759 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6760 }
6761 }
abc56d60
PA
6762 else
6763 {
6764 if (query (_("Interrupted while waiting for the program.\n"
6765 "Give up waiting? ")))
6766 quit ();
6767 }
c906108c
SS
6768}
6769
6426a772
JM
6770/* Enable/disable target terminal ownership. Most targets can use
6771 terminal groups to control terminal ownership. Remote targets are
6772 different in that explicit transfer of ownership to/from GDB/target
23860348 6773 is required. */
6426a772 6774
f6ac5f3d
PA
6775void
6776remote_target::terminal_inferior ()
6426a772 6777{
6426a772
JM
6778 /* NOTE: At this point we could also register our selves as the
6779 recipient of all input. Any characters typed could then be
23860348 6780 passed on down to the target. */
6426a772
JM
6781}
6782
f6ac5f3d
PA
6783void
6784remote_target::terminal_ours ()
6426a772 6785{
6426a772
JM
6786}
6787
176a6961 6788static void
917317f4 6789remote_console_output (char *msg)
c906108c
SS
6790{
6791 char *p;
6792
c5aa993b 6793 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6794 {
6795 char tb[2];
6796 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6797
c906108c
SS
6798 tb[0] = c;
6799 tb[1] = 0;
43ff13b4 6800 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6801 }
00db5b94
PA
6802 gdb_flush (gdb_stdtarg);
6803}
74531fed 6804
74531fed
PA
6805DEF_VEC_O(cached_reg_t);
6806
722247f1 6807typedef struct stop_reply
74531fed 6808{
722247f1 6809 struct notif_event base;
74531fed 6810
722247f1 6811 /* The identifier of the thread about this event */
74531fed
PA
6812 ptid_t ptid;
6813
340e3c99 6814 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6815 connection, represented by a remote_state object, is closed,
6816 all the associated stop_reply events should be released. */
6817 struct remote_state *rs;
6818
74531fed
PA
6819 struct target_waitstatus ws;
6820
5cd63fda
PA
6821 /* The architecture associated with the expedited registers. */
6822 gdbarch *arch;
6823
15148d6a
PA
6824 /* Expedited registers. This makes remote debugging a bit more
6825 efficient for those targets that provide critical registers as
6826 part of their normal status mechanism (as another roundtrip to
6827 fetch them is avoided). */
74531fed
PA
6828 VEC(cached_reg_t) *regcache;
6829
f7e6eed5
PA
6830 enum target_stop_reason stop_reason;
6831
74531fed
PA
6832 CORE_ADDR watch_data_address;
6833
dc146f7c 6834 int core;
722247f1 6835} *stop_reply_p;
a744cf53 6836
74531fed
PA
6837static void
6838stop_reply_xfree (struct stop_reply *r)
6839{
f48ff2a7 6840 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6841}
6842
221e1a37
PA
6843/* Return the length of the stop reply queue. */
6844
6b8edb51
PA
6845int
6846remote_target::stop_reply_queue_length ()
221e1a37 6847{
6b8edb51
PA
6848 remote_state *rs = get_remote_state ();
6849 return QUEUE_length (stop_reply_p, rs->stop_reply_queue);
221e1a37
PA
6850}
6851
6b8edb51
PA
6852void
6853remote_notif_stop_parse (remote_target *remote,
6854 struct notif_client *self, char *buf,
722247f1
YQ
6855 struct notif_event *event)
6856{
6b8edb51 6857 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
6858}
6859
6860static void
6b8edb51
PA
6861remote_notif_stop_ack (remote_target *remote,
6862 struct notif_client *self, char *buf,
722247f1
YQ
6863 struct notif_event *event)
6864{
6865 struct stop_reply *stop_reply = (struct stop_reply *) event;
6866
6867 /* acknowledge */
6b8edb51 6868 putpkt (remote, self->ack_command);
722247f1
YQ
6869
6870 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6b8edb51 6871 {
722247f1
YQ
6872 /* We got an unknown stop reply. */
6873 error (_("Unknown stop reply"));
6b8edb51 6874 }
722247f1 6875
6b8edb51 6876 remote->push_stop_reply (stop_reply);
722247f1
YQ
6877}
6878
6879static int
6b8edb51
PA
6880remote_notif_stop_can_get_pending_events (remote_target *remote,
6881 struct notif_client *self)
722247f1
YQ
6882{
6883 /* We can't get pending events in remote_notif_process for
6884 notification stop, and we have to do this in remote_wait_ns
6885 instead. If we fetch all queued events from stub, remote stub
6886 may exit and we have no chance to process them back in
6887 remote_wait_ns. */
6b8edb51
PA
6888 remote_state *rs = remote->get_remote_state ();
6889 mark_async_event_handler (rs->remote_async_inferior_event_token);
722247f1
YQ
6890 return 0;
6891}
6892
6893static void
6894stop_reply_dtr (struct notif_event *event)
6895{
6896 struct stop_reply *r = (struct stop_reply *) event;
d1dff226
AH
6897 cached_reg_t *reg;
6898 int ix;
6899
6900 for (ix = 0;
6901 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6902 ix++)
6903 xfree (reg->data);
722247f1
YQ
6904
6905 VEC_free (cached_reg_t, r->regcache);
6906}
6907
6908static struct notif_event *
6909remote_notif_stop_alloc_reply (void)
6910{
8d749320
SM
6911 /* We cast to a pointer to the "base class". */
6912 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6913
6914 r->dtr = stop_reply_dtr;
6915
6916 return r;
6917}
6918
6919/* A client of notification Stop. */
6920
6921struct notif_client notif_client_stop =
6922{
6923 "Stop",
6924 "vStopped",
6925 remote_notif_stop_parse,
6926 remote_notif_stop_ack,
6927 remote_notif_stop_can_get_pending_events,
6928 remote_notif_stop_alloc_reply,
f48ff2a7 6929 REMOTE_NOTIF_STOP,
722247f1
YQ
6930};
6931
6932/* A parameter to pass data in and out. */
6933
6934struct queue_iter_param
6935{
6b8edb51 6936 remote_target *remote;
722247f1
YQ
6937 void *input;
6938 struct stop_reply *output;
6939};
6940
85ad3aaf 6941/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6942 the pid of the process that owns the threads we want to check, or
6943 -1 if we want to check all threads. */
6944
6945static int
6946is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6947 ptid_t thread_ptid)
6948{
6949 if (ws->kind == TARGET_WAITKIND_FORKED
6950 || ws->kind == TARGET_WAITKIND_VFORKED)
6951 {
6952 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6953 return 1;
6954 }
6955
6956 return 0;
6957}
6958
85ad3aaf
PA
6959/* Return the thread's pending status used to determine whether the
6960 thread is a fork parent stopped at a fork event. */
6961
6962static struct target_waitstatus *
6963thread_pending_fork_status (struct thread_info *thread)
6964{
6965 if (thread->suspend.waitstatus_pending_p)
6966 return &thread->suspend.waitstatus;
6967 else
6968 return &thread->pending_follow;
6969}
6970
6971/* Determine if THREAD is a pending fork parent thread. */
6972
6973static int
6974is_pending_fork_parent_thread (struct thread_info *thread)
6975{
6976 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6977 int pid = -1;
6978
6979 return is_pending_fork_parent (ws, pid, thread->ptid);
6980}
6981
cbb8991c
DB
6982/* Check whether EVENT is a fork event, and if it is, remove the
6983 fork child from the context list passed in DATA. */
6984
6985static int
6986remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6987 QUEUE_ITER (stop_reply_p) *iter,
6988 stop_reply_p event,
6989 void *data)
6990{
19ba03f4
SM
6991 struct queue_iter_param *param = (struct queue_iter_param *) data;
6992 struct threads_listing_context *context
6993 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6994
6995 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6996 || event->ws.kind == TARGET_WAITKIND_VFORKED
6997 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
21fe1c75 6998 context->remove_thread (event->ws.value.related_pid);
cbb8991c
DB
6999
7000 return 1;
7001}
7002
7003/* If CONTEXT contains any fork child threads that have not been
7004 reported yet, remove them from the CONTEXT list. If such a
7005 thread exists it is because we are stopped at a fork catchpoint
7006 and have not yet called follow_fork, which will set up the
7007 host-side data structures for the new process. */
7008
6b8edb51
PA
7009void
7010remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c
DB
7011{
7012 struct thread_info * thread;
7013 int pid = -1;
7014 struct notif_client *notif = &notif_client_stop;
7015 struct queue_iter_param param;
7016
7017 /* For any threads stopped at a fork event, remove the corresponding
7018 fork child threads from the CONTEXT list. */
7019 ALL_NON_EXITED_THREADS (thread)
7020 {
85ad3aaf 7021 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
7022
7023 if (is_pending_fork_parent (ws, pid, thread->ptid))
21fe1c75 7024 context->remove_thread (ws->value.related_pid);
cbb8991c
DB
7025 }
7026
7027 /* Check for any pending fork events (not reported or processed yet)
7028 in process PID and remove those fork child threads from the
7029 CONTEXT list as well. */
7030 remote_notif_get_pending_events (notif);
6b8edb51 7031 param.remote = this;
cbb8991c
DB
7032 param.input = context;
7033 param.output = NULL;
6b8edb51 7034 QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
cbb8991c
DB
7035 remove_child_of_pending_fork, &param);
7036}
7037
6b8edb51
PA
7038/* Callback data for
7039 check_pending_event_prevents_wildcard_vcont_callback. */
7040struct check_pending_event_prevents_wildcard_vcont_callback_data
7041{
7042 /* The remote target. */
7043 remote_target *remote;
7044
7045 /* Whether we can do a global wildcard (vCont;c) */
7046 int *may_global_wildcard_vcont;
7047};
7048
85ad3aaf
PA
7049/* Check whether EVENT would prevent a global or process wildcard
7050 vCont action. */
7051
7052static int
7053check_pending_event_prevents_wildcard_vcont_callback
7054 (QUEUE (stop_reply_p) *q,
7055 QUEUE_ITER (stop_reply_p) *iter,
7056 stop_reply_p event,
7057 void *data)
7058{
7059 struct inferior *inf;
6b8edb51 7060 auto *cb_data = (check_pending_event_prevents_wildcard_vcont_callback_data *) data;
85ad3aaf
PA
7061
7062 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7063 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7064 return 1;
7065
7066 if (event->ws.kind == TARGET_WAITKIND_FORKED
7067 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6b8edb51 7068 *cb_data->may_global_wildcard_vcont = 0;
85ad3aaf
PA
7069
7070 inf = find_inferior_ptid (event->ptid);
7071
7072 /* This may be the first time we heard about this process.
7073 Regardless, we must not do a global wildcard resume, otherwise
7074 we'd resume this process too. */
6b8edb51 7075 *cb_data->may_global_wildcard_vcont = 0;
85ad3aaf 7076 if (inf != NULL)
089354bb 7077 get_remote_inferior (inf)->may_wildcard_vcont = false;
85ad3aaf
PA
7078
7079 return 1;
7080}
7081
7082/* Check whether any event pending in the vStopped queue would prevent
7083 a global or process wildcard vCont action. Clear
7084 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7085 and clear the event inferior's may_wildcard_vcont flag if we can't
7086 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7087
6b8edb51
PA
7088void
7089remote_target::check_pending_events_prevent_wildcard_vcont
7090 (int *may_global_wildcard)
85ad3aaf
PA
7091{
7092 struct notif_client *notif = &notif_client_stop;
6b8edb51
PA
7093 check_pending_event_prevents_wildcard_vcont_callback_data cb_data
7094 {this, may_global_wildcard};
85ad3aaf
PA
7095
7096 remote_notif_get_pending_events (notif);
6b8edb51 7097 QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
85ad3aaf 7098 check_pending_event_prevents_wildcard_vcont_callback,
6b8edb51 7099 &cb_data);
85ad3aaf
PA
7100}
7101
f48ff2a7
YQ
7102/* Remove stop replies in the queue if its pid is equal to the given
7103 inferior's pid. */
722247f1
YQ
7104
7105static int
f48ff2a7
YQ
7106remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
7107 QUEUE_ITER (stop_reply_p) *iter,
7108 stop_reply_p event,
7109 void *data)
722247f1 7110{
19ba03f4
SM
7111 struct queue_iter_param *param = (struct queue_iter_param *) data;
7112 struct inferior *inf = (struct inferior *) param->input;
722247f1 7113
f48ff2a7 7114 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
7115 {
7116 stop_reply_xfree (event);
7117 QUEUE_remove_elem (stop_reply_p, q, iter);
7118 }
7119
7120 return 1;
7121}
7122
f48ff2a7 7123/* Discard all pending stop replies of inferior INF. */
c906108c 7124
6b8edb51
PA
7125void
7126remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7127{
722247f1 7128 struct queue_iter_param param;
f48ff2a7
YQ
7129 struct stop_reply *reply;
7130 struct remote_state *rs = get_remote_state ();
7131 struct remote_notif_state *rns = rs->notif_state;
7132
7133 /* This function can be notified when an inferior exists. When the
7134 target is not remote, the notification state is NULL. */
7135 if (rs->remote_desc == NULL)
7136 return;
7137
7138 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7139
74531fed 7140 /* Discard the in-flight notification. */
f48ff2a7 7141 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 7142 {
722247f1 7143 stop_reply_xfree (reply);
f48ff2a7 7144 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 7145 }
c906108c 7146
6b8edb51 7147 param.remote = this;
722247f1
YQ
7148 param.input = inf;
7149 param.output = NULL;
74531fed
PA
7150 /* Discard the stop replies we have already pulled with
7151 vStopped. */
6b8edb51 7152 QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
f48ff2a7
YQ
7153 remove_stop_reply_for_inferior, &param);
7154}
7155
bcc75809
YQ
7156/* If its remote state is equal to the given remote state,
7157 remove EVENT from the stop reply queue. */
7158
7159static int
7160remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
7161 QUEUE_ITER (stop_reply_p) *iter,
7162 stop_reply_p event,
7163 void *data)
7164{
19ba03f4
SM
7165 struct queue_iter_param *param = (struct queue_iter_param *) data;
7166 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
7167
7168 if (event->rs == rs)
7169 {
7170 stop_reply_xfree (event);
7171 QUEUE_remove_elem (stop_reply_p, q, iter);
7172 }
7173
7174 return 1;
7175}
7176
7177/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7178
6b8edb51
PA
7179void
7180remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7181{
6b8edb51 7182 remote_state *rs = get_remote_state ();
f48ff2a7
YQ
7183 struct queue_iter_param param;
7184
6b8edb51 7185 param.remote = this;
bcc75809 7186 param.input = rs;
f48ff2a7
YQ
7187 param.output = NULL;
7188 /* Discard the stop replies we have already pulled with
7189 vStopped. */
6b8edb51 7190 QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
bcc75809 7191 remove_stop_reply_of_remote_state, &param);
722247f1 7192}
74531fed 7193
722247f1
YQ
7194/* A parameter to pass data in and out. */
7195
7196static int
7197remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
7198 QUEUE_ITER (stop_reply_p) *iter,
7199 stop_reply_p event,
7200 void *data)
7201{
19ba03f4
SM
7202 struct queue_iter_param *param = (struct queue_iter_param *) data;
7203 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
7204
7205 if (ptid_match (event->ptid, *ptid))
7206 {
7207 param->output = event;
7208 QUEUE_remove_elem (stop_reply_p, q, iter);
7209 return 0;
c8e38a49 7210 }
722247f1
YQ
7211
7212 return 1;
74531fed 7213}
43ff13b4 7214
722247f1
YQ
7215/* Remove the first reply in 'stop_reply_queue' which matches
7216 PTID. */
2e9f7625 7217
6b8edb51
PA
7218struct stop_reply *
7219remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7220{
722247f1
YQ
7221 struct queue_iter_param param;
7222
6b8edb51 7223 param.remote = this;
722247f1
YQ
7224 param.input = &ptid;
7225 param.output = NULL;
7226
6b8edb51 7227 QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
722247f1
YQ
7228 remote_notif_remove_once_on_match, &param);
7229 if (notif_debug)
7230 fprintf_unfiltered (gdb_stdlog,
7231 "notif: discard queued event: 'Stop' in %s\n",
7232 target_pid_to_str (ptid));
a744cf53 7233
722247f1 7234 return param.output;
74531fed 7235}
75c99385 7236
74531fed
PA
7237/* Look for a queued stop reply belonging to PTID. If one is found,
7238 remove it from the queue, and return it. Returns NULL if none is
7239 found. If there are still queued events left to process, tell the
7240 event loop to get back to target_wait soon. */
e24a49d8 7241
6b8edb51
PA
7242struct stop_reply *
7243remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7244{
722247f1 7245 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7246
6b8edb51
PA
7247 if (!QUEUE_is_empty (stop_reply_p, get_remote_state ()->stop_reply_queue))
7248 {
7249 remote_state *rs = get_remote_state ();
7250 /* There's still at least an event left. */
7251 mark_async_event_handler (rs->remote_async_inferior_event_token);
7252 }
74531fed 7253
722247f1 7254 return r;
74531fed
PA
7255}
7256
7257/* Push a fully parsed stop reply in the stop reply queue. Since we
7258 know that we now have at least one queued event left to pass to the
7259 core side, tell the event loop to get back to target_wait soon. */
7260
6b8edb51
PA
7261void
7262remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7263{
6b8edb51
PA
7264 remote_state *rs = get_remote_state ();
7265 QUEUE_enque (stop_reply_p, rs->stop_reply_queue, new_event);
74531fed 7266
722247f1
YQ
7267 if (notif_debug)
7268 fprintf_unfiltered (gdb_stdlog,
7269 "notif: push 'Stop' %s to queue %d\n",
7270 target_pid_to_str (new_event->ptid),
7271 QUEUE_length (stop_reply_p,
6b8edb51 7272 rs->stop_reply_queue));
74531fed 7273
6b8edb51 7274 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
7275}
7276
722247f1
YQ
7277static int
7278stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
7279 QUEUE_ITER (stop_reply_p) *iter,
7280 struct stop_reply *event,
7281 void *data)
7282{
19ba03f4 7283 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
7284
7285 return !(ptid_equal (*ptid, event->ptid)
7286 && event->ws.kind == TARGET_WAITKIND_STOPPED);
7287}
7288
74531fed
PA
7289/* Returns true if we have a stop reply for PTID. */
7290
6b8edb51
PA
7291int
7292remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7293{
6b8edb51
PA
7294 remote_state *rs = get_remote_state ();
7295 return !QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
722247f1 7296 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
7297}
7298
26d56a93
SL
7299/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7300 starting with P and ending with PEND matches PREFIX. */
7301
7302static int
7303strprefix (const char *p, const char *pend, const char *prefix)
7304{
7305 for ( ; p < pend; p++, prefix++)
7306 if (*p != *prefix)
7307 return 0;
7308 return *prefix == '\0';
7309}
7310
74531fed
PA
7311/* Parse the stop reply in BUF. Either the function succeeds, and the
7312 result is stored in EVENT, or throws an error. */
7313
6b8edb51
PA
7314void
7315remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
74531fed 7316{
5cd63fda 7317 remote_arch_state *rsa = NULL;
74531fed 7318 ULONGEST addr;
256642e8 7319 const char *p;
94585166 7320 int skipregs = 0;
74531fed
PA
7321
7322 event->ptid = null_ptid;
bcc75809 7323 event->rs = get_remote_state ();
74531fed
PA
7324 event->ws.kind = TARGET_WAITKIND_IGNORE;
7325 event->ws.value.integer = 0;
f7e6eed5 7326 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 7327 event->regcache = NULL;
dc146f7c 7328 event->core = -1;
74531fed
PA
7329
7330 switch (buf[0])
7331 {
7332 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7333 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7334 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7335 ss = signal number
7336 n... = register number
7337 r... = register contents
7338 */
7339
7340 p = &buf[3]; /* after Txx */
7341 while (*p)
7342 {
256642e8 7343 const char *p1;
cea39f65 7344 int fieldsize;
43ff13b4 7345
1f10ba14
PA
7346 p1 = strchr (p, ':');
7347 if (p1 == NULL)
7348 error (_("Malformed packet(a) (missing colon): %s\n\
7349Packet: '%s'\n"),
7350 p, buf);
7351 if (p == p1)
7352 error (_("Malformed packet(a) (missing register number): %s\n\
7353Packet: '%s'\n"),
7354 p, buf);
3c3bea1c 7355
1f10ba14
PA
7356 /* Some "registers" are actually extended stop information.
7357 Note if you're adding a new entry here: GDB 7.9 and
7358 earlier assume that all register "numbers" that start
7359 with an hex digit are real register numbers. Make sure
7360 the server only sends such a packet if it knows the
7361 client understands it. */
c8e38a49 7362
26d56a93 7363 if (strprefix (p, p1, "thread"))
1f10ba14 7364 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7365 else if (strprefix (p, p1, "syscall_entry"))
7366 {
7367 ULONGEST sysno;
7368
7369 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7370 p = unpack_varlen_hex (++p1, &sysno);
7371 event->ws.value.syscall_number = (int) sysno;
7372 }
7373 else if (strprefix (p, p1, "syscall_return"))
7374 {
7375 ULONGEST sysno;
7376
7377 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7378 p = unpack_varlen_hex (++p1, &sysno);
7379 event->ws.value.syscall_number = (int) sysno;
7380 }
26d56a93
SL
7381 else if (strprefix (p, p1, "watch")
7382 || strprefix (p, p1, "rwatch")
7383 || strprefix (p, p1, "awatch"))
cea39f65 7384 {
f7e6eed5 7385 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7386 p = unpack_varlen_hex (++p1, &addr);
7387 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7388 }
26d56a93 7389 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7390 {
7391 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7392
7393 /* Make sure the stub doesn't forget to indicate support
7394 with qSupported. */
7395 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7396 error (_("Unexpected swbreak stop reason"));
7397
7398 /* The value part is documented as "must be empty",
7399 though we ignore it, in case we ever decide to make
7400 use of it in a backward compatible way. */
8424cc97 7401 p = strchrnul (p1 + 1, ';');
f7e6eed5 7402 }
26d56a93 7403 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7404 {
7405 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7406
7407 /* Make sure the stub doesn't forget to indicate support
7408 with qSupported. */
7409 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7410 error (_("Unexpected hwbreak stop reason"));
7411
7412 /* See above. */
8424cc97 7413 p = strchrnul (p1 + 1, ';');
f7e6eed5 7414 }
26d56a93 7415 else if (strprefix (p, p1, "library"))
cea39f65 7416 {
1f10ba14 7417 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 7418 p = strchrnul (p1 + 1, ';');
1f10ba14 7419 }
26d56a93 7420 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
7421 {
7422 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7423 /* p1 will indicate "begin" or "end", but it makes
7424 no difference for now, so ignore it. */
8424cc97 7425 p = strchrnul (p1 + 1, ';');
1f10ba14 7426 }
26d56a93 7427 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7428 {
7429 ULONGEST c;
a744cf53 7430
1f10ba14
PA
7431 p = unpack_varlen_hex (++p1, &c);
7432 event->core = c;
cea39f65 7433 }
26d56a93 7434 else if (strprefix (p, p1, "fork"))
de0d863e
DB
7435 {
7436 event->ws.value.related_pid = read_ptid (++p1, &p);
7437 event->ws.kind = TARGET_WAITKIND_FORKED;
7438 }
26d56a93 7439 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
7440 {
7441 event->ws.value.related_pid = read_ptid (++p1, &p);
7442 event->ws.kind = TARGET_WAITKIND_VFORKED;
7443 }
26d56a93 7444 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
7445 {
7446 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 7447 p = strchrnul (p1 + 1, ';');
c269dbdb 7448 }
6ab24463 7449 else if (strprefix (p, p1, "exec"))
94585166
DB
7450 {
7451 ULONGEST ignored;
7452 char pathname[PATH_MAX];
7453 int pathlen;
7454
7455 /* Determine the length of the execd pathname. */
7456 p = unpack_varlen_hex (++p1, &ignored);
7457 pathlen = (p - p1) / 2;
7458
7459 /* Save the pathname for event reporting and for
7460 the next run command. */
7461 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7462 pathname[pathlen] = '\0';
7463
7464 /* This is freed during event handling. */
7465 event->ws.value.execd_pathname = xstrdup (pathname);
7466 event->ws.kind = TARGET_WAITKIND_EXECD;
7467
7468 /* Skip the registers included in this packet, since
7469 they may be for an architecture different from the
7470 one used by the original program. */
7471 skipregs = 1;
7472 }
65706a29
PA
7473 else if (strprefix (p, p1, "create"))
7474 {
7475 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 7476 p = strchrnul (p1 + 1, ';');
65706a29 7477 }
cea39f65
MS
7478 else
7479 {
1f10ba14 7480 ULONGEST pnum;
256642e8 7481 const char *p_temp;
1f10ba14 7482
94585166
DB
7483 if (skipregs)
7484 {
8424cc97 7485 p = strchrnul (p1 + 1, ';');
94585166
DB
7486 p++;
7487 continue;
7488 }
7489
1f10ba14
PA
7490 /* Maybe a real ``P'' register number. */
7491 p_temp = unpack_varlen_hex (p, &pnum);
7492 /* If the first invalid character is the colon, we got a
7493 register number. Otherwise, it's an unknown stop
7494 reason. */
7495 if (p_temp == p1)
7496 {
5cd63fda
PA
7497 /* If we haven't parsed the event's thread yet, find
7498 it now, in order to find the architecture of the
7499 reported expedited registers. */
7500 if (event->ptid == null_ptid)
7501 {
7502 const char *thr = strstr (p1 + 1, ";thread:");
7503 if (thr != NULL)
7504 event->ptid = read_ptid (thr + strlen (";thread:"),
7505 NULL);
7506 else
3cada740
PA
7507 {
7508 /* Either the current thread hasn't changed,
7509 or the inferior is not multi-threaded.
7510 The event must be for the thread we last
7511 set as (or learned as being) current. */
7512 event->ptid = event->rs->general_thread;
7513 }
5cd63fda
PA
7514 }
7515
7516 if (rsa == NULL)
7517 {
7518 inferior *inf = (event->ptid == null_ptid
7519 ? NULL
7520 : find_inferior_ptid (event->ptid));
7521 /* If this is the first time we learn anything
7522 about this process, skip the registers
7523 included in this packet, since we don't yet
7524 know which architecture to use to parse them.
7525 We'll determine the architecture later when
7526 we process the stop reply and retrieve the
7527 target description, via
7528 remote_notice_new_inferior ->
7529 post_create_inferior. */
7530 if (inf == NULL)
7531 {
7532 p = strchrnul (p1 + 1, ';');
7533 p++;
7534 continue;
7535 }
7536
7537 event->arch = inf->gdbarch;
9d6eea31 7538 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7539 }
7540
7541 packet_reg *reg
7542 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7543 cached_reg_t cached_reg;
43ff13b4 7544
1f10ba14
PA
7545 if (reg == NULL)
7546 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7547Packet: '%s'\n"),
1f10ba14 7548 hex_string (pnum), p, buf);
c8e38a49 7549
1f10ba14 7550 cached_reg.num = reg->regnum;
d1dff226 7551 cached_reg.data = (gdb_byte *)
5cd63fda 7552 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7553
1f10ba14
PA
7554 p = p1 + 1;
7555 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7556 register_size (event->arch, reg->regnum));
1f10ba14 7557 p += 2 * fieldsize;
5cd63fda 7558 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7559 warning (_("Remote reply is too short: %s"), buf);
74531fed 7560
1f10ba14
PA
7561 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7562 }
7563 else
7564 {
7565 /* Not a number. Silently skip unknown optional
7566 info. */
8424cc97 7567 p = strchrnul (p1 + 1, ';');
1f10ba14 7568 }
cea39f65 7569 }
c8e38a49 7570
cea39f65
MS
7571 if (*p != ';')
7572 error (_("Remote register badly formatted: %s\nhere: %s"),
7573 buf, p);
7574 ++p;
7575 }
5b5596ff
PA
7576
7577 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7578 break;
7579
c8e38a49
PA
7580 /* fall through */
7581 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7582 {
7583 int sig;
7584
7585 event->ws.kind = TARGET_WAITKIND_STOPPED;
7586 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7587 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7588 event->ws.value.sig = (enum gdb_signal) sig;
7589 else
7590 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7591 }
c8e38a49 7592 break;
65706a29
PA
7593 case 'w': /* Thread exited. */
7594 {
256642e8 7595 const char *p;
65706a29
PA
7596 ULONGEST value;
7597
7598 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7599 p = unpack_varlen_hex (&buf[1], &value);
7600 event->ws.value.integer = value;
7601 if (*p != ';')
7602 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7603 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7604 break;
7605 }
c8e38a49
PA
7606 case 'W': /* Target exited. */
7607 case 'X':
7608 {
256642e8 7609 const char *p;
c8e38a49
PA
7610 int pid;
7611 ULONGEST value;
82f73884 7612
c8e38a49
PA
7613 /* GDB used to accept only 2 hex chars here. Stubs should
7614 only send more if they detect GDB supports multi-process
7615 support. */
7616 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7617
c8e38a49
PA
7618 if (buf[0] == 'W')
7619 {
7620 /* The remote process exited. */
74531fed
PA
7621 event->ws.kind = TARGET_WAITKIND_EXITED;
7622 event->ws.value.integer = value;
c8e38a49
PA
7623 }
7624 else
7625 {
7626 /* The remote process exited with a signal. */
74531fed 7627 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7628 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7629 event->ws.value.sig = (enum gdb_signal) value;
7630 else
7631 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7632 }
82f73884 7633
c8e38a49
PA
7634 /* If no process is specified, assume inferior_ptid. */
7635 pid = ptid_get_pid (inferior_ptid);
7636 if (*p == '\0')
7637 ;
7638 else if (*p == ';')
7639 {
7640 p++;
7641
0b24eb2d 7642 if (*p == '\0')
82f73884 7643 ;
61012eef 7644 else if (startswith (p, "process:"))
82f73884 7645 {
c8e38a49 7646 ULONGEST upid;
a744cf53 7647
c8e38a49
PA
7648 p += sizeof ("process:") - 1;
7649 unpack_varlen_hex (p, &upid);
7650 pid = upid;
82f73884
PA
7651 }
7652 else
7653 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7654 }
c8e38a49
PA
7655 else
7656 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
7657 event->ptid = pid_to_ptid (pid);
7658 }
7659 break;
f2faf941
PA
7660 case 'N':
7661 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7662 event->ptid = minus_one_ptid;
7663 break;
74531fed
PA
7664 }
7665
6efcd9a8 7666 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
7667 error (_("No process or thread specified in stop reply: %s"), buf);
7668}
7669
722247f1
YQ
7670/* When the stub wants to tell GDB about a new notification reply, it
7671 sends a notification (%Stop, for example). Those can come it at
7672 any time, hence, we have to make sure that any pending
7673 putpkt/getpkt sequence we're making is finished, before querying
7674 the stub for more events with the corresponding ack command
7675 (vStopped, for example). E.g., if we started a vStopped sequence
7676 immediately upon receiving the notification, something like this
7677 could happen:
74531fed
PA
7678
7679 1.1) --> Hg 1
7680 1.2) <-- OK
7681 1.3) --> g
7682 1.4) <-- %Stop
7683 1.5) --> vStopped
7684 1.6) <-- (registers reply to step #1.3)
7685
7686 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7687 query.
7688
796cb314 7689 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7690 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7691 doing whatever we were doing:
7692
7693 2.1) --> Hg 1
7694 2.2) <-- OK
7695 2.3) --> g
7696 2.4) <-- %Stop
7697 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7698 2.5) <-- (registers reply to step #2.3)
7699
7700 Eventualy after step #2.5, we return to the event loop, which
7701 notices there's an event on the
7702 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7703 associated callback --- the function below. At this point, we're
7704 always safe to start a vStopped sequence. :
7705
7706 2.6) --> vStopped
7707 2.7) <-- T05 thread:2
7708 2.8) --> vStopped
7709 2.9) --> OK
7710*/
7711
722247f1 7712void
6b8edb51 7713remote_target::remote_notif_get_pending_events (notif_client *nc)
74531fed
PA
7714{
7715 struct remote_state *rs = get_remote_state ();
74531fed 7716
f48ff2a7 7717 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7718 {
722247f1
YQ
7719 if (notif_debug)
7720 fprintf_unfiltered (gdb_stdlog,
7721 "notif: process: '%s' ack pending event\n",
7722 nc->name);
74531fed 7723
722247f1 7724 /* acknowledge */
6b8edb51 7725 nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
f48ff2a7 7726 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7727
7728 while (1)
7729 {
7730 getpkt (&rs->buf, &rs->buf_size, 0);
7731 if (strcmp (rs->buf, "OK") == 0)
7732 break;
7733 else
6b8edb51 7734 remote_notif_ack (this, nc, rs->buf);
74531fed
PA
7735 }
7736 }
722247f1
YQ
7737 else
7738 {
7739 if (notif_debug)
7740 fprintf_unfiltered (gdb_stdlog,
7741 "notif: process: '%s' no pending reply\n",
7742 nc->name);
7743 }
74531fed
PA
7744}
7745
6b8edb51
PA
7746/* Wrapper around remote_target::remote_notif_get_pending_events to
7747 avoid having to export the whole remote_target class. */
7748
7749void
7750remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7751{
7752 remote->remote_notif_get_pending_events (nc);
7753}
7754
74531fed
PA
7755/* Called when it is decided that STOP_REPLY holds the info of the
7756 event that is to be returned to the core. This function always
7757 destroys STOP_REPLY. */
7758
6b8edb51
PA
7759ptid_t
7760remote_target::process_stop_reply (struct stop_reply *stop_reply,
7761 struct target_waitstatus *status)
74531fed
PA
7762{
7763 ptid_t ptid;
7764
7765 *status = stop_reply->ws;
7766 ptid = stop_reply->ptid;
7767
7768 /* If no thread/process was reported by the stub, assume the current
7769 inferior. */
7770 if (ptid_equal (ptid, null_ptid))
7771 ptid = inferior_ptid;
7772
5f3563ea 7773 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7774 && status->kind != TARGET_WAITKIND_SIGNALLED
7775 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7776 {
5f3563ea
PA
7777 /* Expedited registers. */
7778 if (stop_reply->regcache)
7779 {
217f1f79 7780 struct regcache *regcache
5cd63fda 7781 = get_thread_arch_regcache (ptid, stop_reply->arch);
5f3563ea
PA
7782 cached_reg_t *reg;
7783 int ix;
7784
7785 for (ix = 0;
d1dff226 7786 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
5f3563ea 7787 ix++)
d1dff226 7788 {
217f1f79 7789 regcache_raw_supply (regcache, reg->num, reg->data);
d1dff226
AH
7790 xfree (reg->data);
7791 }
7792
5f3563ea
PA
7793 VEC_free (cached_reg_t, stop_reply->regcache);
7794 }
74531fed 7795
1941c569 7796 remote_notice_new_inferior (ptid, 0);
7aabaf9d 7797 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
799a2abe
PA
7798 remote_thr->core = stop_reply->core;
7799 remote_thr->stop_reason = stop_reply->stop_reason;
7800 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7801 remote_thr->vcont_resumed = 0;
74531fed
PA
7802 }
7803
74531fed
PA
7804 stop_reply_xfree (stop_reply);
7805 return ptid;
7806}
7807
7808/* The non-stop mode version of target_wait. */
7809
6b8edb51
PA
7810ptid_t
7811remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7812{
7813 struct remote_state *rs = get_remote_state ();
74531fed
PA
7814 struct stop_reply *stop_reply;
7815 int ret;
fee9eda9 7816 int is_notif = 0;
74531fed
PA
7817
7818 /* If in non-stop mode, get out of getpkt even if a
7819 notification is received. */
7820
7821 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7822 0 /* forever */, &is_notif);
74531fed
PA
7823 while (1)
7824 {
fee9eda9 7825 if (ret != -1 && !is_notif)
74531fed
PA
7826 switch (rs->buf[0])
7827 {
7828 case 'E': /* Error of some sort. */
7829 /* We're out of sync with the target now. Did it continue
7830 or not? We can't tell which thread it was in non-stop,
7831 so just ignore this. */
7832 warning (_("Remote failure reply: %s"), rs->buf);
7833 break;
7834 case 'O': /* Console output. */
7835 remote_console_output (rs->buf + 1);
7836 break;
7837 default:
7838 warning (_("Invalid remote reply: %s"), rs->buf);
7839 break;
7840 }
7841
7842 /* Acknowledge a pending stop reply that may have arrived in the
7843 mean time. */
f48ff2a7 7844 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7845 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7846
7847 /* If indeed we noticed a stop reply, we're done. */
7848 stop_reply = queued_stop_reply (ptid);
7849 if (stop_reply != NULL)
7850 return process_stop_reply (stop_reply, status);
7851
47608cb1 7852 /* Still no event. If we're just polling for an event, then
74531fed 7853 return to the event loop. */
47608cb1 7854 if (options & TARGET_WNOHANG)
74531fed
PA
7855 {
7856 status->kind = TARGET_WAITKIND_IGNORE;
7857 return minus_one_ptid;
7858 }
7859
47608cb1 7860 /* Otherwise do a blocking wait. */
74531fed 7861 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7862 1 /* forever */, &is_notif);
74531fed
PA
7863 }
7864}
7865
7866/* Wait until the remote machine stops, then return, storing status in
7867 STATUS just as `wait' would. */
7868
6b8edb51
PA
7869ptid_t
7870remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
74531fed
PA
7871{
7872 struct remote_state *rs = get_remote_state ();
74531fed 7873 ptid_t event_ptid = null_ptid;
cea39f65 7874 char *buf;
74531fed
PA
7875 struct stop_reply *stop_reply;
7876
47608cb1
PA
7877 again:
7878
74531fed
PA
7879 status->kind = TARGET_WAITKIND_IGNORE;
7880 status->value.integer = 0;
7881
7882 stop_reply = queued_stop_reply (ptid);
7883 if (stop_reply != NULL)
7884 return process_stop_reply (stop_reply, status);
7885
7886 if (rs->cached_wait_status)
7887 /* Use the cached wait status, but only once. */
7888 rs->cached_wait_status = 0;
7889 else
7890 {
7891 int ret;
722247f1 7892 int is_notif;
567420d1 7893 int forever = ((options & TARGET_WNOHANG) == 0
6b8edb51 7894 && rs->wait_forever_enabled_p);
567420d1
PA
7895
7896 if (!rs->waiting_for_stop_reply)
7897 {
7898 status->kind = TARGET_WAITKIND_NO_RESUMED;
7899 return minus_one_ptid;
7900 }
74531fed 7901
74531fed
PA
7902 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7903 _never_ wait for ever -> test on target_is_async_p().
7904 However, before we do that we need to ensure that the caller
7905 knows how to take the target into/out of async mode. */
722247f1 7906 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 7907 forever, &is_notif);
722247f1
YQ
7908
7909 /* GDB gets a notification. Return to core as this event is
7910 not interesting. */
7911 if (ret != -1 && is_notif)
7912 return minus_one_ptid;
567420d1
PA
7913
7914 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7915 return minus_one_ptid;
74531fed
PA
7916 }
7917
7918 buf = rs->buf;
7919
3a29589a
DJ
7920 /* Assume that the target has acknowledged Ctrl-C unless we receive
7921 an 'F' or 'O' packet. */
7922 if (buf[0] != 'F' && buf[0] != 'O')
7923 rs->ctrlc_pending_p = 0;
7924
74531fed
PA
7925 switch (buf[0])
7926 {
7927 case 'E': /* Error of some sort. */
7928 /* We're out of sync with the target now. Did it continue or
7929 not? Not is more likely, so report a stop. */
29090fb6
LM
7930 rs->waiting_for_stop_reply = 0;
7931
74531fed
PA
7932 warning (_("Remote failure reply: %s"), buf);
7933 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7934 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7935 break;
7936 case 'F': /* File-I/O request. */
e42e5352
YQ
7937 /* GDB may access the inferior memory while handling the File-I/O
7938 request, but we don't want GDB accessing memory while waiting
7939 for a stop reply. See the comments in putpkt_binary. Set
7940 waiting_for_stop_reply to 0 temporarily. */
7941 rs->waiting_for_stop_reply = 0;
6b8edb51 7942 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
3a29589a 7943 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7944 /* GDB handled the File-I/O request, and the target is running
7945 again. Keep waiting for events. */
7946 rs->waiting_for_stop_reply = 1;
74531fed 7947 break;
f2faf941 7948 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7949 {
29090fb6
LM
7950 struct stop_reply *stop_reply;
7951
7952 /* There is a stop reply to handle. */
7953 rs->waiting_for_stop_reply = 0;
7954
7955 stop_reply
6b8edb51
PA
7956 = (struct stop_reply *) remote_notif_parse (this,
7957 &notif_client_stop,
722247f1 7958 rs->buf);
74531fed 7959
74531fed 7960 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7961 break;
7962 }
7963 case 'O': /* Console output. */
7964 remote_console_output (buf + 1);
c8e38a49
PA
7965 break;
7966 case '\0':
b73be471 7967 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7968 {
7969 /* Zero length reply means that we tried 'S' or 'C' and the
7970 remote system doesn't support it. */
223ffa71 7971 target_terminal::ours_for_output ();
c8e38a49
PA
7972 printf_filtered
7973 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7974 gdb_signal_to_name (rs->last_sent_signal));
7975 rs->last_sent_signal = GDB_SIGNAL_0;
223ffa71 7976 target_terminal::inferior ();
c8e38a49 7977
f5c4fcd9
TT
7978 strcpy (buf, rs->last_sent_step ? "s" : "c");
7979 putpkt (buf);
c8e38a49 7980 break;
43ff13b4 7981 }
86a73007 7982 /* fallthrough */
c8e38a49
PA
7983 default:
7984 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7985 break;
43ff13b4 7986 }
c8e38a49 7987
f2faf941
PA
7988 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7989 return minus_one_ptid;
7990 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7991 {
7992 /* Nothing interesting happened. If we're doing a non-blocking
7993 poll, we're done. Otherwise, go back to waiting. */
7994 if (options & TARGET_WNOHANG)
7995 return minus_one_ptid;
7996 else
7997 goto again;
7998 }
74531fed
PA
7999 else if (status->kind != TARGET_WAITKIND_EXITED
8000 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
8001 {
8002 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 8003 record_currthread (rs, event_ptid);
82f73884
PA
8004 else
8005 event_ptid = inferior_ptid;
43ff13b4 8006 }
74531fed
PA
8007 else
8008 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 8009 record_currthread (rs, minus_one_ptid);
79d7f229 8010
82f73884 8011 return event_ptid;
43ff13b4
JM
8012}
8013
74531fed
PA
8014/* Wait until the remote machine stops, then return, storing status in
8015 STATUS just as `wait' would. */
8016
f6ac5f3d
PA
8017ptid_t
8018remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
8019{
8020 ptid_t event_ptid;
8021
6efcd9a8 8022 if (target_is_non_stop_p ())
6b8edb51 8023 event_ptid = wait_ns (ptid, status, options);
74531fed 8024 else
6b8edb51 8025 event_ptid = wait_as (ptid, status, options);
c8e38a49 8026
d9d41e78 8027 if (target_is_async_p ())
c8e38a49 8028 {
6b8edb51
PA
8029 remote_state *rs = get_remote_state ();
8030
74531fed
PA
8031 /* If there are are events left in the queue tell the event loop
8032 to return here. */
6b8edb51
PA
8033 if (!QUEUE_is_empty (stop_reply_p, rs->stop_reply_queue))
8034 mark_async_event_handler (rs->remote_async_inferior_event_token);
c8e38a49 8035 }
c8e38a49
PA
8036
8037 return event_ptid;
8038}
8039
74ca34ce 8040/* Fetch a single register using a 'p' packet. */
c906108c 8041
6b8edb51
PA
8042int
8043remote_target::fetch_register_using_p (struct regcache *regcache,
8044 packet_reg *reg)
b96ec7ac 8045{
ac7936df 8046 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 8047 struct remote_state *rs = get_remote_state ();
2e9f7625 8048 char *buf, *p;
9890e433 8049 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
8050 int i;
8051
4082afcc 8052 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
8053 return 0;
8054
8055 if (reg->pnum == -1)
8056 return 0;
8057
2e9f7625 8058 p = rs->buf;
fcad0fa4 8059 *p++ = 'p';
74ca34ce 8060 p += hexnumstr (p, reg->pnum);
fcad0fa4 8061 *p++ = '\0';
1f4437a4
MS
8062 putpkt (rs->buf);
8063 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 8064
2e9f7625
DJ
8065 buf = rs->buf;
8066
74ca34ce
DJ
8067 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
8068 {
8069 case PACKET_OK:
8070 break;
8071 case PACKET_UNKNOWN:
8072 return 0;
8073 case PACKET_ERROR:
27a9c0bf 8074 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 8075 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
8076 reg->regnum),
8077 buf);
74ca34ce 8078 }
3f9a994c
JB
8079
8080 /* If this register is unfetchable, tell the regcache. */
8081 if (buf[0] == 'x')
8480adf2 8082 {
56be3814 8083 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 8084 return 1;
b96ec7ac 8085 }
b96ec7ac 8086
3f9a994c
JB
8087 /* Otherwise, parse and supply the value. */
8088 p = buf;
8089 i = 0;
8090 while (p[0] != 0)
8091 {
8092 if (p[1] == 0)
74ca34ce 8093 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
8094
8095 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8096 p += 2;
8097 }
56be3814 8098 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 8099 return 1;
b96ec7ac
AC
8100}
8101
74ca34ce
DJ
8102/* Fetch the registers included in the target's 'g' packet. */
8103
6b8edb51
PA
8104int
8105remote_target::send_g_packet ()
c906108c 8106{
d01949b6 8107 struct remote_state *rs = get_remote_state ();
cea39f65 8108 int buf_len;
c906108c 8109
bba74b36 8110 xsnprintf (rs->buf, get_remote_packet_size (), "g");
b75abf5b
AK
8111 putpkt (rs->buf);
8112 getpkt (&rs->buf, &rs->buf_size, 0);
8113 if (packet_check_result (rs->buf) == PACKET_ERROR)
8114 error (_("Could not read registers; remote failure reply '%s'"),
8115 rs->buf);
c906108c 8116
29709017
DJ
8117 /* We can get out of synch in various cases. If the first character
8118 in the buffer is not a hex character, assume that has happened
8119 and try to fetch another packet to read. */
8120 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8121 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8122 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8123 && rs->buf[0] != 'x') /* New: unavailable register value. */
8124 {
8125 if (remote_debug)
8126 fprintf_unfiltered (gdb_stdlog,
8127 "Bad register packet; fetching a new packet\n");
8128 getpkt (&rs->buf, &rs->buf_size, 0);
8129 }
8130
74ca34ce
DJ
8131 buf_len = strlen (rs->buf);
8132
8133 /* Sanity check the received packet. */
8134 if (buf_len % 2 != 0)
8135 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
8136
8137 return buf_len / 2;
8138}
8139
6b8edb51
PA
8140void
8141remote_target::process_g_packet (struct regcache *regcache)
29709017 8142{
ac7936df 8143 struct gdbarch *gdbarch = regcache->arch ();
29709017 8144 struct remote_state *rs = get_remote_state ();
9d6eea31 8145 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8146 int i, buf_len;
8147 char *p;
8148 char *regs;
8149
8150 buf_len = strlen (rs->buf);
8151
8152 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8153 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827
SM
8154 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8155 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
74ca34ce
DJ
8156
8157 /* Save the size of the packet sent to us by the target. It is used
8158 as a heuristic when determining the max size of packets that the
8159 target can safely receive. */
8160 if (rsa->actual_register_packet_size == 0)
8161 rsa->actual_register_packet_size = buf_len;
8162
8163 /* If this is smaller than we guessed the 'g' packet would be,
8164 update our records. A 'g' reply that doesn't include a register's
8165 value implies either that the register is not available, or that
8166 the 'p' packet must be used. */
8167 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8168 {
9dc193c3 8169 long sizeof_g_packet = buf_len / 2;
74ca34ce 8170
4a22f64d 8171 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8172 {
9dc193c3
LF
8173 long offset = rsa->regs[i].offset;
8174 long reg_size = register_size (gdbarch, i);
8175
74ca34ce
DJ
8176 if (rsa->regs[i].pnum == -1)
8177 continue;
8178
9dc193c3 8179 if (offset >= sizeof_g_packet)
74ca34ce 8180 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8181 else if (offset + reg_size > sizeof_g_packet)
8182 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8183 else
74ca34ce 8184 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8185 }
9dc193c3
LF
8186
8187 /* Looks valid enough, we can assume this is the correct length
8188 for a 'g' packet. It's important not to adjust
8189 rsa->sizeof_g_packet if we have truncated registers otherwise
8190 this "if" won't be run the next time the method is called
8191 with a packet of the same size and one of the internal errors
8192 below will trigger instead. */
8193 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8194 }
b323314b 8195
224c3ddb 8196 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8197
8198 /* Unimplemented registers read as all bits zero. */
ea9c271d 8199 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8200
c906108c
SS
8201 /* Reply describes registers byte by byte, each byte encoded as two
8202 hex characters. Suck them all up, then supply them to the
8203 register cacheing/storage mechanism. */
8204
74ca34ce 8205 p = rs->buf;
ea9c271d 8206 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8207 {
74ca34ce
DJ
8208 if (p[0] == 0 || p[1] == 0)
8209 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8210 internal_error (__FILE__, __LINE__,
9b20d036 8211 _("unexpected end of 'g' packet reply"));
74ca34ce 8212
c906108c 8213 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8214 regs[i] = 0; /* 'x' */
c906108c
SS
8215 else
8216 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8217 p += 2;
8218 }
8219
a744cf53
MS
8220 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8221 {
8222 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8223 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8224
8225 if (r->in_g_packet)
8226 {
9dc193c3 8227 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
a744cf53
MS
8228 /* This shouldn't happen - we adjusted in_g_packet above. */
8229 internal_error (__FILE__, __LINE__,
9b20d036 8230 _("unexpected end of 'g' packet reply"));
a744cf53
MS
8231 else if (rs->buf[r->offset * 2] == 'x')
8232 {
8233 gdb_assert (r->offset * 2 < strlen (rs->buf));
8234 /* The register isn't available, mark it as such (at
8235 the same time setting the value to zero). */
8236 regcache_raw_supply (regcache, r->regnum, NULL);
8237 }
8238 else
8239 regcache_raw_supply (regcache, r->regnum,
8240 regs + r->offset);
8241 }
8242 }
c906108c
SS
8243}
8244
6b8edb51
PA
8245void
8246remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8247{
8248 send_g_packet ();
56be3814 8249 process_g_packet (regcache);
29709017
DJ
8250}
8251
e6e4e701
PA
8252/* Make the remote selected traceframe match GDB's selected
8253 traceframe. */
8254
6b8edb51
PA
8255void
8256remote_target::set_remote_traceframe ()
e6e4e701
PA
8257{
8258 int newnum;
262e1174 8259 struct remote_state *rs = get_remote_state ();
e6e4e701 8260
262e1174 8261 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8262 return;
8263
8264 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8265 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8266
8267 newnum = target_trace_find (tfind_number,
8268 get_traceframe_number (), 0, 0, NULL);
8269
8270 /* Should not happen. If it does, all bets are off. */
8271 if (newnum != get_traceframe_number ())
8272 warning (_("could not set remote traceframe"));
8273}
8274
f6ac5f3d
PA
8275void
8276remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8277{
ac7936df 8278 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8279 struct remote_state *rs = get_remote_state ();
8280 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8281 int i;
8282
e6e4e701 8283 set_remote_traceframe ();
222312d3 8284 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8285
8286 if (regnum >= 0)
8287 {
5cd63fda 8288 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8289
74ca34ce
DJ
8290 gdb_assert (reg != NULL);
8291
8292 /* If this register might be in the 'g' packet, try that first -
8293 we are likely to read more than one register. If this is the
8294 first 'g' packet, we might be overly optimistic about its
8295 contents, so fall back to 'p'. */
8296 if (reg->in_g_packet)
8297 {
56be3814 8298 fetch_registers_using_g (regcache);
74ca34ce
DJ
8299 if (reg->in_g_packet)
8300 return;
8301 }
8302
56be3814 8303 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8304 return;
8305
8306 /* This register is not available. */
56be3814 8307 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
8308
8309 return;
8310 }
8311
56be3814 8312 fetch_registers_using_g (regcache);
74ca34ce 8313
5cd63fda 8314 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8315 if (!rsa->regs[i].in_g_packet)
56be3814 8316 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8317 {
8318 /* This register is not available. */
56be3814 8319 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
8320 }
8321}
8322
c906108c
SS
8323/* Prepare to store registers. Since we may send them all (using a
8324 'G' request), we have to read out the ones we don't want to change
8325 first. */
8326
f6ac5f3d
PA
8327void
8328remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8329{
9d6eea31
PA
8330 struct remote_state *rs = get_remote_state ();
8331 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8332 int i;
cf0e1e0d 8333
c906108c 8334 /* Make sure the entire registers array is valid. */
4082afcc 8335 switch (packet_support (PACKET_P))
5a2468f5
JM
8336 {
8337 case PACKET_DISABLE:
8338 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8339 /* Make sure all the necessary registers are cached. */
ac7936df 8340 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8341 if (rsa->regs[i].in_g_packet)
0b47d985 8342 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
8343 break;
8344 case PACKET_ENABLE:
8345 break;
8346 }
8347}
8348
ad10f812 8349/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8350 packet was not recognized. */
5a2468f5 8351
6b8edb51
PA
8352int
8353remote_target::store_register_using_P (const struct regcache *regcache,
8354 packet_reg *reg)
5a2468f5 8355{
ac7936df 8356 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8357 struct remote_state *rs = get_remote_state ();
5a2468f5 8358 /* Try storing a single register. */
6d820c5c 8359 char *buf = rs->buf;
9890e433 8360 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8361 char *p;
5a2468f5 8362
4082afcc 8363 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8364 return 0;
8365
8366 if (reg->pnum == -1)
8367 return 0;
8368
ea9c271d 8369 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8370 p = buf + strlen (buf);
56be3814 8371 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 8372 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
8373 putpkt (rs->buf);
8374 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 8375
74ca34ce
DJ
8376 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8377 {
8378 case PACKET_OK:
8379 return 1;
8380 case PACKET_ERROR:
27a9c0bf
MS
8381 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8382 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
8383 case PACKET_UNKNOWN:
8384 return 0;
8385 default:
8386 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8387 }
c906108c
SS
8388}
8389
23860348
MS
8390/* Store register REGNUM, or all registers if REGNUM == -1, from the
8391 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8392
6b8edb51
PA
8393void
8394remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8395{
d01949b6 8396 struct remote_state *rs = get_remote_state ();
9d6eea31 8397 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8398 gdb_byte *regs;
c906108c
SS
8399 char *p;
8400
193cb69f
AC
8401 /* Extract all the registers in the regcache copying them into a
8402 local buffer. */
8403 {
b323314b 8404 int i;
a744cf53 8405
224c3ddb 8406 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8407 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8408 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8409 {
ea9c271d 8410 struct packet_reg *r = &rsa->regs[i];
a744cf53 8411
b323314b 8412 if (r->in_g_packet)
56be3814 8413 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
8414 }
8415 }
c906108c
SS
8416
8417 /* Command describes registers byte by byte,
8418 each byte encoded as two hex characters. */
6d820c5c 8419 p = rs->buf;
193cb69f 8420 *p++ = 'G';
74ca34ce 8421 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
8422 putpkt (rs->buf);
8423 getpkt (&rs->buf, &rs->buf_size, 0);
8424 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
8425 error (_("Could not write registers; remote failure reply '%s'"),
8426 rs->buf);
c906108c 8427}
74ca34ce
DJ
8428
8429/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8430 of the register cache buffer. FIXME: ignores errors. */
8431
f6ac5f3d
PA
8432void
8433remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8434{
5cd63fda 8435 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8436 struct remote_state *rs = get_remote_state ();
8437 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8438 int i;
8439
e6e4e701 8440 set_remote_traceframe ();
222312d3 8441 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8442
8443 if (regnum >= 0)
8444 {
5cd63fda 8445 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8446
74ca34ce
DJ
8447 gdb_assert (reg != NULL);
8448
8449 /* Always prefer to store registers using the 'P' packet if
8450 possible; we often change only a small number of registers.
8451 Sometimes we change a larger number; we'd need help from a
8452 higher layer to know to use 'G'. */
56be3814 8453 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8454 return;
8455
8456 /* For now, don't complain if we have no way to write the
8457 register. GDB loses track of unavailable registers too
8458 easily. Some day, this may be an error. We don't have
0df8b418 8459 any way to read the register, either... */
74ca34ce
DJ
8460 if (!reg->in_g_packet)
8461 return;
8462
56be3814 8463 store_registers_using_G (regcache);
74ca34ce
DJ
8464 return;
8465 }
8466
56be3814 8467 store_registers_using_G (regcache);
74ca34ce 8468
5cd63fda 8469 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8470 if (!rsa->regs[i].in_g_packet)
56be3814 8471 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8472 /* See above for why we do not issue an error here. */
8473 continue;
8474}
c906108c
SS
8475\f
8476
8477/* Return the number of hex digits in num. */
8478
8479static int
fba45db2 8480hexnumlen (ULONGEST num)
c906108c
SS
8481{
8482 int i;
8483
8484 for (i = 0; num != 0; i++)
8485 num >>= 4;
8486
325fac50 8487 return std::max (i, 1);
c906108c
SS
8488}
8489
2df3850c 8490/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8491
8492static int
fba45db2 8493hexnumstr (char *buf, ULONGEST num)
c906108c 8494{
c906108c 8495 int len = hexnumlen (num);
a744cf53 8496
2df3850c
JM
8497 return hexnumnstr (buf, num, len);
8498}
8499
c906108c 8500
2df3850c 8501/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8502
2df3850c 8503static int
fba45db2 8504hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8505{
8506 int i;
8507
8508 buf[width] = '\0';
8509
8510 for (i = width - 1; i >= 0; i--)
c906108c 8511 {
c5aa993b 8512 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8513 num >>= 4;
8514 }
8515
2df3850c 8516 return width;
c906108c
SS
8517}
8518
23860348 8519/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8520
8521static CORE_ADDR
fba45db2 8522remote_address_masked (CORE_ADDR addr)
c906108c 8523{
883b9c6c 8524 unsigned int address_size = remote_address_size;
a744cf53 8525
911c95a5
UW
8526 /* If "remoteaddresssize" was not set, default to target address size. */
8527 if (!address_size)
f5656ead 8528 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8529
8530 if (address_size > 0
8531 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8532 {
8533 /* Only create a mask when that mask can safely be constructed
23860348 8534 in a ULONGEST variable. */
c906108c 8535 ULONGEST mask = 1;
a744cf53 8536
911c95a5 8537 mask = (mask << address_size) - 1;
c906108c
SS
8538 addr &= mask;
8539 }
8540 return addr;
8541}
8542
8543/* Determine whether the remote target supports binary downloading.
8544 This is accomplished by sending a no-op memory write of zero length
8545 to the target at the specified address. It does not suffice to send
23860348
MS
8546 the whole packet, since many stubs strip the eighth bit and
8547 subsequently compute a wrong checksum, which causes real havoc with
8548 remote_write_bytes.
7a292a7a 8549
96baa820 8550 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8551 clean. In cases like this, the user should clear "remote
23860348 8552 X-packet". */
96baa820 8553
6b8edb51
PA
8554void
8555remote_target::check_binary_download (CORE_ADDR addr)
c906108c 8556{
d01949b6 8557 struct remote_state *rs = get_remote_state ();
24b06219 8558
4082afcc 8559 switch (packet_support (PACKET_X))
c906108c 8560 {
96baa820
JM
8561 case PACKET_DISABLE:
8562 break;
8563 case PACKET_ENABLE:
8564 break;
8565 case PACKET_SUPPORT_UNKNOWN:
8566 {
96baa820 8567 char *p;
802188a7 8568
2e9f7625 8569 p = rs->buf;
96baa820
JM
8570 *p++ = 'X';
8571 p += hexnumstr (p, (ULONGEST) addr);
8572 *p++ = ',';
8573 p += hexnumstr (p, (ULONGEST) 0);
8574 *p++ = ':';
8575 *p = '\0';
802188a7 8576
2e9f7625 8577 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8578 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8579
2e9f7625 8580 if (rs->buf[0] == '\0')
96baa820
JM
8581 {
8582 if (remote_debug)
8583 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8584 "binary downloading NOT "
8585 "supported by target\n");
444abaca 8586 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8587 }
8588 else
8589 {
8590 if (remote_debug)
8591 fprintf_unfiltered (gdb_stdlog,
64b9b334 8592 "binary downloading supported by target\n");
444abaca 8593 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8594 }
8595 break;
8596 }
c906108c
SS
8597 }
8598}
8599
124e13d9
SM
8600/* Helper function to resize the payload in order to try to get a good
8601 alignment. We try to write an amount of data such that the next write will
8602 start on an address aligned on REMOTE_ALIGN_WRITES. */
8603
8604static int
8605align_for_efficient_write (int todo, CORE_ADDR memaddr)
8606{
8607 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8608}
8609
c906108c
SS
8610/* Write memory data directly to the remote machine.
8611 This does not inform the data cache; the data cache uses this.
a76d924d 8612 HEADER is the starting part of the packet.
c906108c
SS
8613 MEMADDR is the address in the remote memory space.
8614 MYADDR is the address of the buffer in our space.
124e13d9
SM
8615 LEN_UNITS is the number of addressable units to write.
8616 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8617 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8618 should send data as binary ('X'), or hex-encoded ('M').
8619
8620 The function creates packet of the form
8621 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8622
124e13d9 8623 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8624
8625 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8626 are omitted.
8627
9b409511 8628 Return the transferred status, error or OK (an
124e13d9
SM
8629 'enum target_xfer_status' value). Save the number of addressable units
8630 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8631
8632 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8633 exchange between gdb and the stub could look like (?? in place of the
8634 checksum):
8635
8636 -> $m1000,4#??
8637 <- aaaabbbbccccdddd
8638
8639 -> $M1000,3:eeeeffffeeee#??
8640 <- OK
8641
8642 -> $m1000,4#??
8643 <- eeeeffffeeeedddd */
c906108c 8644
6b8edb51
PA
8645target_xfer_status
8646remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8647 const gdb_byte *myaddr,
8648 ULONGEST len_units,
8649 int unit_size,
8650 ULONGEST *xfered_len_units,
8651 char packet_format, int use_length)
c906108c 8652{
6d820c5c 8653 struct remote_state *rs = get_remote_state ();
cfd77fa1 8654 char *p;
a76d924d
DJ
8655 char *plen = NULL;
8656 int plenlen = 0;
124e13d9
SM
8657 int todo_units;
8658 int units_written;
8659 int payload_capacity_bytes;
8660 int payload_length_bytes;
a76d924d
DJ
8661
8662 if (packet_format != 'X' && packet_format != 'M')
8663 internal_error (__FILE__, __LINE__,
9b20d036 8664 _("remote_write_bytes_aux: bad packet format"));
c906108c 8665
124e13d9 8666 if (len_units == 0)
9b409511 8667 return TARGET_XFER_EOF;
b2182ed2 8668
124e13d9 8669 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8670
6d820c5c
DJ
8671 /* The packet buffer will be large enough for the payload;
8672 get_memory_packet_size ensures this. */
a76d924d 8673 rs->buf[0] = '\0';
c906108c 8674
a257b5bb 8675 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8676 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8677
124e13d9 8678 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8679 if (!use_length)
0df8b418 8680 /* The comma won't be used. */
124e13d9
SM
8681 payload_capacity_bytes += 1;
8682 payload_capacity_bytes -= strlen (header);
8683 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8684
a76d924d 8685 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8686
a76d924d
DJ
8687 strcat (rs->buf, header);
8688 p = rs->buf + strlen (header);
8689
8690 /* Compute a best guess of the number of bytes actually transfered. */
8691 if (packet_format == 'X')
c906108c 8692 {
23860348 8693 /* Best guess at number of bytes that will fit. */
325fac50
PA
8694 todo_units = std::min (len_units,
8695 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8696 if (use_length)
124e13d9 8697 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8698 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8699 }
8700 else
8701 {
124e13d9 8702 /* Number of bytes that will fit. */
325fac50
PA
8703 todo_units
8704 = std::min (len_units,
8705 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8706 if (use_length)
124e13d9 8707 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8708 todo_units = std::min (todo_units,
8709 (payload_capacity_bytes / unit_size) / 2);
917317f4 8710 }
a76d924d 8711
124e13d9 8712 if (todo_units <= 0)
3de11b2e 8713 internal_error (__FILE__, __LINE__,
405f8e94 8714 _("minimum packet size too small to write data"));
802188a7 8715
6765f3e5
DJ
8716 /* If we already need another packet, then try to align the end
8717 of this packet to a useful boundary. */
124e13d9
SM
8718 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8719 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8720
a257b5bb 8721 /* Append "<memaddr>". */
917317f4
JM
8722 memaddr = remote_address_masked (memaddr);
8723 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8724
a76d924d
DJ
8725 if (use_length)
8726 {
8727 /* Append ",". */
8728 *p++ = ',';
802188a7 8729
124e13d9
SM
8730 /* Append the length and retain its location and size. It may need to be
8731 adjusted once the packet body has been created. */
a76d924d 8732 plen = p;
124e13d9 8733 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8734 p += plenlen;
8735 }
a257b5bb
AC
8736
8737 /* Append ":". */
917317f4
JM
8738 *p++ = ':';
8739 *p = '\0';
802188a7 8740
a257b5bb 8741 /* Append the packet body. */
a76d924d 8742 if (packet_format == 'X')
917317f4 8743 {
917317f4
JM
8744 /* Binary mode. Send target system values byte by byte, in
8745 increasing byte addresses. Only escape certain critical
8746 characters. */
124e13d9
SM
8747 payload_length_bytes =
8748 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8749 &units_written, payload_capacity_bytes);
6765f3e5 8750
124e13d9 8751 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8752 a second try to keep the end of the packet aligned. Don't do
8753 this if the packet is tiny. */
124e13d9 8754 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8755 {
124e13d9
SM
8756 int new_todo_units;
8757
8758 new_todo_units = align_for_efficient_write (units_written, memaddr);
8759
8760 if (new_todo_units != units_written)
8761 payload_length_bytes =
8762 remote_escape_output (myaddr, new_todo_units, unit_size,
8763 (gdb_byte *) p, &units_written,
8764 payload_capacity_bytes);
6765f3e5
DJ
8765 }
8766
124e13d9
SM
8767 p += payload_length_bytes;
8768 if (use_length && units_written < todo_units)
c906108c 8769 {
802188a7 8770 /* Escape chars have filled up the buffer prematurely,
124e13d9 8771 and we have actually sent fewer units than planned.
917317f4
JM
8772 Fix-up the length field of the packet. Use the same
8773 number of characters as before. */
124e13d9
SM
8774 plen += hexnumnstr (plen, (ULONGEST) units_written,
8775 plenlen);
917317f4 8776 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8777 }
a76d924d
DJ
8778 }
8779 else
8780 {
917317f4
JM
8781 /* Normal mode: Send target system values byte by byte, in
8782 increasing byte addresses. Each byte is encoded as a two hex
8783 value. */
124e13d9
SM
8784 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8785 units_written = todo_units;
c906108c 8786 }
802188a7 8787
2e9f7625 8788 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8789 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8790
2e9f7625 8791 if (rs->buf[0] == 'E')
00d84524 8792 return TARGET_XFER_E_IO;
802188a7 8793
124e13d9
SM
8794 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8795 send fewer units than we'd planned. */
8796 *xfered_len_units = (ULONGEST) units_written;
92ffd475 8797 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
8798}
8799
a76d924d
DJ
8800/* Write memory data directly to the remote machine.
8801 This does not inform the data cache; the data cache uses this.
8802 MEMADDR is the address in the remote memory space.
8803 MYADDR is the address of the buffer in our space.
8804 LEN is the number of bytes.
8805
9b409511
YQ
8806 Return the transferred status, error or OK (an
8807 'enum target_xfer_status' value). Save the number of bytes
8808 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8809
6b8edb51
PA
8810target_xfer_status
8811remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8812 ULONGEST len, int unit_size,
8813 ULONGEST *xfered_len)
a76d924d 8814{
a121b7c1 8815 const char *packet_format = NULL;
a76d924d
DJ
8816
8817 /* Check whether the target supports binary download. */
8818 check_binary_download (memaddr);
8819
4082afcc 8820 switch (packet_support (PACKET_X))
a76d924d
DJ
8821 {
8822 case PACKET_ENABLE:
8823 packet_format = "X";
8824 break;
8825 case PACKET_DISABLE:
8826 packet_format = "M";
8827 break;
8828 case PACKET_SUPPORT_UNKNOWN:
8829 internal_error (__FILE__, __LINE__,
8830 _("remote_write_bytes: bad internal state"));
8831 default:
8832 internal_error (__FILE__, __LINE__, _("bad switch"));
8833 }
8834
8835 return remote_write_bytes_aux (packet_format,
124e13d9 8836 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8837 packet_format[0], 1);
a76d924d
DJ
8838}
8839
9217e74e
YQ
8840/* Read memory data directly from the remote machine.
8841 This does not use the data cache; the data cache uses this.
8842 MEMADDR is the address in the remote memory space.
8843 MYADDR is the address of the buffer in our space.
124e13d9
SM
8844 LEN_UNITS is the number of addressable memory units to read..
8845 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8846
8847 Return the transferred status, error or OK (an
8848 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8849 transferred in *XFERED_LEN_UNITS.
8850
8851 See the comment of remote_write_bytes_aux for an example of
8852 memory read/write exchange between gdb and the stub. */
9217e74e 8853
6b8edb51
PA
8854target_xfer_status
8855remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8856 ULONGEST len_units,
8857 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8858{
8859 struct remote_state *rs = get_remote_state ();
124e13d9 8860 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8861 char *p;
124e13d9
SM
8862 int todo_units;
8863 int decoded_bytes;
9217e74e 8864
124e13d9 8865 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8866 /* The packet buffer will be large enough for the payload;
8867 get_memory_packet_size ensures this. */
8868
124e13d9 8869 /* Number of units that will fit. */
325fac50
PA
8870 todo_units = std::min (len_units,
8871 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8872
8873 /* Construct "m"<memaddr>","<len>". */
8874 memaddr = remote_address_masked (memaddr);
8875 p = rs->buf;
8876 *p++ = 'm';
8877 p += hexnumstr (p, (ULONGEST) memaddr);
8878 *p++ = ',';
124e13d9 8879 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8880 *p = '\0';
8881 putpkt (rs->buf);
8882 getpkt (&rs->buf, &rs->buf_size, 0);
8883 if (rs->buf[0] == 'E'
8884 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8885 && rs->buf[3] == '\0')
8886 return TARGET_XFER_E_IO;
8887 /* Reply describes memory byte by byte, each byte encoded as two hex
8888 characters. */
8889 p = rs->buf;
124e13d9 8890 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8891 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8892 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 8893 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
8894}
8895
b55fbac4
YQ
8896/* Using the set of read-only target sections of remote, read live
8897 read-only memory.
8acf9577
YQ
8898
8899 For interface/parameters/return description see target.h,
8900 to_xfer_partial. */
8901
6b8edb51
PA
8902target_xfer_status
8903remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8904 ULONGEST memaddr,
8905 ULONGEST len,
8906 int unit_size,
8907 ULONGEST *xfered_len)
8acf9577
YQ
8908{
8909 struct target_section *secp;
8910 struct target_section_table *table;
8911
6b8edb51 8912 secp = target_section_by_addr (this, memaddr);
8acf9577
YQ
8913 if (secp != NULL
8914 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8915 secp->the_bfd_section)
8916 & SEC_READONLY))
8917 {
8918 struct target_section *p;
8919 ULONGEST memend = memaddr + len;
8920
6b8edb51 8921 table = target_get_section_table (this);
8acf9577
YQ
8922
8923 for (p = table->sections; p < table->sections_end; p++)
8924 {
8925 if (memaddr >= p->addr)
8926 {
8927 if (memend <= p->endaddr)
8928 {
8929 /* Entire transfer is within this section. */
124e13d9 8930 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8931 xfered_len);
8acf9577
YQ
8932 }
8933 else if (memaddr >= p->endaddr)
8934 {
8935 /* This section ends before the transfer starts. */
8936 continue;
8937 }
8938 else
8939 {
8940 /* This section overlaps the transfer. Just do half. */
8941 len = p->endaddr - memaddr;
124e13d9 8942 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8943 xfered_len);
8acf9577
YQ
8944 }
8945 }
8946 }
8947 }
8948
8949 return TARGET_XFER_EOF;
8950}
8951
9217e74e
YQ
8952/* Similar to remote_read_bytes_1, but it reads from the remote stub
8953 first if the requested memory is unavailable in traceframe.
8954 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8955
6b8edb51
PA
8956target_xfer_status
8957remote_target::remote_read_bytes (CORE_ADDR memaddr,
8958 gdb_byte *myaddr, ULONGEST len, int unit_size,
8959 ULONGEST *xfered_len)
c906108c 8960{
6b6aa828 8961 if (len == 0)
96c4f946 8962 return TARGET_XFER_EOF;
b2182ed2 8963
8acf9577
YQ
8964 if (get_traceframe_number () != -1)
8965 {
a79b1bc6 8966 std::vector<mem_range> available;
8acf9577
YQ
8967
8968 /* If we fail to get the set of available memory, then the
8969 target does not support querying traceframe info, and so we
8970 attempt reading from the traceframe anyway (assuming the
8971 target implements the old QTro packet then). */
8972 if (traceframe_available_memory (&available, memaddr, len))
8973 {
a79b1bc6 8974 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
8975 {
8976 enum target_xfer_status res;
8977
8978 /* Don't read into the traceframe's available
8979 memory. */
a79b1bc6 8980 if (!available.empty ())
8acf9577
YQ
8981 {
8982 LONGEST oldlen = len;
8983
a79b1bc6 8984 len = available[0].start - memaddr;
8acf9577
YQ
8985 gdb_assert (len <= oldlen);
8986 }
8987
8acf9577 8988 /* This goes through the topmost target again. */
6b8edb51 8989 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 8990 len, unit_size, xfered_len);
8acf9577
YQ
8991 if (res == TARGET_XFER_OK)
8992 return TARGET_XFER_OK;
8993 else
8994 {
8995 /* No use trying further, we know some memory starting
8996 at MEMADDR isn't available. */
8997 *xfered_len = len;
92ffd475
PC
8998 return (*xfered_len != 0) ?
8999 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
9000 }
9001 }
9002
9003 /* Don't try to read more than how much is available, in
9004 case the target implements the deprecated QTro packet to
9005 cater for older GDBs (the target's knowledge of read-only
9006 sections may be outdated by now). */
a79b1bc6 9007 len = available[0].length;
8acf9577
YQ
9008 }
9009 }
9010
124e13d9 9011 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 9012}
74531fed 9013
c906108c 9014\f
c906108c 9015
a76d924d
DJ
9016/* Sends a packet with content determined by the printf format string
9017 FORMAT and the remaining arguments, then gets the reply. Returns
9018 whether the packet was a success, a failure, or unknown. */
9019
6b8edb51
PA
9020packet_result
9021remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
9022{
9023 struct remote_state *rs = get_remote_state ();
9024 int max_size = get_remote_packet_size ();
a76d924d 9025 va_list ap;
a744cf53 9026
a76d924d
DJ
9027 va_start (ap, format);
9028
9029 rs->buf[0] = '\0';
9030 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 9031 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
9032
9033 if (putpkt (rs->buf) < 0)
9034 error (_("Communication problem with target."));
9035
9036 rs->buf[0] = '\0';
9037 getpkt (&rs->buf, &rs->buf_size, 0);
9038
9039 return packet_check_result (rs->buf);
9040}
9041
a76d924d
DJ
9042/* Flash writing can take quite some time. We'll set
9043 effectively infinite timeout for flash operations.
9044 In future, we'll need to decide on a better approach. */
9045static const int remote_flash_timeout = 1000;
9046
f6ac5f3d
PA
9047void
9048remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 9049{
f5656ead 9050 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 9051 enum packet_result ret;
2ec845e7
TT
9052 scoped_restore restore_timeout
9053 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
9054
9055 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 9056 phex (address, addr_size),
a76d924d
DJ
9057 phex (length, 4));
9058 switch (ret)
9059 {
9060 case PACKET_UNKNOWN:
9061 error (_("Remote target does not support flash erase"));
9062 case PACKET_ERROR:
9063 error (_("Error erasing flash with vFlashErase packet"));
9064 default:
9065 break;
9066 }
a76d924d
DJ
9067}
9068
6b8edb51
PA
9069target_xfer_status
9070remote_target::remote_flash_write (ULONGEST address,
9071 ULONGEST length, ULONGEST *xfered_len,
9072 const gdb_byte *data)
a76d924d 9073{
2ec845e7
TT
9074 scoped_restore restore_timeout
9075 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9076 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9077 xfered_len,'X', 0);
a76d924d
DJ
9078}
9079
f6ac5f3d
PA
9080void
9081remote_target::flash_done ()
a76d924d 9082{
a76d924d 9083 int ret;
a76d924d 9084
2ec845e7
TT
9085 scoped_restore restore_timeout
9086 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9087
a76d924d 9088 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
9089
9090 switch (ret)
9091 {
9092 case PACKET_UNKNOWN:
9093 error (_("Remote target does not support vFlashDone"));
9094 case PACKET_ERROR:
9095 error (_("Error finishing flash operation"));
9096 default:
9097 break;
9098 }
9099}
9100
f6ac5f3d
PA
9101void
9102remote_target::files_info ()
c906108c
SS
9103{
9104 puts_filtered ("Debugging a target over a serial line.\n");
9105}
9106\f
9107/* Stuff for dealing with the packets which are part of this protocol.
9108 See comment at top of file for details. */
9109
1927e618
PA
9110/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9111 error to higher layers. Called when a serial error is detected.
9112 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
9113 the system error message for errno at function entry and final dot
9114 for output compatibility with throw_perror_with_name. */
1927e618
PA
9115
9116static void
9117unpush_and_perror (const char *string)
9118{
d6cb50a2 9119 int saved_errno = errno;
1927e618
PA
9120
9121 remote_unpush_target ();
d6cb50a2
JK
9122 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9123 safe_strerror (saved_errno));
1927e618
PA
9124}
9125
048094ac
PA
9126/* Read a single character from the remote end. The current quit
9127 handler is overridden to avoid quitting in the middle of packet
9128 sequence, as that would break communication with the remote server.
9129 See remote_serial_quit_handler for more detail. */
c906108c 9130
6b8edb51
PA
9131int
9132remote_target::readchar (int timeout)
c906108c
SS
9133{
9134 int ch;
5d93a237 9135 struct remote_state *rs = get_remote_state ();
048094ac 9136
2ec845e7 9137 {
6b8edb51
PA
9138 scoped_restore restore_quit_target
9139 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9140 scoped_restore restore_quit
6b8edb51 9141 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9142
2ec845e7 9143 rs->got_ctrlc_during_io = 0;
c906108c 9144
2ec845e7 9145 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9146
2ec845e7
TT
9147 if (rs->got_ctrlc_during_io)
9148 set_quit_flag ();
9149 }
048094ac 9150
2acceee2 9151 if (ch >= 0)
0876f84a 9152 return ch;
2acceee2
JM
9153
9154 switch ((enum serial_rc) ch)
c906108c
SS
9155 {
9156 case SERIAL_EOF:
78a095c3 9157 remote_unpush_target ();
598d3636 9158 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9159 /* no return */
c906108c 9160 case SERIAL_ERROR:
1927e618
PA
9161 unpush_and_perror (_("Remote communication error. "
9162 "Target disconnected."));
2acceee2 9163 /* no return */
c906108c 9164 case SERIAL_TIMEOUT:
2acceee2 9165 break;
c906108c 9166 }
2acceee2 9167 return ch;
c906108c
SS
9168}
9169
c33e31fd 9170/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9171 writing fails. The current quit handler is overridden to avoid
9172 quitting in the middle of packet sequence, as that would break
9173 communication with the remote server. See
9174 remote_serial_quit_handler for more detail. */
c33e31fd 9175
6b8edb51
PA
9176void
9177remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9178{
5d93a237 9179 struct remote_state *rs = get_remote_state ();
048094ac 9180
6b8edb51
PA
9181 scoped_restore restore_quit_target
9182 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9183 scoped_restore restore_quit
6b8edb51 9184 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9185
9186 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9187
9188 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9189 {
1927e618
PA
9190 unpush_and_perror (_("Remote communication error. "
9191 "Target disconnected."));
c33e31fd 9192 }
048094ac
PA
9193
9194 if (rs->got_ctrlc_during_io)
9195 set_quit_flag ();
c33e31fd
PA
9196}
9197
b3ced9ba
PA
9198/* Return a string representing an escaped version of BUF, of len N.
9199 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9200
b3ced9ba 9201static std::string
6e5abd65
PA
9202escape_buffer (const char *buf, int n)
9203{
d7e74731 9204 string_file stb;
6e5abd65 9205
d7e74731
PA
9206 stb.putstrn (buf, n, '\\');
9207 return std::move (stb.string ());
6e5abd65
PA
9208}
9209
c906108c
SS
9210/* Display a null-terminated packet on stdout, for debugging, using C
9211 string notation. */
9212
9213static void
baa336ce 9214print_packet (const char *buf)
c906108c
SS
9215{
9216 puts_filtered ("\"");
43e526b9 9217 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
9218 puts_filtered ("\"");
9219}
9220
9221int
6b8edb51 9222remote_target::putpkt (const char *buf)
c906108c
SS
9223{
9224 return putpkt_binary (buf, strlen (buf));
9225}
9226
6b8edb51
PA
9227/* Wrapper around remote_target::putpkt to avoid exporting
9228 remote_target. */
9229
9230int
9231putpkt (remote_target *remote, const char *buf)
9232{
9233 return remote->putpkt (buf);
9234}
9235
c906108c 9236/* Send a packet to the remote machine, with error checking. The data
23860348 9237 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9238 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9239 and for a possible /0 if we are debugging (remote_debug) and want
9240 to print the sent packet as a string. */
c906108c 9241
6b8edb51
PA
9242int
9243remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9244{
2d717e4f 9245 struct remote_state *rs = get_remote_state ();
c906108c
SS
9246 int i;
9247 unsigned char csum = 0;
b80406ac
TT
9248 gdb::def_vector<char> data (cnt + 6);
9249 char *buf2 = data.data ();
085dd6e6 9250
c906108c
SS
9251 int ch;
9252 int tcount = 0;
9253 char *p;
9254
e24a49d8
PA
9255 /* Catch cases like trying to read memory or listing threads while
9256 we're waiting for a stop reply. The remote server wouldn't be
9257 ready to handle this request, so we'd hang and timeout. We don't
9258 have to worry about this in synchronous mode, because in that
9259 case it's not possible to issue a command while the target is
74531fed
PA
9260 running. This is not a problem in non-stop mode, because in that
9261 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9262 if (!target_is_non_stop_p ()
9263 && target_is_async_p ()
9264 && rs->waiting_for_stop_reply)
9597b22a
DE
9265 {
9266 error (_("Cannot execute this command while the target is running.\n"
9267 "Use the \"interrupt\" command to stop the target\n"
9268 "and then try again."));
9269 }
e24a49d8 9270
2d717e4f
DJ
9271 /* We're sending out a new packet. Make sure we don't look at a
9272 stale cached response. */
9273 rs->cached_wait_status = 0;
9274
c906108c
SS
9275 /* Copy the packet into buffer BUF2, encapsulating it
9276 and giving it a checksum. */
9277
c906108c
SS
9278 p = buf2;
9279 *p++ = '$';
9280
9281 for (i = 0; i < cnt; i++)
9282 {
9283 csum += buf[i];
9284 *p++ = buf[i];
9285 }
9286 *p++ = '#';
9287 *p++ = tohex ((csum >> 4) & 0xf);
9288 *p++ = tohex (csum & 0xf);
9289
9290 /* Send it over and over until we get a positive ack. */
9291
9292 while (1)
9293 {
9294 int started_error_output = 0;
9295
9296 if (remote_debug)
9297 {
9298 *p = '\0';
b3ced9ba 9299
6f8976bf
YQ
9300 int len = (int) (p - buf2);
9301
9302 std::string str
9303 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9304
9305 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9306
567a3e54
SM
9307 if (len > REMOTE_DEBUG_MAX_CHAR)
9308 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9309 len - REMOTE_DEBUG_MAX_CHAR);
6f8976bf
YQ
9310
9311 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 9312
0f71a2f6 9313 gdb_flush (gdb_stdlog);
c906108c 9314 }
c33e31fd 9315 remote_serial_write (buf2, p - buf2);
c906108c 9316
a6f3e723
SL
9317 /* If this is a no acks version of the remote protocol, send the
9318 packet and move on. */
9319 if (rs->noack_mode)
9320 break;
9321
74531fed
PA
9322 /* Read until either a timeout occurs (-2) or '+' is read.
9323 Handle any notification that arrives in the mean time. */
c906108c
SS
9324 while (1)
9325 {
9326 ch = readchar (remote_timeout);
9327
c5aa993b 9328 if (remote_debug)
c906108c
SS
9329 {
9330 switch (ch)
9331 {
9332 case '+':
1216fa2c 9333 case '-':
c906108c
SS
9334 case SERIAL_TIMEOUT:
9335 case '$':
74531fed 9336 case '%':
c906108c
SS
9337 if (started_error_output)
9338 {
9339 putchar_unfiltered ('\n');
9340 started_error_output = 0;
9341 }
9342 }
9343 }
9344
9345 switch (ch)
9346 {
9347 case '+':
9348 if (remote_debug)
0f71a2f6 9349 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 9350 return 1;
1216fa2c
AC
9351 case '-':
9352 if (remote_debug)
9353 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 9354 /* FALLTHROUGH */
c906108c 9355 case SERIAL_TIMEOUT:
c5aa993b 9356 tcount++;
c906108c 9357 if (tcount > 3)
b80406ac 9358 return 0;
23860348 9359 break; /* Retransmit buffer. */
c906108c
SS
9360 case '$':
9361 {
40e3f985 9362 if (remote_debug)
2bc416ba 9363 fprintf_unfiltered (gdb_stdlog,
23860348 9364 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
9365 /* It's probably an old response sent because an ACK
9366 was lost. Gobble up the packet and ack it so it
9367 doesn't get retransmitted when we resend this
9368 packet. */
6d820c5c 9369 skip_frame ();
c33e31fd 9370 remote_serial_write ("+", 1);
23860348 9371 continue; /* Now, go look for +. */
c906108c 9372 }
74531fed
PA
9373
9374 case '%':
9375 {
9376 int val;
9377
9378 /* If we got a notification, handle it, and go back to looking
9379 for an ack. */
9380 /* We've found the start of a notification. Now
9381 collect the data. */
9382 val = read_frame (&rs->buf, &rs->buf_size);
9383 if (val >= 0)
9384 {
9385 if (remote_debug)
9386 {
b3ced9ba 9387 std::string str = escape_buffer (rs->buf, val);
6e5abd65 9388
6e5abd65
PA
9389 fprintf_unfiltered (gdb_stdlog,
9390 " Notification received: %s\n",
b3ced9ba 9391 str.c_str ());
74531fed 9392 }
5965e028 9393 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
9394 /* We're in sync now, rewait for the ack. */
9395 tcount = 0;
9396 }
9397 else
9398 {
9399 if (remote_debug)
9400 {
9401 if (!started_error_output)
9402 {
9403 started_error_output = 1;
9404 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9405 }
9406 fputc_unfiltered (ch & 0177, gdb_stdlog);
9407 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9408 }
9409 }
9410 continue;
9411 }
9412 /* fall-through */
c906108c
SS
9413 default:
9414 if (remote_debug)
9415 {
9416 if (!started_error_output)
9417 {
9418 started_error_output = 1;
0f71a2f6 9419 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 9420 }
0f71a2f6 9421 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
9422 }
9423 continue;
9424 }
23860348 9425 break; /* Here to retransmit. */
c906108c
SS
9426 }
9427
9428#if 0
9429 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
9430 able to get out next time we call QUIT, without anything as
9431 violent as interrupt_query. If we want to provide a way out of
9432 here without getting to the next QUIT, it should be based on
9433 hitting ^C twice as in remote_wait. */
c906108c
SS
9434 if (quit_flag)
9435 {
9436 quit_flag = 0;
9437 interrupt_query ();
9438 }
9439#endif
9440 }
a5c0808e 9441
a6f3e723 9442 return 0;
c906108c
SS
9443}
9444
6d820c5c
DJ
9445/* Come here after finding the start of a frame when we expected an
9446 ack. Do our best to discard the rest of this packet. */
9447
6b8edb51
PA
9448void
9449remote_target::skip_frame ()
6d820c5c
DJ
9450{
9451 int c;
9452
9453 while (1)
9454 {
9455 c = readchar (remote_timeout);
9456 switch (c)
9457 {
9458 case SERIAL_TIMEOUT:
9459 /* Nothing we can do. */
9460 return;
9461 case '#':
9462 /* Discard the two bytes of checksum and stop. */
9463 c = readchar (remote_timeout);
9464 if (c >= 0)
9465 c = readchar (remote_timeout);
9466
9467 return;
9468 case '*': /* Run length encoding. */
9469 /* Discard the repeat count. */
9470 c = readchar (remote_timeout);
9471 if (c < 0)
9472 return;
9473 break;
9474 default:
9475 /* A regular character. */
9476 break;
9477 }
9478 }
9479}
9480
c906108c 9481/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9482 into *BUF, verifying the checksum, length, and handling run-length
9483 compression. NUL terminate the buffer. If there is not enough room,
9484 expand *BUF using xrealloc.
c906108c 9485
c2d11a7d
JM
9486 Returns -1 on error, number of characters in buffer (ignoring the
9487 trailing NULL) on success. (could be extended to return one of the
23860348 9488 SERIAL status indications). */
c2d11a7d 9489
6b8edb51
PA
9490long
9491remote_target::read_frame (char **buf_p, long *sizeof_buf)
c906108c
SS
9492{
9493 unsigned char csum;
c2d11a7d 9494 long bc;
c906108c 9495 int c;
6d820c5c 9496 char *buf = *buf_p;
a6f3e723 9497 struct remote_state *rs = get_remote_state ();
c906108c
SS
9498
9499 csum = 0;
c2d11a7d 9500 bc = 0;
c906108c
SS
9501
9502 while (1)
9503 {
9504 c = readchar (remote_timeout);
c906108c
SS
9505 switch (c)
9506 {
9507 case SERIAL_TIMEOUT:
9508 if (remote_debug)
0f71a2f6 9509 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 9510 return -1;
c906108c
SS
9511 case '$':
9512 if (remote_debug)
0f71a2f6
JM
9513 fputs_filtered ("Saw new packet start in middle of old one\n",
9514 gdb_stdlog);
23860348 9515 return -1; /* Start a new packet, count retries. */
c906108c
SS
9516 case '#':
9517 {
9518 unsigned char pktcsum;
e1b09194
AC
9519 int check_0 = 0;
9520 int check_1 = 0;
c906108c 9521
c2d11a7d 9522 buf[bc] = '\0';
c906108c 9523
e1b09194
AC
9524 check_0 = readchar (remote_timeout);
9525 if (check_0 >= 0)
9526 check_1 = readchar (remote_timeout);
802188a7 9527
e1b09194
AC
9528 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9529 {
9530 if (remote_debug)
2bc416ba 9531 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 9532 gdb_stdlog);
e1b09194
AC
9533 return -1;
9534 }
9535 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
9536 {
9537 if (remote_debug)
2bc416ba 9538 fputs_filtered ("Communication error in checksum\n",
23860348 9539 gdb_stdlog);
40e3f985
FN
9540 return -1;
9541 }
c906108c 9542
a6f3e723
SL
9543 /* Don't recompute the checksum; with no ack packets we
9544 don't have any way to indicate a packet retransmission
9545 is necessary. */
9546 if (rs->noack_mode)
9547 return bc;
9548
e1b09194 9549 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9550 if (csum == pktcsum)
c2d11a7d 9551 return bc;
c906108c 9552
c5aa993b 9553 if (remote_debug)
c906108c 9554 {
b3ced9ba 9555 std::string str = escape_buffer (buf, bc);
6e5abd65 9556
6e5abd65 9557 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9558 "Bad checksum, sentsum=0x%x, "
9559 "csum=0x%x, buf=%s\n",
b3ced9ba 9560 pktcsum, csum, str.c_str ());
c906108c 9561 }
c2d11a7d 9562 /* Number of characters in buffer ignoring trailing
23860348 9563 NULL. */
c2d11a7d 9564 return -1;
c906108c 9565 }
23860348 9566 case '*': /* Run length encoding. */
c2c6d25f
JM
9567 {
9568 int repeat;
c906108c 9569
a744cf53 9570 csum += c;
b4501125
AC
9571 c = readchar (remote_timeout);
9572 csum += c;
23860348 9573 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9574
23860348 9575 /* The character before ``*'' is repeated. */
c2d11a7d 9576
6d820c5c 9577 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9578 {
6d820c5c
DJ
9579 if (bc + repeat - 1 >= *sizeof_buf - 1)
9580 {
9581 /* Make some more room in the buffer. */
9582 *sizeof_buf += repeat;
224c3ddb 9583 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
9584 buf = *buf_p;
9585 }
9586
c2d11a7d
JM
9587 memset (&buf[bc], buf[bc - 1], repeat);
9588 bc += repeat;
c2c6d25f
JM
9589 continue;
9590 }
9591
c2d11a7d 9592 buf[bc] = '\0';
6d820c5c 9593 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9594 return -1;
c2c6d25f 9595 }
c906108c 9596 default:
6d820c5c 9597 if (bc >= *sizeof_buf - 1)
c906108c 9598 {
6d820c5c
DJ
9599 /* Make some more room in the buffer. */
9600 *sizeof_buf *= 2;
224c3ddb 9601 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 9602 buf = *buf_p;
c906108c
SS
9603 }
9604
6d820c5c
DJ
9605 buf[bc++] = c;
9606 csum += c;
9607 continue;
c906108c
SS
9608 }
9609 }
9610}
9611
9612/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9613 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9614 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9615 rather than timing out; this is used (in synchronous mode) to wait
9616 for a target that is is executing user code to stop. */
d9fcf2fb
JM
9617/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9618 don't have to change all the calls to getpkt to deal with the
9619 return value, because at the moment I don't know what the right
23860348 9620 thing to do it for those. */
6b8edb51 9621
c906108c 9622void
6b8edb51 9623remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
d9fcf2fb 9624{
54887903 9625 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
9626}
9627
9628
9629/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9630 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9631 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9632 rather than timing out; this is used (in synchronous mode) to wait
9633 for a target that is is executing user code to stop. If FOREVER ==
9634 0, this function is allowed to time out gracefully and return an
74531fed
PA
9635 indication of this to the caller. Otherwise return the number of
9636 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
9637 enough reason to return to the caller. *IS_NOTIF is an output
9638 boolean that indicates whether *BUF holds a notification or not
9639 (a regular packet). */
74531fed 9640
6b8edb51
PA
9641int
9642remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9643 int forever, int expecting_notif,
9644 int *is_notif)
c906108c 9645{
2d717e4f 9646 struct remote_state *rs = get_remote_state ();
c906108c
SS
9647 int c;
9648 int tries;
9649 int timeout;
df4b58fe 9650 int val = -1;
c906108c 9651
2d717e4f
DJ
9652 /* We're reading a new response. Make sure we don't look at a
9653 previously cached response. */
9654 rs->cached_wait_status = 0;
9655
6d820c5c 9656 strcpy (*buf, "timeout");
c906108c
SS
9657
9658 if (forever)
74531fed
PA
9659 timeout = watchdog > 0 ? watchdog : -1;
9660 else if (expecting_notif)
9661 timeout = 0; /* There should already be a char in the buffer. If
9662 not, bail out. */
c906108c
SS
9663 else
9664 timeout = remote_timeout;
9665
9666#define MAX_TRIES 3
9667
74531fed
PA
9668 /* Process any number of notifications, and then return when
9669 we get a packet. */
9670 for (;;)
c906108c 9671 {
d9c43928 9672 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9673 times. */
9674 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9675 {
74531fed
PA
9676 /* This can loop forever if the remote side sends us
9677 characters continuously, but if it pauses, we'll get
9678 SERIAL_TIMEOUT from readchar because of timeout. Then
9679 we'll count that as a retry.
9680
9681 Note that even when forever is set, we will only wait
9682 forever prior to the start of a packet. After that, we
9683 expect characters to arrive at a brisk pace. They should
9684 show up within remote_timeout intervals. */
9685 do
9686 c = readchar (timeout);
9687 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9688
9689 if (c == SERIAL_TIMEOUT)
9690 {
74531fed
PA
9691 if (expecting_notif)
9692 return -1; /* Don't complain, it's normal to not get
9693 anything in this case. */
9694
23860348 9695 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9696 {
78a095c3 9697 remote_unpush_target ();
598d3636
JK
9698 throw_error (TARGET_CLOSE_ERROR,
9699 _("Watchdog timeout has expired. "
9700 "Target detached."));
c906108c 9701 }
c906108c 9702 if (remote_debug)
0f71a2f6 9703 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9704 }
74531fed
PA
9705 else
9706 {
9707 /* We've found the start of a packet or notification.
9708 Now collect the data. */
9709 val = read_frame (buf, sizeof_buf);
9710 if (val >= 0)
9711 break;
9712 }
9713
c33e31fd 9714 remote_serial_write ("-", 1);
c906108c 9715 }
c906108c 9716
74531fed
PA
9717 if (tries > MAX_TRIES)
9718 {
9719 /* We have tried hard enough, and just can't receive the
9720 packet/notification. Give up. */
9721 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9722
74531fed
PA
9723 /* Skip the ack char if we're in no-ack mode. */
9724 if (!rs->noack_mode)
c33e31fd 9725 remote_serial_write ("+", 1);
74531fed
PA
9726 return -1;
9727 }
c906108c 9728
74531fed
PA
9729 /* If we got an ordinary packet, return that to our caller. */
9730 if (c == '$')
c906108c
SS
9731 {
9732 if (remote_debug)
43e526b9 9733 {
6f8976bf
YQ
9734 std::string str
9735 = escape_buffer (*buf,
9736 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9737
9738 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9739 str.c_str ());
9740
567a3e54
SM
9741 if (val > REMOTE_DEBUG_MAX_CHAR)
9742 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9743 val - REMOTE_DEBUG_MAX_CHAR);
6e5abd65 9744
6f8976bf 9745 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9746 }
a6f3e723
SL
9747
9748 /* Skip the ack char if we're in no-ack mode. */
9749 if (!rs->noack_mode)
c33e31fd 9750 remote_serial_write ("+", 1);
fee9eda9
YQ
9751 if (is_notif != NULL)
9752 *is_notif = 0;
0876f84a 9753 return val;
c906108c
SS
9754 }
9755
74531fed
PA
9756 /* If we got a notification, handle it, and go back to looking
9757 for a packet. */
9758 else
9759 {
9760 gdb_assert (c == '%');
9761
9762 if (remote_debug)
9763 {
b3ced9ba 9764 std::string str = escape_buffer (*buf, val);
6e5abd65 9765
6e5abd65
PA
9766 fprintf_unfiltered (gdb_stdlog,
9767 " Notification received: %s\n",
b3ced9ba 9768 str.c_str ());
74531fed 9769 }
fee9eda9
YQ
9770 if (is_notif != NULL)
9771 *is_notif = 1;
c906108c 9772
5965e028 9773 handle_notification (rs->notif_state, *buf);
c906108c 9774
74531fed 9775 /* Notifications require no acknowledgement. */
a6f3e723 9776
74531fed 9777 if (expecting_notif)
fee9eda9 9778 return val;
74531fed
PA
9779 }
9780 }
9781}
9782
6b8edb51
PA
9783int
9784remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
74531fed 9785{
fee9eda9 9786 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
9787}
9788
6b8edb51
PA
9789int
9790remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9791 int *is_notif)
74531fed 9792{
fee9eda9
YQ
9793 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9794 is_notif);
c906108c 9795}
74531fed 9796
cbb8991c
DB
9797/* Check whether EVENT is a fork event for the process specified
9798 by the pid passed in DATA, and if it is, kill the fork child. */
9799
6b8edb51
PA
9800int
9801remote_kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9802 QUEUE_ITER (stop_reply_p) *iter,
9803 stop_reply_p event,
9804 void *data)
cbb8991c 9805{
19ba03f4 9806 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
9807 int parent_pid = *(int *) param->input;
9808
9809 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9810 {
6b8edb51 9811 remote_target *remote = param->remote;
cbb8991c
DB
9812 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9813 int res;
9814
6b8edb51 9815 res = remote->remote_vkill (child_pid);
cbb8991c
DB
9816 if (res != 0)
9817 error (_("Can't kill fork child process %d"), child_pid);
9818 }
9819
9820 return 1;
9821}
9822
9823/* Kill any new fork children of process PID that haven't been
9824 processed by follow_fork. */
9825
6b8edb51
PA
9826void
9827remote_target::kill_new_fork_children (int pid)
cbb8991c 9828{
6b8edb51 9829 remote_state *rs = get_remote_state ();
cbb8991c
DB
9830 struct thread_info *thread;
9831 struct notif_client *notif = &notif_client_stop;
9832 struct queue_iter_param param;
9833
9834 /* Kill the fork child threads of any threads in process PID
9835 that are stopped at a fork event. */
9836 ALL_NON_EXITED_THREADS (thread)
9837 {
9838 struct target_waitstatus *ws = &thread->pending_follow;
9839
9840 if (is_pending_fork_parent (ws, pid, thread->ptid))
9841 {
cbb8991c
DB
9842 int child_pid = ptid_get_pid (ws->value.related_pid);
9843 int res;
9844
6b8edb51 9845 res = remote_vkill (child_pid);
cbb8991c
DB
9846 if (res != 0)
9847 error (_("Can't kill fork child process %d"), child_pid);
9848 }
9849 }
9850
9851 /* Check for any pending fork events (not reported or processed yet)
9852 in process PID and kill those fork child threads as well. */
9853 remote_notif_get_pending_events (notif);
6b8edb51 9854 param.remote = this;
cbb8991c
DB
9855 param.input = &pid;
9856 param.output = NULL;
6b8edb51
PA
9857 QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
9858 remote_kill_child_of_pending_fork, &param);
cbb8991c
DB
9859}
9860
c906108c 9861\f
8020350c
DB
9862/* Target hook to kill the current inferior. */
9863
f6ac5f3d
PA
9864void
9865remote_target::kill ()
43ff13b4 9866{
8020350c
DB
9867 int res = -1;
9868 int pid = ptid_get_pid (inferior_ptid);
9869 struct remote_state *rs = get_remote_state ();
0fdf84ca 9870
8020350c 9871 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9872 {
8020350c
DB
9873 /* If we're stopped while forking and we haven't followed yet,
9874 kill the child task. We need to do this before killing the
9875 parent task because if this is a vfork then the parent will
9876 be sleeping. */
6b8edb51 9877 kill_new_fork_children (pid);
8020350c 9878
6b8edb51 9879 res = remote_vkill (pid);
8020350c 9880 if (res == 0)
0fdf84ca 9881 {
bc1e6c81 9882 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9883 return;
9884 }
8020350c 9885 }
0fdf84ca 9886
8020350c
DB
9887 /* If we are in 'target remote' mode and we are killing the only
9888 inferior, then we will tell gdbserver to exit and unpush the
9889 target. */
9890 if (res == -1 && !remote_multi_process_p (rs)
9891 && number_of_live_inferiors () == 1)
9892 {
9893 remote_kill_k ();
9894
9895 /* We've killed the remote end, we get to mourn it. If we are
9896 not in extended mode, mourning the inferior also unpushes
9897 remote_ops from the target stack, which closes the remote
9898 connection. */
bc1e6c81 9899 target_mourn_inferior (inferior_ptid);
8020350c
DB
9900
9901 return;
0fdf84ca 9902 }
43ff13b4 9903
8020350c 9904 error (_("Can't kill process"));
43ff13b4
JM
9905}
9906
8020350c
DB
9907/* Send a kill request to the target using the 'vKill' packet. */
9908
6b8edb51
PA
9909int
9910remote_target::remote_vkill (int pid)
82f73884 9911{
4082afcc 9912 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9913 return -1;
9914
6b8edb51
PA
9915 remote_state *rs = get_remote_state ();
9916
82f73884 9917 /* Tell the remote target to detach. */
bba74b36 9918 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
9919 putpkt (rs->buf);
9920 getpkt (&rs->buf, &rs->buf_size, 0);
9921
4082afcc
PA
9922 switch (packet_ok (rs->buf,
9923 &remote_protocol_packets[PACKET_vKill]))
9924 {
9925 case PACKET_OK:
9926 return 0;
9927 case PACKET_ERROR:
9928 return 1;
9929 case PACKET_UNKNOWN:
9930 return -1;
9931 default:
9932 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9933 }
82f73884
PA
9934}
9935
8020350c
DB
9936/* Send a kill request to the target using the 'k' packet. */
9937
6b8edb51
PA
9938void
9939remote_target::remote_kill_k ()
82f73884 9940{
8020350c
DB
9941 /* Catch errors so the user can quit from gdb even when we
9942 aren't on speaking terms with the remote system. */
9943 TRY
82f73884 9944 {
82f73884 9945 putpkt ("k");
82f73884 9946 }
8020350c
DB
9947 CATCH (ex, RETURN_MASK_ERROR)
9948 {
9949 if (ex.error == TARGET_CLOSE_ERROR)
9950 {
9951 /* If we got an (EOF) error that caused the target
9952 to go away, then we're done, that's what we wanted.
9953 "k" is susceptible to cause a premature EOF, given
9954 that the remote server isn't actually required to
9955 reply to "k", and it can happen that it doesn't
9956 even get to reply ACK to the "k". */
9957 return;
9958 }
82f73884 9959
8020350c
DB
9960 /* Otherwise, something went wrong. We didn't actually kill
9961 the target. Just propagate the exception, and let the
9962 user or higher layers decide what to do. */
9963 throw_exception (ex);
9964 }
9965 END_CATCH
82f73884
PA
9966}
9967
f6ac5f3d
PA
9968void
9969remote_target::mourn_inferior ()
c906108c 9970{
8020350c 9971 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9972
9607784a
PA
9973 /* We're no longer interested in notification events of an inferior
9974 that exited or was killed/detached. */
9975 discard_pending_stop_replies (current_inferior ());
9976
8020350c
DB
9977 /* In 'target remote' mode with one inferior, we close the connection. */
9978 if (!rs->extended && number_of_live_inferiors () <= 1)
9979 {
f6ac5f3d 9980 unpush_target (this);
c906108c 9981
8020350c
DB
9982 /* remote_close takes care of doing most of the clean up. */
9983 generic_mourn_inferior ();
9984 return;
9985 }
c906108c 9986
e24a49d8
PA
9987 /* In case we got here due to an error, but we're going to stay
9988 connected. */
9989 rs->waiting_for_stop_reply = 0;
9990
dc1981d7
PA
9991 /* If the current general thread belonged to the process we just
9992 detached from or has exited, the remote side current general
9993 thread becomes undefined. Considering a case like this:
9994
9995 - We just got here due to a detach.
9996 - The process that we're detaching from happens to immediately
9997 report a global breakpoint being hit in non-stop mode, in the
9998 same thread we had selected before.
9999 - GDB attaches to this process again.
10000 - This event happens to be the next event we handle.
10001
10002 GDB would consider that the current general thread didn't need to
10003 be set on the stub side (with Hg), since for all it knew,
10004 GENERAL_THREAD hadn't changed.
10005
10006 Notice that although in all-stop mode, the remote server always
10007 sets the current thread to the thread reporting the stop event,
10008 that doesn't happen in non-stop mode; in non-stop, the stub *must
10009 not* change the current thread when reporting a breakpoint hit,
10010 due to the decoupling of event reporting and event handling.
10011
10012 To keep things simple, we always invalidate our notion of the
10013 current thread. */
47f8a51d 10014 record_currthread (rs, minus_one_ptid);
dc1981d7 10015
8020350c 10016 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
10017 generic_mourn_inferior ();
10018
d729566a 10019 if (!have_inferiors ())
2d717e4f 10020 {
82f73884
PA
10021 if (!remote_multi_process_p (rs))
10022 {
10023 /* Check whether the target is running now - some remote stubs
10024 automatically restart after kill. */
10025 putpkt ("?");
10026 getpkt (&rs->buf, &rs->buf_size, 0);
10027
10028 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
10029 {
3e43a32a
MS
10030 /* Assume that the target has been restarted. Set
10031 inferior_ptid so that bits of core GDB realizes
10032 there's something here, e.g., so that the user can
10033 say "kill" again. */
82f73884
PA
10034 inferior_ptid = magic_null_ptid;
10035 }
82f73884 10036 }
2d717e4f
DJ
10037 }
10038}
c906108c 10039
57810aa7 10040bool
f6ac5f3d 10041extended_remote_target::supports_disable_randomization ()
03583c20 10042{
4082afcc 10043 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
10044}
10045
6b8edb51
PA
10046void
10047remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
10048{
10049 struct remote_state *rs = get_remote_state ();
10050 char *reply;
10051
bba74b36
YQ
10052 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
10053 val);
03583c20 10054 putpkt (rs->buf);
b6bb3468 10055 reply = remote_get_noisy_reply ();
03583c20
UW
10056 if (*reply == '\0')
10057 error (_("Target does not support QDisableRandomization."));
10058 if (strcmp (reply, "OK") != 0)
10059 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10060}
10061
6b8edb51
PA
10062int
10063remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
10064{
10065 struct remote_state *rs = get_remote_state ();
2d717e4f 10066 int len;
94585166 10067 const char *remote_exec_file = get_remote_exec_file ();
c906108c 10068
2d717e4f
DJ
10069 /* If the user has disabled vRun support, or we have detected that
10070 support is not available, do not try it. */
4082afcc 10071 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 10072 return -1;
424163ea 10073
2d717e4f
DJ
10074 strcpy (rs->buf, "vRun;");
10075 len = strlen (rs->buf);
c906108c 10076
2d717e4f
DJ
10077 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10078 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
10079 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
10080 strlen (remote_exec_file));
2d717e4f 10081
7c5ded6a 10082 if (!args.empty ())
2d717e4f 10083 {
2d717e4f 10084 int i;
2d717e4f 10085
773a1edc 10086 gdb_argv argv (args.c_str ());
2d717e4f
DJ
10087 for (i = 0; argv[i] != NULL; i++)
10088 {
10089 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10090 error (_("Argument list too long for run packet"));
10091 rs->buf[len++] = ';';
9f1b45b0
TT
10092 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
10093 strlen (argv[i]));
2d717e4f 10094 }
2d717e4f
DJ
10095 }
10096
10097 rs->buf[len++] = '\0';
10098
10099 putpkt (rs->buf);
10100 getpkt (&rs->buf, &rs->buf_size, 0);
10101
4082afcc 10102 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 10103 {
4082afcc 10104 case PACKET_OK:
3405876a 10105 /* We have a wait response. All is well. */
2d717e4f 10106 return 0;
4082afcc
PA
10107 case PACKET_UNKNOWN:
10108 return -1;
10109 case PACKET_ERROR:
2d717e4f
DJ
10110 if (remote_exec_file[0] == '\0')
10111 error (_("Running the default executable on the remote target failed; "
10112 "try \"set remote exec-file\"?"));
10113 else
10114 error (_("Running \"%s\" on the remote target failed"),
10115 remote_exec_file);
4082afcc
PA
10116 default:
10117 gdb_assert_not_reached (_("bad switch"));
2d717e4f 10118 }
c906108c
SS
10119}
10120
0a2dde4a
SDJ
10121/* Helper function to send set/unset environment packets. ACTION is
10122 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10123 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10124 sent. */
10125
6b8edb51
PA
10126void
10127remote_target::send_environment_packet (const char *action,
10128 const char *packet,
10129 const char *value)
0a2dde4a 10130{
6b8edb51
PA
10131 remote_state *rs = get_remote_state ();
10132
0a2dde4a
SDJ
10133 /* Convert the environment variable to an hex string, which
10134 is the best format to be transmitted over the wire. */
10135 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10136 strlen (value));
10137
10138 xsnprintf (rs->buf, get_remote_packet_size (),
10139 "%s:%s", packet, encoded_value.c_str ());
10140
10141 putpkt (rs->buf);
10142 getpkt (&rs->buf, &rs->buf_size, 0);
10143 if (strcmp (rs->buf, "OK") != 0)
10144 warning (_("Unable to %s environment variable '%s' on remote."),
10145 action, value);
10146}
10147
10148/* Helper function to handle the QEnvironment* packets. */
10149
6b8edb51
PA
10150void
10151remote_target::extended_remote_environment_support ()
0a2dde4a 10152{
6b8edb51
PA
10153 remote_state *rs = get_remote_state ();
10154
0a2dde4a
SDJ
10155 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10156 {
10157 putpkt ("QEnvironmentReset");
10158 getpkt (&rs->buf, &rs->buf_size, 0);
10159 if (strcmp (rs->buf, "OK") != 0)
10160 warning (_("Unable to reset environment on remote."));
10161 }
10162
10163 gdb_environ *e = &current_inferior ()->environment;
10164
10165 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10166 for (const std::string &el : e->user_set_env ())
6b8edb51 10167 send_environment_packet ("set", "QEnvironmentHexEncoded",
0a2dde4a
SDJ
10168 el.c_str ());
10169
10170 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10171 for (const std::string &el : e->user_unset_env ())
6b8edb51 10172 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10173}
10174
bc3b087d
SDJ
10175/* Helper function to set the current working directory for the
10176 inferior in the remote target. */
10177
6b8edb51
PA
10178void
10179remote_target::extended_remote_set_inferior_cwd ()
bc3b087d
SDJ
10180{
10181 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10182 {
10183 const char *inferior_cwd = get_inferior_cwd ();
6b8edb51 10184 remote_state *rs = get_remote_state ();
bc3b087d
SDJ
10185
10186 if (inferior_cwd != NULL)
10187 {
10188 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10189 strlen (inferior_cwd));
10190
10191 xsnprintf (rs->buf, get_remote_packet_size (),
10192 "QSetWorkingDir:%s", hexpath.c_str ());
10193 }
10194 else
10195 {
10196 /* An empty inferior_cwd means that the user wants us to
10197 reset the remote server's inferior's cwd. */
10198 xsnprintf (rs->buf, get_remote_packet_size (),
10199 "QSetWorkingDir:");
10200 }
10201
10202 putpkt (rs->buf);
10203 getpkt (&rs->buf, &rs->buf_size, 0);
10204 if (packet_ok (rs->buf,
10205 &remote_protocol_packets[PACKET_QSetWorkingDir])
10206 != PACKET_OK)
10207 error (_("\
10208Remote replied unexpectedly while setting the inferior's working\n\
10209directory: %s"),
10210 rs->buf);
10211
10212 }
10213}
10214
2d717e4f
DJ
10215/* In the extended protocol we want to be able to do things like
10216 "run" and have them basically work as expected. So we need
10217 a special create_inferior function. We support changing the
10218 executable file and the command line arguments, but not the
10219 environment. */
10220
f6ac5f3d
PA
10221void
10222extended_remote_target::create_inferior (const char *exec_file,
10223 const std::string &args,
10224 char **env, int from_tty)
43ff13b4 10225{
3405876a
PA
10226 int run_worked;
10227 char *stop_reply;
10228 struct remote_state *rs = get_remote_state ();
94585166 10229 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10230
43ff13b4 10231 /* If running asynchronously, register the target file descriptor
23860348 10232 with the event loop. */
75c99385 10233 if (target_can_async_p ())
6a3753b3 10234 target_async (1);
43ff13b4 10235
03583c20 10236 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10237 if (supports_disable_randomization ())
03583c20
UW
10238 extended_remote_disable_randomization (disable_randomization);
10239
aefd8b33
SDJ
10240 /* If startup-with-shell is on, we inform gdbserver to start the
10241 remote inferior using a shell. */
10242 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10243 {
10244 xsnprintf (rs->buf, get_remote_packet_size (),
10245 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10246 putpkt (rs->buf);
10247 getpkt (&rs->buf, &rs->buf_size, 0);
10248 if (strcmp (rs->buf, "OK") != 0)
10249 error (_("\
10250Remote replied unexpectedly while setting startup-with-shell: %s"),
10251 rs->buf);
10252 }
10253
6b8edb51 10254 extended_remote_environment_support ();
0a2dde4a 10255
6b8edb51 10256 extended_remote_set_inferior_cwd ();
bc3b087d 10257
43ff13b4 10258 /* Now restart the remote server. */
3405876a
PA
10259 run_worked = extended_remote_run (args) != -1;
10260 if (!run_worked)
2d717e4f
DJ
10261 {
10262 /* vRun was not supported. Fail if we need it to do what the
10263 user requested. */
10264 if (remote_exec_file[0])
10265 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10266 if (!args.empty ())
2d717e4f 10267 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 10268
2d717e4f
DJ
10269 /* Fall back to "R". */
10270 extended_remote_restart ();
10271 }
424163ea 10272
6c95b8df
PA
10273 if (!have_inferiors ())
10274 {
10275 /* Clean up from the last time we ran, before we mark the target
10276 running again. This will mark breakpoints uninserted, and
10277 get_offsets may insert breakpoints. */
10278 init_thread_list ();
10279 init_wait_for_inferior ();
10280 }
45280a52 10281
3405876a
PA
10282 /* vRun's success return is a stop reply. */
10283 stop_reply = run_worked ? rs->buf : NULL;
10284 add_current_inferior_and_thread (stop_reply);
c0a2216e 10285
2d717e4f
DJ
10286 /* Get updated offsets, if the stub uses qOffsets. */
10287 get_offsets ();
2d717e4f 10288}
c906108c 10289\f
c5aa993b 10290
b775012e
LM
10291/* Given a location's target info BP_TGT and the packet buffer BUF, output
10292 the list of conditions (in agent expression bytecode format), if any, the
10293 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10294 started from BUF and ended at BUF_END. */
b775012e
LM
10295
10296static int
10297remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10298 struct bp_target_info *bp_tgt, char *buf,
10299 char *buf_end)
b775012e 10300{
3cde5c42 10301 if (bp_tgt->conditions.empty ())
b775012e
LM
10302 return 0;
10303
10304 buf += strlen (buf);
bba74b36 10305 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10306 buf++;
10307
83621223 10308 /* Send conditions to the target. */
d538e36d 10309 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10310 {
bba74b36 10311 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 10312 buf += strlen (buf);
3cde5c42 10313 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
10314 buf = pack_hex_byte (buf, aexpr->buf[i]);
10315 *buf = '\0';
10316 }
b775012e
LM
10317 return 0;
10318}
10319
d3ce09f5
SS
10320static void
10321remote_add_target_side_commands (struct gdbarch *gdbarch,
10322 struct bp_target_info *bp_tgt, char *buf)
10323{
3cde5c42 10324 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10325 return;
10326
10327 buf += strlen (buf);
10328
10329 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10330 buf += strlen (buf);
10331
10332 /* Concatenate all the agent expressions that are commands into the
10333 cmds parameter. */
df97be55 10334 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
10335 {
10336 sprintf (buf, "X%x,", aexpr->len);
10337 buf += strlen (buf);
3cde5c42 10338 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
10339 buf = pack_hex_byte (buf, aexpr->buf[i]);
10340 *buf = '\0';
10341 }
d3ce09f5
SS
10342}
10343
8181d85f
DJ
10344/* Insert a breakpoint. On targets that have software breakpoint
10345 support, we ask the remote target to do the work; on targets
10346 which don't, we insert a traditional memory breakpoint. */
c906108c 10347
f6ac5f3d
PA
10348int
10349remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10350 struct bp_target_info *bp_tgt)
c906108c 10351{
d471ea57
AC
10352 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10353 If it succeeds, then set the support to PACKET_ENABLE. If it
10354 fails, and the user has explicitly requested the Z support then
23860348 10355 report an error, otherwise, mark it disabled and go on. */
802188a7 10356
4082afcc 10357 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10358 {
0d5ed153 10359 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10360 struct remote_state *rs;
bba74b36 10361 char *p, *endbuf;
4fff2411 10362
28439a30
PA
10363 /* Make sure the remote is pointing at the right process, if
10364 necessary. */
10365 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10366 set_general_process ();
10367
4fff2411
JZ
10368 rs = get_remote_state ();
10369 p = rs->buf;
bba74b36 10370 endbuf = rs->buf + get_remote_packet_size ();
802188a7 10371
96baa820
JM
10372 *(p++) = 'Z';
10373 *(p++) = '0';
10374 *(p++) = ',';
7c0f6dcc 10375 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10376 p += hexnumstr (p, addr);
579c6ad9 10377 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10378
f6ac5f3d 10379 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10380 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10381
f6ac5f3d 10382 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10383 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10384
6d820c5c
DJ
10385 putpkt (rs->buf);
10386 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10387
6d820c5c 10388 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 10389 {
d471ea57
AC
10390 case PACKET_ERROR:
10391 return -1;
10392 case PACKET_OK:
10393 return 0;
10394 case PACKET_UNKNOWN:
10395 break;
96baa820
JM
10396 }
10397 }
c906108c 10398
0000e5cc
PA
10399 /* If this breakpoint has target-side commands but this stub doesn't
10400 support Z0 packets, throw error. */
3cde5c42 10401 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10402 throw_error (NOT_SUPPORTED_ERROR, _("\
10403Target doesn't support breakpoints that have target side commands."));
10404
f6ac5f3d 10405 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10406}
10407
f6ac5f3d
PA
10408int
10409remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10410 struct bp_target_info *bp_tgt,
10411 enum remove_bp_reason reason)
c906108c 10412{
8181d85f 10413 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10414 struct remote_state *rs = get_remote_state ();
96baa820 10415
4082afcc 10416 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10417 {
6d820c5c 10418 char *p = rs->buf;
bba74b36 10419 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 10420
28439a30
PA
10421 /* Make sure the remote is pointing at the right process, if
10422 necessary. */
10423 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10424 set_general_process ();
10425
96baa820
JM
10426 *(p++) = 'z';
10427 *(p++) = '0';
10428 *(p++) = ',';
10429
8181d85f
DJ
10430 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10431 p += hexnumstr (p, addr);
579c6ad9 10432 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10433
6d820c5c
DJ
10434 putpkt (rs->buf);
10435 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10436
6d820c5c 10437 return (rs->buf[0] == 'E');
96baa820
JM
10438 }
10439
f6ac5f3d 10440 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10441}
10442
f486487f 10443static enum Z_packet_type
d471ea57
AC
10444watchpoint_to_Z_packet (int type)
10445{
10446 switch (type)
10447 {
10448 case hw_write:
bb858e6a 10449 return Z_PACKET_WRITE_WP;
d471ea57
AC
10450 break;
10451 case hw_read:
bb858e6a 10452 return Z_PACKET_READ_WP;
d471ea57
AC
10453 break;
10454 case hw_access:
bb858e6a 10455 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10456 break;
10457 default:
8e65ff28 10458 internal_error (__FILE__, __LINE__,
e2e0b3e5 10459 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10460 }
10461}
10462
f6ac5f3d
PA
10463int
10464remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10465 enum target_hw_bp_type type, struct expression *cond)
96baa820 10466{
d01949b6 10467 struct remote_state *rs = get_remote_state ();
bba74b36 10468 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10469 char *p;
d471ea57 10470 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10471
4082afcc 10472 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10473 return 1;
802188a7 10474
28439a30
PA
10475 /* Make sure the remote is pointing at the right process, if
10476 necessary. */
10477 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10478 set_general_process ();
10479
bba74b36 10480 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 10481 p = strchr (rs->buf, '\0');
96baa820
JM
10482 addr = remote_address_masked (addr);
10483 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10484 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10485
6d820c5c
DJ
10486 putpkt (rs->buf);
10487 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10488
6d820c5c 10489 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10490 {
10491 case PACKET_ERROR:
d471ea57 10492 return -1;
85d721b8
PA
10493 case PACKET_UNKNOWN:
10494 return 1;
d471ea57
AC
10495 case PACKET_OK:
10496 return 0;
10497 }
8e65ff28 10498 internal_error (__FILE__, __LINE__,
e2e0b3e5 10499 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10500}
10501
57810aa7 10502bool
f6ac5f3d
PA
10503remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10504 CORE_ADDR start, int length)
283002cf
MR
10505{
10506 CORE_ADDR diff = remote_address_masked (addr - start);
10507
10508 return diff < length;
10509}
10510
d471ea57 10511
f6ac5f3d
PA
10512int
10513remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10514 enum target_hw_bp_type type, struct expression *cond)
96baa820 10515{
d01949b6 10516 struct remote_state *rs = get_remote_state ();
bba74b36 10517 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10518 char *p;
d471ea57
AC
10519 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10520
4082afcc 10521 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10522 return -1;
802188a7 10523
28439a30
PA
10524 /* Make sure the remote is pointing at the right process, if
10525 necessary. */
10526 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10527 set_general_process ();
10528
bba74b36 10529 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 10530 p = strchr (rs->buf, '\0');
96baa820
JM
10531 addr = remote_address_masked (addr);
10532 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10533 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
10534 putpkt (rs->buf);
10535 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10536
6d820c5c 10537 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10538 {
10539 case PACKET_ERROR:
10540 case PACKET_UNKNOWN:
10541 return -1;
10542 case PACKET_OK:
10543 return 0;
10544 }
8e65ff28 10545 internal_error (__FILE__, __LINE__,
e2e0b3e5 10546 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10547}
10548
3c3bea1c 10549
501eef12 10550int remote_hw_watchpoint_limit = -1;
480a3f21 10551int remote_hw_watchpoint_length_limit = -1;
501eef12 10552int remote_hw_breakpoint_limit = -1;
d471ea57 10553
f6ac5f3d
PA
10554int
10555remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10556{
10557 if (remote_hw_watchpoint_length_limit == 0)
10558 return 0;
10559 else if (remote_hw_watchpoint_length_limit < 0)
10560 return 1;
10561 else if (len <= remote_hw_watchpoint_length_limit)
10562 return 1;
10563 else
10564 return 0;
10565}
10566
f6ac5f3d
PA
10567int
10568remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10569{
3c3bea1c
GS
10570 if (type == bp_hardware_breakpoint)
10571 {
10572 if (remote_hw_breakpoint_limit == 0)
10573 return 0;
501eef12
AC
10574 else if (remote_hw_breakpoint_limit < 0)
10575 return 1;
3c3bea1c
GS
10576 else if (cnt <= remote_hw_breakpoint_limit)
10577 return 1;
10578 }
10579 else
10580 {
10581 if (remote_hw_watchpoint_limit == 0)
10582 return 0;
501eef12
AC
10583 else if (remote_hw_watchpoint_limit < 0)
10584 return 1;
3c3bea1c
GS
10585 else if (ot)
10586 return -1;
10587 else if (cnt <= remote_hw_watchpoint_limit)
10588 return 1;
10589 }
10590 return -1;
10591}
10592
f7e6eed5
PA
10593/* The to_stopped_by_sw_breakpoint method of target remote. */
10594
57810aa7 10595bool
f6ac5f3d 10596remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10597{
799a2abe 10598 struct thread_info *thread = inferior_thread ();
f7e6eed5 10599
799a2abe 10600 return (thread->priv != NULL
7aabaf9d
SM
10601 && (get_remote_thread_info (thread)->stop_reason
10602 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10603}
10604
10605/* The to_supports_stopped_by_sw_breakpoint method of target
10606 remote. */
10607
57810aa7 10608bool
f6ac5f3d 10609remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10610{
f7e6eed5
PA
10611 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10612}
10613
10614/* The to_stopped_by_hw_breakpoint method of target remote. */
10615
57810aa7 10616bool
f6ac5f3d 10617remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10618{
799a2abe 10619 struct thread_info *thread = inferior_thread ();
f7e6eed5 10620
799a2abe 10621 return (thread->priv != NULL
7aabaf9d
SM
10622 && (get_remote_thread_info (thread)->stop_reason
10623 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10624}
10625
10626/* The to_supports_stopped_by_hw_breakpoint method of target
10627 remote. */
10628
57810aa7 10629bool
f6ac5f3d 10630remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10631{
f7e6eed5
PA
10632 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10633}
10634
57810aa7 10635bool
f6ac5f3d 10636remote_target::stopped_by_watchpoint ()
3c3bea1c 10637{
799a2abe 10638 struct thread_info *thread = inferior_thread ();
ee154bee 10639
799a2abe 10640 return (thread->priv != NULL
7aabaf9d
SM
10641 && (get_remote_thread_info (thread)->stop_reason
10642 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10643}
10644
57810aa7 10645bool
f6ac5f3d 10646remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10647{
799a2abe 10648 struct thread_info *thread = inferior_thread ();
a744cf53 10649
799a2abe 10650 if (thread->priv != NULL
7aabaf9d
SM
10651 && (get_remote_thread_info (thread)->stop_reason
10652 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10653 {
7aabaf9d 10654 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 10655 return true;
4aa7a7f5
JJ
10656 }
10657
57810aa7 10658 return false;
3c3bea1c
GS
10659}
10660
10661
f6ac5f3d
PA
10662int
10663remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10664 struct bp_target_info *bp_tgt)
3c3bea1c 10665{
0d5ed153 10666 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10667 struct remote_state *rs;
bba74b36 10668 char *p, *endbuf;
dd61ec5c 10669 char *message;
3c3bea1c 10670
4082afcc 10671 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10672 return -1;
2bc416ba 10673
28439a30
PA
10674 /* Make sure the remote is pointing at the right process, if
10675 necessary. */
10676 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10677 set_general_process ();
10678
4fff2411
JZ
10679 rs = get_remote_state ();
10680 p = rs->buf;
bba74b36 10681 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 10682
96baa820
JM
10683 *(p++) = 'Z';
10684 *(p++) = '1';
10685 *(p++) = ',';
802188a7 10686
0d5ed153 10687 addr = remote_address_masked (addr);
96baa820 10688 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10689 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10690
f6ac5f3d 10691 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10692 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10693
f6ac5f3d 10694 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10695 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10696
6d820c5c
DJ
10697 putpkt (rs->buf);
10698 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10699
6d820c5c 10700 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10701 {
10702 case PACKET_ERROR:
dd61ec5c
MW
10703 if (rs->buf[1] == '.')
10704 {
10705 message = strchr (rs->buf + 2, '.');
10706 if (message)
0316657e 10707 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10708 }
10709 return -1;
d471ea57
AC
10710 case PACKET_UNKNOWN:
10711 return -1;
10712 case PACKET_OK:
10713 return 0;
10714 }
8e65ff28 10715 internal_error (__FILE__, __LINE__,
e2e0b3e5 10716 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10717}
10718
d471ea57 10719
f6ac5f3d
PA
10720int
10721remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10722 struct bp_target_info *bp_tgt)
96baa820 10723{
8181d85f 10724 CORE_ADDR addr;
d01949b6 10725 struct remote_state *rs = get_remote_state ();
6d820c5c 10726 char *p = rs->buf;
bba74b36 10727 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 10728
4082afcc 10729 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10730 return -1;
802188a7 10731
28439a30
PA
10732 /* Make sure the remote is pointing at the right process, if
10733 necessary. */
10734 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10735 set_general_process ();
10736
96baa820
JM
10737 *(p++) = 'z';
10738 *(p++) = '1';
10739 *(p++) = ',';
802188a7 10740
8181d85f 10741 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10742 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10743 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10744
6d820c5c
DJ
10745 putpkt (rs->buf);
10746 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 10747
6d820c5c 10748 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10749 {
10750 case PACKET_ERROR:
10751 case PACKET_UNKNOWN:
10752 return -1;
10753 case PACKET_OK:
10754 return 0;
10755 }
8e65ff28 10756 internal_error (__FILE__, __LINE__,
e2e0b3e5 10757 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10758}
96baa820 10759
4a5e7a5b
PA
10760/* Verify memory using the "qCRC:" request. */
10761
f6ac5f3d
PA
10762int
10763remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
10764{
10765 struct remote_state *rs = get_remote_state ();
10766 unsigned long host_crc, target_crc;
10767 char *tmp;
10768
936d2992
PA
10769 /* It doesn't make sense to use qCRC if the remote target is
10770 connected but not running. */
10771 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10772 {
10773 enum packet_result result;
28439a30 10774
936d2992
PA
10775 /* Make sure the remote is pointing at the right process. */
10776 set_general_process ();
4a5e7a5b 10777
936d2992
PA
10778 /* FIXME: assumes lma can fit into long. */
10779 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10780 (long) lma, (long) size);
10781 putpkt (rs->buf);
4a5e7a5b 10782
936d2992
PA
10783 /* Be clever; compute the host_crc before waiting for target
10784 reply. */
10785 host_crc = xcrc32 (data, size, 0xffffffff);
10786
10787 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 10788
936d2992
PA
10789 result = packet_ok (rs->buf,
10790 &remote_protocol_packets[PACKET_qCRC]);
10791 if (result == PACKET_ERROR)
10792 return -1;
10793 else if (result == PACKET_OK)
10794 {
10795 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10796 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10797
936d2992
PA
10798 return (host_crc == target_crc);
10799 }
10800 }
4a5e7a5b 10801
f6ac5f3d 10802 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
10803}
10804
c906108c
SS
10805/* compare-sections command
10806
10807 With no arguments, compares each loadable section in the exec bfd
10808 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10809 Useful for verifying the image on the target against the exec file. */
e514a9d6 10810
c906108c 10811static void
ac88e2de 10812compare_sections_command (const char *args, int from_tty)
c906108c
SS
10813{
10814 asection *s;
ce359b09 10815 const char *sectname;
c906108c
SS
10816 bfd_size_type size;
10817 bfd_vma lma;
10818 int matched = 0;
10819 int mismatched = 0;
4a5e7a5b 10820 int res;
95cf3b38 10821 int read_only = 0;
c906108c
SS
10822
10823 if (!exec_bfd)
8a3fe4f8 10824 error (_("command cannot be used without an exec file"));
c906108c 10825
95cf3b38
DT
10826 if (args != NULL && strcmp (args, "-r") == 0)
10827 {
10828 read_only = 1;
10829 args = NULL;
10830 }
10831
c5aa993b 10832 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10833 {
10834 if (!(s->flags & SEC_LOAD))
0df8b418 10835 continue; /* Skip non-loadable section. */
c906108c 10836
95cf3b38
DT
10837 if (read_only && (s->flags & SEC_READONLY) == 0)
10838 continue; /* Skip writeable sections */
10839
2c500098 10840 size = bfd_get_section_size (s);
c906108c 10841 if (size == 0)
0df8b418 10842 continue; /* Skip zero-length section. */
c906108c 10843
ce359b09 10844 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10845 if (args && strcmp (args, sectname) != 0)
0df8b418 10846 continue; /* Not the section selected by user. */
c906108c 10847
0df8b418 10848 matched = 1; /* Do this section. */
c906108c 10849 lma = s->lma;
c906108c 10850
b80406ac
TT
10851 gdb::byte_vector sectdata (size);
10852 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
c906108c 10853
b80406ac 10854 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
10855
10856 if (res == -1)
5af949e3 10857 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10858 paddress (target_gdbarch (), lma),
10859 paddress (target_gdbarch (), lma + size));
c906108c 10860
5af949e3 10861 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10862 paddress (target_gdbarch (), lma),
10863 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10864 if (res)
c906108c
SS
10865 printf_filtered ("matched.\n");
10866 else
c5aa993b
JM
10867 {
10868 printf_filtered ("MIS-MATCHED!\n");
10869 mismatched++;
10870 }
c906108c
SS
10871 }
10872 if (mismatched > 0)
936d2992 10873 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10874the loaded file\n"));
c906108c 10875 if (args && !matched)
a3f17187 10876 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10877}
10878
0e7f50da
UW
10879/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10880 into remote target. The number of bytes written to the remote
10881 target is returned, or -1 for error. */
10882
6b8edb51
PA
10883target_xfer_status
10884remote_target::remote_write_qxfer (const char *object_name,
10885 const char *annex, const gdb_byte *writebuf,
10886 ULONGEST offset, LONGEST len,
10887 ULONGEST *xfered_len,
10888 struct packet_config *packet)
0e7f50da
UW
10889{
10890 int i, buf_len;
10891 ULONGEST n;
0e7f50da
UW
10892 struct remote_state *rs = get_remote_state ();
10893 int max_size = get_memory_write_packet_size ();
10894
7cc244de 10895 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10896 return TARGET_XFER_E_IO;
0e7f50da
UW
10897
10898 /* Insert header. */
10899 i = snprintf (rs->buf, max_size,
10900 "qXfer:%s:write:%s:%s:",
10901 object_name, annex ? annex : "",
10902 phex_nz (offset, sizeof offset));
10903 max_size -= (i + 1);
10904
10905 /* Escape as much data as fits into rs->buf. */
10906 buf_len = remote_escape_output
124e13d9 10907 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
10908
10909 if (putpkt_binary (rs->buf, i + buf_len) < 0
10910 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10911 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10912 return TARGET_XFER_E_IO;
0e7f50da
UW
10913
10914 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
10915
10916 *xfered_len = n;
92ffd475 10917 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
10918}
10919
0876f84a
DJ
10920/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10921 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10922 number of bytes read is returned, or 0 for EOF, or -1 for error.
10923 The number of bytes read may be less than LEN without indicating an
10924 EOF. PACKET is checked and updated to indicate whether the remote
10925 target supports this object. */
10926
6b8edb51
PA
10927target_xfer_status
10928remote_target::remote_read_qxfer (const char *object_name,
10929 const char *annex,
10930 gdb_byte *readbuf, ULONGEST offset,
10931 LONGEST len,
10932 ULONGEST *xfered_len,
10933 struct packet_config *packet)
0876f84a 10934{
0876f84a 10935 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10936 LONGEST i, n, packet_len;
10937
7cc244de 10938 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10939 return TARGET_XFER_E_IO;
0876f84a
DJ
10940
10941 /* Check whether we've cached an end-of-object packet that matches
10942 this request. */
8e88304f 10943 if (rs->finished_object)
0876f84a 10944 {
8e88304f
TT
10945 if (strcmp (object_name, rs->finished_object) == 0
10946 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10947 && offset == rs->finished_offset)
9b409511
YQ
10948 return TARGET_XFER_EOF;
10949
0876f84a
DJ
10950
10951 /* Otherwise, we're now reading something different. Discard
10952 the cache. */
8e88304f
TT
10953 xfree (rs->finished_object);
10954 xfree (rs->finished_annex);
10955 rs->finished_object = NULL;
10956 rs->finished_annex = NULL;
0876f84a
DJ
10957 }
10958
10959 /* Request only enough to fit in a single packet. The actual data
10960 may not, since we don't know how much of it will need to be escaped;
10961 the target is free to respond with slightly less data. We subtract
10962 five to account for the response type and the protocol frame. */
768adc05 10963 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
0876f84a
DJ
10964 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10965 object_name, annex ? annex : "",
10966 phex_nz (offset, sizeof offset),
10967 phex_nz (n, sizeof n));
10968 i = putpkt (rs->buf);
10969 if (i < 0)
2ed4b548 10970 return TARGET_XFER_E_IO;
0876f84a
DJ
10971
10972 rs->buf[0] = '\0';
10973 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10974 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10975 return TARGET_XFER_E_IO;
0876f84a
DJ
10976
10977 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10978 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10979
10980 /* 'm' means there is (or at least might be) more data after this
10981 batch. That does not make sense unless there's at least one byte
10982 of data in this reply. */
10983 if (rs->buf[0] == 'm' && packet_len == 1)
10984 error (_("Remote qXfer reply contained no data."));
10985
10986 /* Got some data. */
bc20a4af
PA
10987 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10988 packet_len - 1, readbuf, n);
0876f84a
DJ
10989
10990 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10991 or possibly empty. If we have the final block of a non-empty
10992 object, record this fact to bypass a subsequent partial read. */
10993 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10994 {
8e88304f
TT
10995 rs->finished_object = xstrdup (object_name);
10996 rs->finished_annex = xstrdup (annex ? annex : "");
10997 rs->finished_offset = offset + i;
0876f84a
DJ
10998 }
10999
9b409511
YQ
11000 if (i == 0)
11001 return TARGET_XFER_EOF;
11002 else
11003 {
11004 *xfered_len = i;
11005 return TARGET_XFER_OK;
11006 }
0876f84a
DJ
11007}
11008
f6ac5f3d
PA
11009enum target_xfer_status
11010remote_target::xfer_partial (enum target_object object,
11011 const char *annex, gdb_byte *readbuf,
11012 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11013 ULONGEST *xfered_len)
c906108c 11014{
82f73884 11015 struct remote_state *rs;
c906108c 11016 int i;
6d820c5c 11017 char *p2;
1e3ff5ad 11018 char query_type;
124e13d9 11019 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 11020
e6e4e701 11021 set_remote_traceframe ();
82f73884
PA
11022 set_general_thread (inferior_ptid);
11023
11024 rs = get_remote_state ();
11025
b2182ed2 11026 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
11027 if (object == TARGET_OBJECT_MEMORY)
11028 {
2d717e4f
DJ
11029 /* If the remote target is connected but not running, we should
11030 pass this request down to a lower stratum (e.g. the executable
11031 file). */
11032 if (!target_has_execution)
9b409511 11033 return TARGET_XFER_EOF;
2d717e4f 11034
21e3b9b9 11035 if (writebuf != NULL)
124e13d9
SM
11036 return remote_write_bytes (offset, writebuf, len, unit_size,
11037 xfered_len);
21e3b9b9 11038 else
6b8edb51 11039 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 11040 xfered_len);
21e3b9b9
DJ
11041 }
11042
0df8b418 11043 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
11044 if (object == TARGET_OBJECT_SPU)
11045 {
11046 if (readbuf)
f6ac5f3d 11047 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
9b409511
YQ
11048 xfered_len, &remote_protocol_packets
11049 [PACKET_qXfer_spu_read]);
0e7f50da 11050 else
f6ac5f3d 11051 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
9b409511
YQ
11052 xfered_len, &remote_protocol_packets
11053 [PACKET_qXfer_spu_write]);
0e7f50da
UW
11054 }
11055
4aa995e1
PA
11056 /* Handle extra signal info using qxfer packets. */
11057 if (object == TARGET_OBJECT_SIGNAL_INFO)
11058 {
11059 if (readbuf)
f6ac5f3d 11060 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
9b409511 11061 xfered_len, &remote_protocol_packets
4aa995e1
PA
11062 [PACKET_qXfer_siginfo_read]);
11063 else
f6ac5f3d 11064 return remote_write_qxfer ("siginfo", annex,
9b409511 11065 writebuf, offset, len, xfered_len,
4aa995e1
PA
11066 &remote_protocol_packets
11067 [PACKET_qXfer_siginfo_write]);
11068 }
11069
0fb4aa4b
PA
11070 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11071 {
11072 if (readbuf)
f6ac5f3d 11073 return remote_read_qxfer ("statictrace", annex,
9b409511 11074 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
11075 &remote_protocol_packets
11076 [PACKET_qXfer_statictrace_read]);
11077 else
2ed4b548 11078 return TARGET_XFER_E_IO;
0fb4aa4b
PA
11079 }
11080
a76d924d
DJ
11081 /* Only handle flash writes. */
11082 if (writebuf != NULL)
11083 {
a76d924d
DJ
11084 switch (object)
11085 {
11086 case TARGET_OBJECT_FLASH:
6b8edb51 11087 return remote_flash_write (offset, len, xfered_len,
9b409511 11088 writebuf);
a76d924d
DJ
11089
11090 default:
2ed4b548 11091 return TARGET_XFER_E_IO;
a76d924d
DJ
11092 }
11093 }
4b8a223f 11094
1e3ff5ad
AC
11095 /* Map pre-existing objects onto letters. DO NOT do this for new
11096 objects!!! Instead specify new query packets. */
11097 switch (object)
c906108c 11098 {
1e3ff5ad
AC
11099 case TARGET_OBJECT_AVR:
11100 query_type = 'R';
11101 break;
802188a7
RM
11102
11103 case TARGET_OBJECT_AUXV:
0876f84a 11104 gdb_assert (annex == NULL);
f6ac5f3d 11105 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
9b409511 11106 xfered_len,
0876f84a 11107 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 11108
23181151
DJ
11109 case TARGET_OBJECT_AVAILABLE_FEATURES:
11110 return remote_read_qxfer
f6ac5f3d 11111 ("features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
11112 &remote_protocol_packets[PACKET_qXfer_features]);
11113
cfa9d6d9
DJ
11114 case TARGET_OBJECT_LIBRARIES:
11115 return remote_read_qxfer
f6ac5f3d 11116 ("libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
11117 &remote_protocol_packets[PACKET_qXfer_libraries]);
11118
2268b414
JK
11119 case TARGET_OBJECT_LIBRARIES_SVR4:
11120 return remote_read_qxfer
f6ac5f3d 11121 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
11122 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11123
fd79ecee
DJ
11124 case TARGET_OBJECT_MEMORY_MAP:
11125 gdb_assert (annex == NULL);
f6ac5f3d 11126 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
9b409511 11127 xfered_len,
fd79ecee
DJ
11128 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11129
07e059b5
VP
11130 case TARGET_OBJECT_OSDATA:
11131 /* Should only get here if we're connected. */
5d93a237 11132 gdb_assert (rs->remote_desc);
07e059b5 11133 return remote_read_qxfer
f6ac5f3d 11134 ("osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
11135 &remote_protocol_packets[PACKET_qXfer_osdata]);
11136
dc146f7c
VP
11137 case TARGET_OBJECT_THREADS:
11138 gdb_assert (annex == NULL);
f6ac5f3d 11139 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
9b409511 11140 xfered_len,
dc146f7c
VP
11141 &remote_protocol_packets[PACKET_qXfer_threads]);
11142
b3b9301e
PA
11143 case TARGET_OBJECT_TRACEFRAME_INFO:
11144 gdb_assert (annex == NULL);
11145 return remote_read_qxfer
f6ac5f3d 11146 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 11147 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
11148
11149 case TARGET_OBJECT_FDPIC:
f6ac5f3d 11150 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
9b409511 11151 xfered_len,
78d85199 11152 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
11153
11154 case TARGET_OBJECT_OPENVMS_UIB:
f6ac5f3d 11155 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
9b409511 11156 xfered_len,
169081d0
TG
11157 &remote_protocol_packets[PACKET_qXfer_uib]);
11158
9accd112 11159 case TARGET_OBJECT_BTRACE:
f6ac5f3d 11160 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
9b409511 11161 xfered_len,
9accd112
MM
11162 &remote_protocol_packets[PACKET_qXfer_btrace]);
11163
f4abbc16 11164 case TARGET_OBJECT_BTRACE_CONF:
f6ac5f3d 11165 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
f4abbc16
MM
11166 len, xfered_len,
11167 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11168
c78fa86a 11169 case TARGET_OBJECT_EXEC_FILE:
f6ac5f3d 11170 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
c78fa86a
GB
11171 len, xfered_len,
11172 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11173
1e3ff5ad 11174 default:
2ed4b548 11175 return TARGET_XFER_E_IO;
c906108c
SS
11176 }
11177
0df8b418 11178 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11179 large enough let the caller deal with it. */
ea9c271d 11180 if (len < get_remote_packet_size ())
2ed4b548 11181 return TARGET_XFER_E_IO;
ea9c271d 11182 len = get_remote_packet_size ();
1e3ff5ad 11183
23860348 11184 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11185 if (!rs->remote_desc)
8a3fe4f8 11186 error (_("remote query is only available after target open"));
c906108c 11187
1e3ff5ad 11188 gdb_assert (annex != NULL);
4b8a223f 11189 gdb_assert (readbuf != NULL);
c906108c 11190
6d820c5c 11191 p2 = rs->buf;
c906108c
SS
11192 *p2++ = 'q';
11193 *p2++ = query_type;
11194
23860348
MS
11195 /* We used one buffer char for the remote protocol q command and
11196 another for the query type. As the remote protocol encapsulation
11197 uses 4 chars plus one extra in case we are debugging
11198 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11199 string. */
c906108c 11200 i = 0;
ea9c271d 11201 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11202 {
1e3ff5ad
AC
11203 /* Bad caller may have sent forbidden characters. */
11204 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11205 *p2++ = annex[i];
c906108c
SS
11206 i++;
11207 }
1e3ff5ad
AC
11208 *p2 = '\0';
11209 gdb_assert (annex[i] == '\0');
c906108c 11210
6d820c5c 11211 i = putpkt (rs->buf);
c5aa993b 11212 if (i < 0)
2ed4b548 11213 return TARGET_XFER_E_IO;
c906108c 11214
6d820c5c
DJ
11215 getpkt (&rs->buf, &rs->buf_size, 0);
11216 strcpy ((char *) readbuf, rs->buf);
c906108c 11217
9b409511 11218 *xfered_len = strlen ((char *) readbuf);
92ffd475 11219 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11220}
11221
09c98b44
DB
11222/* Implementation of to_get_memory_xfer_limit. */
11223
f6ac5f3d
PA
11224ULONGEST
11225remote_target::get_memory_xfer_limit ()
09c98b44
DB
11226{
11227 return get_memory_write_packet_size ();
11228}
11229
f6ac5f3d
PA
11230int
11231remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11232 const gdb_byte *pattern, ULONGEST pattern_len,
11233 CORE_ADDR *found_addrp)
08388c79 11234{
f5656ead 11235 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
11236 struct remote_state *rs = get_remote_state ();
11237 int max_size = get_memory_write_packet_size ();
11238 struct packet_config *packet =
11239 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
11240 /* Number of packet bytes used to encode the pattern;
11241 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11242 int escaped_pattern_len;
0df8b418 11243 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11244 int used_pattern_len;
11245 int i;
11246 int found;
11247 ULONGEST found_addr;
11248
7cc244de
PA
11249 /* Don't go to the target if we don't have to. This is done before
11250 checking packet_config_support to avoid the possibility that a
11251 success for this edge case means the facility works in
11252 general. */
08388c79
DE
11253 if (pattern_len > search_space_len)
11254 return 0;
11255 if (pattern_len == 0)
11256 {
11257 *found_addrp = start_addr;
11258 return 1;
11259 }
11260
11261 /* If we already know the packet isn't supported, fall back to the simple
11262 way of searching memory. */
11263
4082afcc 11264 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
11265 {
11266 /* Target doesn't provided special support, fall back and use the
11267 standard support (copy memory and do the search here). */
f6ac5f3d 11268 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11269 pattern, pattern_len, found_addrp);
11270 }
11271
28439a30
PA
11272 /* Make sure the remote is pointing at the right process. */
11273 set_general_process ();
11274
08388c79
DE
11275 /* Insert header. */
11276 i = snprintf (rs->buf, max_size,
11277 "qSearch:memory:%s;%s;",
5af949e3 11278 phex_nz (start_addr, addr_size),
08388c79
DE
11279 phex_nz (search_space_len, sizeof (search_space_len)));
11280 max_size -= (i + 1);
11281
11282 /* Escape as much data as fits into rs->buf. */
11283 escaped_pattern_len =
124e13d9 11284 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
11285 &used_pattern_len, max_size);
11286
11287 /* Bail if the pattern is too large. */
11288 if (used_pattern_len != pattern_len)
9b20d036 11289 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
11290
11291 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11292 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11293 || packet_ok (rs->buf, packet) != PACKET_OK)
11294 {
11295 /* The request may not have worked because the command is not
11296 supported. If so, fall back to the simple way. */
7cc244de 11297 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79 11298 {
f6ac5f3d 11299 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11300 pattern, pattern_len, found_addrp);
11301 }
11302 return -1;
11303 }
11304
11305 if (rs->buf[0] == '0')
11306 found = 0;
11307 else if (rs->buf[0] == '1')
11308 {
11309 found = 1;
11310 if (rs->buf[1] != ',')
10e0fa18 11311 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
11312 unpack_varlen_hex (rs->buf + 2, &found_addr);
11313 *found_addrp = found_addr;
11314 }
11315 else
10e0fa18 11316 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
11317
11318 return found;
11319}
11320
f6ac5f3d
PA
11321void
11322remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11323{
d01949b6 11324 struct remote_state *rs = get_remote_state ();
2e9f7625 11325 char *p = rs->buf;
96baa820 11326
5d93a237 11327 if (!rs->remote_desc)
8a3fe4f8 11328 error (_("remote rcmd is only available after target open"));
96baa820 11329
23860348 11330 /* Send a NULL command across as an empty command. */
7be570e7
JM
11331 if (command == NULL)
11332 command = "";
11333
23860348 11334 /* The query prefix. */
2e9f7625
DJ
11335 strcpy (rs->buf, "qRcmd,");
11336 p = strchr (rs->buf, '\0');
96baa820 11337
3e43a32a
MS
11338 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11339 > get_remote_packet_size ())
8a3fe4f8 11340 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11341
23860348 11342 /* Encode the actual command. */
a30bf1f1 11343 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11344
6d820c5c 11345 if (putpkt (rs->buf) < 0)
8a3fe4f8 11346 error (_("Communication problem with target."));
96baa820
JM
11347
11348 /* get/display the response */
11349 while (1)
11350 {
2e9f7625
DJ
11351 char *buf;
11352
00bf0b85 11353 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11354 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11355 rs->buf[0] = '\0';
5b37825d
PW
11356 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11357 {
11358 /* Timeout. Continue to (try to) read responses.
11359 This is better than stopping with an error, assuming the stub
11360 is still executing the (long) monitor command.
11361 If needed, the user can interrupt gdb using C-c, obtaining
11362 an effect similar to stop on timeout. */
11363 continue;
11364 }
2e9f7625 11365 buf = rs->buf;
96baa820 11366 if (buf[0] == '\0')
8a3fe4f8 11367 error (_("Target does not support this command."));
96baa820
JM
11368 if (buf[0] == 'O' && buf[1] != 'K')
11369 {
23860348 11370 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11371 continue;
11372 }
11373 if (strcmp (buf, "OK") == 0)
11374 break;
7be570e7
JM
11375 if (strlen (buf) == 3 && buf[0] == 'E'
11376 && isdigit (buf[1]) && isdigit (buf[2]))
11377 {
8a3fe4f8 11378 error (_("Protocol error with Rcmd"));
7be570e7 11379 }
96baa820
JM
11380 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11381 {
11382 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11383
96baa820
JM
11384 fputc_unfiltered (c, outbuf);
11385 }
11386 break;
11387 }
11388}
11389
f6ac5f3d
PA
11390std::vector<mem_region>
11391remote_target::memory_map ()
fd79ecee 11392{
a664f67e 11393 std::vector<mem_region> result;
9018be22 11394 gdb::optional<gdb::char_vector> text
f6ac5f3d 11395 = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11396
11397 if (text)
9018be22 11398 result = parse_memory_map (text->data ());
fd79ecee
DJ
11399
11400 return result;
11401}
11402
c906108c 11403static void
ac88e2de 11404packet_command (const char *args, int from_tty)
c906108c 11405{
6b8edb51 11406 remote_target *remote = get_current_remote_target ();
c906108c 11407
6b8edb51 11408 if (remote == nullptr)
8a3fe4f8 11409 error (_("command can only be used with remote target"));
c906108c 11410
6b8edb51
PA
11411 remote->packet_command (args, from_tty);
11412}
11413
11414void
11415remote_target::packet_command (const char *args, int from_tty)
11416{
c5aa993b 11417 if (!args)
8a3fe4f8 11418 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
11419
11420 puts_filtered ("sending: ");
11421 print_packet (args);
11422 puts_filtered ("\n");
11423 putpkt (args);
11424
6b8edb51
PA
11425 remote_state *rs = get_remote_state ();
11426
6d820c5c 11427 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 11428 puts_filtered ("received: ");
6d820c5c 11429 print_packet (rs->buf);
c906108c
SS
11430 puts_filtered ("\n");
11431}
11432
11433#if 0
23860348 11434/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11435
a14ed312 11436static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11437
a14ed312 11438static void threadset_test_cmd (char *cmd, int tty);
c906108c 11439
a14ed312 11440static void threadalive_test (char *cmd, int tty);
c906108c 11441
a14ed312 11442static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11443
23860348 11444int get_and_display_threadinfo (threadref *ref);
c906108c 11445
a14ed312 11446static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11447
23860348 11448static int thread_display_step (threadref *ref, void *context);
c906108c 11449
a14ed312 11450static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11451
a14ed312 11452static void init_remote_threadtests (void);
c906108c 11453
23860348 11454#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11455
11456static void
0b39b52e 11457threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11458{
11459 int sample_thread = SAMPLE_THREAD;
11460
a3f17187 11461 printf_filtered (_("Remote threadset test\n"));
79d7f229 11462 set_general_thread (sample_thread);
c906108c
SS
11463}
11464
11465
11466static void
0b39b52e 11467threadalive_test (const char *cmd, int tty)
c906108c
SS
11468{
11469 int sample_thread = SAMPLE_THREAD;
79d7f229 11470 int pid = ptid_get_pid (inferior_ptid);
ba348170 11471 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 11472
79d7f229 11473 if (remote_thread_alive (ptid))
c906108c
SS
11474 printf_filtered ("PASS: Thread alive test\n");
11475 else
11476 printf_filtered ("FAIL: Thread alive test\n");
11477}
11478
23860348 11479void output_threadid (char *title, threadref *ref);
c906108c
SS
11480
11481void
fba45db2 11482output_threadid (char *title, threadref *ref)
c906108c
SS
11483{
11484 char hexid[20];
11485
23860348 11486 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
11487 hexid[16] = 0;
11488 printf_filtered ("%s %s\n", title, (&hexid[0]));
11489}
11490
11491static void
0b39b52e 11492threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11493{
11494 int startflag = 1;
11495 threadref nextthread;
11496 int done, result_count;
11497 threadref threadlist[3];
11498
11499 printf_filtered ("Remote Threadlist test\n");
11500 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11501 &result_count, &threadlist[0]))
11502 printf_filtered ("FAIL: threadlist test\n");
11503 else
11504 {
11505 threadref *scan = threadlist;
11506 threadref *limit = scan + result_count;
11507
11508 while (scan < limit)
11509 output_threadid (" thread ", scan++);
11510 }
11511}
11512
11513void
fba45db2 11514display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11515{
11516 output_threadid ("Threadid: ", &info->threadid);
11517 printf_filtered ("Name: %s\n ", info->shortname);
11518 printf_filtered ("State: %s\n", info->display);
11519 printf_filtered ("other: %s\n\n", info->more_display);
11520}
11521
11522int
fba45db2 11523get_and_display_threadinfo (threadref *ref)
c906108c
SS
11524{
11525 int result;
11526 int set;
11527 struct gdb_ext_thread_info threadinfo;
11528
11529 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11530 | TAG_MOREDISPLAY | TAG_DISPLAY;
11531 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11532 display_thread_info (&threadinfo);
11533 return result;
11534}
11535
11536static void
0b39b52e 11537threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11538{
11539 int athread = SAMPLE_THREAD;
11540 threadref thread;
11541 int set;
11542
11543 int_to_threadref (&thread, athread);
11544 printf_filtered ("Remote Threadinfo test\n");
11545 if (!get_and_display_threadinfo (&thread))
11546 printf_filtered ("FAIL cannot get thread info\n");
11547}
11548
11549static int
fba45db2 11550thread_display_step (threadref *ref, void *context)
c906108c
SS
11551{
11552 /* output_threadid(" threadstep ",ref); *//* simple test */
11553 return get_and_display_threadinfo (ref);
11554}
11555
11556static void
0b39b52e 11557threadlist_update_test_cmd (const char *cmd, int tty)
c906108c
SS
11558{
11559 printf_filtered ("Remote Threadlist update test\n");
11560 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11561}
11562
11563static void
11564init_remote_threadtests (void)
11565{
3e43a32a
MS
11566 add_com ("tlist", class_obscure, threadlist_test_cmd,
11567 _("Fetch and print the remote list of "
11568 "thread identifiers, one pkt only"));
c906108c 11569 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 11570 _("Fetch and display info about one thread"));
c906108c 11571 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 11572 _("Test setting to a different thread"));
c906108c 11573 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 11574 _("Iterate through updating all remote thread info"));
c906108c 11575 add_com ("talive", class_obscure, threadalive_test,
1bedd215 11576 _(" Remote thread alive test "));
c906108c
SS
11577}
11578
11579#endif /* 0 */
11580
f3fb8c85
MS
11581/* Convert a thread ID to a string. Returns the string in a static
11582 buffer. */
11583
f6ac5f3d
PA
11584const char *
11585remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11586{
79d7f229 11587 static char buf[64];
82f73884 11588 struct remote_state *rs = get_remote_state ();
f3fb8c85 11589
7cee1e54
PA
11590 if (ptid_equal (ptid, null_ptid))
11591 return normal_pid_to_str (ptid);
11592 else if (ptid_is_pid (ptid))
ecd0ada5
PA
11593 {
11594 /* Printing an inferior target id. */
11595
11596 /* When multi-process extensions are off, there's no way in the
11597 remote protocol to know the remote process id, if there's any
11598 at all. There's one exception --- when we're connected with
11599 target extended-remote, and we manually attached to a process
11600 with "attach PID". We don't record anywhere a flag that
11601 allows us to distinguish that case from the case of
11602 connecting with extended-remote and the stub already being
11603 attached to a process, and reporting yes to qAttached, hence
11604 no smart special casing here. */
11605 if (!remote_multi_process_p (rs))
11606 {
11607 xsnprintf (buf, sizeof buf, "Remote target");
11608 return buf;
11609 }
11610
11611 return normal_pid_to_str (ptid);
82f73884 11612 }
ecd0ada5 11613 else
79d7f229 11614 {
ecd0ada5
PA
11615 if (ptid_equal (magic_null_ptid, ptid))
11616 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 11617 else if (remote_multi_process_p (rs))
de0d863e
DB
11618 if (ptid_get_lwp (ptid) == 0)
11619 return normal_pid_to_str (ptid);
11620 else
11621 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11622 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
11623 else
11624 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 11625 ptid_get_lwp (ptid));
79d7f229
PA
11626 return buf;
11627 }
f3fb8c85
MS
11628}
11629
38691318
KB
11630/* Get the address of the thread local variable in OBJFILE which is
11631 stored at OFFSET within the thread local storage for thread PTID. */
11632
f6ac5f3d
PA
11633CORE_ADDR
11634remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11635 CORE_ADDR offset)
38691318 11636{
4082afcc 11637 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11638 {
11639 struct remote_state *rs = get_remote_state ();
6d820c5c 11640 char *p = rs->buf;
82f73884 11641 char *endp = rs->buf + get_remote_packet_size ();
571dd617 11642 enum packet_result result;
38691318
KB
11643
11644 strcpy (p, "qGetTLSAddr:");
11645 p += strlen (p);
82f73884 11646 p = write_ptid (p, endp, ptid);
38691318
KB
11647 *p++ = ',';
11648 p += hexnumstr (p, offset);
11649 *p++ = ',';
11650 p += hexnumstr (p, lm);
11651 *p++ = '\0';
11652
6d820c5c
DJ
11653 putpkt (rs->buf);
11654 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
11655 result = packet_ok (rs->buf,
11656 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11657 if (result == PACKET_OK)
38691318
KB
11658 {
11659 ULONGEST result;
11660
6d820c5c 11661 unpack_varlen_hex (rs->buf, &result);
38691318
KB
11662 return result;
11663 }
571dd617 11664 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11665 throw_error (TLS_GENERIC_ERROR,
11666 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11667 else
109c3e39
AC
11668 throw_error (TLS_GENERIC_ERROR,
11669 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11670 }
11671 else
109c3e39
AC
11672 throw_error (TLS_GENERIC_ERROR,
11673 _("TLS not supported or disabled on this target"));
38691318
KB
11674 /* Not reached. */
11675 return 0;
11676}
11677
711e434b
PM
11678/* Provide thread local base, i.e. Thread Information Block address.
11679 Returns 1 if ptid is found and thread_local_base is non zero. */
11680
57810aa7 11681bool
f6ac5f3d 11682remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 11683{
4082afcc 11684 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11685 {
11686 struct remote_state *rs = get_remote_state ();
11687 char *p = rs->buf;
11688 char *endp = rs->buf + get_remote_packet_size ();
11689 enum packet_result result;
11690
11691 strcpy (p, "qGetTIBAddr:");
11692 p += strlen (p);
11693 p = write_ptid (p, endp, ptid);
11694 *p++ = '\0';
11695
11696 putpkt (rs->buf);
11697 getpkt (&rs->buf, &rs->buf_size, 0);
11698 result = packet_ok (rs->buf,
11699 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11700 if (result == PACKET_OK)
11701 {
11702 ULONGEST result;
11703
11704 unpack_varlen_hex (rs->buf, &result);
11705 if (addr)
11706 *addr = (CORE_ADDR) result;
57810aa7 11707 return true;
711e434b
PM
11708 }
11709 else if (result == PACKET_UNKNOWN)
11710 error (_("Remote target doesn't support qGetTIBAddr packet"));
11711 else
11712 error (_("Remote target failed to process qGetTIBAddr request"));
11713 }
11714 else
11715 error (_("qGetTIBAddr not supported or disabled on this target"));
11716 /* Not reached. */
57810aa7 11717 return false;
711e434b
PM
11718}
11719
29709017
DJ
11720/* Support for inferring a target description based on the current
11721 architecture and the size of a 'g' packet. While the 'g' packet
11722 can have any size (since optional registers can be left off the
11723 end), some sizes are easily recognizable given knowledge of the
11724 approximate architecture. */
11725
11726struct remote_g_packet_guess
11727{
11728 int bytes;
11729 const struct target_desc *tdesc;
11730};
11731typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11732DEF_VEC_O(remote_g_packet_guess_s);
11733
11734struct remote_g_packet_data
11735{
11736 VEC(remote_g_packet_guess_s) *guesses;
11737};
11738
11739static struct gdbarch_data *remote_g_packet_data_handle;
11740
11741static void *
11742remote_g_packet_data_init (struct obstack *obstack)
11743{
11744 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11745}
11746
11747void
11748register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11749 const struct target_desc *tdesc)
11750{
11751 struct remote_g_packet_data *data
19ba03f4
SM
11752 = ((struct remote_g_packet_data *)
11753 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11754 struct remote_g_packet_guess new_guess, *guess;
11755 int ix;
11756
11757 gdb_assert (tdesc != NULL);
11758
11759 for (ix = 0;
11760 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11761 ix++)
11762 if (guess->bytes == bytes)
11763 internal_error (__FILE__, __LINE__,
9b20d036 11764 _("Duplicate g packet description added for size %d"),
29709017
DJ
11765 bytes);
11766
11767 new_guess.bytes = bytes;
11768 new_guess.tdesc = tdesc;
11769 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11770}
11771
d962ef82
DJ
11772/* Return 1 if remote_read_description would do anything on this target
11773 and architecture, 0 otherwise. */
11774
11775static int
11776remote_read_description_p (struct target_ops *target)
11777{
11778 struct remote_g_packet_data *data
19ba03f4
SM
11779 = ((struct remote_g_packet_data *)
11780 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
11781
11782 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11783 return 1;
11784
11785 return 0;
11786}
11787
f6ac5f3d
PA
11788const struct target_desc *
11789remote_target::read_description ()
29709017
DJ
11790{
11791 struct remote_g_packet_data *data
19ba03f4
SM
11792 = ((struct remote_g_packet_data *)
11793 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11794
d962ef82
DJ
11795 /* Do not try this during initial connection, when we do not know
11796 whether there is a running but stopped thread. */
11797 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
f6ac5f3d 11798 return beneath->read_description ();
d962ef82 11799
29709017
DJ
11800 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11801 {
11802 struct remote_g_packet_guess *guess;
11803 int ix;
11804 int bytes = send_g_packet ();
11805
11806 for (ix = 0;
11807 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11808 ix++)
11809 if (guess->bytes == bytes)
11810 return guess->tdesc;
11811
11812 /* We discard the g packet. A minor optimization would be to
11813 hold on to it, and fill the register cache once we have selected
11814 an architecture, but it's too tricky to do safely. */
11815 }
11816
f6ac5f3d 11817 return beneath->read_description ();
29709017
DJ
11818}
11819
a6b151f1
DJ
11820/* Remote file transfer support. This is host-initiated I/O, not
11821 target-initiated; for target-initiated, see remote-fileio.c. */
11822
11823/* If *LEFT is at least the length of STRING, copy STRING to
11824 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11825 decrease *LEFT. Otherwise raise an error. */
11826
11827static void
a121b7c1 11828remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11829{
11830 int len = strlen (string);
11831
11832 if (len > *left)
11833 error (_("Packet too long for target."));
11834
11835 memcpy (*buffer, string, len);
11836 *buffer += len;
11837 *left -= len;
11838
11839 /* NUL-terminate the buffer as a convenience, if there is
11840 room. */
11841 if (*left)
11842 **buffer = '\0';
11843}
11844
11845/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11846 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11847 decrease *LEFT. Otherwise raise an error. */
11848
11849static void
11850remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11851 int len)
11852{
11853 if (2 * len > *left)
11854 error (_("Packet too long for target."));
11855
11856 bin2hex (bytes, *buffer, len);
11857 *buffer += 2 * len;
11858 *left -= 2 * len;
11859
11860 /* NUL-terminate the buffer as a convenience, if there is
11861 room. */
11862 if (*left)
11863 **buffer = '\0';
11864}
11865
11866/* If *LEFT is large enough, convert VALUE to hex and add it to
11867 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11868 decrease *LEFT. Otherwise raise an error. */
11869
11870static void
11871remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11872{
11873 int len = hexnumlen (value);
11874
11875 if (len > *left)
11876 error (_("Packet too long for target."));
11877
11878 hexnumstr (*buffer, value);
11879 *buffer += len;
11880 *left -= len;
11881
11882 /* NUL-terminate the buffer as a convenience, if there is
11883 room. */
11884 if (*left)
11885 **buffer = '\0';
11886}
11887
11888/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11889 value, *REMOTE_ERRNO to the remote error number or zero if none
11890 was included, and *ATTACHMENT to point to the start of the annex
11891 if any. The length of the packet isn't needed here; there may
11892 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11893
11894 Return 0 if the packet could be parsed, -1 if it could not. If
11895 -1 is returned, the other variables may not be initialized. */
11896
11897static int
11898remote_hostio_parse_result (char *buffer, int *retcode,
11899 int *remote_errno, char **attachment)
11900{
11901 char *p, *p2;
11902
11903 *remote_errno = 0;
11904 *attachment = NULL;
11905
11906 if (buffer[0] != 'F')
11907 return -1;
11908
11909 errno = 0;
11910 *retcode = strtol (&buffer[1], &p, 16);
11911 if (errno != 0 || p == &buffer[1])
11912 return -1;
11913
11914 /* Check for ",errno". */
11915 if (*p == ',')
11916 {
11917 errno = 0;
11918 *remote_errno = strtol (p + 1, &p2, 16);
11919 if (errno != 0 || p + 1 == p2)
11920 return -1;
11921 p = p2;
11922 }
11923
11924 /* Check for ";attachment". If there is no attachment, the
11925 packet should end here. */
11926 if (*p == ';')
11927 {
11928 *attachment = p + 1;
11929 return 0;
11930 }
11931 else if (*p == '\0')
11932 return 0;
11933 else
11934 return -1;
11935}
11936
11937/* Send a prepared I/O packet to the target and read its response.
11938 The prepared packet is in the global RS->BUF before this function
11939 is called, and the answer is there when we return.
11940
11941 COMMAND_BYTES is the length of the request to send, which may include
11942 binary data. WHICH_PACKET is the packet configuration to check
11943 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11944 is set to the error number and -1 is returned. Otherwise the value
11945 returned by the function is returned.
11946
11947 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11948 attachment is expected; an error will be reported if there's a
11949 mismatch. If one is found, *ATTACHMENT will be set to point into
11950 the packet buffer and *ATTACHMENT_LEN will be set to the
11951 attachment's length. */
11952
6b8edb51
PA
11953int
11954remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11955 int *remote_errno, char **attachment,
11956 int *attachment_len)
a6b151f1
DJ
11957{
11958 struct remote_state *rs = get_remote_state ();
11959 int ret, bytes_read;
11960 char *attachment_tmp;
11961
20db9c52 11962 if (packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11963 {
11964 *remote_errno = FILEIO_ENOSYS;
11965 return -1;
11966 }
11967
11968 putpkt_binary (rs->buf, command_bytes);
11969 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11970
11971 /* If it timed out, something is wrong. Don't try to parse the
11972 buffer. */
11973 if (bytes_read < 0)
11974 {
11975 *remote_errno = FILEIO_EINVAL;
11976 return -1;
11977 }
11978
11979 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11980 {
11981 case PACKET_ERROR:
11982 *remote_errno = FILEIO_EINVAL;
11983 return -1;
11984 case PACKET_UNKNOWN:
11985 *remote_errno = FILEIO_ENOSYS;
11986 return -1;
11987 case PACKET_OK:
11988 break;
11989 }
11990
11991 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11992 &attachment_tmp))
11993 {
11994 *remote_errno = FILEIO_EINVAL;
11995 return -1;
11996 }
11997
11998 /* Make sure we saw an attachment if and only if we expected one. */
11999 if ((attachment_tmp == NULL && attachment != NULL)
12000 || (attachment_tmp != NULL && attachment == NULL))
12001 {
12002 *remote_errno = FILEIO_EINVAL;
12003 return -1;
12004 }
12005
12006 /* If an attachment was found, it must point into the packet buffer;
12007 work out how many bytes there were. */
12008 if (attachment_tmp != NULL)
12009 {
12010 *attachment = attachment_tmp;
12011 *attachment_len = bytes_read - (*attachment - rs->buf);
12012 }
12013
12014 return ret;
12015}
12016
dd194f6b 12017/* See declaration.h. */
80152258 12018
dd194f6b
PA
12019void
12020readahead_cache::invalidate ()
80152258 12021{
dd194f6b 12022 this->fd = -1;
80152258
PA
12023}
12024
dd194f6b 12025/* See declaration.h. */
80152258 12026
dd194f6b
PA
12027void
12028readahead_cache::invalidate_fd (int fd)
80152258 12029{
dd194f6b
PA
12030 if (this->fd == fd)
12031 this->fd = -1;
80152258
PA
12032}
12033
15a201c8
GB
12034/* Set the filesystem remote_hostio functions that take FILENAME
12035 arguments will use. Return 0 on success, or -1 if an error
12036 occurs (and set *REMOTE_ERRNO). */
12037
6b8edb51
PA
12038int
12039remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12040 int *remote_errno)
15a201c8
GB
12041{
12042 struct remote_state *rs = get_remote_state ();
12043 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12044 char *p = rs->buf;
12045 int left = get_remote_packet_size () - 1;
12046 char arg[9];
12047 int ret;
12048
12049 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12050 return 0;
12051
12052 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12053 return 0;
12054
12055 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12056
12057 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12058 remote_buffer_add_string (&p, &left, arg);
12059
12060 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
12061 remote_errno, NULL, NULL);
12062
12063 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12064 return 0;
12065
12066 if (ret == 0)
12067 rs->fs_pid = required_pid;
12068
12069 return ret;
12070}
12071
12e2a5fd 12072/* Implementation of to_fileio_open. */
a6b151f1 12073
6b8edb51
PA
12074int
12075remote_target::remote_hostio_open (inferior *inf, const char *filename,
12076 int flags, int mode, int warn_if_slow,
12077 int *remote_errno)
a6b151f1
DJ
12078{
12079 struct remote_state *rs = get_remote_state ();
12080 char *p = rs->buf;
12081 int left = get_remote_packet_size () - 1;
12082
4313b8c0
GB
12083 if (warn_if_slow)
12084 {
12085 static int warning_issued = 0;
12086
12087 printf_unfiltered (_("Reading %s from remote target...\n"),
12088 filename);
12089
12090 if (!warning_issued)
12091 {
12092 warning (_("File transfers from remote targets can be slow."
12093 " Use \"set sysroot\" to access files locally"
12094 " instead."));
12095 warning_issued = 1;
12096 }
12097 }
12098
15a201c8
GB
12099 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12100 return -1;
12101
a6b151f1
DJ
12102 remote_buffer_add_string (&p, &left, "vFile:open:");
12103
12104 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12105 strlen (filename));
12106 remote_buffer_add_string (&p, &left, ",");
12107
12108 remote_buffer_add_int (&p, &left, flags);
12109 remote_buffer_add_string (&p, &left, ",");
12110
12111 remote_buffer_add_int (&p, &left, mode);
12112
12113 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
12114 remote_errno, NULL, NULL);
12115}
12116
f6ac5f3d
PA
12117int
12118remote_target::fileio_open (struct inferior *inf, const char *filename,
12119 int flags, int mode, int warn_if_slow,
12120 int *remote_errno)
12121{
6b8edb51 12122 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
12123 remote_errno);
12124}
12125
12e2a5fd 12126/* Implementation of to_fileio_pwrite. */
a6b151f1 12127
6b8edb51
PA
12128int
12129remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12130 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12131{
12132 struct remote_state *rs = get_remote_state ();
12133 char *p = rs->buf;
12134 int left = get_remote_packet_size ();
12135 int out_len;
12136
dd194f6b 12137 rs->readahead_cache.invalidate_fd (fd);
80152258 12138
a6b151f1
DJ
12139 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12140
12141 remote_buffer_add_int (&p, &left, fd);
12142 remote_buffer_add_string (&p, &left, ",");
12143
12144 remote_buffer_add_int (&p, &left, offset);
12145 remote_buffer_add_string (&p, &left, ",");
12146
124e13d9 12147 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
12148 get_remote_packet_size () - (p - rs->buf));
12149
12150 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12151 remote_errno, NULL, NULL);
12152}
12153
f6ac5f3d
PA
12154int
12155remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12156 ULONGEST offset, int *remote_errno)
12157{
6b8edb51 12158 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12159}
12160
80152258
PA
12161/* Helper for the implementation of to_fileio_pread. Read the file
12162 from the remote side with vFile:pread. */
a6b151f1 12163
6b8edb51
PA
12164int
12165remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12166 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12167{
12168 struct remote_state *rs = get_remote_state ();
12169 char *p = rs->buf;
12170 char *attachment;
12171 int left = get_remote_packet_size ();
12172 int ret, attachment_len;
12173 int read_len;
12174
12175 remote_buffer_add_string (&p, &left, "vFile:pread:");
12176
12177 remote_buffer_add_int (&p, &left, fd);
12178 remote_buffer_add_string (&p, &left, ",");
12179
12180 remote_buffer_add_int (&p, &left, len);
12181 remote_buffer_add_string (&p, &left, ",");
12182
12183 remote_buffer_add_int (&p, &left, offset);
12184
12185 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12186 remote_errno, &attachment,
12187 &attachment_len);
12188
12189 if (ret < 0)
12190 return ret;
12191
bc20a4af 12192 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12193 read_buf, len);
12194 if (read_len != ret)
12195 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12196
12197 return ret;
12198}
12199
dd194f6b 12200/* See declaration.h. */
80152258 12201
dd194f6b
PA
12202int
12203readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12204 ULONGEST offset)
80152258 12205{
dd194f6b
PA
12206 if (this->fd == fd
12207 && this->offset <= offset
12208 && offset < this->offset + this->bufsize)
80152258 12209 {
dd194f6b 12210 ULONGEST max = this->offset + this->bufsize;
80152258
PA
12211
12212 if (offset + len > max)
12213 len = max - offset;
12214
dd194f6b 12215 memcpy (read_buf, this->buf + offset - this->offset, len);
80152258
PA
12216 return len;
12217 }
12218
12219 return 0;
12220}
12221
12222/* Implementation of to_fileio_pread. */
12223
6b8edb51
PA
12224int
12225remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12226 ULONGEST offset, int *remote_errno)
80152258
PA
12227{
12228 int ret;
12229 struct remote_state *rs = get_remote_state ();
dd194f6b 12230 readahead_cache *cache = &rs->readahead_cache;
80152258 12231
dd194f6b 12232 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12233 if (ret > 0)
12234 {
12235 cache->hit_count++;
12236
12237 if (remote_debug)
12238 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12239 pulongest (cache->hit_count));
12240 return ret;
12241 }
12242
12243 cache->miss_count++;
12244 if (remote_debug)
12245 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12246 pulongest (cache->miss_count));
12247
12248 cache->fd = fd;
12249 cache->offset = offset;
12250 cache->bufsize = get_remote_packet_size ();
224c3ddb 12251 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258 12252
6b8edb51 12253 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
80152258
PA
12254 cache->offset, remote_errno);
12255 if (ret <= 0)
12256 {
dd194f6b 12257 cache->invalidate_fd (fd);
80152258
PA
12258 return ret;
12259 }
12260
12261 cache->bufsize = ret;
dd194f6b 12262 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12263}
12264
f6ac5f3d
PA
12265int
12266remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12267 ULONGEST offset, int *remote_errno)
12268{
6b8edb51 12269 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12270}
12271
12e2a5fd 12272/* Implementation of to_fileio_close. */
a6b151f1 12273
6b8edb51
PA
12274int
12275remote_target::remote_hostio_close (int fd, int *remote_errno)
a6b151f1
DJ
12276{
12277 struct remote_state *rs = get_remote_state ();
12278 char *p = rs->buf;
12279 int left = get_remote_packet_size () - 1;
12280
dd194f6b 12281 rs->readahead_cache.invalidate_fd (fd);
80152258 12282
a6b151f1
DJ
12283 remote_buffer_add_string (&p, &left, "vFile:close:");
12284
12285 remote_buffer_add_int (&p, &left, fd);
12286
12287 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12288 remote_errno, NULL, NULL);
12289}
12290
f6ac5f3d
PA
12291int
12292remote_target::fileio_close (int fd, int *remote_errno)
12293{
6b8edb51 12294 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12295}
12296
12e2a5fd 12297/* Implementation of to_fileio_unlink. */
a6b151f1 12298
6b8edb51
PA
12299int
12300remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12301 int *remote_errno)
a6b151f1
DJ
12302{
12303 struct remote_state *rs = get_remote_state ();
12304 char *p = rs->buf;
12305 int left = get_remote_packet_size () - 1;
12306
15a201c8
GB
12307 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12308 return -1;
12309
a6b151f1
DJ
12310 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12311
12312 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12313 strlen (filename));
12314
12315 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12316 remote_errno, NULL, NULL);
12317}
12318
f6ac5f3d
PA
12319int
12320remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12321 int *remote_errno)
12322{
6b8edb51 12323 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12324}
12325
12e2a5fd 12326/* Implementation of to_fileio_readlink. */
b9e7b9c3 12327
f6ac5f3d
PA
12328gdb::optional<std::string>
12329remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12330 int *remote_errno)
b9e7b9c3
UW
12331{
12332 struct remote_state *rs = get_remote_state ();
12333 char *p = rs->buf;
12334 char *attachment;
12335 int left = get_remote_packet_size ();
12336 int len, attachment_len;
12337 int read_len;
b9e7b9c3 12338
15a201c8 12339 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12340 return {};
15a201c8 12341
b9e7b9c3
UW
12342 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12343
12344 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12345 strlen (filename));
12346
12347 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12348 remote_errno, &attachment,
12349 &attachment_len);
12350
12351 if (len < 0)
e0d3522b 12352 return {};
b9e7b9c3 12353
e0d3522b 12354 std::string ret (len, '\0');
b9e7b9c3 12355
bc20a4af 12356 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12357 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12358 if (read_len != len)
12359 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12360
b9e7b9c3
UW
12361 return ret;
12362}
12363
12e2a5fd 12364/* Implementation of to_fileio_fstat. */
0a93529c 12365
f6ac5f3d
PA
12366int
12367remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
0a93529c
GB
12368{
12369 struct remote_state *rs = get_remote_state ();
12370 char *p = rs->buf;
12371 int left = get_remote_packet_size ();
12372 int attachment_len, ret;
12373 char *attachment;
12374 struct fio_stat fst;
12375 int read_len;
12376
464b0089
GB
12377 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12378
12379 remote_buffer_add_int (&p, &left, fd);
12380
12381 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12382 remote_errno, &attachment,
12383 &attachment_len);
12384 if (ret < 0)
0a93529c 12385 {
464b0089
GB
12386 if (*remote_errno != FILEIO_ENOSYS)
12387 return ret;
12388
0a93529c
GB
12389 /* Strictly we should return -1, ENOSYS here, but when
12390 "set sysroot remote:" was implemented in August 2008
12391 BFD's need for a stat function was sidestepped with
12392 this hack. This was not remedied until March 2015
12393 so we retain the previous behavior to avoid breaking
12394 compatibility.
12395
12396 Note that the memset is a March 2015 addition; older
12397 GDBs set st_size *and nothing else* so the structure
12398 would have garbage in all other fields. This might
12399 break something but retaining the previous behavior
12400 here would be just too wrong. */
12401
12402 memset (st, 0, sizeof (struct stat));
12403 st->st_size = INT_MAX;
12404 return 0;
12405 }
12406
0a93529c
GB
12407 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12408 (gdb_byte *) &fst, sizeof (fst));
12409
12410 if (read_len != ret)
12411 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12412
12413 if (read_len != sizeof (fst))
12414 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12415 read_len, (int) sizeof (fst));
12416
12417 remote_fileio_to_host_stat (&fst, st);
12418
12419 return 0;
12420}
12421
12e2a5fd 12422/* Implementation of to_filesystem_is_local. */
e3dd7556 12423
57810aa7 12424bool
f6ac5f3d 12425remote_target::filesystem_is_local ()
e3dd7556
GB
12426{
12427 /* Valgrind GDB presents itself as a remote target but works
12428 on the local filesystem: it does not implement remote get
12429 and users are not expected to set a sysroot. To handle
12430 this case we treat the remote filesystem as local if the
12431 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12432 does not support vFile:open. */
a3be80c3 12433 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
12434 {
12435 enum packet_support ps = packet_support (PACKET_vFile_open);
12436
12437 if (ps == PACKET_SUPPORT_UNKNOWN)
12438 {
12439 int fd, remote_errno;
12440
12441 /* Try opening a file to probe support. The supplied
12442 filename is irrelevant, we only care about whether
12443 the stub recognizes the packet or not. */
6b8edb51 12444 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12445 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12446 &remote_errno);
12447
12448 if (fd >= 0)
6b8edb51 12449 remote_hostio_close (fd, &remote_errno);
e3dd7556
GB
12450
12451 ps = packet_support (PACKET_vFile_open);
12452 }
12453
12454 if (ps == PACKET_DISABLE)
12455 {
12456 static int warning_issued = 0;
12457
12458 if (!warning_issued)
12459 {
12460 warning (_("remote target does not support file"
12461 " transfer, attempting to access files"
12462 " from local filesystem."));
12463 warning_issued = 1;
12464 }
12465
57810aa7 12466 return true;
e3dd7556
GB
12467 }
12468 }
12469
57810aa7 12470 return false;
e3dd7556
GB
12471}
12472
a6b151f1
DJ
12473static int
12474remote_fileio_errno_to_host (int errnum)
12475{
12476 switch (errnum)
12477 {
12478 case FILEIO_EPERM:
12479 return EPERM;
12480 case FILEIO_ENOENT:
12481 return ENOENT;
12482 case FILEIO_EINTR:
12483 return EINTR;
12484 case FILEIO_EIO:
12485 return EIO;
12486 case FILEIO_EBADF:
12487 return EBADF;
12488 case FILEIO_EACCES:
12489 return EACCES;
12490 case FILEIO_EFAULT:
12491 return EFAULT;
12492 case FILEIO_EBUSY:
12493 return EBUSY;
12494 case FILEIO_EEXIST:
12495 return EEXIST;
12496 case FILEIO_ENODEV:
12497 return ENODEV;
12498 case FILEIO_ENOTDIR:
12499 return ENOTDIR;
12500 case FILEIO_EISDIR:
12501 return EISDIR;
12502 case FILEIO_EINVAL:
12503 return EINVAL;
12504 case FILEIO_ENFILE:
12505 return ENFILE;
12506 case FILEIO_EMFILE:
12507 return EMFILE;
12508 case FILEIO_EFBIG:
12509 return EFBIG;
12510 case FILEIO_ENOSPC:
12511 return ENOSPC;
12512 case FILEIO_ESPIPE:
12513 return ESPIPE;
12514 case FILEIO_EROFS:
12515 return EROFS;
12516 case FILEIO_ENOSYS:
12517 return ENOSYS;
12518 case FILEIO_ENAMETOOLONG:
12519 return ENAMETOOLONG;
12520 }
12521 return -1;
12522}
12523
12524static char *
12525remote_hostio_error (int errnum)
12526{
12527 int host_error = remote_fileio_errno_to_host (errnum);
12528
12529 if (host_error == -1)
12530 error (_("Unknown remote I/O error %d"), errnum);
12531 else
12532 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12533}
12534
440b7aec
PA
12535/* A RAII wrapper around a remote file descriptor. */
12536
12537class scoped_remote_fd
a6b151f1 12538{
440b7aec 12539public:
6b8edb51
PA
12540 scoped_remote_fd (remote_target *remote, int fd)
12541 : m_remote (remote), m_fd (fd)
440b7aec
PA
12542 {
12543 }
a6b151f1 12544
440b7aec
PA
12545 ~scoped_remote_fd ()
12546 {
12547 if (m_fd != -1)
12548 {
12549 try
12550 {
12551 int remote_errno;
6b8edb51 12552 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12553 }
12554 catch (...)
12555 {
12556 /* Swallow exception before it escapes the dtor. If
12557 something goes wrong, likely the connection is gone,
12558 and there's nothing else that can be done. */
12559 }
12560 }
12561 }
12562
12563 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12564
12565 /* Release ownership of the file descriptor, and return it. */
12566 int release () noexcept
12567 {
12568 int fd = m_fd;
12569 m_fd = -1;
12570 return fd;
12571 }
12572
12573 /* Return the owned file descriptor. */
12574 int get () const noexcept
12575 {
12576 return m_fd;
12577 }
12578
12579private:
6b8edb51
PA
12580 /* The remote target. */
12581 remote_target *m_remote;
12582
440b7aec
PA
12583 /* The owned remote I/O file descriptor. */
12584 int m_fd;
12585};
a6b151f1
DJ
12586
12587void
12588remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12589{
12590 remote_target *remote = get_current_remote_target ();
12591
12592 if (remote == nullptr)
12593 error (_("command can only be used with remote target"));
12594
12595 remote->remote_file_put (local_file, remote_file, from_tty);
12596}
12597
12598void
12599remote_target::remote_file_put (const char *local_file, const char *remote_file,
12600 int from_tty)
a6b151f1 12601{
440b7aec 12602 int retcode, remote_errno, bytes, io_size;
a6b151f1
DJ
12603 int bytes_in_buffer;
12604 int saw_eof;
12605 ULONGEST offset;
a6b151f1 12606
d419f42d 12607 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12608 if (file == NULL)
12609 perror_with_name (local_file);
a6b151f1 12610
440b7aec 12611 scoped_remote_fd fd
6b8edb51
PA
12612 (this, remote_hostio_open (NULL,
12613 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12614 | FILEIO_O_TRUNC),
12615 0700, 0, &remote_errno));
440b7aec 12616 if (fd.get () == -1)
a6b151f1
DJ
12617 remote_hostio_error (remote_errno);
12618
12619 /* Send up to this many bytes at once. They won't all fit in the
12620 remote packet limit, so we'll transfer slightly fewer. */
12621 io_size = get_remote_packet_size ();
5ca3b260 12622 gdb::byte_vector buffer (io_size);
a6b151f1 12623
a6b151f1
DJ
12624 bytes_in_buffer = 0;
12625 saw_eof = 0;
12626 offset = 0;
12627 while (bytes_in_buffer || !saw_eof)
12628 {
12629 if (!saw_eof)
12630 {
5ca3b260 12631 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 12632 io_size - bytes_in_buffer,
d419f42d 12633 file.get ());
a6b151f1
DJ
12634 if (bytes == 0)
12635 {
d419f42d 12636 if (ferror (file.get ()))
a6b151f1
DJ
12637 error (_("Error reading %s."), local_file);
12638 else
12639 {
12640 /* EOF. Unless there is something still in the
12641 buffer from the last iteration, we are done. */
12642 saw_eof = 1;
12643 if (bytes_in_buffer == 0)
12644 break;
12645 }
12646 }
12647 }
12648 else
12649 bytes = 0;
12650
12651 bytes += bytes_in_buffer;
12652 bytes_in_buffer = 0;
12653
5ca3b260 12654 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 12655 offset, &remote_errno);
a6b151f1
DJ
12656
12657 if (retcode < 0)
12658 remote_hostio_error (remote_errno);
12659 else if (retcode == 0)
12660 error (_("Remote write of %d bytes returned 0!"), bytes);
12661 else if (retcode < bytes)
12662 {
12663 /* Short write. Save the rest of the read data for the next
12664 write. */
12665 bytes_in_buffer = bytes - retcode;
5ca3b260 12666 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
12667 }
12668
12669 offset += retcode;
12670 }
12671
6b8edb51 12672 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12673 remote_hostio_error (remote_errno);
12674
12675 if (from_tty)
12676 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
a6b151f1
DJ
12677}
12678
12679void
12680remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
12681{
12682 remote_target *remote = get_current_remote_target ();
12683
12684 if (remote == nullptr)
12685 error (_("command can only be used with remote target"));
12686
12687 remote->remote_file_get (remote_file, local_file, from_tty);
12688}
12689
12690void
12691remote_target::remote_file_get (const char *remote_file, const char *local_file,
12692 int from_tty)
a6b151f1 12693{
440b7aec 12694 int remote_errno, bytes, io_size;
a6b151f1 12695 ULONGEST offset;
a6b151f1 12696
440b7aec 12697 scoped_remote_fd fd
6b8edb51
PA
12698 (this, remote_hostio_open (NULL,
12699 remote_file, FILEIO_O_RDONLY, 0, 0,
12700 &remote_errno));
440b7aec 12701 if (fd.get () == -1)
a6b151f1
DJ
12702 remote_hostio_error (remote_errno);
12703
d419f42d 12704 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12705 if (file == NULL)
12706 perror_with_name (local_file);
a6b151f1
DJ
12707
12708 /* Send up to this many bytes at once. They won't all fit in the
12709 remote packet limit, so we'll transfer slightly fewer. */
12710 io_size = get_remote_packet_size ();
5ca3b260 12711 gdb::byte_vector buffer (io_size);
a6b151f1 12712
a6b151f1
DJ
12713 offset = 0;
12714 while (1)
12715 {
5ca3b260 12716 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 12717 &remote_errno);
a6b151f1
DJ
12718 if (bytes == 0)
12719 /* Success, but no bytes, means end-of-file. */
12720 break;
12721 if (bytes == -1)
12722 remote_hostio_error (remote_errno);
12723
12724 offset += bytes;
12725
5ca3b260 12726 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
12727 if (bytes == 0)
12728 perror_with_name (local_file);
12729 }
12730
6b8edb51 12731 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12732 remote_hostio_error (remote_errno);
12733
12734 if (from_tty)
12735 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
a6b151f1
DJ
12736}
12737
12738void
12739remote_file_delete (const char *remote_file, int from_tty)
12740{
6b8edb51 12741 remote_target *remote = get_current_remote_target ();
a6b151f1 12742
6b8edb51 12743 if (remote == nullptr)
a6b151f1
DJ
12744 error (_("command can only be used with remote target"));
12745
6b8edb51
PA
12746 remote->remote_file_delete (remote_file, from_tty);
12747}
12748
12749void
12750remote_target::remote_file_delete (const char *remote_file, int from_tty)
12751{
12752 int retcode, remote_errno;
12753
12754 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
12755 if (retcode == -1)
12756 remote_hostio_error (remote_errno);
12757
12758 if (from_tty)
12759 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12760}
12761
12762static void
ac88e2de 12763remote_put_command (const char *args, int from_tty)
a6b151f1 12764{
d1a41061
PP
12765 if (args == NULL)
12766 error_no_arg (_("file to put"));
12767
773a1edc 12768 gdb_argv argv (args);
a6b151f1
DJ
12769 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12770 error (_("Invalid parameters to remote put"));
12771
12772 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12773}
12774
12775static void
ac88e2de 12776remote_get_command (const char *args, int from_tty)
a6b151f1 12777{
d1a41061
PP
12778 if (args == NULL)
12779 error_no_arg (_("file to get"));
12780
773a1edc 12781 gdb_argv argv (args);
a6b151f1
DJ
12782 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12783 error (_("Invalid parameters to remote get"));
12784
12785 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12786}
12787
12788static void
ac88e2de 12789remote_delete_command (const char *args, int from_tty)
a6b151f1 12790{
d1a41061
PP
12791 if (args == NULL)
12792 error_no_arg (_("file to delete"));
12793
773a1edc 12794 gdb_argv argv (args);
a6b151f1
DJ
12795 if (argv[0] == NULL || argv[1] != NULL)
12796 error (_("Invalid parameters to remote delete"));
12797
12798 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12799}
12800
12801static void
981a3fb3 12802remote_command (const char *args, int from_tty)
a6b151f1 12803{
635c7e8a 12804 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12805}
12806
57810aa7 12807bool
f6ac5f3d 12808remote_target::can_execute_reverse ()
b2175913 12809{
4082afcc
PA
12810 if (packet_support (PACKET_bs) == PACKET_ENABLE
12811 || packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 12812 return true;
40ab02ce 12813 else
57810aa7 12814 return false;
b2175913
MS
12815}
12816
57810aa7 12817bool
f6ac5f3d 12818remote_target::supports_non_stop ()
74531fed 12819{
57810aa7 12820 return true;
74531fed
PA
12821}
12822
57810aa7 12823bool
f6ac5f3d 12824remote_target::supports_disable_randomization ()
03583c20
UW
12825{
12826 /* Only supported in extended mode. */
57810aa7 12827 return false;
03583c20
UW
12828}
12829
57810aa7 12830bool
f6ac5f3d 12831remote_target::supports_multi_process ()
8a305172
PA
12832{
12833 struct remote_state *rs = get_remote_state ();
a744cf53 12834
8020350c 12835 return remote_multi_process_p (rs);
8a305172
PA
12836}
12837
70221824 12838static int
f6ac5f3d 12839remote_supports_cond_tracepoints ()
782b2b07 12840{
4082afcc 12841 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12842}
12843
57810aa7 12844bool
f6ac5f3d 12845remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 12846{
4082afcc 12847 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12848}
12849
70221824 12850static int
f6ac5f3d 12851remote_supports_fast_tracepoints ()
7a697b8d 12852{
4082afcc 12853 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12854}
12855
0fb4aa4b 12856static int
f6ac5f3d 12857remote_supports_static_tracepoints ()
0fb4aa4b 12858{
4082afcc 12859 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12860}
12861
1e4d1764 12862static int
f6ac5f3d 12863remote_supports_install_in_trace ()
1e4d1764 12864{
4082afcc 12865 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12866}
12867
57810aa7 12868bool
f6ac5f3d 12869remote_target::supports_enable_disable_tracepoint ()
d248b706 12870{
4082afcc
PA
12871 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12872 == PACKET_ENABLE);
d248b706
KY
12873}
12874
57810aa7 12875bool
f6ac5f3d 12876remote_target::supports_string_tracing ()
3065dfb6 12877{
4082afcc 12878 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12879}
12880
57810aa7 12881bool
f6ac5f3d 12882remote_target::can_run_breakpoint_commands ()
d3ce09f5 12883{
4082afcc 12884 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12885}
12886
f6ac5f3d
PA
12887void
12888remote_target::trace_init ()
35b1e5cc 12889{
b6bb3468
PA
12890 struct remote_state *rs = get_remote_state ();
12891
35b1e5cc 12892 putpkt ("QTinit");
b6bb3468
PA
12893 remote_get_noisy_reply ();
12894 if (strcmp (rs->buf, "OK") != 0)
35b1e5cc
SS
12895 error (_("Target does not support this command."));
12896}
12897
409873ef
SS
12898/* Recursive routine to walk through command list including loops, and
12899 download packets for each command. */
12900
6b8edb51
PA
12901void
12902remote_target::remote_download_command_source (int num, ULONGEST addr,
12903 struct command_line *cmds)
409873ef
SS
12904{
12905 struct remote_state *rs = get_remote_state ();
12906 struct command_line *cmd;
12907
12908 for (cmd = cmds; cmd; cmd = cmd->next)
12909 {
0df8b418 12910 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12911 strcpy (rs->buf, "QTDPsrc:");
12912 encode_source_string (num, addr, "cmd", cmd->line,
12913 rs->buf + strlen (rs->buf),
12914 rs->buf_size - strlen (rs->buf));
12915 putpkt (rs->buf);
b6bb3468
PA
12916 remote_get_noisy_reply ();
12917 if (strcmp (rs->buf, "OK"))
409873ef
SS
12918 warning (_("Target does not support source download."));
12919
12920 if (cmd->control_type == while_control
12921 || cmd->control_type == while_stepping_control)
12922 {
12973681 12923 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 12924
0df8b418 12925 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12926 strcpy (rs->buf, "QTDPsrc:");
12927 encode_source_string (num, addr, "cmd", "end",
12928 rs->buf + strlen (rs->buf),
12929 rs->buf_size - strlen (rs->buf));
12930 putpkt (rs->buf);
b6bb3468
PA
12931 remote_get_noisy_reply ();
12932 if (strcmp (rs->buf, "OK"))
409873ef
SS
12933 warning (_("Target does not support source download."));
12934 }
12935 }
12936}
12937
f6ac5f3d
PA
12938void
12939remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc 12940{
bba74b36 12941#define BUF_SIZE 2048
e8ba3115 12942
35b1e5cc 12943 CORE_ADDR tpaddr;
409873ef 12944 char addrbuf[40];
bba74b36 12945 char buf[BUF_SIZE];
b44ec619
SM
12946 std::vector<std::string> tdp_actions;
12947 std::vector<std::string> stepping_actions;
35b1e5cc 12948 char *pkt;
e8ba3115 12949 struct breakpoint *b = loc->owner;
d9b3f62e 12950 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 12951 struct remote_state *rs = get_remote_state ();
35b1e5cc 12952
dc673c81 12953 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12954
12955 tpaddr = loc->address;
12956 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
12957 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12958 addrbuf, /* address */
12959 (b->enable_state == bp_enabled ? 'E' : 'D'),
12960 t->step_count, t->pass_count);
e8ba3115
YQ
12961 /* Fast tracepoints are mostly handled by the target, but we can
12962 tell the target how big of an instruction block should be moved
12963 around. */
12964 if (b->type == bp_fast_tracepoint)
12965 {
12966 /* Only test for support at download time; we may not know
12967 target capabilities at definition time. */
12968 if (remote_supports_fast_tracepoints ())
35b1e5cc 12969 {
6b940e6a
PL
12970 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12971 NULL))
bba74b36 12972 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 12973 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 12974 else
e8ba3115
YQ
12975 /* If it passed validation at definition but fails now,
12976 something is very wrong. */
12977 internal_error (__FILE__, __LINE__,
12978 _("Fast tracepoint not "
12979 "valid during download"));
35b1e5cc 12980 }
e8ba3115
YQ
12981 else
12982 /* Fast tracepoints are functionally identical to regular
12983 tracepoints, so don't take lack of support as a reason to
12984 give up on the trace run. */
12985 warning (_("Target does not support fast tracepoints, "
12986 "downloading %d as regular tracepoint"), b->number);
12987 }
12988 else if (b->type == bp_static_tracepoint)
12989 {
12990 /* Only test for support at download time; we may not know
12991 target capabilities at definition time. */
12992 if (remote_supports_static_tracepoints ())
0fb4aa4b 12993 {
e8ba3115 12994 struct static_tracepoint_marker marker;
0fb4aa4b 12995
e8ba3115
YQ
12996 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12997 strcat (buf, ":S");
0fb4aa4b 12998 else
e8ba3115 12999 error (_("Static tracepoint not valid during download"));
0fb4aa4b 13000 }
e8ba3115
YQ
13001 else
13002 /* Fast tracepoints are functionally identical to regular
13003 tracepoints, so don't take lack of support as a reason
13004 to give up on the trace run. */
13005 error (_("Target does not support static tracepoints"));
13006 }
13007 /* If the tracepoint has a conditional, make it into an agent
13008 expression and append to the definition. */
13009 if (loc->cond)
13010 {
13011 /* Only test support at download time, we may not know target
13012 capabilities at definition time. */
13013 if (remote_supports_cond_tracepoints ())
35b1e5cc 13014 {
833177a4 13015 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
bba74b36
YQ
13016 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
13017 aexpr->len);
e8ba3115 13018 pkt = buf + strlen (buf);
b44ec619 13019 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
13020 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13021 *pkt = '\0';
35b1e5cc 13022 }
e8ba3115
YQ
13023 else
13024 warning (_("Target does not support conditional tracepoints, "
13025 "ignoring tp %d cond"), b->number);
13026 }
35b1e5cc 13027
d9b3f62e 13028 if (b->commands || *default_collect)
e8ba3115
YQ
13029 strcat (buf, "-");
13030 putpkt (buf);
b6bb3468
PA
13031 remote_get_noisy_reply ();
13032 if (strcmp (rs->buf, "OK"))
e8ba3115 13033 error (_("Target does not support tracepoints."));
35b1e5cc 13034
e8ba3115 13035 /* do_single_steps (t); */
b44ec619
SM
13036 for (auto action_it = tdp_actions.begin ();
13037 action_it != tdp_actions.end (); action_it++)
e8ba3115 13038 {
b44ec619
SM
13039 QUIT; /* Allow user to bail out with ^C. */
13040
13041 bool has_more = (action_it != tdp_actions.end ()
13042 || !stepping_actions.empty ());
13043
13044 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
13045 b->number, addrbuf, /* address */
13046 action_it->c_str (),
13047 has_more ? '-' : 0);
13048 putpkt (buf);
13049 remote_get_noisy_reply ();
13050 if (strcmp (rs->buf, "OK"))
13051 error (_("Error on target while setting tracepoints."));
e8ba3115 13052 }
409873ef 13053
b44ec619
SM
13054 for (auto action_it = stepping_actions.begin ();
13055 action_it != stepping_actions.end (); action_it++)
13056 {
13057 QUIT; /* Allow user to bail out with ^C. */
13058
13059 bool is_first = action_it == stepping_actions.begin ();
13060 bool has_more = action_it != stepping_actions.end ();
13061
13062 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
13063 b->number, addrbuf, /* address */
13064 is_first ? "S" : "",
13065 action_it->c_str (),
13066 has_more ? "-" : "");
13067 putpkt (buf);
13068 remote_get_noisy_reply ();
13069 if (strcmp (rs->buf, "OK"))
13070 error (_("Error on target while setting tracepoints."));
13071 }
13072
4082afcc 13073 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 13074 {
f00aae0f 13075 if (b->location != NULL)
409873ef 13076 {
e8ba3115 13077 strcpy (buf, "QTDPsrc:");
f00aae0f 13078 encode_source_string (b->number, loc->address, "at",
d28cd78a 13079 event_location_to_string (b->location.get ()),
f00aae0f 13080 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115 13081 putpkt (buf);
b6bb3468
PA
13082 remote_get_noisy_reply ();
13083 if (strcmp (rs->buf, "OK"))
e8ba3115 13084 warning (_("Target does not support source download."));
409873ef 13085 }
e8ba3115
YQ
13086 if (b->cond_string)
13087 {
13088 strcpy (buf, "QTDPsrc:");
13089 encode_source_string (b->number, loc->address,
13090 "cond", b->cond_string, buf + strlen (buf),
13091 2048 - strlen (buf));
13092 putpkt (buf);
b6bb3468
PA
13093 remote_get_noisy_reply ();
13094 if (strcmp (rs->buf, "OK"))
e8ba3115
YQ
13095 warning (_("Target does not support source download."));
13096 }
13097 remote_download_command_source (b->number, loc->address,
13098 breakpoint_commands (b));
35b1e5cc 13099 }
35b1e5cc
SS
13100}
13101
57810aa7 13102bool
f6ac5f3d 13103remote_target::can_download_tracepoint ()
1e4d1764 13104{
1e51243a
PA
13105 struct remote_state *rs = get_remote_state ();
13106 struct trace_status *ts;
13107 int status;
13108
13109 /* Don't try to install tracepoints until we've relocated our
13110 symbols, and fetched and merged the target's tracepoint list with
13111 ours. */
13112 if (rs->starting_up)
57810aa7 13113 return false;
1e51243a
PA
13114
13115 ts = current_trace_status ();
f6ac5f3d 13116 status = get_trace_status (ts);
1e4d1764
YQ
13117
13118 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13119 return false;
1e4d1764
YQ
13120
13121 /* If we are in a tracing experiment, but remote stub doesn't support
13122 installing tracepoint in trace, we have to return. */
13123 if (!remote_supports_install_in_trace ())
57810aa7 13124 return false;
1e4d1764 13125
57810aa7 13126 return true;
1e4d1764
YQ
13127}
13128
13129
f6ac5f3d
PA
13130void
13131remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
13132{
13133 struct remote_state *rs = get_remote_state ();
00bf0b85 13134 char *p;
35b1e5cc 13135
bba74b36 13136 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
13137 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13138 tsv.builtin);
00bf0b85 13139 p = rs->buf + strlen (rs->buf);
c252925c 13140 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
00bf0b85 13141 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 13142 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 13143 *p++ = '\0';
35b1e5cc 13144 putpkt (rs->buf);
b6bb3468
PA
13145 remote_get_noisy_reply ();
13146 if (*rs->buf == '\0')
ad91cd99 13147 error (_("Target does not support this command."));
b6bb3468 13148 if (strcmp (rs->buf, "OK") != 0)
ad91cd99 13149 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13150}
13151
f6ac5f3d
PA
13152void
13153remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13154{
13155 struct remote_state *rs = get_remote_state ();
13156 char addr_buf[40];
13157
13158 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
13159 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13160 location->owner->number, addr_buf);
d248b706 13161 putpkt (rs->buf);
b6bb3468 13162 remote_get_noisy_reply ();
d248b706
KY
13163 if (*rs->buf == '\0')
13164 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13165 if (strcmp (rs->buf, "OK") != 0)
13166 error (_("Error on target while enabling tracepoint."));
13167}
13168
f6ac5f3d
PA
13169void
13170remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13171{
13172 struct remote_state *rs = get_remote_state ();
13173 char addr_buf[40];
13174
13175 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
13176 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13177 location->owner->number, addr_buf);
d248b706 13178 putpkt (rs->buf);
b6bb3468 13179 remote_get_noisy_reply ();
d248b706
KY
13180 if (*rs->buf == '\0')
13181 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13182 if (strcmp (rs->buf, "OK") != 0)
13183 error (_("Error on target while disabling tracepoint."));
13184}
13185
f6ac5f3d
PA
13186void
13187remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13188{
13189 asection *s;
81b9b86e 13190 bfd *abfd = NULL;
35b1e5cc 13191 bfd_size_type size;
608bcef2 13192 bfd_vma vma;
35b1e5cc 13193 int anysecs = 0;
c2fa21f1 13194 int offset = 0;
35b1e5cc
SS
13195
13196 if (!exec_bfd)
13197 return; /* No information to give. */
13198
b6bb3468
PA
13199 struct remote_state *rs = get_remote_state ();
13200
13201 strcpy (rs->buf, "QTro");
13202 offset = strlen (rs->buf);
35b1e5cc
SS
13203 for (s = exec_bfd->sections; s; s = s->next)
13204 {
13205 char tmp1[40], tmp2[40];
c2fa21f1 13206 int sec_length;
35b1e5cc
SS
13207
13208 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 13209 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
13210 (s->flags & SEC_READONLY) == 0)
13211 continue;
13212
13213 anysecs = 1;
81b9b86e 13214 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 13215 size = bfd_get_section_size (s);
608bcef2
HZ
13216 sprintf_vma (tmp1, vma);
13217 sprintf_vma (tmp2, vma + size);
c2fa21f1 13218 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
b6bb3468 13219 if (offset + sec_length + 1 > rs->buf_size)
c2fa21f1 13220 {
4082afcc 13221 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 13222 warning (_("\
c2fa21f1
HZ
13223Too many sections for read-only sections definition packet."));
13224 break;
13225 }
b6bb3468 13226 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
bba74b36 13227 tmp1, tmp2);
c2fa21f1 13228 offset += sec_length;
35b1e5cc
SS
13229 }
13230 if (anysecs)
13231 {
b6bb3468
PA
13232 putpkt (rs->buf);
13233 getpkt (&rs->buf, &rs->buf_size, 0);
35b1e5cc
SS
13234 }
13235}
13236
f6ac5f3d
PA
13237void
13238remote_target::trace_start ()
35b1e5cc 13239{
b6bb3468
PA
13240 struct remote_state *rs = get_remote_state ();
13241
35b1e5cc 13242 putpkt ("QTStart");
b6bb3468
PA
13243 remote_get_noisy_reply ();
13244 if (*rs->buf == '\0')
ad91cd99 13245 error (_("Target does not support this command."));
b6bb3468
PA
13246 if (strcmp (rs->buf, "OK") != 0)
13247 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
13248}
13249
f6ac5f3d
PA
13250int
13251remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13252{
953b98d1 13253 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13254 char *p = NULL;
0df8b418 13255 /* FIXME we need to get register block size some other way. */
00bf0b85 13256 extern int trace_regblock_size;
bd3eecc3 13257 enum packet_result result;
b6bb3468 13258 struct remote_state *rs = get_remote_state ();
bd3eecc3 13259
4082afcc 13260 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13261 return -1;
a744cf53 13262
5cd63fda 13263 trace_regblock_size
9d6eea31 13264 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 13265
049dc89b
JK
13266 putpkt ("qTStatus");
13267
492d29ea 13268 TRY
67f41397 13269 {
b6bb3468 13270 p = remote_get_noisy_reply ();
67f41397 13271 }
492d29ea 13272 CATCH (ex, RETURN_MASK_ERROR)
67f41397 13273 {
598d3636
JK
13274 if (ex.error != TARGET_CLOSE_ERROR)
13275 {
13276 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13277 return -1;
13278 }
13279 throw_exception (ex);
67f41397 13280 }
492d29ea 13281 END_CATCH
00bf0b85 13282
bd3eecc3
PA
13283 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13284
00bf0b85 13285 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13286 if (result == PACKET_UNKNOWN)
00bf0b85 13287 return -1;
35b1e5cc 13288
00bf0b85 13289 /* We're working with a live target. */
f5911ea1 13290 ts->filename = NULL;
00bf0b85 13291
00bf0b85 13292 if (*p++ != 'T')
b6bb3468 13293 error (_("Bogus trace status reply from target: %s"), rs->buf);
35b1e5cc 13294
84cebc4a
YQ
13295 /* Function 'parse_trace_status' sets default value of each field of
13296 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13297 parse_trace_status (p, ts);
13298
13299 return ts->running;
35b1e5cc
SS
13300}
13301
f6ac5f3d
PA
13302void
13303remote_target::get_tracepoint_status (struct breakpoint *bp,
13304 struct uploaded_tp *utp)
f196051f
SS
13305{
13306 struct remote_state *rs = get_remote_state ();
f196051f
SS
13307 char *reply;
13308 struct bp_location *loc;
13309 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 13310 size_t size = get_remote_packet_size ();
f196051f
SS
13311
13312 if (tp)
13313 {
c1fc2657 13314 tp->hit_count = 0;
f196051f 13315 tp->traceframe_usage = 0;
c1fc2657 13316 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
13317 {
13318 /* If the tracepoint was never downloaded, don't go asking for
13319 any status. */
13320 if (tp->number_on_target == 0)
13321 continue;
bba74b36
YQ
13322 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13323 phex_nz (loc->address, 0));
f196051f 13324 putpkt (rs->buf);
b6bb3468 13325 reply = remote_get_noisy_reply ();
f196051f
SS
13326 if (reply && *reply)
13327 {
13328 if (*reply == 'V')
13329 parse_tracepoint_status (reply + 1, bp, utp);
13330 }
13331 }
13332 }
13333 else if (utp)
13334 {
13335 utp->hit_count = 0;
13336 utp->traceframe_usage = 0;
bba74b36
YQ
13337 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13338 phex_nz (utp->addr, 0));
f196051f 13339 putpkt (rs->buf);
b6bb3468 13340 reply = remote_get_noisy_reply ();
f196051f
SS
13341 if (reply && *reply)
13342 {
13343 if (*reply == 'V')
13344 parse_tracepoint_status (reply + 1, bp, utp);
13345 }
13346 }
13347}
13348
f6ac5f3d
PA
13349void
13350remote_target::trace_stop ()
35b1e5cc 13351{
b6bb3468
PA
13352 struct remote_state *rs = get_remote_state ();
13353
35b1e5cc 13354 putpkt ("QTStop");
b6bb3468
PA
13355 remote_get_noisy_reply ();
13356 if (*rs->buf == '\0')
ad91cd99 13357 error (_("Target does not support this command."));
b6bb3468
PA
13358 if (strcmp (rs->buf, "OK") != 0)
13359 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
13360}
13361
f6ac5f3d
PA
13362int
13363remote_target::trace_find (enum trace_find_type type, int num,
13364 CORE_ADDR addr1, CORE_ADDR addr2,
13365 int *tpp)
35b1e5cc
SS
13366{
13367 struct remote_state *rs = get_remote_state ();
bba74b36 13368 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
13369 char *p, *reply;
13370 int target_frameno = -1, target_tracept = -1;
13371
e6e4e701
PA
13372 /* Lookups other than by absolute frame number depend on the current
13373 trace selected, so make sure it is correct on the remote end
13374 first. */
13375 if (type != tfind_number)
13376 set_remote_traceframe ();
13377
35b1e5cc
SS
13378 p = rs->buf;
13379 strcpy (p, "QTFrame:");
13380 p = strchr (p, '\0');
13381 switch (type)
13382 {
13383 case tfind_number:
bba74b36 13384 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13385 break;
13386 case tfind_pc:
bba74b36 13387 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13388 break;
13389 case tfind_tp:
bba74b36 13390 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13391 break;
13392 case tfind_range:
bba74b36
YQ
13393 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13394 phex_nz (addr2, 0));
35b1e5cc
SS
13395 break;
13396 case tfind_outside:
bba74b36
YQ
13397 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13398 phex_nz (addr2, 0));
35b1e5cc
SS
13399 break;
13400 default:
9b20d036 13401 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13402 }
13403
13404 putpkt (rs->buf);
b6bb3468 13405 reply = remote_get_noisy_reply ();
ad91cd99
PA
13406 if (*reply == '\0')
13407 error (_("Target does not support this command."));
35b1e5cc
SS
13408
13409 while (reply && *reply)
13410 switch (*reply)
13411 {
13412 case 'F':
f197e0f1
VP
13413 p = ++reply;
13414 target_frameno = (int) strtol (p, &reply, 16);
13415 if (reply == p)
13416 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13417 /* Don't update our remote traceframe number cache on failure
13418 to select a remote traceframe. */
f197e0f1
VP
13419 if (target_frameno == -1)
13420 return -1;
35b1e5cc
SS
13421 break;
13422 case 'T':
f197e0f1
VP
13423 p = ++reply;
13424 target_tracept = (int) strtol (p, &reply, 16);
13425 if (reply == p)
13426 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13427 break;
13428 case 'O': /* "OK"? */
13429 if (reply[1] == 'K' && reply[2] == '\0')
13430 reply += 2;
13431 else
13432 error (_("Bogus reply from target: %s"), reply);
13433 break;
13434 default:
13435 error (_("Bogus reply from target: %s"), reply);
13436 }
13437 if (tpp)
13438 *tpp = target_tracept;
e6e4e701 13439
262e1174 13440 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13441 return target_frameno;
13442}
13443
57810aa7 13444bool
f6ac5f3d 13445remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13446{
13447 struct remote_state *rs = get_remote_state ();
13448 char *reply;
13449 ULONGEST uval;
13450
e6e4e701
PA
13451 set_remote_traceframe ();
13452
bba74b36 13453 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13454 putpkt (rs->buf);
b6bb3468 13455 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13456 if (reply && *reply)
13457 {
13458 if (*reply == 'V')
13459 {
13460 unpack_varlen_hex (reply + 1, &uval);
13461 *val = (LONGEST) uval;
57810aa7 13462 return true;
35b1e5cc
SS
13463 }
13464 }
57810aa7 13465 return false;
35b1e5cc
SS
13466}
13467
f6ac5f3d
PA
13468int
13469remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13470{
13471 struct remote_state *rs = get_remote_state ();
13472 char *p, *reply;
13473
13474 p = rs->buf;
13475 strcpy (p, "QTSave:");
13476 p += strlen (p);
13477 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13478 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13479 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13480 *p++ = '\0';
13481 putpkt (rs->buf);
b6bb3468 13482 reply = remote_get_noisy_reply ();
d6c5869f 13483 if (*reply == '\0')
ad91cd99
PA
13484 error (_("Target does not support this command."));
13485 if (strcmp (reply, "OK") != 0)
13486 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13487 return 0;
13488}
13489
13490/* This is basically a memory transfer, but needs to be its own packet
13491 because we don't know how the target actually organizes its trace
13492 memory, plus we want to be able to ask for as much as possible, but
13493 not be unhappy if we don't get as much as we ask for. */
13494
f6ac5f3d
PA
13495LONGEST
13496remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13497{
13498 struct remote_state *rs = get_remote_state ();
13499 char *reply;
13500 char *p;
13501 int rslt;
13502
13503 p = rs->buf;
13504 strcpy (p, "qTBuffer:");
13505 p += strlen (p);
13506 p += hexnumstr (p, offset);
13507 *p++ = ',';
13508 p += hexnumstr (p, len);
13509 *p++ = '\0';
13510
13511 putpkt (rs->buf);
b6bb3468 13512 reply = remote_get_noisy_reply ();
00bf0b85
SS
13513 if (reply && *reply)
13514 {
13515 /* 'l' by itself means we're at the end of the buffer and
13516 there is nothing more to get. */
13517 if (*reply == 'l')
13518 return 0;
13519
13520 /* Convert the reply into binary. Limit the number of bytes to
13521 convert according to our passed-in buffer size, rather than
13522 what was returned in the packet; if the target is
13523 unexpectedly generous and gives us a bigger reply than we
13524 asked for, we don't want to crash. */
b6bb3468 13525 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13526 return rslt;
13527 }
13528
13529 /* Something went wrong, flag as an error. */
13530 return -1;
13531}
13532
f6ac5f3d
PA
13533void
13534remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13535{
13536 struct remote_state *rs = get_remote_state ();
13537
4082afcc 13538 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 13539 {
ad91cd99
PA
13540 char *reply;
13541
bba74b36 13542 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 13543 putpkt (rs->buf);
b6bb3468 13544 reply = remote_get_noisy_reply ();
ad91cd99 13545 if (*reply == '\0')
33da3f1c 13546 error (_("Target does not support this command."));
ad91cd99
PA
13547 if (strcmp (reply, "OK") != 0)
13548 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13549 }
13550 else if (val)
13551 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13552}
13553
f6ac5f3d
PA
13554int
13555remote_target::core_of_thread (ptid_t ptid)
dc146f7c
VP
13556{
13557 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 13558
7aabaf9d
SM
13559 if (info != NULL && info->priv != NULL)
13560 return get_remote_thread_info (info)->core;
13561
dc146f7c
VP
13562 return -1;
13563}
13564
f6ac5f3d
PA
13565void
13566remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13567{
13568 struct remote_state *rs = get_remote_state ();
ad91cd99 13569 char *reply;
4daf5ac0 13570
bba74b36 13571 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 13572 putpkt (rs->buf);
b6bb3468 13573 reply = remote_get_noisy_reply ();
ad91cd99 13574 if (*reply == '\0')
4daf5ac0 13575 error (_("Target does not support this command."));
ad91cd99
PA
13576 if (strcmp (reply, "OK") != 0)
13577 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13578}
13579
f6ac5f3d
PA
13580traceframe_info_up
13581remote_target::traceframe_info ()
b3b9301e 13582{
9018be22 13583 gdb::optional<gdb::char_vector> text
f6ac5f3d 13584 = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13585 NULL);
9018be22
SM
13586 if (text)
13587 return parse_traceframe_info (text->data ());
b3b9301e
PA
13588
13589 return NULL;
13590}
13591
405f8e94
SS
13592/* Handle the qTMinFTPILen packet. Returns the minimum length of
13593 instruction on which a fast tracepoint may be placed. Returns -1
13594 if the packet is not supported, and 0 if the minimum instruction
13595 length is unknown. */
13596
f6ac5f3d
PA
13597int
13598remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13599{
13600 struct remote_state *rs = get_remote_state ();
13601 char *reply;
13602
e886a173
PA
13603 /* If we're not debugging a process yet, the IPA can't be
13604 loaded. */
13605 if (!target_has_execution)
13606 return 0;
13607
13608 /* Make sure the remote is pointing at the right process. */
13609 set_general_process ();
13610
bba74b36 13611 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13612 putpkt (rs->buf);
b6bb3468 13613 reply = remote_get_noisy_reply ();
405f8e94
SS
13614 if (*reply == '\0')
13615 return -1;
13616 else
13617 {
13618 ULONGEST min_insn_len;
13619
13620 unpack_varlen_hex (reply, &min_insn_len);
13621
13622 return (int) min_insn_len;
13623 }
13624}
13625
f6ac5f3d
PA
13626void
13627remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13628{
4082afcc 13629 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13630 {
13631 struct remote_state *rs = get_remote_state ();
13632 char *buf = rs->buf;
13633 char *endbuf = rs->buf + get_remote_packet_size ();
13634 enum packet_result result;
13635
13636 gdb_assert (val >= 0 || val == -1);
13637 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13638 /* Send -1 as literal "-1" to avoid host size dependency. */
13639 if (val < 0)
13640 {
13641 *buf++ = '-';
13642 buf += hexnumstr (buf, (ULONGEST) -val);
13643 }
13644 else
13645 buf += hexnumstr (buf, (ULONGEST) val);
13646
13647 putpkt (rs->buf);
b6bb3468 13648 remote_get_noisy_reply ();
f6f899bf
HAQ
13649 result = packet_ok (rs->buf,
13650 &remote_protocol_packets[PACKET_QTBuffer_size]);
13651
13652 if (result != PACKET_OK)
13653 warning (_("Bogus reply from target: %s"), rs->buf);
13654 }
13655}
13656
57810aa7 13657bool
f6ac5f3d
PA
13658remote_target::set_trace_notes (const char *user, const char *notes,
13659 const char *stop_notes)
f196051f
SS
13660{
13661 struct remote_state *rs = get_remote_state ();
13662 char *reply;
13663 char *buf = rs->buf;
13664 char *endbuf = rs->buf + get_remote_packet_size ();
13665 int nbytes;
13666
13667 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13668 if (user)
13669 {
13670 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13671 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13672 buf += 2 * nbytes;
13673 *buf++ = ';';
13674 }
13675 if (notes)
13676 {
13677 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13678 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13679 buf += 2 * nbytes;
13680 *buf++ = ';';
13681 }
13682 if (stop_notes)
13683 {
13684 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13685 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13686 buf += 2 * nbytes;
13687 *buf++ = ';';
13688 }
13689 /* Ensure the buffer is terminated. */
13690 *buf = '\0';
13691
13692 putpkt (rs->buf);
b6bb3468 13693 reply = remote_get_noisy_reply ();
f196051f 13694 if (*reply == '\0')
57810aa7 13695 return false;
f196051f
SS
13696
13697 if (strcmp (reply, "OK") != 0)
13698 error (_("Bogus reply from target: %s"), reply);
13699
57810aa7 13700 return true;
f196051f
SS
13701}
13702
57810aa7
PA
13703bool
13704remote_target::use_agent (bool use)
d1feda86 13705{
4082afcc 13706 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13707 {
13708 struct remote_state *rs = get_remote_state ();
13709
13710 /* If the stub supports QAgent. */
bba74b36 13711 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
13712 putpkt (rs->buf);
13713 getpkt (&rs->buf, &rs->buf_size, 0);
13714
13715 if (strcmp (rs->buf, "OK") == 0)
13716 {
f6ac5f3d 13717 ::use_agent = use;
57810aa7 13718 return true;
d1feda86
YQ
13719 }
13720 }
13721
57810aa7 13722 return false;
d1feda86
YQ
13723}
13724
57810aa7 13725bool
f6ac5f3d 13726remote_target::can_use_agent ()
d1feda86 13727{
4082afcc 13728 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13729}
13730
9accd112
MM
13731struct btrace_target_info
13732{
13733 /* The ptid of the traced thread. */
13734 ptid_t ptid;
f4abbc16
MM
13735
13736 /* The obtained branch trace configuration. */
13737 struct btrace_config conf;
9accd112
MM
13738};
13739
f4abbc16
MM
13740/* Reset our idea of our target's btrace configuration. */
13741
13742static void
6b8edb51 13743remote_btrace_reset (remote_state *rs)
f4abbc16 13744{
f4abbc16
MM
13745 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13746}
13747
f4abbc16
MM
13748/* Synchronize the configuration with the target. */
13749
6b8edb51
PA
13750void
13751remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 13752{
d33501a5
MM
13753 struct packet_config *packet;
13754 struct remote_state *rs;
13755 char *buf, *pos, *endbuf;
13756
13757 rs = get_remote_state ();
13758 buf = rs->buf;
13759 endbuf = buf + get_remote_packet_size ();
13760
13761 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13762 if (packet_config_support (packet) == PACKET_ENABLE
13763 && conf->bts.size != rs->btrace_config.bts.size)
13764 {
13765 pos = buf;
13766 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13767 conf->bts.size);
13768
13769 putpkt (buf);
13770 getpkt (&buf, &rs->buf_size, 0);
13771
13772 if (packet_ok (buf, packet) == PACKET_ERROR)
13773 {
13774 if (buf[0] == 'E' && buf[1] == '.')
13775 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13776 else
13777 error (_("Failed to configure the BTS buffer size."));
13778 }
13779
13780 rs->btrace_config.bts.size = conf->bts.size;
13781 }
b20a6524
MM
13782
13783 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13784 if (packet_config_support (packet) == PACKET_ENABLE
13785 && conf->pt.size != rs->btrace_config.pt.size)
13786 {
13787 pos = buf;
13788 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13789 conf->pt.size);
13790
13791 putpkt (buf);
13792 getpkt (&buf, &rs->buf_size, 0);
13793
13794 if (packet_ok (buf, packet) == PACKET_ERROR)
13795 {
13796 if (buf[0] == 'E' && buf[1] == '.')
13797 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13798 else
13799 error (_("Failed to configure the trace buffer size."));
13800 }
13801
13802 rs->btrace_config.pt.size = conf->pt.size;
13803 }
f4abbc16
MM
13804}
13805
13806/* Read the current thread's btrace configuration from the target and
13807 store it into CONF. */
13808
13809static void
13810btrace_read_config (struct btrace_config *conf)
13811{
9018be22 13812 gdb::optional<gdb::char_vector> xml
f6ac5f3d 13813 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
13814 if (xml)
13815 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
13816}
13817
c0272db5
TW
13818/* Maybe reopen target btrace. */
13819
6b8edb51
PA
13820void
13821remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
13822{
13823 struct remote_state *rs = get_remote_state ();
c0272db5
TW
13824 struct thread_info *tp;
13825 int btrace_target_pushed = 0;
13826 int warned = 0;
13827
5ed8105e
PA
13828 scoped_restore_current_thread restore_thread;
13829
c0272db5
TW
13830 ALL_NON_EXITED_THREADS (tp)
13831 {
13832 set_general_thread (tp->ptid);
13833
13834 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13835 btrace_read_config (&rs->btrace_config);
13836
13837 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13838 continue;
13839
13840#if !defined (HAVE_LIBIPT)
13841 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13842 {
13843 if (!warned)
13844 {
13845 warned = 1;
c4e12631
MM
13846 warning (_("Target is recording using Intel Processor Trace "
13847 "but support was disabled at compile time."));
c0272db5
TW
13848 }
13849
13850 continue;
13851 }
13852#endif /* !defined (HAVE_LIBIPT) */
13853
13854 /* Push target, once, but before anything else happens. This way our
13855 changes to the threads will be cleaned up by unpushing the target
13856 in case btrace_read_config () throws. */
13857 if (!btrace_target_pushed)
13858 {
13859 btrace_target_pushed = 1;
13860 record_btrace_push_target ();
13861 printf_filtered (_("Target is recording using %s.\n"),
13862 btrace_format_string (rs->btrace_config.format));
13863 }
13864
13865 tp->btrace.target = XCNEW (struct btrace_target_info);
13866 tp->btrace.target->ptid = tp->ptid;
13867 tp->btrace.target->conf = rs->btrace_config;
13868 }
c0272db5
TW
13869}
13870
9accd112
MM
13871/* Enable branch tracing. */
13872
f6ac5f3d
PA
13873struct btrace_target_info *
13874remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
9accd112
MM
13875{
13876 struct btrace_target_info *tinfo = NULL;
b20a6524 13877 struct packet_config *packet = NULL;
9accd112
MM
13878 struct remote_state *rs = get_remote_state ();
13879 char *buf = rs->buf;
13880 char *endbuf = rs->buf + get_remote_packet_size ();
13881
b20a6524
MM
13882 switch (conf->format)
13883 {
13884 case BTRACE_FORMAT_BTS:
13885 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13886 break;
13887
13888 case BTRACE_FORMAT_PT:
13889 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13890 break;
13891 }
13892
13893 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13894 error (_("Target does not support branch tracing."));
13895
f4abbc16
MM
13896 btrace_sync_conf (conf);
13897
9accd112
MM
13898 set_general_thread (ptid);
13899
13900 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13901 putpkt (rs->buf);
13902 getpkt (&rs->buf, &rs->buf_size, 0);
13903
13904 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13905 {
13906 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13907 error (_("Could not enable branch tracing for %s: %s"),
13908 target_pid_to_str (ptid), rs->buf + 2);
13909 else
13910 error (_("Could not enable branch tracing for %s."),
13911 target_pid_to_str (ptid));
13912 }
13913
8d749320 13914 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13915 tinfo->ptid = ptid;
13916
f4abbc16
MM
13917 /* If we fail to read the configuration, we lose some information, but the
13918 tracing itself is not impacted. */
492d29ea
PA
13919 TRY
13920 {
13921 btrace_read_config (&tinfo->conf);
13922 }
13923 CATCH (err, RETURN_MASK_ERROR)
13924 {
13925 if (err.message != NULL)
13926 warning ("%s", err.message);
13927 }
13928 END_CATCH
f4abbc16 13929
9accd112
MM
13930 return tinfo;
13931}
13932
13933/* Disable branch tracing. */
13934
f6ac5f3d
PA
13935void
13936remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13937{
13938 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13939 struct remote_state *rs = get_remote_state ();
13940 char *buf = rs->buf;
13941 char *endbuf = rs->buf + get_remote_packet_size ();
13942
4082afcc 13943 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13944 error (_("Target does not support branch tracing."));
13945
13946 set_general_thread (tinfo->ptid);
13947
13948 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13949 putpkt (rs->buf);
13950 getpkt (&rs->buf, &rs->buf_size, 0);
13951
13952 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13953 {
13954 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13955 error (_("Could not disable branch tracing for %s: %s"),
13956 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13957 else
13958 error (_("Could not disable branch tracing for %s."),
13959 target_pid_to_str (tinfo->ptid));
13960 }
13961
13962 xfree (tinfo);
13963}
13964
13965/* Teardown branch tracing. */
13966
f6ac5f3d
PA
13967void
13968remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13969{
13970 /* We must not talk to the target during teardown. */
13971 xfree (tinfo);
13972}
13973
13974/* Read the branch trace. */
13975
f6ac5f3d
PA
13976enum btrace_error
13977remote_target::read_btrace (struct btrace_data *btrace,
13978 struct btrace_target_info *tinfo,
13979 enum btrace_read_type type)
9accd112
MM
13980{
13981 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 13982 const char *annex;
9accd112 13983
4082afcc 13984 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13985 error (_("Target does not support branch tracing."));
13986
13987#if !defined(HAVE_LIBEXPAT)
13988 error (_("Cannot process branch tracing result. XML parsing not supported."));
13989#endif
13990
13991 switch (type)
13992 {
864089d2 13993 case BTRACE_READ_ALL:
9accd112
MM
13994 annex = "all";
13995 break;
864089d2 13996 case BTRACE_READ_NEW:
9accd112
MM
13997 annex = "new";
13998 break;
969c39fb
MM
13999 case BTRACE_READ_DELTA:
14000 annex = "delta";
14001 break;
9accd112
MM
14002 default:
14003 internal_error (__FILE__, __LINE__,
14004 _("Bad branch tracing read type: %u."),
14005 (unsigned int) type);
14006 }
14007
9018be22 14008 gdb::optional<gdb::char_vector> xml
f6ac5f3d 14009 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
9018be22 14010 if (!xml)
969c39fb 14011 return BTRACE_ERR_UNKNOWN;
9accd112 14012
9018be22 14013 parse_xml_btrace (btrace, xml->data ());
9accd112 14014
969c39fb 14015 return BTRACE_ERR_NONE;
9accd112
MM
14016}
14017
f6ac5f3d
PA
14018const struct btrace_config *
14019remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
14020{
14021 return &tinfo->conf;
14022}
14023
57810aa7 14024bool
f6ac5f3d 14025remote_target::augmented_libraries_svr4_read ()
ced63ec0 14026{
4082afcc
PA
14027 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14028 == PACKET_ENABLE);
ced63ec0
GB
14029}
14030
9dd130a0
TT
14031/* Implementation of to_load. */
14032
f6ac5f3d
PA
14033void
14034remote_target::load (const char *name, int from_tty)
9dd130a0
TT
14035{
14036 generic_load (name, from_tty);
14037}
14038
c78fa86a
GB
14039/* Accepts an integer PID; returns a string representing a file that
14040 can be opened on the remote side to get the symbols for the child
14041 process. Returns NULL if the operation is not supported. */
14042
f6ac5f3d
PA
14043char *
14044remote_target::pid_to_exec_file (int pid)
c78fa86a 14045{
9018be22 14046 static gdb::optional<gdb::char_vector> filename;
835205d0
GB
14047 struct inferior *inf;
14048 char *annex = NULL;
c78fa86a
GB
14049
14050 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14051 return NULL;
14052
835205d0
GB
14053 inf = find_inferior_pid (pid);
14054 if (inf == NULL)
14055 internal_error (__FILE__, __LINE__,
14056 _("not currently attached to process %d"), pid);
14057
14058 if (!inf->fake_pid_p)
14059 {
14060 const int annex_size = 9;
14061
224c3ddb 14062 annex = (char *) alloca (annex_size);
835205d0
GB
14063 xsnprintf (annex, annex_size, "%x", pid);
14064 }
14065
f6ac5f3d 14066 filename = target_read_stralloc (target_stack,
c78fa86a
GB
14067 TARGET_OBJECT_EXEC_FILE, annex);
14068
9018be22 14069 return filename ? filename->data () : nullptr;
c78fa86a
GB
14070}
14071
750ce8d1
YQ
14072/* Implement the to_can_do_single_step target_ops method. */
14073
f6ac5f3d
PA
14074int
14075remote_target::can_do_single_step ()
750ce8d1
YQ
14076{
14077 /* We can only tell whether target supports single step or not by
14078 supported s and S vCont actions if the stub supports vContSupported
14079 feature. If the stub doesn't support vContSupported feature,
14080 we have conservatively to think target doesn't supports single
14081 step. */
14082 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14083 {
14084 struct remote_state *rs = get_remote_state ();
14085
14086 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 14087 remote_vcont_probe ();
750ce8d1
YQ
14088
14089 return rs->supports_vCont.s && rs->supports_vCont.S;
14090 }
14091 else
14092 return 0;
14093}
14094
3a00c802
PA
14095/* Implementation of the to_execution_direction method for the remote
14096 target. */
14097
f6ac5f3d
PA
14098enum exec_direction_kind
14099remote_target::execution_direction ()
3a00c802
PA
14100{
14101 struct remote_state *rs = get_remote_state ();
14102
14103 return rs->last_resume_exec_dir;
14104}
14105
f6327dcb
KB
14106/* Return pointer to the thread_info struct which corresponds to
14107 THREAD_HANDLE (having length HANDLE_LEN). */
14108
f6ac5f3d
PA
14109thread_info *
14110remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14111 int handle_len,
14112 inferior *inf)
f6327dcb
KB
14113{
14114 struct thread_info *tp;
14115
14116 ALL_NON_EXITED_THREADS (tp)
14117 {
7aabaf9d 14118 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
14119
14120 if (tp->inf == inf && priv != NULL)
14121 {
7aabaf9d 14122 if (handle_len != priv->thread_handle.size ())
f6327dcb 14123 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
7aabaf9d
SM
14124 handle_len, priv->thread_handle.size ());
14125 if (memcmp (thread_handle, priv->thread_handle.data (),
f6327dcb
KB
14126 handle_len) == 0)
14127 return tp;
14128 }
14129 }
14130
14131 return NULL;
14132}
14133
57810aa7 14134bool
f6ac5f3d 14135remote_target::can_async_p ()
6426a772 14136{
5d93a237
TT
14137 struct remote_state *rs = get_remote_state ();
14138
3015c064
SM
14139 /* We don't go async if the user has explicitly prevented it with the
14140 "maint set target-async" command. */
c6ebd6cf 14141 if (!target_async_permitted)
57810aa7 14142 return false;
75c99385 14143
23860348 14144 /* We're async whenever the serial device is. */
5d93a237 14145 return serial_can_async_p (rs->remote_desc);
6426a772
JM
14146}
14147
57810aa7 14148bool
f6ac5f3d 14149remote_target::is_async_p ()
6426a772 14150{
5d93a237
TT
14151 struct remote_state *rs = get_remote_state ();
14152
c6ebd6cf 14153 if (!target_async_permitted)
75c99385 14154 /* We only enable async when the user specifically asks for it. */
57810aa7 14155 return false;
75c99385 14156
23860348 14157 /* We're async whenever the serial device is. */
5d93a237 14158 return serial_is_async_p (rs->remote_desc);
6426a772
JM
14159}
14160
2acceee2
JM
14161/* Pass the SERIAL event on and up to the client. One day this code
14162 will be able to delay notifying the client of an event until the
23860348 14163 point where an entire packet has been received. */
2acceee2 14164
2acceee2
JM
14165static serial_event_ftype remote_async_serial_handler;
14166
6426a772 14167static void
819cc324 14168remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14169{
2acceee2
JM
14170 /* Don't propogate error information up to the client. Instead let
14171 the client find out about the error by querying the target. */
6a3753b3 14172 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
14173}
14174
74531fed
PA
14175static void
14176remote_async_inferior_event_handler (gdb_client_data data)
14177{
6b8edb51 14178 inferior_event_handler (INF_REG_EVENT, data);
74531fed
PA
14179}
14180
f6ac5f3d
PA
14181void
14182remote_target::async (int enable)
2acceee2 14183{
5d93a237
TT
14184 struct remote_state *rs = get_remote_state ();
14185
6a3753b3 14186 if (enable)
2acceee2 14187 {
88b496c3 14188 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14189
14190 /* If there are pending events in the stop reply queue tell the
14191 event loop to process them. */
6b8edb51
PA
14192 if (!QUEUE_is_empty (stop_reply_p, rs->stop_reply_queue))
14193 mark_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14194 /* For simplicity, below we clear the pending events token
14195 without remembering whether it is marked, so here we always
14196 mark it. If there's actually no pending notification to
14197 process, this ends up being a no-op (other than a spurious
14198 event-loop wakeup). */
14199 if (target_is_non_stop_p ())
14200 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14201 }
14202 else
b7d2e916
PA
14203 {
14204 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14205 /* If the core is disabling async, it doesn't want to be
14206 disturbed with target events. Clear all async event sources
14207 too. */
6b8edb51 14208 clear_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14209 if (target_is_non_stop_p ())
14210 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14211 }
6426a772
JM
14212}
14213
65706a29
PA
14214/* Implementation of the to_thread_events method. */
14215
f6ac5f3d
PA
14216void
14217remote_target::thread_events (int enable)
65706a29
PA
14218{
14219 struct remote_state *rs = get_remote_state ();
14220 size_t size = get_remote_packet_size ();
65706a29
PA
14221
14222 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14223 return;
14224
14225 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14226 putpkt (rs->buf);
14227 getpkt (&rs->buf, &rs->buf_size, 0);
14228
14229 switch (packet_ok (rs->buf,
14230 &remote_protocol_packets[PACKET_QThreadEvents]))
14231 {
14232 case PACKET_OK:
14233 if (strcmp (rs->buf, "OK") != 0)
14234 error (_("Remote refused setting thread events: %s"), rs->buf);
14235 break;
14236 case PACKET_ERROR:
14237 warning (_("Remote failure reply: %s"), rs->buf);
14238 break;
14239 case PACKET_UNKNOWN:
14240 break;
14241 }
14242}
14243
5a2468f5 14244static void
981a3fb3 14245set_remote_cmd (const char *args, int from_tty)
5a2468f5 14246{
635c7e8a 14247 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
14248}
14249
d471ea57 14250static void
981a3fb3 14251show_remote_cmd (const char *args, int from_tty)
d471ea57 14252{
37a105a1 14253 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14254 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14255 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14256 struct ui_out *uiout = current_uiout;
37a105a1 14257
2e783024 14258 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14259 for (; list != NULL; list = list->next)
14260 if (strcmp (list->name, "Z-packet") == 0)
14261 continue;
427c3a89
DJ
14262 else if (list->type == not_set_cmd)
14263 /* Alias commands are exactly like the original, except they
14264 don't have the normal type. */
14265 continue;
14266 else
37a105a1 14267 {
2e783024 14268 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14269
112e8700
SM
14270 uiout->field_string ("name", list->name);
14271 uiout->text (": ");
427c3a89 14272 if (list->type == show_cmd)
f5c4fcd9 14273 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14274 else
14275 cmd_func (list, NULL, from_tty);
37a105a1 14276 }
d471ea57 14277}
5a2468f5 14278
0f71a2f6 14279
23860348 14280/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
14281static void
14282remote_new_objfile (struct objfile *objfile)
14283{
6b8edb51 14284 remote_target *remote = get_current_remote_target ();
5d93a237 14285
6b8edb51
PA
14286 if (remote != NULL) /* Have a remote connection. */
14287 remote->remote_check_symbols ();
dc8acb97
MS
14288}
14289
00bf0b85
SS
14290/* Pull all the tracepoints defined on the target and create local
14291 data structures representing them. We don't want to create real
14292 tracepoints yet, we don't want to mess up the user's existing
14293 collection. */
14294
f6ac5f3d
PA
14295int
14296remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 14297{
00bf0b85
SS
14298 struct remote_state *rs = get_remote_state ();
14299 char *p;
d5551862 14300
00bf0b85
SS
14301 /* Ask for a first packet of tracepoint definition. */
14302 putpkt ("qTfP");
14303 getpkt (&rs->buf, &rs->buf_size, 0);
14304 p = rs->buf;
14305 while (*p && *p != 'l')
d5551862 14306 {
00bf0b85
SS
14307 parse_tracepoint_definition (p, utpp);
14308 /* Ask for another packet of tracepoint definition. */
14309 putpkt ("qTsP");
14310 getpkt (&rs->buf, &rs->buf_size, 0);
14311 p = rs->buf;
d5551862 14312 }
00bf0b85 14313 return 0;
d5551862
SS
14314}
14315
f6ac5f3d
PA
14316int
14317remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 14318{
00bf0b85 14319 struct remote_state *rs = get_remote_state ();
d5551862 14320 char *p;
d5551862 14321
00bf0b85
SS
14322 /* Ask for a first packet of variable definition. */
14323 putpkt ("qTfV");
d5551862
SS
14324 getpkt (&rs->buf, &rs->buf_size, 0);
14325 p = rs->buf;
00bf0b85 14326 while (*p && *p != 'l')
d5551862 14327 {
00bf0b85
SS
14328 parse_tsv_definition (p, utsvp);
14329 /* Ask for another packet of variable definition. */
14330 putpkt ("qTsV");
d5551862
SS
14331 getpkt (&rs->buf, &rs->buf_size, 0);
14332 p = rs->buf;
14333 }
00bf0b85 14334 return 0;
d5551862
SS
14335}
14336
c1e36e3e
PA
14337/* The "set/show range-stepping" show hook. */
14338
14339static void
14340show_range_stepping (struct ui_file *file, int from_tty,
14341 struct cmd_list_element *c,
14342 const char *value)
14343{
14344 fprintf_filtered (file,
14345 _("Debugger's willingness to use range stepping "
14346 "is %s.\n"), value);
14347}
14348
6b8edb51
PA
14349/* Return true if the vCont;r action is supported by the remote
14350 stub. */
14351
14352bool
14353remote_target::vcont_r_supported ()
14354{
14355 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14356 remote_vcont_probe ();
14357
14358 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14359 && get_remote_state ()->supports_vCont.r);
14360}
14361
c1e36e3e
PA
14362/* The "set/show range-stepping" set hook. */
14363
14364static void
eb4c3f4a 14365set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
14366 struct cmd_list_element *c)
14367{
6b8edb51
PA
14368 /* When enabling, check whether range stepping is actually supported
14369 by the target, and warn if not. */
c1e36e3e
PA
14370 if (use_range_stepping)
14371 {
6b8edb51
PA
14372 remote_target *remote = get_current_remote_target ();
14373 if (remote == NULL
14374 || !remote->vcont_r_supported ())
14375 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
14376 }
14377}
14378
c906108c 14379void
fba45db2 14380_initialize_remote (void)
c906108c 14381{
9a7071a8 14382 struct cmd_list_element *cmd;
6f937416 14383 const char *cmd_name;
ea9c271d 14384
0f71a2f6 14385 /* architecture specific data */
29709017
DJ
14386 remote_g_packet_data_handle =
14387 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14388
94585166
DB
14389 remote_pspace_data
14390 = register_program_space_data_with_cleanup (NULL,
14391 remote_pspace_data_cleanup);
14392
d9f719f1
PA
14393 add_target (remote_target_info, remote_target::open);
14394 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 14395
dc8acb97 14396 /* Hook into new objfile notification. */
76727919 14397 gdb::observers::new_objfile.attach (remote_new_objfile);
dc8acb97 14398
c906108c
SS
14399#if 0
14400 init_remote_threadtests ();
14401#endif
14402
23860348 14403 /* set/show remote ... */
d471ea57 14404
1bedd215 14405 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
14406Remote protocol specific variables\n\
14407Configure various remote-protocol specific variables such as\n\
1bedd215 14408the packets being used"),
cff3e48b 14409 &remote_set_cmdlist, "set remote ",
23860348 14410 0 /* allow-unknown */, &setlist);
1bedd215 14411 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
14412Remote protocol specific variables\n\
14413Configure various remote-protocol specific variables such as\n\
1bedd215 14414the packets being used"),
cff3e48b 14415 &remote_show_cmdlist, "show remote ",
23860348 14416 0 /* allow-unknown */, &showlist);
5a2468f5 14417
1a966eab
AC
14418 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14419Compare section data on target to the exec file.\n\
95cf3b38
DT
14420Argument is a single section name (default: all loaded sections).\n\
14421To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14422 &cmdlist);
14423
1a966eab
AC
14424 add_cmd ("packet", class_maintenance, packet_command, _("\
14425Send an arbitrary packet to a remote target.\n\
c906108c
SS
14426 maintenance packet TEXT\n\
14427If GDB is talking to an inferior via the GDB serial protocol, then\n\
14428this command sends the string TEXT to the inferior, and displays the\n\
14429response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14430terminating `#' character and checksum."),
c906108c
SS
14431 &maintenancelist);
14432
7915a72c
AC
14433 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14434Set whether to send break if interrupted."), _("\
14435Show whether to send break if interrupted."), _("\
14436If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14437 set_remotebreak, show_remotebreak,
e707bbc2 14438 &setlist, &showlist);
9a7071a8
JB
14439 cmd_name = "remotebreak";
14440 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14441 deprecate_cmd (cmd, "set remote interrupt-sequence");
14442 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14443 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14444 deprecate_cmd (cmd, "show remote interrupt-sequence");
14445
14446 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14447 interrupt_sequence_modes, &interrupt_sequence_mode,
14448 _("\
9a7071a8
JB
14449Set interrupt sequence to remote target."), _("\
14450Show interrupt sequence to remote target."), _("\
14451Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14452 NULL, show_interrupt_sequence,
14453 &remote_set_cmdlist,
14454 &remote_show_cmdlist);
14455
14456 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14457 &interrupt_on_connect, _("\
14458Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14459Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14460If set, interrupt sequence is sent to remote target."),
14461 NULL, NULL,
14462 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14463
23860348 14464 /* Install commands for configuring memory read/write packets. */
11cf8741 14465
1a966eab
AC
14466 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14467Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14468 &setlist);
1a966eab
AC
14469 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14470Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14471 &showlist);
14472 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14473 set_memory_write_packet_size, _("\
14474Set the maximum number of bytes per memory-write packet.\n\
14475Specify the number of bytes in a packet or 0 (zero) for the\n\
14476default packet size. The actual limit is further reduced\n\
14477dependent on the target. Specify ``fixed'' to disable the\n\
14478further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14479 &remote_set_cmdlist);
14480 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14481 set_memory_read_packet_size, _("\
14482Set the maximum number of bytes per memory-read packet.\n\
14483Specify the number of bytes in a packet or 0 (zero) for the\n\
14484default packet size. The actual limit is further reduced\n\
14485dependent on the target. Specify ``fixed'' to disable the\n\
14486further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14487 &remote_set_cmdlist);
14488 add_cmd ("memory-write-packet-size", no_class,
14489 show_memory_write_packet_size,
1a966eab 14490 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14491 &remote_show_cmdlist);
14492 add_cmd ("memory-read-packet-size", no_class,
14493 show_memory_read_packet_size,
1a966eab 14494 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14495 &remote_show_cmdlist);
c906108c 14496
b3f42336 14497 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14498 &remote_hw_watchpoint_limit, _("\
14499Set the maximum number of target hardware watchpoints."), _("\
14500Show the maximum number of target hardware watchpoints."), _("\
14501Specify a negative limit for unlimited."),
3e43a32a
MS
14502 NULL, NULL, /* FIXME: i18n: The maximum
14503 number of target hardware
14504 watchpoints is %s. */
b3f42336 14505 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
14506 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14507 &remote_hw_watchpoint_length_limit, _("\
14508Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14509Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14510Specify a negative limit for unlimited."),
14511 NULL, NULL, /* FIXME: i18n: The maximum
14512 length (in bytes) of a target
14513 hardware watchpoint is %s. */
14514 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 14515 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14516 &remote_hw_breakpoint_limit, _("\
14517Set the maximum number of target hardware breakpoints."), _("\
14518Show the maximum number of target hardware breakpoints."), _("\
14519Specify a negative limit for unlimited."),
3e43a32a
MS
14520 NULL, NULL, /* FIXME: i18n: The maximum
14521 number of target hardware
14522 breakpoints is %s. */
b3f42336 14523 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14524
1b493192
PA
14525 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14526 &remote_address_size, _("\
4d28ad1e
AC
14527Set the maximum size of the address (in bits) in a memory packet."), _("\
14528Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14529 NULL,
14530 NULL, /* FIXME: i18n: */
14531 &setlist, &showlist);
c906108c 14532
ca4f7f8b
PA
14533 init_all_packet_configs ();
14534
444abaca 14535 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14536 "X", "binary-download", 1);
0f71a2f6 14537
444abaca 14538 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14539 "vCont", "verbose-resume", 0);
506fb367 14540
89be2091
DJ
14541 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14542 "QPassSignals", "pass-signals", 0);
14543
82075af2
JS
14544 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14545 "QCatchSyscalls", "catch-syscalls", 0);
14546
9b224c5e
PA
14547 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14548 "QProgramSignals", "program-signals", 0);
14549
bc3b087d
SDJ
14550 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14551 "QSetWorkingDir", "set-working-dir", 0);
14552
aefd8b33
SDJ
14553 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14554 "QStartupWithShell", "startup-with-shell", 0);
14555
0a2dde4a
SDJ
14556 add_packet_config_cmd (&remote_protocol_packets
14557 [PACKET_QEnvironmentHexEncoded],
14558 "QEnvironmentHexEncoded", "environment-hex-encoded",
14559 0);
14560
14561 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14562 "QEnvironmentReset", "environment-reset",
14563 0);
14564
14565 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14566 "QEnvironmentUnset", "environment-unset",
14567 0);
14568
444abaca 14569 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14570 "qSymbol", "symbol-lookup", 0);
dc8acb97 14571
444abaca 14572 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14573 "P", "set-register", 1);
d471ea57 14574
444abaca 14575 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14576 "p", "fetch-register", 1);
b96ec7ac 14577
444abaca 14578 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14579 "Z0", "software-breakpoint", 0);
d471ea57 14580
444abaca 14581 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14582 "Z1", "hardware-breakpoint", 0);
d471ea57 14583
444abaca 14584 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14585 "Z2", "write-watchpoint", 0);
d471ea57 14586
444abaca 14587 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14588 "Z3", "read-watchpoint", 0);
d471ea57 14589
444abaca 14590 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14591 "Z4", "access-watchpoint", 0);
d471ea57 14592
0876f84a
DJ
14593 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14594 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14595
c78fa86a
GB
14596 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14597 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14598
23181151
DJ
14599 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14600 "qXfer:features:read", "target-features", 0);
14601
cfa9d6d9
DJ
14602 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14603 "qXfer:libraries:read", "library-info", 0);
14604
2268b414
JK
14605 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14606 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14607
fd79ecee
DJ
14608 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14609 "qXfer:memory-map:read", "memory-map", 0);
14610
0e7f50da
UW
14611 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14612 "qXfer:spu:read", "read-spu-object", 0);
14613
14614 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14615 "qXfer:spu:write", "write-spu-object", 0);
14616
07e059b5
VP
14617 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14618 "qXfer:osdata:read", "osdata", 0);
14619
dc146f7c
VP
14620 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14621 "qXfer:threads:read", "threads", 0);
14622
4aa995e1
PA
14623 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14624 "qXfer:siginfo:read", "read-siginfo-object", 0);
14625
14626 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14627 "qXfer:siginfo:write", "write-siginfo-object", 0);
14628
b3b9301e
PA
14629 add_packet_config_cmd
14630 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14631 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14632
169081d0
TG
14633 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14634 "qXfer:uib:read", "unwind-info-block", 0);
14635
444abaca 14636 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14637 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14638 0);
14639
711e434b
PM
14640 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14641 "qGetTIBAddr", "get-thread-information-block-address",
14642 0);
14643
40ab02ce
MS
14644 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14645 "bc", "reverse-continue", 0);
14646
14647 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14648 "bs", "reverse-step", 0);
14649
be2a5f71
DJ
14650 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14651 "qSupported", "supported-packets", 0);
14652
08388c79
DE
14653 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14654 "qSearch:memory", "search-memory", 0);
14655
bd3eecc3
PA
14656 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14657 "qTStatus", "trace-status", 0);
14658
15a201c8
GB
14659 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14660 "vFile:setfs", "hostio-setfs", 0);
14661
a6b151f1
DJ
14662 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14663 "vFile:open", "hostio-open", 0);
14664
14665 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14666 "vFile:pread", "hostio-pread", 0);
14667
14668 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14669 "vFile:pwrite", "hostio-pwrite", 0);
14670
14671 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14672 "vFile:close", "hostio-close", 0);
14673
14674 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14675 "vFile:unlink", "hostio-unlink", 0);
14676
b9e7b9c3
UW
14677 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14678 "vFile:readlink", "hostio-readlink", 0);
14679
0a93529c
GB
14680 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14681 "vFile:fstat", "hostio-fstat", 0);
14682
2d717e4f
DJ
14683 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14684 "vAttach", "attach", 0);
14685
14686 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14687 "vRun", "run", 0);
14688
a6f3e723
SL
14689 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14690 "QStartNoAckMode", "noack", 0);
14691
82f73884
PA
14692 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14693 "vKill", "kill", 0);
14694
0b16c5cf
PA
14695 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14696 "qAttached", "query-attached", 0);
14697
782b2b07 14698 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14699 "ConditionalTracepoints",
14700 "conditional-tracepoints", 0);
3788aec7
LM
14701
14702 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14703 "ConditionalBreakpoints",
14704 "conditional-breakpoints", 0);
14705
d3ce09f5
SS
14706 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14707 "BreakpointCommands",
14708 "breakpoint-commands", 0);
14709
7a697b8d
SS
14710 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14711 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14712
409873ef
SS
14713 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14714 "TracepointSource", "TracepointSource", 0);
14715
d914c394
SS
14716 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14717 "QAllow", "allow", 0);
14718
0fb4aa4b
PA
14719 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14720 "StaticTracepoints", "static-tracepoints", 0);
14721
1e4d1764
YQ
14722 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14723 "InstallInTrace", "install-in-trace", 0);
14724
0fb4aa4b
PA
14725 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14726 "qXfer:statictrace:read", "read-sdata-object", 0);
14727
78d85199
YQ
14728 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14729 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14730
03583c20
UW
14731 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14732 "QDisableRandomization", "disable-randomization", 0);
14733
d1feda86
YQ
14734 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14735 "QAgent", "agent", 0);
14736
f6f899bf
HAQ
14737 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14738 "QTBuffer:size", "trace-buffer-size", 0);
14739
9accd112
MM
14740 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14741 "Qbtrace:off", "disable-btrace", 0);
14742
14743 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14744 "Qbtrace:bts", "enable-btrace-bts", 0);
14745
14746 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14747 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14748
14749 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14750 "qXfer:btrace", "read-btrace", 0);
14751
f4abbc16
MM
14752 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14753 "qXfer:btrace-conf", "read-btrace-conf", 0);
14754
d33501a5
MM
14755 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14756 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14757
73b8c1fd
PA
14758 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14759 "multiprocess-feature", "multiprocess-feature", 0);
14760
f7e6eed5
PA
14761 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14762 "swbreak-feature", "swbreak-feature", 0);
14763
14764 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14765 "hwbreak-feature", "hwbreak-feature", 0);
14766
89245bc0
DB
14767 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14768 "fork-event-feature", "fork-event-feature", 0);
14769
14770 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14771 "vfork-event-feature", "vfork-event-feature", 0);
14772
b20a6524
MM
14773 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14774 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14775
750ce8d1
YQ
14776 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14777 "vContSupported", "verbose-resume-supported", 0);
14778
94585166
DB
14779 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14780 "exec-event-feature", "exec-event-feature", 0);
14781
de979965
PA
14782 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14783 "vCtrlC", "ctrl-c", 0);
14784
65706a29
PA
14785 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14786 "QThreadEvents", "thread-events", 0);
14787
f2faf941
PA
14788 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14789 "N stop reply", "no-resumed-stop-reply", 0);
14790
0b736949
DB
14791 /* Assert that we've registered "set remote foo-packet" commands
14792 for all packet configs. */
ca4f7f8b
PA
14793 {
14794 int i;
14795
14796 for (i = 0; i < PACKET_MAX; i++)
14797 {
14798 /* Ideally all configs would have a command associated. Some
14799 still don't though. */
14800 int excepted;
14801
14802 switch (i)
14803 {
14804 case PACKET_QNonStop:
ca4f7f8b
PA
14805 case PACKET_EnableDisableTracepoints_feature:
14806 case PACKET_tracenz_feature:
14807 case PACKET_DisconnectedTracing_feature:
14808 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14809 case PACKET_qCRC:
14810 /* Additions to this list need to be well justified:
14811 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14812 excepted = 1;
14813 break;
14814 default:
14815 excepted = 0;
14816 break;
14817 }
14818
14819 /* This catches both forgetting to add a config command, and
14820 forgetting to remove a packet from the exception list. */
14821 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14822 }
14823 }
14824
37a105a1
DJ
14825 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14826 Z sub-packet has its own set and show commands, but users may
14827 have sets to this variable in their .gdbinit files (or in their
14828 documentation). */
e9e68a56 14829 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14830 &remote_Z_packet_detect, _("\
14831Set use of remote protocol `Z' packets"), _("\
14832Show use of remote protocol `Z' packets "), _("\
3b64bf98 14833When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14834packets."),
e9e68a56 14835 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14836 show_remote_protocol_Z_packet_cmd,
14837 /* FIXME: i18n: Use of remote protocol
14838 `Z' packets is %s. */
e9e68a56 14839 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14840
a6b151f1
DJ
14841 add_prefix_cmd ("remote", class_files, remote_command, _("\
14842Manipulate files on the remote system\n\
14843Transfer files to and from the remote target system."),
14844 &remote_cmdlist, "remote ",
14845 0 /* allow-unknown */, &cmdlist);
14846
14847 add_cmd ("put", class_files, remote_put_command,
14848 _("Copy a local file to the remote system."),
14849 &remote_cmdlist);
14850
14851 add_cmd ("get", class_files, remote_get_command,
14852 _("Copy a remote file to the local system."),
14853 &remote_cmdlist);
14854
14855 add_cmd ("delete", class_files, remote_delete_command,
14856 _("Delete a remote file."),
14857 &remote_cmdlist);
14858
2d717e4f 14859 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14860 &remote_exec_file_var, _("\
2d717e4f 14861Set the remote pathname for \"run\""), _("\
94585166
DB
14862Show the remote pathname for \"run\""), NULL,
14863 set_remote_exec_file,
14864 show_remote_exec_file,
14865 &remote_set_cmdlist,
14866 &remote_show_cmdlist);
2d717e4f 14867
c1e36e3e
PA
14868 add_setshow_boolean_cmd ("range-stepping", class_run,
14869 &use_range_stepping, _("\
14870Enable or disable range stepping."), _("\
14871Show whether target-assisted range stepping is enabled."), _("\
14872If on, and the target supports it, when stepping a source line, GDB\n\
14873tells the target to step the corresponding range of addresses itself instead\n\
14874of issuing multiple single-steps. This speeds up source level\n\
14875stepping. If off, GDB always issues single-steps, even if range\n\
14876stepping is supported by the target. The default is on."),
14877 set_range_stepping,
14878 show_range_stepping,
14879 &setlist,
14880 &showlist);
14881
449092f6
CV
14882 /* Eventually initialize fileio. See fileio.c */
14883 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14884
ba348170 14885 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14886 special ptids with it set to != 0. */
ba348170
PA
14887 magic_null_ptid = ptid_build (42000, -1, 1);
14888 not_sent_ptid = ptid_build (42000, -2, 1);
14889 any_thread_ptid = ptid_build (42000, 0, 1);
c906108c 14890}
This page took 3.736678 seconds and 4 git commands to generate.