btrace: check for indirect jump return in _Unwind_RaiseException
[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;
953edf2b 99static void stop_reply_xfree (struct stop_reply *);
6b8edb51 100
953edf2b
TT
101struct stop_reply_deleter
102{
103 void operator() (stop_reply *r) const
104 {
105 stop_reply_xfree (r);
106 }
107};
108
109typedef std::unique_ptr<stop_reply, stop_reply_deleter> stop_reply_up;
6b8edb51
PA
110
111/* Generic configuration support for packets the stub optionally
112 supports. Allows the user to specify the use of the packet as well
113 as allowing GDB to auto-detect support in the remote stub. */
114
115enum packet_support
116 {
117 PACKET_SUPPORT_UNKNOWN = 0,
118 PACKET_ENABLE,
119 PACKET_DISABLE
120 };
121
122/* Analyze a packet's return value and update the packet config
123 accordingly. */
124
125enum packet_result
126{
127 PACKET_ERROR,
128 PACKET_OK,
129 PACKET_UNKNOWN
130};
131
132struct threads_listing_context;
3c69da40
PA
133
134/* Stub vCont actions support.
135
136 Each field is a boolean flag indicating whether the stub reports
137 support for the corresponding action. */
138
139struct vCont_action_support
140{
141 /* vCont;t */
142 bool t = false;
143
144 /* vCont;r */
145 bool r = false;
146
147 /* vCont;s */
148 bool s = false;
149
150 /* vCont;S */
151 bool S = false;
152};
153
154/* About this many threadisds fit in a packet. */
155
156#define MAXTHREADLISTRESULTS 32
157
158/* Data for the vFile:pread readahead cache. */
159
160struct readahead_cache
161{
162 /* Invalidate the readahead cache. */
163 void invalidate ();
164
165 /* Invalidate the readahead cache if it is holding data for FD. */
166 void invalidate_fd (int fd);
167
168 /* Serve pread from the readahead cache. Returns number of bytes
169 read, or 0 if the request can't be served from the cache. */
170 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
171
172 /* The file descriptor for the file that is being cached. -1 if the
173 cache is invalid. */
174 int fd = -1;
175
176 /* The offset into the file that the cache buffer corresponds
177 to. */
178 ULONGEST offset = 0;
179
180 /* The buffer holding the cache contents. */
181 gdb_byte *buf = nullptr;
182 /* The buffer's size. We try to read as much as fits into a packet
183 at a time. */
184 size_t bufsize = 0;
185
186 /* Cache hit and miss counters. */
187 ULONGEST hit_count = 0;
188 ULONGEST miss_count = 0;
189};
190
191/* Description of the remote protocol for a given architecture. */
192
193struct packet_reg
194{
195 long offset; /* Offset into G packet. */
196 long regnum; /* GDB's internal register number. */
197 LONGEST pnum; /* Remote protocol register number. */
198 int in_g_packet; /* Always part of G packet. */
199 /* long size in bytes; == register_size (target_gdbarch (), regnum);
200 at present. */
201 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
202 at present. */
203};
204
205struct remote_arch_state
206{
207 explicit remote_arch_state (struct gdbarch *gdbarch);
208
209 /* Description of the remote protocol registers. */
210 long sizeof_g_packet;
211
212 /* Description of the remote protocol registers indexed by REGNUM
213 (making an array gdbarch_num_regs in size). */
214 std::unique_ptr<packet_reg[]> regs;
215
216 /* This is the size (in chars) of the first response to the ``g''
217 packet. It is used as a heuristic when determining the maximum
218 size of memory-read and memory-write packets. A target will
219 typically only reserve a buffer large enough to hold the ``g''
220 packet. The size does not include packet overhead (headers and
221 trailers). */
222 long actual_register_packet_size;
223
224 /* This is the maximum size (in chars) of a non read/write packet.
225 It is also used as a cap on the size of read/write packets. */
226 long remote_packet_size;
227};
228
229/* Description of the remote protocol state for the currently
230 connected target. This is per-target state, and independent of the
231 selected architecture. */
232
233class remote_state
234{
235public:
236
237 remote_state ();
238 ~remote_state ();
239
240 /* Get the remote arch state for GDBARCH. */
241 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
242
243public: /* data */
244
245 /* A buffer to use for incoming packets, and its current size. The
246 buffer is grown dynamically for larger incoming packets.
247 Outgoing packets may also be constructed in this buffer.
248 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
249 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
250 packets. */
251 char *buf;
252 long buf_size;
253
254 /* True if we're going through initial connection setup (finding out
255 about the remote side's threads, relocating symbols, etc.). */
256 bool starting_up = false;
257
258 /* If we negotiated packet size explicitly (and thus can bypass
259 heuristics for the largest packet size that will not overflow
260 a buffer in the stub), this will be set to that packet size.
261 Otherwise zero, meaning to use the guessed size. */
262 long explicit_packet_size = 0;
263
264 /* remote_wait is normally called when the target is running and
265 waits for a stop reply packet. But sometimes we need to call it
266 when the target is already stopped. We can send a "?" packet
267 and have remote_wait read the response. Or, if we already have
268 the response, we can stash it in BUF and tell remote_wait to
269 skip calling getpkt. This flag is set when BUF contains a
270 stop reply packet and the target is not waiting. */
271 int cached_wait_status = 0;
272
273 /* True, if in no ack mode. That is, neither GDB nor the stub will
274 expect acks from each other. The connection is assumed to be
275 reliable. */
276 bool noack_mode = false;
277
278 /* True if we're connected in extended remote mode. */
279 bool extended = false;
280
281 /* True if we resumed the target and we're waiting for the target to
282 stop. In the mean time, we can't start another command/query.
283 The remote server wouldn't be ready to process it, so we'd
284 timeout waiting for a reply that would never come and eventually
285 we'd close the connection. This can happen in asynchronous mode
286 because we allow GDB commands while the target is running. */
287 bool waiting_for_stop_reply = false;
288
289 /* The status of the stub support for the various vCont actions. */
290 vCont_action_support supports_vCont;
291
292 /* True if the user has pressed Ctrl-C, but the target hasn't
293 responded to that. */
294 bool ctrlc_pending_p = false;
295
296 /* True if we saw a Ctrl-C while reading or writing from/to the
297 remote descriptor. At that point it is not safe to send a remote
298 interrupt packet, so we instead remember we saw the Ctrl-C and
299 process it once we're done with sending/receiving the current
300 packet, which should be shortly. If however that takes too long,
301 and the user presses Ctrl-C again, we offer to disconnect. */
302 bool got_ctrlc_during_io = false;
303
304 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
305 remote_open knows that we don't have a file open when the program
306 starts. */
307 struct serial *remote_desc = nullptr;
308
309 /* These are the threads which we last sent to the remote system. The
310 TID member will be -1 for all or -2 for not sent yet. */
311 ptid_t general_thread = null_ptid;
312 ptid_t continue_thread = null_ptid;
313
314 /* This is the traceframe which we last selected on the remote system.
315 It will be -1 if no traceframe is selected. */
316 int remote_traceframe_number = -1;
317
318 char *last_pass_packet = nullptr;
319
320 /* The last QProgramSignals packet sent to the target. We bypass
321 sending a new program signals list down to the target if the new
322 packet is exactly the same as the last we sent. IOW, we only let
323 the target know about program signals list changes. */
324 char *last_program_signals_packet = nullptr;
325
326 gdb_signal last_sent_signal = GDB_SIGNAL_0;
327
328 bool last_sent_step = false;
329
330 /* The execution direction of the last resume we got. */
331 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
332
333 char *finished_object = nullptr;
334 char *finished_annex = nullptr;
335 ULONGEST finished_offset = 0;
336
337 /* Should we try the 'ThreadInfo' query packet?
338
339 This variable (NOT available to the user: auto-detect only!)
340 determines whether GDB will use the new, simpler "ThreadInfo"
341 query or the older, more complex syntax for thread queries.
342 This is an auto-detect variable (set to true at each connect,
343 and set to false when the target fails to recognize it). */
344 bool use_threadinfo_query = false;
345 bool use_threadextra_query = false;
346
347 threadref echo_nextthread {};
348 threadref nextthread {};
349 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
350
351 /* The state of remote notification. */
352 struct remote_notif_state *notif_state = nullptr;
353
354 /* The branch trace configuration. */
355 struct btrace_config btrace_config {};
356
357 /* The argument to the last "vFile:setfs:" packet we sent, used
358 to avoid sending repeated unnecessary "vFile:setfs:" packets.
359 Initialized to -1 to indicate that no "vFile:setfs:" packet
360 has yet been sent. */
361 int fs_pid = -1;
362
363 /* A readahead cache for vFile:pread. Often, reading a binary
364 involves a sequence of small reads. E.g., when parsing an ELF
365 file. A readahead cache helps mostly the case of remote
366 debugging on a connection with higher latency, due to the
367 request/reply nature of the RSP. We only cache data for a single
368 file descriptor at a time. */
369 struct readahead_cache readahead_cache;
370
371 /* The list of already fetched and acknowledged stop events. This
372 queue is used for notification Stop, and other notifications
373 don't need queue for their events, because the notification
374 events of Stop can't be consumed immediately, so that events
375 should be queued first, and be consumed by remote_wait_{ns,as}
376 one per time. Other notifications can consume their events
377 immediately, so queue is not needed for them. */
953edf2b 378 std::vector<stop_reply_up> stop_reply_queue;
3c69da40
PA
379
380 /* Asynchronous signal handle registered as event loop source for
381 when we have pending events ready to be passed to the core. */
382 struct async_event_handler *remote_async_inferior_event_token = nullptr;
383
384 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
385 ``forever'' still use the normal timeout mechanism. This is
386 currently used by the ASYNC code to guarentee that target reads
387 during the initial connect always time-out. Once getpkt has been
388 modified to return a timeout indication and, in turn
389 remote_wait()/wait_for_inferior() have gained a timeout parameter
390 this can go away. */
391 int wait_forever_enabled_p = 1;
392
393private:
394 /* Mapping of remote protocol data for each gdbarch. Usually there
395 is only one entry here, though we may see more with stubs that
396 support multi-process. */
397 std::unordered_map<struct gdbarch *, remote_arch_state>
398 m_arch_states;
399};
6b8edb51 400
d9f719f1
PA
401static const target_info remote_target_info = {
402 "remote",
403 N_("Remote serial target in gdb-specific protocol"),
404 remote_doc
405};
406
f6ac5f3d
PA
407class remote_target : public target_ops
408{
409public:
410 remote_target ()
411 {
412 to_stratum = process_stratum;
413 }
6b8edb51 414 ~remote_target () override;
f6ac5f3d 415
d9f719f1
PA
416 const target_info &info () const override
417 { return remote_target_info; }
f6ac5f3d
PA
418
419 thread_control_capabilities get_thread_control_capabilities () override
420 { return tc_schedlock; }
421
d9f719f1
PA
422 /* Open a remote connection. */
423 static void open (const char *, int);
424
f6ac5f3d
PA
425 void close () override;
426
427 void detach (inferior *, int) override;
428 void disconnect (const char *, int) override;
429
430 void commit_resume () override;
431 void resume (ptid_t, int, enum gdb_signal) override;
432 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
433
434 void fetch_registers (struct regcache *, int) override;
435 void store_registers (struct regcache *, int) override;
436 void prepare_to_store (struct regcache *) override;
437
438 void files_info () override;
439
440 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
441
442 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
443 enum remove_bp_reason) override;
444
445
57810aa7
PA
446 bool stopped_by_sw_breakpoint () override;
447 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 448
57810aa7 449 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 450
57810aa7 451 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 452
57810aa7 453 bool stopped_by_watchpoint () override;
f6ac5f3d 454
57810aa7 455 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 456
57810aa7 457 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
458
459 int can_use_hw_breakpoint (enum bptype, int, int) override;
460
461 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
462
463 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
464
465 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
466
467 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
468 struct expression *) override;
469
470 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
471 struct expression *) override;
472
473 void kill () override;
474
475 void load (const char *, int) override;
476
477 void mourn_inferior () override;
478
479 void pass_signals (int, unsigned char *) override;
480
481 int set_syscall_catchpoint (int, bool, int,
482 gdb::array_view<const int>) override;
483
484 void program_signals (int, unsigned char *) override;
485
57810aa7 486 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
487
488 const char *thread_name (struct thread_info *) override;
489
490 void update_thread_list () override;
491
492 const char *pid_to_str (ptid_t) override;
493
494 const char *extra_thread_info (struct thread_info *) override;
495
496 ptid_t get_ada_task_ptid (long lwp, long thread) override;
497
498 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
499 int handle_len,
500 inferior *inf) override;
501
502 void stop (ptid_t) override;
503
504 void interrupt () override;
505
506 void pass_ctrlc () override;
507
508 enum target_xfer_status xfer_partial (enum target_object object,
509 const char *annex,
510 gdb_byte *readbuf,
511 const gdb_byte *writebuf,
512 ULONGEST offset, ULONGEST len,
513 ULONGEST *xfered_len) override;
514
515 ULONGEST get_memory_xfer_limit () override;
516
517 void rcmd (const char *command, struct ui_file *output) override;
518
519 char *pid_to_exec_file (int pid) override;
520
521 void log_command (const char *cmd) override
522 {
523 serial_log_command (this, cmd);
524 }
525
526 CORE_ADDR get_thread_local_address (ptid_t ptid,
527 CORE_ADDR load_module_addr,
528 CORE_ADDR offset) override;
529
57810aa7
PA
530 bool has_all_memory () override { return default_child_has_all_memory (); }
531 bool has_memory () override { return default_child_has_memory (); }
532 bool has_stack () override { return default_child_has_stack (); }
533 bool has_registers () override { return default_child_has_registers (); }
534 bool has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
f6ac5f3d 535
57810aa7 536 bool can_execute_reverse () override;
f6ac5f3d
PA
537
538 std::vector<mem_region> memory_map () override;
539
540 void flash_erase (ULONGEST address, LONGEST length) override;
541
542 void flash_done () override;
543
544 const struct target_desc *read_description () override;
545
546 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
547 const gdb_byte *pattern, ULONGEST pattern_len,
548 CORE_ADDR *found_addrp) override;
549
57810aa7 550 bool can_async_p () override;
f6ac5f3d 551
57810aa7 552 bool is_async_p () override;
f6ac5f3d
PA
553
554 void async (int) override;
555
556 void thread_events (int) override;
557
558 int can_do_single_step () override;
559
560 void terminal_inferior () override;
561
562 void terminal_ours () override;
563
57810aa7 564 bool supports_non_stop () override;
f6ac5f3d 565
57810aa7 566 bool supports_multi_process () override;
f6ac5f3d 567
57810aa7 568 bool supports_disable_randomization () override;
f6ac5f3d 569
57810aa7 570 bool filesystem_is_local () override;
f6ac5f3d
PA
571
572
573 int fileio_open (struct inferior *inf, const char *filename,
574 int flags, int mode, int warn_if_slow,
575 int *target_errno) override;
576
577 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
578 ULONGEST offset, int *target_errno) override;
579
580 int fileio_pread (int fd, gdb_byte *read_buf, int len,
581 ULONGEST offset, int *target_errno) override;
582
583 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
584
585 int fileio_close (int fd, int *target_errno) override;
586
587 int fileio_unlink (struct inferior *inf,
588 const char *filename,
589 int *target_errno) override;
590
591 gdb::optional<std::string>
592 fileio_readlink (struct inferior *inf,
593 const char *filename,
594 int *target_errno) override;
595
57810aa7 596 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 597
57810aa7 598 bool supports_string_tracing () override;
f6ac5f3d 599
57810aa7 600 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 601
57810aa7 602 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
603
604 void trace_init () override;
605
606 void download_tracepoint (struct bp_location *location) override;
607
57810aa7 608 bool can_download_tracepoint () override;
f6ac5f3d
PA
609
610 void download_trace_state_variable (const trace_state_variable &tsv) override;
611
612 void enable_tracepoint (struct bp_location *location) override;
613
614 void disable_tracepoint (struct bp_location *location) override;
615
616 void trace_set_readonly_regions () override;
617
618 void trace_start () override;
619
620 int get_trace_status (struct trace_status *ts) override;
621
622 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
623 override;
624
625 void trace_stop () override;
626
627 int trace_find (enum trace_find_type type, int num,
628 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
629
57810aa7 630 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
631
632 int save_trace_data (const char *filename) override;
633
634 int upload_tracepoints (struct uploaded_tp **utpp) override;
635
636 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
637
638 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
639
640 int get_min_fast_tracepoint_insn_len () override;
641
642 void set_disconnected_tracing (int val) override;
643
644 void set_circular_trace_buffer (int val) override;
645
646 void set_trace_buffer_size (LONGEST val) override;
647
57810aa7
PA
648 bool set_trace_notes (const char *user, const char *notes,
649 const char *stopnotes) override;
f6ac5f3d
PA
650
651 int core_of_thread (ptid_t ptid) override;
652
653 int verify_memory (const gdb_byte *data,
654 CORE_ADDR memaddr, ULONGEST size) override;
655
656
57810aa7 657 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
658
659 void set_permissions () override;
660
661 bool static_tracepoint_marker_at (CORE_ADDR,
662 struct static_tracepoint_marker *marker)
663 override;
664
665 std::vector<static_tracepoint_marker>
666 static_tracepoint_markers_by_strid (const char *id) override;
667
668 traceframe_info_up traceframe_info () override;
669
57810aa7
PA
670 bool use_agent (bool use) override;
671 bool can_use_agent () override;
f6ac5f3d
PA
672
673 struct btrace_target_info *enable_btrace (ptid_t ptid,
674 const struct btrace_config *conf) override;
675
676 void disable_btrace (struct btrace_target_info *tinfo) override;
677
678 void teardown_btrace (struct btrace_target_info *tinfo) override;
679
680 enum btrace_error read_btrace (struct btrace_data *data,
681 struct btrace_target_info *btinfo,
682 enum btrace_read_type type) override;
683
684 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 685 bool augmented_libraries_svr4_read () override;
f6ac5f3d
PA
686 int follow_fork (int, int) override;
687 void follow_exec (struct inferior *, char *) override;
688 int insert_fork_catchpoint (int) override;
689 int remove_fork_catchpoint (int) override;
690 int insert_vfork_catchpoint (int) override;
691 int remove_vfork_catchpoint (int) override;
692 int insert_exec_catchpoint (int) override;
693 int remove_exec_catchpoint (int) override;
694 enum exec_direction_kind execution_direction () override;
695
6b8edb51
PA
696public: /* Remote specific methods. */
697
698 void remote_download_command_source (int num, ULONGEST addr,
699 struct command_line *cmds);
700
701 void remote_file_put (const char *local_file, const char *remote_file,
702 int from_tty);
703 void remote_file_get (const char *remote_file, const char *local_file,
704 int from_tty);
705 void remote_file_delete (const char *remote_file, int from_tty);
706
707 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, int *remote_errno);
709 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
710 ULONGEST offset, int *remote_errno);
711 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
712 ULONGEST offset, int *remote_errno);
713
714 int remote_hostio_send_command (int command_bytes, int which_packet,
715 int *remote_errno, char **attachment,
716 int *attachment_len);
717 int remote_hostio_set_filesystem (struct inferior *inf,
718 int *remote_errno);
719 /* We should get rid of this and use fileio_open directly. */
720 int remote_hostio_open (struct inferior *inf, const char *filename,
721 int flags, int mode, int warn_if_slow,
722 int *remote_errno);
723 int remote_hostio_close (int fd, int *remote_errno);
724
725 int remote_hostio_unlink (inferior *inf, const char *filename,
726 int *remote_errno);
727
728 struct remote_state *get_remote_state ();
729
730 long get_remote_packet_size (void);
731 long get_memory_packet_size (struct memory_packet_config *config);
732
733 long get_memory_write_packet_size ();
734 long get_memory_read_packet_size ();
735
736 char *append_pending_thread_resumptions (char *p, char *endp,
737 ptid_t ptid);
d9f719f1 738 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d 739 void start_remote (int from_tty, int extended_p);
00431a78 740 void remote_detach_1 (struct inferior *inf, int from_tty);
6b8edb51
PA
741
742 char *append_resumption (char *p, char *endp,
743 ptid_t ptid, int step, gdb_signal siggnal);
744 int remote_resume_with_vcont (ptid_t ptid, int step,
745 gdb_signal siggnal);
746
747 void add_current_inferior_and_thread (char *wait_status);
748
749 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
750 int options);
751 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
752 int options);
753
754 ptid_t process_stop_reply (struct stop_reply *stop_reply,
755 target_waitstatus *status);
756
757 void remote_notice_new_inferior (ptid_t currthread, int executing);
758
759 void process_initial_stop_replies (int from_tty);
760
00431a78 761 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
6b8edb51
PA
762
763 void btrace_sync_conf (const btrace_config *conf);
764
765 void remote_btrace_maybe_reopen ();
766
767 void remove_new_fork_children (threads_listing_context *context);
768 void kill_new_fork_children (int pid);
769 void discard_pending_stop_replies (struct inferior *inf);
770 int stop_reply_queue_length ();
771
772 void check_pending_events_prevent_wildcard_vcont
773 (int *may_global_wildcard_vcont);
774
775 void discard_pending_stop_replies_in_queue ();
776 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
777 struct stop_reply *queued_stop_reply (ptid_t ptid);
778 int peek_stop_reply (ptid_t ptid);
779 void remote_parse_stop_reply (char *buf, stop_reply *event);
780
781 void remote_stop_ns (ptid_t ptid);
782 void remote_interrupt_as ();
783 void remote_interrupt_ns ();
784
785 char *remote_get_noisy_reply ();
786 int remote_query_attached (int pid);
787 inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
788 int try_open_exec);
789
790 ptid_t remote_current_thread (ptid_t oldpid);
791 ptid_t get_current_thread (char *wait_status);
792
793 void set_thread (ptid_t ptid, int gen);
794 void set_general_thread (ptid_t ptid);
795 void set_continue_thread (ptid_t ptid);
796 void set_general_process ();
797
798 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
799
800 int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
801 gdb_ext_thread_info *info);
802 int remote_get_threadinfo (threadref *threadid, int fieldset,
803 gdb_ext_thread_info *info);
804
805 int parse_threadlist_response (char *pkt, int result_limit,
806 threadref *original_echo,
807 threadref *resultlist,
808 int *doneflag);
809 int remote_get_threadlist (int startflag, threadref *nextthread,
810 int result_limit, int *done, int *result_count,
811 threadref *threadlist);
812
813 int remote_threadlist_iterator (rmt_thread_action stepfunction,
814 void *context, int looplimit);
815
816 int remote_get_threads_with_ql (threads_listing_context *context);
817 int remote_get_threads_with_qxfer (threads_listing_context *context);
818 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
819
820 void extended_remote_restart ();
821
822 void get_offsets ();
823
824 void remote_check_symbols ();
825
826 void remote_supported_packet (const struct protocol_feature *feature,
827 enum packet_support support,
828 const char *argument);
829
830 void remote_query_supported ();
831
832 void remote_packet_size (const protocol_feature *feature,
833 packet_support support, const char *value);
834
835 void remote_serial_quit_handler ();
836
837 void remote_detach_pid (int pid);
838
839 void remote_vcont_probe ();
840
841 void remote_resume_with_hc (ptid_t ptid, int step,
842 gdb_signal siggnal);
843
844 void send_interrupt_sequence ();
845 void interrupt_query ();
846
847 void remote_notif_get_pending_events (notif_client *nc);
848
849 int fetch_register_using_p (struct regcache *regcache,
850 packet_reg *reg);
851 int send_g_packet ();
852 void process_g_packet (struct regcache *regcache);
853 void fetch_registers_using_g (struct regcache *regcache);
854 int store_register_using_P (const struct regcache *regcache,
855 packet_reg *reg);
856 void store_registers_using_G (const struct regcache *regcache);
857
858 void set_remote_traceframe ();
859
860 void check_binary_download (CORE_ADDR addr);
861
862 target_xfer_status remote_write_bytes_aux (const char *header,
863 CORE_ADDR memaddr,
864 const gdb_byte *myaddr,
865 ULONGEST len_units,
866 int unit_size,
867 ULONGEST *xfered_len_units,
868 char packet_format,
869 int use_length);
870
871 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
872 const gdb_byte *myaddr, ULONGEST len,
873 int unit_size, ULONGEST *xfered_len);
874
875 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
876 ULONGEST len_units,
877 int unit_size, ULONGEST *xfered_len_units);
878
879 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
880 ULONGEST memaddr,
881 ULONGEST len,
882 int unit_size,
883 ULONGEST *xfered_len);
884
885 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
886 gdb_byte *myaddr, ULONGEST len,
887 int unit_size,
888 ULONGEST *xfered_len);
889
890 packet_result remote_send_printf (const char *format, ...)
891 ATTRIBUTE_PRINTF (2, 3);
892
893 target_xfer_status remote_flash_write (ULONGEST address,
894 ULONGEST length, ULONGEST *xfered_len,
895 const gdb_byte *data);
896
897 int readchar (int timeout);
898
899 void remote_serial_write (const char *str, int len);
900
901 int putpkt (const char *buf);
902 int putpkt_binary (const char *buf, int cnt);
903
904 void skip_frame ();
905 long read_frame (char **buf_p, long *sizeof_buf);
906 void getpkt (char **buf, long *sizeof_buf, int forever);
907 int getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
908 int expecting_notif, int *is_notif);
909 int getpkt_sane (char **buf, long *sizeof_buf, int forever);
910 int getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
911 int *is_notif);
912 int remote_vkill (int pid);
913 void remote_kill_k ();
914
915 void extended_remote_disable_randomization (int val);
916 int extended_remote_run (const std::string &args);
917
918 void send_environment_packet (const char *action,
919 const char *packet,
920 const char *value);
921
922 void extended_remote_environment_support ();
3c69da40 923 void extended_remote_set_inferior_cwd ();
80152258 924
3c69da40
PA
925 target_xfer_status remote_write_qxfer (const char *object_name,
926 const char *annex,
927 const gdb_byte *writebuf,
928 ULONGEST offset, LONGEST len,
929 ULONGEST *xfered_len,
930 struct packet_config *packet);
43c3a0e4 931
3c69da40
PA
932 target_xfer_status remote_read_qxfer (const char *object_name,
933 const char *annex,
934 gdb_byte *readbuf, ULONGEST offset,
935 LONGEST len,
936 ULONGEST *xfered_len,
937 struct packet_config *packet);
43c3a0e4 938
3c69da40 939 void push_stop_reply (struct stop_reply *new_event);
43c3a0e4 940
3c69da40 941 bool vcont_r_supported ();
43c3a0e4 942
3c69da40 943 void packet_command (const char *args, int from_tty);
43c3a0e4 944
3c69da40 945private: /* data fields */
43c3a0e4 946
3c69da40
PA
947 /* The remote state. Don't reference this directly. Use the
948 get_remote_state method instead. */
949 remote_state m_remote_state;
43c3a0e4
PA
950};
951
3c69da40
PA
952static const target_info extended_remote_target_info = {
953 "extended-remote",
954 N_("Extended remote serial target in gdb-specific protocol"),
955 remote_doc
956};
ea9c271d 957
3c69da40
PA
958/* Set up the extended remote target by extending the standard remote
959 target and adding to it. */
960
961class extended_remote_target final : public remote_target
ea9c271d 962{
9d6eea31 963public:
3c69da40
PA
964 const target_info &info () const override
965 { return extended_remote_target_info; }
9d6eea31 966
3c69da40
PA
967 /* Open an extended-remote connection. */
968 static void open (const char *, int);
de44f5a7 969
3c69da40
PA
970 bool can_create_inferior () override { return true; }
971 void create_inferior (const char *, const std::string &,
972 char **, int) override;
9d6eea31 973
3c69da40 974 void detach (inferior *, int) override;
9d6eea31 975
3c69da40
PA
976 bool can_attach () override { return true; }
977 void attach (const char *, int) override;
be2a5f71 978
3c69da40
PA
979 void post_attach (int) override;
980 bool supports_disable_randomization () override;
981};
1e51243a 982
3c69da40
PA
983/* Per-program-space data key. */
984static const struct program_space_data *remote_pspace_data;
2d717e4f 985
3c69da40
PA
986/* The variable registered as the control variable used by the
987 remote exec-file commands. While the remote exec-file setting is
988 per-program-space, the set/show machinery uses this as the
989 location of the remote exec-file value. */
990static char *remote_exec_file_var;
a6f3e723 991
3c69da40
PA
992/* The size to align memory write packets, when practical. The protocol
993 does not guarantee any alignment, and gdb will generate short
994 writes and unaligned writes, but even as a best-effort attempt this
995 can improve bulk transfers. For instance, if a write is misaligned
996 relative to the target's data bus, the stub may need to make an extra
997 round trip fetching data from the target. This doesn't make a
998 huge difference, but it's easy to do, so we try to be helpful.
82f73884 999
3c69da40
PA
1000 The alignment chosen is arbitrary; usually data bus width is
1001 important here, not the possibly larger cache line size. */
1002enum { REMOTE_ALIGN_WRITES = 16 };
82f73884 1003
3c69da40 1004/* Prototypes for local functions. */
74531fed 1005
3c69da40 1006static int hexnumlen (ULONGEST num);
782b2b07 1007
3c69da40 1008static int stubhex (int ch);
5d93a237 1009
3c69da40 1010static int hexnumstr (char *, ULONGEST);
048094ac 1011
3c69da40 1012static int hexnumnstr (char *, ULONGEST, int);
47f8a51d 1013
3c69da40 1014static CORE_ADDR remote_address_masked (CORE_ADDR);
262e1174 1015
3c69da40 1016static void print_packet (const char *);
747dc59d 1017
3c69da40 1018static int stub_unpack_int (char *buff, int fieldlength);
5e4a05c4 1019
3c69da40 1020struct packet_config;
b73be471 1021
3c69da40 1022static void show_packet_config_cmd (struct packet_config *config);
280ceea3 1023
3c69da40
PA
1024static void show_remote_protocol_packet_cmd (struct ui_file *file,
1025 int from_tty,
1026 struct cmd_list_element *c,
1027 const char *value);
8e88304f 1028
3c69da40 1029static ptid_t read_ptid (const char *buf, const char **obuf);
3a00c802 1030
3c69da40 1031static void remote_async_inferior_event_handler (gdb_client_data);
b80fafe3 1032
3c69da40 1033static int remote_read_description_p (struct target_ops *target);
88b496c3 1034
3c69da40 1035static void remote_console_output (char *msg);
5965e028 1036
3c69da40 1037static void remote_btrace_reset (remote_state *rs);
f4abbc16 1038
3c69da40 1039static void remote_unpush_and_throw (void);
15a201c8 1040
3c69da40 1041/* For "remote". */
80152258 1042
3c69da40 1043static struct cmd_list_element *remote_cmdlist;
9d6eea31 1044
3c69da40 1045/* For "set remote" and "show remote". */
6b8edb51 1046
3c69da40
PA
1047static struct cmd_list_element *remote_set_cmdlist;
1048static struct cmd_list_element *remote_show_cmdlist;
6b8edb51 1049
3c69da40 1050/* Controls whether GDB is willing to use range stepping. */
6b8edb51 1051
3c69da40
PA
1052static int use_range_stepping = 1;
1053
1054/* The max number of chars in debug output. The rest of chars are
1055 omitted. */
1056
1057#define REMOTE_DEBUG_MAX_CHAR 512
ea9c271d 1058
7aabaf9d
SM
1059/* Private data that we'll store in (struct thread_info)->priv. */
1060struct remote_thread_info : public private_thread_info
dc146f7c 1061{
7aabaf9d
SM
1062 std::string extra;
1063 std::string name;
1064 int core = -1;
799a2abe 1065
f6327dcb
KB
1066 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1067 sequence of bytes. */
7aabaf9d 1068 gdb::byte_vector thread_handle;
f6327dcb 1069
799a2abe 1070 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1071 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1072
1073 /* This is set to the data address of the access causing the target
1074 to stop for a watchpoint. */
7aabaf9d 1075 CORE_ADDR watch_data_address = 0;
85ad3aaf
PA
1076
1077 /* Fields used by the vCont action coalescing implemented in
1078 remote_resume / remote_commit_resume. remote_resume stores each
1079 thread's last resume request in these fields, so that a later
1080 remote_commit_resume knows which is the proper action for this
1081 thread to include in the vCont packet. */
1082
1083 /* True if the last target_resume call for this thread was a step
1084 request, false if a continue request. */
7aabaf9d 1085 int last_resume_step = 0;
85ad3aaf
PA
1086
1087 /* The signal specified in the last target_resume call for this
1088 thread. */
7aabaf9d 1089 gdb_signal last_resume_sig = GDB_SIGNAL_0;
85ad3aaf
PA
1090
1091 /* Whether this thread was already vCont-resumed on the remote
1092 side. */
7aabaf9d 1093 int vcont_resumed = 0;
dc146f7c
VP
1094};
1095
de44f5a7
PA
1096remote_state::remote_state ()
1097{
1098 /* The default buffer size is unimportant; it will be expanded
1099 whenever a larger buffer is needed. */
1100 this->buf_size = 400;
1101 this->buf = (char *) xmalloc (this->buf_size);
1102}
1103
1104remote_state::~remote_state ()
1105{
1106 xfree (this->last_pass_packet);
1107 xfree (this->last_program_signals_packet);
1108 xfree (this->buf);
1109 xfree (this->finished_object);
1110 xfree (this->finished_annex);
cf792862
TT
1111}
1112
35b1e5cc
SS
1113/* Utility: generate error from an incoming stub packet. */
1114static void
1115trace_error (char *buf)
1116{
1117 if (*buf++ != 'E')
1118 return; /* not an error msg */
1119 switch (*buf)
1120 {
1121 case '1': /* malformed packet error */
1122 if (*++buf == '0') /* general case: */
1123 error (_("remote.c: error in outgoing packet."));
1124 else
1125 error (_("remote.c: error in outgoing packet at field #%ld."),
1126 strtol (buf, NULL, 16));
35b1e5cc
SS
1127 default:
1128 error (_("Target returns error code '%s'."), buf);
1129 }
1130}
1131
1132/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1133
6b8edb51
PA
1134char *
1135remote_target::remote_get_noisy_reply ()
35b1e5cc 1136{
b6bb3468
PA
1137 struct remote_state *rs = get_remote_state ();
1138
35b1e5cc
SS
1139 do /* Loop on reply from remote stub. */
1140 {
1141 char *buf;
a744cf53 1142
0df8b418 1143 QUIT; /* Allow user to bail out with ^C. */
b6bb3468
PA
1144 getpkt (&rs->buf, &rs->buf_size, 0);
1145 buf = rs->buf;
ad91cd99 1146 if (buf[0] == 'E')
35b1e5cc 1147 trace_error (buf);
61012eef 1148 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1149 {
1150 ULONGEST ul;
1151 CORE_ADDR from, to, org_to;
256642e8 1152 const char *p, *pp;
dde08ee1 1153 int adjusted_size = 0;
7556d4a4 1154 int relocated = 0;
dde08ee1
PA
1155
1156 p = buf + strlen ("qRelocInsn:");
1157 pp = unpack_varlen_hex (p, &ul);
1158 if (*pp != ';')
cb91c06a 1159 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1160 from = ul;
1161
1162 p = pp + 1;
a9cbf802 1163 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1164 to = ul;
1165
1166 org_to = to;
1167
492d29ea 1168 TRY
dde08ee1 1169 {
f5656ead 1170 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 1171 relocated = 1;
dde08ee1 1172 }
492d29ea 1173 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
1174 {
1175 if (ex.error == MEMORY_ERROR)
1176 {
1177 /* Propagate memory errors silently back to the
1178 target. The stub may have limited the range of
1179 addresses we can write to, for example. */
1180 }
1181 else
1182 {
1183 /* Something unexpectedly bad happened. Be verbose
1184 so we can tell what, and propagate the error back
1185 to the stub, so it doesn't get stuck waiting for
1186 a response. */
1187 exception_fprintf (gdb_stderr, ex,
1188 _("warning: relocating instruction: "));
1189 }
1190 putpkt ("E01");
1191 }
492d29ea 1192 END_CATCH
7556d4a4
PA
1193
1194 if (relocated)
dde08ee1
PA
1195 {
1196 adjusted_size = to - org_to;
1197
b6bb3468 1198 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1199 putpkt (buf);
1200 }
dde08ee1 1201 }
ad91cd99 1202 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
1203 remote_console_output (buf + 1); /* 'O' message from stub */
1204 else
0df8b418 1205 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1206 }
1207 while (1);
1208}
3c3bea1c 1209
9d6eea31
PA
1210struct remote_arch_state *
1211remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1212{
43c3a0e4
PA
1213 remote_arch_state *rsa;
1214
1215 auto it = this->m_arch_states.find (gdbarch);
1216 if (it == this->m_arch_states.end ())
9d6eea31 1217 {
43c3a0e4
PA
1218 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1219 std::forward_as_tuple (gdbarch),
1220 std::forward_as_tuple (gdbarch));
1221 rsa = &p.first->second;
9d6eea31
PA
1222
1223 /* Make sure that the packet buffer is plenty big enough for
1224 this architecture. */
1225 if (this->buf_size < rsa->remote_packet_size)
1226 {
1227 this->buf_size = 2 * rsa->remote_packet_size;
1228 this->buf = (char *) xrealloc (this->buf, this->buf_size);
1229 }
1230 }
43c3a0e4
PA
1231 else
1232 rsa = &it->second;
1233
1234 return rsa;
d01949b6
AC
1235}
1236
0b83947e
DJ
1237/* Fetch the global remote target state. */
1238
6b8edb51
PA
1239remote_state *
1240remote_target::get_remote_state ()
0b83947e
DJ
1241{
1242 /* Make sure that the remote architecture state has been
1243 initialized, because doing so might reallocate rs->buf. Any
1244 function which calls getpkt also needs to be mindful of changes
1245 to rs->buf, but this call limits the number of places which run
1246 into trouble. */
3c69da40 1247 m_remote_state.get_remote_arch_state (target_gdbarch ());
0b83947e 1248
3c69da40 1249 return &m_remote_state;
0b83947e
DJ
1250}
1251
94585166
DB
1252/* Cleanup routine for the remote module's pspace data. */
1253
1254static void
1255remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1256{
19ba03f4 1257 char *remote_exec_file = (char *) arg;
94585166
DB
1258
1259 xfree (remote_exec_file);
1260}
1261
1262/* Fetch the remote exec-file from the current program space. */
1263
1264static const char *
1265get_remote_exec_file (void)
1266{
1267 char *remote_exec_file;
1268
19ba03f4
SM
1269 remote_exec_file
1270 = (char *) program_space_data (current_program_space,
1271 remote_pspace_data);
94585166
DB
1272 if (remote_exec_file == NULL)
1273 return "";
1274
1275 return remote_exec_file;
1276}
1277
1278/* Set the remote exec file for PSPACE. */
1279
1280static void
1281set_pspace_remote_exec_file (struct program_space *pspace,
1282 char *remote_exec_file)
1283{
19ba03f4 1284 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
1285
1286 xfree (old_file);
1287 set_program_space_data (pspace, remote_pspace_data,
1288 xstrdup (remote_exec_file));
1289}
1290
1291/* The "set/show remote exec-file" set command hook. */
1292
1293static void
eb4c3f4a 1294set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1295 struct cmd_list_element *c)
1296{
1297 gdb_assert (remote_exec_file_var != NULL);
1298 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1299}
1300
1301/* The "set/show remote exec-file" show command hook. */
1302
1303static void
1304show_remote_exec_file (struct ui_file *file, int from_tty,
1305 struct cmd_list_element *cmd, const char *value)
1306{
1307 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1308}
1309
74ca34ce
DJ
1310static int
1311compare_pnums (const void *lhs_, const void *rhs_)
1312{
19ba03f4
SM
1313 const struct packet_reg * const *lhs
1314 = (const struct packet_reg * const *) lhs_;
1315 const struct packet_reg * const *rhs
1316 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
1317
1318 if ((*lhs)->pnum < (*rhs)->pnum)
1319 return -1;
1320 else if ((*lhs)->pnum == (*rhs)->pnum)
1321 return 0;
1322 else
1323 return 1;
1324}
1325
c21236dc
PA
1326static int
1327map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1328{
74ca34ce 1329 int regnum, num_remote_regs, offset;
74ca34ce 1330 struct packet_reg **remote_regs;
ea9c271d 1331
4a22f64d 1332 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1333 {
c21236dc 1334 struct packet_reg *r = &regs[regnum];
baef701f 1335
4a22f64d 1336 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1337 /* Do not try to fetch zero-sized (placeholder) registers. */
1338 r->pnum = -1;
1339 else
1340 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1341
b323314b 1342 r->regnum = regnum;
74ca34ce
DJ
1343 }
1344
1345 /* Define the g/G packet format as the contents of each register
1346 with a remote protocol number, in order of ascending protocol
1347 number. */
1348
224c3ddb 1349 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1350 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1351 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1352 regnum++)
c21236dc
PA
1353 if (regs[regnum].pnum != -1)
1354 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1355
74ca34ce
DJ
1356 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1357 compare_pnums);
1358
1359 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1360 {
1361 remote_regs[regnum]->in_g_packet = 1;
1362 remote_regs[regnum]->offset = offset;
4a22f64d 1363 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1364 }
1365
c21236dc
PA
1366 return offset;
1367}
1368
1369/* Given the architecture described by GDBARCH, return the remote
1370 protocol register's number and the register's offset in the g/G
1371 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1372 If the target does not have a mapping for REGNUM, return false,
1373 otherwise, return true. */
1374
1375int
1376remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1377 int *pnum, int *poffset)
1378{
c21236dc
PA
1379 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1380
b80406ac 1381 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1382
b80406ac 1383 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1384
1385 *pnum = regs[regnum].pnum;
1386 *poffset = regs[regnum].offset;
1387
c21236dc
PA
1388 return *pnum != -1;
1389}
1390
9d6eea31 1391remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1392{
c21236dc
PA
1393 /* Use the architecture to build a regnum<->pnum table, which will be
1394 1:1 unless a feature set specifies otherwise. */
9d6eea31 1395 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1396
74ca34ce
DJ
1397 /* Record the maximum possible size of the g packet - it may turn out
1398 to be smaller. */
9d6eea31
PA
1399 this->sizeof_g_packet
1400 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1401
0df8b418 1402 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1403 remote stubs have a hardwired buffer size of 400 bytes
1404 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1405 as the maximum packet-size to ensure that the packet and an extra
1406 NUL character can always fit in the buffer. This stops GDB
1407 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1408 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1409 this->remote_packet_size = 400 - 1;
d01949b6 1410
ea9c271d 1411 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1412 this->actual_register_packet_size = 0;
ea9c271d
DJ
1413
1414 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1415 default, adjust the size accordingly. Remember that each byte is
1416 encoded as two characters. 32 is the overhead for the packet
1417 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1418 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1419 little. */
9d6eea31
PA
1420 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1421 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1422}
1423
6b8edb51
PA
1424/* Get a pointer to the current remote target. If not connected to a
1425 remote target, return NULL. */
1426
1427static remote_target *
1428get_current_remote_target ()
1429{
1430 target_ops *proc_target = find_target_at (process_stratum);
1431 return dynamic_cast<remote_target *> (proc_target);
1432}
1433
ea9c271d
DJ
1434/* Return the current allowed size of a remote packet. This is
1435 inferred from the current architecture, and should be used to
1436 limit the length of outgoing packets. */
6b8edb51
PA
1437long
1438remote_target::get_remote_packet_size ()
ea9c271d 1439{
be2a5f71 1440 struct remote_state *rs = get_remote_state ();
9d6eea31 1441 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1442
be2a5f71
DJ
1443 if (rs->explicit_packet_size)
1444 return rs->explicit_packet_size;
1445
ea9c271d 1446 return rsa->remote_packet_size;
d01949b6
AC
1447}
1448
ad10f812 1449static struct packet_reg *
5cd63fda
PA
1450packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1451 long regnum)
ad10f812 1452{
5cd63fda 1453 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1454 return NULL;
1455 else
ad10f812 1456 {
ea9c271d 1457 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1458
b323314b
AC
1459 gdb_assert (r->regnum == regnum);
1460 return r;
ad10f812 1461 }
ad10f812
AC
1462}
1463
1464static struct packet_reg *
5cd63fda
PA
1465packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1466 LONGEST pnum)
ad10f812 1467{
b323314b 1468 int i;
a744cf53 1469
5cd63fda 1470 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1471 {
ea9c271d 1472 struct packet_reg *r = &rsa->regs[i];
a744cf53 1473
b323314b
AC
1474 if (r->pnum == pnum)
1475 return r;
ad10f812
AC
1476 }
1477 return NULL;
d01949b6
AC
1478}
1479
9a7071a8
JB
1480/* Allow the user to specify what sequence to send to the remote
1481 when he requests a program interruption: Although ^C is usually
1482 what remote systems expect (this is the default, here), it is
1483 sometimes preferable to send a break. On other systems such
1484 as the Linux kernel, a break followed by g, which is Magic SysRq g
1485 is required in order to interrupt the execution. */
1486const char interrupt_sequence_control_c[] = "Ctrl-C";
1487const char interrupt_sequence_break[] = "BREAK";
1488const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1489static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1490 {
1491 interrupt_sequence_control_c,
1492 interrupt_sequence_break,
1493 interrupt_sequence_break_g,
1494 NULL
1495 };
1496static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1497
1498static void
1499show_interrupt_sequence (struct ui_file *file, int from_tty,
1500 struct cmd_list_element *c,
1501 const char *value)
1502{
1503 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1504 fprintf_filtered (file,
1505 _("Send the ASCII ETX character (Ctrl-c) "
1506 "to the remote target to interrupt the "
1507 "execution of the program.\n"));
1508 else if (interrupt_sequence_mode == interrupt_sequence_break)
1509 fprintf_filtered (file,
1510 _("send a break signal to the remote target "
1511 "to interrupt the execution of the program.\n"));
1512 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1513 fprintf_filtered (file,
1514 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1515 "the remote target to interrupt the execution "
1516 "of Linux kernel.\n"));
1517 else
1518 internal_error (__FILE__, __LINE__,
1519 _("Invalid value for interrupt_sequence_mode: %s."),
1520 interrupt_sequence_mode);
1521}
6426a772 1522
9a7071a8
JB
1523/* This boolean variable specifies whether interrupt_sequence is sent
1524 to the remote target when gdb connects to it.
1525 This is mostly needed when you debug the Linux kernel: The Linux kernel
1526 expects BREAK g which is Magic SysRq g for connecting gdb. */
1527static int interrupt_on_connect = 0;
c906108c 1528
9a7071a8
JB
1529/* This variable is used to implement the "set/show remotebreak" commands.
1530 Since these commands are now deprecated in favor of "set/show remote
1531 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
1532static int remote_break;
1533
9a7071a8 1534static void
eb4c3f4a 1535set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1536{
1537 if (remote_break)
1538 interrupt_sequence_mode = interrupt_sequence_break;
1539 else
1540 interrupt_sequence_mode = interrupt_sequence_control_c;
1541}
1542
1543static void
1544show_remotebreak (struct ui_file *file, int from_tty,
1545 struct cmd_list_element *c,
1546 const char *value)
1547{
1548}
1549
c906108c
SS
1550/* This variable sets the number of bits in an address that are to be
1551 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1552 leading zeros, the entire address would be sent. This variable
c906108c
SS
1553 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1554 initial implementation of remote.c restricted the address sent in
1555 memory packets to ``host::sizeof long'' bytes - (typically 32
1556 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1557 address was never sent. Since fixing this bug may cause a break in
1558 some remote targets this variable is principly provided to
23860348 1559 facilitate backward compatibility. */
c906108c 1560
883b9c6c 1561static unsigned int remote_address_size;
c906108c 1562
11cf8741 1563\f
11cf8741 1564/* User configurable variables for the number of characters in a
ea9c271d
DJ
1565 memory read/write packet. MIN (rsa->remote_packet_size,
1566 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1567 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1568 (speed up transfers). The variables ``preferred_*'' (the user
1569 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1570 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1571
1572struct memory_packet_config
1573{
a121b7c1 1574 const char *name;
11cf8741
JM
1575 long size;
1576 int fixed_p;
1577};
1578
cc0be08f
PA
1579/* The default max memory-write-packet-size, when the setting is
1580 "fixed". The 16k is historical. (It came from older GDB's using
1581 alloca for buffers and the knowledge (folklore?) that some hosts
1582 don't cope very well with large alloca calls.) */
1583#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
1584
1585/* The minimum remote packet size for memory transfers. Ensures we
1586 can write at least one byte. */
1587#define MIN_MEMORY_PACKET_SIZE 20
1588
cc0be08f
PA
1589/* Get the memory packet size, assuming it is fixed. */
1590
1591static long
1592get_fixed_memory_packet_size (struct memory_packet_config *config)
1593{
1594 gdb_assert (config->fixed_p);
1595
1596 if (config->size <= 0)
1597 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1598 else
1599 return config->size;
1600}
1601
11cf8741
JM
1602/* Compute the current size of a read/write packet. Since this makes
1603 use of ``actual_register_packet_size'' the computation is dynamic. */
1604
6b8edb51
PA
1605long
1606remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 1607{
d01949b6 1608 struct remote_state *rs = get_remote_state ();
9d6eea31 1609 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1610
11cf8741
JM
1611 long what_they_get;
1612 if (config->fixed_p)
cc0be08f 1613 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
1614 else
1615 {
ea9c271d 1616 what_they_get = get_remote_packet_size ();
23860348 1617 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1618 if (config->size > 0
1619 && what_they_get > config->size)
1620 what_they_get = config->size;
be2a5f71
DJ
1621
1622 /* Limit it to the size of the targets ``g'' response unless we have
1623 permission from the stub to use a larger packet size. */
1624 if (rs->explicit_packet_size == 0
1625 && rsa->actual_register_packet_size > 0
1626 && what_they_get > rsa->actual_register_packet_size)
1627 what_they_get = rsa->actual_register_packet_size;
11cf8741 1628 }
a5c0808e
PA
1629 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1630 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1631
1632 /* Make sure there is room in the global buffer for this packet
1633 (including its trailing NUL byte). */
1634 if (rs->buf_size < what_they_get + 1)
1635 {
1636 rs->buf_size = 2 * what_they_get;
224c3ddb 1637 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1638 }
1639
11cf8741
JM
1640 return what_they_get;
1641}
1642
0df8b418 1643/* Update the size of a read/write packet. If they user wants
23860348 1644 something really big then do a sanity check. */
11cf8741
JM
1645
1646static void
ac88e2de 1647set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1648{
1649 int fixed_p = config->fixed_p;
1650 long size = config->size;
a744cf53 1651
11cf8741 1652 if (args == NULL)
8a3fe4f8 1653 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1654 else if (strcmp (args, "hard") == 0
1655 || strcmp (args, "fixed") == 0)
1656 fixed_p = 1;
1657 else if (strcmp (args, "soft") == 0
1658 || strcmp (args, "limit") == 0)
1659 fixed_p = 0;
1660 else
1661 {
1662 char *end;
a744cf53 1663
11cf8741
JM
1664 size = strtoul (args, &end, 0);
1665 if (args == end)
8a3fe4f8 1666 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1667
1668 /* Instead of explicitly capping the size of a packet to or
1669 disallowing it, the user is allowed to set the size to
1670 something arbitrarily large. */
11cf8741 1671 }
a5c0808e 1672
23860348 1673 /* Extra checks? */
11cf8741
JM
1674 if (fixed_p && !config->fixed_p)
1675 {
cc0be08f
PA
1676 /* So that the query shows the correct value. */
1677 long query_size = (size <= 0
1678 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1679 : size);
1680
e2e0b3e5
AC
1681 if (! query (_("The target may not be able to correctly handle a %s\n"
1682 "of %ld bytes. Change the packet size? "),
cc0be08f 1683 config->name, query_size))
8a3fe4f8 1684 error (_("Packet size not changed."));
11cf8741 1685 }
23860348 1686 /* Update the config. */
11cf8741
JM
1687 config->fixed_p = fixed_p;
1688 config->size = size;
1689}
1690
1691static void
1692show_memory_packet_size (struct memory_packet_config *config)
1693{
cc0be08f
PA
1694 if (config->size == 0)
1695 printf_filtered (_("The %s is 0 (default). "), config->name);
1696 else
1697 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1698 if (config->fixed_p)
a3f17187 1699 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
cc0be08f 1700 get_fixed_memory_packet_size (config));
11cf8741 1701 else
cc0be08f 1702 {
6b8edb51 1703 remote_target *remote = get_current_remote_target ();
cc0be08f 1704
6b8edb51 1705 if (remote != NULL)
cc0be08f 1706 printf_filtered (_("Packets are limited to %ld bytes.\n"),
6b8edb51 1707 remote->get_memory_packet_size (config));
cc0be08f
PA
1708 else
1709 puts_filtered ("The actual limit will be further reduced "
1710 "dependent on the target.\n");
1711 }
11cf8741
JM
1712}
1713
1714static struct memory_packet_config memory_write_packet_config =
1715{
1716 "memory-write-packet-size",
1717};
1718
1719static void
ac88e2de 1720set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1721{
1722 set_memory_packet_size (args, &memory_write_packet_config);
1723}
1724
1725static void
ac88e2de 1726show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1727{
1728 show_memory_packet_size (&memory_write_packet_config);
1729}
1730
055303e2
AB
1731/* Show the number of hardware watchpoints that can be used. */
1732
1733static void
1734show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1735 struct cmd_list_element *c,
1736 const char *value)
1737{
1738 fprintf_filtered (file, _("The maximum number of target hardware "
1739 "watchpoints is %s.\n"), value);
1740}
1741
1742/* Show the length limit (in bytes) for hardware watchpoints. */
1743
1744static void
1745show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1746 struct cmd_list_element *c,
1747 const char *value)
1748{
1749 fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1750 "hardware watchpoint is %s.\n"), value);
1751}
1752
1753/* Show the number of hardware breakpoints that can be used. */
1754
1755static void
1756show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1757 struct cmd_list_element *c,
1758 const char *value)
1759{
1760 fprintf_filtered (file, _("The maximum number of target hardware "
1761 "breakpoints is %s.\n"), value);
1762}
1763
6b8edb51
PA
1764long
1765remote_target::get_memory_write_packet_size ()
11cf8741
JM
1766{
1767 return get_memory_packet_size (&memory_write_packet_config);
1768}
1769
1770static struct memory_packet_config memory_read_packet_config =
1771{
1772 "memory-read-packet-size",
1773};
1774
1775static void
ac88e2de 1776set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1777{
1778 set_memory_packet_size (args, &memory_read_packet_config);
1779}
1780
1781static void
ac88e2de 1782show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1783{
1784 show_memory_packet_size (&memory_read_packet_config);
1785}
1786
6b8edb51
PA
1787long
1788remote_target::get_memory_read_packet_size ()
11cf8741
JM
1789{
1790 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1791
11cf8741
JM
1792 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1793 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1794 increased beyond this. */
1795 if (size > get_remote_packet_size ())
1796 size = get_remote_packet_size ();
11cf8741
JM
1797 return size;
1798}
1799
11cf8741 1800\f
5a2468f5 1801
5a2468f5
JM
1802struct packet_config
1803 {
bb572ddd
DJ
1804 const char *name;
1805 const char *title;
4082afcc
PA
1806
1807 /* If auto, GDB auto-detects support for this packet or feature,
1808 either through qSupported, or by trying the packet and looking
1809 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1810 packet. If false, the packet is disabled. Configs that don't
1811 have an associated command always have this set to auto. */
7f19b9a2 1812 enum auto_boolean detect;
4082afcc
PA
1813
1814 /* Does the target support this packet? */
5a2468f5
JM
1815 enum packet_support support;
1816 };
1817
4082afcc
PA
1818static enum packet_support packet_config_support (struct packet_config *config);
1819static enum packet_support packet_support (int packet);
5a2468f5
JM
1820
1821static void
fba45db2 1822show_packet_config_cmd (struct packet_config *config)
5a2468f5 1823{
a121b7c1 1824 const char *support = "internal-error";
a744cf53 1825
4082afcc 1826 switch (packet_config_support (config))
5a2468f5
JM
1827 {
1828 case PACKET_ENABLE:
1829 support = "enabled";
1830 break;
1831 case PACKET_DISABLE:
1832 support = "disabled";
1833 break;
1834 case PACKET_SUPPORT_UNKNOWN:
1835 support = "unknown";
1836 break;
1837 }
1838 switch (config->detect)
1839 {
7f19b9a2 1840 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1841 printf_filtered (_("Support for the `%s' packet "
1842 "is auto-detected, currently %s.\n"),
37a105a1 1843 config->name, support);
5a2468f5 1844 break;
7f19b9a2
AC
1845 case AUTO_BOOLEAN_TRUE:
1846 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1847 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1848 config->name, support);
8e248173 1849 break;
5a2468f5
JM
1850 }
1851}
1852
1853static void
bb572ddd
DJ
1854add_packet_config_cmd (struct packet_config *config, const char *name,
1855 const char *title, int legacy)
d471ea57 1856{
5a2468f5
JM
1857 char *set_doc;
1858 char *show_doc;
d471ea57 1859 char *cmd_name;
3ed07be4 1860
5a2468f5
JM
1861 config->name = name;
1862 config->title = title;
b435e160
AC
1863 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1864 name, title);
3e43a32a
MS
1865 show_doc = xstrprintf ("Show current use of remote "
1866 "protocol `%s' (%s) packet",
b435e160 1867 name, title);
d471ea57 1868 /* set/show TITLE-packet {auto,on,off} */
b435e160 1869 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1870 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1871 &config->detect, set_doc,
1872 show_doc, NULL, /* help_doc */
4082afcc 1873 NULL,
bb572ddd
DJ
1874 show_remote_protocol_packet_cmd,
1875 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1876 /* The command code copies the documentation strings. */
1877 xfree (set_doc);
1878 xfree (show_doc);
23860348 1879 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1880 if (legacy)
1881 {
1882 char *legacy_name;
a744cf53 1883
b435e160 1884 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1885 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1886 &remote_set_cmdlist);
d471ea57 1887 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1888 &remote_show_cmdlist);
d471ea57 1889 }
5a2468f5
JM
1890}
1891
d471ea57 1892static enum packet_result
a76d924d 1893packet_check_result (const char *buf)
5a2468f5 1894{
d471ea57 1895 if (buf[0] != '\0')
5a2468f5 1896 {
d471ea57 1897 /* The stub recognized the packet request. Check that the
23860348 1898 operation succeeded. */
a76d924d
DJ
1899 if (buf[0] == 'E'
1900 && isxdigit (buf[1]) && isxdigit (buf[2])
1901 && buf[3] == '\0')
1902 /* "Enn" - definitly an error. */
1903 return PACKET_ERROR;
1904
1905 /* Always treat "E." as an error. This will be used for
1906 more verbose error messages, such as E.memtypes. */
1907 if (buf[0] == 'E' && buf[1] == '.')
1908 return PACKET_ERROR;
1909
1910 /* The packet may or may not be OK. Just assume it is. */
1911 return PACKET_OK;
1912 }
1913 else
1914 /* The stub does not support the packet. */
1915 return PACKET_UNKNOWN;
1916}
1917
1918static enum packet_result
1919packet_ok (const char *buf, struct packet_config *config)
1920{
1921 enum packet_result result;
1922
4082afcc
PA
1923 if (config->detect != AUTO_BOOLEAN_TRUE
1924 && config->support == PACKET_DISABLE)
1925 internal_error (__FILE__, __LINE__,
1926 _("packet_ok: attempt to use a disabled packet"));
1927
a76d924d
DJ
1928 result = packet_check_result (buf);
1929 switch (result)
1930 {
1931 case PACKET_OK:
1932 case PACKET_ERROR:
1933 /* The stub recognized the packet request. */
4082afcc 1934 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1935 {
d471ea57
AC
1936 if (remote_debug)
1937 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1938 "Packet %s (%s) is supported\n",
1939 config->name, config->title);
d471ea57 1940 config->support = PACKET_ENABLE;
d471ea57 1941 }
a76d924d
DJ
1942 break;
1943 case PACKET_UNKNOWN:
23860348 1944 /* The stub does not support the packet. */
4082afcc
PA
1945 if (config->detect == AUTO_BOOLEAN_AUTO
1946 && config->support == PACKET_ENABLE)
d471ea57 1947 {
4082afcc
PA
1948 /* If the stub previously indicated that the packet was
1949 supported then there is a protocol error. */
1950 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1951 config->name, config->title);
1952 }
1953 else if (config->detect == AUTO_BOOLEAN_TRUE)
1954 {
1955 /* The user set it wrong. */
1956 error (_("Enabled packet %s (%s) not recognized by stub"),
1957 config->name, config->title);
d471ea57 1958 }
4082afcc
PA
1959
1960 if (remote_debug)
1961 fprintf_unfiltered (gdb_stdlog,
1962 "Packet %s (%s) is NOT supported\n",
1963 config->name, config->title);
1964 config->support = PACKET_DISABLE;
a76d924d 1965 break;
5a2468f5 1966 }
a76d924d
DJ
1967
1968 return result;
5a2468f5
JM
1969}
1970
444abaca
DJ
1971enum {
1972 PACKET_vCont = 0,
1973 PACKET_X,
1974 PACKET_qSymbol,
1975 PACKET_P,
1976 PACKET_p,
1977 PACKET_Z0,
1978 PACKET_Z1,
1979 PACKET_Z2,
1980 PACKET_Z3,
1981 PACKET_Z4,
15a201c8 1982 PACKET_vFile_setfs,
a6b151f1
DJ
1983 PACKET_vFile_open,
1984 PACKET_vFile_pread,
1985 PACKET_vFile_pwrite,
1986 PACKET_vFile_close,
1987 PACKET_vFile_unlink,
b9e7b9c3 1988 PACKET_vFile_readlink,
0a93529c 1989 PACKET_vFile_fstat,
0876f84a 1990 PACKET_qXfer_auxv,
23181151 1991 PACKET_qXfer_features,
c78fa86a 1992 PACKET_qXfer_exec_file,
cfa9d6d9 1993 PACKET_qXfer_libraries,
2268b414 1994 PACKET_qXfer_libraries_svr4,
fd79ecee 1995 PACKET_qXfer_memory_map,
0e7f50da
UW
1996 PACKET_qXfer_spu_read,
1997 PACKET_qXfer_spu_write,
07e059b5 1998 PACKET_qXfer_osdata,
dc146f7c 1999 PACKET_qXfer_threads,
0fb4aa4b 2000 PACKET_qXfer_statictrace_read,
b3b9301e 2001 PACKET_qXfer_traceframe_info,
169081d0 2002 PACKET_qXfer_uib,
711e434b 2003 PACKET_qGetTIBAddr,
444abaca 2004 PACKET_qGetTLSAddr,
be2a5f71 2005 PACKET_qSupported,
bd3eecc3 2006 PACKET_qTStatus,
89be2091 2007 PACKET_QPassSignals,
82075af2 2008 PACKET_QCatchSyscalls,
9b224c5e 2009 PACKET_QProgramSignals,
bc3b087d 2010 PACKET_QSetWorkingDir,
aefd8b33 2011 PACKET_QStartupWithShell,
0a2dde4a
SDJ
2012 PACKET_QEnvironmentHexEncoded,
2013 PACKET_QEnvironmentReset,
2014 PACKET_QEnvironmentUnset,
936d2992 2015 PACKET_qCRC,
08388c79 2016 PACKET_qSearch_memory,
2d717e4f
DJ
2017 PACKET_vAttach,
2018 PACKET_vRun,
a6f3e723 2019 PACKET_QStartNoAckMode,
82f73884 2020 PACKET_vKill,
4aa995e1
PA
2021 PACKET_qXfer_siginfo_read,
2022 PACKET_qXfer_siginfo_write,
0b16c5cf 2023 PACKET_qAttached,
4082afcc
PA
2024
2025 /* Support for conditional tracepoints. */
782b2b07 2026 PACKET_ConditionalTracepoints,
4082afcc
PA
2027
2028 /* Support for target-side breakpoint conditions. */
3788aec7 2029 PACKET_ConditionalBreakpoints,
4082afcc
PA
2030
2031 /* Support for target-side breakpoint commands. */
d3ce09f5 2032 PACKET_BreakpointCommands,
4082afcc
PA
2033
2034 /* Support for fast tracepoints. */
7a697b8d 2035 PACKET_FastTracepoints,
4082afcc
PA
2036
2037 /* Support for static tracepoints. */
0fb4aa4b 2038 PACKET_StaticTracepoints,
4082afcc
PA
2039
2040 /* Support for installing tracepoints while a trace experiment is
2041 running. */
1e4d1764 2042 PACKET_InstallInTrace,
4082afcc 2043
40ab02ce
MS
2044 PACKET_bc,
2045 PACKET_bs,
409873ef 2046 PACKET_TracepointSource,
d914c394 2047 PACKET_QAllow,
78d85199 2048 PACKET_qXfer_fdpic,
03583c20 2049 PACKET_QDisableRandomization,
d1feda86 2050 PACKET_QAgent,
f6f899bf 2051 PACKET_QTBuffer_size,
9accd112
MM
2052 PACKET_Qbtrace_off,
2053 PACKET_Qbtrace_bts,
b20a6524 2054 PACKET_Qbtrace_pt,
9accd112 2055 PACKET_qXfer_btrace,
4082afcc
PA
2056
2057 /* Support for the QNonStop packet. */
2058 PACKET_QNonStop,
2059
65706a29
PA
2060 /* Support for the QThreadEvents packet. */
2061 PACKET_QThreadEvents,
2062
4082afcc
PA
2063 /* Support for multi-process extensions. */
2064 PACKET_multiprocess_feature,
2065
2066 /* Support for enabling and disabling tracepoints while a trace
2067 experiment is running. */
2068 PACKET_EnableDisableTracepoints_feature,
2069
2070 /* Support for collecting strings using the tracenz bytecode. */
2071 PACKET_tracenz_feature,
2072
2073 /* Support for continuing to run a trace experiment while GDB is
2074 disconnected. */
2075 PACKET_DisconnectedTracing_feature,
2076
2077 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2078 PACKET_augmented_libraries_svr4_read_feature,
2079
f4abbc16
MM
2080 /* Support for the qXfer:btrace-conf:read packet. */
2081 PACKET_qXfer_btrace_conf,
2082
d33501a5
MM
2083 /* Support for the Qbtrace-conf:bts:size packet. */
2084 PACKET_Qbtrace_conf_bts_size,
2085
f7e6eed5
PA
2086 /* Support for swbreak+ feature. */
2087 PACKET_swbreak_feature,
2088
2089 /* Support for hwbreak+ feature. */
2090 PACKET_hwbreak_feature,
2091
89245bc0
DB
2092 /* Support for fork events. */
2093 PACKET_fork_event_feature,
2094
2095 /* Support for vfork events. */
2096 PACKET_vfork_event_feature,
2097
b20a6524
MM
2098 /* Support for the Qbtrace-conf:pt:size packet. */
2099 PACKET_Qbtrace_conf_pt_size,
2100
94585166
DB
2101 /* Support for exec events. */
2102 PACKET_exec_event_feature,
2103
750ce8d1
YQ
2104 /* Support for query supported vCont actions. */
2105 PACKET_vContSupported,
2106
de979965
PA
2107 /* Support remote CTRL-C. */
2108 PACKET_vCtrlC,
2109
f2faf941
PA
2110 /* Support TARGET_WAITKIND_NO_RESUMED. */
2111 PACKET_no_resumed,
2112
444abaca
DJ
2113 PACKET_MAX
2114};
506fb367 2115
444abaca 2116static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 2117
f7e6eed5
PA
2118/* Returns the packet's corresponding "set remote foo-packet" command
2119 state. See struct packet_config for more details. */
2120
2121static enum auto_boolean
2122packet_set_cmd_state (int packet)
2123{
2124 return remote_protocol_packets[packet].detect;
2125}
2126
4082afcc
PA
2127/* Returns whether a given packet or feature is supported. This takes
2128 into account the state of the corresponding "set remote foo-packet"
2129 command, which may be used to bypass auto-detection. */
dc8acb97 2130
4082afcc
PA
2131static enum packet_support
2132packet_config_support (struct packet_config *config)
2133{
2134 switch (config->detect)
444abaca 2135 {
4082afcc
PA
2136 case AUTO_BOOLEAN_TRUE:
2137 return PACKET_ENABLE;
2138 case AUTO_BOOLEAN_FALSE:
2139 return PACKET_DISABLE;
2140 case AUTO_BOOLEAN_AUTO:
2141 return config->support;
2142 default:
2143 gdb_assert_not_reached (_("bad switch"));
444abaca 2144 }
4082afcc
PA
2145}
2146
2147/* Same as packet_config_support, but takes the packet's enum value as
2148 argument. */
2149
2150static enum packet_support
2151packet_support (int packet)
2152{
2153 struct packet_config *config = &remote_protocol_packets[packet];
2154
2155 return packet_config_support (config);
dc8acb97
MS
2156}
2157
5a2468f5 2158static void
444abaca
DJ
2159show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2160 struct cmd_list_element *c,
2161 const char *value)
5a2468f5 2162{
444abaca 2163 struct packet_config *packet;
5a2468f5 2164
444abaca
DJ
2165 for (packet = remote_protocol_packets;
2166 packet < &remote_protocol_packets[PACKET_MAX];
2167 packet++)
2168 {
2169 if (&packet->detect == c->var)
2170 {
2171 show_packet_config_cmd (packet);
2172 return;
2173 }
2174 }
9b20d036 2175 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 2176 c->name);
5a2468f5
JM
2177}
2178
d471ea57
AC
2179/* Should we try one of the 'Z' requests? */
2180
2181enum Z_packet_type
2182{
2183 Z_PACKET_SOFTWARE_BP,
2184 Z_PACKET_HARDWARE_BP,
2185 Z_PACKET_WRITE_WP,
2186 Z_PACKET_READ_WP,
2187 Z_PACKET_ACCESS_WP,
2188 NR_Z_PACKET_TYPES
2189};
96baa820 2190
d471ea57 2191/* For compatibility with older distributions. Provide a ``set remote
23860348 2192 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2193
7f19b9a2 2194static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2195
2196static void
eb4c3f4a 2197set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2198 struct cmd_list_element *c)
96baa820 2199{
d471ea57 2200 int i;
a744cf53 2201
d471ea57 2202 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 2203 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
2204}
2205
2206static void
08546159
AC
2207show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2208 struct cmd_list_element *c,
2209 const char *value)
96baa820 2210{
d471ea57 2211 int i;
a744cf53 2212
d471ea57
AC
2213 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2214 {
444abaca 2215 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 2216 }
96baa820
JM
2217}
2218
4082afcc
PA
2219/* Returns true if the multi-process extensions are in effect. */
2220
2221static int
2222remote_multi_process_p (struct remote_state *rs)
2223{
2224 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2225}
2226
de0d863e
DB
2227/* Returns true if fork events are supported. */
2228
2229static int
2230remote_fork_event_p (struct remote_state *rs)
2231{
2232 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2233}
2234
c269dbdb
DB
2235/* Returns true if vfork events are supported. */
2236
2237static int
2238remote_vfork_event_p (struct remote_state *rs)
2239{
2240 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2241}
2242
d46addbb
DB
2243/* Returns true if exec events are supported. */
2244
2245static int
2246remote_exec_event_p (struct remote_state *rs)
2247{
2248 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2249}
2250
cbb8991c
DB
2251/* Insert fork catchpoint target routine. If fork events are enabled
2252 then return success, nothing more to do. */
2253
f6ac5f3d
PA
2254int
2255remote_target::insert_fork_catchpoint (int pid)
cbb8991c
DB
2256{
2257 struct remote_state *rs = get_remote_state ();
2258
2259 return !remote_fork_event_p (rs);
2260}
2261
2262/* Remove fork catchpoint target routine. Nothing to do, just
2263 return success. */
2264
f6ac5f3d
PA
2265int
2266remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2267{
2268 return 0;
2269}
2270
2271/* Insert vfork catchpoint target routine. If vfork events are enabled
2272 then return success, nothing more to do. */
2273
f6ac5f3d
PA
2274int
2275remote_target::insert_vfork_catchpoint (int pid)
cbb8991c
DB
2276{
2277 struct remote_state *rs = get_remote_state ();
2278
2279 return !remote_vfork_event_p (rs);
2280}
2281
2282/* Remove vfork catchpoint target routine. Nothing to do, just
2283 return success. */
2284
f6ac5f3d
PA
2285int
2286remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2287{
2288 return 0;
2289}
2290
d46addbb
DB
2291/* Insert exec catchpoint target routine. If exec events are
2292 enabled, just return success. */
2293
f6ac5f3d
PA
2294int
2295remote_target::insert_exec_catchpoint (int pid)
d46addbb
DB
2296{
2297 struct remote_state *rs = get_remote_state ();
2298
2299 return !remote_exec_event_p (rs);
2300}
2301
2302/* Remove exec catchpoint target routine. Nothing to do, just
2303 return success. */
2304
f6ac5f3d
PA
2305int
2306remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2307{
2308 return 0;
2309}
2310
c906108c
SS
2311\f
2312
79d7f229
PA
2313static ptid_t magic_null_ptid;
2314static ptid_t not_sent_ptid;
2315static ptid_t any_thread_ptid;
2316
0b16c5cf
PA
2317/* Find out if the stub attached to PID (and hence GDB should offer to
2318 detach instead of killing it when bailing out). */
2319
6b8edb51
PA
2320int
2321remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2322{
2323 struct remote_state *rs = get_remote_state ();
bba74b36 2324 size_t size = get_remote_packet_size ();
0b16c5cf 2325
4082afcc 2326 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2327 return 0;
2328
2329 if (remote_multi_process_p (rs))
bba74b36 2330 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 2331 else
bba74b36 2332 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
2333
2334 putpkt (rs->buf);
2335 getpkt (&rs->buf, &rs->buf_size, 0);
2336
2337 switch (packet_ok (rs->buf,
1554e9be 2338 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
2339 {
2340 case PACKET_OK:
2341 if (strcmp (rs->buf, "1") == 0)
2342 return 1;
2343 break;
2344 case PACKET_ERROR:
2345 warning (_("Remote failure reply: %s"), rs->buf);
2346 break;
2347 case PACKET_UNKNOWN:
2348 break;
2349 }
2350
2351 return 0;
2352}
2353
49c62f2e
PA
2354/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2355 has been invented by GDB, instead of reported by the target. Since
2356 we can be connected to a remote system before before knowing about
2357 any inferior, mark the target with execution when we find the first
2358 inferior. If ATTACHED is 1, then we had just attached to this
2359 inferior. If it is 0, then we just created this inferior. If it
2360 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2361 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2362 attempt to open this inferior's executable as the main executable
2363 if no main executable is open already. */
1941c569 2364
6b8edb51
PA
2365inferior *
2366remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2367 int try_open_exec)
1941c569 2368{
1941c569
PA
2369 struct inferior *inf;
2370
0b16c5cf
PA
2371 /* Check whether this process we're learning about is to be
2372 considered attached, or if is to be considered to have been
2373 spawned by the stub. */
2374 if (attached == -1)
2375 attached = remote_query_attached (pid);
2376
f5656ead 2377 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2378 {
2379 /* If the target shares code across all inferiors, then every
2380 attach adds a new inferior. */
2381 inf = add_inferior (pid);
2382
2383 /* ... and every inferior is bound to the same program space.
2384 However, each inferior may still have its own address
2385 space. */
2386 inf->aspace = maybe_new_address_space ();
2387 inf->pspace = current_program_space;
2388 }
2389 else
2390 {
2391 /* In the traditional debugging scenario, there's a 1-1 match
2392 between program/address spaces. We simply bind the inferior
2393 to the program space's address space. */
2394 inf = current_inferior ();
2395 inferior_appeared (inf, pid);
2396 }
1941c569 2397
0b16c5cf 2398 inf->attach_flag = attached;
49c62f2e 2399 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2400
1b6e6f5c
GB
2401 /* If no main executable is currently open then attempt to
2402 open the file that was executed to create this inferior. */
835205d0 2403 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2404 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2405
1941c569
PA
2406 return inf;
2407}
2408
7aabaf9d 2409static remote_thread_info *get_remote_thread_info (thread_info *thread);
00431a78 2410static remote_thread_info *get_remote_thread_info (ptid_t ptid);
85ad3aaf 2411
1941c569
PA
2412/* Add thread PTID to GDB's thread list. Tag it as executing/running
2413 according to RUNNING. */
2414
00431a78 2415thread_info *
6b8edb51 2416remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
c906108c 2417{
b7ea362b 2418 struct remote_state *rs = get_remote_state ();
85ad3aaf 2419 struct thread_info *thread;
b7ea362b
PA
2420
2421 /* GDB historically didn't pull threads in the initial connection
2422 setup. If the remote target doesn't even have a concept of
2423 threads (e.g., a bare-metal target), even if internally we
2424 consider that a single-threaded target, mentioning a new thread
2425 might be confusing to the user. Be silent then, preserving the
2426 age old behavior. */
2427 if (rs->starting_up)
85ad3aaf 2428 thread = add_thread_silent (ptid);
b7ea362b 2429 else
85ad3aaf 2430 thread = add_thread (ptid);
1941c569 2431
7aabaf9d 2432 get_remote_thread_info (thread)->vcont_resumed = executing;
0d5b594f 2433 set_executing (ptid, executing);
1941c569 2434 set_running (ptid, running);
00431a78
PA
2435
2436 return thread;
1941c569
PA
2437}
2438
2439/* Come here when we learn about a thread id from the remote target.
2440 It may be the first time we hear about such thread, so take the
2441 opportunity to add it to GDB's thread list. In case this is the
2442 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2443 GDB's inferior list as well. EXECUTING indicates whether the
2444 thread is (internally) executing or stopped. */
1941c569 2445
6b8edb51
PA
2446void
2447remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 2448{
0d5b594f
PA
2449 /* In non-stop mode, we assume new found threads are (externally)
2450 running until proven otherwise with a stop reply. In all-stop,
2451 we can only get here if all threads are stopped. */
2452 int running = target_is_non_stop_p () ? 1 : 0;
2453
c906108c
SS
2454 /* If this is a new thread, add it to GDB's thread list.
2455 If we leave it up to WFI to do this, bad things will happen. */
82f73884 2456
00431a78
PA
2457 thread_info *tp = find_thread_ptid (currthread);
2458 if (tp != NULL && tp->state == THREAD_EXITED)
82f73884
PA
2459 {
2460 /* We're seeing an event on a thread id we knew had exited.
2461 This has to be a new thread reusing the old id. Add it. */
0d5b594f 2462 remote_add_thread (currthread, running, executing);
82f73884
PA
2463 return;
2464 }
2465
79d7f229 2466 if (!in_thread_list (currthread))
c0a2216e 2467 {
1941c569 2468 struct inferior *inf = NULL;
e99b03dc 2469 int pid = currthread.pid ();
1941c569 2470
0e998d96 2471 if (inferior_ptid.is_pid ()
e99b03dc 2472 && pid == inferior_ptid.pid ())
c0a2216e
PA
2473 {
2474 /* inferior_ptid has no thread member yet. This can happen
2475 with the vAttach -> remote_wait,"TAAthread:" path if the
2476 stub doesn't support qC. This is the first stop reported
2477 after an attach, so this is the main thread. Update the
2478 ptid in the thread list. */
f2907e49 2479 if (in_thread_list (ptid_t (pid)))
bad34192
PA
2480 thread_change_ptid (inferior_ptid, currthread);
2481 else
2482 {
0d5b594f 2483 remote_add_thread (currthread, running, executing);
bad34192
PA
2484 inferior_ptid = currthread;
2485 }
dc146f7c 2486 return;
c0a2216e 2487 }
82f73884 2488
d7e15655 2489 if (magic_null_ptid == inferior_ptid)
c0a2216e
PA
2490 {
2491 /* inferior_ptid is not set yet. This can happen with the
2492 vRun -> remote_wait,"TAAthread:" path if the stub
2493 doesn't support qC. This is the first stop reported
2494 after an attach, so this is the main thread. Update the
2495 ptid in the thread list. */
dc146f7c 2496 thread_change_ptid (inferior_ptid, currthread);
82f73884 2497 return;
c0a2216e 2498 }
82f73884 2499
29c87f7f
PA
2500 /* When connecting to a target remote, or to a target
2501 extended-remote which already was debugging an inferior, we
2502 may not know about it yet. Add it before adding its child
2503 thread, so notifications are emitted in a sensible order. */
e99b03dc 2504 if (find_inferior_pid (currthread.pid ()) == NULL)
49c62f2e
PA
2505 {
2506 struct remote_state *rs = get_remote_state ();
2507 int fake_pid_p = !remote_multi_process_p (rs);
2508
2509 inf = remote_add_inferior (fake_pid_p,
e99b03dc 2510 currthread.pid (), -1, 1);
49c62f2e 2511 }
29c87f7f 2512
82f73884 2513 /* This is really a new thread. Add it. */
00431a78
PA
2514 thread_info *new_thr
2515 = remote_add_thread (currthread, running, executing);
1941c569
PA
2516
2517 /* If we found a new inferior, let the common code do whatever
2518 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2519 breakpoints), unless we're just setting up an all-stop
2520 connection. */
1941c569 2521 if (inf != NULL)
b7ea362b
PA
2522 {
2523 struct remote_state *rs = get_remote_state ();
2524
6efcd9a8 2525 if (!rs->starting_up)
00431a78 2526 notice_new_inferior (new_thr, executing, 0);
b7ea362b 2527 }
c0a2216e 2528 }
c906108c
SS
2529}
2530
85ad3aaf 2531/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2532
7aabaf9d
SM
2533static remote_thread_info *
2534get_remote_thread_info (thread_info *thread)
dc146f7c 2535{
85ad3aaf 2536 gdb_assert (thread != NULL);
dc146f7c 2537
85ad3aaf 2538 if (thread->priv == NULL)
7aabaf9d 2539 thread->priv.reset (new remote_thread_info);
dc146f7c 2540
7aabaf9d 2541 return static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2542}
2543
7aabaf9d
SM
2544static remote_thread_info *
2545get_remote_thread_info (ptid_t ptid)
85ad3aaf 2546{
00431a78
PA
2547 thread_info *thr = find_thread_ptid (ptid);
2548 return get_remote_thread_info (thr);
dc146f7c
VP
2549}
2550
74531fed
PA
2551/* Call this function as a result of
2552 1) A halt indication (T packet) containing a thread id
2553 2) A direct query of currthread
0df8b418 2554 3) Successful execution of set thread */
74531fed
PA
2555
2556static void
47f8a51d 2557record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2558{
47f8a51d 2559 rs->general_thread = currthread;
74531fed
PA
2560}
2561
89be2091
DJ
2562/* If 'QPassSignals' is supported, tell the remote stub what signals
2563 it can simply pass through to the inferior without reporting. */
2564
f6ac5f3d
PA
2565void
2566remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
89be2091 2567{
4082afcc 2568 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2569 {
2570 char *pass_packet, *p;
89be2091 2571 int count = 0, i;
747dc59d 2572 struct remote_state *rs = get_remote_state ();
89be2091
DJ
2573
2574 gdb_assert (numsigs < 256);
2575 for (i = 0; i < numsigs; i++)
2576 {
2455069d 2577 if (pass_signals[i])
89be2091
DJ
2578 count++;
2579 }
224c3ddb 2580 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2581 strcpy (pass_packet, "QPassSignals:");
2582 p = pass_packet + strlen (pass_packet);
2583 for (i = 0; i < numsigs; i++)
2584 {
2455069d 2585 if (pass_signals[i])
89be2091
DJ
2586 {
2587 if (i >= 16)
2588 *p++ = tohex (i >> 4);
2589 *p++ = tohex (i & 15);
2590 if (count)
2591 *p++ = ';';
2592 else
2593 break;
2594 count--;
2595 }
2596 }
2597 *p = 0;
747dc59d 2598 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2599 {
89be2091
DJ
2600 putpkt (pass_packet);
2601 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2602 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2603 if (rs->last_pass_packet)
2604 xfree (rs->last_pass_packet);
2605 rs->last_pass_packet = pass_packet;
89be2091
DJ
2606 }
2607 else
2608 xfree (pass_packet);
2609 }
2610}
2611
82075af2
JS
2612/* If 'QCatchSyscalls' is supported, tell the remote stub
2613 to report syscalls to GDB. */
2614
f6ac5f3d
PA
2615int
2616remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2617 gdb::array_view<const int> syscall_counts)
82075af2 2618{
b80406ac 2619 const char *catch_packet;
82075af2
JS
2620 enum packet_result result;
2621 int n_sysno = 0;
2622
2623 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2624 {
2625 /* Not supported. */
2626 return 1;
2627 }
2628
649a140c 2629 if (needed && any_count == 0)
82075af2 2630 {
649a140c
PA
2631 /* Count how many syscalls are to be caught. */
2632 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2633 {
649a140c 2634 if (syscall_counts[i] != 0)
82075af2
JS
2635 n_sysno++;
2636 }
2637 }
2638
2639 if (remote_debug)
2640 {
2641 fprintf_unfiltered (gdb_stdlog,
2642 "remote_set_syscall_catchpoint "
2643 "pid %d needed %d any_count %d n_sysno %d\n",
2644 pid, needed, any_count, n_sysno);
2645 }
2646
1b81856f 2647 std::string built_packet;
82075af2
JS
2648 if (needed)
2649 {
2650 /* Prepare a packet with the sysno list, assuming max 8+1
2651 characters for a sysno. If the resulting packet size is too
2652 big, fallback on the non-selective packet. */
2653 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2654 built_packet.reserve (maxpktsz);
2655 built_packet = "QCatchSyscalls:1";
649a140c 2656 if (any_count == 0)
82075af2 2657 {
649a140c
PA
2658 /* Add in each syscall to be caught. */
2659 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2660 {
649a140c
PA
2661 if (syscall_counts[i] != 0)
2662 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2663 }
2664 }
1b81856f 2665 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2666 {
2667 /* catch_packet too big. Fallback to less efficient
2668 non selective mode, with GDB doing the filtering. */
b80406ac 2669 catch_packet = "QCatchSyscalls:1";
82075af2 2670 }
b80406ac 2671 else
1b81856f 2672 catch_packet = built_packet.c_str ();
82075af2
JS
2673 }
2674 else
b80406ac 2675 catch_packet = "QCatchSyscalls:0";
82075af2 2676
b80406ac 2677 struct remote_state *rs = get_remote_state ();
82075af2 2678
b80406ac
TT
2679 putpkt (catch_packet);
2680 getpkt (&rs->buf, &rs->buf_size, 0);
2681 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2682 if (result == PACKET_OK)
2683 return 0;
2684 else
2685 return -1;
82075af2
JS
2686}
2687
9b224c5e
PA
2688/* If 'QProgramSignals' is supported, tell the remote stub what
2689 signals it should pass through to the inferior when detaching. */
2690
f6ac5f3d
PA
2691void
2692remote_target::program_signals (int numsigs, unsigned char *signals)
9b224c5e 2693{
4082afcc 2694 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2695 {
2696 char *packet, *p;
2697 int count = 0, i;
5e4a05c4 2698 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2699
2700 gdb_assert (numsigs < 256);
2701 for (i = 0; i < numsigs; i++)
2702 {
2703 if (signals[i])
2704 count++;
2705 }
224c3ddb 2706 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2707 strcpy (packet, "QProgramSignals:");
2708 p = packet + strlen (packet);
2709 for (i = 0; i < numsigs; i++)
2710 {
2711 if (signal_pass_state (i))
2712 {
2713 if (i >= 16)
2714 *p++ = tohex (i >> 4);
2715 *p++ = tohex (i & 15);
2716 if (count)
2717 *p++ = ';';
2718 else
2719 break;
2720 count--;
2721 }
2722 }
2723 *p = 0;
5e4a05c4
TT
2724 if (!rs->last_program_signals_packet
2725 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2726 {
9b224c5e
PA
2727 putpkt (packet);
2728 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2729 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2730 xfree (rs->last_program_signals_packet);
2731 rs->last_program_signals_packet = packet;
9b224c5e
PA
2732 }
2733 else
2734 xfree (packet);
2735 }
2736}
2737
79d7f229
PA
2738/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2739 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2740 thread. If GEN is set, set the general thread, if not, then set
2741 the step/continue thread. */
6b8edb51
PA
2742void
2743remote_target::set_thread (ptid_t ptid, int gen)
c906108c 2744{
d01949b6 2745 struct remote_state *rs = get_remote_state ();
47f8a51d 2746 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2747 char *buf = rs->buf;
79d7f229 2748 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2749
d7e15655 2750 if (state == ptid)
c906108c
SS
2751 return;
2752
79d7f229
PA
2753 *buf++ = 'H';
2754 *buf++ = gen ? 'g' : 'c';
d7e15655 2755 if (ptid == magic_null_ptid)
79d7f229 2756 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2757 else if (ptid == any_thread_ptid)
79d7f229 2758 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2759 else if (ptid == minus_one_ptid)
79d7f229
PA
2760 xsnprintf (buf, endbuf - buf, "-1");
2761 else
82f73884 2762 write_ptid (buf, endbuf, ptid);
79d7f229 2763 putpkt (rs->buf);
6d820c5c 2764 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2765 if (gen)
47f8a51d 2766 rs->general_thread = ptid;
c906108c 2767 else
47f8a51d 2768 rs->continue_thread = ptid;
c906108c 2769}
79d7f229 2770
6b8edb51
PA
2771void
2772remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
2773{
2774 set_thread (ptid, 1);
2775}
2776
6b8edb51
PA
2777void
2778remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
2779{
2780 set_thread (ptid, 0);
2781}
2782
3c9c4b83
PA
2783/* Change the remote current process. Which thread within the process
2784 ends up selected isn't important, as long as it is the same process
2785 as what INFERIOR_PTID points to.
2786
2787 This comes from that fact that there is no explicit notion of
2788 "selected process" in the protocol. The selected process for
2789 general operations is the process the selected general thread
2790 belongs to. */
2791
6b8edb51
PA
2792void
2793remote_target::set_general_process ()
3c9c4b83
PA
2794{
2795 struct remote_state *rs = get_remote_state ();
2796
2797 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2798 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2799 return;
2800
2801 /* We only need to change the remote current thread if it's pointing
2802 at some other process. */
e99b03dc 2803 if (rs->general_thread.pid () != inferior_ptid.pid ())
3c9c4b83
PA
2804 set_general_thread (inferior_ptid);
2805}
2806
c906108c 2807\f
7d1a114c
PA
2808/* Return nonzero if this is the main thread that we made up ourselves
2809 to model non-threaded targets as single-threaded. */
c906108c
SS
2810
2811static int
f6ac5f3d 2812remote_thread_always_alive (ptid_t ptid)
c906108c 2813{
d7e15655 2814 if (ptid == magic_null_ptid)
c0a2216e
PA
2815 /* The main thread is always alive. */
2816 return 1;
2817
e38504b3 2818 if (ptid.pid () != 0 && ptid.lwp () == 0)
c0a2216e
PA
2819 /* The main thread is always alive. This can happen after a
2820 vAttach, if the remote side doesn't support
2821 multi-threading. */
2822 return 1;
2823
7d1a114c
PA
2824 return 0;
2825}
2826
2827/* Return nonzero if the thread PTID is still alive on the remote
2828 system. */
2829
57810aa7 2830bool
f6ac5f3d 2831remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
2832{
2833 struct remote_state *rs = get_remote_state ();
2834 char *p, *endp;
2835
2836 /* Check if this is a thread that we made up ourselves to model
2837 non-threaded targets as single-threaded. */
f6ac5f3d 2838 if (remote_thread_always_alive (ptid))
7d1a114c
PA
2839 return 1;
2840
82f73884
PA
2841 p = rs->buf;
2842 endp = rs->buf + get_remote_packet_size ();
2843
2844 *p++ = 'T';
2845 write_ptid (p, endp, ptid);
2846
2e9f7625 2847 putpkt (rs->buf);
6d820c5c 2848 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2849 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2850}
2851
79efa585
SM
2852/* Return a pointer to a thread name if we know it and NULL otherwise.
2853 The thread_info object owns the memory for the name. */
2854
f6ac5f3d
PA
2855const char *
2856remote_target::thread_name (struct thread_info *info)
79efa585
SM
2857{
2858 if (info->priv != NULL)
a9334058
SM
2859 {
2860 const std::string &name = get_remote_thread_info (info)->name;
2861 return !name.empty () ? name.c_str () : NULL;
2862 }
79efa585
SM
2863
2864 return NULL;
2865}
2866
c906108c
SS
2867/* About these extended threadlist and threadinfo packets. They are
2868 variable length packets but, the fields within them are often fixed
2869 length. They are redundent enough to send over UDP as is the
2870 remote protocol in general. There is a matching unit test module
2871 in libstub. */
2872
23860348 2873/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2874 libstub protocol encoding, and remote.c. It is not particularly
23860348 2875 changable. */
cce74817
JM
2876
2877/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2878 Plan to fix this. */
cce74817 2879
23860348 2880typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2881
9d1f7ab2 2882/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2883 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2884
2885struct gdb_ext_thread_info
c5aa993b 2886 {
23860348 2887 threadref threadid; /* External form of thread reference. */
2bc416ba 2888 int active; /* Has state interesting to GDB?
23860348 2889 regs, stack. */
2bc416ba 2890 char display[256]; /* Brief state display, name,
cedea757 2891 blocked/suspended. */
23860348 2892 char shortname[32]; /* To be used to name threads. */
2bc416ba 2893 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2894 whatever. */
c5aa993b 2895 };
cce74817
JM
2896
2897/* The volume of remote transfers can be limited by submitting
2898 a mask containing bits specifying the desired information.
2899 Use a union of these values as the 'selection' parameter to
0df8b418 2900 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2901
2902#define TAG_THREADID 1
2903#define TAG_EXISTS 2
2904#define TAG_DISPLAY 4
2905#define TAG_THREADNAME 8
c5aa993b 2906#define TAG_MOREDISPLAY 16
cce74817 2907
23860348 2908#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2909
a14ed312 2910static char *unpack_nibble (char *buf, int *val);
cce74817 2911
a14ed312 2912static char *unpack_byte (char *buf, int *value);
cce74817 2913
a14ed312 2914static char *pack_int (char *buf, int value);
cce74817 2915
a14ed312 2916static char *unpack_int (char *buf, int *value);
cce74817 2917
a14ed312 2918static char *unpack_string (char *src, char *dest, int length);
cce74817 2919
23860348 2920static char *pack_threadid (char *pkt, threadref *id);
cce74817 2921
23860348 2922static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2923
23860348 2924void int_to_threadref (threadref *id, int value);
cce74817 2925
23860348 2926static int threadref_to_int (threadref *ref);
cce74817 2927
23860348 2928static void copy_threadref (threadref *dest, threadref *src);
cce74817 2929
23860348 2930static int threadmatch (threadref *dest, threadref *src);
cce74817 2931
2bc416ba 2932static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2933 threadref *id);
cce74817 2934
a14ed312
KB
2935static char *pack_threadlist_request (char *pkt, int startflag,
2936 int threadcount,
23860348 2937 threadref *nextthread);
cce74817 2938
23860348 2939static int remote_newthread_step (threadref *ref, void *context);
cce74817 2940
82f73884
PA
2941
2942/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2943 buffer we're allowed to write to. Returns
2944 BUF+CHARACTERS_WRITTEN. */
2945
6b8edb51
PA
2946char *
2947remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
2948{
2949 int pid, tid;
2950 struct remote_state *rs = get_remote_state ();
2951
2952 if (remote_multi_process_p (rs))
2953 {
e99b03dc 2954 pid = ptid.pid ();
82f73884
PA
2955 if (pid < 0)
2956 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2957 else
2958 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2959 }
e38504b3 2960 tid = ptid.lwp ();
82f73884
PA
2961 if (tid < 0)
2962 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2963 else
2964 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2965
2966 return buf;
2967}
2968
256642e8
PA
2969/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2970 last parsed char. Returns null_ptid if no thread id is found, and
2971 throws an error if the thread id has an invalid format. */
82f73884
PA
2972
2973static ptid_t
256642e8 2974read_ptid (const char *buf, const char **obuf)
82f73884 2975{
256642e8
PA
2976 const char *p = buf;
2977 const char *pp;
82f73884 2978 ULONGEST pid = 0, tid = 0;
82f73884
PA
2979
2980 if (*p == 'p')
2981 {
2982 /* Multi-process ptid. */
2983 pp = unpack_varlen_hex (p + 1, &pid);
2984 if (*pp != '.')
b37520b6 2985 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2986
2987 p = pp;
2988 pp = unpack_varlen_hex (p + 1, &tid);
2989 if (obuf)
2990 *obuf = pp;
fd79271b 2991 return ptid_t (pid, tid, 0);
82f73884
PA
2992 }
2993
2994 /* No multi-process. Just a tid. */
2995 pp = unpack_varlen_hex (p, &tid);
2996
c9f35b34
KB
2997 /* Return null_ptid when no thread id is found. */
2998 if (p == pp)
2999 {
3000 if (obuf)
3001 *obuf = pp;
3002 return null_ptid;
3003 }
3004
82f73884 3005 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
3006 what's in inferior_ptid, unless it's null at this point. If so,
3007 then since there's no way to know the pid of the reported
3008 threads, use the magic number. */
d7e15655 3009 if (inferior_ptid == null_ptid)
e99b03dc 3010 pid = magic_null_ptid.pid ();
ca19bf23 3011 else
e99b03dc 3012 pid = inferior_ptid.pid ();
82f73884
PA
3013
3014 if (obuf)
3015 *obuf = pp;
fd79271b 3016 return ptid_t (pid, tid, 0);
82f73884
PA
3017}
3018
c906108c 3019static int
fba45db2 3020stubhex (int ch)
c906108c
SS
3021{
3022 if (ch >= 'a' && ch <= 'f')
3023 return ch - 'a' + 10;
3024 if (ch >= '0' && ch <= '9')
3025 return ch - '0';
3026 if (ch >= 'A' && ch <= 'F')
3027 return ch - 'A' + 10;
3028 return -1;
3029}
3030
3031static int
fba45db2 3032stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
3033{
3034 int nibble;
3035 int retval = 0;
3036
3037 while (fieldlength)
3038 {
3039 nibble = stubhex (*buff++);
3040 retval |= nibble;
3041 fieldlength--;
3042 if (fieldlength)
3043 retval = retval << 4;
3044 }
3045 return retval;
3046}
3047
c906108c 3048static char *
fba45db2 3049unpack_nibble (char *buf, int *val)
c906108c 3050{
b7589f7d 3051 *val = fromhex (*buf++);
c906108c
SS
3052 return buf;
3053}
3054
c906108c 3055static char *
fba45db2 3056unpack_byte (char *buf, int *value)
c906108c
SS
3057{
3058 *value = stub_unpack_int (buf, 2);
3059 return buf + 2;
3060}
3061
3062static char *
fba45db2 3063pack_int (char *buf, int value)
c906108c
SS
3064{
3065 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3066 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3067 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3068 buf = pack_hex_byte (buf, (value & 0xff));
3069 return buf;
3070}
3071
3072static char *
fba45db2 3073unpack_int (char *buf, int *value)
c906108c
SS
3074{
3075 *value = stub_unpack_int (buf, 8);
3076 return buf + 8;
3077}
3078
23860348 3079#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3080static char *pack_string (char *pkt, char *string);
c906108c
SS
3081
3082static char *
fba45db2 3083pack_string (char *pkt, char *string)
c906108c
SS
3084{
3085 char ch;
3086 int len;
3087
3088 len = strlen (string);
3089 if (len > 200)
23860348 3090 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3091 pkt = pack_hex_byte (pkt, len);
3092 while (len-- > 0)
3093 {
3094 ch = *string++;
3095 if ((ch == '\0') || (ch == '#'))
23860348 3096 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3097 *pkt++ = ch;
3098 }
3099 return pkt;
3100}
3101#endif /* 0 (unused) */
3102
3103static char *
fba45db2 3104unpack_string (char *src, char *dest, int length)
c906108c
SS
3105{
3106 while (length--)
3107 *dest++ = *src++;
3108 *dest = '\0';
3109 return src;
3110}
3111
3112static char *
fba45db2 3113pack_threadid (char *pkt, threadref *id)
c906108c
SS
3114{
3115 char *limit;
3116 unsigned char *altid;
3117
3118 altid = (unsigned char *) id;
3119 limit = pkt + BUF_THREAD_ID_SIZE;
3120 while (pkt < limit)
3121 pkt = pack_hex_byte (pkt, *altid++);
3122 return pkt;
3123}
3124
3125
3126static char *
fba45db2 3127unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
3128{
3129 char *altref;
3130 char *limit = inbuf + BUF_THREAD_ID_SIZE;
3131 int x, y;
3132
3133 altref = (char *) id;
3134
3135 while (inbuf < limit)
3136 {
3137 x = stubhex (*inbuf++);
3138 y = stubhex (*inbuf++);
3139 *altref++ = (x << 4) | y;
3140 }
3141 return inbuf;
3142}
3143
3144/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3145 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3146 to use 64bit thread references internally. This is an adapter
3147 function. */
3148
3149void
fba45db2 3150int_to_threadref (threadref *id, int value)
c906108c
SS
3151{
3152 unsigned char *scan;
3153
3154 scan = (unsigned char *) id;
3155 {
3156 int i = 4;
3157 while (i--)
3158 *scan++ = 0;
3159 }
3160 *scan++ = (value >> 24) & 0xff;
3161 *scan++ = (value >> 16) & 0xff;
3162 *scan++ = (value >> 8) & 0xff;
3163 *scan++ = (value & 0xff);
3164}
3165
3166static int
fba45db2 3167threadref_to_int (threadref *ref)
c906108c
SS
3168{
3169 int i, value = 0;
3170 unsigned char *scan;
3171
cfd77fa1 3172 scan = *ref;
c906108c
SS
3173 scan += 4;
3174 i = 4;
3175 while (i-- > 0)
3176 value = (value << 8) | ((*scan++) & 0xff);
3177 return value;
3178}
3179
3180static void
fba45db2 3181copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3182{
3183 int i;
3184 unsigned char *csrc, *cdest;
3185
3186 csrc = (unsigned char *) src;
3187 cdest = (unsigned char *) dest;
3188 i = 8;
3189 while (i--)
3190 *cdest++ = *csrc++;
3191}
3192
3193static int
fba45db2 3194threadmatch (threadref *dest, threadref *src)
c906108c 3195{
23860348 3196 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3197#if 0
3198 unsigned char *srcp, *destp;
3199 int i, result;
3200 srcp = (char *) src;
3201 destp = (char *) dest;
3202
3203 result = 1;
3204 while (i-- > 0)
3205 result &= (*srcp++ == *destp++) ? 1 : 0;
3206 return result;
3207#endif
3208 return 1;
3209}
3210
3211/*
c5aa993b
JM
3212 threadid:1, # always request threadid
3213 context_exists:2,
3214 display:4,
3215 unique_name:8,
3216 more_display:16
3217 */
c906108c
SS
3218
3219/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3220
3221static char *
fba45db2 3222pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3223{
23860348
MS
3224 *pkt++ = 'q'; /* Info Query */
3225 *pkt++ = 'P'; /* process or thread info */
3226 pkt = pack_int (pkt, mode); /* mode */
c906108c 3227 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3228 *pkt = '\0'; /* terminate */
c906108c
SS
3229 return pkt;
3230}
3231
23860348 3232/* These values tag the fields in a thread info response packet. */
c906108c 3233/* Tagging the fields allows us to request specific fields and to
23860348 3234 add more fields as time goes by. */
c906108c 3235
23860348 3236#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3237#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3238 fetch registers and its stack? */
c5aa993b 3239#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3240#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3241#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3242 the process. */
c906108c 3243
6b8edb51
PA
3244int
3245remote_target::remote_unpack_thread_info_response (char *pkt,
3246 threadref *expectedref,
3247 gdb_ext_thread_info *info)
c906108c 3248{
d01949b6 3249 struct remote_state *rs = get_remote_state ();
c906108c 3250 int mask, length;
cfd77fa1 3251 int tag;
c906108c 3252 threadref ref;
6d820c5c 3253 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
3254 int retval = 1;
3255
23860348 3256 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3257 info->active = 0;
3258 info->display[0] = '\0';
3259 info->shortname[0] = '\0';
3260 info->more_display[0] = '\0';
3261
23860348
MS
3262 /* Assume the characters indicating the packet type have been
3263 stripped. */
c906108c
SS
3264 pkt = unpack_int (pkt, &mask); /* arg mask */
3265 pkt = unpack_threadid (pkt, &ref);
3266
3267 if (mask == 0)
8a3fe4f8 3268 warning (_("Incomplete response to threadinfo request."));
c906108c 3269 if (!threadmatch (&ref, expectedref))
23860348 3270 { /* This is an answer to a different request. */
8a3fe4f8 3271 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3272 return 0;
3273 }
3274 copy_threadref (&info->threadid, &ref);
3275
23860348 3276 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 3277
23860348
MS
3278 /* Packets are terminated with nulls. */
3279 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3280 {
3281 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3282 pkt = unpack_byte (pkt, &length); /* length */
3283 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3284 {
8a3fe4f8 3285 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3286 retval = 0;
3287 break;
3288 }
3289 if (tag == TAG_THREADID)
3290 {
3291 if (length != 16)
3292 {
8a3fe4f8 3293 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3294 retval = 0;
3295 break;
3296 }
3297 pkt = unpack_threadid (pkt, &ref);
3298 mask = mask & ~TAG_THREADID;
3299 continue;
3300 }
3301 if (tag == TAG_EXISTS)
3302 {
3303 info->active = stub_unpack_int (pkt, length);
3304 pkt += length;
3305 mask = mask & ~(TAG_EXISTS);
3306 if (length > 8)
3307 {
8a3fe4f8 3308 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3309 retval = 0;
3310 break;
3311 }
3312 continue;
3313 }
3314 if (tag == TAG_THREADNAME)
3315 {
3316 pkt = unpack_string (pkt, &info->shortname[0], length);
3317 mask = mask & ~TAG_THREADNAME;
3318 continue;
3319 }
3320 if (tag == TAG_DISPLAY)
3321 {
3322 pkt = unpack_string (pkt, &info->display[0], length);
3323 mask = mask & ~TAG_DISPLAY;
3324 continue;
3325 }
3326 if (tag == TAG_MOREDISPLAY)
3327 {
3328 pkt = unpack_string (pkt, &info->more_display[0], length);
3329 mask = mask & ~TAG_MOREDISPLAY;
3330 continue;
3331 }
8a3fe4f8 3332 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3333 break; /* Not a tag we know about. */
c906108c
SS
3334 }
3335 return retval;
3336}
3337
6b8edb51
PA
3338int
3339remote_target::remote_get_threadinfo (threadref *threadid,
3340 int fieldset,
3341 gdb_ext_thread_info *info)
c906108c 3342{
d01949b6 3343 struct remote_state *rs = get_remote_state ();
c906108c 3344 int result;
c906108c 3345
2e9f7625
DJ
3346 pack_threadinfo_request (rs->buf, fieldset, threadid);
3347 putpkt (rs->buf);
6d820c5c 3348 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
3349
3350 if (rs->buf[0] == '\0')
3351 return 0;
3352
2e9f7625 3353 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 3354 threadid, info);
c906108c
SS
3355 return result;
3356}
3357
c906108c
SS
3358/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3359
3360static char *
fba45db2
KB
3361pack_threadlist_request (char *pkt, int startflag, int threadcount,
3362 threadref *nextthread)
c906108c
SS
3363{
3364 *pkt++ = 'q'; /* info query packet */
3365 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3366 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3367 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3368 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3369 *pkt = '\0';
3370 return pkt;
3371}
3372
3373/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3374
6b8edb51
PA
3375int
3376remote_target::parse_threadlist_response (char *pkt, int result_limit,
3377 threadref *original_echo,
3378 threadref *resultlist,
3379 int *doneflag)
c906108c 3380{
d01949b6 3381 struct remote_state *rs = get_remote_state ();
c906108c
SS
3382 char *limit;
3383 int count, resultcount, done;
3384
3385 resultcount = 0;
3386 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 3387 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 3388 /* done parse past here */
c906108c
SS
3389 pkt = unpack_byte (pkt, &count); /* count field */
3390 pkt = unpack_nibble (pkt, &done);
3391 /* The first threadid is the argument threadid. */
3392 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3393 while ((count-- > 0) && (pkt < limit))
3394 {
3395 pkt = unpack_threadid (pkt, resultlist++);
3396 if (resultcount++ >= result_limit)
3397 break;
3398 }
3399 if (doneflag)
3400 *doneflag = done;
3401 return resultcount;
3402}
3403
6dc54d91
PA
3404/* Fetch the next batch of threads from the remote. Returns -1 if the
3405 qL packet is not supported, 0 on error and 1 on success. */
3406
6b8edb51
PA
3407int
3408remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3409 int result_limit, int *done, int *result_count,
3410 threadref *threadlist)
c906108c 3411{
d01949b6 3412 struct remote_state *rs = get_remote_state ();
c906108c
SS
3413 int result = 1;
3414
23860348 3415 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
3416 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3417 >= get_remote_packet_size ())
ea9c271d 3418 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3419
6d820c5c
DJ
3420 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3421 putpkt (rs->buf);
3422 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 3423 if (*rs->buf == '\0')
6dc54d91
PA
3424 {
3425 /* Packet not supported. */
3426 return -1;
3427 }
3428
3429 *result_count =
3430 parse_threadlist_response (rs->buf + 2, result_limit,
3431 &rs->echo_nextthread, threadlist, done);
c906108c 3432
0d031856 3433 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3434 {
23860348
MS
3435 /* FIXME: This is a good reason to drop the packet. */
3436 /* Possably, there is a duplicate response. */
c906108c
SS
3437 /* Possabilities :
3438 retransmit immediatly - race conditions
3439 retransmit after timeout - yes
3440 exit
3441 wait for packet, then exit
3442 */
8a3fe4f8 3443 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3444 return 0; /* I choose simply exiting. */
c906108c
SS
3445 }
3446 if (*result_count <= 0)
3447 {
3448 if (*done != 1)
3449 {
8a3fe4f8 3450 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3451 result = 0;
3452 }
3453 return result; /* break; */
3454 }
3455 if (*result_count > result_limit)
3456 {
3457 *result_count = 0;
8a3fe4f8 3458 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3459 return 0;
3460 }
3461 return result;
3462}
3463
6dc54d91
PA
3464/* Fetch the list of remote threads, with the qL packet, and call
3465 STEPFUNCTION for each thread found. Stops iterating and returns 1
3466 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3467 STEPFUNCTION returns false. If the packet is not supported,
3468 returns -1. */
c906108c 3469
6b8edb51
PA
3470int
3471remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3472 void *context, int looplimit)
c906108c 3473{
0d031856 3474 struct remote_state *rs = get_remote_state ();
c906108c
SS
3475 int done, i, result_count;
3476 int startflag = 1;
3477 int result = 1;
3478 int loopcount = 0;
c906108c
SS
3479
3480 done = 0;
3481 while (!done)
3482 {
3483 if (loopcount++ > looplimit)
3484 {
3485 result = 0;
8a3fe4f8 3486 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3487 break;
3488 }
6dc54d91
PA
3489 result = remote_get_threadlist (startflag, &rs->nextthread,
3490 MAXTHREADLISTRESULTS,
3491 &done, &result_count,
3492 rs->resultthreadlist);
3493 if (result <= 0)
3494 break;
23860348 3495 /* Clear for later iterations. */
c906108c
SS
3496 startflag = 0;
3497 /* Setup to resume next batch of thread references, set nextthread. */
3498 if (result_count >= 1)
0d031856
TT
3499 copy_threadref (&rs->nextthread,
3500 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3501 i = 0;
3502 while (result_count--)
6dc54d91
PA
3503 {
3504 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3505 {
3506 result = 0;
3507 break;
3508 }
3509 }
c906108c
SS
3510 }
3511 return result;
3512}
3513
6dc54d91
PA
3514/* A thread found on the remote target. */
3515
21fe1c75 3516struct thread_item
6dc54d91 3517{
21fe1c75
SM
3518 explicit thread_item (ptid_t ptid_)
3519 : ptid (ptid_)
3520 {}
3521
3522 thread_item (thread_item &&other) = default;
3523 thread_item &operator= (thread_item &&other) = default;
3524
3525 DISABLE_COPY_AND_ASSIGN (thread_item);
3526
6dc54d91
PA
3527 /* The thread's PTID. */
3528 ptid_t ptid;
3529
21fe1c75
SM
3530 /* The thread's extra info. */
3531 std::string extra;
6dc54d91 3532
21fe1c75
SM
3533 /* The thread's name. */
3534 std::string name;
79efa585 3535
6dc54d91 3536 /* The core the thread was running on. -1 if not known. */
21fe1c75 3537 int core = -1;
f6327dcb
KB
3538
3539 /* The thread handle associated with the thread. */
21fe1c75 3540 gdb::byte_vector thread_handle;
21fe1c75 3541};
6dc54d91
PA
3542
3543/* Context passed around to the various methods listing remote
3544 threads. As new threads are found, they're added to the ITEMS
3545 vector. */
3546
3547struct threads_listing_context
3548{
21fe1c75
SM
3549 /* Return true if this object contains an entry for a thread with ptid
3550 PTID. */
6dc54d91 3551
21fe1c75
SM
3552 bool contains_thread (ptid_t ptid) const
3553 {
3554 auto match_ptid = [&] (const thread_item &item)
3555 {
3556 return item.ptid == ptid;
3557 };
80134cf5 3558
21fe1c75
SM
3559 auto it = std::find_if (this->items.begin (),
3560 this->items.end (),
3561 match_ptid);
80134cf5 3562
21fe1c75
SM
3563 return it != this->items.end ();
3564 }
80134cf5 3565
21fe1c75 3566 /* Remove the thread with ptid PTID. */
80134cf5 3567
21fe1c75
SM
3568 void remove_thread (ptid_t ptid)
3569 {
3570 auto match_ptid = [&] (const thread_item &item)
3571 {
3572 return item.ptid == ptid;
3573 };
cbb8991c 3574
21fe1c75
SM
3575 auto it = std::remove_if (this->items.begin (),
3576 this->items.end (),
3577 match_ptid);
cbb8991c 3578
21fe1c75
SM
3579 if (it != this->items.end ())
3580 this->items.erase (it);
3581 }
3582
3583 /* The threads found on the remote target. */
3584 std::vector<thread_item> items;
3585};
cbb8991c 3586
c906108c 3587static int
6dc54d91 3588remote_newthread_step (threadref *ref, void *data)
c906108c 3589{
19ba03f4
SM
3590 struct threads_listing_context *context
3591 = (struct threads_listing_context *) data;
21fe1c75
SM
3592 int pid = inferior_ptid.pid ();
3593 int lwp = threadref_to_int (ref);
3594 ptid_t ptid (pid, lwp);
6dc54d91 3595
21fe1c75 3596 context->items.emplace_back (ptid);
6dc54d91 3597
c906108c
SS
3598 return 1; /* continue iterator */
3599}
3600
3601#define CRAZY_MAX_THREADS 1000
3602
6b8edb51
PA
3603ptid_t
3604remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3605{
d01949b6 3606 struct remote_state *rs = get_remote_state ();
c906108c
SS
3607
3608 putpkt ("qC");
6d820c5c 3609 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3610 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3611 {
256642e8 3612 const char *obuf;
c9f35b34
KB
3613 ptid_t result;
3614
3615 result = read_ptid (&rs->buf[2], &obuf);
3616 if (*obuf != '\0' && remote_debug)
3617 fprintf_unfiltered (gdb_stdlog,
3618 "warning: garbage in qC reply\n");
3619
3620 return result;
3621 }
c906108c
SS
3622 else
3623 return oldpid;
3624}
3625
6dc54d91 3626/* List remote threads using the deprecated qL packet. */
cce74817 3627
6b8edb51
PA
3628int
3629remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3630{
6dc54d91
PA
3631 if (remote_threadlist_iterator (remote_newthread_step, context,
3632 CRAZY_MAX_THREADS) >= 0)
3633 return 1;
3634
3635 return 0;
c906108c
SS
3636}
3637
dc146f7c
VP
3638#if defined(HAVE_LIBEXPAT)
3639
dc146f7c
VP
3640static void
3641start_thread (struct gdb_xml_parser *parser,
3642 const struct gdb_xml_element *element,
4d0fdd9b
SM
3643 void *user_data,
3644 std::vector<gdb_xml_value> &attributes)
dc146f7c 3645{
19ba03f4
SM
3646 struct threads_listing_context *data
3647 = (struct threads_listing_context *) user_data;
3d2c1d41 3648 struct gdb_xml_value *attr;
dc146f7c 3649
4d0fdd9b 3650 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3651 ptid_t ptid = read_ptid (id, NULL);
3652
3653 data->items.emplace_back (ptid);
3654 thread_item &item = data->items.back ();
dc146f7c 3655
3d2c1d41
PA
3656 attr = xml_find_attribute (attributes, "core");
3657 if (attr != NULL)
4d0fdd9b 3658 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3659
79efa585 3660 attr = xml_find_attribute (attributes, "name");
21fe1c75 3661 if (attr != NULL)
4d0fdd9b 3662 item.name = (const char *) attr->value.get ();
79efa585 3663
f6327dcb
KB
3664 attr = xml_find_attribute (attributes, "handle");
3665 if (attr != NULL)
4d0fdd9b 3666 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3667}
3668
3669static void
3670end_thread (struct gdb_xml_parser *parser,
3671 const struct gdb_xml_element *element,
3672 void *user_data, const char *body_text)
3673{
19ba03f4
SM
3674 struct threads_listing_context *data
3675 = (struct threads_listing_context *) user_data;
dc146f7c 3676
21fe1c75
SM
3677 if (body_text != NULL && *body_text != '\0')
3678 data->items.back ().extra = body_text;
dc146f7c
VP
3679}
3680
3681const struct gdb_xml_attribute thread_attributes[] = {
3682 { "id", GDB_XML_AF_NONE, NULL, NULL },
3683 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3684 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3685 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3686 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3687};
3688
3689const struct gdb_xml_element thread_children[] = {
3690 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3691};
3692
3693const struct gdb_xml_element threads_children[] = {
3694 { "thread", thread_attributes, thread_children,
3695 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3696 start_thread, end_thread },
3697 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3698};
3699
3700const struct gdb_xml_element threads_elements[] = {
3701 { "threads", NULL, threads_children,
3702 GDB_XML_EF_NONE, NULL, NULL },
3703 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3704};
3705
3706#endif
3707
6dc54d91 3708/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3709
6b8edb51
PA
3710int
3711remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 3712{
dc146f7c 3713#if defined(HAVE_LIBEXPAT)
4082afcc 3714 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3715 {
9018be22 3716 gdb::optional<gdb::char_vector> xml
6b8edb51 3717 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3718
9018be22 3719 if (xml && (*xml)[0] != '\0')
dc146f7c 3720 {
6dc54d91 3721 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3722 threads_elements, xml->data (), context);
dc146f7c
VP
3723 }
3724
6dc54d91 3725 return 1;
dc146f7c
VP
3726 }
3727#endif
3728
6dc54d91
PA
3729 return 0;
3730}
3731
3732/* List remote threads using qfThreadInfo/qsThreadInfo. */
3733
6b8edb51
PA
3734int
3735remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
3736{
3737 struct remote_state *rs = get_remote_state ();
3738
b80fafe3 3739 if (rs->use_threadinfo_query)
9d1f7ab2 3740 {
256642e8 3741 const char *bufp;
6dc54d91 3742
9d1f7ab2 3743 putpkt ("qfThreadInfo");
6d820c5c 3744 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3745 bufp = rs->buf;
9d1f7ab2 3746 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3747 {
9d1f7ab2
MS
3748 while (*bufp++ == 'm') /* reply contains one or more TID */
3749 {
3750 do
3751 {
21fe1c75
SM
3752 ptid_t ptid = read_ptid (bufp, &bufp);
3753 context->items.emplace_back (ptid);
9d1f7ab2
MS
3754 }
3755 while (*bufp++ == ','); /* comma-separated list */
3756 putpkt ("qsThreadInfo");
6d820c5c 3757 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3758 bufp = rs->buf;
9d1f7ab2 3759 }
6dc54d91
PA
3760 return 1;
3761 }
3762 else
3763 {
3764 /* Packet not recognized. */
3765 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3766 }
3767 }
3768
6dc54d91
PA
3769 return 0;
3770}
3771
e8032dde 3772/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3773 targets. */
3774
f6ac5f3d
PA
3775void
3776remote_target::update_thread_list ()
6dc54d91 3777{
6dc54d91 3778 struct threads_listing_context context;
ab970af1 3779 int got_list = 0;
e8032dde 3780
6dc54d91
PA
3781 /* We have a few different mechanisms to fetch the thread list. Try
3782 them all, starting with the most preferred one first, falling
3783 back to older methods. */
6b8edb51
PA
3784 if (remote_get_threads_with_qxfer (&context)
3785 || remote_get_threads_with_qthreadinfo (&context)
3786 || remote_get_threads_with_ql (&context))
6dc54d91 3787 {
ab970af1
PA
3788 struct thread_info *tp, *tmp;
3789
3790 got_list = 1;
3791
21fe1c75 3792 if (context.items.empty ()
f6ac5f3d 3793 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
3794 {
3795 /* Some targets don't really support threads, but still
3796 reply an (empty) thread list in response to the thread
3797 listing packets, instead of replying "packet not
3798 supported". Exit early so we don't delete the main
3799 thread. */
7d1a114c
PA
3800 return;
3801 }
3802
ab970af1
PA
3803 /* CONTEXT now holds the current thread list on the remote
3804 target end. Delete GDB-side threads no longer found on the
3805 target. */
8a06aea7 3806 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3807 {
21fe1c75 3808 if (!context.contains_thread (tp->ptid))
ab970af1
PA
3809 {
3810 /* Not found. */
00431a78 3811 delete_thread (tp);
ab970af1 3812 }
cbb8991c
DB
3813 }
3814
3815 /* Remove any unreported fork child threads from CONTEXT so
3816 that we don't interfere with follow fork, which is where
3817 creation of such threads is handled. */
3818 remove_new_fork_children (&context);
74531fed 3819
ab970af1 3820 /* And now add threads we don't know about yet to our list. */
21fe1c75 3821 for (thread_item &item : context.items)
6dc54d91 3822 {
21fe1c75 3823 if (item.ptid != null_ptid)
6dc54d91 3824 {
6dc54d91 3825 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3826 executing until proven otherwise with a stop reply.
3827 In all-stop, we can only get here if all threads are
6dc54d91 3828 stopped. */
0d5b594f 3829 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3830
21fe1c75 3831 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 3832
b926417a 3833 tp = find_thread_ptid (item.ptid);
00431a78 3834 remote_thread_info *info = get_remote_thread_info (tp);
21fe1c75 3835 info->core = item.core;
7aabaf9d
SM
3836 info->extra = std::move (item.extra);
3837 info->name = std::move (item.name);
3838 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
3839 }
3840 }
3841 }
3842
ab970af1
PA
3843 if (!got_list)
3844 {
3845 /* If no thread listing method is supported, then query whether
3846 each known thread is alive, one by one, with the T packet.
3847 If the target doesn't support threads at all, then this is a
3848 no-op. See remote_thread_alive. */
3849 prune_threads ();
3850 }
9d1f7ab2
MS
3851}
3852
802188a7 3853/*
9d1f7ab2
MS
3854 * Collect a descriptive string about the given thread.
3855 * The target may say anything it wants to about the thread
3856 * (typically info about its blocked / runnable state, name, etc.).
3857 * This string will appear in the info threads display.
802188a7 3858 *
9d1f7ab2
MS
3859 * Optional: targets are not required to implement this function.
3860 */
3861
f6ac5f3d
PA
3862const char *
3863remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 3864{
d01949b6 3865 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3866 int set;
3867 threadref id;
3868 struct gdb_ext_thread_info threadinfo;
9d1f7ab2 3869
5d93a237 3870 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3871 internal_error (__FILE__, __LINE__,
e2e0b3e5 3872 _("remote_threads_extra_info"));
9d1f7ab2 3873
d7e15655 3874 if (tp->ptid == magic_null_ptid
e38504b3 3875 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
60e569b9
PA
3876 /* This is the main thread which was added by GDB. The remote
3877 server doesn't know about it. */
3878 return NULL;
3879
c76a8ea3
PA
3880 std::string &extra = get_remote_thread_info (tp)->extra;
3881
3882 /* If already have cached info, use it. */
3883 if (!extra.empty ())
3884 return extra.c_str ();
3885
4082afcc 3886 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3887 {
c76a8ea3
PA
3888 /* If we're using qXfer:threads:read, then the extra info is
3889 included in the XML. So if we didn't have anything cached,
3890 it's because there's really no extra info. */
3891 return NULL;
dc146f7c
VP
3892 }
3893
b80fafe3 3894 if (rs->use_threadextra_query)
9d1f7ab2 3895 {
82f73884
PA
3896 char *b = rs->buf;
3897 char *endb = rs->buf + get_remote_packet_size ();
3898
3899 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3900 b += strlen (b);
3901 write_ptid (b, endb, tp->ptid);
3902
2e9f7625 3903 putpkt (rs->buf);
6d820c5c 3904 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3905 if (rs->buf[0] != 0)
9d1f7ab2 3906 {
c76a8ea3
PA
3907 extra.resize (strlen (rs->buf) / 2);
3908 hex2bin (rs->buf, (gdb_byte *) &extra[0], extra.size ());
3909 return extra.c_str ();
9d1f7ab2 3910 }
0f71a2f6 3911 }
9d1f7ab2
MS
3912
3913 /* If the above query fails, fall back to the old method. */
b80fafe3 3914 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3915 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3916 | TAG_MOREDISPLAY | TAG_DISPLAY;
e38504b3 3917 int_to_threadref (&id, tp->ptid.lwp ());
9d1f7ab2
MS
3918 if (remote_get_threadinfo (&id, set, &threadinfo))
3919 if (threadinfo.active)
0f71a2f6 3920 {
9d1f7ab2 3921 if (*threadinfo.shortname)
c76a8ea3 3922 string_appendf (extra, " Name: %s", threadinfo.shortname);
9d1f7ab2 3923 if (*threadinfo.display)
c76a8ea3
PA
3924 {
3925 if (!extra.empty ())
3926 extra += ',';
3927 string_appendf (extra, " State: %s", threadinfo.display);
3928 }
9d1f7ab2 3929 if (*threadinfo.more_display)
c5aa993b 3930 {
c76a8ea3
PA
3931 if (!extra.empty ())
3932 extra += ',';
3933 string_appendf (extra, " Priority: %s", threadinfo.more_display);
c5aa993b 3934 }
c76a8ea3 3935 return extra.c_str ();
0f71a2f6 3936 }
9d1f7ab2 3937 return NULL;
0f71a2f6 3938}
c906108c 3939\f
c5aa993b 3940
f6ac5f3d
PA
3941bool
3942remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3943 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
3944{
3945 struct remote_state *rs = get_remote_state ();
3946 char *p = rs->buf;
3947
bba74b36 3948 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3949 p += strlen (p);
3950 p += hexnumstr (p, addr);
3951 putpkt (rs->buf);
3952 getpkt (&rs->buf, &rs->buf_size, 0);
3953 p = rs->buf;
3954
3955 if (*p == 'E')
3956 error (_("Remote failure reply: %s"), p);
3957
3958 if (*p++ == 'm')
3959 {
256642e8 3960 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 3961 return true;
0fb4aa4b
PA
3962 }
3963
5d9310c4 3964 return false;
0fb4aa4b
PA
3965}
3966
f6ac5f3d
PA
3967std::vector<static_tracepoint_marker>
3968remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
3969{
3970 struct remote_state *rs = get_remote_state ();
5d9310c4 3971 std::vector<static_tracepoint_marker> markers;
256642e8 3972 const char *p;
5d9310c4 3973 static_tracepoint_marker marker;
0fb4aa4b
PA
3974
3975 /* Ask for a first packet of static tracepoint marker
3976 definition. */
3977 putpkt ("qTfSTM");
3978 getpkt (&rs->buf, &rs->buf_size, 0);
3979 p = rs->buf;
3980 if (*p == 'E')
3981 error (_("Remote failure reply: %s"), p);
3982
0fb4aa4b
PA
3983 while (*p++ == 'm')
3984 {
0fb4aa4b
PA
3985 do
3986 {
5d9310c4 3987 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 3988
5d9310c4
SM
3989 if (strid == NULL || marker.str_id == strid)
3990 markers.push_back (std::move (marker));
0fb4aa4b
PA
3991 }
3992 while (*p++ == ','); /* comma-separated list */
3993 /* Ask for another packet of static tracepoint definition. */
3994 putpkt ("qTsSTM");
3995 getpkt (&rs->buf, &rs->buf_size, 0);
3996 p = rs->buf;
3997 }
3998
0fb4aa4b
PA
3999 return markers;
4000}
4001
4002\f
10760264
JB
4003/* Implement the to_get_ada_task_ptid function for the remote targets. */
4004
f6ac5f3d
PA
4005ptid_t
4006remote_target::get_ada_task_ptid (long lwp, long thread)
10760264 4007{
e99b03dc 4008 return ptid_t (inferior_ptid.pid (), lwp, 0);
10760264
JB
4009}
4010\f
4011
24b06219 4012/* Restart the remote side; this is an extended protocol operation. */
c906108c 4013
6b8edb51
PA
4014void
4015remote_target::extended_remote_restart ()
c906108c 4016{
d01949b6 4017 struct remote_state *rs = get_remote_state ();
c906108c
SS
4018
4019 /* Send the restart command; for reasons I don't understand the
4020 remote side really expects a number after the "R". */
ea9c271d 4021 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 4022 putpkt (rs->buf);
c906108c 4023
ad9a8f3f 4024 remote_fileio_reset ();
c906108c
SS
4025}
4026\f
4027/* Clean up connection to a remote debugger. */
4028
f6ac5f3d
PA
4029void
4030remote_target::close ()
c906108c 4031{
048094ac 4032 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4033 terminal_ours ();
ce5ce7ed 4034
ce5ce7ed 4035 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
4036 of all the inferiors and their threads we were controlling.
4037 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4038 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 4039 inferior_ptid = null_ptid;
f67fd822 4040 discard_all_inferiors ();
ce5ce7ed 4041
6b8edb51
PA
4042 trace_reset_local_state ();
4043
4044 delete this;
4045}
4046
4047remote_target::~remote_target ()
4048{
4049 struct remote_state *rs = get_remote_state ();
4050
4051 /* Check for NULL because we may get here with a partially
4052 constructed target/connection. */
4053 if (rs->remote_desc == nullptr)
4054 return;
4055
4056 serial_close (rs->remote_desc);
4057
4058 /* We are destroying the remote target, so we should discard
f48ff2a7 4059 everything of this target. */
6b8edb51 4060 discard_pending_stop_replies_in_queue ();
74531fed 4061
6b8edb51
PA
4062 if (rs->remote_async_inferior_event_token)
4063 delete_async_event_handler (&rs->remote_async_inferior_event_token);
722247f1 4064
5965e028 4065 remote_notif_state_xfree (rs->notif_state);
c906108c
SS
4066}
4067
23860348 4068/* Query the remote side for the text, data and bss offsets. */
c906108c 4069
6b8edb51
PA
4070void
4071remote_target::get_offsets ()
c906108c 4072{
d01949b6 4073 struct remote_state *rs = get_remote_state ();
2e9f7625 4074 char *buf;
085dd6e6 4075 char *ptr;
31d99776
DJ
4076 int lose, num_segments = 0, do_sections, do_segments;
4077 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 4078 struct section_offsets *offs;
31d99776
DJ
4079 struct symfile_segment_data *data;
4080
4081 if (symfile_objfile == NULL)
4082 return;
c906108c
SS
4083
4084 putpkt ("qOffsets");
6d820c5c 4085 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4086 buf = rs->buf;
c906108c
SS
4087
4088 if (buf[0] == '\000')
4089 return; /* Return silently. Stub doesn't support
23860348 4090 this command. */
c906108c
SS
4091 if (buf[0] == 'E')
4092 {
8a3fe4f8 4093 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4094 return;
4095 }
4096
4097 /* Pick up each field in turn. This used to be done with scanf, but
4098 scanf will make trouble if CORE_ADDR size doesn't match
4099 conversion directives correctly. The following code will work
4100 with any size of CORE_ADDR. */
4101 text_addr = data_addr = bss_addr = 0;
4102 ptr = buf;
4103 lose = 0;
4104
61012eef 4105 if (startswith (ptr, "Text="))
c906108c
SS
4106 {
4107 ptr += 5;
4108 /* Don't use strtol, could lose on big values. */
4109 while (*ptr && *ptr != ';')
4110 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4111
61012eef 4112 if (startswith (ptr, ";Data="))
31d99776
DJ
4113 {
4114 ptr += 6;
4115 while (*ptr && *ptr != ';')
4116 data_addr = (data_addr << 4) + fromhex (*ptr++);
4117 }
4118 else
4119 lose = 1;
4120
61012eef 4121 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4122 {
4123 ptr += 5;
4124 while (*ptr && *ptr != ';')
4125 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4126
31d99776
DJ
4127 if (bss_addr != data_addr)
4128 warning (_("Target reported unsupported offsets: %s"), buf);
4129 }
4130 else
4131 lose = 1;
4132 }
61012eef 4133 else if (startswith (ptr, "TextSeg="))
c906108c 4134 {
31d99776
DJ
4135 ptr += 8;
4136 /* Don't use strtol, could lose on big values. */
c906108c 4137 while (*ptr && *ptr != ';')
31d99776
DJ
4138 text_addr = (text_addr << 4) + fromhex (*ptr++);
4139 num_segments = 1;
4140
61012eef 4141 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4142 {
4143 ptr += 9;
4144 while (*ptr && *ptr != ';')
4145 data_addr = (data_addr << 4) + fromhex (*ptr++);
4146 num_segments++;
4147 }
c906108c
SS
4148 }
4149 else
4150 lose = 1;
4151
4152 if (lose)
8a3fe4f8 4153 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4154 else if (*ptr != '\0')
4155 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4156
802188a7 4157 offs = ((struct section_offsets *)
a39a16c4 4158 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 4159 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 4160 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 4161
31d99776
DJ
4162 data = get_symfile_segment_data (symfile_objfile->obfd);
4163 do_segments = (data != NULL);
4164 do_sections = num_segments == 0;
c906108c 4165
28c32713 4166 if (num_segments > 0)
31d99776 4167 {
31d99776
DJ
4168 segments[0] = text_addr;
4169 segments[1] = data_addr;
4170 }
28c32713
JB
4171 /* If we have two segments, we can still try to relocate everything
4172 by assuming that the .text and .data offsets apply to the whole
4173 text and data segments. Convert the offsets given in the packet
4174 to base addresses for symfile_map_offsets_to_segments. */
4175 else if (data && data->num_segments == 2)
4176 {
4177 segments[0] = data->segment_bases[0] + text_addr;
4178 segments[1] = data->segment_bases[1] + data_addr;
4179 num_segments = 2;
4180 }
8d385431
DJ
4181 /* If the object file has only one segment, assume that it is text
4182 rather than data; main programs with no writable data are rare,
4183 but programs with no code are useless. Of course the code might
4184 have ended up in the data segment... to detect that we would need
4185 the permissions here. */
4186 else if (data && data->num_segments == 1)
4187 {
4188 segments[0] = data->segment_bases[0] + text_addr;
4189 num_segments = 1;
4190 }
28c32713
JB
4191 /* There's no way to relocate by segment. */
4192 else
4193 do_segments = 0;
31d99776
DJ
4194
4195 if (do_segments)
4196 {
4197 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4198 offs, num_segments, segments);
4199
4200 if (ret == 0 && !do_sections)
3e43a32a
MS
4201 error (_("Can not handle qOffsets TextSeg "
4202 "response with this symbol file"));
31d99776
DJ
4203
4204 if (ret > 0)
4205 do_sections = 0;
4206 }
c906108c 4207
9ef895d6
DJ
4208 if (data)
4209 free_symfile_segment_data (data);
31d99776
DJ
4210
4211 if (do_sections)
4212 {
4213 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4214
3e43a32a
MS
4215 /* This is a temporary kludge to force data and bss to use the
4216 same offsets because that's what nlmconv does now. The real
4217 solution requires changes to the stub and remote.c that I
4218 don't have time to do right now. */
31d99776
DJ
4219
4220 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4221 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4222 }
c906108c
SS
4223
4224 objfile_relocate (symfile_objfile, offs);
4225}
4226
9a7071a8 4227/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4228
4229void
4230remote_target::send_interrupt_sequence ()
9a7071a8 4231{
5d93a237
TT
4232 struct remote_state *rs = get_remote_state ();
4233
9a7071a8 4234 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4235 remote_serial_write ("\x03", 1);
9a7071a8 4236 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4237 serial_send_break (rs->remote_desc);
9a7071a8
JB
4238 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4239 {
5d93a237 4240 serial_send_break (rs->remote_desc);
c33e31fd 4241 remote_serial_write ("g", 1);
9a7071a8
JB
4242 }
4243 else
4244 internal_error (__FILE__, __LINE__,
4245 _("Invalid value for interrupt_sequence_mode: %s."),
4246 interrupt_sequence_mode);
4247}
4248
3405876a
PA
4249
4250/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4251 and extract the PTID. Returns NULL_PTID if not found. */
4252
4253static ptid_t
4254stop_reply_extract_thread (char *stop_reply)
4255{
4256 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4257 {
256642e8 4258 const char *p;
3405876a
PA
4259
4260 /* Txx r:val ; r:val (...) */
4261 p = &stop_reply[3];
4262
4263 /* Look for "register" named "thread". */
4264 while (*p != '\0')
4265 {
256642e8 4266 const char *p1;
3405876a
PA
4267
4268 p1 = strchr (p, ':');
4269 if (p1 == NULL)
4270 return null_ptid;
4271
4272 if (strncmp (p, "thread", p1 - p) == 0)
4273 return read_ptid (++p1, &p);
4274
4275 p1 = strchr (p, ';');
4276 if (p1 == NULL)
4277 return null_ptid;
4278 p1++;
4279
4280 p = p1;
4281 }
4282 }
4283
4284 return null_ptid;
4285}
4286
b7ea362b
PA
4287/* Determine the remote side's current thread. If we have a stop
4288 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4289 "thread" register we can extract the current thread from. If not,
4290 ask the remote which is the current thread with qC. The former
4291 method avoids a roundtrip. */
4292
6b8edb51
PA
4293ptid_t
4294remote_target::get_current_thread (char *wait_status)
b7ea362b 4295{
6a49a997 4296 ptid_t ptid = null_ptid;
b7ea362b
PA
4297
4298 /* Note we don't use remote_parse_stop_reply as that makes use of
4299 the target architecture, which we haven't yet fully determined at
4300 this point. */
4301 if (wait_status != NULL)
4302 ptid = stop_reply_extract_thread (wait_status);
d7e15655 4303 if (ptid == null_ptid)
b7ea362b
PA
4304 ptid = remote_current_thread (inferior_ptid);
4305
4306 return ptid;
4307}
4308
49c62f2e
PA
4309/* Query the remote target for which is the current thread/process,
4310 add it to our tables, and update INFERIOR_PTID. The caller is
4311 responsible for setting the state such that the remote end is ready
3405876a
PA
4312 to return the current thread.
4313
4314 This function is called after handling the '?' or 'vRun' packets,
4315 whose response is a stop reply from which we can also try
4316 extracting the thread. If the target doesn't support the explicit
4317 qC query, we infer the current thread from that stop reply, passed
4318 in in WAIT_STATUS, which may be NULL. */
49c62f2e 4319
6b8edb51
PA
4320void
4321remote_target::add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
4322{
4323 struct remote_state *rs = get_remote_state ();
4324 int fake_pid_p = 0;
49c62f2e
PA
4325
4326 inferior_ptid = null_ptid;
4327
b7ea362b 4328 /* Now, if we have thread information, update inferior_ptid. */
87215ad1 4329 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4330
87215ad1 4331 if (curr_ptid != null_ptid)
49c62f2e
PA
4332 {
4333 if (!remote_multi_process_p (rs))
4334 fake_pid_p = 1;
49c62f2e
PA
4335 }
4336 else
4337 {
4338 /* Without this, some commands which require an active target
4339 (such as kill) won't work. This variable serves (at least)
4340 double duty as both the pid of the target process (if it has
4341 such), and as a flag indicating that a target is active. */
87215ad1 4342 curr_ptid = magic_null_ptid;
49c62f2e
PA
4343 fake_pid_p = 1;
4344 }
4345
e99b03dc 4346 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
49c62f2e 4347
87215ad1
SDJ
4348 /* Add the main thread and switch to it. Don't try reading
4349 registers yet, since we haven't fetched the target description
4350 yet. */
4351 thread_info *tp = add_thread_silent (curr_ptid);
4352 switch_to_thread_no_regs (tp);
49c62f2e
PA
4353}
4354
6efcd9a8
PA
4355/* Print info about a thread that was found already stopped on
4356 connection. */
4357
4358static void
4359print_one_stopped_thread (struct thread_info *thread)
4360{
4361 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4362
00431a78 4363 switch_to_thread (thread);
f2ffa92b 4364 thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
6efcd9a8
PA
4365 set_current_sal_from_frame (get_current_frame ());
4366
4367 thread->suspend.waitstatus_pending_p = 0;
4368
4369 if (ws->kind == TARGET_WAITKIND_STOPPED)
4370 {
4371 enum gdb_signal sig = ws->value.sig;
4372
4373 if (signal_print_state (sig))
76727919 4374 gdb::observers::signal_received.notify (sig);
6efcd9a8 4375 }
76727919 4376 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4377}
4378
221e1a37
PA
4379/* Process all initial stop replies the remote side sent in response
4380 to the ? packet. These indicate threads that were already stopped
4381 on initial connection. We mark these threads as stopped and print
4382 their current frame before giving the user the prompt. */
4383
6b8edb51
PA
4384void
4385remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4386{
4387 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4388 struct inferior *inf;
4389 struct thread_info *thread;
4390 struct thread_info *selected = NULL;
4391 struct thread_info *lowest_stopped = NULL;
4392 struct thread_info *first = NULL;
221e1a37
PA
4393
4394 /* Consume the initial pending events. */
4395 while (pending_stop_replies-- > 0)
4396 {
4397 ptid_t waiton_ptid = minus_one_ptid;
4398 ptid_t event_ptid;
4399 struct target_waitstatus ws;
4400 int ignore_event = 0;
4401
4402 memset (&ws, 0, sizeof (ws));
4403 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4404 if (remote_debug)
4405 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4406
4407 switch (ws.kind)
4408 {
4409 case TARGET_WAITKIND_IGNORE:
4410 case TARGET_WAITKIND_NO_RESUMED:
4411 case TARGET_WAITKIND_SIGNALLED:
4412 case TARGET_WAITKIND_EXITED:
4413 /* We shouldn't see these, but if we do, just ignore. */
4414 if (remote_debug)
4415 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4416 ignore_event = 1;
4417 break;
4418
4419 case TARGET_WAITKIND_EXECD:
4420 xfree (ws.value.execd_pathname);
4421 break;
4422 default:
4423 break;
4424 }
4425
4426 if (ignore_event)
4427 continue;
4428
b926417a 4429 struct thread_info *evthread = find_thread_ptid (event_ptid);
221e1a37
PA
4430
4431 if (ws.kind == TARGET_WAITKIND_STOPPED)
4432 {
4433 enum gdb_signal sig = ws.value.sig;
4434
4435 /* Stubs traditionally report SIGTRAP as initial signal,
4436 instead of signal 0. Suppress it. */
4437 if (sig == GDB_SIGNAL_TRAP)
4438 sig = GDB_SIGNAL_0;
b926417a 4439 evthread->suspend.stop_signal = sig;
6efcd9a8
PA
4440 ws.value.sig = sig;
4441 }
221e1a37 4442
b926417a 4443 evthread->suspend.waitstatus = ws;
6efcd9a8
PA
4444
4445 if (ws.kind != TARGET_WAITKIND_STOPPED
4446 || ws.value.sig != GDB_SIGNAL_0)
b926417a 4447 evthread->suspend.waitstatus_pending_p = 1;
6efcd9a8
PA
4448
4449 set_executing (event_ptid, 0);
4450 set_running (event_ptid, 0);
b926417a 4451 get_remote_thread_info (evthread)->vcont_resumed = 0;
6efcd9a8
PA
4452 }
4453
4454 /* "Notice" the new inferiors before anything related to
4455 registers/memory. */
4456 ALL_INFERIORS (inf)
4457 {
4458 if (inf->pid == 0)
4459 continue;
4460
4461 inf->needs_setup = 1;
4462
4463 if (non_stop)
4464 {
00431a78
PA
4465 thread = any_live_thread_of_inferior (inf);
4466 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
6efcd9a8
PA
4467 from_tty);
4468 }
4469 }
4470
4471 /* If all-stop on top of non-stop, pause all threads. Note this
4472 records the threads' stop pc, so must be done after "noticing"
4473 the inferiors. */
4474 if (!non_stop)
4475 {
4476 stop_all_threads ();
4477
4478 /* If all threads of an inferior were already stopped, we
4479 haven't setup the inferior yet. */
4480 ALL_INFERIORS (inf)
4481 {
4482 if (inf->pid == 0)
4483 continue;
221e1a37 4484
6efcd9a8
PA
4485 if (inf->needs_setup)
4486 {
00431a78 4487 thread = any_live_thread_of_inferior (inf);
6efcd9a8
PA
4488 switch_to_thread_no_regs (thread);
4489 setup_inferior (0);
4490 }
4491 }
221e1a37 4492 }
6efcd9a8
PA
4493
4494 /* Now go over all threads that are stopped, and print their current
4495 frame. If all-stop, then if there's a signalled thread, pick
4496 that as current. */
4497 ALL_NON_EXITED_THREADS (thread)
4498 {
6efcd9a8
PA
4499 if (first == NULL)
4500 first = thread;
4501
4502 if (!non_stop)
00431a78 4503 thread->set_running (false);
6efcd9a8
PA
4504 else if (thread->state != THREAD_STOPPED)
4505 continue;
4506
6efcd9a8
PA
4507 if (selected == NULL
4508 && thread->suspend.waitstatus_pending_p)
4509 selected = thread;
4510
5d5658a1
PA
4511 if (lowest_stopped == NULL
4512 || thread->inf->num < lowest_stopped->inf->num
4513 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4514 lowest_stopped = thread;
4515
4516 if (non_stop)
4517 print_one_stopped_thread (thread);
4518 }
4519
4520 /* In all-stop, we only print the status of one thread, and leave
4521 others with their status pending. */
4522 if (!non_stop)
4523 {
4524 thread = selected;
4525 if (thread == NULL)
4526 thread = lowest_stopped;
4527 if (thread == NULL)
4528 thread = first;
4529
4530 print_one_stopped_thread (thread);
4531 }
4532
4533 /* For "info program". */
4534 thread = inferior_thread ();
4535 if (thread->state == THREAD_STOPPED)
4536 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4537}
4538
048094ac
PA
4539/* Start the remote connection and sync state. */
4540
f6ac5f3d
PA
4541void
4542remote_target::start_remote (int from_tty, int extended_p)
c906108c 4543{
c8d104ad
PA
4544 struct remote_state *rs = get_remote_state ();
4545 struct packet_config *noack_config;
2d717e4f 4546 char *wait_status = NULL;
8621d6a9 4547
048094ac
PA
4548 /* Signal other parts that we're going through the initial setup,
4549 and so things may not be stable yet. E.g., we don't try to
4550 install tracepoints until we've relocated symbols. Also, a
4551 Ctrl-C before we're connected and synced up can't interrupt the
4552 target. Instead, it offers to drop the (potentially wedged)
4553 connection. */
4554 rs->starting_up = 1;
4555
522002f9 4556 QUIT;
c906108c 4557
9a7071a8
JB
4558 if (interrupt_on_connect)
4559 send_interrupt_sequence ();
4560
57e12211 4561 /* Ack any packet which the remote side has already sent. */
048094ac 4562 remote_serial_write ("+", 1);
1e51243a 4563
c8d104ad
PA
4564 /* The first packet we send to the target is the optional "supported
4565 packets" request. If the target can answer this, it will tell us
4566 which later probes to skip. */
4567 remote_query_supported ();
4568
d914c394 4569 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4570 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4571 set_permissions ();
d914c394 4572
57809e5e
JK
4573 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4574 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4575 as a reply to known packet. For packet "vFile:setfs:" it is an
4576 invalid reply and GDB would return error in
4577 remote_hostio_set_filesystem, making remote files access impossible.
4578 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4579 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4580 {
4581 const char v_mustreplyempty[] = "vMustReplyEmpty";
4582
4583 putpkt (v_mustreplyempty);
4584 getpkt (&rs->buf, &rs->buf_size, 0);
4585 if (strcmp (rs->buf, "OK") == 0)
4586 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4587 else if (strcmp (rs->buf, "") != 0)
4588 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4589 rs->buf);
4590 }
4591
c8d104ad
PA
4592 /* Next, we possibly activate noack mode.
4593
4594 If the QStartNoAckMode packet configuration is set to AUTO,
4595 enable noack mode if the stub reported a wish for it with
4596 qSupported.
4597
4598 If set to TRUE, then enable noack mode even if the stub didn't
4599 report it in qSupported. If the stub doesn't reply OK, the
4600 session ends with an error.
4601
4602 If FALSE, then don't activate noack mode, regardless of what the
4603 stub claimed should be the default with qSupported. */
4604
4605 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4606 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4607 {
4608 putpkt ("QStartNoAckMode");
4609 getpkt (&rs->buf, &rs->buf_size, 0);
4610 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4611 rs->noack_mode = 1;
4612 }
4613
04bd08de 4614 if (extended_p)
5fe04517
PA
4615 {
4616 /* Tell the remote that we are using the extended protocol. */
4617 putpkt ("!");
4618 getpkt (&rs->buf, &rs->buf_size, 0);
4619 }
4620
9b224c5e
PA
4621 /* Let the target know which signals it is allowed to pass down to
4622 the program. */
4623 update_signals_program_target ();
4624
d962ef82
DJ
4625 /* Next, if the target can specify a description, read it. We do
4626 this before anything involving memory or registers. */
4627 target_find_description ();
4628
6c95b8df
PA
4629 /* Next, now that we know something about the target, update the
4630 address spaces in the program spaces. */
4631 update_address_spaces ();
4632
50c71eaf
PA
4633 /* On OSs where the list of libraries is global to all
4634 processes, we fetch them early. */
f5656ead 4635 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4636 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4637
6efcd9a8 4638 if (target_is_non_stop_p ())
74531fed 4639 {
4082afcc 4640 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4641 error (_("Non-stop mode requested, but remote "
4642 "does not support non-stop"));
74531fed
PA
4643
4644 putpkt ("QNonStop:1");
4645 getpkt (&rs->buf, &rs->buf_size, 0);
4646
4647 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4648 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4649
4650 /* Find about threads and processes the stub is already
4651 controlling. We default to adding them in the running state.
4652 The '?' query below will then tell us about which threads are
4653 stopped. */
f6ac5f3d 4654 this->update_thread_list ();
74531fed 4655 }
4082afcc 4656 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4657 {
4658 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4659 Request it explicitly. */
74531fed
PA
4660 putpkt ("QNonStop:0");
4661 getpkt (&rs->buf, &rs->buf_size, 0);
4662
4663 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4664 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4665 }
4666
a0743c90
YQ
4667 /* Upload TSVs regardless of whether the target is running or not. The
4668 remote stub, such as GDBserver, may have some predefined or builtin
4669 TSVs, even if the target is not running. */
f6ac5f3d 4670 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4671 {
4672 struct uploaded_tsv *uploaded_tsvs = NULL;
4673
f6ac5f3d 4674 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4675 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4676 }
4677
2d717e4f
DJ
4678 /* Check whether the target is running now. */
4679 putpkt ("?");
4680 getpkt (&rs->buf, &rs->buf_size, 0);
4681
6efcd9a8 4682 if (!target_is_non_stop_p ())
2d717e4f 4683 {
74531fed 4684 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4685 {
04bd08de 4686 if (!extended_p)
74531fed 4687 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4688
4689 /* We're connected, but not running. Drop out before we
4690 call start_remote. */
e278ad5b 4691 rs->starting_up = 0;
c35b1492 4692 return;
2d717e4f
DJ
4693 }
4694 else
74531fed 4695 {
74531fed 4696 /* Save the reply for later. */
224c3ddb 4697 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4698 strcpy (wait_status, rs->buf);
4699 }
4700
b7ea362b 4701 /* Fetch thread list. */
e8032dde 4702 target_update_thread_list ();
b7ea362b 4703
74531fed
PA
4704 /* Let the stub know that we want it to return the thread. */
4705 set_continue_thread (minus_one_ptid);
4706
b7ea362b
PA
4707 if (thread_count () == 0)
4708 {
4709 /* Target has no concept of threads at all. GDB treats
4710 non-threaded target as single-threaded; add a main
4711 thread. */
4712 add_current_inferior_and_thread (wait_status);
4713 }
4714 else
4715 {
4716 /* We have thread information; select the thread the target
4717 says should be current. If we're reconnecting to a
4718 multi-threaded program, this will ideally be the thread
4719 that last reported an event before GDB disconnected. */
4720 inferior_ptid = get_current_thread (wait_status);
d7e15655 4721 if (inferior_ptid == null_ptid)
b7ea362b
PA
4722 {
4723 /* Odd... The target was able to list threads, but not
4724 tell us which thread was current (no "thread"
4725 register in T stop reply?). Just pick the first
4726 thread in the thread list then. */
c9f35b34
KB
4727
4728 if (remote_debug)
4729 fprintf_unfiltered (gdb_stdlog,
4730 "warning: couldn't determine remote "
4731 "current thread; picking first in list.\n");
4732
b7ea362b
PA
4733 inferior_ptid = thread_list->ptid;
4734 }
4735 }
74531fed 4736
6e586cc5
YQ
4737 /* init_wait_for_inferior should be called before get_offsets in order
4738 to manage `inserted' flag in bp loc in a correct state.
4739 breakpoint_init_inferior, called from init_wait_for_inferior, set
4740 `inserted' flag to 0, while before breakpoint_re_set, called from
4741 start_remote, set `inserted' flag to 1. In the initialization of
4742 inferior, breakpoint_init_inferior should be called first, and then
4743 breakpoint_re_set can be called. If this order is broken, state of
4744 `inserted' flag is wrong, and cause some problems on breakpoint
4745 manipulation. */
4746 init_wait_for_inferior ();
4747
74531fed
PA
4748 get_offsets (); /* Get text, data & bss offsets. */
4749
d962ef82
DJ
4750 /* If we could not find a description using qXfer, and we know
4751 how to do it some other way, try again. This is not
4752 supported for non-stop; it could be, but it is tricky if
4753 there are no stopped threads when we connect. */
f6ac5f3d 4754 if (remote_read_description_p (this)
f5656ead 4755 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4756 {
4757 target_clear_description ();
4758 target_find_description ();
4759 }
4760
74531fed
PA
4761 /* Use the previously fetched status. */
4762 gdb_assert (wait_status != NULL);
4763 strcpy (rs->buf, wait_status);
4764 rs->cached_wait_status = 1;
4765
f6ac5f3d 4766 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4767 }
4768 else
4769 {
68c97600
PA
4770 /* Clear WFI global state. Do this before finding about new
4771 threads and inferiors, and setting the current inferior.
4772 Otherwise we would clear the proceed status of the current
4773 inferior when we want its stop_soon state to be preserved
4774 (see notice_new_inferior). */
4775 init_wait_for_inferior ();
4776
74531fed
PA
4777 /* In non-stop, we will either get an "OK", meaning that there
4778 are no stopped threads at this time; or, a regular stop
4779 reply. In the latter case, there may be more than one thread
4780 stopped --- we pull them all out using the vStopped
4781 mechanism. */
4782 if (strcmp (rs->buf, "OK") != 0)
4783 {
722247f1 4784 struct notif_client *notif = &notif_client_stop;
2d717e4f 4785
722247f1
YQ
4786 /* remote_notif_get_pending_replies acks this one, and gets
4787 the rest out. */
f48ff2a7 4788 rs->notif_state->pending_event[notif_client_stop.id]
6b8edb51 4789 = remote_notif_parse (this, notif, rs->buf);
722247f1 4790 remote_notif_get_pending_events (notif);
74531fed 4791 }
2d717e4f 4792
74531fed
PA
4793 if (thread_count () == 0)
4794 {
04bd08de 4795 if (!extended_p)
74531fed 4796 error (_("The target is not running (try extended-remote?)"));
82f73884 4797
c35b1492
PA
4798 /* We're connected, but not running. Drop out before we
4799 call start_remote. */
e278ad5b 4800 rs->starting_up = 0;
c35b1492
PA
4801 return;
4802 }
74531fed 4803
74531fed
PA
4804 /* In non-stop mode, any cached wait status will be stored in
4805 the stop reply queue. */
4806 gdb_assert (wait_status == NULL);
f0223081 4807
2455069d 4808 /* Report all signals during attach/startup. */
f6ac5f3d 4809 pass_signals (0, NULL);
221e1a37
PA
4810
4811 /* If there are already stopped threads, mark them stopped and
4812 report their stops before giving the prompt to the user. */
6efcd9a8 4813 process_initial_stop_replies (from_tty);
221e1a37
PA
4814
4815 if (target_can_async_p ())
4816 target_async (1);
74531fed 4817 }
c8d104ad 4818
c8d104ad
PA
4819 /* If we connected to a live target, do some additional setup. */
4820 if (target_has_execution)
4821 {
f4ccffad 4822 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4823 remote_check_symbols ();
c8d104ad 4824 }
50c71eaf 4825
d5551862
SS
4826 /* Possibly the target has been engaged in a trace run started
4827 previously; find out where things are at. */
f6ac5f3d 4828 if (get_trace_status (current_trace_status ()) != -1)
d5551862 4829 {
00bf0b85 4830 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4831
00bf0b85
SS
4832 if (current_trace_status ()->running)
4833 printf_filtered (_("Trace is already running on the target.\n"));
4834
f6ac5f3d 4835 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
4836
4837 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4838 }
4839
c0272db5
TW
4840 /* Possibly the target has been engaged in a btrace record started
4841 previously; find out where things are at. */
4842 remote_btrace_maybe_reopen ();
4843
1e51243a
PA
4844 /* The thread and inferior lists are now synchronized with the
4845 target, our symbols have been relocated, and we're merged the
4846 target's tracepoints with ours. We're done with basic start
4847 up. */
4848 rs->starting_up = 0;
4849
a25a5a45
PA
4850 /* Maybe breakpoints are global and need to be inserted now. */
4851 if (breakpoints_should_be_inserted_now ())
50c71eaf 4852 insert_breakpoints ();
c906108c
SS
4853}
4854
4855/* Open a connection to a remote debugger.
4856 NAME is the filename used for communication. */
4857
f6ac5f3d
PA
4858void
4859remote_target::open (const char *name, int from_tty)
c906108c 4860{
f6ac5f3d 4861 open_1 (name, from_tty, 0);
43ff13b4
JM
4862}
4863
c906108c
SS
4864/* Open a connection to a remote debugger using the extended
4865 remote gdb protocol. NAME is the filename used for communication. */
4866
f6ac5f3d
PA
4867void
4868extended_remote_target::open (const char *name, int from_tty)
c906108c 4869{
f6ac5f3d 4870 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
4871}
4872
ca4f7f8b
PA
4873/* Reset all packets back to "unknown support". Called when opening a
4874 new connection to a remote target. */
c906108c 4875
d471ea57 4876static void
ca4f7f8b 4877reset_all_packet_configs_support (void)
d471ea57
AC
4878{
4879 int i;
a744cf53 4880
444abaca 4881 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4882 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4883}
4884
ca4f7f8b
PA
4885/* Initialize all packet configs. */
4886
4887static void
4888init_all_packet_configs (void)
4889{
4890 int i;
4891
4892 for (i = 0; i < PACKET_MAX; i++)
4893 {
4894 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4895 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4896 }
4897}
4898
23860348 4899/* Symbol look-up. */
dc8acb97 4900
6b8edb51
PA
4901void
4902remote_target::remote_check_symbols ()
dc8acb97
MS
4903{
4904 char *msg, *reply, *tmp;
dc8acb97 4905 int end;
28170b88 4906 long reply_size;
a5c0808e 4907 struct cleanup *old_chain;
dc8acb97 4908
63154eca
PA
4909 /* The remote side has no concept of inferiors that aren't running
4910 yet, it only knows about running processes. If we're connected
4911 but our current inferior is not running, we should not invite the
4912 remote target to request symbol lookups related to its
4913 (unrelated) current process. */
4914 if (!target_has_execution)
4915 return;
4916
4082afcc 4917 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4918 return;
4919
63154eca
PA
4920 /* Make sure the remote is pointing at the right process. Note
4921 there's no way to select "no process". */
3c9c4b83
PA
4922 set_general_process ();
4923
6d820c5c
DJ
4924 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4925 because we need both at the same time. */
224c3ddb 4926 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4927 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4928 reply = (char *) xmalloc (get_remote_packet_size ());
4929 make_cleanup (free_current_contents, &reply);
4930 reply_size = get_remote_packet_size ();
6d820c5c 4931
23860348 4932 /* Invite target to request symbol lookups. */
dc8acb97
MS
4933
4934 putpkt ("qSymbol::");
28170b88
MK
4935 getpkt (&reply, &reply_size, 0);
4936 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4937
61012eef 4938 while (startswith (reply, "qSymbol:"))
dc8acb97 4939 {
77e371c0
TT
4940 struct bound_minimal_symbol sym;
4941
dc8acb97 4942 tmp = &reply[8];
cfd77fa1 4943 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4944 msg[end] = '\0';
4945 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4946 if (sym.minsym == NULL)
ea9c271d 4947 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4948 else
2bbe3cc1 4949 {
f5656ead 4950 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4951 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4952
4953 /* If this is a function address, return the start of code
4954 instead of any data function descriptor. */
f5656ead 4955 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1 4956 sym_addr,
8b88a78e 4957 current_top_target ());
2bbe3cc1
DJ
4958
4959 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4960 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4961 }
4962
dc8acb97 4963 putpkt (msg);
28170b88 4964 getpkt (&reply, &reply_size, 0);
dc8acb97 4965 }
a5c0808e
PA
4966
4967 do_cleanups (old_chain);
dc8acb97
MS
4968}
4969
9db8d71f 4970static struct serial *
baa336ce 4971remote_serial_open (const char *name)
9db8d71f
DJ
4972{
4973 static int udp_warning = 0;
4974
4975 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4976 of in ser-tcp.c, because it is the remote protocol assuming that the
4977 serial connection is reliable and not the serial connection promising
4978 to be. */
61012eef 4979 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4980 {
3e43a32a
MS
4981 warning (_("The remote protocol may be unreliable over UDP.\n"
4982 "Some events may be lost, rendering further debugging "
4983 "impossible."));
9db8d71f
DJ
4984 udp_warning = 1;
4985 }
4986
4987 return serial_open (name);
4988}
4989
d914c394
SS
4990/* Inform the target of our permission settings. The permission flags
4991 work without this, but if the target knows the settings, it can do
4992 a couple things. First, it can add its own check, to catch cases
4993 that somehow manage to get by the permissions checks in target
4994 methods. Second, if the target is wired to disallow particular
4995 settings (for instance, a system in the field that is not set up to
4996 be able to stop at a breakpoint), it can object to any unavailable
4997 permissions. */
4998
4999void
f6ac5f3d 5000remote_target::set_permissions ()
d914c394
SS
5001{
5002 struct remote_state *rs = get_remote_state ();
5003
bba74b36
YQ
5004 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
5005 "WriteReg:%x;WriteMem:%x;"
5006 "InsertBreak:%x;InsertTrace:%x;"
5007 "InsertFastTrace:%x;Stop:%x",
5008 may_write_registers, may_write_memory,
5009 may_insert_breakpoints, may_insert_tracepoints,
5010 may_insert_fast_tracepoints, may_stop);
d914c394
SS
5011 putpkt (rs->buf);
5012 getpkt (&rs->buf, &rs->buf_size, 0);
5013
5014 /* If the target didn't like the packet, warn the user. Do not try
5015 to undo the user's settings, that would just be maddening. */
5016 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 5017 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
5018}
5019
be2a5f71
DJ
5020/* This type describes each known response to the qSupported
5021 packet. */
5022struct protocol_feature
5023{
5024 /* The name of this protocol feature. */
5025 const char *name;
5026
5027 /* The default for this protocol feature. */
5028 enum packet_support default_support;
5029
5030 /* The function to call when this feature is reported, or after
5031 qSupported processing if the feature is not supported.
5032 The first argument points to this structure. The second
5033 argument indicates whether the packet requested support be
5034 enabled, disabled, or probed (or the default, if this function
5035 is being called at the end of processing and this feature was
5036 not reported). The third argument may be NULL; if not NULL, it
5037 is a NUL-terminated string taken from the packet following
5038 this feature's name and an equals sign. */
6b8edb51
PA
5039 void (*func) (remote_target *remote, const struct protocol_feature *,
5040 enum packet_support, const char *);
be2a5f71
DJ
5041
5042 /* The corresponding packet for this feature. Only used if
5043 FUNC is remote_supported_packet. */
5044 int packet;
5045};
5046
be2a5f71 5047static void
6b8edb51
PA
5048remote_supported_packet (remote_target *remote,
5049 const struct protocol_feature *feature,
be2a5f71
DJ
5050 enum packet_support support,
5051 const char *argument)
5052{
5053 if (argument)
5054 {
5055 warning (_("Remote qSupported response supplied an unexpected value for"
5056 " \"%s\"."), feature->name);
5057 return;
5058 }
5059
4082afcc 5060 remote_protocol_packets[feature->packet].support = support;
be2a5f71 5061}
be2a5f71 5062
6b8edb51
PA
5063void
5064remote_target::remote_packet_size (const protocol_feature *feature,
5065 enum packet_support support, const char *value)
be2a5f71
DJ
5066{
5067 struct remote_state *rs = get_remote_state ();
5068
5069 int packet_size;
5070 char *value_end;
5071
5072 if (support != PACKET_ENABLE)
5073 return;
5074
5075 if (value == NULL || *value == '\0')
5076 {
5077 warning (_("Remote target reported \"%s\" without a size."),
5078 feature->name);
5079 return;
5080 }
5081
5082 errno = 0;
5083 packet_size = strtol (value, &value_end, 16);
5084 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5085 {
5086 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5087 feature->name, value);
5088 return;
5089 }
5090
be2a5f71
DJ
5091 /* Record the new maximum packet size. */
5092 rs->explicit_packet_size = packet_size;
5093}
5094
6b8edb51
PA
5095void
5096remote_packet_size (remote_target *remote, const protocol_feature *feature,
5097 enum packet_support support, const char *value)
5098{
5099 remote->remote_packet_size (feature, support, value);
5100}
5101
dc473cfb 5102static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5103 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5104 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5105 PACKET_qXfer_auxv },
c78fa86a
GB
5106 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5107 PACKET_qXfer_exec_file },
23181151
DJ
5108 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5109 PACKET_qXfer_features },
cfa9d6d9
DJ
5110 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5111 PACKET_qXfer_libraries },
2268b414
JK
5112 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5113 PACKET_qXfer_libraries_svr4 },
ced63ec0 5114 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5115 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5116 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5117 PACKET_qXfer_memory_map },
4de6483e
UW
5118 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5119 PACKET_qXfer_spu_read },
5120 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5121 PACKET_qXfer_spu_write },
07e059b5
VP
5122 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5123 PACKET_qXfer_osdata },
dc146f7c
VP
5124 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5125 PACKET_qXfer_threads },
b3b9301e
PA
5126 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5127 PACKET_qXfer_traceframe_info },
89be2091
DJ
5128 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5129 PACKET_QPassSignals },
82075af2
JS
5130 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5131 PACKET_QCatchSyscalls },
9b224c5e
PA
5132 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5133 PACKET_QProgramSignals },
bc3b087d
SDJ
5134 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5135 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5136 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5137 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5138 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5139 PACKET_QEnvironmentHexEncoded },
5140 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5141 PACKET_QEnvironmentReset },
5142 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5143 PACKET_QEnvironmentUnset },
a6f3e723
SL
5144 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5145 PACKET_QStartNoAckMode },
4082afcc
PA
5146 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5147 PACKET_multiprocess_feature },
5148 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5149 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5150 PACKET_qXfer_siginfo_read },
5151 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5152 PACKET_qXfer_siginfo_write },
4082afcc 5153 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5154 PACKET_ConditionalTracepoints },
4082afcc 5155 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5156 PACKET_ConditionalBreakpoints },
4082afcc 5157 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5158 PACKET_BreakpointCommands },
4082afcc 5159 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5160 PACKET_FastTracepoints },
4082afcc 5161 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5162 PACKET_StaticTracepoints },
4082afcc 5163 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5164 PACKET_InstallInTrace},
4082afcc
PA
5165 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5166 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5167 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5168 PACKET_bc },
5169 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5170 PACKET_bs },
409873ef
SS
5171 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5172 PACKET_TracepointSource },
d914c394
SS
5173 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5174 PACKET_QAllow },
4082afcc
PA
5175 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5176 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5177 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5178 PACKET_qXfer_fdpic },
169081d0
TG
5179 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5180 PACKET_qXfer_uib },
03583c20
UW
5181 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5182 PACKET_QDisableRandomization },
d1feda86 5183 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5184 { "QTBuffer:size", PACKET_DISABLE,
5185 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5186 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5187 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5188 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5189 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5190 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5191 PACKET_qXfer_btrace },
5192 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5193 PACKET_qXfer_btrace_conf },
5194 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5195 PACKET_Qbtrace_conf_bts_size },
5196 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5197 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5198 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5199 PACKET_fork_event_feature },
5200 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5201 PACKET_vfork_event_feature },
94585166
DB
5202 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5203 PACKET_exec_event_feature },
b20a6524 5204 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5205 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5206 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5207 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5208 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
5209};
5210
c8d5aac9
L
5211static char *remote_support_xml;
5212
5213/* Register string appended to "xmlRegisters=" in qSupported query. */
5214
5215void
6e39997a 5216register_remote_support_xml (const char *xml)
c8d5aac9
L
5217{
5218#if defined(HAVE_LIBEXPAT)
5219 if (remote_support_xml == NULL)
c4f7c687 5220 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5221 else
5222 {
5223 char *copy = xstrdup (remote_support_xml + 13);
5224 char *p = strtok (copy, ",");
5225
5226 do
5227 {
5228 if (strcmp (p, xml) == 0)
5229 {
5230 /* already there */
5231 xfree (copy);
5232 return;
5233 }
5234 }
5235 while ((p = strtok (NULL, ",")) != NULL);
5236 xfree (copy);
5237
94b0dee1
PA
5238 remote_support_xml = reconcat (remote_support_xml,
5239 remote_support_xml, ",", xml,
5240 (char *) NULL);
c8d5aac9
L
5241 }
5242#endif
5243}
5244
69b6ecb0
TT
5245static void
5246remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5247{
69b6ecb0
TT
5248 if (!msg->empty ())
5249 msg->append (";");
5250 msg->append (append);
c8d5aac9
L
5251}
5252
6b8edb51
PA
5253void
5254remote_target::remote_query_supported ()
be2a5f71
DJ
5255{
5256 struct remote_state *rs = get_remote_state ();
5257 char *next;
5258 int i;
5259 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5260
5261 /* The packet support flags are handled differently for this packet
5262 than for most others. We treat an error, a disabled packet, and
5263 an empty response identically: any features which must be reported
5264 to be used will be automatically disabled. An empty buffer
5265 accomplishes this, since that is also the representation for a list
5266 containing no features. */
5267
5268 rs->buf[0] = 0;
4082afcc 5269 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5270 {
69b6ecb0 5271 std::string q;
c8d5aac9 5272
73b8c1fd 5273 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5274 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5275
f7e6eed5 5276 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5277 remote_query_supported_append (&q, "swbreak+");
f7e6eed5 5278 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5279 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5280
69b6ecb0 5281 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5282
8020350c
DB
5283 if (packet_set_cmd_state (PACKET_fork_event_feature)
5284 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5285 remote_query_supported_append (&q, "fork-events+");
8020350c
DB
5286 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5287 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5288 remote_query_supported_append (&q, "vfork-events+");
8020350c
DB
5289 if (packet_set_cmd_state (PACKET_exec_event_feature)
5290 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5291 remote_query_supported_append (&q, "exec-events+");
89245bc0 5292
750ce8d1 5293 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5294 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5295
65706a29 5296 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5297 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5298
f2faf941 5299 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5300 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5301
b35d5edb
PA
5302 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5303 the qSupported:xmlRegisters=i386 handling. */
7cc244de
PA
5304 if (remote_support_xml != NULL
5305 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
69b6ecb0 5306 remote_query_supported_append (&q, remote_support_xml);
82f73884 5307
69b6ecb0
TT
5308 q = "qSupported:" + q;
5309 putpkt (q.c_str ());
94b0dee1 5310
be2a5f71
DJ
5311 getpkt (&rs->buf, &rs->buf_size, 0);
5312
5313 /* If an error occured, warn, but do not return - just reset the
5314 buffer to empty and go on to disable features. */
5315 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5316 == PACKET_ERROR)
5317 {
5318 warning (_("Remote failure reply: %s"), rs->buf);
5319 rs->buf[0] = 0;
5320 }
5321 }
5322
5323 memset (seen, 0, sizeof (seen));
5324
5325 next = rs->buf;
5326 while (*next)
5327 {
5328 enum packet_support is_supported;
5329 char *p, *end, *name_end, *value;
5330
5331 /* First separate out this item from the rest of the packet. If
5332 there's another item after this, we overwrite the separator
5333 (terminated strings are much easier to work with). */
5334 p = next;
5335 end = strchr (p, ';');
5336 if (end == NULL)
5337 {
5338 end = p + strlen (p);
5339 next = end;
5340 }
5341 else
5342 {
89be2091
DJ
5343 *end = '\0';
5344 next = end + 1;
5345
be2a5f71
DJ
5346 if (end == p)
5347 {
5348 warning (_("empty item in \"qSupported\" response"));
5349 continue;
5350 }
be2a5f71
DJ
5351 }
5352
5353 name_end = strchr (p, '=');
5354 if (name_end)
5355 {
5356 /* This is a name=value entry. */
5357 is_supported = PACKET_ENABLE;
5358 value = name_end + 1;
5359 *name_end = '\0';
5360 }
5361 else
5362 {
5363 value = NULL;
5364 switch (end[-1])
5365 {
5366 case '+':
5367 is_supported = PACKET_ENABLE;
5368 break;
5369
5370 case '-':
5371 is_supported = PACKET_DISABLE;
5372 break;
5373
5374 case '?':
5375 is_supported = PACKET_SUPPORT_UNKNOWN;
5376 break;
5377
5378 default:
3e43a32a
MS
5379 warning (_("unrecognized item \"%s\" "
5380 "in \"qSupported\" response"), p);
be2a5f71
DJ
5381 continue;
5382 }
5383 end[-1] = '\0';
5384 }
5385
5386 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5387 if (strcmp (remote_protocol_features[i].name, p) == 0)
5388 {
5389 const struct protocol_feature *feature;
5390
5391 seen[i] = 1;
5392 feature = &remote_protocol_features[i];
6b8edb51 5393 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5394 break;
5395 }
5396 }
5397
5398 /* If we increased the packet size, make sure to increase the global
5399 buffer size also. We delay this until after parsing the entire
5400 qSupported packet, because this is the same buffer we were
5401 parsing. */
5402 if (rs->buf_size < rs->explicit_packet_size)
5403 {
5404 rs->buf_size = rs->explicit_packet_size;
224c3ddb 5405 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
5406 }
5407
5408 /* Handle the defaults for unmentioned features. */
5409 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5410 if (!seen[i])
5411 {
5412 const struct protocol_feature *feature;
5413
5414 feature = &remote_protocol_features[i];
6b8edb51 5415 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5416 }
5417}
5418
048094ac
PA
5419/* Serial QUIT handler for the remote serial descriptor.
5420
5421 Defers handling a Ctrl-C until we're done with the current
5422 command/response packet sequence, unless:
5423
5424 - We're setting up the connection. Don't send a remote interrupt
5425 request, as we're not fully synced yet. Quit immediately
5426 instead.
5427
5428 - The target has been resumed in the foreground
223ffa71 5429 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5430 packet, and we're blocked waiting for the stop reply, thus a
5431 Ctrl-C should be immediately sent to the target.
5432
5433 - We get a second Ctrl-C while still within the same serial read or
5434 write. In that case the serial is seemingly wedged --- offer to
5435 quit/disconnect.
5436
5437 - We see a second Ctrl-C without target response, after having
5438 previously interrupted the target. In that case the target/stub
5439 is probably wedged --- offer to quit/disconnect.
5440*/
5441
6b8edb51
PA
5442void
5443remote_target::remote_serial_quit_handler ()
048094ac
PA
5444{
5445 struct remote_state *rs = get_remote_state ();
5446
5447 if (check_quit_flag ())
5448 {
5449 /* If we're starting up, we're not fully synced yet. Quit
5450 immediately. */
5451 if (rs->starting_up)
5452 quit ();
5453 else if (rs->got_ctrlc_during_io)
5454 {
5455 if (query (_("The target is not responding to GDB commands.\n"
5456 "Stop debugging it? ")))
5457 remote_unpush_and_throw ();
5458 }
5459 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5460 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5461 interrupt_query ();
5462 /* All-stop protocol, and blocked waiting for stop reply. Send
5463 an interrupt request. */
223ffa71 5464 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5465 target_interrupt ();
048094ac
PA
5466 else
5467 rs->got_ctrlc_during_io = 1;
5468 }
5469}
5470
6b8edb51
PA
5471/* The remote_target that is current while the quit handler is
5472 overridden with remote_serial_quit_handler. */
5473static remote_target *curr_quit_handler_target;
5474
5475static void
5476remote_serial_quit_handler ()
5477{
5478 curr_quit_handler_target->remote_serial_quit_handler ();
5479}
5480
78a095c3
JK
5481/* Remove any of the remote.c targets from target stack. Upper targets depend
5482 on it so remove them first. */
5483
5484static void
5485remote_unpush_target (void)
5486{
915ef8b1 5487 pop_all_targets_at_and_above (process_stratum);
78a095c3 5488}
be2a5f71 5489
048094ac
PA
5490static void
5491remote_unpush_and_throw (void)
5492{
5493 remote_unpush_target ();
5494 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5495}
5496
f6ac5f3d
PA
5497void
5498remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5499{
6b8edb51 5500 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5501
c906108c 5502 if (name == 0)
8a3fe4f8 5503 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5504 "serial device is attached to the remote system\n"
8a3fe4f8 5505 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5506
2d717e4f 5507 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5508 Ask this question first, before target_preopen has a chance to kill
5509 anything. */
6b8edb51 5510 if (curr_remote != NULL && !have_inferiors ())
2d717e4f 5511 {
78a095c3
JK
5512 if (from_tty
5513 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5514 error (_("Still connected."));
5515 }
5516
78a095c3 5517 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5518 target_preopen (from_tty);
5519
ad9a8f3f 5520 remote_fileio_reset ();
1dd41f16
NS
5521 reopen_exec_file ();
5522 reread_symbols ();
5523
6b8edb51
PA
5524 remote_target *remote
5525 = (extended_p ? new extended_remote_target () : new remote_target ());
5526 target_ops_up target_holder (remote);
5527
5528 remote_state *rs = remote->get_remote_state ();
5529
5530 /* See FIXME above. */
5531 if (!target_async_permitted)
5532 rs->wait_forever_enabled_p = 1;
5533
5d93a237
TT
5534 rs->remote_desc = remote_serial_open (name);
5535 if (!rs->remote_desc)
c906108c
SS
5536 perror_with_name (name);
5537
5538 if (baud_rate != -1)
5539 {
5d93a237 5540 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5541 {
9b74d5d3
KB
5542 /* The requested speed could not be set. Error out to
5543 top level after closing remote_desc. Take care to
5544 set remote_desc to NULL to avoid closing remote_desc
5545 more than once. */
5d93a237
TT
5546 serial_close (rs->remote_desc);
5547 rs->remote_desc = NULL;
c906108c
SS
5548 perror_with_name (name);
5549 }
5550 }
5551
236af5e3 5552 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5553 serial_raw (rs->remote_desc);
c906108c
SS
5554
5555 /* If there is something sitting in the buffer we might take it as a
5556 response to a command, which would be bad. */
5d93a237 5557 serial_flush_input (rs->remote_desc);
c906108c
SS
5558
5559 if (from_tty)
5560 {
5561 puts_filtered ("Remote debugging using ");
5562 puts_filtered (name);
5563 puts_filtered ("\n");
5564 }
d9f719f1 5565
6b8edb51
PA
5566 /* Switch to using the remote target now. */
5567 push_target (remote);
5568 /* The target stack owns the target now. */
5569 target_holder.release ();
c906108c 5570
74531fed 5571 /* Register extra event sources in the event loop. */
6b8edb51 5572 rs->remote_async_inferior_event_token
74531fed 5573 = create_async_event_handler (remote_async_inferior_event_handler,
6b8edb51
PA
5574 remote);
5575 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 5576
be2a5f71
DJ
5577 /* Reset the target state; these things will be queried either by
5578 remote_query_supported or as they are needed. */
ca4f7f8b 5579 reset_all_packet_configs_support ();
74531fed 5580 rs->cached_wait_status = 0;
be2a5f71 5581 rs->explicit_packet_size = 0;
a6f3e723 5582 rs->noack_mode = 0;
82f73884 5583 rs->extended = extended_p;
e24a49d8 5584 rs->waiting_for_stop_reply = 0;
3a29589a 5585 rs->ctrlc_pending_p = 0;
048094ac 5586 rs->got_ctrlc_during_io = 0;
802188a7 5587
47f8a51d
TT
5588 rs->general_thread = not_sent_ptid;
5589 rs->continue_thread = not_sent_ptid;
262e1174 5590 rs->remote_traceframe_number = -1;
c906108c 5591
3a00c802
PA
5592 rs->last_resume_exec_dir = EXEC_FORWARD;
5593
9d1f7ab2 5594 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5595 rs->use_threadinfo_query = 1;
5596 rs->use_threadextra_query = 1;
9d1f7ab2 5597
dd194f6b 5598 rs->readahead_cache.invalidate ();
80152258 5599
c6ebd6cf 5600 if (target_async_permitted)
92d1e331 5601 {
92d1e331
DJ
5602 /* FIXME: cagney/1999-09-23: During the initial connection it is
5603 assumed that the target is already ready and able to respond to
0df8b418 5604 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5605 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5606 around this. Eventually a mechanism that allows
92d1e331 5607 wait_for_inferior() to expect/get timeouts will be
23860348 5608 implemented. */
6b8edb51 5609 rs->wait_forever_enabled_p = 0;
92d1e331
DJ
5610 }
5611
23860348 5612 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5613 no_shared_libraries (NULL, 0);
f78f6cf1 5614
74531fed
PA
5615 /* Start afresh. */
5616 init_thread_list ();
5617
36918e70 5618 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5619 target (we'd otherwise be in an inconsistent state) and then
5620 propogate the error on up the exception chain. This ensures that
5621 the caller doesn't stumble along blindly assuming that the
5622 function succeeded. The CLI doesn't have this problem but other
5623 UI's, such as MI do.
36918e70
AC
5624
5625 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5626 this function should return an error indication letting the
ce2826aa 5627 caller restore the previous state. Unfortunately the command
36918e70
AC
5628 ``target remote'' is directly wired to this function making that
5629 impossible. On a positive note, the CLI side of this problem has
5630 been fixed - the function set_cmd_context() makes it possible for
5631 all the ``target ....'' commands to share a common callback
5632 function. See cli-dump.c. */
109c3e39 5633 {
2d717e4f 5634
492d29ea 5635 TRY
04bd08de 5636 {
6b8edb51 5637 remote->start_remote (from_tty, extended_p);
04bd08de 5638 }
492d29ea 5639 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5640 {
c8d104ad
PA
5641 /* Pop the partially set up target - unless something else did
5642 already before throwing the exception. */
6b8edb51 5643 if (ex.error != TARGET_CLOSE_ERROR)
78a095c3 5644 remote_unpush_target ();
109c3e39
AC
5645 throw_exception (ex);
5646 }
492d29ea 5647 END_CATCH
109c3e39 5648 }
c906108c 5649
6b8edb51 5650 remote_btrace_reset (rs);
f4abbc16 5651
c6ebd6cf 5652 if (target_async_permitted)
6b8edb51 5653 rs->wait_forever_enabled_p = 1;
43ff13b4
JM
5654}
5655
de0d863e
DB
5656/* Detach the specified process. */
5657
6b8edb51
PA
5658void
5659remote_target::remote_detach_pid (int pid)
de0d863e
DB
5660{
5661 struct remote_state *rs = get_remote_state ();
5662
4c7333b3
PA
5663 /* This should not be necessary, but the handling for D;PID in
5664 GDBserver versions prior to 8.2 incorrectly assumes that the
5665 selected process points to the same process we're detaching,
5666 leading to misbehavior (and possibly GDBserver crashing) when it
5667 does not. Since it's easy and cheap, work around it by forcing
5668 GDBserver to select GDB's current process. */
5669 set_general_process ();
5670
de0d863e
DB
5671 if (remote_multi_process_p (rs))
5672 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5673 else
5674 strcpy (rs->buf, "D");
5675
5676 putpkt (rs->buf);
5677 getpkt (&rs->buf, &rs->buf_size, 0);
5678
5679 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5680 ;
5681 else if (rs->buf[0] == '\0')
5682 error (_("Remote doesn't know how to detach"));
5683 else
5684 error (_("Can't detach process."));
5685}
5686
5687/* This detaches a program to which we previously attached, using
5688 inferior_ptid to identify the process. After this is done, GDB
5689 can be used to debug some other program. We better not have left
5690 any breakpoints in the target program or it'll die when it hits
5691 one. */
c906108c 5692
6b8edb51 5693void
00431a78 5694remote_target::remote_detach_1 (inferior *inf, int from_tty)
c906108c 5695{
e99b03dc 5696 int pid = inferior_ptid.pid ();
d01949b6 5697 struct remote_state *rs = get_remote_state ();
de0d863e 5698 int is_fork_parent;
c906108c 5699
2d717e4f
DJ
5700 if (!target_has_execution)
5701 error (_("No process to detach from."));
5702
0f48b757 5703 target_announce_detach (from_tty);
7cee1e54 5704
c906108c 5705 /* Tell the remote target to detach. */
de0d863e 5706 remote_detach_pid (pid);
82f73884 5707
8020350c
DB
5708 /* Exit only if this is the only active inferior. */
5709 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5710 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5711
00431a78
PA
5712 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5713
de0d863e
DB
5714 /* Check to see if we are detaching a fork parent. Note that if we
5715 are detaching a fork child, tp == NULL. */
5716 is_fork_parent = (tp != NULL
5717 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5718
5719 /* If doing detach-on-fork, we don't mourn, because that will delete
5720 breakpoints that should be available for the followed inferior. */
5721 if (!is_fork_parent)
f67c0c91 5722 {
249b5733
PA
5723 /* Save the pid as a string before mourning, since that will
5724 unpush the remote target, and we need the string after. */
f2907e49 5725 std::string infpid = target_pid_to_str (ptid_t (pid));
f67c0c91
SDJ
5726
5727 target_mourn_inferior (inferior_ptid);
5728 if (print_inferior_events)
5729 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5730 inf->num, infpid.c_str ());
5731 }
de0d863e
DB
5732 else
5733 {
5734 inferior_ptid = null_ptid;
00431a78 5735 detach_inferior (current_inferior ());
de0d863e 5736 }
2d717e4f
DJ
5737}
5738
f6ac5f3d
PA
5739void
5740remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5741{
00431a78 5742 remote_detach_1 (inf, from_tty);
2d717e4f
DJ
5743}
5744
f6ac5f3d
PA
5745void
5746extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5747{
00431a78 5748 remote_detach_1 (inf, from_tty);
de0d863e
DB
5749}
5750
5751/* Target follow-fork function for remote targets. On entry, and
5752 at return, the current inferior is the fork parent.
5753
5754 Note that although this is currently only used for extended-remote,
5755 it is named remote_follow_fork in anticipation of using it for the
5756 remote target as well. */
5757
f6ac5f3d
PA
5758int
5759remote_target::follow_fork (int follow_child, int detach_fork)
de0d863e
DB
5760{
5761 struct remote_state *rs = get_remote_state ();
c269dbdb 5762 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5763
c269dbdb
DB
5764 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5765 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5766 {
5767 /* When following the parent and detaching the child, we detach
5768 the child here. For the case of following the child and
5769 detaching the parent, the detach is done in the target-
5770 independent follow fork code in infrun.c. We can't use
5771 target_detach when detaching an unfollowed child because
5772 the client side doesn't know anything about the child. */
5773 if (detach_fork && !follow_child)
5774 {
5775 /* Detach the fork child. */
5776 ptid_t child_ptid;
5777 pid_t child_pid;
5778
5779 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
e99b03dc 5780 child_pid = child_ptid.pid ();
de0d863e
DB
5781
5782 remote_detach_pid (child_pid);
de0d863e
DB
5783 }
5784 }
5785 return 0;
c906108c
SS
5786}
5787
94585166
DB
5788/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5789 in the program space of the new inferior. On entry and at return the
5790 current inferior is the exec'ing inferior. INF is the new exec'd
5791 inferior, which may be the same as the exec'ing inferior unless
5792 follow-exec-mode is "new". */
5793
f6ac5f3d
PA
5794void
5795remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
94585166
DB
5796{
5797 /* We know that this is a target file name, so if it has the "target:"
5798 prefix we strip it off before saving it in the program space. */
5799 if (is_target_filename (execd_pathname))
5800 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5801
5802 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5803}
5804
6ad8ae5c
DJ
5805/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5806
f6ac5f3d
PA
5807void
5808remote_target::disconnect (const char *args, int from_tty)
43ff13b4 5809{
43ff13b4 5810 if (args)
2d717e4f 5811 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5812
8020350c
DB
5813 /* Make sure we unpush even the extended remote targets. Calling
5814 target_mourn_inferior won't unpush, and remote_mourn won't
5815 unpush if there is more than one inferior left. */
f6ac5f3d 5816 unpush_target (this);
8020350c 5817 generic_mourn_inferior ();
2d717e4f 5818
43ff13b4
JM
5819 if (from_tty)
5820 puts_filtered ("Ending remote debugging.\n");
5821}
5822
2d717e4f
DJ
5823/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5824 be chatty about it. */
5825
f6ac5f3d
PA
5826void
5827extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
5828{
5829 struct remote_state *rs = get_remote_state ();
be86555c 5830 int pid;
96ef3384 5831 char *wait_status = NULL;
2d717e4f 5832
74164c56 5833 pid = parse_pid_to_attach (args);
2d717e4f 5834
74164c56
JK
5835 /* Remote PID can be freely equal to getpid, do not check it here the same
5836 way as in other targets. */
2d717e4f 5837
4082afcc 5838 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5839 error (_("This target does not support attaching to a process"));
5840
7cee1e54
PA
5841 if (from_tty)
5842 {
5843 char *exec_file = get_exec_file (0);
5844
5845 if (exec_file)
5846 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
f2907e49 5847 target_pid_to_str (ptid_t (pid)));
7cee1e54
PA
5848 else
5849 printf_unfiltered (_("Attaching to %s\n"),
f2907e49 5850 target_pid_to_str (ptid_t (pid)));
7cee1e54
PA
5851
5852 gdb_flush (gdb_stdout);
5853 }
5854
bba74b36 5855 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5856 putpkt (rs->buf);
5857 getpkt (&rs->buf, &rs->buf_size, 0);
5858
4082afcc
PA
5859 switch (packet_ok (rs->buf,
5860 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5861 {
4082afcc 5862 case PACKET_OK:
6efcd9a8 5863 if (!target_is_non_stop_p ())
74531fed
PA
5864 {
5865 /* Save the reply for later. */
224c3ddb 5866 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5867 strcpy (wait_status, rs->buf);
5868 }
5869 else if (strcmp (rs->buf, "OK") != 0)
5870 error (_("Attaching to %s failed with: %s"),
f2907e49 5871 target_pid_to_str (ptid_t (pid)),
74531fed 5872 rs->buf);
4082afcc
PA
5873 break;
5874 case PACKET_UNKNOWN:
5875 error (_("This target does not support attaching to a process"));
5876 default:
5877 error (_("Attaching to %s failed"),
f2907e49 5878 target_pid_to_str (ptid_t (pid)));
2d717e4f 5879 }
2d717e4f 5880
1b6e6f5c 5881 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5882
f2907e49 5883 inferior_ptid = ptid_t (pid);
79d7f229 5884
6efcd9a8 5885 if (target_is_non_stop_p ())
bad34192
PA
5886 {
5887 struct thread_info *thread;
79d7f229 5888
bad34192 5889 /* Get list of threads. */
f6ac5f3d 5890 update_thread_list ();
82f73884 5891
00431a78 5892 thread = first_thread_of_inferior (current_inferior ());
bad34192
PA
5893 if (thread)
5894 inferior_ptid = thread->ptid;
5895 else
f2907e49 5896 inferior_ptid = ptid_t (pid);
bad34192
PA
5897
5898 /* Invalidate our notion of the remote current thread. */
47f8a51d 5899 record_currthread (rs, minus_one_ptid);
bad34192 5900 }
74531fed 5901 else
bad34192
PA
5902 {
5903 /* Now, if we have thread information, update inferior_ptid. */
5904 inferior_ptid = remote_current_thread (inferior_ptid);
5905
5906 /* Add the main thread to the thread list. */
00aecdcf
PA
5907 thread_info *thr = add_thread_silent (inferior_ptid);
5908 /* Don't consider the thread stopped until we've processed the
5909 saved stop reply. */
5910 set_executing (thr->ptid, true);
bad34192 5911 }
c0a2216e 5912
96ef3384
UW
5913 /* Next, if the target can specify a description, read it. We do
5914 this before anything involving memory or registers. */
5915 target_find_description ();
5916
6efcd9a8 5917 if (!target_is_non_stop_p ())
74531fed
PA
5918 {
5919 /* Use the previously fetched status. */
5920 gdb_assert (wait_status != NULL);
5921
5922 if (target_can_async_p ())
5923 {
722247f1 5924 struct notif_event *reply
6b8edb51 5925 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 5926
722247f1 5927 push_stop_reply ((struct stop_reply *) reply);
74531fed 5928
6a3753b3 5929 target_async (1);
74531fed
PA
5930 }
5931 else
5932 {
5933 gdb_assert (wait_status != NULL);
5934 strcpy (rs->buf, wait_status);
5935 rs->cached_wait_status = 1;
5936 }
5937 }
5938 else
5939 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5940}
5941
b9c1d481
AS
5942/* Implementation of the to_post_attach method. */
5943
f6ac5f3d
PA
5944void
5945extended_remote_target::post_attach (int pid)
b9c1d481 5946{
6efcd9a8
PA
5947 /* Get text, data & bss offsets. */
5948 get_offsets ();
5949
b9c1d481
AS
5950 /* In certain cases GDB might not have had the chance to start
5951 symbol lookup up until now. This could happen if the debugged
5952 binary is not using shared libraries, the vsyscall page is not
5953 present (on Linux) and the binary itself hadn't changed since the
5954 debugging process was started. */
5955 if (symfile_objfile != NULL)
5956 remote_check_symbols();
5957}
5958
c906108c 5959\f
506fb367
DJ
5960/* Check for the availability of vCont. This function should also check
5961 the response. */
c906108c 5962
6b8edb51
PA
5963void
5964remote_target::remote_vcont_probe ()
c906108c 5965{
6b8edb51 5966 remote_state *rs = get_remote_state ();
2e9f7625 5967 char *buf;
6d820c5c 5968
2e9f7625
DJ
5969 strcpy (rs->buf, "vCont?");
5970 putpkt (rs->buf);
6d820c5c 5971 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5972 buf = rs->buf;
c906108c 5973
506fb367 5974 /* Make sure that the features we assume are supported. */
61012eef 5975 if (startswith (buf, "vCont"))
506fb367
DJ
5976 {
5977 char *p = &buf[5];
750ce8d1 5978 int support_c, support_C;
506fb367 5979
750ce8d1
YQ
5980 rs->supports_vCont.s = 0;
5981 rs->supports_vCont.S = 0;
506fb367
DJ
5982 support_c = 0;
5983 support_C = 0;
d458bd84 5984 rs->supports_vCont.t = 0;
c1e36e3e 5985 rs->supports_vCont.r = 0;
506fb367
DJ
5986 while (p && *p == ';')
5987 {
5988 p++;
5989 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5990 rs->supports_vCont.s = 1;
506fb367 5991 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5992 rs->supports_vCont.S = 1;
506fb367
DJ
5993 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5994 support_c = 1;
5995 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5996 support_C = 1;
74531fed 5997 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5998 rs->supports_vCont.t = 1;
c1e36e3e
PA
5999 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6000 rs->supports_vCont.r = 1;
506fb367
DJ
6001
6002 p = strchr (p, ';');
6003 }
c906108c 6004
750ce8d1
YQ
6005 /* If c, and C are not all supported, we can't use vCont. Clearing
6006 BUF will make packet_ok disable the packet. */
6007 if (!support_c || !support_C)
506fb367
DJ
6008 buf[0] = 0;
6009 }
c906108c 6010
444abaca 6011 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 6012}
c906108c 6013
0d8f58ca
PA
6014/* Helper function for building "vCont" resumptions. Write a
6015 resumption to P. ENDP points to one-passed-the-end of the buffer
6016 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6017 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6018 resumed thread should be single-stepped and/or signalled. If PTID
6019 equals minus_one_ptid, then all threads are resumed; if PTID
6020 represents a process, then all threads of the process are resumed;
6021 the thread to be stepped and/or signalled is given in the global
6022 INFERIOR_PTID. */
6023
6b8edb51
PA
6024char *
6025remote_target::append_resumption (char *p, char *endp,
6026 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
6027{
6028 struct remote_state *rs = get_remote_state ();
6029
a493e3e2 6030 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 6031 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
6032 else if (step
6033 /* GDB is willing to range step. */
6034 && use_range_stepping
6035 /* Target supports range stepping. */
6036 && rs->supports_vCont.r
6037 /* We don't currently support range stepping multiple
6038 threads with a wildcard (though the protocol allows it,
6039 so stubs shouldn't make an active effort to forbid
6040 it). */
0e998d96 6041 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
c1e36e3e
PA
6042 {
6043 struct thread_info *tp;
6044
d7e15655 6045 if (ptid == minus_one_ptid)
c1e36e3e
PA
6046 {
6047 /* If we don't know about the target thread's tid, then
6048 we're resuming magic_null_ptid (see caller). */
6049 tp = find_thread_ptid (magic_null_ptid);
6050 }
6051 else
6052 tp = find_thread_ptid (ptid);
6053 gdb_assert (tp != NULL);
6054
6055 if (tp->control.may_range_step)
6056 {
6057 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6058
6059 p += xsnprintf (p, endp - p, ";r%s,%s",
6060 phex_nz (tp->control.step_range_start,
6061 addr_size),
6062 phex_nz (tp->control.step_range_end,
6063 addr_size));
6064 }
6065 else
6066 p += xsnprintf (p, endp - p, ";s");
6067 }
0d8f58ca
PA
6068 else if (step)
6069 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6070 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6071 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6072 else
6073 p += xsnprintf (p, endp - p, ";c");
6074
0e998d96 6075 if (remote_multi_process_p (rs) && ptid.is_pid ())
0d8f58ca
PA
6076 {
6077 ptid_t nptid;
6078
6079 /* All (-1) threads of process. */
e99b03dc 6080 nptid = ptid_t (ptid.pid (), -1, 0);
0d8f58ca
PA
6081
6082 p += xsnprintf (p, endp - p, ":");
6083 p = write_ptid (p, endp, nptid);
6084 }
d7e15655 6085 else if (ptid != minus_one_ptid)
0d8f58ca
PA
6086 {
6087 p += xsnprintf (p, endp - p, ":");
6088 p = write_ptid (p, endp, ptid);
6089 }
6090
6091 return p;
6092}
6093
799a2abe
PA
6094/* Clear the thread's private info on resume. */
6095
6096static void
6097resume_clear_thread_private_info (struct thread_info *thread)
6098{
6099 if (thread->priv != NULL)
6100 {
7aabaf9d
SM
6101 remote_thread_info *priv = get_remote_thread_info (thread);
6102
6103 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6104 priv->watch_data_address = 0;
799a2abe
PA
6105 }
6106}
6107
e5ef252a
PA
6108/* Append a vCont continue-with-signal action for threads that have a
6109 non-zero stop signal. */
6110
6b8edb51
PA
6111char *
6112remote_target::append_pending_thread_resumptions (char *p, char *endp,
6113 ptid_t ptid)
e5ef252a
PA
6114{
6115 struct thread_info *thread;
6116
034f788c 6117 ALL_NON_EXITED_THREADS (thread)
26a57c92 6118 if (thread->ptid.matches (ptid)
d7e15655 6119 && inferior_ptid != thread->ptid
70509625 6120 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
6121 {
6122 p = append_resumption (p, endp, thread->ptid,
6123 0, thread->suspend.stop_signal);
6124 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 6125 resume_clear_thread_private_info (thread);
e5ef252a
PA
6126 }
6127
6128 return p;
6129}
6130
7b68ffbb
PA
6131/* Set the target running, using the packets that use Hc
6132 (c/s/C/S). */
6133
6b8edb51
PA
6134void
6135remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6136 gdb_signal siggnal)
7b68ffbb
PA
6137{
6138 struct remote_state *rs = get_remote_state ();
6139 struct thread_info *thread;
6140 char *buf;
6141
6142 rs->last_sent_signal = siggnal;
6143 rs->last_sent_step = step;
6144
6145 /* The c/s/C/S resume packets use Hc, so set the continue
6146 thread. */
d7e15655 6147 if (ptid == minus_one_ptid)
7b68ffbb
PA
6148 set_continue_thread (any_thread_ptid);
6149 else
6150 set_continue_thread (ptid);
6151
6152 ALL_NON_EXITED_THREADS (thread)
6153 resume_clear_thread_private_info (thread);
6154
6155 buf = rs->buf;
6b8edb51 6156 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6157 {
6158 /* We don't pass signals to the target in reverse exec mode. */
6159 if (info_verbose && siggnal != GDB_SIGNAL_0)
6160 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6161 siggnal);
6162
6163 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6164 error (_("Remote reverse-step not supported."));
6165 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6166 error (_("Remote reverse-continue not supported."));
6167
6168 strcpy (buf, step ? "bs" : "bc");
6169 }
6170 else if (siggnal != GDB_SIGNAL_0)
6171 {
6172 buf[0] = step ? 'S' : 'C';
6173 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6174 buf[2] = tohex (((int) siggnal) & 0xf);
6175 buf[3] = '\0';
6176 }
6177 else
6178 strcpy (buf, step ? "s" : "c");
6179
6180 putpkt (buf);
6181}
6182
506fb367
DJ
6183/* Resume the remote inferior by using a "vCont" packet. The thread
6184 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
6185 resumed thread should be single-stepped and/or signalled. If PTID
6186 equals minus_one_ptid, then all threads are resumed; the thread to
6187 be stepped and/or signalled is given in the global INFERIOR_PTID.
6188 This function returns non-zero iff it resumes the inferior.
44eaed12 6189
7b68ffbb
PA
6190 This function issues a strict subset of all possible vCont commands
6191 at the moment. */
44eaed12 6192
6b8edb51
PA
6193int
6194remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6195 enum gdb_signal siggnal)
506fb367
DJ
6196{
6197 struct remote_state *rs = get_remote_state ();
82f73884
PA
6198 char *p;
6199 char *endp;
44eaed12 6200
7b68ffbb 6201 /* No reverse execution actions defined for vCont. */
6b8edb51 6202 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6203 return 0;
6204
4082afcc 6205 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6206 remote_vcont_probe ();
44eaed12 6207
4082afcc 6208 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6209 return 0;
44eaed12 6210
82f73884
PA
6211 p = rs->buf;
6212 endp = rs->buf + get_remote_packet_size ();
6213
506fb367
DJ
6214 /* If we could generate a wider range of packets, we'd have to worry
6215 about overflowing BUF. Should there be a generic
6216 "multi-part-packet" packet? */
6217
0d8f58ca
PA
6218 p += xsnprintf (p, endp - p, "vCont");
6219
d7e15655 6220 if (ptid == magic_null_ptid)
c906108c 6221 {
79d7f229
PA
6222 /* MAGIC_NULL_PTID means that we don't have any active threads,
6223 so we don't have any TID numbers the inferior will
6224 understand. Make sure to only send forms that do not specify
6225 a TID. */
a9cbf802 6226 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6227 }
d7e15655 6228 else if (ptid == minus_one_ptid || ptid.is_pid ())
506fb367 6229 {
0d8f58ca
PA
6230 /* Resume all threads (of all processes, or of a single
6231 process), with preference for INFERIOR_PTID. This assumes
6232 inferior_ptid belongs to the set of all threads we are about
6233 to resume. */
a493e3e2 6234 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6235 {
0d8f58ca
PA
6236 /* Step inferior_ptid, with or without signal. */
6237 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6238 }
0d8f58ca 6239
e5ef252a
PA
6240 /* Also pass down any pending signaled resumption for other
6241 threads not the current. */
6242 p = append_pending_thread_resumptions (p, endp, ptid);
6243
0d8f58ca 6244 /* And continue others without a signal. */
a493e3e2 6245 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6246 }
6247 else
506fb367
DJ
6248 {
6249 /* Scheduler locking; resume only PTID. */
a9cbf802 6250 append_resumption (p, endp, ptid, step, siggnal);
506fb367 6251 }
c906108c 6252
82f73884
PA
6253 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6254 putpkt (rs->buf);
506fb367 6255
6efcd9a8 6256 if (target_is_non_stop_p ())
74531fed
PA
6257 {
6258 /* In non-stop, the stub replies to vCont with "OK". The stop
6259 reply will be reported asynchronously by means of a `%Stop'
6260 notification. */
6261 getpkt (&rs->buf, &rs->buf_size, 0);
6262 if (strcmp (rs->buf, "OK") != 0)
6263 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6264 }
6265
506fb367 6266 return 1;
c906108c 6267}
43ff13b4 6268
506fb367
DJ
6269/* Tell the remote machine to resume. */
6270
f6ac5f3d
PA
6271void
6272remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 6273{
d01949b6 6274 struct remote_state *rs = get_remote_state ();
43ff13b4 6275
85ad3aaf
PA
6276 /* When connected in non-stop mode, the core resumes threads
6277 individually. Resuming remote threads directly in target_resume
6278 would thus result in sending one packet per thread. Instead, to
6279 minimize roundtrip latency, here we just store the resume
6280 request; the actual remote resumption will be done in
6281 target_commit_resume / remote_commit_resume, where we'll be able
6282 to do vCont action coalescing. */
f6ac5f3d 6283 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6284 {
7aabaf9d 6285 remote_thread_info *remote_thr;
85ad3aaf 6286
d7e15655 6287 if (minus_one_ptid == ptid || ptid.is_pid ())
7aabaf9d 6288 remote_thr = get_remote_thread_info (inferior_ptid);
85ad3aaf 6289 else
7aabaf9d
SM
6290 remote_thr = get_remote_thread_info (ptid);
6291
85ad3aaf
PA
6292 remote_thr->last_resume_step = step;
6293 remote_thr->last_resume_sig = siggnal;
6294 return;
6295 }
6296
722247f1
YQ
6297 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6298 (explained in remote-notif.c:handle_notification) so
6299 remote_notif_process is not called. We need find a place where
6300 it is safe to start a 'vNotif' sequence. It is good to do it
6301 before resuming inferior, because inferior was stopped and no RSP
6302 traffic at that moment. */
6efcd9a8 6303 if (!target_is_non_stop_p ())
5965e028 6304 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6305
f6ac5f3d 6306 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6307
7b68ffbb
PA
6308 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6309 if (!remote_resume_with_vcont (ptid, step, siggnal))
6b8edb51 6310 remote_resume_with_hc (ptid, step, siggnal);
43ff13b4 6311
2acceee2 6312 /* We are about to start executing the inferior, let's register it
0df8b418
MS
6313 with the event loop. NOTE: this is the one place where all the
6314 execution commands end up. We could alternatively do this in each
23860348 6315 of the execution commands in infcmd.c. */
2acceee2
JM
6316 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6317 into infcmd.c in order to allow inferior function calls to work
23860348 6318 NOT asynchronously. */
362646f5 6319 if (target_can_async_p ())
6a3753b3 6320 target_async (1);
e24a49d8
PA
6321
6322 /* We've just told the target to resume. The remote server will
6323 wait for the inferior to stop, and then send a stop reply. In
6324 the mean time, we can't start another command/query ourselves
74531fed
PA
6325 because the stub wouldn't be ready to process it. This applies
6326 only to the base all-stop protocol, however. In non-stop (which
6327 only supports vCont), the stub replies with an "OK", and is
6328 immediate able to process further serial input. */
6efcd9a8 6329 if (!target_is_non_stop_p ())
74531fed 6330 rs->waiting_for_stop_reply = 1;
43ff13b4 6331}
85ad3aaf 6332
85ad3aaf
PA
6333static int is_pending_fork_parent_thread (struct thread_info *thread);
6334
6335/* Private per-inferior info for target remote processes. */
6336
089354bb 6337struct remote_inferior : public private_inferior
85ad3aaf
PA
6338{
6339 /* Whether we can send a wildcard vCont for this process. */
089354bb 6340 bool may_wildcard_vcont = true;
85ad3aaf
PA
6341};
6342
089354bb
SM
6343/* Get the remote private inferior data associated to INF. */
6344
6345static remote_inferior *
6346get_remote_inferior (inferior *inf)
6347{
6348 if (inf->priv == NULL)
6349 inf->priv.reset (new remote_inferior);
6350
6351 return static_cast<remote_inferior *> (inf->priv.get ());
6352}
6353
f5db4863 6354/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6355 outgoing packet buffer. This is used to send multiple vCont
6356 packets if we have more actions than would fit a single packet. */
6357
f5db4863 6358class vcont_builder
85ad3aaf 6359{
f5db4863 6360public:
6b8edb51
PA
6361 explicit vcont_builder (remote_target *remote)
6362 : m_remote (remote)
f5db4863
PA
6363 {
6364 restart ();
6365 }
6366
6367 void flush ();
6368 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6369
6370private:
6371 void restart ();
6372
6b8edb51
PA
6373 /* The remote target. */
6374 remote_target *m_remote;
6375
85ad3aaf
PA
6376 /* Pointer to the first action. P points here if no action has been
6377 appended yet. */
f5db4863 6378 char *m_first_action;
85ad3aaf
PA
6379
6380 /* Where the next action will be appended. */
f5db4863 6381 char *m_p;
85ad3aaf
PA
6382
6383 /* The end of the buffer. Must never write past this. */
f5db4863 6384 char *m_endp;
85ad3aaf
PA
6385};
6386
6387/* Prepare the outgoing buffer for a new vCont packet. */
6388
f5db4863
PA
6389void
6390vcont_builder::restart ()
85ad3aaf 6391{
6b8edb51 6392 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6393
f5db4863 6394 m_p = rs->buf;
6b8edb51 6395 m_endp = rs->buf + m_remote->get_remote_packet_size ();
f5db4863
PA
6396 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6397 m_first_action = m_p;
85ad3aaf
PA
6398}
6399
6400/* If the vCont packet being built has any action, send it to the
6401 remote end. */
6402
f5db4863
PA
6403void
6404vcont_builder::flush ()
85ad3aaf
PA
6405{
6406 struct remote_state *rs;
6407
f5db4863 6408 if (m_p == m_first_action)
85ad3aaf
PA
6409 return;
6410
6b8edb51
PA
6411 rs = m_remote->get_remote_state ();
6412 m_remote->putpkt (rs->buf);
6413 m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
85ad3aaf
PA
6414 if (strcmp (rs->buf, "OK") != 0)
6415 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6416}
6417
6418/* The largest action is range-stepping, with its two addresses. This
6419 is more than sufficient. If a new, bigger action is created, it'll
6420 quickly trigger a failed assertion in append_resumption (and we'll
6421 just bump this). */
6422#define MAX_ACTION_SIZE 200
6423
6424/* Append a new vCont action in the outgoing packet being built. If
6425 the action doesn't fit the packet along with previous actions, push
6426 what we've got so far to the remote end and start over a new vCont
6427 packet (with the new action). */
6428
f5db4863
PA
6429void
6430vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6431{
6432 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6433
6b8edb51
PA
6434 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6435 ptid, step, siggnal);
85ad3aaf
PA
6436
6437 /* Check whether this new action would fit in the vCont packet along
6438 with previous actions. If not, send what we've got so far and
6439 start a new vCont packet. */
f5db4863
PA
6440 size_t rsize = endp - buf;
6441 if (rsize > m_endp - m_p)
85ad3aaf 6442 {
f5db4863
PA
6443 flush ();
6444 restart ();
85ad3aaf
PA
6445
6446 /* Should now fit. */
f5db4863 6447 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6448 }
6449
f5db4863
PA
6450 memcpy (m_p, buf, rsize);
6451 m_p += rsize;
6452 *m_p = '\0';
85ad3aaf
PA
6453}
6454
6455/* to_commit_resume implementation. */
6456
f6ac5f3d
PA
6457void
6458remote_target::commit_resume ()
85ad3aaf 6459{
85ad3aaf
PA
6460 struct inferior *inf;
6461 struct thread_info *tp;
6462 int any_process_wildcard;
6463 int may_global_wildcard_vcont;
85ad3aaf
PA
6464
6465 /* If connected in all-stop mode, we'd send the remote resume
6466 request directly from remote_resume. Likewise if
6467 reverse-debugging, as there are no defined vCont actions for
6468 reverse execution. */
f6ac5f3d 6469 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6470 return;
6471
6472 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6473 instead of resuming all threads of each process individually.
6474 However, if any thread of a process must remain halted, we can't
6475 send wildcard resumes and must send one action per thread.
6476
6477 Care must be taken to not resume threads/processes the server
6478 side already told us are stopped, but the core doesn't know about
6479 yet, because the events are still in the vStopped notification
6480 queue. For example:
6481
6482 #1 => vCont s:p1.1;c
6483 #2 <= OK
6484 #3 <= %Stopped T05 p1.1
6485 #4 => vStopped
6486 #5 <= T05 p1.2
6487 #6 => vStopped
6488 #7 <= OK
6489 #8 (infrun handles the stop for p1.1 and continues stepping)
6490 #9 => vCont s:p1.1;c
6491
6492 The last vCont above would resume thread p1.2 by mistake, because
6493 the server has no idea that the event for p1.2 had not been
6494 handled yet.
6495
6496 The server side must similarly ignore resume actions for the
6497 thread that has a pending %Stopped notification (and any other
6498 threads with events pending), until GDB acks the notification
6499 with vStopped. Otherwise, e.g., the following case is
6500 mishandled:
6501
6502 #1 => g (or any other packet)
6503 #2 <= [registers]
6504 #3 <= %Stopped T05 p1.2
6505 #4 => vCont s:p1.1;c
6506 #5 <= OK
6507
6508 Above, the server must not resume thread p1.2. GDB can't know
6509 that p1.2 stopped until it acks the %Stopped notification, and
6510 since from GDB's perspective all threads should be running, it
6511 sends a "c" action.
6512
6513 Finally, special care must also be given to handling fork/vfork
6514 events. A (v)fork event actually tells us that two processes
6515 stopped -- the parent and the child. Until we follow the fork,
6516 we must not resume the child. Therefore, if we have a pending
6517 fork follow, we must not send a global wildcard resume action
6518 (vCont;c). We can still send process-wide wildcards though. */
6519
6520 /* Start by assuming a global wildcard (vCont;c) is possible. */
6521 may_global_wildcard_vcont = 1;
6522
6523 /* And assume every process is individually wildcard-able too. */
6524 ALL_NON_EXITED_INFERIORS (inf)
6525 {
089354bb
SM
6526 remote_inferior *priv = get_remote_inferior (inf);
6527
6528 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6529 }
6530
6531 /* Check for any pending events (not reported or processed yet) and
6532 disable process and global wildcard resumes appropriately. */
6533 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6534
6535 ALL_NON_EXITED_THREADS (tp)
6536 {
6537 /* If a thread of a process is not meant to be resumed, then we
6538 can't wildcard that process. */
6539 if (!tp->executing)
6540 {
089354bb 6541 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6542
6543 /* And if we can't wildcard a process, we can't wildcard
6544 everything either. */
6545 may_global_wildcard_vcont = 0;
6546 continue;
6547 }
6548
6549 /* If a thread is the parent of an unfollowed fork, then we
6550 can't do a global wildcard, as that would resume the fork
6551 child. */
6552 if (is_pending_fork_parent_thread (tp))
6553 may_global_wildcard_vcont = 0;
6554 }
6555
6556 /* Now let's build the vCont packet(s). Actions must be appended
6557 from narrower to wider scopes (thread -> process -> global). If
6558 we end up with too many actions for a single packet vcont_builder
6559 flushes the current vCont packet to the remote side and starts a
6560 new one. */
6b8edb51 6561 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
6562
6563 /* Threads first. */
6564 ALL_NON_EXITED_THREADS (tp)
6565 {
7aabaf9d 6566 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf
PA
6567
6568 if (!tp->executing || remote_thr->vcont_resumed)
6569 continue;
6570
6571 gdb_assert (!thread_is_in_step_over_chain (tp));
6572
6573 if (!remote_thr->last_resume_step
6574 && remote_thr->last_resume_sig == GDB_SIGNAL_0
089354bb 6575 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
85ad3aaf
PA
6576 {
6577 /* We'll send a wildcard resume instead. */
6578 remote_thr->vcont_resumed = 1;
6579 continue;
6580 }
6581
f5db4863 6582 vcont_builder.push_action (tp->ptid,
85ad3aaf
PA
6583 remote_thr->last_resume_step,
6584 remote_thr->last_resume_sig);
6585 remote_thr->vcont_resumed = 1;
6586 }
6587
6588 /* Now check whether we can send any process-wide wildcard. This is
6589 to avoid sending a global wildcard in the case nothing is
6590 supposed to be resumed. */
6591 any_process_wildcard = 0;
6592
6593 ALL_NON_EXITED_INFERIORS (inf)
6594 {
089354bb 6595 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf
PA
6596 {
6597 any_process_wildcard = 1;
6598 break;
6599 }
6600 }
6601
6602 if (any_process_wildcard)
6603 {
6604 /* If all processes are wildcard-able, then send a single "c"
6605 action, otherwise, send an "all (-1) threads of process"
6606 continue action for each running process, if any. */
6607 if (may_global_wildcard_vcont)
6608 {
f5db4863
PA
6609 vcont_builder.push_action (minus_one_ptid,
6610 false, GDB_SIGNAL_0);
85ad3aaf
PA
6611 }
6612 else
6613 {
6614 ALL_NON_EXITED_INFERIORS (inf)
6615 {
089354bb 6616 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6617 {
f2907e49 6618 vcont_builder.push_action (ptid_t (inf->pid),
f5db4863 6619 false, GDB_SIGNAL_0);
85ad3aaf
PA
6620 }
6621 }
6622 }
6623 }
6624
f5db4863 6625 vcont_builder.flush ();
85ad3aaf
PA
6626}
6627
c906108c 6628\f
43ff13b4 6629
74531fed
PA
6630/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6631 thread, all threads of a remote process, or all threads of all
6632 processes. */
6633
6b8edb51
PA
6634void
6635remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
6636{
6637 struct remote_state *rs = get_remote_state ();
6638 char *p = rs->buf;
6639 char *endp = rs->buf + get_remote_packet_size ();
74531fed 6640
4082afcc 6641 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6642 remote_vcont_probe ();
74531fed 6643
d458bd84 6644 if (!rs->supports_vCont.t)
74531fed
PA
6645 error (_("Remote server does not support stopping threads"));
6646
d7e15655 6647 if (ptid == minus_one_ptid
0e998d96 6648 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
74531fed
PA
6649 p += xsnprintf (p, endp - p, "vCont;t");
6650 else
6651 {
6652 ptid_t nptid;
6653
74531fed
PA
6654 p += xsnprintf (p, endp - p, "vCont;t:");
6655
0e998d96 6656 if (ptid.is_pid ())
74531fed 6657 /* All (-1) threads of process. */
e99b03dc 6658 nptid = ptid_t (ptid.pid (), -1, 0);
74531fed
PA
6659 else
6660 {
6661 /* Small optimization: if we already have a stop reply for
6662 this thread, no use in telling the stub we want this
6663 stopped. */
6664 if (peek_stop_reply (ptid))
6665 return;
6666
6667 nptid = ptid;
6668 }
6669
a9cbf802 6670 write_ptid (p, endp, nptid);
74531fed
PA
6671 }
6672
6673 /* In non-stop, we get an immediate OK reply. The stop reply will
6674 come in asynchronously by notification. */
6675 putpkt (rs->buf);
6676 getpkt (&rs->buf, &rs->buf_size, 0);
6677 if (strcmp (rs->buf, "OK") != 0)
6678 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6679}
6680
bfedc46a
PA
6681/* All-stop version of target_interrupt. Sends a break or a ^C to
6682 interrupt the remote target. It is undefined which thread of which
6683 process reports the interrupt. */
74531fed 6684
6b8edb51
PA
6685void
6686remote_target::remote_interrupt_as ()
74531fed
PA
6687{
6688 struct remote_state *rs = get_remote_state ();
6689
3a29589a
DJ
6690 rs->ctrlc_pending_p = 1;
6691
74531fed
PA
6692 /* If the inferior is stopped already, but the core didn't know
6693 about it yet, just ignore the request. The cached wait status
6694 will be collected in remote_wait. */
6695 if (rs->cached_wait_status)
6696 return;
6697
9a7071a8
JB
6698 /* Send interrupt_sequence to remote target. */
6699 send_interrupt_sequence ();
74531fed
PA
6700}
6701
de979965
PA
6702/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6703 the remote target. It is undefined which thread of which process
e42de8c7
PA
6704 reports the interrupt. Throws an error if the packet is not
6705 supported by the server. */
de979965 6706
6b8edb51
PA
6707void
6708remote_target::remote_interrupt_ns ()
de979965
PA
6709{
6710 struct remote_state *rs = get_remote_state ();
6711 char *p = rs->buf;
6712 char *endp = rs->buf + get_remote_packet_size ();
6713
6714 xsnprintf (p, endp - p, "vCtrlC");
6715
6716 /* In non-stop, we get an immediate OK reply. The stop reply will
6717 come in asynchronously by notification. */
6718 putpkt (rs->buf);
6719 getpkt (&rs->buf, &rs->buf_size, 0);
6720
6721 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6722 {
6723 case PACKET_OK:
6724 break;
6725 case PACKET_UNKNOWN:
e42de8c7 6726 error (_("No support for interrupting the remote target."));
de979965
PA
6727 case PACKET_ERROR:
6728 error (_("Interrupting target failed: %s"), rs->buf);
6729 }
de979965
PA
6730}
6731
bfedc46a 6732/* Implement the to_stop function for the remote targets. */
74531fed 6733
f6ac5f3d
PA
6734void
6735remote_target::stop (ptid_t ptid)
c906108c 6736{
7a292a7a 6737 if (remote_debug)
0f71a2f6 6738 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6739
6efcd9a8 6740 if (target_is_non_stop_p ())
74531fed 6741 remote_stop_ns (ptid);
c906108c 6742 else
bfedc46a
PA
6743 {
6744 /* We don't currently have a way to transparently pause the
6745 remote target in all-stop mode. Interrupt it instead. */
de979965 6746 remote_interrupt_as ();
bfedc46a
PA
6747 }
6748}
6749
6750/* Implement the to_interrupt function for the remote targets. */
6751
f6ac5f3d
PA
6752void
6753remote_target::interrupt ()
bfedc46a
PA
6754{
6755 if (remote_debug)
6756 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6757
e42de8c7
PA
6758 if (target_is_non_stop_p ())
6759 remote_interrupt_ns ();
bfedc46a 6760 else
e42de8c7 6761 remote_interrupt_as ();
c906108c
SS
6762}
6763
93692b58
PA
6764/* Implement the to_pass_ctrlc function for the remote targets. */
6765
f6ac5f3d
PA
6766void
6767remote_target::pass_ctrlc ()
93692b58
PA
6768{
6769 struct remote_state *rs = get_remote_state ();
6770
6771 if (remote_debug)
6772 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6773
6774 /* If we're starting up, we're not fully synced yet. Quit
6775 immediately. */
6776 if (rs->starting_up)
6777 quit ();
6778 /* If ^C has already been sent once, offer to disconnect. */
6779 else if (rs->ctrlc_pending_p)
6780 interrupt_query ();
6781 else
e671cd59 6782 target_interrupt ();
93692b58
PA
6783}
6784
c906108c
SS
6785/* Ask the user what to do when an interrupt is received. */
6786
6b8edb51
PA
6787void
6788remote_target::interrupt_query ()
c906108c 6789{
abc56d60 6790 struct remote_state *rs = get_remote_state ();
c906108c 6791
abc56d60 6792 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6793 {
abc56d60
PA
6794 if (query (_("The target is not responding to interrupt requests.\n"
6795 "Stop debugging it? ")))
74531fed 6796 {
78a095c3 6797 remote_unpush_target ();
abc56d60 6798 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6799 }
6800 }
abc56d60
PA
6801 else
6802 {
6803 if (query (_("Interrupted while waiting for the program.\n"
6804 "Give up waiting? ")))
6805 quit ();
6806 }
c906108c
SS
6807}
6808
6426a772
JM
6809/* Enable/disable target terminal ownership. Most targets can use
6810 terminal groups to control terminal ownership. Remote targets are
6811 different in that explicit transfer of ownership to/from GDB/target
23860348 6812 is required. */
6426a772 6813
f6ac5f3d
PA
6814void
6815remote_target::terminal_inferior ()
6426a772 6816{
6426a772
JM
6817 /* NOTE: At this point we could also register our selves as the
6818 recipient of all input. Any characters typed could then be
23860348 6819 passed on down to the target. */
6426a772
JM
6820}
6821
f6ac5f3d
PA
6822void
6823remote_target::terminal_ours ()
6426a772 6824{
6426a772
JM
6825}
6826
176a6961 6827static void
917317f4 6828remote_console_output (char *msg)
c906108c
SS
6829{
6830 char *p;
6831
c5aa993b 6832 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6833 {
6834 char tb[2];
6835 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6836
c906108c
SS
6837 tb[0] = c;
6838 tb[1] = 0;
43ff13b4 6839 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6840 }
00db5b94
PA
6841 gdb_flush (gdb_stdtarg);
6842}
74531fed 6843
74531fed
PA
6844DEF_VEC_O(cached_reg_t);
6845
722247f1 6846typedef struct stop_reply
74531fed 6847{
722247f1 6848 struct notif_event base;
74531fed 6849
722247f1 6850 /* The identifier of the thread about this event */
74531fed
PA
6851 ptid_t ptid;
6852
340e3c99 6853 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6854 connection, represented by a remote_state object, is closed,
6855 all the associated stop_reply events should be released. */
6856 struct remote_state *rs;
6857
74531fed
PA
6858 struct target_waitstatus ws;
6859
5cd63fda
PA
6860 /* The architecture associated with the expedited registers. */
6861 gdbarch *arch;
6862
15148d6a
PA
6863 /* Expedited registers. This makes remote debugging a bit more
6864 efficient for those targets that provide critical registers as
6865 part of their normal status mechanism (as another roundtrip to
6866 fetch them is avoided). */
74531fed
PA
6867 VEC(cached_reg_t) *regcache;
6868
f7e6eed5
PA
6869 enum target_stop_reason stop_reason;
6870
74531fed
PA
6871 CORE_ADDR watch_data_address;
6872
dc146f7c 6873 int core;
722247f1 6874} *stop_reply_p;
a744cf53 6875
74531fed
PA
6876static void
6877stop_reply_xfree (struct stop_reply *r)
6878{
f48ff2a7 6879 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6880}
6881
221e1a37
PA
6882/* Return the length of the stop reply queue. */
6883
6b8edb51
PA
6884int
6885remote_target::stop_reply_queue_length ()
221e1a37 6886{
6b8edb51 6887 remote_state *rs = get_remote_state ();
953edf2b 6888 return rs->stop_reply_queue.size ();
221e1a37
PA
6889}
6890
6b8edb51
PA
6891void
6892remote_notif_stop_parse (remote_target *remote,
6893 struct notif_client *self, char *buf,
722247f1
YQ
6894 struct notif_event *event)
6895{
6b8edb51 6896 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
6897}
6898
6899static void
6b8edb51
PA
6900remote_notif_stop_ack (remote_target *remote,
6901 struct notif_client *self, char *buf,
722247f1
YQ
6902 struct notif_event *event)
6903{
6904 struct stop_reply *stop_reply = (struct stop_reply *) event;
6905
6906 /* acknowledge */
6b8edb51 6907 putpkt (remote, self->ack_command);
722247f1
YQ
6908
6909 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6b8edb51 6910 {
722247f1
YQ
6911 /* We got an unknown stop reply. */
6912 error (_("Unknown stop reply"));
6b8edb51 6913 }
722247f1 6914
6b8edb51 6915 remote->push_stop_reply (stop_reply);
722247f1
YQ
6916}
6917
6918static int
6b8edb51
PA
6919remote_notif_stop_can_get_pending_events (remote_target *remote,
6920 struct notif_client *self)
722247f1
YQ
6921{
6922 /* We can't get pending events in remote_notif_process for
6923 notification stop, and we have to do this in remote_wait_ns
6924 instead. If we fetch all queued events from stub, remote stub
6925 may exit and we have no chance to process them back in
6926 remote_wait_ns. */
6b8edb51
PA
6927 remote_state *rs = remote->get_remote_state ();
6928 mark_async_event_handler (rs->remote_async_inferior_event_token);
722247f1
YQ
6929 return 0;
6930}
6931
6932static void
6933stop_reply_dtr (struct notif_event *event)
6934{
6935 struct stop_reply *r = (struct stop_reply *) event;
d1dff226
AH
6936 cached_reg_t *reg;
6937 int ix;
6938
6939 for (ix = 0;
6940 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6941 ix++)
6942 xfree (reg->data);
722247f1
YQ
6943
6944 VEC_free (cached_reg_t, r->regcache);
6945}
6946
6947static struct notif_event *
6948remote_notif_stop_alloc_reply (void)
6949{
8d749320
SM
6950 /* We cast to a pointer to the "base class". */
6951 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6952
6953 r->dtr = stop_reply_dtr;
6954
6955 return r;
6956}
6957
6958/* A client of notification Stop. */
6959
6960struct notif_client notif_client_stop =
6961{
6962 "Stop",
6963 "vStopped",
6964 remote_notif_stop_parse,
6965 remote_notif_stop_ack,
6966 remote_notif_stop_can_get_pending_events,
6967 remote_notif_stop_alloc_reply,
f48ff2a7 6968 REMOTE_NOTIF_STOP,
722247f1
YQ
6969};
6970
85ad3aaf 6971/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6972 the pid of the process that owns the threads we want to check, or
6973 -1 if we want to check all threads. */
6974
6975static int
6976is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6977 ptid_t thread_ptid)
6978{
6979 if (ws->kind == TARGET_WAITKIND_FORKED
6980 || ws->kind == TARGET_WAITKIND_VFORKED)
6981 {
e99b03dc 6982 if (event_pid == -1 || event_pid == thread_ptid.pid ())
cbb8991c
DB
6983 return 1;
6984 }
6985
6986 return 0;
6987}
6988
85ad3aaf
PA
6989/* Return the thread's pending status used to determine whether the
6990 thread is a fork parent stopped at a fork event. */
6991
6992static struct target_waitstatus *
6993thread_pending_fork_status (struct thread_info *thread)
6994{
6995 if (thread->suspend.waitstatus_pending_p)
6996 return &thread->suspend.waitstatus;
6997 else
6998 return &thread->pending_follow;
6999}
7000
7001/* Determine if THREAD is a pending fork parent thread. */
7002
7003static int
7004is_pending_fork_parent_thread (struct thread_info *thread)
7005{
7006 struct target_waitstatus *ws = thread_pending_fork_status (thread);
7007 int pid = -1;
7008
7009 return is_pending_fork_parent (ws, pid, thread->ptid);
7010}
7011
cbb8991c
DB
7012/* If CONTEXT contains any fork child threads that have not been
7013 reported yet, remove them from the CONTEXT list. If such a
7014 thread exists it is because we are stopped at a fork catchpoint
7015 and have not yet called follow_fork, which will set up the
7016 host-side data structures for the new process. */
7017
6b8edb51
PA
7018void
7019remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c
DB
7020{
7021 struct thread_info * thread;
7022 int pid = -1;
7023 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
7024
7025 /* For any threads stopped at a fork event, remove the corresponding
7026 fork child threads from the CONTEXT list. */
7027 ALL_NON_EXITED_THREADS (thread)
7028 {
85ad3aaf 7029 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
7030
7031 if (is_pending_fork_parent (ws, pid, thread->ptid))
21fe1c75 7032 context->remove_thread (ws->value.related_pid);
cbb8991c
DB
7033 }
7034
7035 /* Check for any pending fork events (not reported or processed yet)
7036 in process PID and remove those fork child threads from the
7037 CONTEXT list as well. */
7038 remote_notif_get_pending_events (notif);
953edf2b
TT
7039 for (auto &event : get_remote_state ()->stop_reply_queue)
7040 if (event->ws.kind == TARGET_WAITKIND_FORKED
7041 || event->ws.kind == TARGET_WAITKIND_VFORKED
7042 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7043 context->remove_thread (event->ws.value.related_pid);
85ad3aaf
PA
7044}
7045
7046/* Check whether any event pending in the vStopped queue would prevent
7047 a global or process wildcard vCont action. Clear
7048 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7049 and clear the event inferior's may_wildcard_vcont flag if we can't
7050 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7051
6b8edb51
PA
7052void
7053remote_target::check_pending_events_prevent_wildcard_vcont
7054 (int *may_global_wildcard)
85ad3aaf
PA
7055{
7056 struct notif_client *notif = &notif_client_stop;
7057
7058 remote_notif_get_pending_events (notif);
953edf2b
TT
7059 for (auto &event : get_remote_state ()->stop_reply_queue)
7060 {
7061 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7062 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7063 continue;
85ad3aaf 7064
953edf2b
TT
7065 if (event->ws.kind == TARGET_WAITKIND_FORKED
7066 || event->ws.kind == TARGET_WAITKIND_VFORKED)
7067 *may_global_wildcard = 0;
722247f1 7068
953edf2b 7069 struct inferior *inf = find_inferior_ptid (event->ptid);
722247f1 7070
953edf2b
TT
7071 /* This may be the first time we heard about this process.
7072 Regardless, we must not do a global wildcard resume, otherwise
7073 we'd resume this process too. */
7074 *may_global_wildcard = 0;
7075 if (inf != NULL)
7076 get_remote_inferior (inf)->may_wildcard_vcont = false;
722247f1 7077 }
722247f1
YQ
7078}
7079
f48ff2a7 7080/* Discard all pending stop replies of inferior INF. */
c906108c 7081
6b8edb51
PA
7082void
7083remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7084{
f48ff2a7
YQ
7085 struct stop_reply *reply;
7086 struct remote_state *rs = get_remote_state ();
7087 struct remote_notif_state *rns = rs->notif_state;
7088
7089 /* This function can be notified when an inferior exists. When the
7090 target is not remote, the notification state is NULL. */
7091 if (rs->remote_desc == NULL)
7092 return;
7093
7094 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7095
74531fed 7096 /* Discard the in-flight notification. */
e99b03dc 7097 if (reply != NULL && reply->ptid.pid () == inf->pid)
74531fed 7098 {
722247f1 7099 stop_reply_xfree (reply);
f48ff2a7 7100 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 7101 }
c906108c 7102
74531fed
PA
7103 /* Discard the stop replies we have already pulled with
7104 vStopped. */
953edf2b
TT
7105 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7106 rs->stop_reply_queue.end (),
7107 [=] (const stop_reply_up &event)
7108 {
7109 return event->ptid.pid () == inf->pid;
7110 });
7111 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
bcc75809
YQ
7112}
7113
7114/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7115
6b8edb51
PA
7116void
7117remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7118{
6b8edb51 7119 remote_state *rs = get_remote_state ();
f48ff2a7 7120
f48ff2a7
YQ
7121 /* Discard the stop replies we have already pulled with
7122 vStopped. */
953edf2b
TT
7123 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7124 rs->stop_reply_queue.end (),
7125 [=] (const stop_reply_up &event)
7126 {
7127 return event->rs == rs;
7128 });
7129 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
74531fed 7130}
43ff13b4 7131
722247f1
YQ
7132/* Remove the first reply in 'stop_reply_queue' which matches
7133 PTID. */
2e9f7625 7134
6b8edb51
PA
7135struct stop_reply *
7136remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7137{
953edf2b 7138 remote_state *rs = get_remote_state ();
722247f1 7139
953edf2b
TT
7140 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7141 rs->stop_reply_queue.end (),
7142 [=] (const stop_reply_up &event)
7143 {
7144 return event->ptid.matches (ptid);
7145 });
7146 struct stop_reply *result;
7147 if (iter == rs->stop_reply_queue.end ())
7148 result = nullptr;
7149 else
7150 {
7151 result = iter->release ();
7152 rs->stop_reply_queue.erase (iter);
7153 }
722247f1 7154
722247f1
YQ
7155 if (notif_debug)
7156 fprintf_unfiltered (gdb_stdlog,
7157 "notif: discard queued event: 'Stop' in %s\n",
7158 target_pid_to_str (ptid));
a744cf53 7159
953edf2b 7160 return result;
74531fed 7161}
75c99385 7162
74531fed
PA
7163/* Look for a queued stop reply belonging to PTID. If one is found,
7164 remove it from the queue, and return it. Returns NULL if none is
7165 found. If there are still queued events left to process, tell the
7166 event loop to get back to target_wait soon. */
e24a49d8 7167
6b8edb51
PA
7168struct stop_reply *
7169remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7170{
953edf2b 7171 remote_state *rs = get_remote_state ();
722247f1 7172 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7173
953edf2b 7174 if (!rs->stop_reply_queue.empty ())
6b8edb51 7175 {
6b8edb51
PA
7176 /* There's still at least an event left. */
7177 mark_async_event_handler (rs->remote_async_inferior_event_token);
7178 }
74531fed 7179
722247f1 7180 return r;
74531fed
PA
7181}
7182
7183/* Push a fully parsed stop reply in the stop reply queue. Since we
7184 know that we now have at least one queued event left to pass to the
7185 core side, tell the event loop to get back to target_wait soon. */
7186
6b8edb51
PA
7187void
7188remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7189{
6b8edb51 7190 remote_state *rs = get_remote_state ();
953edf2b 7191 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
74531fed 7192
722247f1
YQ
7193 if (notif_debug)
7194 fprintf_unfiltered (gdb_stdlog,
7195 "notif: push 'Stop' %s to queue %d\n",
7196 target_pid_to_str (new_event->ptid),
953edf2b 7197 int (rs->stop_reply_queue.size ()));
74531fed 7198
6b8edb51 7199 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
7200}
7201
7202/* Returns true if we have a stop reply for PTID. */
7203
6b8edb51
PA
7204int
7205remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7206{
6b8edb51 7207 remote_state *rs = get_remote_state ();
953edf2b
TT
7208 for (auto &event : rs->stop_reply_queue)
7209 if (ptid == event->ptid
7210 && event->ws.kind == TARGET_WAITKIND_STOPPED)
7211 return 1;
7212 return 0;
74531fed
PA
7213}
7214
26d56a93
SL
7215/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7216 starting with P and ending with PEND matches PREFIX. */
7217
7218static int
7219strprefix (const char *p, const char *pend, const char *prefix)
7220{
7221 for ( ; p < pend; p++, prefix++)
7222 if (*p != *prefix)
7223 return 0;
7224 return *prefix == '\0';
7225}
7226
74531fed
PA
7227/* Parse the stop reply in BUF. Either the function succeeds, and the
7228 result is stored in EVENT, or throws an error. */
7229
6b8edb51
PA
7230void
7231remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
74531fed 7232{
5cd63fda 7233 remote_arch_state *rsa = NULL;
74531fed 7234 ULONGEST addr;
256642e8 7235 const char *p;
94585166 7236 int skipregs = 0;
74531fed
PA
7237
7238 event->ptid = null_ptid;
bcc75809 7239 event->rs = get_remote_state ();
74531fed
PA
7240 event->ws.kind = TARGET_WAITKIND_IGNORE;
7241 event->ws.value.integer = 0;
f7e6eed5 7242 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 7243 event->regcache = NULL;
dc146f7c 7244 event->core = -1;
74531fed
PA
7245
7246 switch (buf[0])
7247 {
7248 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7249 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7250 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7251 ss = signal number
7252 n... = register number
7253 r... = register contents
7254 */
7255
7256 p = &buf[3]; /* after Txx */
7257 while (*p)
7258 {
256642e8 7259 const char *p1;
cea39f65 7260 int fieldsize;
43ff13b4 7261
1f10ba14
PA
7262 p1 = strchr (p, ':');
7263 if (p1 == NULL)
7264 error (_("Malformed packet(a) (missing colon): %s\n\
7265Packet: '%s'\n"),
7266 p, buf);
7267 if (p == p1)
7268 error (_("Malformed packet(a) (missing register number): %s\n\
7269Packet: '%s'\n"),
7270 p, buf);
3c3bea1c 7271
1f10ba14
PA
7272 /* Some "registers" are actually extended stop information.
7273 Note if you're adding a new entry here: GDB 7.9 and
7274 earlier assume that all register "numbers" that start
7275 with an hex digit are real register numbers. Make sure
7276 the server only sends such a packet if it knows the
7277 client understands it. */
c8e38a49 7278
26d56a93 7279 if (strprefix (p, p1, "thread"))
1f10ba14 7280 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7281 else if (strprefix (p, p1, "syscall_entry"))
7282 {
7283 ULONGEST sysno;
7284
7285 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7286 p = unpack_varlen_hex (++p1, &sysno);
7287 event->ws.value.syscall_number = (int) sysno;
7288 }
7289 else if (strprefix (p, p1, "syscall_return"))
7290 {
7291 ULONGEST sysno;
7292
7293 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7294 p = unpack_varlen_hex (++p1, &sysno);
7295 event->ws.value.syscall_number = (int) sysno;
7296 }
26d56a93
SL
7297 else if (strprefix (p, p1, "watch")
7298 || strprefix (p, p1, "rwatch")
7299 || strprefix (p, p1, "awatch"))
cea39f65 7300 {
f7e6eed5 7301 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7302 p = unpack_varlen_hex (++p1, &addr);
7303 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7304 }
26d56a93 7305 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7306 {
7307 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7308
7309 /* Make sure the stub doesn't forget to indicate support
7310 with qSupported. */
7311 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7312 error (_("Unexpected swbreak stop reason"));
7313
7314 /* The value part is documented as "must be empty",
7315 though we ignore it, in case we ever decide to make
7316 use of it in a backward compatible way. */
8424cc97 7317 p = strchrnul (p1 + 1, ';');
f7e6eed5 7318 }
26d56a93 7319 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7320 {
7321 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7322
7323 /* Make sure the stub doesn't forget to indicate support
7324 with qSupported. */
7325 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7326 error (_("Unexpected hwbreak stop reason"));
7327
7328 /* See above. */
8424cc97 7329 p = strchrnul (p1 + 1, ';');
f7e6eed5 7330 }
26d56a93 7331 else if (strprefix (p, p1, "library"))
cea39f65 7332 {
1f10ba14 7333 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 7334 p = strchrnul (p1 + 1, ';');
1f10ba14 7335 }
26d56a93 7336 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
7337 {
7338 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7339 /* p1 will indicate "begin" or "end", but it makes
7340 no difference for now, so ignore it. */
8424cc97 7341 p = strchrnul (p1 + 1, ';');
1f10ba14 7342 }
26d56a93 7343 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7344 {
7345 ULONGEST c;
a744cf53 7346
1f10ba14
PA
7347 p = unpack_varlen_hex (++p1, &c);
7348 event->core = c;
cea39f65 7349 }
26d56a93 7350 else if (strprefix (p, p1, "fork"))
de0d863e
DB
7351 {
7352 event->ws.value.related_pid = read_ptid (++p1, &p);
7353 event->ws.kind = TARGET_WAITKIND_FORKED;
7354 }
26d56a93 7355 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
7356 {
7357 event->ws.value.related_pid = read_ptid (++p1, &p);
7358 event->ws.kind = TARGET_WAITKIND_VFORKED;
7359 }
26d56a93 7360 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
7361 {
7362 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 7363 p = strchrnul (p1 + 1, ';');
c269dbdb 7364 }
6ab24463 7365 else if (strprefix (p, p1, "exec"))
94585166
DB
7366 {
7367 ULONGEST ignored;
7368 char pathname[PATH_MAX];
7369 int pathlen;
7370
7371 /* Determine the length of the execd pathname. */
7372 p = unpack_varlen_hex (++p1, &ignored);
7373 pathlen = (p - p1) / 2;
7374
7375 /* Save the pathname for event reporting and for
7376 the next run command. */
7377 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7378 pathname[pathlen] = '\0';
7379
7380 /* This is freed during event handling. */
7381 event->ws.value.execd_pathname = xstrdup (pathname);
7382 event->ws.kind = TARGET_WAITKIND_EXECD;
7383
7384 /* Skip the registers included in this packet, since
7385 they may be for an architecture different from the
7386 one used by the original program. */
7387 skipregs = 1;
7388 }
65706a29
PA
7389 else if (strprefix (p, p1, "create"))
7390 {
7391 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 7392 p = strchrnul (p1 + 1, ';');
65706a29 7393 }
cea39f65
MS
7394 else
7395 {
1f10ba14 7396 ULONGEST pnum;
256642e8 7397 const char *p_temp;
1f10ba14 7398
94585166
DB
7399 if (skipregs)
7400 {
8424cc97 7401 p = strchrnul (p1 + 1, ';');
94585166
DB
7402 p++;
7403 continue;
7404 }
7405
1f10ba14
PA
7406 /* Maybe a real ``P'' register number. */
7407 p_temp = unpack_varlen_hex (p, &pnum);
7408 /* If the first invalid character is the colon, we got a
7409 register number. Otherwise, it's an unknown stop
7410 reason. */
7411 if (p_temp == p1)
7412 {
5cd63fda
PA
7413 /* If we haven't parsed the event's thread yet, find
7414 it now, in order to find the architecture of the
7415 reported expedited registers. */
7416 if (event->ptid == null_ptid)
7417 {
7418 const char *thr = strstr (p1 + 1, ";thread:");
7419 if (thr != NULL)
7420 event->ptid = read_ptid (thr + strlen (";thread:"),
7421 NULL);
7422 else
3cada740
PA
7423 {
7424 /* Either the current thread hasn't changed,
7425 or the inferior is not multi-threaded.
7426 The event must be for the thread we last
7427 set as (or learned as being) current. */
7428 event->ptid = event->rs->general_thread;
7429 }
5cd63fda
PA
7430 }
7431
7432 if (rsa == NULL)
7433 {
7434 inferior *inf = (event->ptid == null_ptid
7435 ? NULL
7436 : find_inferior_ptid (event->ptid));
7437 /* If this is the first time we learn anything
7438 about this process, skip the registers
7439 included in this packet, since we don't yet
7440 know which architecture to use to parse them.
7441 We'll determine the architecture later when
7442 we process the stop reply and retrieve the
7443 target description, via
7444 remote_notice_new_inferior ->
7445 post_create_inferior. */
7446 if (inf == NULL)
7447 {
7448 p = strchrnul (p1 + 1, ';');
7449 p++;
7450 continue;
7451 }
7452
7453 event->arch = inf->gdbarch;
9d6eea31 7454 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7455 }
7456
7457 packet_reg *reg
7458 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7459 cached_reg_t cached_reg;
43ff13b4 7460
1f10ba14
PA
7461 if (reg == NULL)
7462 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7463Packet: '%s'\n"),
1f10ba14 7464 hex_string (pnum), p, buf);
c8e38a49 7465
1f10ba14 7466 cached_reg.num = reg->regnum;
d1dff226 7467 cached_reg.data = (gdb_byte *)
5cd63fda 7468 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7469
1f10ba14
PA
7470 p = p1 + 1;
7471 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7472 register_size (event->arch, reg->regnum));
1f10ba14 7473 p += 2 * fieldsize;
5cd63fda 7474 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7475 warning (_("Remote reply is too short: %s"), buf);
74531fed 7476
1f10ba14
PA
7477 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7478 }
7479 else
7480 {
7481 /* Not a number. Silently skip unknown optional
7482 info. */
8424cc97 7483 p = strchrnul (p1 + 1, ';');
1f10ba14 7484 }
cea39f65 7485 }
c8e38a49 7486
cea39f65
MS
7487 if (*p != ';')
7488 error (_("Remote register badly formatted: %s\nhere: %s"),
7489 buf, p);
7490 ++p;
7491 }
5b5596ff
PA
7492
7493 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7494 break;
7495
c8e38a49
PA
7496 /* fall through */
7497 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7498 {
7499 int sig;
7500
7501 event->ws.kind = TARGET_WAITKIND_STOPPED;
7502 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7503 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7504 event->ws.value.sig = (enum gdb_signal) sig;
7505 else
7506 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7507 }
c8e38a49 7508 break;
65706a29
PA
7509 case 'w': /* Thread exited. */
7510 {
65706a29
PA
7511 ULONGEST value;
7512
7513 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7514 p = unpack_varlen_hex (&buf[1], &value);
7515 event->ws.value.integer = value;
7516 if (*p != ';')
7517 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7518 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7519 break;
7520 }
c8e38a49
PA
7521 case 'W': /* Target exited. */
7522 case 'X':
7523 {
c8e38a49
PA
7524 int pid;
7525 ULONGEST value;
82f73884 7526
c8e38a49
PA
7527 /* GDB used to accept only 2 hex chars here. Stubs should
7528 only send more if they detect GDB supports multi-process
7529 support. */
7530 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7531
c8e38a49
PA
7532 if (buf[0] == 'W')
7533 {
7534 /* The remote process exited. */
74531fed
PA
7535 event->ws.kind = TARGET_WAITKIND_EXITED;
7536 event->ws.value.integer = value;
c8e38a49
PA
7537 }
7538 else
7539 {
7540 /* The remote process exited with a signal. */
74531fed 7541 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7542 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7543 event->ws.value.sig = (enum gdb_signal) value;
7544 else
7545 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7546 }
82f73884 7547
c8e38a49 7548 /* If no process is specified, assume inferior_ptid. */
e99b03dc 7549 pid = inferior_ptid.pid ();
c8e38a49
PA
7550 if (*p == '\0')
7551 ;
7552 else if (*p == ';')
7553 {
7554 p++;
7555
0b24eb2d 7556 if (*p == '\0')
82f73884 7557 ;
61012eef 7558 else if (startswith (p, "process:"))
82f73884 7559 {
c8e38a49 7560 ULONGEST upid;
a744cf53 7561
c8e38a49
PA
7562 p += sizeof ("process:") - 1;
7563 unpack_varlen_hex (p, &upid);
7564 pid = upid;
82f73884
PA
7565 }
7566 else
7567 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7568 }
c8e38a49
PA
7569 else
7570 error (_("unknown stop reply packet: %s"), buf);
f2907e49 7571 event->ptid = ptid_t (pid);
74531fed
PA
7572 }
7573 break;
f2faf941
PA
7574 case 'N':
7575 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7576 event->ptid = minus_one_ptid;
7577 break;
74531fed
PA
7578 }
7579
d7e15655 7580 if (target_is_non_stop_p () && event->ptid == null_ptid)
74531fed
PA
7581 error (_("No process or thread specified in stop reply: %s"), buf);
7582}
7583
722247f1
YQ
7584/* When the stub wants to tell GDB about a new notification reply, it
7585 sends a notification (%Stop, for example). Those can come it at
7586 any time, hence, we have to make sure that any pending
7587 putpkt/getpkt sequence we're making is finished, before querying
7588 the stub for more events with the corresponding ack command
7589 (vStopped, for example). E.g., if we started a vStopped sequence
7590 immediately upon receiving the notification, something like this
7591 could happen:
74531fed
PA
7592
7593 1.1) --> Hg 1
7594 1.2) <-- OK
7595 1.3) --> g
7596 1.4) <-- %Stop
7597 1.5) --> vStopped
7598 1.6) <-- (registers reply to step #1.3)
7599
7600 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7601 query.
7602
796cb314 7603 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7604 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7605 doing whatever we were doing:
7606
7607 2.1) --> Hg 1
7608 2.2) <-- OK
7609 2.3) --> g
7610 2.4) <-- %Stop
7611 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7612 2.5) <-- (registers reply to step #2.3)
7613
7614 Eventualy after step #2.5, we return to the event loop, which
7615 notices there's an event on the
7616 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7617 associated callback --- the function below. At this point, we're
7618 always safe to start a vStopped sequence. :
7619
7620 2.6) --> vStopped
7621 2.7) <-- T05 thread:2
7622 2.8) --> vStopped
7623 2.9) --> OK
7624*/
7625
722247f1 7626void
6b8edb51 7627remote_target::remote_notif_get_pending_events (notif_client *nc)
74531fed
PA
7628{
7629 struct remote_state *rs = get_remote_state ();
74531fed 7630
f48ff2a7 7631 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7632 {
722247f1
YQ
7633 if (notif_debug)
7634 fprintf_unfiltered (gdb_stdlog,
7635 "notif: process: '%s' ack pending event\n",
7636 nc->name);
74531fed 7637
722247f1 7638 /* acknowledge */
6b8edb51 7639 nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
f48ff2a7 7640 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7641
7642 while (1)
7643 {
7644 getpkt (&rs->buf, &rs->buf_size, 0);
7645 if (strcmp (rs->buf, "OK") == 0)
7646 break;
7647 else
6b8edb51 7648 remote_notif_ack (this, nc, rs->buf);
74531fed
PA
7649 }
7650 }
722247f1
YQ
7651 else
7652 {
7653 if (notif_debug)
7654 fprintf_unfiltered (gdb_stdlog,
7655 "notif: process: '%s' no pending reply\n",
7656 nc->name);
7657 }
74531fed
PA
7658}
7659
6b8edb51
PA
7660/* Wrapper around remote_target::remote_notif_get_pending_events to
7661 avoid having to export the whole remote_target class. */
7662
7663void
7664remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7665{
7666 remote->remote_notif_get_pending_events (nc);
7667}
7668
74531fed
PA
7669/* Called when it is decided that STOP_REPLY holds the info of the
7670 event that is to be returned to the core. This function always
7671 destroys STOP_REPLY. */
7672
6b8edb51
PA
7673ptid_t
7674remote_target::process_stop_reply (struct stop_reply *stop_reply,
7675 struct target_waitstatus *status)
74531fed
PA
7676{
7677 ptid_t ptid;
7678
7679 *status = stop_reply->ws;
7680 ptid = stop_reply->ptid;
7681
7682 /* If no thread/process was reported by the stub, assume the current
7683 inferior. */
d7e15655 7684 if (ptid == null_ptid)
74531fed
PA
7685 ptid = inferior_ptid;
7686
5f3563ea 7687 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7688 && status->kind != TARGET_WAITKIND_SIGNALLED
7689 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7690 {
5f3563ea
PA
7691 /* Expedited registers. */
7692 if (stop_reply->regcache)
7693 {
217f1f79 7694 struct regcache *regcache
5cd63fda 7695 = get_thread_arch_regcache (ptid, stop_reply->arch);
5f3563ea
PA
7696 cached_reg_t *reg;
7697 int ix;
7698
7699 for (ix = 0;
d1dff226 7700 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
5f3563ea 7701 ix++)
d1dff226 7702 {
73e1c03f 7703 regcache->raw_supply (reg->num, reg->data);
d1dff226
AH
7704 xfree (reg->data);
7705 }
7706
5f3563ea
PA
7707 VEC_free (cached_reg_t, stop_reply->regcache);
7708 }
74531fed 7709
1941c569 7710 remote_notice_new_inferior (ptid, 0);
7aabaf9d 7711 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
799a2abe
PA
7712 remote_thr->core = stop_reply->core;
7713 remote_thr->stop_reason = stop_reply->stop_reason;
7714 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7715 remote_thr->vcont_resumed = 0;
74531fed
PA
7716 }
7717
74531fed
PA
7718 stop_reply_xfree (stop_reply);
7719 return ptid;
7720}
7721
7722/* The non-stop mode version of target_wait. */
7723
6b8edb51
PA
7724ptid_t
7725remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7726{
7727 struct remote_state *rs = get_remote_state ();
74531fed
PA
7728 struct stop_reply *stop_reply;
7729 int ret;
fee9eda9 7730 int is_notif = 0;
74531fed
PA
7731
7732 /* If in non-stop mode, get out of getpkt even if a
7733 notification is received. */
7734
7735 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7736 0 /* forever */, &is_notif);
74531fed
PA
7737 while (1)
7738 {
fee9eda9 7739 if (ret != -1 && !is_notif)
74531fed
PA
7740 switch (rs->buf[0])
7741 {
7742 case 'E': /* Error of some sort. */
7743 /* We're out of sync with the target now. Did it continue
7744 or not? We can't tell which thread it was in non-stop,
7745 so just ignore this. */
7746 warning (_("Remote failure reply: %s"), rs->buf);
7747 break;
7748 case 'O': /* Console output. */
7749 remote_console_output (rs->buf + 1);
7750 break;
7751 default:
7752 warning (_("Invalid remote reply: %s"), rs->buf);
7753 break;
7754 }
7755
7756 /* Acknowledge a pending stop reply that may have arrived in the
7757 mean time. */
f48ff2a7 7758 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7759 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7760
7761 /* If indeed we noticed a stop reply, we're done. */
7762 stop_reply = queued_stop_reply (ptid);
7763 if (stop_reply != NULL)
7764 return process_stop_reply (stop_reply, status);
7765
47608cb1 7766 /* Still no event. If we're just polling for an event, then
74531fed 7767 return to the event loop. */
47608cb1 7768 if (options & TARGET_WNOHANG)
74531fed
PA
7769 {
7770 status->kind = TARGET_WAITKIND_IGNORE;
7771 return minus_one_ptid;
7772 }
7773
47608cb1 7774 /* Otherwise do a blocking wait. */
74531fed 7775 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7776 1 /* forever */, &is_notif);
74531fed
PA
7777 }
7778}
7779
7780/* Wait until the remote machine stops, then return, storing status in
7781 STATUS just as `wait' would. */
7782
6b8edb51
PA
7783ptid_t
7784remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
74531fed
PA
7785{
7786 struct remote_state *rs = get_remote_state ();
74531fed 7787 ptid_t event_ptid = null_ptid;
cea39f65 7788 char *buf;
74531fed
PA
7789 struct stop_reply *stop_reply;
7790
47608cb1
PA
7791 again:
7792
74531fed
PA
7793 status->kind = TARGET_WAITKIND_IGNORE;
7794 status->value.integer = 0;
7795
7796 stop_reply = queued_stop_reply (ptid);
7797 if (stop_reply != NULL)
7798 return process_stop_reply (stop_reply, status);
7799
7800 if (rs->cached_wait_status)
7801 /* Use the cached wait status, but only once. */
7802 rs->cached_wait_status = 0;
7803 else
7804 {
7805 int ret;
722247f1 7806 int is_notif;
567420d1 7807 int forever = ((options & TARGET_WNOHANG) == 0
6b8edb51 7808 && rs->wait_forever_enabled_p);
567420d1
PA
7809
7810 if (!rs->waiting_for_stop_reply)
7811 {
7812 status->kind = TARGET_WAITKIND_NO_RESUMED;
7813 return minus_one_ptid;
7814 }
74531fed 7815
74531fed
PA
7816 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7817 _never_ wait for ever -> test on target_is_async_p().
7818 However, before we do that we need to ensure that the caller
7819 knows how to take the target into/out of async mode. */
722247f1 7820 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 7821 forever, &is_notif);
722247f1
YQ
7822
7823 /* GDB gets a notification. Return to core as this event is
7824 not interesting. */
7825 if (ret != -1 && is_notif)
7826 return minus_one_ptid;
567420d1
PA
7827
7828 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7829 return minus_one_ptid;
74531fed
PA
7830 }
7831
7832 buf = rs->buf;
7833
3a29589a
DJ
7834 /* Assume that the target has acknowledged Ctrl-C unless we receive
7835 an 'F' or 'O' packet. */
7836 if (buf[0] != 'F' && buf[0] != 'O')
7837 rs->ctrlc_pending_p = 0;
7838
74531fed
PA
7839 switch (buf[0])
7840 {
7841 case 'E': /* Error of some sort. */
7842 /* We're out of sync with the target now. Did it continue or
7843 not? Not is more likely, so report a stop. */
29090fb6
LM
7844 rs->waiting_for_stop_reply = 0;
7845
74531fed
PA
7846 warning (_("Remote failure reply: %s"), buf);
7847 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7848 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7849 break;
7850 case 'F': /* File-I/O request. */
e42e5352
YQ
7851 /* GDB may access the inferior memory while handling the File-I/O
7852 request, but we don't want GDB accessing memory while waiting
7853 for a stop reply. See the comments in putpkt_binary. Set
7854 waiting_for_stop_reply to 0 temporarily. */
7855 rs->waiting_for_stop_reply = 0;
6b8edb51 7856 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
3a29589a 7857 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7858 /* GDB handled the File-I/O request, and the target is running
7859 again. Keep waiting for events. */
7860 rs->waiting_for_stop_reply = 1;
74531fed 7861 break;
f2faf941 7862 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7863 {
29090fb6
LM
7864 /* There is a stop reply to handle. */
7865 rs->waiting_for_stop_reply = 0;
7866
7867 stop_reply
6b8edb51
PA
7868 = (struct stop_reply *) remote_notif_parse (this,
7869 &notif_client_stop,
722247f1 7870 rs->buf);
74531fed 7871
74531fed 7872 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7873 break;
7874 }
7875 case 'O': /* Console output. */
7876 remote_console_output (buf + 1);
c8e38a49
PA
7877 break;
7878 case '\0':
b73be471 7879 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7880 {
7881 /* Zero length reply means that we tried 'S' or 'C' and the
7882 remote system doesn't support it. */
223ffa71 7883 target_terminal::ours_for_output ();
c8e38a49
PA
7884 printf_filtered
7885 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7886 gdb_signal_to_name (rs->last_sent_signal));
7887 rs->last_sent_signal = GDB_SIGNAL_0;
223ffa71 7888 target_terminal::inferior ();
c8e38a49 7889
f5c4fcd9
TT
7890 strcpy (buf, rs->last_sent_step ? "s" : "c");
7891 putpkt (buf);
c8e38a49 7892 break;
43ff13b4 7893 }
86a73007 7894 /* fallthrough */
c8e38a49
PA
7895 default:
7896 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7897 break;
43ff13b4 7898 }
c8e38a49 7899
f2faf941
PA
7900 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7901 return minus_one_ptid;
7902 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7903 {
7904 /* Nothing interesting happened. If we're doing a non-blocking
7905 poll, we're done. Otherwise, go back to waiting. */
7906 if (options & TARGET_WNOHANG)
7907 return minus_one_ptid;
7908 else
7909 goto again;
7910 }
74531fed
PA
7911 else if (status->kind != TARGET_WAITKIND_EXITED
7912 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884 7913 {
d7e15655 7914 if (event_ptid != null_ptid)
47f8a51d 7915 record_currthread (rs, event_ptid);
82f73884
PA
7916 else
7917 event_ptid = inferior_ptid;
43ff13b4 7918 }
74531fed
PA
7919 else
7920 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7921 record_currthread (rs, minus_one_ptid);
79d7f229 7922
82f73884 7923 return event_ptid;
43ff13b4
JM
7924}
7925
74531fed
PA
7926/* Wait until the remote machine stops, then return, storing status in
7927 STATUS just as `wait' would. */
7928
f6ac5f3d
PA
7929ptid_t
7930remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7931{
7932 ptid_t event_ptid;
7933
6efcd9a8 7934 if (target_is_non_stop_p ())
6b8edb51 7935 event_ptid = wait_ns (ptid, status, options);
74531fed 7936 else
6b8edb51 7937 event_ptid = wait_as (ptid, status, options);
c8e38a49 7938
d9d41e78 7939 if (target_is_async_p ())
c8e38a49 7940 {
6b8edb51
PA
7941 remote_state *rs = get_remote_state ();
7942
74531fed
PA
7943 /* If there are are events left in the queue tell the event loop
7944 to return here. */
953edf2b 7945 if (!rs->stop_reply_queue.empty ())
6b8edb51 7946 mark_async_event_handler (rs->remote_async_inferior_event_token);
c8e38a49 7947 }
c8e38a49
PA
7948
7949 return event_ptid;
7950}
7951
74ca34ce 7952/* Fetch a single register using a 'p' packet. */
c906108c 7953
6b8edb51
PA
7954int
7955remote_target::fetch_register_using_p (struct regcache *regcache,
7956 packet_reg *reg)
b96ec7ac 7957{
ac7936df 7958 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 7959 struct remote_state *rs = get_remote_state ();
2e9f7625 7960 char *buf, *p;
9890e433 7961 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
7962 int i;
7963
4082afcc 7964 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7965 return 0;
7966
7967 if (reg->pnum == -1)
7968 return 0;
7969
2e9f7625 7970 p = rs->buf;
fcad0fa4 7971 *p++ = 'p';
74ca34ce 7972 p += hexnumstr (p, reg->pnum);
fcad0fa4 7973 *p++ = '\0';
1f4437a4
MS
7974 putpkt (rs->buf);
7975 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7976
2e9f7625
DJ
7977 buf = rs->buf;
7978
74ca34ce
DJ
7979 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7980 {
7981 case PACKET_OK:
7982 break;
7983 case PACKET_UNKNOWN:
7984 return 0;
7985 case PACKET_ERROR:
27a9c0bf 7986 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 7987 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
7988 reg->regnum),
7989 buf);
74ca34ce 7990 }
3f9a994c
JB
7991
7992 /* If this register is unfetchable, tell the regcache. */
7993 if (buf[0] == 'x')
8480adf2 7994 {
73e1c03f 7995 regcache->raw_supply (reg->regnum, NULL);
8480adf2 7996 return 1;
b96ec7ac 7997 }
b96ec7ac 7998
3f9a994c
JB
7999 /* Otherwise, parse and supply the value. */
8000 p = buf;
8001 i = 0;
8002 while (p[0] != 0)
8003 {
8004 if (p[1] == 0)
74ca34ce 8005 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
8006
8007 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8008 p += 2;
8009 }
73e1c03f 8010 regcache->raw_supply (reg->regnum, regp);
3f9a994c 8011 return 1;
b96ec7ac
AC
8012}
8013
74ca34ce
DJ
8014/* Fetch the registers included in the target's 'g' packet. */
8015
6b8edb51
PA
8016int
8017remote_target::send_g_packet ()
c906108c 8018{
d01949b6 8019 struct remote_state *rs = get_remote_state ();
cea39f65 8020 int buf_len;
c906108c 8021
bba74b36 8022 xsnprintf (rs->buf, get_remote_packet_size (), "g");
b75abf5b
AK
8023 putpkt (rs->buf);
8024 getpkt (&rs->buf, &rs->buf_size, 0);
8025 if (packet_check_result (rs->buf) == PACKET_ERROR)
8026 error (_("Could not read registers; remote failure reply '%s'"),
8027 rs->buf);
c906108c 8028
29709017
DJ
8029 /* We can get out of synch in various cases. If the first character
8030 in the buffer is not a hex character, assume that has happened
8031 and try to fetch another packet to read. */
8032 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8033 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8034 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8035 && rs->buf[0] != 'x') /* New: unavailable register value. */
8036 {
8037 if (remote_debug)
8038 fprintf_unfiltered (gdb_stdlog,
8039 "Bad register packet; fetching a new packet\n");
8040 getpkt (&rs->buf, &rs->buf_size, 0);
8041 }
8042
74ca34ce
DJ
8043 buf_len = strlen (rs->buf);
8044
8045 /* Sanity check the received packet. */
8046 if (buf_len % 2 != 0)
8047 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
8048
8049 return buf_len / 2;
8050}
8051
6b8edb51
PA
8052void
8053remote_target::process_g_packet (struct regcache *regcache)
29709017 8054{
ac7936df 8055 struct gdbarch *gdbarch = regcache->arch ();
29709017 8056 struct remote_state *rs = get_remote_state ();
9d6eea31 8057 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8058 int i, buf_len;
8059 char *p;
8060 char *regs;
8061
8062 buf_len = strlen (rs->buf);
8063
8064 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8065 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827
SM
8066 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8067 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
74ca34ce
DJ
8068
8069 /* Save the size of the packet sent to us by the target. It is used
8070 as a heuristic when determining the max size of packets that the
8071 target can safely receive. */
8072 if (rsa->actual_register_packet_size == 0)
8073 rsa->actual_register_packet_size = buf_len;
8074
8075 /* If this is smaller than we guessed the 'g' packet would be,
8076 update our records. A 'g' reply that doesn't include a register's
8077 value implies either that the register is not available, or that
8078 the 'p' packet must be used. */
8079 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8080 {
9dc193c3 8081 long sizeof_g_packet = buf_len / 2;
74ca34ce 8082
4a22f64d 8083 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8084 {
9dc193c3
LF
8085 long offset = rsa->regs[i].offset;
8086 long reg_size = register_size (gdbarch, i);
8087
74ca34ce
DJ
8088 if (rsa->regs[i].pnum == -1)
8089 continue;
8090
9dc193c3 8091 if (offset >= sizeof_g_packet)
74ca34ce 8092 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8093 else if (offset + reg_size > sizeof_g_packet)
8094 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8095 else
74ca34ce 8096 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8097 }
9dc193c3
LF
8098
8099 /* Looks valid enough, we can assume this is the correct length
8100 for a 'g' packet. It's important not to adjust
8101 rsa->sizeof_g_packet if we have truncated registers otherwise
8102 this "if" won't be run the next time the method is called
8103 with a packet of the same size and one of the internal errors
8104 below will trigger instead. */
8105 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8106 }
b323314b 8107
224c3ddb 8108 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8109
8110 /* Unimplemented registers read as all bits zero. */
ea9c271d 8111 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8112
c906108c
SS
8113 /* Reply describes registers byte by byte, each byte encoded as two
8114 hex characters. Suck them all up, then supply them to the
8115 register cacheing/storage mechanism. */
8116
74ca34ce 8117 p = rs->buf;
ea9c271d 8118 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8119 {
74ca34ce
DJ
8120 if (p[0] == 0 || p[1] == 0)
8121 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8122 internal_error (__FILE__, __LINE__,
9b20d036 8123 _("unexpected end of 'g' packet reply"));
74ca34ce 8124
c906108c 8125 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8126 regs[i] = 0; /* 'x' */
c906108c
SS
8127 else
8128 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8129 p += 2;
8130 }
8131
a744cf53
MS
8132 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8133 {
8134 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8135 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8136
8137 if (r->in_g_packet)
8138 {
9dc193c3 8139 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
a744cf53
MS
8140 /* This shouldn't happen - we adjusted in_g_packet above. */
8141 internal_error (__FILE__, __LINE__,
9b20d036 8142 _("unexpected end of 'g' packet reply"));
a744cf53
MS
8143 else if (rs->buf[r->offset * 2] == 'x')
8144 {
8145 gdb_assert (r->offset * 2 < strlen (rs->buf));
8146 /* The register isn't available, mark it as such (at
8147 the same time setting the value to zero). */
73e1c03f 8148 regcache->raw_supply (r->regnum, NULL);
a744cf53
MS
8149 }
8150 else
73e1c03f 8151 regcache->raw_supply (r->regnum, regs + r->offset);
a744cf53
MS
8152 }
8153 }
c906108c
SS
8154}
8155
6b8edb51
PA
8156void
8157remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8158{
8159 send_g_packet ();
56be3814 8160 process_g_packet (regcache);
29709017
DJ
8161}
8162
e6e4e701
PA
8163/* Make the remote selected traceframe match GDB's selected
8164 traceframe. */
8165
6b8edb51
PA
8166void
8167remote_target::set_remote_traceframe ()
e6e4e701
PA
8168{
8169 int newnum;
262e1174 8170 struct remote_state *rs = get_remote_state ();
e6e4e701 8171
262e1174 8172 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8173 return;
8174
8175 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8176 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8177
8178 newnum = target_trace_find (tfind_number,
8179 get_traceframe_number (), 0, 0, NULL);
8180
8181 /* Should not happen. If it does, all bets are off. */
8182 if (newnum != get_traceframe_number ())
8183 warning (_("could not set remote traceframe"));
8184}
8185
f6ac5f3d
PA
8186void
8187remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8188{
ac7936df 8189 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8190 struct remote_state *rs = get_remote_state ();
8191 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8192 int i;
8193
e6e4e701 8194 set_remote_traceframe ();
222312d3 8195 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8196
8197 if (regnum >= 0)
8198 {
5cd63fda 8199 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8200
74ca34ce
DJ
8201 gdb_assert (reg != NULL);
8202
8203 /* If this register might be in the 'g' packet, try that first -
8204 we are likely to read more than one register. If this is the
8205 first 'g' packet, we might be overly optimistic about its
8206 contents, so fall back to 'p'. */
8207 if (reg->in_g_packet)
8208 {
56be3814 8209 fetch_registers_using_g (regcache);
74ca34ce
DJ
8210 if (reg->in_g_packet)
8211 return;
8212 }
8213
56be3814 8214 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8215 return;
8216
8217 /* This register is not available. */
73e1c03f 8218 regcache->raw_supply (reg->regnum, NULL);
74ca34ce
DJ
8219
8220 return;
8221 }
8222
56be3814 8223 fetch_registers_using_g (regcache);
74ca34ce 8224
5cd63fda 8225 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8226 if (!rsa->regs[i].in_g_packet)
56be3814 8227 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8228 {
8229 /* This register is not available. */
73e1c03f 8230 regcache->raw_supply (i, NULL);
74ca34ce
DJ
8231 }
8232}
8233
c906108c
SS
8234/* Prepare to store registers. Since we may send them all (using a
8235 'G' request), we have to read out the ones we don't want to change
8236 first. */
8237
f6ac5f3d
PA
8238void
8239remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8240{
9d6eea31
PA
8241 struct remote_state *rs = get_remote_state ();
8242 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8243 int i;
cf0e1e0d 8244
c906108c 8245 /* Make sure the entire registers array is valid. */
4082afcc 8246 switch (packet_support (PACKET_P))
5a2468f5
JM
8247 {
8248 case PACKET_DISABLE:
8249 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8250 /* Make sure all the necessary registers are cached. */
ac7936df 8251 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8252 if (rsa->regs[i].in_g_packet)
0b47d985 8253 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
8254 break;
8255 case PACKET_ENABLE:
8256 break;
8257 }
8258}
8259
ad10f812 8260/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8261 packet was not recognized. */
5a2468f5 8262
6b8edb51
PA
8263int
8264remote_target::store_register_using_P (const struct regcache *regcache,
8265 packet_reg *reg)
5a2468f5 8266{
ac7936df 8267 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8268 struct remote_state *rs = get_remote_state ();
5a2468f5 8269 /* Try storing a single register. */
6d820c5c 8270 char *buf = rs->buf;
9890e433 8271 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8272 char *p;
5a2468f5 8273
4082afcc 8274 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8275 return 0;
8276
8277 if (reg->pnum == -1)
8278 return 0;
8279
ea9c271d 8280 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8281 p = buf + strlen (buf);
34a79281 8282 regcache->raw_collect (reg->regnum, regp);
4a22f64d 8283 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
8284 putpkt (rs->buf);
8285 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 8286
74ca34ce
DJ
8287 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8288 {
8289 case PACKET_OK:
8290 return 1;
8291 case PACKET_ERROR:
27a9c0bf
MS
8292 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8293 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
8294 case PACKET_UNKNOWN:
8295 return 0;
8296 default:
8297 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8298 }
c906108c
SS
8299}
8300
23860348
MS
8301/* Store register REGNUM, or all registers if REGNUM == -1, from the
8302 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8303
6b8edb51
PA
8304void
8305remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8306{
d01949b6 8307 struct remote_state *rs = get_remote_state ();
9d6eea31 8308 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8309 gdb_byte *regs;
c906108c
SS
8310 char *p;
8311
193cb69f
AC
8312 /* Extract all the registers in the regcache copying them into a
8313 local buffer. */
8314 {
b323314b 8315 int i;
a744cf53 8316
224c3ddb 8317 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8318 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8319 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8320 {
ea9c271d 8321 struct packet_reg *r = &rsa->regs[i];
a744cf53 8322
b323314b 8323 if (r->in_g_packet)
34a79281 8324 regcache->raw_collect (r->regnum, regs + r->offset);
193cb69f
AC
8325 }
8326 }
c906108c
SS
8327
8328 /* Command describes registers byte by byte,
8329 each byte encoded as two hex characters. */
6d820c5c 8330 p = rs->buf;
193cb69f 8331 *p++ = 'G';
74ca34ce 8332 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
8333 putpkt (rs->buf);
8334 getpkt (&rs->buf, &rs->buf_size, 0);
8335 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
8336 error (_("Could not write registers; remote failure reply '%s'"),
8337 rs->buf);
c906108c 8338}
74ca34ce
DJ
8339
8340/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8341 of the register cache buffer. FIXME: ignores errors. */
8342
f6ac5f3d
PA
8343void
8344remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8345{
5cd63fda 8346 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8347 struct remote_state *rs = get_remote_state ();
8348 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8349 int i;
8350
e6e4e701 8351 set_remote_traceframe ();
222312d3 8352 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8353
8354 if (regnum >= 0)
8355 {
5cd63fda 8356 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8357
74ca34ce
DJ
8358 gdb_assert (reg != NULL);
8359
8360 /* Always prefer to store registers using the 'P' packet if
8361 possible; we often change only a small number of registers.
8362 Sometimes we change a larger number; we'd need help from a
8363 higher layer to know to use 'G'. */
56be3814 8364 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8365 return;
8366
8367 /* For now, don't complain if we have no way to write the
8368 register. GDB loses track of unavailable registers too
8369 easily. Some day, this may be an error. We don't have
0df8b418 8370 any way to read the register, either... */
74ca34ce
DJ
8371 if (!reg->in_g_packet)
8372 return;
8373
56be3814 8374 store_registers_using_G (regcache);
74ca34ce
DJ
8375 return;
8376 }
8377
56be3814 8378 store_registers_using_G (regcache);
74ca34ce 8379
5cd63fda 8380 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8381 if (!rsa->regs[i].in_g_packet)
56be3814 8382 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8383 /* See above for why we do not issue an error here. */
8384 continue;
8385}
c906108c
SS
8386\f
8387
8388/* Return the number of hex digits in num. */
8389
8390static int
fba45db2 8391hexnumlen (ULONGEST num)
c906108c
SS
8392{
8393 int i;
8394
8395 for (i = 0; num != 0; i++)
8396 num >>= 4;
8397
325fac50 8398 return std::max (i, 1);
c906108c
SS
8399}
8400
2df3850c 8401/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8402
8403static int
fba45db2 8404hexnumstr (char *buf, ULONGEST num)
c906108c 8405{
c906108c 8406 int len = hexnumlen (num);
a744cf53 8407
2df3850c
JM
8408 return hexnumnstr (buf, num, len);
8409}
8410
c906108c 8411
2df3850c 8412/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8413
2df3850c 8414static int
fba45db2 8415hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8416{
8417 int i;
8418
8419 buf[width] = '\0';
8420
8421 for (i = width - 1; i >= 0; i--)
c906108c 8422 {
c5aa993b 8423 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8424 num >>= 4;
8425 }
8426
2df3850c 8427 return width;
c906108c
SS
8428}
8429
23860348 8430/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8431
8432static CORE_ADDR
fba45db2 8433remote_address_masked (CORE_ADDR addr)
c906108c 8434{
883b9c6c 8435 unsigned int address_size = remote_address_size;
a744cf53 8436
911c95a5
UW
8437 /* If "remoteaddresssize" was not set, default to target address size. */
8438 if (!address_size)
f5656ead 8439 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8440
8441 if (address_size > 0
8442 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8443 {
8444 /* Only create a mask when that mask can safely be constructed
23860348 8445 in a ULONGEST variable. */
c906108c 8446 ULONGEST mask = 1;
a744cf53 8447
911c95a5 8448 mask = (mask << address_size) - 1;
c906108c
SS
8449 addr &= mask;
8450 }
8451 return addr;
8452}
8453
8454/* Determine whether the remote target supports binary downloading.
8455 This is accomplished by sending a no-op memory write of zero length
8456 to the target at the specified address. It does not suffice to send
23860348
MS
8457 the whole packet, since many stubs strip the eighth bit and
8458 subsequently compute a wrong checksum, which causes real havoc with
8459 remote_write_bytes.
7a292a7a 8460
96baa820 8461 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8462 clean. In cases like this, the user should clear "remote
23860348 8463 X-packet". */
96baa820 8464
6b8edb51
PA
8465void
8466remote_target::check_binary_download (CORE_ADDR addr)
c906108c 8467{
d01949b6 8468 struct remote_state *rs = get_remote_state ();
24b06219 8469
4082afcc 8470 switch (packet_support (PACKET_X))
c906108c 8471 {
96baa820
JM
8472 case PACKET_DISABLE:
8473 break;
8474 case PACKET_ENABLE:
8475 break;
8476 case PACKET_SUPPORT_UNKNOWN:
8477 {
96baa820 8478 char *p;
802188a7 8479
2e9f7625 8480 p = rs->buf;
96baa820
JM
8481 *p++ = 'X';
8482 p += hexnumstr (p, (ULONGEST) addr);
8483 *p++ = ',';
8484 p += hexnumstr (p, (ULONGEST) 0);
8485 *p++ = ':';
8486 *p = '\0';
802188a7 8487
2e9f7625 8488 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8489 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8490
2e9f7625 8491 if (rs->buf[0] == '\0')
96baa820
JM
8492 {
8493 if (remote_debug)
8494 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8495 "binary downloading NOT "
8496 "supported by target\n");
444abaca 8497 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8498 }
8499 else
8500 {
8501 if (remote_debug)
8502 fprintf_unfiltered (gdb_stdlog,
64b9b334 8503 "binary downloading supported by target\n");
444abaca 8504 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8505 }
8506 break;
8507 }
c906108c
SS
8508 }
8509}
8510
124e13d9
SM
8511/* Helper function to resize the payload in order to try to get a good
8512 alignment. We try to write an amount of data such that the next write will
8513 start on an address aligned on REMOTE_ALIGN_WRITES. */
8514
8515static int
8516align_for_efficient_write (int todo, CORE_ADDR memaddr)
8517{
8518 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8519}
8520
c906108c
SS
8521/* Write memory data directly to the remote machine.
8522 This does not inform the data cache; the data cache uses this.
a76d924d 8523 HEADER is the starting part of the packet.
c906108c
SS
8524 MEMADDR is the address in the remote memory space.
8525 MYADDR is the address of the buffer in our space.
124e13d9
SM
8526 LEN_UNITS is the number of addressable units to write.
8527 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8528 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8529 should send data as binary ('X'), or hex-encoded ('M').
8530
8531 The function creates packet of the form
8532 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8533
124e13d9 8534 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8535
8536 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8537 are omitted.
8538
9b409511 8539 Return the transferred status, error or OK (an
124e13d9
SM
8540 'enum target_xfer_status' value). Save the number of addressable units
8541 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8542
8543 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8544 exchange between gdb and the stub could look like (?? in place of the
8545 checksum):
8546
8547 -> $m1000,4#??
8548 <- aaaabbbbccccdddd
8549
8550 -> $M1000,3:eeeeffffeeee#??
8551 <- OK
8552
8553 -> $m1000,4#??
8554 <- eeeeffffeeeedddd */
c906108c 8555
6b8edb51
PA
8556target_xfer_status
8557remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8558 const gdb_byte *myaddr,
8559 ULONGEST len_units,
8560 int unit_size,
8561 ULONGEST *xfered_len_units,
8562 char packet_format, int use_length)
c906108c 8563{
6d820c5c 8564 struct remote_state *rs = get_remote_state ();
cfd77fa1 8565 char *p;
a76d924d
DJ
8566 char *plen = NULL;
8567 int plenlen = 0;
124e13d9
SM
8568 int todo_units;
8569 int units_written;
8570 int payload_capacity_bytes;
8571 int payload_length_bytes;
a76d924d
DJ
8572
8573 if (packet_format != 'X' && packet_format != 'M')
8574 internal_error (__FILE__, __LINE__,
9b20d036 8575 _("remote_write_bytes_aux: bad packet format"));
c906108c 8576
124e13d9 8577 if (len_units == 0)
9b409511 8578 return TARGET_XFER_EOF;
b2182ed2 8579
124e13d9 8580 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8581
6d820c5c
DJ
8582 /* The packet buffer will be large enough for the payload;
8583 get_memory_packet_size ensures this. */
a76d924d 8584 rs->buf[0] = '\0';
c906108c 8585
a257b5bb 8586 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8587 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8588
124e13d9 8589 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8590 if (!use_length)
0df8b418 8591 /* The comma won't be used. */
124e13d9
SM
8592 payload_capacity_bytes += 1;
8593 payload_capacity_bytes -= strlen (header);
8594 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8595
a76d924d 8596 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8597
a76d924d
DJ
8598 strcat (rs->buf, header);
8599 p = rs->buf + strlen (header);
8600
8601 /* Compute a best guess of the number of bytes actually transfered. */
8602 if (packet_format == 'X')
c906108c 8603 {
23860348 8604 /* Best guess at number of bytes that will fit. */
325fac50
PA
8605 todo_units = std::min (len_units,
8606 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8607 if (use_length)
124e13d9 8608 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8609 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8610 }
8611 else
8612 {
124e13d9 8613 /* Number of bytes that will fit. */
325fac50
PA
8614 todo_units
8615 = std::min (len_units,
8616 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8617 if (use_length)
124e13d9 8618 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8619 todo_units = std::min (todo_units,
8620 (payload_capacity_bytes / unit_size) / 2);
917317f4 8621 }
a76d924d 8622
124e13d9 8623 if (todo_units <= 0)
3de11b2e 8624 internal_error (__FILE__, __LINE__,
405f8e94 8625 _("minimum packet size too small to write data"));
802188a7 8626
6765f3e5
DJ
8627 /* If we already need another packet, then try to align the end
8628 of this packet to a useful boundary. */
124e13d9
SM
8629 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8630 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8631
a257b5bb 8632 /* Append "<memaddr>". */
917317f4
JM
8633 memaddr = remote_address_masked (memaddr);
8634 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8635
a76d924d
DJ
8636 if (use_length)
8637 {
8638 /* Append ",". */
8639 *p++ = ',';
802188a7 8640
124e13d9
SM
8641 /* Append the length and retain its location and size. It may need to be
8642 adjusted once the packet body has been created. */
a76d924d 8643 plen = p;
124e13d9 8644 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8645 p += plenlen;
8646 }
a257b5bb
AC
8647
8648 /* Append ":". */
917317f4
JM
8649 *p++ = ':';
8650 *p = '\0';
802188a7 8651
a257b5bb 8652 /* Append the packet body. */
a76d924d 8653 if (packet_format == 'X')
917317f4 8654 {
917317f4
JM
8655 /* Binary mode. Send target system values byte by byte, in
8656 increasing byte addresses. Only escape certain critical
8657 characters. */
124e13d9
SM
8658 payload_length_bytes =
8659 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8660 &units_written, payload_capacity_bytes);
6765f3e5 8661
124e13d9 8662 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8663 a second try to keep the end of the packet aligned. Don't do
8664 this if the packet is tiny. */
124e13d9 8665 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8666 {
124e13d9
SM
8667 int new_todo_units;
8668
8669 new_todo_units = align_for_efficient_write (units_written, memaddr);
8670
8671 if (new_todo_units != units_written)
8672 payload_length_bytes =
8673 remote_escape_output (myaddr, new_todo_units, unit_size,
8674 (gdb_byte *) p, &units_written,
8675 payload_capacity_bytes);
6765f3e5
DJ
8676 }
8677
124e13d9
SM
8678 p += payload_length_bytes;
8679 if (use_length && units_written < todo_units)
c906108c 8680 {
802188a7 8681 /* Escape chars have filled up the buffer prematurely,
124e13d9 8682 and we have actually sent fewer units than planned.
917317f4
JM
8683 Fix-up the length field of the packet. Use the same
8684 number of characters as before. */
124e13d9
SM
8685 plen += hexnumnstr (plen, (ULONGEST) units_written,
8686 plenlen);
917317f4 8687 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8688 }
a76d924d
DJ
8689 }
8690 else
8691 {
917317f4
JM
8692 /* Normal mode: Send target system values byte by byte, in
8693 increasing byte addresses. Each byte is encoded as a two hex
8694 value. */
124e13d9
SM
8695 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8696 units_written = todo_units;
c906108c 8697 }
802188a7 8698
2e9f7625 8699 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8700 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8701
2e9f7625 8702 if (rs->buf[0] == 'E')
00d84524 8703 return TARGET_XFER_E_IO;
802188a7 8704
124e13d9
SM
8705 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8706 send fewer units than we'd planned. */
8707 *xfered_len_units = (ULONGEST) units_written;
92ffd475 8708 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
8709}
8710
a76d924d
DJ
8711/* Write memory data directly to the remote machine.
8712 This does not inform the data cache; the data cache uses this.
8713 MEMADDR is the address in the remote memory space.
8714 MYADDR is the address of the buffer in our space.
8715 LEN is the number of bytes.
8716
9b409511
YQ
8717 Return the transferred status, error or OK (an
8718 'enum target_xfer_status' value). Save the number of bytes
8719 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8720
6b8edb51
PA
8721target_xfer_status
8722remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8723 ULONGEST len, int unit_size,
8724 ULONGEST *xfered_len)
a76d924d 8725{
a121b7c1 8726 const char *packet_format = NULL;
a76d924d
DJ
8727
8728 /* Check whether the target supports binary download. */
8729 check_binary_download (memaddr);
8730
4082afcc 8731 switch (packet_support (PACKET_X))
a76d924d
DJ
8732 {
8733 case PACKET_ENABLE:
8734 packet_format = "X";
8735 break;
8736 case PACKET_DISABLE:
8737 packet_format = "M";
8738 break;
8739 case PACKET_SUPPORT_UNKNOWN:
8740 internal_error (__FILE__, __LINE__,
8741 _("remote_write_bytes: bad internal state"));
8742 default:
8743 internal_error (__FILE__, __LINE__, _("bad switch"));
8744 }
8745
8746 return remote_write_bytes_aux (packet_format,
124e13d9 8747 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8748 packet_format[0], 1);
a76d924d
DJ
8749}
8750
9217e74e
YQ
8751/* Read memory data directly from the remote machine.
8752 This does not use the data cache; the data cache uses this.
8753 MEMADDR is the address in the remote memory space.
8754 MYADDR is the address of the buffer in our space.
124e13d9
SM
8755 LEN_UNITS is the number of addressable memory units to read..
8756 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8757
8758 Return the transferred status, error or OK (an
8759 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8760 transferred in *XFERED_LEN_UNITS.
8761
8762 See the comment of remote_write_bytes_aux for an example of
8763 memory read/write exchange between gdb and the stub. */
9217e74e 8764
6b8edb51
PA
8765target_xfer_status
8766remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8767 ULONGEST len_units,
8768 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8769{
8770 struct remote_state *rs = get_remote_state ();
124e13d9 8771 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8772 char *p;
124e13d9
SM
8773 int todo_units;
8774 int decoded_bytes;
9217e74e 8775
124e13d9 8776 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8777 /* The packet buffer will be large enough for the payload;
8778 get_memory_packet_size ensures this. */
8779
124e13d9 8780 /* Number of units that will fit. */
325fac50
PA
8781 todo_units = std::min (len_units,
8782 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8783
8784 /* Construct "m"<memaddr>","<len>". */
8785 memaddr = remote_address_masked (memaddr);
8786 p = rs->buf;
8787 *p++ = 'm';
8788 p += hexnumstr (p, (ULONGEST) memaddr);
8789 *p++ = ',';
124e13d9 8790 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8791 *p = '\0';
8792 putpkt (rs->buf);
8793 getpkt (&rs->buf, &rs->buf_size, 0);
8794 if (rs->buf[0] == 'E'
8795 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8796 && rs->buf[3] == '\0')
8797 return TARGET_XFER_E_IO;
8798 /* Reply describes memory byte by byte, each byte encoded as two hex
8799 characters. */
8800 p = rs->buf;
124e13d9 8801 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8802 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8803 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 8804 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
8805}
8806
b55fbac4
YQ
8807/* Using the set of read-only target sections of remote, read live
8808 read-only memory.
8acf9577
YQ
8809
8810 For interface/parameters/return description see target.h,
8811 to_xfer_partial. */
8812
6b8edb51
PA
8813target_xfer_status
8814remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8815 ULONGEST memaddr,
8816 ULONGEST len,
8817 int unit_size,
8818 ULONGEST *xfered_len)
8acf9577
YQ
8819{
8820 struct target_section *secp;
8821 struct target_section_table *table;
8822
6b8edb51 8823 secp = target_section_by_addr (this, memaddr);
8acf9577
YQ
8824 if (secp != NULL
8825 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8826 secp->the_bfd_section)
8827 & SEC_READONLY))
8828 {
8829 struct target_section *p;
8830 ULONGEST memend = memaddr + len;
8831
6b8edb51 8832 table = target_get_section_table (this);
8acf9577
YQ
8833
8834 for (p = table->sections; p < table->sections_end; p++)
8835 {
8836 if (memaddr >= p->addr)
8837 {
8838 if (memend <= p->endaddr)
8839 {
8840 /* Entire transfer is within this section. */
124e13d9 8841 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8842 xfered_len);
8acf9577
YQ
8843 }
8844 else if (memaddr >= p->endaddr)
8845 {
8846 /* This section ends before the transfer starts. */
8847 continue;
8848 }
8849 else
8850 {
8851 /* This section overlaps the transfer. Just do half. */
8852 len = p->endaddr - memaddr;
124e13d9 8853 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8854 xfered_len);
8acf9577
YQ
8855 }
8856 }
8857 }
8858 }
8859
8860 return TARGET_XFER_EOF;
8861}
8862
9217e74e
YQ
8863/* Similar to remote_read_bytes_1, but it reads from the remote stub
8864 first if the requested memory is unavailable in traceframe.
8865 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8866
6b8edb51
PA
8867target_xfer_status
8868remote_target::remote_read_bytes (CORE_ADDR memaddr,
8869 gdb_byte *myaddr, ULONGEST len, int unit_size,
8870 ULONGEST *xfered_len)
c906108c 8871{
6b6aa828 8872 if (len == 0)
96c4f946 8873 return TARGET_XFER_EOF;
b2182ed2 8874
8acf9577
YQ
8875 if (get_traceframe_number () != -1)
8876 {
a79b1bc6 8877 std::vector<mem_range> available;
8acf9577
YQ
8878
8879 /* If we fail to get the set of available memory, then the
8880 target does not support querying traceframe info, and so we
8881 attempt reading from the traceframe anyway (assuming the
8882 target implements the old QTro packet then). */
8883 if (traceframe_available_memory (&available, memaddr, len))
8884 {
a79b1bc6 8885 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
8886 {
8887 enum target_xfer_status res;
8888
8889 /* Don't read into the traceframe's available
8890 memory. */
a79b1bc6 8891 if (!available.empty ())
8acf9577
YQ
8892 {
8893 LONGEST oldlen = len;
8894
a79b1bc6 8895 len = available[0].start - memaddr;
8acf9577
YQ
8896 gdb_assert (len <= oldlen);
8897 }
8898
8acf9577 8899 /* This goes through the topmost target again. */
6b8edb51 8900 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 8901 len, unit_size, xfered_len);
8acf9577
YQ
8902 if (res == TARGET_XFER_OK)
8903 return TARGET_XFER_OK;
8904 else
8905 {
8906 /* No use trying further, we know some memory starting
8907 at MEMADDR isn't available. */
8908 *xfered_len = len;
92ffd475
PC
8909 return (*xfered_len != 0) ?
8910 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
8911 }
8912 }
8913
8914 /* Don't try to read more than how much is available, in
8915 case the target implements the deprecated QTro packet to
8916 cater for older GDBs (the target's knowledge of read-only
8917 sections may be outdated by now). */
a79b1bc6 8918 len = available[0].length;
8acf9577
YQ
8919 }
8920 }
8921
124e13d9 8922 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8923}
74531fed 8924
c906108c 8925\f
c906108c 8926
a76d924d
DJ
8927/* Sends a packet with content determined by the printf format string
8928 FORMAT and the remaining arguments, then gets the reply. Returns
8929 whether the packet was a success, a failure, or unknown. */
8930
6b8edb51
PA
8931packet_result
8932remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
8933{
8934 struct remote_state *rs = get_remote_state ();
8935 int max_size = get_remote_packet_size ();
a76d924d 8936 va_list ap;
a744cf53 8937
a76d924d
DJ
8938 va_start (ap, format);
8939
8940 rs->buf[0] = '\0';
8941 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8942 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8943
8944 if (putpkt (rs->buf) < 0)
8945 error (_("Communication problem with target."));
8946
8947 rs->buf[0] = '\0';
8948 getpkt (&rs->buf, &rs->buf_size, 0);
8949
8950 return packet_check_result (rs->buf);
8951}
8952
a76d924d
DJ
8953/* Flash writing can take quite some time. We'll set
8954 effectively infinite timeout for flash operations.
8955 In future, we'll need to decide on a better approach. */
8956static const int remote_flash_timeout = 1000;
8957
f6ac5f3d
PA
8958void
8959remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 8960{
f5656ead 8961 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 8962 enum packet_result ret;
2ec845e7
TT
8963 scoped_restore restore_timeout
8964 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
8965
8966 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8967 phex (address, addr_size),
a76d924d
DJ
8968 phex (length, 4));
8969 switch (ret)
8970 {
8971 case PACKET_UNKNOWN:
8972 error (_("Remote target does not support flash erase"));
8973 case PACKET_ERROR:
8974 error (_("Error erasing flash with vFlashErase packet"));
8975 default:
8976 break;
8977 }
a76d924d
DJ
8978}
8979
6b8edb51
PA
8980target_xfer_status
8981remote_target::remote_flash_write (ULONGEST address,
8982 ULONGEST length, ULONGEST *xfered_len,
8983 const gdb_byte *data)
a76d924d 8984{
2ec845e7
TT
8985 scoped_restore restore_timeout
8986 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8987 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8988 xfered_len,'X', 0);
a76d924d
DJ
8989}
8990
f6ac5f3d
PA
8991void
8992remote_target::flash_done ()
a76d924d 8993{
a76d924d 8994 int ret;
a76d924d 8995
2ec845e7
TT
8996 scoped_restore restore_timeout
8997 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8998
a76d924d 8999 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
9000
9001 switch (ret)
9002 {
9003 case PACKET_UNKNOWN:
9004 error (_("Remote target does not support vFlashDone"));
9005 case PACKET_ERROR:
9006 error (_("Error finishing flash operation"));
9007 default:
9008 break;
9009 }
9010}
9011
f6ac5f3d
PA
9012void
9013remote_target::files_info ()
c906108c
SS
9014{
9015 puts_filtered ("Debugging a target over a serial line.\n");
9016}
9017\f
9018/* Stuff for dealing with the packets which are part of this protocol.
9019 See comment at top of file for details. */
9020
1927e618
PA
9021/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9022 error to higher layers. Called when a serial error is detected.
9023 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
9024 the system error message for errno at function entry and final dot
9025 for output compatibility with throw_perror_with_name. */
1927e618
PA
9026
9027static void
9028unpush_and_perror (const char *string)
9029{
d6cb50a2 9030 int saved_errno = errno;
1927e618
PA
9031
9032 remote_unpush_target ();
d6cb50a2
JK
9033 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9034 safe_strerror (saved_errno));
1927e618
PA
9035}
9036
048094ac
PA
9037/* Read a single character from the remote end. The current quit
9038 handler is overridden to avoid quitting in the middle of packet
9039 sequence, as that would break communication with the remote server.
9040 See remote_serial_quit_handler for more detail. */
c906108c 9041
6b8edb51
PA
9042int
9043remote_target::readchar (int timeout)
c906108c
SS
9044{
9045 int ch;
5d93a237 9046 struct remote_state *rs = get_remote_state ();
048094ac 9047
2ec845e7 9048 {
6b8edb51
PA
9049 scoped_restore restore_quit_target
9050 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9051 scoped_restore restore_quit
6b8edb51 9052 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9053
2ec845e7 9054 rs->got_ctrlc_during_io = 0;
c906108c 9055
2ec845e7 9056 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9057
2ec845e7
TT
9058 if (rs->got_ctrlc_during_io)
9059 set_quit_flag ();
9060 }
048094ac 9061
2acceee2 9062 if (ch >= 0)
0876f84a 9063 return ch;
2acceee2
JM
9064
9065 switch ((enum serial_rc) ch)
c906108c
SS
9066 {
9067 case SERIAL_EOF:
78a095c3 9068 remote_unpush_target ();
598d3636 9069 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9070 /* no return */
c906108c 9071 case SERIAL_ERROR:
1927e618
PA
9072 unpush_and_perror (_("Remote communication error. "
9073 "Target disconnected."));
2acceee2 9074 /* no return */
c906108c 9075 case SERIAL_TIMEOUT:
2acceee2 9076 break;
c906108c 9077 }
2acceee2 9078 return ch;
c906108c
SS
9079}
9080
c33e31fd 9081/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9082 writing fails. The current quit handler is overridden to avoid
9083 quitting in the middle of packet sequence, as that would break
9084 communication with the remote server. See
9085 remote_serial_quit_handler for more detail. */
c33e31fd 9086
6b8edb51
PA
9087void
9088remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9089{
5d93a237 9090 struct remote_state *rs = get_remote_state ();
048094ac 9091
6b8edb51
PA
9092 scoped_restore restore_quit_target
9093 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9094 scoped_restore restore_quit
6b8edb51 9095 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9096
9097 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9098
9099 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9100 {
1927e618
PA
9101 unpush_and_perror (_("Remote communication error. "
9102 "Target disconnected."));
c33e31fd 9103 }
048094ac
PA
9104
9105 if (rs->got_ctrlc_during_io)
9106 set_quit_flag ();
c33e31fd
PA
9107}
9108
b3ced9ba
PA
9109/* Return a string representing an escaped version of BUF, of len N.
9110 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9111
b3ced9ba 9112static std::string
6e5abd65
PA
9113escape_buffer (const char *buf, int n)
9114{
d7e74731 9115 string_file stb;
6e5abd65 9116
d7e74731
PA
9117 stb.putstrn (buf, n, '\\');
9118 return std::move (stb.string ());
6e5abd65
PA
9119}
9120
c906108c
SS
9121/* Display a null-terminated packet on stdout, for debugging, using C
9122 string notation. */
9123
9124static void
baa336ce 9125print_packet (const char *buf)
c906108c
SS
9126{
9127 puts_filtered ("\"");
43e526b9 9128 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
9129 puts_filtered ("\"");
9130}
9131
9132int
6b8edb51 9133remote_target::putpkt (const char *buf)
c906108c
SS
9134{
9135 return putpkt_binary (buf, strlen (buf));
9136}
9137
6b8edb51
PA
9138/* Wrapper around remote_target::putpkt to avoid exporting
9139 remote_target. */
9140
9141int
9142putpkt (remote_target *remote, const char *buf)
9143{
9144 return remote->putpkt (buf);
9145}
9146
c906108c 9147/* Send a packet to the remote machine, with error checking. The data
23860348 9148 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9149 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9150 and for a possible /0 if we are debugging (remote_debug) and want
9151 to print the sent packet as a string. */
c906108c 9152
6b8edb51
PA
9153int
9154remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9155{
2d717e4f 9156 struct remote_state *rs = get_remote_state ();
c906108c
SS
9157 int i;
9158 unsigned char csum = 0;
b80406ac
TT
9159 gdb::def_vector<char> data (cnt + 6);
9160 char *buf2 = data.data ();
085dd6e6 9161
c906108c
SS
9162 int ch;
9163 int tcount = 0;
9164 char *p;
9165
e24a49d8
PA
9166 /* Catch cases like trying to read memory or listing threads while
9167 we're waiting for a stop reply. The remote server wouldn't be
9168 ready to handle this request, so we'd hang and timeout. We don't
9169 have to worry about this in synchronous mode, because in that
9170 case it's not possible to issue a command while the target is
74531fed
PA
9171 running. This is not a problem in non-stop mode, because in that
9172 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9173 if (!target_is_non_stop_p ()
9174 && target_is_async_p ()
9175 && rs->waiting_for_stop_reply)
9597b22a
DE
9176 {
9177 error (_("Cannot execute this command while the target is running.\n"
9178 "Use the \"interrupt\" command to stop the target\n"
9179 "and then try again."));
9180 }
e24a49d8 9181
2d717e4f
DJ
9182 /* We're sending out a new packet. Make sure we don't look at a
9183 stale cached response. */
9184 rs->cached_wait_status = 0;
9185
c906108c
SS
9186 /* Copy the packet into buffer BUF2, encapsulating it
9187 and giving it a checksum. */
9188
c906108c
SS
9189 p = buf2;
9190 *p++ = '$';
9191
9192 for (i = 0; i < cnt; i++)
9193 {
9194 csum += buf[i];
9195 *p++ = buf[i];
9196 }
9197 *p++ = '#';
9198 *p++ = tohex ((csum >> 4) & 0xf);
9199 *p++ = tohex (csum & 0xf);
9200
9201 /* Send it over and over until we get a positive ack. */
9202
9203 while (1)
9204 {
9205 int started_error_output = 0;
9206
9207 if (remote_debug)
9208 {
9209 *p = '\0';
b3ced9ba 9210
6f8976bf
YQ
9211 int len = (int) (p - buf2);
9212
9213 std::string str
9214 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9215
9216 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9217
567a3e54
SM
9218 if (len > REMOTE_DEBUG_MAX_CHAR)
9219 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9220 len - REMOTE_DEBUG_MAX_CHAR);
6f8976bf
YQ
9221
9222 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 9223
0f71a2f6 9224 gdb_flush (gdb_stdlog);
c906108c 9225 }
c33e31fd 9226 remote_serial_write (buf2, p - buf2);
c906108c 9227
a6f3e723
SL
9228 /* If this is a no acks version of the remote protocol, send the
9229 packet and move on. */
9230 if (rs->noack_mode)
9231 break;
9232
74531fed
PA
9233 /* Read until either a timeout occurs (-2) or '+' is read.
9234 Handle any notification that arrives in the mean time. */
c906108c
SS
9235 while (1)
9236 {
9237 ch = readchar (remote_timeout);
9238
c5aa993b 9239 if (remote_debug)
c906108c
SS
9240 {
9241 switch (ch)
9242 {
9243 case '+':
1216fa2c 9244 case '-':
c906108c
SS
9245 case SERIAL_TIMEOUT:
9246 case '$':
74531fed 9247 case '%':
c906108c
SS
9248 if (started_error_output)
9249 {
9250 putchar_unfiltered ('\n');
9251 started_error_output = 0;
9252 }
9253 }
9254 }
9255
9256 switch (ch)
9257 {
9258 case '+':
9259 if (remote_debug)
0f71a2f6 9260 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 9261 return 1;
1216fa2c
AC
9262 case '-':
9263 if (remote_debug)
9264 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 9265 /* FALLTHROUGH */
c906108c 9266 case SERIAL_TIMEOUT:
c5aa993b 9267 tcount++;
c906108c 9268 if (tcount > 3)
b80406ac 9269 return 0;
23860348 9270 break; /* Retransmit buffer. */
c906108c
SS
9271 case '$':
9272 {
40e3f985 9273 if (remote_debug)
2bc416ba 9274 fprintf_unfiltered (gdb_stdlog,
23860348 9275 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
9276 /* It's probably an old response sent because an ACK
9277 was lost. Gobble up the packet and ack it so it
9278 doesn't get retransmitted when we resend this
9279 packet. */
6d820c5c 9280 skip_frame ();
c33e31fd 9281 remote_serial_write ("+", 1);
23860348 9282 continue; /* Now, go look for +. */
c906108c 9283 }
74531fed
PA
9284
9285 case '%':
9286 {
9287 int val;
9288
9289 /* If we got a notification, handle it, and go back to looking
9290 for an ack. */
9291 /* We've found the start of a notification. Now
9292 collect the data. */
9293 val = read_frame (&rs->buf, &rs->buf_size);
9294 if (val >= 0)
9295 {
9296 if (remote_debug)
9297 {
b3ced9ba 9298 std::string str = escape_buffer (rs->buf, val);
6e5abd65 9299
6e5abd65
PA
9300 fprintf_unfiltered (gdb_stdlog,
9301 " Notification received: %s\n",
b3ced9ba 9302 str.c_str ());
74531fed 9303 }
5965e028 9304 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
9305 /* We're in sync now, rewait for the ack. */
9306 tcount = 0;
9307 }
9308 else
9309 {
9310 if (remote_debug)
9311 {
9312 if (!started_error_output)
9313 {
9314 started_error_output = 1;
9315 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9316 }
9317 fputc_unfiltered (ch & 0177, gdb_stdlog);
9318 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9319 }
9320 }
9321 continue;
9322 }
9323 /* fall-through */
c906108c
SS
9324 default:
9325 if (remote_debug)
9326 {
9327 if (!started_error_output)
9328 {
9329 started_error_output = 1;
0f71a2f6 9330 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 9331 }
0f71a2f6 9332 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
9333 }
9334 continue;
9335 }
23860348 9336 break; /* Here to retransmit. */
c906108c
SS
9337 }
9338
9339#if 0
9340 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
9341 able to get out next time we call QUIT, without anything as
9342 violent as interrupt_query. If we want to provide a way out of
9343 here without getting to the next QUIT, it should be based on
9344 hitting ^C twice as in remote_wait. */
c906108c
SS
9345 if (quit_flag)
9346 {
9347 quit_flag = 0;
9348 interrupt_query ();
9349 }
9350#endif
9351 }
a5c0808e 9352
a6f3e723 9353 return 0;
c906108c
SS
9354}
9355
6d820c5c
DJ
9356/* Come here after finding the start of a frame when we expected an
9357 ack. Do our best to discard the rest of this packet. */
9358
6b8edb51
PA
9359void
9360remote_target::skip_frame ()
6d820c5c
DJ
9361{
9362 int c;
9363
9364 while (1)
9365 {
9366 c = readchar (remote_timeout);
9367 switch (c)
9368 {
9369 case SERIAL_TIMEOUT:
9370 /* Nothing we can do. */
9371 return;
9372 case '#':
9373 /* Discard the two bytes of checksum and stop. */
9374 c = readchar (remote_timeout);
9375 if (c >= 0)
9376 c = readchar (remote_timeout);
9377
9378 return;
9379 case '*': /* Run length encoding. */
9380 /* Discard the repeat count. */
9381 c = readchar (remote_timeout);
9382 if (c < 0)
9383 return;
9384 break;
9385 default:
9386 /* A regular character. */
9387 break;
9388 }
9389 }
9390}
9391
c906108c 9392/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9393 into *BUF, verifying the checksum, length, and handling run-length
9394 compression. NUL terminate the buffer. If there is not enough room,
9395 expand *BUF using xrealloc.
c906108c 9396
c2d11a7d
JM
9397 Returns -1 on error, number of characters in buffer (ignoring the
9398 trailing NULL) on success. (could be extended to return one of the
23860348 9399 SERIAL status indications). */
c2d11a7d 9400
6b8edb51
PA
9401long
9402remote_target::read_frame (char **buf_p, long *sizeof_buf)
c906108c
SS
9403{
9404 unsigned char csum;
c2d11a7d 9405 long bc;
c906108c 9406 int c;
6d820c5c 9407 char *buf = *buf_p;
a6f3e723 9408 struct remote_state *rs = get_remote_state ();
c906108c
SS
9409
9410 csum = 0;
c2d11a7d 9411 bc = 0;
c906108c
SS
9412
9413 while (1)
9414 {
9415 c = readchar (remote_timeout);
c906108c
SS
9416 switch (c)
9417 {
9418 case SERIAL_TIMEOUT:
9419 if (remote_debug)
0f71a2f6 9420 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 9421 return -1;
c906108c
SS
9422 case '$':
9423 if (remote_debug)
0f71a2f6
JM
9424 fputs_filtered ("Saw new packet start in middle of old one\n",
9425 gdb_stdlog);
23860348 9426 return -1; /* Start a new packet, count retries. */
c906108c
SS
9427 case '#':
9428 {
9429 unsigned char pktcsum;
e1b09194
AC
9430 int check_0 = 0;
9431 int check_1 = 0;
c906108c 9432
c2d11a7d 9433 buf[bc] = '\0';
c906108c 9434
e1b09194
AC
9435 check_0 = readchar (remote_timeout);
9436 if (check_0 >= 0)
9437 check_1 = readchar (remote_timeout);
802188a7 9438
e1b09194
AC
9439 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9440 {
9441 if (remote_debug)
2bc416ba 9442 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 9443 gdb_stdlog);
e1b09194
AC
9444 return -1;
9445 }
9446 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
9447 {
9448 if (remote_debug)
2bc416ba 9449 fputs_filtered ("Communication error in checksum\n",
23860348 9450 gdb_stdlog);
40e3f985
FN
9451 return -1;
9452 }
c906108c 9453
a6f3e723
SL
9454 /* Don't recompute the checksum; with no ack packets we
9455 don't have any way to indicate a packet retransmission
9456 is necessary. */
9457 if (rs->noack_mode)
9458 return bc;
9459
e1b09194 9460 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9461 if (csum == pktcsum)
c2d11a7d 9462 return bc;
c906108c 9463
c5aa993b 9464 if (remote_debug)
c906108c 9465 {
b3ced9ba 9466 std::string str = escape_buffer (buf, bc);
6e5abd65 9467
6e5abd65 9468 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9469 "Bad checksum, sentsum=0x%x, "
9470 "csum=0x%x, buf=%s\n",
b3ced9ba 9471 pktcsum, csum, str.c_str ());
c906108c 9472 }
c2d11a7d 9473 /* Number of characters in buffer ignoring trailing
23860348 9474 NULL. */
c2d11a7d 9475 return -1;
c906108c 9476 }
23860348 9477 case '*': /* Run length encoding. */
c2c6d25f
JM
9478 {
9479 int repeat;
c906108c 9480
a744cf53 9481 csum += c;
b4501125
AC
9482 c = readchar (remote_timeout);
9483 csum += c;
23860348 9484 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9485
23860348 9486 /* The character before ``*'' is repeated. */
c2d11a7d 9487
6d820c5c 9488 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9489 {
6d820c5c
DJ
9490 if (bc + repeat - 1 >= *sizeof_buf - 1)
9491 {
9492 /* Make some more room in the buffer. */
9493 *sizeof_buf += repeat;
224c3ddb 9494 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
9495 buf = *buf_p;
9496 }
9497
c2d11a7d
JM
9498 memset (&buf[bc], buf[bc - 1], repeat);
9499 bc += repeat;
c2c6d25f
JM
9500 continue;
9501 }
9502
c2d11a7d 9503 buf[bc] = '\0';
6d820c5c 9504 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9505 return -1;
c2c6d25f 9506 }
c906108c 9507 default:
6d820c5c 9508 if (bc >= *sizeof_buf - 1)
c906108c 9509 {
6d820c5c
DJ
9510 /* Make some more room in the buffer. */
9511 *sizeof_buf *= 2;
224c3ddb 9512 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 9513 buf = *buf_p;
c906108c
SS
9514 }
9515
6d820c5c
DJ
9516 buf[bc++] = c;
9517 csum += c;
9518 continue;
c906108c
SS
9519 }
9520 }
9521}
9522
9523/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9524 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9525 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9526 rather than timing out; this is used (in synchronous mode) to wait
9527 for a target that is is executing user code to stop. */
d9fcf2fb
JM
9528/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9529 don't have to change all the calls to getpkt to deal with the
9530 return value, because at the moment I don't know what the right
23860348 9531 thing to do it for those. */
6b8edb51 9532
c906108c 9533void
6b8edb51 9534remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
d9fcf2fb 9535{
54887903 9536 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
9537}
9538
9539
9540/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9541 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9542 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9543 rather than timing out; this is used (in synchronous mode) to wait
9544 for a target that is is executing user code to stop. If FOREVER ==
9545 0, this function is allowed to time out gracefully and return an
74531fed
PA
9546 indication of this to the caller. Otherwise return the number of
9547 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
9548 enough reason to return to the caller. *IS_NOTIF is an output
9549 boolean that indicates whether *BUF holds a notification or not
9550 (a regular packet). */
74531fed 9551
6b8edb51
PA
9552int
9553remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9554 int forever, int expecting_notif,
9555 int *is_notif)
c906108c 9556{
2d717e4f 9557 struct remote_state *rs = get_remote_state ();
c906108c
SS
9558 int c;
9559 int tries;
9560 int timeout;
df4b58fe 9561 int val = -1;
c906108c 9562
2d717e4f
DJ
9563 /* We're reading a new response. Make sure we don't look at a
9564 previously cached response. */
9565 rs->cached_wait_status = 0;
9566
6d820c5c 9567 strcpy (*buf, "timeout");
c906108c
SS
9568
9569 if (forever)
74531fed
PA
9570 timeout = watchdog > 0 ? watchdog : -1;
9571 else if (expecting_notif)
9572 timeout = 0; /* There should already be a char in the buffer. If
9573 not, bail out. */
c906108c
SS
9574 else
9575 timeout = remote_timeout;
9576
9577#define MAX_TRIES 3
9578
74531fed
PA
9579 /* Process any number of notifications, and then return when
9580 we get a packet. */
9581 for (;;)
c906108c 9582 {
d9c43928 9583 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9584 times. */
9585 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9586 {
74531fed
PA
9587 /* This can loop forever if the remote side sends us
9588 characters continuously, but if it pauses, we'll get
9589 SERIAL_TIMEOUT from readchar because of timeout. Then
9590 we'll count that as a retry.
9591
9592 Note that even when forever is set, we will only wait
9593 forever prior to the start of a packet. After that, we
9594 expect characters to arrive at a brisk pace. They should
9595 show up within remote_timeout intervals. */
9596 do
9597 c = readchar (timeout);
9598 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9599
9600 if (c == SERIAL_TIMEOUT)
9601 {
74531fed
PA
9602 if (expecting_notif)
9603 return -1; /* Don't complain, it's normal to not get
9604 anything in this case. */
9605
23860348 9606 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9607 {
78a095c3 9608 remote_unpush_target ();
598d3636
JK
9609 throw_error (TARGET_CLOSE_ERROR,
9610 _("Watchdog timeout has expired. "
9611 "Target detached."));
c906108c 9612 }
c906108c 9613 if (remote_debug)
0f71a2f6 9614 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9615 }
74531fed
PA
9616 else
9617 {
9618 /* We've found the start of a packet or notification.
9619 Now collect the data. */
9620 val = read_frame (buf, sizeof_buf);
9621 if (val >= 0)
9622 break;
9623 }
9624
c33e31fd 9625 remote_serial_write ("-", 1);
c906108c 9626 }
c906108c 9627
74531fed
PA
9628 if (tries > MAX_TRIES)
9629 {
9630 /* We have tried hard enough, and just can't receive the
9631 packet/notification. Give up. */
9632 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9633
74531fed
PA
9634 /* Skip the ack char if we're in no-ack mode. */
9635 if (!rs->noack_mode)
c33e31fd 9636 remote_serial_write ("+", 1);
74531fed
PA
9637 return -1;
9638 }
c906108c 9639
74531fed
PA
9640 /* If we got an ordinary packet, return that to our caller. */
9641 if (c == '$')
c906108c
SS
9642 {
9643 if (remote_debug)
43e526b9 9644 {
6f8976bf
YQ
9645 std::string str
9646 = escape_buffer (*buf,
9647 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9648
9649 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9650 str.c_str ());
9651
567a3e54
SM
9652 if (val > REMOTE_DEBUG_MAX_CHAR)
9653 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9654 val - REMOTE_DEBUG_MAX_CHAR);
6e5abd65 9655
6f8976bf 9656 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9657 }
a6f3e723
SL
9658
9659 /* Skip the ack char if we're in no-ack mode. */
9660 if (!rs->noack_mode)
c33e31fd 9661 remote_serial_write ("+", 1);
fee9eda9
YQ
9662 if (is_notif != NULL)
9663 *is_notif = 0;
0876f84a 9664 return val;
c906108c
SS
9665 }
9666
74531fed
PA
9667 /* If we got a notification, handle it, and go back to looking
9668 for a packet. */
9669 else
9670 {
9671 gdb_assert (c == '%');
9672
9673 if (remote_debug)
9674 {
b3ced9ba 9675 std::string str = escape_buffer (*buf, val);
6e5abd65 9676
6e5abd65
PA
9677 fprintf_unfiltered (gdb_stdlog,
9678 " Notification received: %s\n",
b3ced9ba 9679 str.c_str ());
74531fed 9680 }
fee9eda9
YQ
9681 if (is_notif != NULL)
9682 *is_notif = 1;
c906108c 9683
5965e028 9684 handle_notification (rs->notif_state, *buf);
c906108c 9685
74531fed 9686 /* Notifications require no acknowledgement. */
a6f3e723 9687
74531fed 9688 if (expecting_notif)
fee9eda9 9689 return val;
74531fed
PA
9690 }
9691 }
9692}
9693
6b8edb51
PA
9694int
9695remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
74531fed 9696{
fee9eda9 9697 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
9698}
9699
6b8edb51
PA
9700int
9701remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9702 int *is_notif)
74531fed 9703{
fee9eda9
YQ
9704 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9705 is_notif);
c906108c 9706}
74531fed 9707
cbb8991c
DB
9708/* Kill any new fork children of process PID that haven't been
9709 processed by follow_fork. */
9710
6b8edb51
PA
9711void
9712remote_target::kill_new_fork_children (int pid)
cbb8991c 9713{
6b8edb51 9714 remote_state *rs = get_remote_state ();
cbb8991c
DB
9715 struct thread_info *thread;
9716 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
9717
9718 /* Kill the fork child threads of any threads in process PID
9719 that are stopped at a fork event. */
9720 ALL_NON_EXITED_THREADS (thread)
9721 {
9722 struct target_waitstatus *ws = &thread->pending_follow;
9723
9724 if (is_pending_fork_parent (ws, pid, thread->ptid))
9725 {
953edf2b 9726 int child_pid = ws->value.related_pid.pid ();
cbb8991c
DB
9727 int res;
9728
6b8edb51 9729 res = remote_vkill (child_pid);
cbb8991c
DB
9730 if (res != 0)
9731 error (_("Can't kill fork child process %d"), child_pid);
9732 }
9733 }
9734
9735 /* Check for any pending fork events (not reported or processed yet)
9736 in process PID and kill those fork child threads as well. */
9737 remote_notif_get_pending_events (notif);
953edf2b
TT
9738 for (auto &event : rs->stop_reply_queue)
9739 if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9740 {
9741 int child_pid = event->ws.value.related_pid.pid ();
9742 int res;
9743
9744 res = remote_vkill (child_pid);
9745 if (res != 0)
9746 error (_("Can't kill fork child process %d"), child_pid);
9747 }
cbb8991c
DB
9748}
9749
c906108c 9750\f
8020350c
DB
9751/* Target hook to kill the current inferior. */
9752
f6ac5f3d
PA
9753void
9754remote_target::kill ()
43ff13b4 9755{
8020350c 9756 int res = -1;
e99b03dc 9757 int pid = inferior_ptid.pid ();
8020350c 9758 struct remote_state *rs = get_remote_state ();
0fdf84ca 9759
8020350c 9760 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9761 {
8020350c
DB
9762 /* If we're stopped while forking and we haven't followed yet,
9763 kill the child task. We need to do this before killing the
9764 parent task because if this is a vfork then the parent will
9765 be sleeping. */
6b8edb51 9766 kill_new_fork_children (pid);
8020350c 9767
6b8edb51 9768 res = remote_vkill (pid);
8020350c 9769 if (res == 0)
0fdf84ca 9770 {
bc1e6c81 9771 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9772 return;
9773 }
8020350c 9774 }
0fdf84ca 9775
8020350c
DB
9776 /* If we are in 'target remote' mode and we are killing the only
9777 inferior, then we will tell gdbserver to exit and unpush the
9778 target. */
9779 if (res == -1 && !remote_multi_process_p (rs)
9780 && number_of_live_inferiors () == 1)
9781 {
9782 remote_kill_k ();
9783
9784 /* We've killed the remote end, we get to mourn it. If we are
9785 not in extended mode, mourning the inferior also unpushes
9786 remote_ops from the target stack, which closes the remote
9787 connection. */
bc1e6c81 9788 target_mourn_inferior (inferior_ptid);
8020350c
DB
9789
9790 return;
0fdf84ca 9791 }
43ff13b4 9792
8020350c 9793 error (_("Can't kill process"));
43ff13b4
JM
9794}
9795
8020350c
DB
9796/* Send a kill request to the target using the 'vKill' packet. */
9797
6b8edb51
PA
9798int
9799remote_target::remote_vkill (int pid)
82f73884 9800{
4082afcc 9801 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9802 return -1;
9803
6b8edb51
PA
9804 remote_state *rs = get_remote_state ();
9805
82f73884 9806 /* Tell the remote target to detach. */
bba74b36 9807 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
9808 putpkt (rs->buf);
9809 getpkt (&rs->buf, &rs->buf_size, 0);
9810
4082afcc
PA
9811 switch (packet_ok (rs->buf,
9812 &remote_protocol_packets[PACKET_vKill]))
9813 {
9814 case PACKET_OK:
9815 return 0;
9816 case PACKET_ERROR:
9817 return 1;
9818 case PACKET_UNKNOWN:
9819 return -1;
9820 default:
9821 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9822 }
82f73884
PA
9823}
9824
8020350c
DB
9825/* Send a kill request to the target using the 'k' packet. */
9826
6b8edb51
PA
9827void
9828remote_target::remote_kill_k ()
82f73884 9829{
8020350c
DB
9830 /* Catch errors so the user can quit from gdb even when we
9831 aren't on speaking terms with the remote system. */
9832 TRY
82f73884 9833 {
82f73884 9834 putpkt ("k");
82f73884 9835 }
8020350c
DB
9836 CATCH (ex, RETURN_MASK_ERROR)
9837 {
9838 if (ex.error == TARGET_CLOSE_ERROR)
9839 {
9840 /* If we got an (EOF) error that caused the target
9841 to go away, then we're done, that's what we wanted.
9842 "k" is susceptible to cause a premature EOF, given
9843 that the remote server isn't actually required to
9844 reply to "k", and it can happen that it doesn't
9845 even get to reply ACK to the "k". */
9846 return;
9847 }
82f73884 9848
8020350c
DB
9849 /* Otherwise, something went wrong. We didn't actually kill
9850 the target. Just propagate the exception, and let the
9851 user or higher layers decide what to do. */
9852 throw_exception (ex);
9853 }
9854 END_CATCH
82f73884
PA
9855}
9856
f6ac5f3d
PA
9857void
9858remote_target::mourn_inferior ()
c906108c 9859{
8020350c 9860 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9861
9607784a
PA
9862 /* We're no longer interested in notification events of an inferior
9863 that exited or was killed/detached. */
9864 discard_pending_stop_replies (current_inferior ());
9865
8020350c
DB
9866 /* In 'target remote' mode with one inferior, we close the connection. */
9867 if (!rs->extended && number_of_live_inferiors () <= 1)
9868 {
f6ac5f3d 9869 unpush_target (this);
c906108c 9870
8020350c
DB
9871 /* remote_close takes care of doing most of the clean up. */
9872 generic_mourn_inferior ();
9873 return;
9874 }
c906108c 9875
e24a49d8
PA
9876 /* In case we got here due to an error, but we're going to stay
9877 connected. */
9878 rs->waiting_for_stop_reply = 0;
9879
dc1981d7
PA
9880 /* If the current general thread belonged to the process we just
9881 detached from or has exited, the remote side current general
9882 thread becomes undefined. Considering a case like this:
9883
9884 - We just got here due to a detach.
9885 - The process that we're detaching from happens to immediately
9886 report a global breakpoint being hit in non-stop mode, in the
9887 same thread we had selected before.
9888 - GDB attaches to this process again.
9889 - This event happens to be the next event we handle.
9890
9891 GDB would consider that the current general thread didn't need to
9892 be set on the stub side (with Hg), since for all it knew,
9893 GENERAL_THREAD hadn't changed.
9894
9895 Notice that although in all-stop mode, the remote server always
9896 sets the current thread to the thread reporting the stop event,
9897 that doesn't happen in non-stop mode; in non-stop, the stub *must
9898 not* change the current thread when reporting a breakpoint hit,
9899 due to the decoupling of event reporting and event handling.
9900
9901 To keep things simple, we always invalidate our notion of the
9902 current thread. */
47f8a51d 9903 record_currthread (rs, minus_one_ptid);
dc1981d7 9904
8020350c 9905 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9906 generic_mourn_inferior ();
9907
d729566a 9908 if (!have_inferiors ())
2d717e4f 9909 {
82f73884
PA
9910 if (!remote_multi_process_p (rs))
9911 {
9912 /* Check whether the target is running now - some remote stubs
9913 automatically restart after kill. */
9914 putpkt ("?");
9915 getpkt (&rs->buf, &rs->buf_size, 0);
9916
9917 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9918 {
3e43a32a
MS
9919 /* Assume that the target has been restarted. Set
9920 inferior_ptid so that bits of core GDB realizes
9921 there's something here, e.g., so that the user can
9922 say "kill" again. */
82f73884
PA
9923 inferior_ptid = magic_null_ptid;
9924 }
82f73884 9925 }
2d717e4f
DJ
9926 }
9927}
c906108c 9928
57810aa7 9929bool
f6ac5f3d 9930extended_remote_target::supports_disable_randomization ()
03583c20 9931{
4082afcc 9932 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9933}
9934
6b8edb51
PA
9935void
9936remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
9937{
9938 struct remote_state *rs = get_remote_state ();
9939 char *reply;
9940
bba74b36
YQ
9941 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9942 val);
03583c20 9943 putpkt (rs->buf);
b6bb3468 9944 reply = remote_get_noisy_reply ();
03583c20
UW
9945 if (*reply == '\0')
9946 error (_("Target does not support QDisableRandomization."));
9947 if (strcmp (reply, "OK") != 0)
9948 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9949}
9950
6b8edb51
PA
9951int
9952remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
9953{
9954 struct remote_state *rs = get_remote_state ();
2d717e4f 9955 int len;
94585166 9956 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9957
2d717e4f
DJ
9958 /* If the user has disabled vRun support, or we have detected that
9959 support is not available, do not try it. */
4082afcc 9960 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9961 return -1;
424163ea 9962
2d717e4f
DJ
9963 strcpy (rs->buf, "vRun;");
9964 len = strlen (rs->buf);
c906108c 9965
2d717e4f
DJ
9966 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9967 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9968 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9969 strlen (remote_exec_file));
2d717e4f 9970
7c5ded6a 9971 if (!args.empty ())
2d717e4f 9972 {
2d717e4f 9973 int i;
2d717e4f 9974
773a1edc 9975 gdb_argv argv (args.c_str ());
2d717e4f
DJ
9976 for (i = 0; argv[i] != NULL; i++)
9977 {
9978 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9979 error (_("Argument list too long for run packet"));
9980 rs->buf[len++] = ';';
9f1b45b0
TT
9981 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9982 strlen (argv[i]));
2d717e4f 9983 }
2d717e4f
DJ
9984 }
9985
9986 rs->buf[len++] = '\0';
9987
9988 putpkt (rs->buf);
9989 getpkt (&rs->buf, &rs->buf_size, 0);
9990
4082afcc 9991 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9992 {
4082afcc 9993 case PACKET_OK:
3405876a 9994 /* We have a wait response. All is well. */
2d717e4f 9995 return 0;
4082afcc
PA
9996 case PACKET_UNKNOWN:
9997 return -1;
9998 case PACKET_ERROR:
2d717e4f
DJ
9999 if (remote_exec_file[0] == '\0')
10000 error (_("Running the default executable on the remote target failed; "
10001 "try \"set remote exec-file\"?"));
10002 else
10003 error (_("Running \"%s\" on the remote target failed"),
10004 remote_exec_file);
4082afcc
PA
10005 default:
10006 gdb_assert_not_reached (_("bad switch"));
2d717e4f 10007 }
c906108c
SS
10008}
10009
0a2dde4a
SDJ
10010/* Helper function to send set/unset environment packets. ACTION is
10011 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10012 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10013 sent. */
10014
6b8edb51
PA
10015void
10016remote_target::send_environment_packet (const char *action,
10017 const char *packet,
10018 const char *value)
0a2dde4a 10019{
6b8edb51
PA
10020 remote_state *rs = get_remote_state ();
10021
0a2dde4a
SDJ
10022 /* Convert the environment variable to an hex string, which
10023 is the best format to be transmitted over the wire. */
10024 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10025 strlen (value));
10026
10027 xsnprintf (rs->buf, get_remote_packet_size (),
10028 "%s:%s", packet, encoded_value.c_str ());
10029
10030 putpkt (rs->buf);
10031 getpkt (&rs->buf, &rs->buf_size, 0);
10032 if (strcmp (rs->buf, "OK") != 0)
10033 warning (_("Unable to %s environment variable '%s' on remote."),
10034 action, value);
10035}
10036
10037/* Helper function to handle the QEnvironment* packets. */
10038
6b8edb51
PA
10039void
10040remote_target::extended_remote_environment_support ()
0a2dde4a 10041{
6b8edb51
PA
10042 remote_state *rs = get_remote_state ();
10043
0a2dde4a
SDJ
10044 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10045 {
10046 putpkt ("QEnvironmentReset");
10047 getpkt (&rs->buf, &rs->buf_size, 0);
10048 if (strcmp (rs->buf, "OK") != 0)
10049 warning (_("Unable to reset environment on remote."));
10050 }
10051
10052 gdb_environ *e = &current_inferior ()->environment;
10053
10054 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10055 for (const std::string &el : e->user_set_env ())
6b8edb51 10056 send_environment_packet ("set", "QEnvironmentHexEncoded",
0a2dde4a
SDJ
10057 el.c_str ());
10058
10059 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10060 for (const std::string &el : e->user_unset_env ())
6b8edb51 10061 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10062}
10063
bc3b087d
SDJ
10064/* Helper function to set the current working directory for the
10065 inferior in the remote target. */
10066
6b8edb51
PA
10067void
10068remote_target::extended_remote_set_inferior_cwd ()
bc3b087d
SDJ
10069{
10070 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10071 {
10072 const char *inferior_cwd = get_inferior_cwd ();
6b8edb51 10073 remote_state *rs = get_remote_state ();
bc3b087d
SDJ
10074
10075 if (inferior_cwd != NULL)
10076 {
10077 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10078 strlen (inferior_cwd));
10079
10080 xsnprintf (rs->buf, get_remote_packet_size (),
10081 "QSetWorkingDir:%s", hexpath.c_str ());
10082 }
10083 else
10084 {
10085 /* An empty inferior_cwd means that the user wants us to
10086 reset the remote server's inferior's cwd. */
10087 xsnprintf (rs->buf, get_remote_packet_size (),
10088 "QSetWorkingDir:");
10089 }
10090
10091 putpkt (rs->buf);
10092 getpkt (&rs->buf, &rs->buf_size, 0);
10093 if (packet_ok (rs->buf,
10094 &remote_protocol_packets[PACKET_QSetWorkingDir])
10095 != PACKET_OK)
10096 error (_("\
10097Remote replied unexpectedly while setting the inferior's working\n\
10098directory: %s"),
10099 rs->buf);
10100
10101 }
10102}
10103
2d717e4f
DJ
10104/* In the extended protocol we want to be able to do things like
10105 "run" and have them basically work as expected. So we need
10106 a special create_inferior function. We support changing the
10107 executable file and the command line arguments, but not the
10108 environment. */
10109
f6ac5f3d
PA
10110void
10111extended_remote_target::create_inferior (const char *exec_file,
10112 const std::string &args,
10113 char **env, int from_tty)
43ff13b4 10114{
3405876a
PA
10115 int run_worked;
10116 char *stop_reply;
10117 struct remote_state *rs = get_remote_state ();
94585166 10118 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10119
43ff13b4 10120 /* If running asynchronously, register the target file descriptor
23860348 10121 with the event loop. */
75c99385 10122 if (target_can_async_p ())
6a3753b3 10123 target_async (1);
43ff13b4 10124
03583c20 10125 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10126 if (supports_disable_randomization ())
03583c20
UW
10127 extended_remote_disable_randomization (disable_randomization);
10128
aefd8b33
SDJ
10129 /* If startup-with-shell is on, we inform gdbserver to start the
10130 remote inferior using a shell. */
10131 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10132 {
10133 xsnprintf (rs->buf, get_remote_packet_size (),
10134 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10135 putpkt (rs->buf);
10136 getpkt (&rs->buf, &rs->buf_size, 0);
10137 if (strcmp (rs->buf, "OK") != 0)
10138 error (_("\
10139Remote replied unexpectedly while setting startup-with-shell: %s"),
10140 rs->buf);
10141 }
10142
6b8edb51 10143 extended_remote_environment_support ();
0a2dde4a 10144
6b8edb51 10145 extended_remote_set_inferior_cwd ();
bc3b087d 10146
43ff13b4 10147 /* Now restart the remote server. */
3405876a
PA
10148 run_worked = extended_remote_run (args) != -1;
10149 if (!run_worked)
2d717e4f
DJ
10150 {
10151 /* vRun was not supported. Fail if we need it to do what the
10152 user requested. */
10153 if (remote_exec_file[0])
10154 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10155 if (!args.empty ())
65e65158 10156 error (_("Remote target does not support \"set args\" or run ARGS"));
43ff13b4 10157
2d717e4f
DJ
10158 /* Fall back to "R". */
10159 extended_remote_restart ();
10160 }
424163ea 10161
6c95b8df
PA
10162 if (!have_inferiors ())
10163 {
10164 /* Clean up from the last time we ran, before we mark the target
10165 running again. This will mark breakpoints uninserted, and
10166 get_offsets may insert breakpoints. */
10167 init_thread_list ();
10168 init_wait_for_inferior ();
10169 }
45280a52 10170
3405876a
PA
10171 /* vRun's success return is a stop reply. */
10172 stop_reply = run_worked ? rs->buf : NULL;
10173 add_current_inferior_and_thread (stop_reply);
c0a2216e 10174
2d717e4f
DJ
10175 /* Get updated offsets, if the stub uses qOffsets. */
10176 get_offsets ();
2d717e4f 10177}
c906108c 10178\f
c5aa993b 10179
b775012e
LM
10180/* Given a location's target info BP_TGT and the packet buffer BUF, output
10181 the list of conditions (in agent expression bytecode format), if any, the
10182 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10183 started from BUF and ended at BUF_END. */
b775012e
LM
10184
10185static int
10186remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10187 struct bp_target_info *bp_tgt, char *buf,
10188 char *buf_end)
b775012e 10189{
3cde5c42 10190 if (bp_tgt->conditions.empty ())
b775012e
LM
10191 return 0;
10192
10193 buf += strlen (buf);
bba74b36 10194 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10195 buf++;
10196
83621223 10197 /* Send conditions to the target. */
d538e36d 10198 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10199 {
bba74b36 10200 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 10201 buf += strlen (buf);
3cde5c42 10202 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
10203 buf = pack_hex_byte (buf, aexpr->buf[i]);
10204 *buf = '\0';
10205 }
b775012e
LM
10206 return 0;
10207}
10208
d3ce09f5
SS
10209static void
10210remote_add_target_side_commands (struct gdbarch *gdbarch,
10211 struct bp_target_info *bp_tgt, char *buf)
10212{
3cde5c42 10213 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10214 return;
10215
10216 buf += strlen (buf);
10217
10218 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10219 buf += strlen (buf);
10220
10221 /* Concatenate all the agent expressions that are commands into the
10222 cmds parameter. */
df97be55 10223 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
10224 {
10225 sprintf (buf, "X%x,", aexpr->len);
10226 buf += strlen (buf);
3cde5c42 10227 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
10228 buf = pack_hex_byte (buf, aexpr->buf[i]);
10229 *buf = '\0';
10230 }
d3ce09f5
SS
10231}
10232
8181d85f
DJ
10233/* Insert a breakpoint. On targets that have software breakpoint
10234 support, we ask the remote target to do the work; on targets
10235 which don't, we insert a traditional memory breakpoint. */
c906108c 10236
f6ac5f3d
PA
10237int
10238remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10239 struct bp_target_info *bp_tgt)
c906108c 10240{
d471ea57
AC
10241 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10242 If it succeeds, then set the support to PACKET_ENABLE. If it
10243 fails, and the user has explicitly requested the Z support then
23860348 10244 report an error, otherwise, mark it disabled and go on. */
802188a7 10245
4082afcc 10246 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10247 {
0d5ed153 10248 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10249 struct remote_state *rs;
bba74b36 10250 char *p, *endbuf;
4fff2411 10251
28439a30
PA
10252 /* Make sure the remote is pointing at the right process, if
10253 necessary. */
10254 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10255 set_general_process ();
10256
4fff2411
JZ
10257 rs = get_remote_state ();
10258 p = rs->buf;
bba74b36 10259 endbuf = rs->buf + get_remote_packet_size ();
802188a7 10260
96baa820
JM
10261 *(p++) = 'Z';
10262 *(p++) = '0';
10263 *(p++) = ',';
7c0f6dcc 10264 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10265 p += hexnumstr (p, addr);
579c6ad9 10266 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10267
f6ac5f3d 10268 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10269 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10270
f6ac5f3d 10271 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10272 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10273
6d820c5c
DJ
10274 putpkt (rs->buf);
10275 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10276
6d820c5c 10277 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 10278 {
d471ea57
AC
10279 case PACKET_ERROR:
10280 return -1;
10281 case PACKET_OK:
10282 return 0;
10283 case PACKET_UNKNOWN:
10284 break;
96baa820
JM
10285 }
10286 }
c906108c 10287
0000e5cc
PA
10288 /* If this breakpoint has target-side commands but this stub doesn't
10289 support Z0 packets, throw error. */
3cde5c42 10290 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10291 throw_error (NOT_SUPPORTED_ERROR, _("\
10292Target doesn't support breakpoints that have target side commands."));
10293
f6ac5f3d 10294 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10295}
10296
f6ac5f3d
PA
10297int
10298remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10299 struct bp_target_info *bp_tgt,
10300 enum remove_bp_reason reason)
c906108c 10301{
8181d85f 10302 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10303 struct remote_state *rs = get_remote_state ();
96baa820 10304
4082afcc 10305 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10306 {
6d820c5c 10307 char *p = rs->buf;
bba74b36 10308 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 10309
28439a30
PA
10310 /* Make sure the remote is pointing at the right process, if
10311 necessary. */
10312 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10313 set_general_process ();
10314
96baa820
JM
10315 *(p++) = 'z';
10316 *(p++) = '0';
10317 *(p++) = ',';
10318
8181d85f
DJ
10319 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10320 p += hexnumstr (p, addr);
579c6ad9 10321 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10322
6d820c5c
DJ
10323 putpkt (rs->buf);
10324 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10325
6d820c5c 10326 return (rs->buf[0] == 'E');
96baa820
JM
10327 }
10328
f6ac5f3d 10329 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10330}
10331
f486487f 10332static enum Z_packet_type
d471ea57
AC
10333watchpoint_to_Z_packet (int type)
10334{
10335 switch (type)
10336 {
10337 case hw_write:
bb858e6a 10338 return Z_PACKET_WRITE_WP;
d471ea57
AC
10339 break;
10340 case hw_read:
bb858e6a 10341 return Z_PACKET_READ_WP;
d471ea57
AC
10342 break;
10343 case hw_access:
bb858e6a 10344 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10345 break;
10346 default:
8e65ff28 10347 internal_error (__FILE__, __LINE__,
e2e0b3e5 10348 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10349 }
10350}
10351
f6ac5f3d
PA
10352int
10353remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10354 enum target_hw_bp_type type, struct expression *cond)
96baa820 10355{
d01949b6 10356 struct remote_state *rs = get_remote_state ();
bba74b36 10357 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10358 char *p;
d471ea57 10359 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10360
4082afcc 10361 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10362 return 1;
802188a7 10363
28439a30
PA
10364 /* Make sure the remote is pointing at the right process, if
10365 necessary. */
10366 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10367 set_general_process ();
10368
bba74b36 10369 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 10370 p = strchr (rs->buf, '\0');
96baa820
JM
10371 addr = remote_address_masked (addr);
10372 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10373 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10374
6d820c5c
DJ
10375 putpkt (rs->buf);
10376 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10377
6d820c5c 10378 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10379 {
10380 case PACKET_ERROR:
d471ea57 10381 return -1;
85d721b8
PA
10382 case PACKET_UNKNOWN:
10383 return 1;
d471ea57
AC
10384 case PACKET_OK:
10385 return 0;
10386 }
8e65ff28 10387 internal_error (__FILE__, __LINE__,
e2e0b3e5 10388 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10389}
10390
57810aa7 10391bool
f6ac5f3d
PA
10392remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10393 CORE_ADDR start, int length)
283002cf
MR
10394{
10395 CORE_ADDR diff = remote_address_masked (addr - start);
10396
10397 return diff < length;
10398}
10399
d471ea57 10400
f6ac5f3d
PA
10401int
10402remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10403 enum target_hw_bp_type type, struct expression *cond)
96baa820 10404{
d01949b6 10405 struct remote_state *rs = get_remote_state ();
bba74b36 10406 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10407 char *p;
d471ea57
AC
10408 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10409
4082afcc 10410 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10411 return -1;
802188a7 10412
28439a30
PA
10413 /* Make sure the remote is pointing at the right process, if
10414 necessary. */
10415 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10416 set_general_process ();
10417
bba74b36 10418 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 10419 p = strchr (rs->buf, '\0');
96baa820
JM
10420 addr = remote_address_masked (addr);
10421 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10422 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
10423 putpkt (rs->buf);
10424 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10425
6d820c5c 10426 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10427 {
10428 case PACKET_ERROR:
10429 case PACKET_UNKNOWN:
10430 return -1;
10431 case PACKET_OK:
10432 return 0;
10433 }
8e65ff28 10434 internal_error (__FILE__, __LINE__,
e2e0b3e5 10435 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10436}
10437
3c3bea1c 10438
501eef12 10439int remote_hw_watchpoint_limit = -1;
480a3f21 10440int remote_hw_watchpoint_length_limit = -1;
501eef12 10441int remote_hw_breakpoint_limit = -1;
d471ea57 10442
f6ac5f3d
PA
10443int
10444remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10445{
10446 if (remote_hw_watchpoint_length_limit == 0)
10447 return 0;
10448 else if (remote_hw_watchpoint_length_limit < 0)
10449 return 1;
10450 else if (len <= remote_hw_watchpoint_length_limit)
10451 return 1;
10452 else
10453 return 0;
10454}
10455
f6ac5f3d
PA
10456int
10457remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10458{
3c3bea1c
GS
10459 if (type == bp_hardware_breakpoint)
10460 {
10461 if (remote_hw_breakpoint_limit == 0)
10462 return 0;
501eef12
AC
10463 else if (remote_hw_breakpoint_limit < 0)
10464 return 1;
3c3bea1c
GS
10465 else if (cnt <= remote_hw_breakpoint_limit)
10466 return 1;
10467 }
10468 else
10469 {
10470 if (remote_hw_watchpoint_limit == 0)
10471 return 0;
501eef12
AC
10472 else if (remote_hw_watchpoint_limit < 0)
10473 return 1;
3c3bea1c
GS
10474 else if (ot)
10475 return -1;
10476 else if (cnt <= remote_hw_watchpoint_limit)
10477 return 1;
10478 }
10479 return -1;
10480}
10481
f7e6eed5
PA
10482/* The to_stopped_by_sw_breakpoint method of target remote. */
10483
57810aa7 10484bool
f6ac5f3d 10485remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10486{
799a2abe 10487 struct thread_info *thread = inferior_thread ();
f7e6eed5 10488
799a2abe 10489 return (thread->priv != NULL
7aabaf9d
SM
10490 && (get_remote_thread_info (thread)->stop_reason
10491 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10492}
10493
10494/* The to_supports_stopped_by_sw_breakpoint method of target
10495 remote. */
10496
57810aa7 10497bool
f6ac5f3d 10498remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10499{
f7e6eed5
PA
10500 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10501}
10502
10503/* The to_stopped_by_hw_breakpoint method of target remote. */
10504
57810aa7 10505bool
f6ac5f3d 10506remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10507{
799a2abe 10508 struct thread_info *thread = inferior_thread ();
f7e6eed5 10509
799a2abe 10510 return (thread->priv != NULL
7aabaf9d
SM
10511 && (get_remote_thread_info (thread)->stop_reason
10512 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10513}
10514
10515/* The to_supports_stopped_by_hw_breakpoint method of target
10516 remote. */
10517
57810aa7 10518bool
f6ac5f3d 10519remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10520{
f7e6eed5
PA
10521 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10522}
10523
57810aa7 10524bool
f6ac5f3d 10525remote_target::stopped_by_watchpoint ()
3c3bea1c 10526{
799a2abe 10527 struct thread_info *thread = inferior_thread ();
ee154bee 10528
799a2abe 10529 return (thread->priv != NULL
7aabaf9d
SM
10530 && (get_remote_thread_info (thread)->stop_reason
10531 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10532}
10533
57810aa7 10534bool
f6ac5f3d 10535remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10536{
799a2abe 10537 struct thread_info *thread = inferior_thread ();
a744cf53 10538
799a2abe 10539 if (thread->priv != NULL
7aabaf9d
SM
10540 && (get_remote_thread_info (thread)->stop_reason
10541 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10542 {
7aabaf9d 10543 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 10544 return true;
4aa7a7f5
JJ
10545 }
10546
57810aa7 10547 return false;
3c3bea1c
GS
10548}
10549
10550
f6ac5f3d
PA
10551int
10552remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10553 struct bp_target_info *bp_tgt)
3c3bea1c 10554{
0d5ed153 10555 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10556 struct remote_state *rs;
bba74b36 10557 char *p, *endbuf;
dd61ec5c 10558 char *message;
3c3bea1c 10559
4082afcc 10560 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10561 return -1;
2bc416ba 10562
28439a30
PA
10563 /* Make sure the remote is pointing at the right process, if
10564 necessary. */
10565 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10566 set_general_process ();
10567
4fff2411
JZ
10568 rs = get_remote_state ();
10569 p = rs->buf;
bba74b36 10570 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 10571
96baa820
JM
10572 *(p++) = 'Z';
10573 *(p++) = '1';
10574 *(p++) = ',';
802188a7 10575
0d5ed153 10576 addr = remote_address_masked (addr);
96baa820 10577 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10578 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10579
f6ac5f3d 10580 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10581 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10582
f6ac5f3d 10583 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10584 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10585
6d820c5c
DJ
10586 putpkt (rs->buf);
10587 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10588
6d820c5c 10589 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10590 {
10591 case PACKET_ERROR:
dd61ec5c
MW
10592 if (rs->buf[1] == '.')
10593 {
10594 message = strchr (rs->buf + 2, '.');
10595 if (message)
0316657e 10596 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10597 }
10598 return -1;
d471ea57
AC
10599 case PACKET_UNKNOWN:
10600 return -1;
10601 case PACKET_OK:
10602 return 0;
10603 }
8e65ff28 10604 internal_error (__FILE__, __LINE__,
e2e0b3e5 10605 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10606}
10607
d471ea57 10608
f6ac5f3d
PA
10609int
10610remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10611 struct bp_target_info *bp_tgt)
96baa820 10612{
8181d85f 10613 CORE_ADDR addr;
d01949b6 10614 struct remote_state *rs = get_remote_state ();
6d820c5c 10615 char *p = rs->buf;
bba74b36 10616 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 10617
4082afcc 10618 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10619 return -1;
802188a7 10620
28439a30
PA
10621 /* Make sure the remote is pointing at the right process, if
10622 necessary. */
10623 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10624 set_general_process ();
10625
96baa820
JM
10626 *(p++) = 'z';
10627 *(p++) = '1';
10628 *(p++) = ',';
802188a7 10629
8181d85f 10630 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10631 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10632 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10633
6d820c5c
DJ
10634 putpkt (rs->buf);
10635 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 10636
6d820c5c 10637 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10638 {
10639 case PACKET_ERROR:
10640 case PACKET_UNKNOWN:
10641 return -1;
10642 case PACKET_OK:
10643 return 0;
10644 }
8e65ff28 10645 internal_error (__FILE__, __LINE__,
e2e0b3e5 10646 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10647}
96baa820 10648
4a5e7a5b
PA
10649/* Verify memory using the "qCRC:" request. */
10650
f6ac5f3d
PA
10651int
10652remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
10653{
10654 struct remote_state *rs = get_remote_state ();
10655 unsigned long host_crc, target_crc;
10656 char *tmp;
10657
936d2992
PA
10658 /* It doesn't make sense to use qCRC if the remote target is
10659 connected but not running. */
10660 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10661 {
10662 enum packet_result result;
28439a30 10663
936d2992
PA
10664 /* Make sure the remote is pointing at the right process. */
10665 set_general_process ();
4a5e7a5b 10666
936d2992
PA
10667 /* FIXME: assumes lma can fit into long. */
10668 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10669 (long) lma, (long) size);
10670 putpkt (rs->buf);
4a5e7a5b 10671
936d2992
PA
10672 /* Be clever; compute the host_crc before waiting for target
10673 reply. */
10674 host_crc = xcrc32 (data, size, 0xffffffff);
10675
10676 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 10677
936d2992
PA
10678 result = packet_ok (rs->buf,
10679 &remote_protocol_packets[PACKET_qCRC]);
10680 if (result == PACKET_ERROR)
10681 return -1;
10682 else if (result == PACKET_OK)
10683 {
10684 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10685 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10686
936d2992
PA
10687 return (host_crc == target_crc);
10688 }
10689 }
4a5e7a5b 10690
f6ac5f3d 10691 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
10692}
10693
c906108c
SS
10694/* compare-sections command
10695
10696 With no arguments, compares each loadable section in the exec bfd
10697 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10698 Useful for verifying the image on the target against the exec file. */
e514a9d6 10699
c906108c 10700static void
ac88e2de 10701compare_sections_command (const char *args, int from_tty)
c906108c
SS
10702{
10703 asection *s;
ce359b09 10704 const char *sectname;
c906108c
SS
10705 bfd_size_type size;
10706 bfd_vma lma;
10707 int matched = 0;
10708 int mismatched = 0;
4a5e7a5b 10709 int res;
95cf3b38 10710 int read_only = 0;
c906108c
SS
10711
10712 if (!exec_bfd)
8a3fe4f8 10713 error (_("command cannot be used without an exec file"));
c906108c 10714
95cf3b38
DT
10715 if (args != NULL && strcmp (args, "-r") == 0)
10716 {
10717 read_only = 1;
10718 args = NULL;
10719 }
10720
c5aa993b 10721 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10722 {
10723 if (!(s->flags & SEC_LOAD))
0df8b418 10724 continue; /* Skip non-loadable section. */
c906108c 10725
95cf3b38
DT
10726 if (read_only && (s->flags & SEC_READONLY) == 0)
10727 continue; /* Skip writeable sections */
10728
2c500098 10729 size = bfd_get_section_size (s);
c906108c 10730 if (size == 0)
0df8b418 10731 continue; /* Skip zero-length section. */
c906108c 10732
ce359b09 10733 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10734 if (args && strcmp (args, sectname) != 0)
0df8b418 10735 continue; /* Not the section selected by user. */
c906108c 10736
0df8b418 10737 matched = 1; /* Do this section. */
c906108c 10738 lma = s->lma;
c906108c 10739
b80406ac
TT
10740 gdb::byte_vector sectdata (size);
10741 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
c906108c 10742
b80406ac 10743 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
10744
10745 if (res == -1)
5af949e3 10746 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10747 paddress (target_gdbarch (), lma),
10748 paddress (target_gdbarch (), lma + size));
c906108c 10749
5af949e3 10750 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10751 paddress (target_gdbarch (), lma),
10752 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10753 if (res)
c906108c
SS
10754 printf_filtered ("matched.\n");
10755 else
c5aa993b
JM
10756 {
10757 printf_filtered ("MIS-MATCHED!\n");
10758 mismatched++;
10759 }
c906108c
SS
10760 }
10761 if (mismatched > 0)
936d2992 10762 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10763the loaded file\n"));
c906108c 10764 if (args && !matched)
a3f17187 10765 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10766}
10767
0e7f50da
UW
10768/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10769 into remote target. The number of bytes written to the remote
10770 target is returned, or -1 for error. */
10771
6b8edb51
PA
10772target_xfer_status
10773remote_target::remote_write_qxfer (const char *object_name,
10774 const char *annex, const gdb_byte *writebuf,
10775 ULONGEST offset, LONGEST len,
10776 ULONGEST *xfered_len,
10777 struct packet_config *packet)
0e7f50da
UW
10778{
10779 int i, buf_len;
10780 ULONGEST n;
0e7f50da
UW
10781 struct remote_state *rs = get_remote_state ();
10782 int max_size = get_memory_write_packet_size ();
10783
7cc244de 10784 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10785 return TARGET_XFER_E_IO;
0e7f50da
UW
10786
10787 /* Insert header. */
10788 i = snprintf (rs->buf, max_size,
10789 "qXfer:%s:write:%s:%s:",
10790 object_name, annex ? annex : "",
10791 phex_nz (offset, sizeof offset));
10792 max_size -= (i + 1);
10793
10794 /* Escape as much data as fits into rs->buf. */
10795 buf_len = remote_escape_output
124e13d9 10796 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
10797
10798 if (putpkt_binary (rs->buf, i + buf_len) < 0
10799 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10800 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10801 return TARGET_XFER_E_IO;
0e7f50da
UW
10802
10803 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
10804
10805 *xfered_len = n;
92ffd475 10806 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
10807}
10808
0876f84a
DJ
10809/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10810 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10811 number of bytes read is returned, or 0 for EOF, or -1 for error.
10812 The number of bytes read may be less than LEN without indicating an
10813 EOF. PACKET is checked and updated to indicate whether the remote
10814 target supports this object. */
10815
6b8edb51
PA
10816target_xfer_status
10817remote_target::remote_read_qxfer (const char *object_name,
10818 const char *annex,
10819 gdb_byte *readbuf, ULONGEST offset,
10820 LONGEST len,
10821 ULONGEST *xfered_len,
10822 struct packet_config *packet)
0876f84a 10823{
0876f84a 10824 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10825 LONGEST i, n, packet_len;
10826
7cc244de 10827 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10828 return TARGET_XFER_E_IO;
0876f84a
DJ
10829
10830 /* Check whether we've cached an end-of-object packet that matches
10831 this request. */
8e88304f 10832 if (rs->finished_object)
0876f84a 10833 {
8e88304f
TT
10834 if (strcmp (object_name, rs->finished_object) == 0
10835 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10836 && offset == rs->finished_offset)
9b409511
YQ
10837 return TARGET_XFER_EOF;
10838
0876f84a
DJ
10839
10840 /* Otherwise, we're now reading something different. Discard
10841 the cache. */
8e88304f
TT
10842 xfree (rs->finished_object);
10843 xfree (rs->finished_annex);
10844 rs->finished_object = NULL;
10845 rs->finished_annex = NULL;
0876f84a
DJ
10846 }
10847
10848 /* Request only enough to fit in a single packet. The actual data
10849 may not, since we don't know how much of it will need to be escaped;
10850 the target is free to respond with slightly less data. We subtract
10851 five to account for the response type and the protocol frame. */
768adc05 10852 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
0876f84a
DJ
10853 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10854 object_name, annex ? annex : "",
10855 phex_nz (offset, sizeof offset),
10856 phex_nz (n, sizeof n));
10857 i = putpkt (rs->buf);
10858 if (i < 0)
2ed4b548 10859 return TARGET_XFER_E_IO;
0876f84a
DJ
10860
10861 rs->buf[0] = '\0';
10862 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10863 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10864 return TARGET_XFER_E_IO;
0876f84a
DJ
10865
10866 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10867 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10868
10869 /* 'm' means there is (or at least might be) more data after this
10870 batch. That does not make sense unless there's at least one byte
10871 of data in this reply. */
10872 if (rs->buf[0] == 'm' && packet_len == 1)
10873 error (_("Remote qXfer reply contained no data."));
10874
10875 /* Got some data. */
bc20a4af
PA
10876 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10877 packet_len - 1, readbuf, n);
0876f84a
DJ
10878
10879 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10880 or possibly empty. If we have the final block of a non-empty
10881 object, record this fact to bypass a subsequent partial read. */
10882 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10883 {
8e88304f
TT
10884 rs->finished_object = xstrdup (object_name);
10885 rs->finished_annex = xstrdup (annex ? annex : "");
10886 rs->finished_offset = offset + i;
0876f84a
DJ
10887 }
10888
9b409511
YQ
10889 if (i == 0)
10890 return TARGET_XFER_EOF;
10891 else
10892 {
10893 *xfered_len = i;
10894 return TARGET_XFER_OK;
10895 }
0876f84a
DJ
10896}
10897
f6ac5f3d
PA
10898enum target_xfer_status
10899remote_target::xfer_partial (enum target_object object,
10900 const char *annex, gdb_byte *readbuf,
10901 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10902 ULONGEST *xfered_len)
c906108c 10903{
82f73884 10904 struct remote_state *rs;
c906108c 10905 int i;
6d820c5c 10906 char *p2;
1e3ff5ad 10907 char query_type;
124e13d9 10908 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 10909
e6e4e701 10910 set_remote_traceframe ();
82f73884
PA
10911 set_general_thread (inferior_ptid);
10912
10913 rs = get_remote_state ();
10914
b2182ed2 10915 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
10916 if (object == TARGET_OBJECT_MEMORY)
10917 {
2d717e4f
DJ
10918 /* If the remote target is connected but not running, we should
10919 pass this request down to a lower stratum (e.g. the executable
10920 file). */
10921 if (!target_has_execution)
9b409511 10922 return TARGET_XFER_EOF;
2d717e4f 10923
21e3b9b9 10924 if (writebuf != NULL)
124e13d9
SM
10925 return remote_write_bytes (offset, writebuf, len, unit_size,
10926 xfered_len);
21e3b9b9 10927 else
6b8edb51 10928 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 10929 xfered_len);
21e3b9b9
DJ
10930 }
10931
0df8b418 10932 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10933 if (object == TARGET_OBJECT_SPU)
10934 {
10935 if (readbuf)
f6ac5f3d 10936 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
9b409511
YQ
10937 xfered_len, &remote_protocol_packets
10938 [PACKET_qXfer_spu_read]);
0e7f50da 10939 else
f6ac5f3d 10940 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
9b409511
YQ
10941 xfered_len, &remote_protocol_packets
10942 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10943 }
10944
4aa995e1
PA
10945 /* Handle extra signal info using qxfer packets. */
10946 if (object == TARGET_OBJECT_SIGNAL_INFO)
10947 {
10948 if (readbuf)
f6ac5f3d 10949 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
9b409511 10950 xfered_len, &remote_protocol_packets
4aa995e1
PA
10951 [PACKET_qXfer_siginfo_read]);
10952 else
f6ac5f3d 10953 return remote_write_qxfer ("siginfo", annex,
9b409511 10954 writebuf, offset, len, xfered_len,
4aa995e1
PA
10955 &remote_protocol_packets
10956 [PACKET_qXfer_siginfo_write]);
10957 }
10958
0fb4aa4b
PA
10959 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10960 {
10961 if (readbuf)
f6ac5f3d 10962 return remote_read_qxfer ("statictrace", annex,
9b409511 10963 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10964 &remote_protocol_packets
10965 [PACKET_qXfer_statictrace_read]);
10966 else
2ed4b548 10967 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10968 }
10969
a76d924d
DJ
10970 /* Only handle flash writes. */
10971 if (writebuf != NULL)
10972 {
a76d924d
DJ
10973 switch (object)
10974 {
10975 case TARGET_OBJECT_FLASH:
6b8edb51 10976 return remote_flash_write (offset, len, xfered_len,
9b409511 10977 writebuf);
a76d924d
DJ
10978
10979 default:
2ed4b548 10980 return TARGET_XFER_E_IO;
a76d924d
DJ
10981 }
10982 }
4b8a223f 10983
1e3ff5ad
AC
10984 /* Map pre-existing objects onto letters. DO NOT do this for new
10985 objects!!! Instead specify new query packets. */
10986 switch (object)
c906108c 10987 {
1e3ff5ad
AC
10988 case TARGET_OBJECT_AVR:
10989 query_type = 'R';
10990 break;
802188a7
RM
10991
10992 case TARGET_OBJECT_AUXV:
0876f84a 10993 gdb_assert (annex == NULL);
f6ac5f3d 10994 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
9b409511 10995 xfered_len,
0876f84a 10996 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10997
23181151
DJ
10998 case TARGET_OBJECT_AVAILABLE_FEATURES:
10999 return remote_read_qxfer
f6ac5f3d 11000 ("features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
11001 &remote_protocol_packets[PACKET_qXfer_features]);
11002
cfa9d6d9
DJ
11003 case TARGET_OBJECT_LIBRARIES:
11004 return remote_read_qxfer
f6ac5f3d 11005 ("libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
11006 &remote_protocol_packets[PACKET_qXfer_libraries]);
11007
2268b414
JK
11008 case TARGET_OBJECT_LIBRARIES_SVR4:
11009 return remote_read_qxfer
f6ac5f3d 11010 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
11011 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11012
fd79ecee
DJ
11013 case TARGET_OBJECT_MEMORY_MAP:
11014 gdb_assert (annex == NULL);
f6ac5f3d 11015 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
9b409511 11016 xfered_len,
fd79ecee
DJ
11017 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11018
07e059b5
VP
11019 case TARGET_OBJECT_OSDATA:
11020 /* Should only get here if we're connected. */
5d93a237 11021 gdb_assert (rs->remote_desc);
07e059b5 11022 return remote_read_qxfer
f6ac5f3d 11023 ("osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
11024 &remote_protocol_packets[PACKET_qXfer_osdata]);
11025
dc146f7c
VP
11026 case TARGET_OBJECT_THREADS:
11027 gdb_assert (annex == NULL);
f6ac5f3d 11028 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
9b409511 11029 xfered_len,
dc146f7c
VP
11030 &remote_protocol_packets[PACKET_qXfer_threads]);
11031
b3b9301e
PA
11032 case TARGET_OBJECT_TRACEFRAME_INFO:
11033 gdb_assert (annex == NULL);
11034 return remote_read_qxfer
f6ac5f3d 11035 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 11036 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
11037
11038 case TARGET_OBJECT_FDPIC:
f6ac5f3d 11039 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
9b409511 11040 xfered_len,
78d85199 11041 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
11042
11043 case TARGET_OBJECT_OPENVMS_UIB:
f6ac5f3d 11044 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
9b409511 11045 xfered_len,
169081d0
TG
11046 &remote_protocol_packets[PACKET_qXfer_uib]);
11047
9accd112 11048 case TARGET_OBJECT_BTRACE:
f6ac5f3d 11049 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
9b409511 11050 xfered_len,
9accd112
MM
11051 &remote_protocol_packets[PACKET_qXfer_btrace]);
11052
f4abbc16 11053 case TARGET_OBJECT_BTRACE_CONF:
f6ac5f3d 11054 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
f4abbc16
MM
11055 len, xfered_len,
11056 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11057
c78fa86a 11058 case TARGET_OBJECT_EXEC_FILE:
f6ac5f3d 11059 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
c78fa86a
GB
11060 len, xfered_len,
11061 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11062
1e3ff5ad 11063 default:
2ed4b548 11064 return TARGET_XFER_E_IO;
c906108c
SS
11065 }
11066
0df8b418 11067 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11068 large enough let the caller deal with it. */
ea9c271d 11069 if (len < get_remote_packet_size ())
2ed4b548 11070 return TARGET_XFER_E_IO;
ea9c271d 11071 len = get_remote_packet_size ();
1e3ff5ad 11072
23860348 11073 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11074 if (!rs->remote_desc)
8a3fe4f8 11075 error (_("remote query is only available after target open"));
c906108c 11076
1e3ff5ad 11077 gdb_assert (annex != NULL);
4b8a223f 11078 gdb_assert (readbuf != NULL);
c906108c 11079
6d820c5c 11080 p2 = rs->buf;
c906108c
SS
11081 *p2++ = 'q';
11082 *p2++ = query_type;
11083
23860348
MS
11084 /* We used one buffer char for the remote protocol q command and
11085 another for the query type. As the remote protocol encapsulation
11086 uses 4 chars plus one extra in case we are debugging
11087 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11088 string. */
c906108c 11089 i = 0;
ea9c271d 11090 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11091 {
1e3ff5ad
AC
11092 /* Bad caller may have sent forbidden characters. */
11093 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11094 *p2++ = annex[i];
c906108c
SS
11095 i++;
11096 }
1e3ff5ad
AC
11097 *p2 = '\0';
11098 gdb_assert (annex[i] == '\0');
c906108c 11099
6d820c5c 11100 i = putpkt (rs->buf);
c5aa993b 11101 if (i < 0)
2ed4b548 11102 return TARGET_XFER_E_IO;
c906108c 11103
6d820c5c
DJ
11104 getpkt (&rs->buf, &rs->buf_size, 0);
11105 strcpy ((char *) readbuf, rs->buf);
c906108c 11106
9b409511 11107 *xfered_len = strlen ((char *) readbuf);
92ffd475 11108 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11109}
11110
09c98b44
DB
11111/* Implementation of to_get_memory_xfer_limit. */
11112
f6ac5f3d
PA
11113ULONGEST
11114remote_target::get_memory_xfer_limit ()
09c98b44
DB
11115{
11116 return get_memory_write_packet_size ();
11117}
11118
f6ac5f3d
PA
11119int
11120remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11121 const gdb_byte *pattern, ULONGEST pattern_len,
11122 CORE_ADDR *found_addrp)
08388c79 11123{
f5656ead 11124 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
11125 struct remote_state *rs = get_remote_state ();
11126 int max_size = get_memory_write_packet_size ();
11127 struct packet_config *packet =
11128 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
11129 /* Number of packet bytes used to encode the pattern;
11130 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11131 int escaped_pattern_len;
0df8b418 11132 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11133 int used_pattern_len;
11134 int i;
11135 int found;
11136 ULONGEST found_addr;
11137
7cc244de
PA
11138 /* Don't go to the target if we don't have to. This is done before
11139 checking packet_config_support to avoid the possibility that a
11140 success for this edge case means the facility works in
11141 general. */
08388c79
DE
11142 if (pattern_len > search_space_len)
11143 return 0;
11144 if (pattern_len == 0)
11145 {
11146 *found_addrp = start_addr;
11147 return 1;
11148 }
11149
11150 /* If we already know the packet isn't supported, fall back to the simple
11151 way of searching memory. */
11152
4082afcc 11153 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
11154 {
11155 /* Target doesn't provided special support, fall back and use the
11156 standard support (copy memory and do the search here). */
f6ac5f3d 11157 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11158 pattern, pattern_len, found_addrp);
11159 }
11160
28439a30
PA
11161 /* Make sure the remote is pointing at the right process. */
11162 set_general_process ();
11163
08388c79
DE
11164 /* Insert header. */
11165 i = snprintf (rs->buf, max_size,
11166 "qSearch:memory:%s;%s;",
5af949e3 11167 phex_nz (start_addr, addr_size),
08388c79
DE
11168 phex_nz (search_space_len, sizeof (search_space_len)));
11169 max_size -= (i + 1);
11170
11171 /* Escape as much data as fits into rs->buf. */
11172 escaped_pattern_len =
124e13d9 11173 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
11174 &used_pattern_len, max_size);
11175
11176 /* Bail if the pattern is too large. */
11177 if (used_pattern_len != pattern_len)
9b20d036 11178 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
11179
11180 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11181 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11182 || packet_ok (rs->buf, packet) != PACKET_OK)
11183 {
11184 /* The request may not have worked because the command is not
11185 supported. If so, fall back to the simple way. */
7cc244de 11186 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79 11187 {
f6ac5f3d 11188 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11189 pattern, pattern_len, found_addrp);
11190 }
11191 return -1;
11192 }
11193
11194 if (rs->buf[0] == '0')
11195 found = 0;
11196 else if (rs->buf[0] == '1')
11197 {
11198 found = 1;
11199 if (rs->buf[1] != ',')
10e0fa18 11200 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
11201 unpack_varlen_hex (rs->buf + 2, &found_addr);
11202 *found_addrp = found_addr;
11203 }
11204 else
10e0fa18 11205 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
11206
11207 return found;
11208}
11209
f6ac5f3d
PA
11210void
11211remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11212{
d01949b6 11213 struct remote_state *rs = get_remote_state ();
2e9f7625 11214 char *p = rs->buf;
96baa820 11215
5d93a237 11216 if (!rs->remote_desc)
8a3fe4f8 11217 error (_("remote rcmd is only available after target open"));
96baa820 11218
23860348 11219 /* Send a NULL command across as an empty command. */
7be570e7
JM
11220 if (command == NULL)
11221 command = "";
11222
23860348 11223 /* The query prefix. */
2e9f7625
DJ
11224 strcpy (rs->buf, "qRcmd,");
11225 p = strchr (rs->buf, '\0');
96baa820 11226
3e43a32a
MS
11227 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11228 > get_remote_packet_size ())
8a3fe4f8 11229 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11230
23860348 11231 /* Encode the actual command. */
a30bf1f1 11232 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11233
6d820c5c 11234 if (putpkt (rs->buf) < 0)
8a3fe4f8 11235 error (_("Communication problem with target."));
96baa820
JM
11236
11237 /* get/display the response */
11238 while (1)
11239 {
2e9f7625
DJ
11240 char *buf;
11241
00bf0b85 11242 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11243 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11244 rs->buf[0] = '\0';
5b37825d
PW
11245 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11246 {
11247 /* Timeout. Continue to (try to) read responses.
11248 This is better than stopping with an error, assuming the stub
11249 is still executing the (long) monitor command.
11250 If needed, the user can interrupt gdb using C-c, obtaining
11251 an effect similar to stop on timeout. */
11252 continue;
11253 }
2e9f7625 11254 buf = rs->buf;
96baa820 11255 if (buf[0] == '\0')
8a3fe4f8 11256 error (_("Target does not support this command."));
96baa820
JM
11257 if (buf[0] == 'O' && buf[1] != 'K')
11258 {
23860348 11259 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11260 continue;
11261 }
11262 if (strcmp (buf, "OK") == 0)
11263 break;
7be570e7
JM
11264 if (strlen (buf) == 3 && buf[0] == 'E'
11265 && isdigit (buf[1]) && isdigit (buf[2]))
11266 {
8a3fe4f8 11267 error (_("Protocol error with Rcmd"));
7be570e7 11268 }
96baa820
JM
11269 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11270 {
11271 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11272
96baa820
JM
11273 fputc_unfiltered (c, outbuf);
11274 }
11275 break;
11276 }
11277}
11278
f6ac5f3d
PA
11279std::vector<mem_region>
11280remote_target::memory_map ()
fd79ecee 11281{
a664f67e 11282 std::vector<mem_region> result;
9018be22 11283 gdb::optional<gdb::char_vector> text
8b88a78e 11284 = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11285
11286 if (text)
9018be22 11287 result = parse_memory_map (text->data ());
fd79ecee
DJ
11288
11289 return result;
11290}
11291
c906108c 11292static void
ac88e2de 11293packet_command (const char *args, int from_tty)
c906108c 11294{
6b8edb51 11295 remote_target *remote = get_current_remote_target ();
c906108c 11296
6b8edb51 11297 if (remote == nullptr)
8a3fe4f8 11298 error (_("command can only be used with remote target"));
c906108c 11299
6b8edb51
PA
11300 remote->packet_command (args, from_tty);
11301}
11302
11303void
11304remote_target::packet_command (const char *args, int from_tty)
11305{
c5aa993b 11306 if (!args)
8a3fe4f8 11307 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
11308
11309 puts_filtered ("sending: ");
11310 print_packet (args);
11311 puts_filtered ("\n");
11312 putpkt (args);
11313
6b8edb51
PA
11314 remote_state *rs = get_remote_state ();
11315
6d820c5c 11316 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 11317 puts_filtered ("received: ");
6d820c5c 11318 print_packet (rs->buf);
c906108c
SS
11319 puts_filtered ("\n");
11320}
11321
11322#if 0
23860348 11323/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11324
a14ed312 11325static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11326
a14ed312 11327static void threadset_test_cmd (char *cmd, int tty);
c906108c 11328
a14ed312 11329static void threadalive_test (char *cmd, int tty);
c906108c 11330
a14ed312 11331static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11332
23860348 11333int get_and_display_threadinfo (threadref *ref);
c906108c 11334
a14ed312 11335static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11336
23860348 11337static int thread_display_step (threadref *ref, void *context);
c906108c 11338
a14ed312 11339static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11340
a14ed312 11341static void init_remote_threadtests (void);
c906108c 11342
23860348 11343#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11344
11345static void
0b39b52e 11346threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11347{
11348 int sample_thread = SAMPLE_THREAD;
11349
a3f17187 11350 printf_filtered (_("Remote threadset test\n"));
79d7f229 11351 set_general_thread (sample_thread);
c906108c
SS
11352}
11353
11354
11355static void
0b39b52e 11356threadalive_test (const char *cmd, int tty)
c906108c
SS
11357{
11358 int sample_thread = SAMPLE_THREAD;
e99b03dc 11359 int pid = inferior_ptid.pid ();
fd79271b 11360 ptid_t ptid = ptid_t (pid, sample_thread, 0);
c906108c 11361
79d7f229 11362 if (remote_thread_alive (ptid))
c906108c
SS
11363 printf_filtered ("PASS: Thread alive test\n");
11364 else
11365 printf_filtered ("FAIL: Thread alive test\n");
11366}
11367
23860348 11368void output_threadid (char *title, threadref *ref);
c906108c
SS
11369
11370void
fba45db2 11371output_threadid (char *title, threadref *ref)
c906108c
SS
11372{
11373 char hexid[20];
11374
23860348 11375 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
11376 hexid[16] = 0;
11377 printf_filtered ("%s %s\n", title, (&hexid[0]));
11378}
11379
11380static void
0b39b52e 11381threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11382{
11383 int startflag = 1;
11384 threadref nextthread;
11385 int done, result_count;
11386 threadref threadlist[3];
11387
11388 printf_filtered ("Remote Threadlist test\n");
11389 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11390 &result_count, &threadlist[0]))
11391 printf_filtered ("FAIL: threadlist test\n");
11392 else
11393 {
11394 threadref *scan = threadlist;
11395 threadref *limit = scan + result_count;
11396
11397 while (scan < limit)
11398 output_threadid (" thread ", scan++);
11399 }
11400}
11401
11402void
fba45db2 11403display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11404{
11405 output_threadid ("Threadid: ", &info->threadid);
11406 printf_filtered ("Name: %s\n ", info->shortname);
11407 printf_filtered ("State: %s\n", info->display);
11408 printf_filtered ("other: %s\n\n", info->more_display);
11409}
11410
11411int
fba45db2 11412get_and_display_threadinfo (threadref *ref)
c906108c
SS
11413{
11414 int result;
11415 int set;
11416 struct gdb_ext_thread_info threadinfo;
11417
11418 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11419 | TAG_MOREDISPLAY | TAG_DISPLAY;
11420 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11421 display_thread_info (&threadinfo);
11422 return result;
11423}
11424
11425static void
0b39b52e 11426threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11427{
11428 int athread = SAMPLE_THREAD;
11429 threadref thread;
11430 int set;
11431
11432 int_to_threadref (&thread, athread);
11433 printf_filtered ("Remote Threadinfo test\n");
11434 if (!get_and_display_threadinfo (&thread))
11435 printf_filtered ("FAIL cannot get thread info\n");
11436}
11437
11438static int
fba45db2 11439thread_display_step (threadref *ref, void *context)
c906108c
SS
11440{
11441 /* output_threadid(" threadstep ",ref); *//* simple test */
11442 return get_and_display_threadinfo (ref);
11443}
11444
11445static void
0b39b52e 11446threadlist_update_test_cmd (const char *cmd, int tty)
c906108c
SS
11447{
11448 printf_filtered ("Remote Threadlist update test\n");
11449 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11450}
11451
11452static void
11453init_remote_threadtests (void)
11454{
3e43a32a
MS
11455 add_com ("tlist", class_obscure, threadlist_test_cmd,
11456 _("Fetch and print the remote list of "
11457 "thread identifiers, one pkt only"));
c906108c 11458 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 11459 _("Fetch and display info about one thread"));
c906108c 11460 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 11461 _("Test setting to a different thread"));
c906108c 11462 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 11463 _("Iterate through updating all remote thread info"));
c906108c 11464 add_com ("talive", class_obscure, threadalive_test,
1bedd215 11465 _(" Remote thread alive test "));
c906108c
SS
11466}
11467
11468#endif /* 0 */
11469
f3fb8c85
MS
11470/* Convert a thread ID to a string. Returns the string in a static
11471 buffer. */
11472
f6ac5f3d
PA
11473const char *
11474remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11475{
79d7f229 11476 static char buf[64];
82f73884 11477 struct remote_state *rs = get_remote_state ();
f3fb8c85 11478
d7e15655 11479 if (ptid == null_ptid)
7cee1e54 11480 return normal_pid_to_str (ptid);
0e998d96 11481 else if (ptid.is_pid ())
ecd0ada5
PA
11482 {
11483 /* Printing an inferior target id. */
11484
11485 /* When multi-process extensions are off, there's no way in the
11486 remote protocol to know the remote process id, if there's any
11487 at all. There's one exception --- when we're connected with
11488 target extended-remote, and we manually attached to a process
11489 with "attach PID". We don't record anywhere a flag that
11490 allows us to distinguish that case from the case of
11491 connecting with extended-remote and the stub already being
11492 attached to a process, and reporting yes to qAttached, hence
11493 no smart special casing here. */
11494 if (!remote_multi_process_p (rs))
11495 {
11496 xsnprintf (buf, sizeof buf, "Remote target");
11497 return buf;
11498 }
11499
11500 return normal_pid_to_str (ptid);
82f73884 11501 }
ecd0ada5 11502 else
79d7f229 11503 {
d7e15655 11504 if (magic_null_ptid == ptid)
ecd0ada5 11505 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 11506 else if (remote_multi_process_p (rs))
e38504b3 11507 if (ptid.lwp () == 0)
de0d863e
DB
11508 return normal_pid_to_str (ptid);
11509 else
11510 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
e38504b3 11511 ptid.pid (), ptid.lwp ());
ecd0ada5
PA
11512 else
11513 xsnprintf (buf, sizeof buf, "Thread %ld",
e38504b3 11514 ptid.lwp ());
79d7f229
PA
11515 return buf;
11516 }
f3fb8c85
MS
11517}
11518
38691318
KB
11519/* Get the address of the thread local variable in OBJFILE which is
11520 stored at OFFSET within the thread local storage for thread PTID. */
11521
f6ac5f3d
PA
11522CORE_ADDR
11523remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11524 CORE_ADDR offset)
38691318 11525{
4082afcc 11526 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11527 {
11528 struct remote_state *rs = get_remote_state ();
6d820c5c 11529 char *p = rs->buf;
82f73884 11530 char *endp = rs->buf + get_remote_packet_size ();
571dd617 11531 enum packet_result result;
38691318
KB
11532
11533 strcpy (p, "qGetTLSAddr:");
11534 p += strlen (p);
82f73884 11535 p = write_ptid (p, endp, ptid);
38691318
KB
11536 *p++ = ',';
11537 p += hexnumstr (p, offset);
11538 *p++ = ',';
11539 p += hexnumstr (p, lm);
11540 *p++ = '\0';
11541
6d820c5c
DJ
11542 putpkt (rs->buf);
11543 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
11544 result = packet_ok (rs->buf,
11545 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11546 if (result == PACKET_OK)
38691318 11547 {
b926417a 11548 ULONGEST addr;
38691318 11549
b926417a
TT
11550 unpack_varlen_hex (rs->buf, &addr);
11551 return addr;
38691318 11552 }
571dd617 11553 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11554 throw_error (TLS_GENERIC_ERROR,
11555 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11556 else
109c3e39
AC
11557 throw_error (TLS_GENERIC_ERROR,
11558 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11559 }
11560 else
109c3e39
AC
11561 throw_error (TLS_GENERIC_ERROR,
11562 _("TLS not supported or disabled on this target"));
38691318
KB
11563 /* Not reached. */
11564 return 0;
11565}
11566
711e434b
PM
11567/* Provide thread local base, i.e. Thread Information Block address.
11568 Returns 1 if ptid is found and thread_local_base is non zero. */
11569
57810aa7 11570bool
f6ac5f3d 11571remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 11572{
4082afcc 11573 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11574 {
11575 struct remote_state *rs = get_remote_state ();
11576 char *p = rs->buf;
11577 char *endp = rs->buf + get_remote_packet_size ();
11578 enum packet_result result;
11579
11580 strcpy (p, "qGetTIBAddr:");
11581 p += strlen (p);
11582 p = write_ptid (p, endp, ptid);
11583 *p++ = '\0';
11584
11585 putpkt (rs->buf);
11586 getpkt (&rs->buf, &rs->buf_size, 0);
11587 result = packet_ok (rs->buf,
11588 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11589 if (result == PACKET_OK)
11590 {
b926417a
TT
11591 ULONGEST val;
11592 unpack_varlen_hex (rs->buf, &val);
711e434b 11593 if (addr)
b926417a 11594 *addr = (CORE_ADDR) val;
57810aa7 11595 return true;
711e434b
PM
11596 }
11597 else if (result == PACKET_UNKNOWN)
11598 error (_("Remote target doesn't support qGetTIBAddr packet"));
11599 else
11600 error (_("Remote target failed to process qGetTIBAddr request"));
11601 }
11602 else
11603 error (_("qGetTIBAddr not supported or disabled on this target"));
11604 /* Not reached. */
57810aa7 11605 return false;
711e434b
PM
11606}
11607
29709017
DJ
11608/* Support for inferring a target description based on the current
11609 architecture and the size of a 'g' packet. While the 'g' packet
11610 can have any size (since optional registers can be left off the
11611 end), some sizes are easily recognizable given knowledge of the
11612 approximate architecture. */
11613
11614struct remote_g_packet_guess
11615{
11616 int bytes;
11617 const struct target_desc *tdesc;
11618};
11619typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11620DEF_VEC_O(remote_g_packet_guess_s);
11621
11622struct remote_g_packet_data
11623{
11624 VEC(remote_g_packet_guess_s) *guesses;
11625};
11626
11627static struct gdbarch_data *remote_g_packet_data_handle;
11628
11629static void *
11630remote_g_packet_data_init (struct obstack *obstack)
11631{
11632 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11633}
11634
11635void
11636register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11637 const struct target_desc *tdesc)
11638{
11639 struct remote_g_packet_data *data
19ba03f4
SM
11640 = ((struct remote_g_packet_data *)
11641 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11642 struct remote_g_packet_guess new_guess, *guess;
11643 int ix;
11644
11645 gdb_assert (tdesc != NULL);
11646
11647 for (ix = 0;
11648 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11649 ix++)
11650 if (guess->bytes == bytes)
11651 internal_error (__FILE__, __LINE__,
9b20d036 11652 _("Duplicate g packet description added for size %d"),
29709017
DJ
11653 bytes);
11654
11655 new_guess.bytes = bytes;
11656 new_guess.tdesc = tdesc;
11657 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11658}
11659
d962ef82
DJ
11660/* Return 1 if remote_read_description would do anything on this target
11661 and architecture, 0 otherwise. */
11662
11663static int
11664remote_read_description_p (struct target_ops *target)
11665{
11666 struct remote_g_packet_data *data
19ba03f4
SM
11667 = ((struct remote_g_packet_data *)
11668 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
11669
11670 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11671 return 1;
11672
11673 return 0;
11674}
11675
f6ac5f3d
PA
11676const struct target_desc *
11677remote_target::read_description ()
29709017
DJ
11678{
11679 struct remote_g_packet_data *data
19ba03f4
SM
11680 = ((struct remote_g_packet_data *)
11681 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11682
d962ef82
DJ
11683 /* Do not try this during initial connection, when we do not know
11684 whether there is a running but stopped thread. */
d7e15655 11685 if (!target_has_execution || inferior_ptid == null_ptid)
b6a8c27b 11686 return beneath ()->read_description ();
d962ef82 11687
29709017
DJ
11688 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11689 {
11690 struct remote_g_packet_guess *guess;
11691 int ix;
11692 int bytes = send_g_packet ();
11693
11694 for (ix = 0;
11695 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11696 ix++)
11697 if (guess->bytes == bytes)
11698 return guess->tdesc;
11699
11700 /* We discard the g packet. A minor optimization would be to
11701 hold on to it, and fill the register cache once we have selected
11702 an architecture, but it's too tricky to do safely. */
11703 }
11704
b6a8c27b 11705 return beneath ()->read_description ();
29709017
DJ
11706}
11707
a6b151f1
DJ
11708/* Remote file transfer support. This is host-initiated I/O, not
11709 target-initiated; for target-initiated, see remote-fileio.c. */
11710
11711/* If *LEFT is at least the length of STRING, copy STRING to
11712 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11713 decrease *LEFT. Otherwise raise an error. */
11714
11715static void
a121b7c1 11716remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11717{
11718 int len = strlen (string);
11719
11720 if (len > *left)
11721 error (_("Packet too long for target."));
11722
11723 memcpy (*buffer, string, len);
11724 *buffer += len;
11725 *left -= len;
11726
11727 /* NUL-terminate the buffer as a convenience, if there is
11728 room. */
11729 if (*left)
11730 **buffer = '\0';
11731}
11732
11733/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11734 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11735 decrease *LEFT. Otherwise raise an error. */
11736
11737static void
11738remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11739 int len)
11740{
11741 if (2 * len > *left)
11742 error (_("Packet too long for target."));
11743
11744 bin2hex (bytes, *buffer, len);
11745 *buffer += 2 * len;
11746 *left -= 2 * len;
11747
11748 /* NUL-terminate the buffer as a convenience, if there is
11749 room. */
11750 if (*left)
11751 **buffer = '\0';
11752}
11753
11754/* If *LEFT is large enough, convert VALUE to hex and add it to
11755 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11756 decrease *LEFT. Otherwise raise an error. */
11757
11758static void
11759remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11760{
11761 int len = hexnumlen (value);
11762
11763 if (len > *left)
11764 error (_("Packet too long for target."));
11765
11766 hexnumstr (*buffer, value);
11767 *buffer += len;
11768 *left -= len;
11769
11770 /* NUL-terminate the buffer as a convenience, if there is
11771 room. */
11772 if (*left)
11773 **buffer = '\0';
11774}
11775
11776/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11777 value, *REMOTE_ERRNO to the remote error number or zero if none
11778 was included, and *ATTACHMENT to point to the start of the annex
11779 if any. The length of the packet isn't needed here; there may
11780 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11781
11782 Return 0 if the packet could be parsed, -1 if it could not. If
11783 -1 is returned, the other variables may not be initialized. */
11784
11785static int
11786remote_hostio_parse_result (char *buffer, int *retcode,
11787 int *remote_errno, char **attachment)
11788{
11789 char *p, *p2;
11790
11791 *remote_errno = 0;
11792 *attachment = NULL;
11793
11794 if (buffer[0] != 'F')
11795 return -1;
11796
11797 errno = 0;
11798 *retcode = strtol (&buffer[1], &p, 16);
11799 if (errno != 0 || p == &buffer[1])
11800 return -1;
11801
11802 /* Check for ",errno". */
11803 if (*p == ',')
11804 {
11805 errno = 0;
11806 *remote_errno = strtol (p + 1, &p2, 16);
11807 if (errno != 0 || p + 1 == p2)
11808 return -1;
11809 p = p2;
11810 }
11811
11812 /* Check for ";attachment". If there is no attachment, the
11813 packet should end here. */
11814 if (*p == ';')
11815 {
11816 *attachment = p + 1;
11817 return 0;
11818 }
11819 else if (*p == '\0')
11820 return 0;
11821 else
11822 return -1;
11823}
11824
11825/* Send a prepared I/O packet to the target and read its response.
11826 The prepared packet is in the global RS->BUF before this function
11827 is called, and the answer is there when we return.
11828
11829 COMMAND_BYTES is the length of the request to send, which may include
11830 binary data. WHICH_PACKET is the packet configuration to check
11831 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11832 is set to the error number and -1 is returned. Otherwise the value
11833 returned by the function is returned.
11834
11835 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11836 attachment is expected; an error will be reported if there's a
11837 mismatch. If one is found, *ATTACHMENT will be set to point into
11838 the packet buffer and *ATTACHMENT_LEN will be set to the
11839 attachment's length. */
11840
6b8edb51
PA
11841int
11842remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11843 int *remote_errno, char **attachment,
11844 int *attachment_len)
a6b151f1
DJ
11845{
11846 struct remote_state *rs = get_remote_state ();
11847 int ret, bytes_read;
11848 char *attachment_tmp;
11849
20db9c52 11850 if (packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11851 {
11852 *remote_errno = FILEIO_ENOSYS;
11853 return -1;
11854 }
11855
11856 putpkt_binary (rs->buf, command_bytes);
11857 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11858
11859 /* If it timed out, something is wrong. Don't try to parse the
11860 buffer. */
11861 if (bytes_read < 0)
11862 {
11863 *remote_errno = FILEIO_EINVAL;
11864 return -1;
11865 }
11866
11867 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11868 {
11869 case PACKET_ERROR:
11870 *remote_errno = FILEIO_EINVAL;
11871 return -1;
11872 case PACKET_UNKNOWN:
11873 *remote_errno = FILEIO_ENOSYS;
11874 return -1;
11875 case PACKET_OK:
11876 break;
11877 }
11878
11879 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11880 &attachment_tmp))
11881 {
11882 *remote_errno = FILEIO_EINVAL;
11883 return -1;
11884 }
11885
11886 /* Make sure we saw an attachment if and only if we expected one. */
11887 if ((attachment_tmp == NULL && attachment != NULL)
11888 || (attachment_tmp != NULL && attachment == NULL))
11889 {
11890 *remote_errno = FILEIO_EINVAL;
11891 return -1;
11892 }
11893
11894 /* If an attachment was found, it must point into the packet buffer;
11895 work out how many bytes there were. */
11896 if (attachment_tmp != NULL)
11897 {
11898 *attachment = attachment_tmp;
11899 *attachment_len = bytes_read - (*attachment - rs->buf);
11900 }
11901
11902 return ret;
11903}
11904
dd194f6b 11905/* See declaration.h. */
80152258 11906
dd194f6b
PA
11907void
11908readahead_cache::invalidate ()
80152258 11909{
dd194f6b 11910 this->fd = -1;
80152258
PA
11911}
11912
dd194f6b 11913/* See declaration.h. */
80152258 11914
dd194f6b
PA
11915void
11916readahead_cache::invalidate_fd (int fd)
80152258 11917{
dd194f6b
PA
11918 if (this->fd == fd)
11919 this->fd = -1;
80152258
PA
11920}
11921
15a201c8
GB
11922/* Set the filesystem remote_hostio functions that take FILENAME
11923 arguments will use. Return 0 on success, or -1 if an error
11924 occurs (and set *REMOTE_ERRNO). */
11925
6b8edb51
PA
11926int
11927remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11928 int *remote_errno)
15a201c8
GB
11929{
11930 struct remote_state *rs = get_remote_state ();
11931 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11932 char *p = rs->buf;
11933 int left = get_remote_packet_size () - 1;
11934 char arg[9];
11935 int ret;
11936
11937 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11938 return 0;
11939
11940 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11941 return 0;
11942
11943 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11944
11945 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11946 remote_buffer_add_string (&p, &left, arg);
11947
11948 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11949 remote_errno, NULL, NULL);
11950
11951 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11952 return 0;
11953
11954 if (ret == 0)
11955 rs->fs_pid = required_pid;
11956
11957 return ret;
11958}
11959
12e2a5fd 11960/* Implementation of to_fileio_open. */
a6b151f1 11961
6b8edb51
PA
11962int
11963remote_target::remote_hostio_open (inferior *inf, const char *filename,
11964 int flags, int mode, int warn_if_slow,
11965 int *remote_errno)
a6b151f1
DJ
11966{
11967 struct remote_state *rs = get_remote_state ();
11968 char *p = rs->buf;
11969 int left = get_remote_packet_size () - 1;
11970
4313b8c0
GB
11971 if (warn_if_slow)
11972 {
11973 static int warning_issued = 0;
11974
11975 printf_unfiltered (_("Reading %s from remote target...\n"),
11976 filename);
11977
11978 if (!warning_issued)
11979 {
11980 warning (_("File transfers from remote targets can be slow."
11981 " Use \"set sysroot\" to access files locally"
11982 " instead."));
11983 warning_issued = 1;
11984 }
11985 }
11986
15a201c8
GB
11987 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11988 return -1;
11989
a6b151f1
DJ
11990 remote_buffer_add_string (&p, &left, "vFile:open:");
11991
11992 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11993 strlen (filename));
11994 remote_buffer_add_string (&p, &left, ",");
11995
11996 remote_buffer_add_int (&p, &left, flags);
11997 remote_buffer_add_string (&p, &left, ",");
11998
11999 remote_buffer_add_int (&p, &left, mode);
12000
12001 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
12002 remote_errno, NULL, NULL);
12003}
12004
f6ac5f3d
PA
12005int
12006remote_target::fileio_open (struct inferior *inf, const char *filename,
12007 int flags, int mode, int warn_if_slow,
12008 int *remote_errno)
12009{
6b8edb51 12010 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
12011 remote_errno);
12012}
12013
12e2a5fd 12014/* Implementation of to_fileio_pwrite. */
a6b151f1 12015
6b8edb51
PA
12016int
12017remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12018 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12019{
12020 struct remote_state *rs = get_remote_state ();
12021 char *p = rs->buf;
12022 int left = get_remote_packet_size ();
12023 int out_len;
12024
dd194f6b 12025 rs->readahead_cache.invalidate_fd (fd);
80152258 12026
a6b151f1
DJ
12027 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12028
12029 remote_buffer_add_int (&p, &left, fd);
12030 remote_buffer_add_string (&p, &left, ",");
12031
12032 remote_buffer_add_int (&p, &left, offset);
12033 remote_buffer_add_string (&p, &left, ",");
12034
124e13d9 12035 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
12036 get_remote_packet_size () - (p - rs->buf));
12037
12038 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12039 remote_errno, NULL, NULL);
12040}
12041
f6ac5f3d
PA
12042int
12043remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12044 ULONGEST offset, int *remote_errno)
12045{
6b8edb51 12046 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12047}
12048
80152258
PA
12049/* Helper for the implementation of to_fileio_pread. Read the file
12050 from the remote side with vFile:pread. */
a6b151f1 12051
6b8edb51
PA
12052int
12053remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12054 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12055{
12056 struct remote_state *rs = get_remote_state ();
12057 char *p = rs->buf;
12058 char *attachment;
12059 int left = get_remote_packet_size ();
12060 int ret, attachment_len;
12061 int read_len;
12062
12063 remote_buffer_add_string (&p, &left, "vFile:pread:");
12064
12065 remote_buffer_add_int (&p, &left, fd);
12066 remote_buffer_add_string (&p, &left, ",");
12067
12068 remote_buffer_add_int (&p, &left, len);
12069 remote_buffer_add_string (&p, &left, ",");
12070
12071 remote_buffer_add_int (&p, &left, offset);
12072
12073 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12074 remote_errno, &attachment,
12075 &attachment_len);
12076
12077 if (ret < 0)
12078 return ret;
12079
bc20a4af 12080 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12081 read_buf, len);
12082 if (read_len != ret)
12083 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12084
12085 return ret;
12086}
12087
dd194f6b 12088/* See declaration.h. */
80152258 12089
dd194f6b
PA
12090int
12091readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12092 ULONGEST offset)
80152258 12093{
dd194f6b
PA
12094 if (this->fd == fd
12095 && this->offset <= offset
12096 && offset < this->offset + this->bufsize)
80152258 12097 {
dd194f6b 12098 ULONGEST max = this->offset + this->bufsize;
80152258
PA
12099
12100 if (offset + len > max)
12101 len = max - offset;
12102
dd194f6b 12103 memcpy (read_buf, this->buf + offset - this->offset, len);
80152258
PA
12104 return len;
12105 }
12106
12107 return 0;
12108}
12109
12110/* Implementation of to_fileio_pread. */
12111
6b8edb51
PA
12112int
12113remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12114 ULONGEST offset, int *remote_errno)
80152258
PA
12115{
12116 int ret;
12117 struct remote_state *rs = get_remote_state ();
dd194f6b 12118 readahead_cache *cache = &rs->readahead_cache;
80152258 12119
dd194f6b 12120 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12121 if (ret > 0)
12122 {
12123 cache->hit_count++;
12124
12125 if (remote_debug)
12126 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12127 pulongest (cache->hit_count));
12128 return ret;
12129 }
12130
12131 cache->miss_count++;
12132 if (remote_debug)
12133 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12134 pulongest (cache->miss_count));
12135
12136 cache->fd = fd;
12137 cache->offset = offset;
12138 cache->bufsize = get_remote_packet_size ();
224c3ddb 12139 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258 12140
6b8edb51 12141 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
80152258
PA
12142 cache->offset, remote_errno);
12143 if (ret <= 0)
12144 {
dd194f6b 12145 cache->invalidate_fd (fd);
80152258
PA
12146 return ret;
12147 }
12148
12149 cache->bufsize = ret;
dd194f6b 12150 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12151}
12152
f6ac5f3d
PA
12153int
12154remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12155 ULONGEST offset, int *remote_errno)
12156{
6b8edb51 12157 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12158}
12159
12e2a5fd 12160/* Implementation of to_fileio_close. */
a6b151f1 12161
6b8edb51
PA
12162int
12163remote_target::remote_hostio_close (int fd, int *remote_errno)
a6b151f1
DJ
12164{
12165 struct remote_state *rs = get_remote_state ();
12166 char *p = rs->buf;
12167 int left = get_remote_packet_size () - 1;
12168
dd194f6b 12169 rs->readahead_cache.invalidate_fd (fd);
80152258 12170
a6b151f1
DJ
12171 remote_buffer_add_string (&p, &left, "vFile:close:");
12172
12173 remote_buffer_add_int (&p, &left, fd);
12174
12175 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12176 remote_errno, NULL, NULL);
12177}
12178
f6ac5f3d
PA
12179int
12180remote_target::fileio_close (int fd, int *remote_errno)
12181{
6b8edb51 12182 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12183}
12184
12e2a5fd 12185/* Implementation of to_fileio_unlink. */
a6b151f1 12186
6b8edb51
PA
12187int
12188remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12189 int *remote_errno)
a6b151f1
DJ
12190{
12191 struct remote_state *rs = get_remote_state ();
12192 char *p = rs->buf;
12193 int left = get_remote_packet_size () - 1;
12194
15a201c8
GB
12195 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12196 return -1;
12197
a6b151f1
DJ
12198 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12199
12200 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12201 strlen (filename));
12202
12203 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12204 remote_errno, NULL, NULL);
12205}
12206
f6ac5f3d
PA
12207int
12208remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12209 int *remote_errno)
12210{
6b8edb51 12211 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12212}
12213
12e2a5fd 12214/* Implementation of to_fileio_readlink. */
b9e7b9c3 12215
f6ac5f3d
PA
12216gdb::optional<std::string>
12217remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12218 int *remote_errno)
b9e7b9c3
UW
12219{
12220 struct remote_state *rs = get_remote_state ();
12221 char *p = rs->buf;
12222 char *attachment;
12223 int left = get_remote_packet_size ();
12224 int len, attachment_len;
12225 int read_len;
b9e7b9c3 12226
15a201c8 12227 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12228 return {};
15a201c8 12229
b9e7b9c3
UW
12230 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12231
12232 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12233 strlen (filename));
12234
12235 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12236 remote_errno, &attachment,
12237 &attachment_len);
12238
12239 if (len < 0)
e0d3522b 12240 return {};
b9e7b9c3 12241
e0d3522b 12242 std::string ret (len, '\0');
b9e7b9c3 12243
bc20a4af 12244 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12245 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12246 if (read_len != len)
12247 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12248
b9e7b9c3
UW
12249 return ret;
12250}
12251
12e2a5fd 12252/* Implementation of to_fileio_fstat. */
0a93529c 12253
f6ac5f3d
PA
12254int
12255remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
0a93529c
GB
12256{
12257 struct remote_state *rs = get_remote_state ();
12258 char *p = rs->buf;
12259 int left = get_remote_packet_size ();
12260 int attachment_len, ret;
12261 char *attachment;
12262 struct fio_stat fst;
12263 int read_len;
12264
464b0089
GB
12265 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12266
12267 remote_buffer_add_int (&p, &left, fd);
12268
12269 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12270 remote_errno, &attachment,
12271 &attachment_len);
12272 if (ret < 0)
0a93529c 12273 {
464b0089
GB
12274 if (*remote_errno != FILEIO_ENOSYS)
12275 return ret;
12276
0a93529c
GB
12277 /* Strictly we should return -1, ENOSYS here, but when
12278 "set sysroot remote:" was implemented in August 2008
12279 BFD's need for a stat function was sidestepped with
12280 this hack. This was not remedied until March 2015
12281 so we retain the previous behavior to avoid breaking
12282 compatibility.
12283
12284 Note that the memset is a March 2015 addition; older
12285 GDBs set st_size *and nothing else* so the structure
12286 would have garbage in all other fields. This might
12287 break something but retaining the previous behavior
12288 here would be just too wrong. */
12289
12290 memset (st, 0, sizeof (struct stat));
12291 st->st_size = INT_MAX;
12292 return 0;
12293 }
12294
0a93529c
GB
12295 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12296 (gdb_byte *) &fst, sizeof (fst));
12297
12298 if (read_len != ret)
12299 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12300
12301 if (read_len != sizeof (fst))
12302 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12303 read_len, (int) sizeof (fst));
12304
12305 remote_fileio_to_host_stat (&fst, st);
12306
12307 return 0;
12308}
12309
12e2a5fd 12310/* Implementation of to_filesystem_is_local. */
e3dd7556 12311
57810aa7 12312bool
f6ac5f3d 12313remote_target::filesystem_is_local ()
e3dd7556
GB
12314{
12315 /* Valgrind GDB presents itself as a remote target but works
12316 on the local filesystem: it does not implement remote get
12317 and users are not expected to set a sysroot. To handle
12318 this case we treat the remote filesystem as local if the
12319 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12320 does not support vFile:open. */
a3be80c3 12321 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
12322 {
12323 enum packet_support ps = packet_support (PACKET_vFile_open);
12324
12325 if (ps == PACKET_SUPPORT_UNKNOWN)
12326 {
12327 int fd, remote_errno;
12328
12329 /* Try opening a file to probe support. The supplied
12330 filename is irrelevant, we only care about whether
12331 the stub recognizes the packet or not. */
6b8edb51 12332 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12333 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12334 &remote_errno);
12335
12336 if (fd >= 0)
6b8edb51 12337 remote_hostio_close (fd, &remote_errno);
e3dd7556
GB
12338
12339 ps = packet_support (PACKET_vFile_open);
12340 }
12341
12342 if (ps == PACKET_DISABLE)
12343 {
12344 static int warning_issued = 0;
12345
12346 if (!warning_issued)
12347 {
12348 warning (_("remote target does not support file"
12349 " transfer, attempting to access files"
12350 " from local filesystem."));
12351 warning_issued = 1;
12352 }
12353
57810aa7 12354 return true;
e3dd7556
GB
12355 }
12356 }
12357
57810aa7 12358 return false;
e3dd7556
GB
12359}
12360
a6b151f1
DJ
12361static int
12362remote_fileio_errno_to_host (int errnum)
12363{
12364 switch (errnum)
12365 {
12366 case FILEIO_EPERM:
12367 return EPERM;
12368 case FILEIO_ENOENT:
12369 return ENOENT;
12370 case FILEIO_EINTR:
12371 return EINTR;
12372 case FILEIO_EIO:
12373 return EIO;
12374 case FILEIO_EBADF:
12375 return EBADF;
12376 case FILEIO_EACCES:
12377 return EACCES;
12378 case FILEIO_EFAULT:
12379 return EFAULT;
12380 case FILEIO_EBUSY:
12381 return EBUSY;
12382 case FILEIO_EEXIST:
12383 return EEXIST;
12384 case FILEIO_ENODEV:
12385 return ENODEV;
12386 case FILEIO_ENOTDIR:
12387 return ENOTDIR;
12388 case FILEIO_EISDIR:
12389 return EISDIR;
12390 case FILEIO_EINVAL:
12391 return EINVAL;
12392 case FILEIO_ENFILE:
12393 return ENFILE;
12394 case FILEIO_EMFILE:
12395 return EMFILE;
12396 case FILEIO_EFBIG:
12397 return EFBIG;
12398 case FILEIO_ENOSPC:
12399 return ENOSPC;
12400 case FILEIO_ESPIPE:
12401 return ESPIPE;
12402 case FILEIO_EROFS:
12403 return EROFS;
12404 case FILEIO_ENOSYS:
12405 return ENOSYS;
12406 case FILEIO_ENAMETOOLONG:
12407 return ENAMETOOLONG;
12408 }
12409 return -1;
12410}
12411
12412static char *
12413remote_hostio_error (int errnum)
12414{
12415 int host_error = remote_fileio_errno_to_host (errnum);
12416
12417 if (host_error == -1)
12418 error (_("Unknown remote I/O error %d"), errnum);
12419 else
12420 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12421}
12422
440b7aec
PA
12423/* A RAII wrapper around a remote file descriptor. */
12424
12425class scoped_remote_fd
a6b151f1 12426{
440b7aec 12427public:
6b8edb51
PA
12428 scoped_remote_fd (remote_target *remote, int fd)
12429 : m_remote (remote), m_fd (fd)
440b7aec
PA
12430 {
12431 }
a6b151f1 12432
440b7aec
PA
12433 ~scoped_remote_fd ()
12434 {
12435 if (m_fd != -1)
12436 {
12437 try
12438 {
12439 int remote_errno;
6b8edb51 12440 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12441 }
12442 catch (...)
12443 {
12444 /* Swallow exception before it escapes the dtor. If
12445 something goes wrong, likely the connection is gone,
12446 and there's nothing else that can be done. */
12447 }
12448 }
12449 }
12450
12451 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12452
12453 /* Release ownership of the file descriptor, and return it. */
12454 int release () noexcept
12455 {
12456 int fd = m_fd;
12457 m_fd = -1;
12458 return fd;
12459 }
12460
12461 /* Return the owned file descriptor. */
12462 int get () const noexcept
12463 {
12464 return m_fd;
12465 }
12466
12467private:
6b8edb51
PA
12468 /* The remote target. */
12469 remote_target *m_remote;
12470
440b7aec
PA
12471 /* The owned remote I/O file descriptor. */
12472 int m_fd;
12473};
a6b151f1
DJ
12474
12475void
12476remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12477{
12478 remote_target *remote = get_current_remote_target ();
12479
12480 if (remote == nullptr)
12481 error (_("command can only be used with remote target"));
12482
12483 remote->remote_file_put (local_file, remote_file, from_tty);
12484}
12485
12486void
12487remote_target::remote_file_put (const char *local_file, const char *remote_file,
12488 int from_tty)
a6b151f1 12489{
440b7aec 12490 int retcode, remote_errno, bytes, io_size;
a6b151f1
DJ
12491 int bytes_in_buffer;
12492 int saw_eof;
12493 ULONGEST offset;
a6b151f1 12494
d419f42d 12495 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12496 if (file == NULL)
12497 perror_with_name (local_file);
a6b151f1 12498
440b7aec 12499 scoped_remote_fd fd
6b8edb51
PA
12500 (this, remote_hostio_open (NULL,
12501 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12502 | FILEIO_O_TRUNC),
12503 0700, 0, &remote_errno));
440b7aec 12504 if (fd.get () == -1)
a6b151f1
DJ
12505 remote_hostio_error (remote_errno);
12506
12507 /* Send up to this many bytes at once. They won't all fit in the
12508 remote packet limit, so we'll transfer slightly fewer. */
12509 io_size = get_remote_packet_size ();
5ca3b260 12510 gdb::byte_vector buffer (io_size);
a6b151f1 12511
a6b151f1
DJ
12512 bytes_in_buffer = 0;
12513 saw_eof = 0;
12514 offset = 0;
12515 while (bytes_in_buffer || !saw_eof)
12516 {
12517 if (!saw_eof)
12518 {
5ca3b260 12519 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 12520 io_size - bytes_in_buffer,
d419f42d 12521 file.get ());
a6b151f1
DJ
12522 if (bytes == 0)
12523 {
d419f42d 12524 if (ferror (file.get ()))
a6b151f1
DJ
12525 error (_("Error reading %s."), local_file);
12526 else
12527 {
12528 /* EOF. Unless there is something still in the
12529 buffer from the last iteration, we are done. */
12530 saw_eof = 1;
12531 if (bytes_in_buffer == 0)
12532 break;
12533 }
12534 }
12535 }
12536 else
12537 bytes = 0;
12538
12539 bytes += bytes_in_buffer;
12540 bytes_in_buffer = 0;
12541
5ca3b260 12542 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 12543 offset, &remote_errno);
a6b151f1
DJ
12544
12545 if (retcode < 0)
12546 remote_hostio_error (remote_errno);
12547 else if (retcode == 0)
12548 error (_("Remote write of %d bytes returned 0!"), bytes);
12549 else if (retcode < bytes)
12550 {
12551 /* Short write. Save the rest of the read data for the next
12552 write. */
12553 bytes_in_buffer = bytes - retcode;
5ca3b260 12554 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
12555 }
12556
12557 offset += retcode;
12558 }
12559
6b8edb51 12560 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12561 remote_hostio_error (remote_errno);
12562
12563 if (from_tty)
12564 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
a6b151f1
DJ
12565}
12566
12567void
12568remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
12569{
12570 remote_target *remote = get_current_remote_target ();
12571
12572 if (remote == nullptr)
12573 error (_("command can only be used with remote target"));
12574
12575 remote->remote_file_get (remote_file, local_file, from_tty);
12576}
12577
12578void
12579remote_target::remote_file_get (const char *remote_file, const char *local_file,
12580 int from_tty)
a6b151f1 12581{
440b7aec 12582 int remote_errno, bytes, io_size;
a6b151f1 12583 ULONGEST offset;
a6b151f1 12584
440b7aec 12585 scoped_remote_fd fd
6b8edb51
PA
12586 (this, remote_hostio_open (NULL,
12587 remote_file, FILEIO_O_RDONLY, 0, 0,
12588 &remote_errno));
440b7aec 12589 if (fd.get () == -1)
a6b151f1
DJ
12590 remote_hostio_error (remote_errno);
12591
d419f42d 12592 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12593 if (file == NULL)
12594 perror_with_name (local_file);
a6b151f1
DJ
12595
12596 /* Send up to this many bytes at once. They won't all fit in the
12597 remote packet limit, so we'll transfer slightly fewer. */
12598 io_size = get_remote_packet_size ();
5ca3b260 12599 gdb::byte_vector buffer (io_size);
a6b151f1 12600
a6b151f1
DJ
12601 offset = 0;
12602 while (1)
12603 {
5ca3b260 12604 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 12605 &remote_errno);
a6b151f1
DJ
12606 if (bytes == 0)
12607 /* Success, but no bytes, means end-of-file. */
12608 break;
12609 if (bytes == -1)
12610 remote_hostio_error (remote_errno);
12611
12612 offset += bytes;
12613
5ca3b260 12614 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
12615 if (bytes == 0)
12616 perror_with_name (local_file);
12617 }
12618
6b8edb51 12619 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12620 remote_hostio_error (remote_errno);
12621
12622 if (from_tty)
12623 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
a6b151f1
DJ
12624}
12625
12626void
12627remote_file_delete (const char *remote_file, int from_tty)
12628{
6b8edb51 12629 remote_target *remote = get_current_remote_target ();
a6b151f1 12630
6b8edb51 12631 if (remote == nullptr)
a6b151f1
DJ
12632 error (_("command can only be used with remote target"));
12633
6b8edb51
PA
12634 remote->remote_file_delete (remote_file, from_tty);
12635}
12636
12637void
12638remote_target::remote_file_delete (const char *remote_file, int from_tty)
12639{
12640 int retcode, remote_errno;
12641
12642 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
12643 if (retcode == -1)
12644 remote_hostio_error (remote_errno);
12645
12646 if (from_tty)
12647 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12648}
12649
12650static void
ac88e2de 12651remote_put_command (const char *args, int from_tty)
a6b151f1 12652{
d1a41061
PP
12653 if (args == NULL)
12654 error_no_arg (_("file to put"));
12655
773a1edc 12656 gdb_argv argv (args);
a6b151f1
DJ
12657 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12658 error (_("Invalid parameters to remote put"));
12659
12660 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12661}
12662
12663static void
ac88e2de 12664remote_get_command (const char *args, int from_tty)
a6b151f1 12665{
d1a41061
PP
12666 if (args == NULL)
12667 error_no_arg (_("file to get"));
12668
773a1edc 12669 gdb_argv argv (args);
a6b151f1
DJ
12670 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12671 error (_("Invalid parameters to remote get"));
12672
12673 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12674}
12675
12676static void
ac88e2de 12677remote_delete_command (const char *args, int from_tty)
a6b151f1 12678{
d1a41061
PP
12679 if (args == NULL)
12680 error_no_arg (_("file to delete"));
12681
773a1edc 12682 gdb_argv argv (args);
a6b151f1
DJ
12683 if (argv[0] == NULL || argv[1] != NULL)
12684 error (_("Invalid parameters to remote delete"));
12685
12686 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12687}
12688
12689static void
981a3fb3 12690remote_command (const char *args, int from_tty)
a6b151f1 12691{
635c7e8a 12692 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12693}
12694
57810aa7 12695bool
f6ac5f3d 12696remote_target::can_execute_reverse ()
b2175913 12697{
4082afcc
PA
12698 if (packet_support (PACKET_bs) == PACKET_ENABLE
12699 || packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 12700 return true;
40ab02ce 12701 else
57810aa7 12702 return false;
b2175913
MS
12703}
12704
57810aa7 12705bool
f6ac5f3d 12706remote_target::supports_non_stop ()
74531fed 12707{
57810aa7 12708 return true;
74531fed
PA
12709}
12710
57810aa7 12711bool
f6ac5f3d 12712remote_target::supports_disable_randomization ()
03583c20
UW
12713{
12714 /* Only supported in extended mode. */
57810aa7 12715 return false;
03583c20
UW
12716}
12717
57810aa7 12718bool
f6ac5f3d 12719remote_target::supports_multi_process ()
8a305172
PA
12720{
12721 struct remote_state *rs = get_remote_state ();
a744cf53 12722
8020350c 12723 return remote_multi_process_p (rs);
8a305172
PA
12724}
12725
70221824 12726static int
f6ac5f3d 12727remote_supports_cond_tracepoints ()
782b2b07 12728{
4082afcc 12729 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12730}
12731
57810aa7 12732bool
f6ac5f3d 12733remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 12734{
4082afcc 12735 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12736}
12737
70221824 12738static int
f6ac5f3d 12739remote_supports_fast_tracepoints ()
7a697b8d 12740{
4082afcc 12741 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12742}
12743
0fb4aa4b 12744static int
f6ac5f3d 12745remote_supports_static_tracepoints ()
0fb4aa4b 12746{
4082afcc 12747 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12748}
12749
1e4d1764 12750static int
f6ac5f3d 12751remote_supports_install_in_trace ()
1e4d1764 12752{
4082afcc 12753 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12754}
12755
57810aa7 12756bool
f6ac5f3d 12757remote_target::supports_enable_disable_tracepoint ()
d248b706 12758{
4082afcc
PA
12759 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12760 == PACKET_ENABLE);
d248b706
KY
12761}
12762
57810aa7 12763bool
f6ac5f3d 12764remote_target::supports_string_tracing ()
3065dfb6 12765{
4082afcc 12766 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12767}
12768
57810aa7 12769bool
f6ac5f3d 12770remote_target::can_run_breakpoint_commands ()
d3ce09f5 12771{
4082afcc 12772 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12773}
12774
f6ac5f3d
PA
12775void
12776remote_target::trace_init ()
35b1e5cc 12777{
b6bb3468
PA
12778 struct remote_state *rs = get_remote_state ();
12779
35b1e5cc 12780 putpkt ("QTinit");
b6bb3468
PA
12781 remote_get_noisy_reply ();
12782 if (strcmp (rs->buf, "OK") != 0)
35b1e5cc
SS
12783 error (_("Target does not support this command."));
12784}
12785
409873ef
SS
12786/* Recursive routine to walk through command list including loops, and
12787 download packets for each command. */
12788
6b8edb51
PA
12789void
12790remote_target::remote_download_command_source (int num, ULONGEST addr,
12791 struct command_line *cmds)
409873ef
SS
12792{
12793 struct remote_state *rs = get_remote_state ();
12794 struct command_line *cmd;
12795
12796 for (cmd = cmds; cmd; cmd = cmd->next)
12797 {
0df8b418 12798 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12799 strcpy (rs->buf, "QTDPsrc:");
12800 encode_source_string (num, addr, "cmd", cmd->line,
12801 rs->buf + strlen (rs->buf),
12802 rs->buf_size - strlen (rs->buf));
12803 putpkt (rs->buf);
b6bb3468
PA
12804 remote_get_noisy_reply ();
12805 if (strcmp (rs->buf, "OK"))
409873ef
SS
12806 warning (_("Target does not support source download."));
12807
12808 if (cmd->control_type == while_control
12809 || cmd->control_type == while_stepping_control)
12810 {
12973681 12811 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 12812
0df8b418 12813 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12814 strcpy (rs->buf, "QTDPsrc:");
12815 encode_source_string (num, addr, "cmd", "end",
12816 rs->buf + strlen (rs->buf),
12817 rs->buf_size - strlen (rs->buf));
12818 putpkt (rs->buf);
b6bb3468
PA
12819 remote_get_noisy_reply ();
12820 if (strcmp (rs->buf, "OK"))
409873ef
SS
12821 warning (_("Target does not support source download."));
12822 }
12823 }
12824}
12825
f6ac5f3d
PA
12826void
12827remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc
SS
12828{
12829 CORE_ADDR tpaddr;
409873ef 12830 char addrbuf[40];
b44ec619
SM
12831 std::vector<std::string> tdp_actions;
12832 std::vector<std::string> stepping_actions;
35b1e5cc 12833 char *pkt;
e8ba3115 12834 struct breakpoint *b = loc->owner;
d9b3f62e 12835 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 12836 struct remote_state *rs = get_remote_state ();
3df3a985 12837 int ret;
ff36536c 12838 const char *err_msg = _("Tracepoint packet too large for target.");
3df3a985
PFC
12839 size_t size_left;
12840
12841 /* We use a buffer other than rs->buf because we'll build strings
12842 across multiple statements, and other statements in between could
12843 modify rs->buf. */
12844 gdb::char_vector buf (get_remote_packet_size ());
35b1e5cc 12845
dc673c81 12846 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12847
12848 tpaddr = loc->address;
12849 sprintf_vma (addrbuf, tpaddr);
3df3a985
PFC
12850 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
12851 b->number, addrbuf, /* address */
12852 (b->enable_state == bp_enabled ? 'E' : 'D'),
12853 t->step_count, t->pass_count);
12854
12855 if (ret < 0 || ret >= buf.size ())
a7f25a84 12856 error ("%s", err_msg);
3df3a985 12857
e8ba3115
YQ
12858 /* Fast tracepoints are mostly handled by the target, but we can
12859 tell the target how big of an instruction block should be moved
12860 around. */
12861 if (b->type == bp_fast_tracepoint)
12862 {
12863 /* Only test for support at download time; we may not know
12864 target capabilities at definition time. */
12865 if (remote_supports_fast_tracepoints ())
35b1e5cc 12866 {
6b940e6a
PL
12867 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12868 NULL))
3df3a985
PFC
12869 {
12870 size_left = buf.size () - strlen (buf.data ());
12871 ret = snprintf (buf.data () + strlen (buf.data ()),
12872 size_left, ":F%x",
12873 gdb_insn_length (loc->gdbarch, tpaddr));
12874
12875 if (ret < 0 || ret >= size_left)
a7f25a84 12876 error ("%s", err_msg);
3df3a985 12877 }
35b1e5cc 12878 else
e8ba3115
YQ
12879 /* If it passed validation at definition but fails now,
12880 something is very wrong. */
12881 internal_error (__FILE__, __LINE__,
12882 _("Fast tracepoint not "
12883 "valid during download"));
35b1e5cc 12884 }
e8ba3115
YQ
12885 else
12886 /* Fast tracepoints are functionally identical to regular
12887 tracepoints, so don't take lack of support as a reason to
12888 give up on the trace run. */
12889 warning (_("Target does not support fast tracepoints, "
12890 "downloading %d as regular tracepoint"), b->number);
12891 }
12892 else if (b->type == bp_static_tracepoint)
12893 {
12894 /* Only test for support at download time; we may not know
12895 target capabilities at definition time. */
12896 if (remote_supports_static_tracepoints ())
0fb4aa4b 12897 {
e8ba3115 12898 struct static_tracepoint_marker marker;
0fb4aa4b 12899
e8ba3115 12900 if (target_static_tracepoint_marker_at (tpaddr, &marker))
3df3a985
PFC
12901 {
12902 size_left = buf.size () - strlen (buf.data ());
12903 ret = snprintf (buf.data () + strlen (buf.data ()),
12904 size_left, ":S");
12905
12906 if (ret < 0 || ret >= size_left)
a7f25a84 12907 error ("%s", err_msg);
3df3a985 12908 }
0fb4aa4b 12909 else
e8ba3115 12910 error (_("Static tracepoint not valid during download"));
0fb4aa4b 12911 }
e8ba3115
YQ
12912 else
12913 /* Fast tracepoints are functionally identical to regular
12914 tracepoints, so don't take lack of support as a reason
12915 to give up on the trace run. */
12916 error (_("Target does not support static tracepoints"));
12917 }
12918 /* If the tracepoint has a conditional, make it into an agent
12919 expression and append to the definition. */
12920 if (loc->cond)
12921 {
12922 /* Only test support at download time, we may not know target
12923 capabilities at definition time. */
12924 if (remote_supports_cond_tracepoints ())
35b1e5cc 12925 {
3df3a985
PFC
12926 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
12927 loc->cond.get ());
12928
12929 size_left = buf.size () - strlen (buf.data ());
12930
12931 ret = snprintf (buf.data () + strlen (buf.data ()),
12932 size_left, ":X%x,", aexpr->len);
12933
12934 if (ret < 0 || ret >= size_left)
a7f25a84 12935 error ("%s", err_msg);
3df3a985
PFC
12936
12937 size_left = buf.size () - strlen (buf.data ());
12938
12939 /* Two bytes to encode each aexpr byte, plus the terminating
12940 null byte. */
12941 if (aexpr->len * 2 + 1 > size_left)
a7f25a84 12942 error ("%s", err_msg);
3df3a985
PFC
12943
12944 pkt = buf.data () + strlen (buf.data ());
12945
b44ec619 12946 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
12947 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12948 *pkt = '\0';
35b1e5cc 12949 }
e8ba3115
YQ
12950 else
12951 warning (_("Target does not support conditional tracepoints, "
12952 "ignoring tp %d cond"), b->number);
12953 }
35b1e5cc 12954
d9b3f62e 12955 if (b->commands || *default_collect)
3df3a985
PFC
12956 {
12957 size_left = buf.size () - strlen (buf.data ());
12958
12959 ret = snprintf (buf.data () + strlen (buf.data ()),
12960 size_left, "-");
12961
12962 if (ret < 0 || ret >= size_left)
a7f25a84 12963 error ("%s", err_msg);
3df3a985
PFC
12964 }
12965
12966 putpkt (buf.data ());
b6bb3468
PA
12967 remote_get_noisy_reply ();
12968 if (strcmp (rs->buf, "OK"))
e8ba3115 12969 error (_("Target does not support tracepoints."));
35b1e5cc 12970
e8ba3115 12971 /* do_single_steps (t); */
b44ec619
SM
12972 for (auto action_it = tdp_actions.begin ();
12973 action_it != tdp_actions.end (); action_it++)
e8ba3115 12974 {
b44ec619
SM
12975 QUIT; /* Allow user to bail out with ^C. */
12976
aa6f3694 12977 bool has_more = ((action_it + 1) != tdp_actions.end ()
b44ec619
SM
12978 || !stepping_actions.empty ());
12979
3df3a985
PFC
12980 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
12981 b->number, addrbuf, /* address */
12982 action_it->c_str (),
12983 has_more ? '-' : 0);
12984
12985 if (ret < 0 || ret >= buf.size ())
a7f25a84 12986 error ("%s", err_msg);
3df3a985
PFC
12987
12988 putpkt (buf.data ());
b44ec619
SM
12989 remote_get_noisy_reply ();
12990 if (strcmp (rs->buf, "OK"))
12991 error (_("Error on target while setting tracepoints."));
e8ba3115 12992 }
409873ef 12993
05abfc39
PFC
12994 for (auto action_it = stepping_actions.begin ();
12995 action_it != stepping_actions.end (); action_it++)
12996 {
12997 QUIT; /* Allow user to bail out with ^C. */
12998
12999 bool is_first = action_it == stepping_actions.begin ();
aa6f3694 13000 bool has_more = (action_it + 1) != stepping_actions.end ();
05abfc39 13001
3df3a985
PFC
13002 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13003 b->number, addrbuf, /* address */
13004 is_first ? "S" : "",
13005 action_it->c_str (),
13006 has_more ? "-" : "");
13007
13008 if (ret < 0 || ret >= buf.size ())
a7f25a84 13009 error ("%s", err_msg);
3df3a985
PFC
13010
13011 putpkt (buf.data ());
05abfc39
PFC
13012 remote_get_noisy_reply ();
13013 if (strcmp (rs->buf, "OK"))
13014 error (_("Error on target while setting tracepoints."));
13015 }
b44ec619 13016
4082afcc 13017 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 13018 {
f00aae0f 13019 if (b->location != NULL)
409873ef 13020 {
3df3a985
PFC
13021 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13022
13023 if (ret < 0 || ret >= buf.size ())
a7f25a84 13024 error ("%s", err_msg);
3df3a985 13025
f00aae0f 13026 encode_source_string (b->number, loc->address, "at",
d28cd78a 13027 event_location_to_string (b->location.get ()),
3df3a985
PFC
13028 buf.data () + strlen (buf.data ()),
13029 buf.size () - strlen (buf.data ()));
13030 putpkt (buf.data ());
b6bb3468
PA
13031 remote_get_noisy_reply ();
13032 if (strcmp (rs->buf, "OK"))
e8ba3115 13033 warning (_("Target does not support source download."));
409873ef 13034 }
e8ba3115
YQ
13035 if (b->cond_string)
13036 {
3df3a985
PFC
13037 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13038
13039 if (ret < 0 || ret >= buf.size ())
a7f25a84 13040 error ("%s", err_msg);
3df3a985 13041
e8ba3115 13042 encode_source_string (b->number, loc->address,
3df3a985
PFC
13043 "cond", b->cond_string,
13044 buf.data () + strlen (buf.data ()),
13045 buf.size () - strlen (buf.data ()));
13046 putpkt (buf.data ());
b6bb3468
PA
13047 remote_get_noisy_reply ();
13048 if (strcmp (rs->buf, "OK"))
e8ba3115
YQ
13049 warning (_("Target does not support source download."));
13050 }
13051 remote_download_command_source (b->number, loc->address,
13052 breakpoint_commands (b));
35b1e5cc 13053 }
35b1e5cc
SS
13054}
13055
57810aa7 13056bool
f6ac5f3d 13057remote_target::can_download_tracepoint ()
1e4d1764 13058{
1e51243a
PA
13059 struct remote_state *rs = get_remote_state ();
13060 struct trace_status *ts;
13061 int status;
13062
13063 /* Don't try to install tracepoints until we've relocated our
13064 symbols, and fetched and merged the target's tracepoint list with
13065 ours. */
13066 if (rs->starting_up)
57810aa7 13067 return false;
1e51243a
PA
13068
13069 ts = current_trace_status ();
f6ac5f3d 13070 status = get_trace_status (ts);
1e4d1764
YQ
13071
13072 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13073 return false;
1e4d1764
YQ
13074
13075 /* If we are in a tracing experiment, but remote stub doesn't support
13076 installing tracepoint in trace, we have to return. */
13077 if (!remote_supports_install_in_trace ())
57810aa7 13078 return false;
1e4d1764 13079
57810aa7 13080 return true;
1e4d1764
YQ
13081}
13082
13083
f6ac5f3d
PA
13084void
13085remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
13086{
13087 struct remote_state *rs = get_remote_state ();
00bf0b85 13088 char *p;
35b1e5cc 13089
bba74b36 13090 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
13091 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13092 tsv.builtin);
00bf0b85 13093 p = rs->buf + strlen (rs->buf);
c252925c 13094 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
00bf0b85 13095 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 13096 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 13097 *p++ = '\0';
35b1e5cc 13098 putpkt (rs->buf);
b6bb3468
PA
13099 remote_get_noisy_reply ();
13100 if (*rs->buf == '\0')
ad91cd99 13101 error (_("Target does not support this command."));
b6bb3468 13102 if (strcmp (rs->buf, "OK") != 0)
ad91cd99 13103 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13104}
13105
f6ac5f3d
PA
13106void
13107remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13108{
13109 struct remote_state *rs = get_remote_state ();
13110 char addr_buf[40];
13111
13112 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
13113 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13114 location->owner->number, addr_buf);
d248b706 13115 putpkt (rs->buf);
b6bb3468 13116 remote_get_noisy_reply ();
d248b706
KY
13117 if (*rs->buf == '\0')
13118 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13119 if (strcmp (rs->buf, "OK") != 0)
13120 error (_("Error on target while enabling tracepoint."));
13121}
13122
f6ac5f3d
PA
13123void
13124remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13125{
13126 struct remote_state *rs = get_remote_state ();
13127 char addr_buf[40];
13128
13129 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
13130 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13131 location->owner->number, addr_buf);
d248b706 13132 putpkt (rs->buf);
b6bb3468 13133 remote_get_noisy_reply ();
d248b706
KY
13134 if (*rs->buf == '\0')
13135 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13136 if (strcmp (rs->buf, "OK") != 0)
13137 error (_("Error on target while disabling tracepoint."));
13138}
13139
f6ac5f3d
PA
13140void
13141remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13142{
13143 asection *s;
81b9b86e 13144 bfd *abfd = NULL;
35b1e5cc 13145 bfd_size_type size;
608bcef2 13146 bfd_vma vma;
35b1e5cc 13147 int anysecs = 0;
c2fa21f1 13148 int offset = 0;
35b1e5cc
SS
13149
13150 if (!exec_bfd)
13151 return; /* No information to give. */
13152
b6bb3468
PA
13153 struct remote_state *rs = get_remote_state ();
13154
13155 strcpy (rs->buf, "QTro");
13156 offset = strlen (rs->buf);
35b1e5cc
SS
13157 for (s = exec_bfd->sections; s; s = s->next)
13158 {
13159 char tmp1[40], tmp2[40];
c2fa21f1 13160 int sec_length;
35b1e5cc
SS
13161
13162 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 13163 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
13164 (s->flags & SEC_READONLY) == 0)
13165 continue;
13166
13167 anysecs = 1;
81b9b86e 13168 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 13169 size = bfd_get_section_size (s);
608bcef2
HZ
13170 sprintf_vma (tmp1, vma);
13171 sprintf_vma (tmp2, vma + size);
c2fa21f1 13172 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
b6bb3468 13173 if (offset + sec_length + 1 > rs->buf_size)
c2fa21f1 13174 {
4082afcc 13175 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 13176 warning (_("\
c2fa21f1
HZ
13177Too many sections for read-only sections definition packet."));
13178 break;
13179 }
b6bb3468 13180 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
bba74b36 13181 tmp1, tmp2);
c2fa21f1 13182 offset += sec_length;
35b1e5cc
SS
13183 }
13184 if (anysecs)
13185 {
b6bb3468
PA
13186 putpkt (rs->buf);
13187 getpkt (&rs->buf, &rs->buf_size, 0);
35b1e5cc
SS
13188 }
13189}
13190
f6ac5f3d
PA
13191void
13192remote_target::trace_start ()
35b1e5cc 13193{
b6bb3468
PA
13194 struct remote_state *rs = get_remote_state ();
13195
35b1e5cc 13196 putpkt ("QTStart");
b6bb3468
PA
13197 remote_get_noisy_reply ();
13198 if (*rs->buf == '\0')
ad91cd99 13199 error (_("Target does not support this command."));
b6bb3468
PA
13200 if (strcmp (rs->buf, "OK") != 0)
13201 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
13202}
13203
f6ac5f3d
PA
13204int
13205remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13206{
953b98d1 13207 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13208 char *p = NULL;
0df8b418 13209 /* FIXME we need to get register block size some other way. */
00bf0b85 13210 extern int trace_regblock_size;
bd3eecc3 13211 enum packet_result result;
b6bb3468 13212 struct remote_state *rs = get_remote_state ();
bd3eecc3 13213
4082afcc 13214 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13215 return -1;
a744cf53 13216
5cd63fda 13217 trace_regblock_size
9d6eea31 13218 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 13219
049dc89b
JK
13220 putpkt ("qTStatus");
13221
492d29ea 13222 TRY
67f41397 13223 {
b6bb3468 13224 p = remote_get_noisy_reply ();
67f41397 13225 }
492d29ea 13226 CATCH (ex, RETURN_MASK_ERROR)
67f41397 13227 {
598d3636
JK
13228 if (ex.error != TARGET_CLOSE_ERROR)
13229 {
13230 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13231 return -1;
13232 }
13233 throw_exception (ex);
67f41397 13234 }
492d29ea 13235 END_CATCH
00bf0b85 13236
bd3eecc3
PA
13237 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13238
00bf0b85 13239 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13240 if (result == PACKET_UNKNOWN)
00bf0b85 13241 return -1;
35b1e5cc 13242
00bf0b85 13243 /* We're working with a live target. */
f5911ea1 13244 ts->filename = NULL;
00bf0b85 13245
00bf0b85 13246 if (*p++ != 'T')
b6bb3468 13247 error (_("Bogus trace status reply from target: %s"), rs->buf);
35b1e5cc 13248
84cebc4a
YQ
13249 /* Function 'parse_trace_status' sets default value of each field of
13250 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13251 parse_trace_status (p, ts);
13252
13253 return ts->running;
35b1e5cc
SS
13254}
13255
f6ac5f3d
PA
13256void
13257remote_target::get_tracepoint_status (struct breakpoint *bp,
13258 struct uploaded_tp *utp)
f196051f
SS
13259{
13260 struct remote_state *rs = get_remote_state ();
f196051f
SS
13261 char *reply;
13262 struct bp_location *loc;
13263 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 13264 size_t size = get_remote_packet_size ();
f196051f
SS
13265
13266 if (tp)
13267 {
c1fc2657 13268 tp->hit_count = 0;
f196051f 13269 tp->traceframe_usage = 0;
c1fc2657 13270 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
13271 {
13272 /* If the tracepoint was never downloaded, don't go asking for
13273 any status. */
13274 if (tp->number_on_target == 0)
13275 continue;
bba74b36
YQ
13276 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13277 phex_nz (loc->address, 0));
f196051f 13278 putpkt (rs->buf);
b6bb3468 13279 reply = remote_get_noisy_reply ();
f196051f
SS
13280 if (reply && *reply)
13281 {
13282 if (*reply == 'V')
13283 parse_tracepoint_status (reply + 1, bp, utp);
13284 }
13285 }
13286 }
13287 else if (utp)
13288 {
13289 utp->hit_count = 0;
13290 utp->traceframe_usage = 0;
bba74b36
YQ
13291 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13292 phex_nz (utp->addr, 0));
f196051f 13293 putpkt (rs->buf);
b6bb3468 13294 reply = remote_get_noisy_reply ();
f196051f
SS
13295 if (reply && *reply)
13296 {
13297 if (*reply == 'V')
13298 parse_tracepoint_status (reply + 1, bp, utp);
13299 }
13300 }
13301}
13302
f6ac5f3d
PA
13303void
13304remote_target::trace_stop ()
35b1e5cc 13305{
b6bb3468
PA
13306 struct remote_state *rs = get_remote_state ();
13307
35b1e5cc 13308 putpkt ("QTStop");
b6bb3468
PA
13309 remote_get_noisy_reply ();
13310 if (*rs->buf == '\0')
ad91cd99 13311 error (_("Target does not support this command."));
b6bb3468
PA
13312 if (strcmp (rs->buf, "OK") != 0)
13313 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
13314}
13315
f6ac5f3d
PA
13316int
13317remote_target::trace_find (enum trace_find_type type, int num,
13318 CORE_ADDR addr1, CORE_ADDR addr2,
13319 int *tpp)
35b1e5cc
SS
13320{
13321 struct remote_state *rs = get_remote_state ();
bba74b36 13322 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
13323 char *p, *reply;
13324 int target_frameno = -1, target_tracept = -1;
13325
e6e4e701
PA
13326 /* Lookups other than by absolute frame number depend on the current
13327 trace selected, so make sure it is correct on the remote end
13328 first. */
13329 if (type != tfind_number)
13330 set_remote_traceframe ();
13331
35b1e5cc
SS
13332 p = rs->buf;
13333 strcpy (p, "QTFrame:");
13334 p = strchr (p, '\0');
13335 switch (type)
13336 {
13337 case tfind_number:
bba74b36 13338 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13339 break;
13340 case tfind_pc:
bba74b36 13341 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13342 break;
13343 case tfind_tp:
bba74b36 13344 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13345 break;
13346 case tfind_range:
bba74b36
YQ
13347 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13348 phex_nz (addr2, 0));
35b1e5cc
SS
13349 break;
13350 case tfind_outside:
bba74b36
YQ
13351 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13352 phex_nz (addr2, 0));
35b1e5cc
SS
13353 break;
13354 default:
9b20d036 13355 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13356 }
13357
13358 putpkt (rs->buf);
b6bb3468 13359 reply = remote_get_noisy_reply ();
ad91cd99
PA
13360 if (*reply == '\0')
13361 error (_("Target does not support this command."));
35b1e5cc
SS
13362
13363 while (reply && *reply)
13364 switch (*reply)
13365 {
13366 case 'F':
f197e0f1
VP
13367 p = ++reply;
13368 target_frameno = (int) strtol (p, &reply, 16);
13369 if (reply == p)
13370 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13371 /* Don't update our remote traceframe number cache on failure
13372 to select a remote traceframe. */
f197e0f1
VP
13373 if (target_frameno == -1)
13374 return -1;
35b1e5cc
SS
13375 break;
13376 case 'T':
f197e0f1
VP
13377 p = ++reply;
13378 target_tracept = (int) strtol (p, &reply, 16);
13379 if (reply == p)
13380 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13381 break;
13382 case 'O': /* "OK"? */
13383 if (reply[1] == 'K' && reply[2] == '\0')
13384 reply += 2;
13385 else
13386 error (_("Bogus reply from target: %s"), reply);
13387 break;
13388 default:
13389 error (_("Bogus reply from target: %s"), reply);
13390 }
13391 if (tpp)
13392 *tpp = target_tracept;
e6e4e701 13393
262e1174 13394 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13395 return target_frameno;
13396}
13397
57810aa7 13398bool
f6ac5f3d 13399remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13400{
13401 struct remote_state *rs = get_remote_state ();
13402 char *reply;
13403 ULONGEST uval;
13404
e6e4e701
PA
13405 set_remote_traceframe ();
13406
bba74b36 13407 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13408 putpkt (rs->buf);
b6bb3468 13409 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13410 if (reply && *reply)
13411 {
13412 if (*reply == 'V')
13413 {
13414 unpack_varlen_hex (reply + 1, &uval);
13415 *val = (LONGEST) uval;
57810aa7 13416 return true;
35b1e5cc
SS
13417 }
13418 }
57810aa7 13419 return false;
35b1e5cc
SS
13420}
13421
f6ac5f3d
PA
13422int
13423remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13424{
13425 struct remote_state *rs = get_remote_state ();
13426 char *p, *reply;
13427
13428 p = rs->buf;
13429 strcpy (p, "QTSave:");
13430 p += strlen (p);
13431 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13432 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13433 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13434 *p++ = '\0';
13435 putpkt (rs->buf);
b6bb3468 13436 reply = remote_get_noisy_reply ();
d6c5869f 13437 if (*reply == '\0')
ad91cd99
PA
13438 error (_("Target does not support this command."));
13439 if (strcmp (reply, "OK") != 0)
13440 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13441 return 0;
13442}
13443
13444/* This is basically a memory transfer, but needs to be its own packet
13445 because we don't know how the target actually organizes its trace
13446 memory, plus we want to be able to ask for as much as possible, but
13447 not be unhappy if we don't get as much as we ask for. */
13448
f6ac5f3d
PA
13449LONGEST
13450remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13451{
13452 struct remote_state *rs = get_remote_state ();
13453 char *reply;
13454 char *p;
13455 int rslt;
13456
13457 p = rs->buf;
13458 strcpy (p, "qTBuffer:");
13459 p += strlen (p);
13460 p += hexnumstr (p, offset);
13461 *p++ = ',';
13462 p += hexnumstr (p, len);
13463 *p++ = '\0';
13464
13465 putpkt (rs->buf);
b6bb3468 13466 reply = remote_get_noisy_reply ();
00bf0b85
SS
13467 if (reply && *reply)
13468 {
13469 /* 'l' by itself means we're at the end of the buffer and
13470 there is nothing more to get. */
13471 if (*reply == 'l')
13472 return 0;
13473
13474 /* Convert the reply into binary. Limit the number of bytes to
13475 convert according to our passed-in buffer size, rather than
13476 what was returned in the packet; if the target is
13477 unexpectedly generous and gives us a bigger reply than we
13478 asked for, we don't want to crash. */
b6bb3468 13479 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13480 return rslt;
13481 }
13482
13483 /* Something went wrong, flag as an error. */
13484 return -1;
13485}
13486
f6ac5f3d
PA
13487void
13488remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13489{
13490 struct remote_state *rs = get_remote_state ();
13491
4082afcc 13492 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 13493 {
ad91cd99
PA
13494 char *reply;
13495
bba74b36 13496 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 13497 putpkt (rs->buf);
b6bb3468 13498 reply = remote_get_noisy_reply ();
ad91cd99 13499 if (*reply == '\0')
33da3f1c 13500 error (_("Target does not support this command."));
ad91cd99
PA
13501 if (strcmp (reply, "OK") != 0)
13502 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13503 }
13504 else if (val)
13505 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13506}
13507
f6ac5f3d
PA
13508int
13509remote_target::core_of_thread (ptid_t ptid)
dc146f7c
VP
13510{
13511 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 13512
7aabaf9d
SM
13513 if (info != NULL && info->priv != NULL)
13514 return get_remote_thread_info (info)->core;
13515
dc146f7c
VP
13516 return -1;
13517}
13518
f6ac5f3d
PA
13519void
13520remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13521{
13522 struct remote_state *rs = get_remote_state ();
ad91cd99 13523 char *reply;
4daf5ac0 13524
bba74b36 13525 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 13526 putpkt (rs->buf);
b6bb3468 13527 reply = remote_get_noisy_reply ();
ad91cd99 13528 if (*reply == '\0')
4daf5ac0 13529 error (_("Target does not support this command."));
ad91cd99
PA
13530 if (strcmp (reply, "OK") != 0)
13531 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13532}
13533
f6ac5f3d
PA
13534traceframe_info_up
13535remote_target::traceframe_info ()
b3b9301e 13536{
9018be22 13537 gdb::optional<gdb::char_vector> text
8b88a78e 13538 = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13539 NULL);
9018be22
SM
13540 if (text)
13541 return parse_traceframe_info (text->data ());
b3b9301e
PA
13542
13543 return NULL;
13544}
13545
405f8e94
SS
13546/* Handle the qTMinFTPILen packet. Returns the minimum length of
13547 instruction on which a fast tracepoint may be placed. Returns -1
13548 if the packet is not supported, and 0 if the minimum instruction
13549 length is unknown. */
13550
f6ac5f3d
PA
13551int
13552remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13553{
13554 struct remote_state *rs = get_remote_state ();
13555 char *reply;
13556
e886a173
PA
13557 /* If we're not debugging a process yet, the IPA can't be
13558 loaded. */
13559 if (!target_has_execution)
13560 return 0;
13561
13562 /* Make sure the remote is pointing at the right process. */
13563 set_general_process ();
13564
bba74b36 13565 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13566 putpkt (rs->buf);
b6bb3468 13567 reply = remote_get_noisy_reply ();
405f8e94
SS
13568 if (*reply == '\0')
13569 return -1;
13570 else
13571 {
13572 ULONGEST min_insn_len;
13573
13574 unpack_varlen_hex (reply, &min_insn_len);
13575
13576 return (int) min_insn_len;
13577 }
13578}
13579
f6ac5f3d
PA
13580void
13581remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13582{
4082afcc 13583 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13584 {
13585 struct remote_state *rs = get_remote_state ();
13586 char *buf = rs->buf;
13587 char *endbuf = rs->buf + get_remote_packet_size ();
13588 enum packet_result result;
13589
13590 gdb_assert (val >= 0 || val == -1);
13591 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13592 /* Send -1 as literal "-1" to avoid host size dependency. */
13593 if (val < 0)
13594 {
13595 *buf++ = '-';
13596 buf += hexnumstr (buf, (ULONGEST) -val);
13597 }
13598 else
13599 buf += hexnumstr (buf, (ULONGEST) val);
13600
13601 putpkt (rs->buf);
b6bb3468 13602 remote_get_noisy_reply ();
f6f899bf
HAQ
13603 result = packet_ok (rs->buf,
13604 &remote_protocol_packets[PACKET_QTBuffer_size]);
13605
13606 if (result != PACKET_OK)
13607 warning (_("Bogus reply from target: %s"), rs->buf);
13608 }
13609}
13610
57810aa7 13611bool
f6ac5f3d
PA
13612remote_target::set_trace_notes (const char *user, const char *notes,
13613 const char *stop_notes)
f196051f
SS
13614{
13615 struct remote_state *rs = get_remote_state ();
13616 char *reply;
13617 char *buf = rs->buf;
13618 char *endbuf = rs->buf + get_remote_packet_size ();
13619 int nbytes;
13620
13621 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13622 if (user)
13623 {
13624 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13625 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13626 buf += 2 * nbytes;
13627 *buf++ = ';';
13628 }
13629 if (notes)
13630 {
13631 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13632 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13633 buf += 2 * nbytes;
13634 *buf++ = ';';
13635 }
13636 if (stop_notes)
13637 {
13638 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13639 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13640 buf += 2 * nbytes;
13641 *buf++ = ';';
13642 }
13643 /* Ensure the buffer is terminated. */
13644 *buf = '\0';
13645
13646 putpkt (rs->buf);
b6bb3468 13647 reply = remote_get_noisy_reply ();
f196051f 13648 if (*reply == '\0')
57810aa7 13649 return false;
f196051f
SS
13650
13651 if (strcmp (reply, "OK") != 0)
13652 error (_("Bogus reply from target: %s"), reply);
13653
57810aa7 13654 return true;
f196051f
SS
13655}
13656
57810aa7
PA
13657bool
13658remote_target::use_agent (bool use)
d1feda86 13659{
4082afcc 13660 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13661 {
13662 struct remote_state *rs = get_remote_state ();
13663
13664 /* If the stub supports QAgent. */
bba74b36 13665 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
13666 putpkt (rs->buf);
13667 getpkt (&rs->buf, &rs->buf_size, 0);
13668
13669 if (strcmp (rs->buf, "OK") == 0)
13670 {
f6ac5f3d 13671 ::use_agent = use;
57810aa7 13672 return true;
d1feda86
YQ
13673 }
13674 }
13675
57810aa7 13676 return false;
d1feda86
YQ
13677}
13678
57810aa7 13679bool
f6ac5f3d 13680remote_target::can_use_agent ()
d1feda86 13681{
4082afcc 13682 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13683}
13684
9accd112
MM
13685struct btrace_target_info
13686{
13687 /* The ptid of the traced thread. */
13688 ptid_t ptid;
f4abbc16
MM
13689
13690 /* The obtained branch trace configuration. */
13691 struct btrace_config conf;
9accd112
MM
13692};
13693
f4abbc16
MM
13694/* Reset our idea of our target's btrace configuration. */
13695
13696static void
6b8edb51 13697remote_btrace_reset (remote_state *rs)
f4abbc16 13698{
f4abbc16
MM
13699 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13700}
13701
f4abbc16
MM
13702/* Synchronize the configuration with the target. */
13703
6b8edb51
PA
13704void
13705remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 13706{
d33501a5
MM
13707 struct packet_config *packet;
13708 struct remote_state *rs;
13709 char *buf, *pos, *endbuf;
13710
13711 rs = get_remote_state ();
13712 buf = rs->buf;
13713 endbuf = buf + get_remote_packet_size ();
13714
13715 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13716 if (packet_config_support (packet) == PACKET_ENABLE
13717 && conf->bts.size != rs->btrace_config.bts.size)
13718 {
13719 pos = buf;
13720 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13721 conf->bts.size);
13722
13723 putpkt (buf);
13724 getpkt (&buf, &rs->buf_size, 0);
13725
13726 if (packet_ok (buf, packet) == PACKET_ERROR)
13727 {
13728 if (buf[0] == 'E' && buf[1] == '.')
13729 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13730 else
13731 error (_("Failed to configure the BTS buffer size."));
13732 }
13733
13734 rs->btrace_config.bts.size = conf->bts.size;
13735 }
b20a6524
MM
13736
13737 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13738 if (packet_config_support (packet) == PACKET_ENABLE
13739 && conf->pt.size != rs->btrace_config.pt.size)
13740 {
13741 pos = buf;
13742 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13743 conf->pt.size);
13744
13745 putpkt (buf);
13746 getpkt (&buf, &rs->buf_size, 0);
13747
13748 if (packet_ok (buf, packet) == PACKET_ERROR)
13749 {
13750 if (buf[0] == 'E' && buf[1] == '.')
13751 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13752 else
13753 error (_("Failed to configure the trace buffer size."));
13754 }
13755
13756 rs->btrace_config.pt.size = conf->pt.size;
13757 }
f4abbc16
MM
13758}
13759
13760/* Read the current thread's btrace configuration from the target and
13761 store it into CONF. */
13762
13763static void
13764btrace_read_config (struct btrace_config *conf)
13765{
9018be22 13766 gdb::optional<gdb::char_vector> xml
8b88a78e 13767 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
13768 if (xml)
13769 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
13770}
13771
c0272db5
TW
13772/* Maybe reopen target btrace. */
13773
6b8edb51
PA
13774void
13775remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
13776{
13777 struct remote_state *rs = get_remote_state ();
c0272db5
TW
13778 struct thread_info *tp;
13779 int btrace_target_pushed = 0;
15766370 13780#if !defined (HAVE_LIBIPT)
c0272db5 13781 int warned = 0;
15766370 13782#endif
c0272db5 13783
5ed8105e
PA
13784 scoped_restore_current_thread restore_thread;
13785
c0272db5
TW
13786 ALL_NON_EXITED_THREADS (tp)
13787 {
13788 set_general_thread (tp->ptid);
13789
13790 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13791 btrace_read_config (&rs->btrace_config);
13792
13793 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13794 continue;
13795
13796#if !defined (HAVE_LIBIPT)
13797 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13798 {
13799 if (!warned)
13800 {
13801 warned = 1;
c4e12631
MM
13802 warning (_("Target is recording using Intel Processor Trace "
13803 "but support was disabled at compile time."));
c0272db5
TW
13804 }
13805
13806 continue;
13807 }
13808#endif /* !defined (HAVE_LIBIPT) */
13809
13810 /* Push target, once, but before anything else happens. This way our
13811 changes to the threads will be cleaned up by unpushing the target
13812 in case btrace_read_config () throws. */
13813 if (!btrace_target_pushed)
13814 {
13815 btrace_target_pushed = 1;
13816 record_btrace_push_target ();
13817 printf_filtered (_("Target is recording using %s.\n"),
13818 btrace_format_string (rs->btrace_config.format));
13819 }
13820
13821 tp->btrace.target = XCNEW (struct btrace_target_info);
13822 tp->btrace.target->ptid = tp->ptid;
13823 tp->btrace.target->conf = rs->btrace_config;
13824 }
c0272db5
TW
13825}
13826
9accd112
MM
13827/* Enable branch tracing. */
13828
f6ac5f3d
PA
13829struct btrace_target_info *
13830remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
9accd112
MM
13831{
13832 struct btrace_target_info *tinfo = NULL;
b20a6524 13833 struct packet_config *packet = NULL;
9accd112
MM
13834 struct remote_state *rs = get_remote_state ();
13835 char *buf = rs->buf;
13836 char *endbuf = rs->buf + get_remote_packet_size ();
13837
b20a6524
MM
13838 switch (conf->format)
13839 {
13840 case BTRACE_FORMAT_BTS:
13841 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13842 break;
13843
13844 case BTRACE_FORMAT_PT:
13845 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13846 break;
13847 }
13848
13849 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13850 error (_("Target does not support branch tracing."));
13851
f4abbc16
MM
13852 btrace_sync_conf (conf);
13853
9accd112
MM
13854 set_general_thread (ptid);
13855
13856 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13857 putpkt (rs->buf);
13858 getpkt (&rs->buf, &rs->buf_size, 0);
13859
13860 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13861 {
13862 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13863 error (_("Could not enable branch tracing for %s: %s"),
13864 target_pid_to_str (ptid), rs->buf + 2);
13865 else
13866 error (_("Could not enable branch tracing for %s."),
13867 target_pid_to_str (ptid));
13868 }
13869
8d749320 13870 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13871 tinfo->ptid = ptid;
13872
f4abbc16
MM
13873 /* If we fail to read the configuration, we lose some information, but the
13874 tracing itself is not impacted. */
492d29ea
PA
13875 TRY
13876 {
13877 btrace_read_config (&tinfo->conf);
13878 }
13879 CATCH (err, RETURN_MASK_ERROR)
13880 {
13881 if (err.message != NULL)
13882 warning ("%s", err.message);
13883 }
13884 END_CATCH
f4abbc16 13885
9accd112
MM
13886 return tinfo;
13887}
13888
13889/* Disable branch tracing. */
13890
f6ac5f3d
PA
13891void
13892remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13893{
13894 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13895 struct remote_state *rs = get_remote_state ();
13896 char *buf = rs->buf;
13897 char *endbuf = rs->buf + get_remote_packet_size ();
13898
4082afcc 13899 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13900 error (_("Target does not support branch tracing."));
13901
13902 set_general_thread (tinfo->ptid);
13903
13904 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13905 putpkt (rs->buf);
13906 getpkt (&rs->buf, &rs->buf_size, 0);
13907
13908 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13909 {
13910 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13911 error (_("Could not disable branch tracing for %s: %s"),
13912 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13913 else
13914 error (_("Could not disable branch tracing for %s."),
13915 target_pid_to_str (tinfo->ptid));
13916 }
13917
13918 xfree (tinfo);
13919}
13920
13921/* Teardown branch tracing. */
13922
f6ac5f3d
PA
13923void
13924remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13925{
13926 /* We must not talk to the target during teardown. */
13927 xfree (tinfo);
13928}
13929
13930/* Read the branch trace. */
13931
f6ac5f3d
PA
13932enum btrace_error
13933remote_target::read_btrace (struct btrace_data *btrace,
13934 struct btrace_target_info *tinfo,
13935 enum btrace_read_type type)
9accd112
MM
13936{
13937 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 13938 const char *annex;
9accd112 13939
4082afcc 13940 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13941 error (_("Target does not support branch tracing."));
13942
13943#if !defined(HAVE_LIBEXPAT)
13944 error (_("Cannot process branch tracing result. XML parsing not supported."));
13945#endif
13946
13947 switch (type)
13948 {
864089d2 13949 case BTRACE_READ_ALL:
9accd112
MM
13950 annex = "all";
13951 break;
864089d2 13952 case BTRACE_READ_NEW:
9accd112
MM
13953 annex = "new";
13954 break;
969c39fb
MM
13955 case BTRACE_READ_DELTA:
13956 annex = "delta";
13957 break;
9accd112
MM
13958 default:
13959 internal_error (__FILE__, __LINE__,
13960 _("Bad branch tracing read type: %u."),
13961 (unsigned int) type);
13962 }
13963
9018be22 13964 gdb::optional<gdb::char_vector> xml
8b88a78e 13965 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
9018be22 13966 if (!xml)
969c39fb 13967 return BTRACE_ERR_UNKNOWN;
9accd112 13968
9018be22 13969 parse_xml_btrace (btrace, xml->data ());
9accd112 13970
969c39fb 13971 return BTRACE_ERR_NONE;
9accd112
MM
13972}
13973
f6ac5f3d
PA
13974const struct btrace_config *
13975remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
13976{
13977 return &tinfo->conf;
13978}
13979
57810aa7 13980bool
f6ac5f3d 13981remote_target::augmented_libraries_svr4_read ()
ced63ec0 13982{
4082afcc
PA
13983 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13984 == PACKET_ENABLE);
ced63ec0
GB
13985}
13986
9dd130a0
TT
13987/* Implementation of to_load. */
13988
f6ac5f3d
PA
13989void
13990remote_target::load (const char *name, int from_tty)
9dd130a0
TT
13991{
13992 generic_load (name, from_tty);
13993}
13994
c78fa86a
GB
13995/* Accepts an integer PID; returns a string representing a file that
13996 can be opened on the remote side to get the symbols for the child
13997 process. Returns NULL if the operation is not supported. */
13998
f6ac5f3d
PA
13999char *
14000remote_target::pid_to_exec_file (int pid)
c78fa86a 14001{
9018be22 14002 static gdb::optional<gdb::char_vector> filename;
835205d0
GB
14003 struct inferior *inf;
14004 char *annex = NULL;
c78fa86a
GB
14005
14006 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14007 return NULL;
14008
835205d0
GB
14009 inf = find_inferior_pid (pid);
14010 if (inf == NULL)
14011 internal_error (__FILE__, __LINE__,
14012 _("not currently attached to process %d"), pid);
14013
14014 if (!inf->fake_pid_p)
14015 {
14016 const int annex_size = 9;
14017
224c3ddb 14018 annex = (char *) alloca (annex_size);
835205d0
GB
14019 xsnprintf (annex, annex_size, "%x", pid);
14020 }
14021
8b88a78e 14022 filename = target_read_stralloc (current_top_target (),
c78fa86a
GB
14023 TARGET_OBJECT_EXEC_FILE, annex);
14024
9018be22 14025 return filename ? filename->data () : nullptr;
c78fa86a
GB
14026}
14027
750ce8d1
YQ
14028/* Implement the to_can_do_single_step target_ops method. */
14029
f6ac5f3d
PA
14030int
14031remote_target::can_do_single_step ()
750ce8d1
YQ
14032{
14033 /* We can only tell whether target supports single step or not by
14034 supported s and S vCont actions if the stub supports vContSupported
14035 feature. If the stub doesn't support vContSupported feature,
14036 we have conservatively to think target doesn't supports single
14037 step. */
14038 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14039 {
14040 struct remote_state *rs = get_remote_state ();
14041
14042 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 14043 remote_vcont_probe ();
750ce8d1
YQ
14044
14045 return rs->supports_vCont.s && rs->supports_vCont.S;
14046 }
14047 else
14048 return 0;
14049}
14050
3a00c802
PA
14051/* Implementation of the to_execution_direction method for the remote
14052 target. */
14053
f6ac5f3d
PA
14054enum exec_direction_kind
14055remote_target::execution_direction ()
3a00c802
PA
14056{
14057 struct remote_state *rs = get_remote_state ();
14058
14059 return rs->last_resume_exec_dir;
14060}
14061
f6327dcb
KB
14062/* Return pointer to the thread_info struct which corresponds to
14063 THREAD_HANDLE (having length HANDLE_LEN). */
14064
f6ac5f3d
PA
14065thread_info *
14066remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14067 int handle_len,
14068 inferior *inf)
f6327dcb
KB
14069{
14070 struct thread_info *tp;
14071
14072 ALL_NON_EXITED_THREADS (tp)
14073 {
7aabaf9d 14074 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
14075
14076 if (tp->inf == inf && priv != NULL)
14077 {
7aabaf9d 14078 if (handle_len != priv->thread_handle.size ())
f6327dcb 14079 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
7aabaf9d
SM
14080 handle_len, priv->thread_handle.size ());
14081 if (memcmp (thread_handle, priv->thread_handle.data (),
f6327dcb
KB
14082 handle_len) == 0)
14083 return tp;
14084 }
14085 }
14086
14087 return NULL;
14088}
14089
57810aa7 14090bool
f6ac5f3d 14091remote_target::can_async_p ()
6426a772 14092{
5d93a237
TT
14093 struct remote_state *rs = get_remote_state ();
14094
3015c064
SM
14095 /* We don't go async if the user has explicitly prevented it with the
14096 "maint set target-async" command. */
c6ebd6cf 14097 if (!target_async_permitted)
57810aa7 14098 return false;
75c99385 14099
23860348 14100 /* We're async whenever the serial device is. */
5d93a237 14101 return serial_can_async_p (rs->remote_desc);
6426a772
JM
14102}
14103
57810aa7 14104bool
f6ac5f3d 14105remote_target::is_async_p ()
6426a772 14106{
5d93a237
TT
14107 struct remote_state *rs = get_remote_state ();
14108
c6ebd6cf 14109 if (!target_async_permitted)
75c99385 14110 /* We only enable async when the user specifically asks for it. */
57810aa7 14111 return false;
75c99385 14112
23860348 14113 /* We're async whenever the serial device is. */
5d93a237 14114 return serial_is_async_p (rs->remote_desc);
6426a772
JM
14115}
14116
2acceee2
JM
14117/* Pass the SERIAL event on and up to the client. One day this code
14118 will be able to delay notifying the client of an event until the
23860348 14119 point where an entire packet has been received. */
2acceee2 14120
2acceee2
JM
14121static serial_event_ftype remote_async_serial_handler;
14122
6426a772 14123static void
819cc324 14124remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14125{
2acceee2
JM
14126 /* Don't propogate error information up to the client. Instead let
14127 the client find out about the error by querying the target. */
6a3753b3 14128 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
14129}
14130
74531fed
PA
14131static void
14132remote_async_inferior_event_handler (gdb_client_data data)
14133{
6b8edb51 14134 inferior_event_handler (INF_REG_EVENT, data);
74531fed
PA
14135}
14136
f6ac5f3d
PA
14137void
14138remote_target::async (int enable)
2acceee2 14139{
5d93a237
TT
14140 struct remote_state *rs = get_remote_state ();
14141
6a3753b3 14142 if (enable)
2acceee2 14143 {
88b496c3 14144 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14145
14146 /* If there are pending events in the stop reply queue tell the
14147 event loop to process them. */
953edf2b 14148 if (!rs->stop_reply_queue.empty ())
6b8edb51 14149 mark_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14150 /* For simplicity, below we clear the pending events token
14151 without remembering whether it is marked, so here we always
14152 mark it. If there's actually no pending notification to
14153 process, this ends up being a no-op (other than a spurious
14154 event-loop wakeup). */
14155 if (target_is_non_stop_p ())
14156 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14157 }
14158 else
b7d2e916
PA
14159 {
14160 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14161 /* If the core is disabling async, it doesn't want to be
14162 disturbed with target events. Clear all async event sources
14163 too. */
6b8edb51 14164 clear_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14165 if (target_is_non_stop_p ())
14166 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14167 }
6426a772
JM
14168}
14169
65706a29
PA
14170/* Implementation of the to_thread_events method. */
14171
f6ac5f3d
PA
14172void
14173remote_target::thread_events (int enable)
65706a29
PA
14174{
14175 struct remote_state *rs = get_remote_state ();
14176 size_t size = get_remote_packet_size ();
65706a29
PA
14177
14178 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14179 return;
14180
14181 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14182 putpkt (rs->buf);
14183 getpkt (&rs->buf, &rs->buf_size, 0);
14184
14185 switch (packet_ok (rs->buf,
14186 &remote_protocol_packets[PACKET_QThreadEvents]))
14187 {
14188 case PACKET_OK:
14189 if (strcmp (rs->buf, "OK") != 0)
14190 error (_("Remote refused setting thread events: %s"), rs->buf);
14191 break;
14192 case PACKET_ERROR:
14193 warning (_("Remote failure reply: %s"), rs->buf);
14194 break;
14195 case PACKET_UNKNOWN:
14196 break;
14197 }
14198}
14199
5a2468f5 14200static void
981a3fb3 14201set_remote_cmd (const char *args, int from_tty)
5a2468f5 14202{
635c7e8a 14203 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
14204}
14205
d471ea57 14206static void
981a3fb3 14207show_remote_cmd (const char *args, int from_tty)
d471ea57 14208{
37a105a1 14209 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14210 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14211 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14212 struct ui_out *uiout = current_uiout;
37a105a1 14213
2e783024 14214 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14215 for (; list != NULL; list = list->next)
14216 if (strcmp (list->name, "Z-packet") == 0)
14217 continue;
427c3a89
DJ
14218 else if (list->type == not_set_cmd)
14219 /* Alias commands are exactly like the original, except they
14220 don't have the normal type. */
14221 continue;
14222 else
37a105a1 14223 {
2e783024 14224 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14225
112e8700
SM
14226 uiout->field_string ("name", list->name);
14227 uiout->text (": ");
427c3a89 14228 if (list->type == show_cmd)
f5c4fcd9 14229 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14230 else
14231 cmd_func (list, NULL, from_tty);
37a105a1 14232 }
d471ea57 14233}
5a2468f5 14234
0f71a2f6 14235
23860348 14236/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
14237static void
14238remote_new_objfile (struct objfile *objfile)
14239{
6b8edb51 14240 remote_target *remote = get_current_remote_target ();
5d93a237 14241
6b8edb51
PA
14242 if (remote != NULL) /* Have a remote connection. */
14243 remote->remote_check_symbols ();
dc8acb97
MS
14244}
14245
00bf0b85
SS
14246/* Pull all the tracepoints defined on the target and create local
14247 data structures representing them. We don't want to create real
14248 tracepoints yet, we don't want to mess up the user's existing
14249 collection. */
14250
f6ac5f3d
PA
14251int
14252remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 14253{
00bf0b85
SS
14254 struct remote_state *rs = get_remote_state ();
14255 char *p;
d5551862 14256
00bf0b85
SS
14257 /* Ask for a first packet of tracepoint definition. */
14258 putpkt ("qTfP");
14259 getpkt (&rs->buf, &rs->buf_size, 0);
14260 p = rs->buf;
14261 while (*p && *p != 'l')
d5551862 14262 {
00bf0b85
SS
14263 parse_tracepoint_definition (p, utpp);
14264 /* Ask for another packet of tracepoint definition. */
14265 putpkt ("qTsP");
14266 getpkt (&rs->buf, &rs->buf_size, 0);
14267 p = rs->buf;
d5551862 14268 }
00bf0b85 14269 return 0;
d5551862
SS
14270}
14271
f6ac5f3d
PA
14272int
14273remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 14274{
00bf0b85 14275 struct remote_state *rs = get_remote_state ();
d5551862 14276 char *p;
d5551862 14277
00bf0b85
SS
14278 /* Ask for a first packet of variable definition. */
14279 putpkt ("qTfV");
d5551862
SS
14280 getpkt (&rs->buf, &rs->buf_size, 0);
14281 p = rs->buf;
00bf0b85 14282 while (*p && *p != 'l')
d5551862 14283 {
00bf0b85
SS
14284 parse_tsv_definition (p, utsvp);
14285 /* Ask for another packet of variable definition. */
14286 putpkt ("qTsV");
d5551862
SS
14287 getpkt (&rs->buf, &rs->buf_size, 0);
14288 p = rs->buf;
14289 }
00bf0b85 14290 return 0;
d5551862
SS
14291}
14292
c1e36e3e
PA
14293/* The "set/show range-stepping" show hook. */
14294
14295static void
14296show_range_stepping (struct ui_file *file, int from_tty,
14297 struct cmd_list_element *c,
14298 const char *value)
14299{
14300 fprintf_filtered (file,
14301 _("Debugger's willingness to use range stepping "
14302 "is %s.\n"), value);
14303}
14304
6b8edb51
PA
14305/* Return true if the vCont;r action is supported by the remote
14306 stub. */
14307
14308bool
14309remote_target::vcont_r_supported ()
14310{
14311 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14312 remote_vcont_probe ();
14313
14314 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14315 && get_remote_state ()->supports_vCont.r);
14316}
14317
c1e36e3e
PA
14318/* The "set/show range-stepping" set hook. */
14319
14320static void
eb4c3f4a 14321set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
14322 struct cmd_list_element *c)
14323{
6b8edb51
PA
14324 /* When enabling, check whether range stepping is actually supported
14325 by the target, and warn if not. */
c1e36e3e
PA
14326 if (use_range_stepping)
14327 {
6b8edb51
PA
14328 remote_target *remote = get_current_remote_target ();
14329 if (remote == NULL
14330 || !remote->vcont_r_supported ())
14331 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
14332 }
14333}
14334
c906108c 14335void
fba45db2 14336_initialize_remote (void)
c906108c 14337{
9a7071a8 14338 struct cmd_list_element *cmd;
6f937416 14339 const char *cmd_name;
ea9c271d 14340
0f71a2f6 14341 /* architecture specific data */
29709017
DJ
14342 remote_g_packet_data_handle =
14343 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14344
94585166
DB
14345 remote_pspace_data
14346 = register_program_space_data_with_cleanup (NULL,
14347 remote_pspace_data_cleanup);
14348
d9f719f1
PA
14349 add_target (remote_target_info, remote_target::open);
14350 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 14351
dc8acb97 14352 /* Hook into new objfile notification. */
76727919 14353 gdb::observers::new_objfile.attach (remote_new_objfile);
dc8acb97 14354
c906108c
SS
14355#if 0
14356 init_remote_threadtests ();
14357#endif
14358
23860348 14359 /* set/show remote ... */
d471ea57 14360
1bedd215 14361 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
14362Remote protocol specific variables\n\
14363Configure various remote-protocol specific variables such as\n\
1bedd215 14364the packets being used"),
cff3e48b 14365 &remote_set_cmdlist, "set remote ",
23860348 14366 0 /* allow-unknown */, &setlist);
1bedd215 14367 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
14368Remote protocol specific variables\n\
14369Configure various remote-protocol specific variables such as\n\
1bedd215 14370the packets being used"),
cff3e48b 14371 &remote_show_cmdlist, "show remote ",
23860348 14372 0 /* allow-unknown */, &showlist);
5a2468f5 14373
1a966eab
AC
14374 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14375Compare section data on target to the exec file.\n\
95cf3b38
DT
14376Argument is a single section name (default: all loaded sections).\n\
14377To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14378 &cmdlist);
14379
1a966eab
AC
14380 add_cmd ("packet", class_maintenance, packet_command, _("\
14381Send an arbitrary packet to a remote target.\n\
c906108c
SS
14382 maintenance packet TEXT\n\
14383If GDB is talking to an inferior via the GDB serial protocol, then\n\
14384this command sends the string TEXT to the inferior, and displays the\n\
14385response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14386terminating `#' character and checksum."),
c906108c
SS
14387 &maintenancelist);
14388
7915a72c
AC
14389 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14390Set whether to send break if interrupted."), _("\
14391Show whether to send break if interrupted."), _("\
14392If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14393 set_remotebreak, show_remotebreak,
e707bbc2 14394 &setlist, &showlist);
9a7071a8
JB
14395 cmd_name = "remotebreak";
14396 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14397 deprecate_cmd (cmd, "set remote interrupt-sequence");
14398 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14399 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14400 deprecate_cmd (cmd, "show remote interrupt-sequence");
14401
14402 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14403 interrupt_sequence_modes, &interrupt_sequence_mode,
14404 _("\
9a7071a8
JB
14405Set interrupt sequence to remote target."), _("\
14406Show interrupt sequence to remote target."), _("\
14407Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14408 NULL, show_interrupt_sequence,
14409 &remote_set_cmdlist,
14410 &remote_show_cmdlist);
14411
14412 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14413 &interrupt_on_connect, _("\
14414Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14415Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14416If set, interrupt sequence is sent to remote target."),
14417 NULL, NULL,
14418 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14419
23860348 14420 /* Install commands for configuring memory read/write packets. */
11cf8741 14421
1a966eab
AC
14422 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14423Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14424 &setlist);
1a966eab
AC
14425 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14426Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14427 &showlist);
14428 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14429 set_memory_write_packet_size, _("\
14430Set the maximum number of bytes per memory-write packet.\n\
14431Specify the number of bytes in a packet or 0 (zero) for the\n\
14432default packet size. The actual limit is further reduced\n\
14433dependent on the target. Specify ``fixed'' to disable the\n\
14434further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14435 &remote_set_cmdlist);
14436 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14437 set_memory_read_packet_size, _("\
14438Set the maximum number of bytes per memory-read packet.\n\
14439Specify the number of bytes in a packet or 0 (zero) for the\n\
14440default packet size. The actual limit is further reduced\n\
14441dependent on the target. Specify ``fixed'' to disable the\n\
14442further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14443 &remote_set_cmdlist);
14444 add_cmd ("memory-write-packet-size", no_class,
14445 show_memory_write_packet_size,
1a966eab 14446 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14447 &remote_show_cmdlist);
14448 add_cmd ("memory-read-packet-size", no_class,
14449 show_memory_read_packet_size,
1a966eab 14450 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14451 &remote_show_cmdlist);
c906108c 14452
055303e2 14453 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14454 &remote_hw_watchpoint_limit, _("\
14455Set the maximum number of target hardware watchpoints."), _("\
14456Show the maximum number of target hardware watchpoints."), _("\
055303e2
AB
14457Specify \"unlimited\" for unlimited hardware watchpoints."),
14458 NULL, show_hardware_watchpoint_limit,
14459 &remote_set_cmdlist,
14460 &remote_show_cmdlist);
14461 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
14462 no_class,
480a3f21
PW
14463 &remote_hw_watchpoint_length_limit, _("\
14464Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14465Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
055303e2
AB
14466Specify \"unlimited\" to allow watchpoints of unlimited size."),
14467 NULL, show_hardware_watchpoint_length_limit,
480a3f21 14468 &remote_set_cmdlist, &remote_show_cmdlist);
055303e2 14469 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14470 &remote_hw_breakpoint_limit, _("\
14471Set the maximum number of target hardware breakpoints."), _("\
14472Show the maximum number of target hardware breakpoints."), _("\
055303e2
AB
14473Specify \"unlimited\" for unlimited hardware breakpoints."),
14474 NULL, show_hardware_breakpoint_limit,
b3f42336 14475 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14476
1b493192
PA
14477 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14478 &remote_address_size, _("\
4d28ad1e
AC
14479Set the maximum size of the address (in bits) in a memory packet."), _("\
14480Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14481 NULL,
14482 NULL, /* FIXME: i18n: */
14483 &setlist, &showlist);
c906108c 14484
ca4f7f8b
PA
14485 init_all_packet_configs ();
14486
444abaca 14487 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14488 "X", "binary-download", 1);
0f71a2f6 14489
444abaca 14490 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14491 "vCont", "verbose-resume", 0);
506fb367 14492
89be2091
DJ
14493 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14494 "QPassSignals", "pass-signals", 0);
14495
82075af2
JS
14496 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14497 "QCatchSyscalls", "catch-syscalls", 0);
14498
9b224c5e
PA
14499 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14500 "QProgramSignals", "program-signals", 0);
14501
bc3b087d
SDJ
14502 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14503 "QSetWorkingDir", "set-working-dir", 0);
14504
aefd8b33
SDJ
14505 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14506 "QStartupWithShell", "startup-with-shell", 0);
14507
0a2dde4a
SDJ
14508 add_packet_config_cmd (&remote_protocol_packets
14509 [PACKET_QEnvironmentHexEncoded],
14510 "QEnvironmentHexEncoded", "environment-hex-encoded",
14511 0);
14512
14513 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14514 "QEnvironmentReset", "environment-reset",
14515 0);
14516
14517 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14518 "QEnvironmentUnset", "environment-unset",
14519 0);
14520
444abaca 14521 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14522 "qSymbol", "symbol-lookup", 0);
dc8acb97 14523
444abaca 14524 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14525 "P", "set-register", 1);
d471ea57 14526
444abaca 14527 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14528 "p", "fetch-register", 1);
b96ec7ac 14529
444abaca 14530 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14531 "Z0", "software-breakpoint", 0);
d471ea57 14532
444abaca 14533 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14534 "Z1", "hardware-breakpoint", 0);
d471ea57 14535
444abaca 14536 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14537 "Z2", "write-watchpoint", 0);
d471ea57 14538
444abaca 14539 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14540 "Z3", "read-watchpoint", 0);
d471ea57 14541
444abaca 14542 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14543 "Z4", "access-watchpoint", 0);
d471ea57 14544
0876f84a
DJ
14545 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14546 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14547
c78fa86a
GB
14548 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14549 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14550
23181151
DJ
14551 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14552 "qXfer:features:read", "target-features", 0);
14553
cfa9d6d9
DJ
14554 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14555 "qXfer:libraries:read", "library-info", 0);
14556
2268b414
JK
14557 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14558 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14559
fd79ecee
DJ
14560 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14561 "qXfer:memory-map:read", "memory-map", 0);
14562
0e7f50da
UW
14563 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14564 "qXfer:spu:read", "read-spu-object", 0);
14565
14566 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14567 "qXfer:spu:write", "write-spu-object", 0);
14568
07e059b5
VP
14569 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14570 "qXfer:osdata:read", "osdata", 0);
14571
dc146f7c
VP
14572 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14573 "qXfer:threads:read", "threads", 0);
14574
4aa995e1
PA
14575 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14576 "qXfer:siginfo:read", "read-siginfo-object", 0);
14577
14578 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14579 "qXfer:siginfo:write", "write-siginfo-object", 0);
14580
b3b9301e
PA
14581 add_packet_config_cmd
14582 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14583 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14584
169081d0
TG
14585 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14586 "qXfer:uib:read", "unwind-info-block", 0);
14587
444abaca 14588 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14589 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14590 0);
14591
711e434b
PM
14592 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14593 "qGetTIBAddr", "get-thread-information-block-address",
14594 0);
14595
40ab02ce
MS
14596 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14597 "bc", "reverse-continue", 0);
14598
14599 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14600 "bs", "reverse-step", 0);
14601
be2a5f71
DJ
14602 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14603 "qSupported", "supported-packets", 0);
14604
08388c79
DE
14605 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14606 "qSearch:memory", "search-memory", 0);
14607
bd3eecc3
PA
14608 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14609 "qTStatus", "trace-status", 0);
14610
15a201c8
GB
14611 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14612 "vFile:setfs", "hostio-setfs", 0);
14613
a6b151f1
DJ
14614 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14615 "vFile:open", "hostio-open", 0);
14616
14617 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14618 "vFile:pread", "hostio-pread", 0);
14619
14620 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14621 "vFile:pwrite", "hostio-pwrite", 0);
14622
14623 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14624 "vFile:close", "hostio-close", 0);
14625
14626 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14627 "vFile:unlink", "hostio-unlink", 0);
14628
b9e7b9c3
UW
14629 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14630 "vFile:readlink", "hostio-readlink", 0);
14631
0a93529c
GB
14632 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14633 "vFile:fstat", "hostio-fstat", 0);
14634
2d717e4f
DJ
14635 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14636 "vAttach", "attach", 0);
14637
14638 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14639 "vRun", "run", 0);
14640
a6f3e723
SL
14641 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14642 "QStartNoAckMode", "noack", 0);
14643
82f73884
PA
14644 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14645 "vKill", "kill", 0);
14646
0b16c5cf
PA
14647 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14648 "qAttached", "query-attached", 0);
14649
782b2b07 14650 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14651 "ConditionalTracepoints",
14652 "conditional-tracepoints", 0);
3788aec7
LM
14653
14654 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14655 "ConditionalBreakpoints",
14656 "conditional-breakpoints", 0);
14657
d3ce09f5
SS
14658 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14659 "BreakpointCommands",
14660 "breakpoint-commands", 0);
14661
7a697b8d
SS
14662 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14663 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14664
409873ef
SS
14665 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14666 "TracepointSource", "TracepointSource", 0);
14667
d914c394
SS
14668 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14669 "QAllow", "allow", 0);
14670
0fb4aa4b
PA
14671 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14672 "StaticTracepoints", "static-tracepoints", 0);
14673
1e4d1764
YQ
14674 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14675 "InstallInTrace", "install-in-trace", 0);
14676
0fb4aa4b
PA
14677 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14678 "qXfer:statictrace:read", "read-sdata-object", 0);
14679
78d85199
YQ
14680 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14681 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14682
03583c20
UW
14683 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14684 "QDisableRandomization", "disable-randomization", 0);
14685
d1feda86
YQ
14686 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14687 "QAgent", "agent", 0);
14688
f6f899bf
HAQ
14689 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14690 "QTBuffer:size", "trace-buffer-size", 0);
14691
9accd112
MM
14692 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14693 "Qbtrace:off", "disable-btrace", 0);
14694
14695 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14696 "Qbtrace:bts", "enable-btrace-bts", 0);
14697
14698 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14699 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14700
14701 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14702 "qXfer:btrace", "read-btrace", 0);
14703
f4abbc16
MM
14704 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14705 "qXfer:btrace-conf", "read-btrace-conf", 0);
14706
d33501a5
MM
14707 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14708 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14709
73b8c1fd
PA
14710 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14711 "multiprocess-feature", "multiprocess-feature", 0);
14712
f7e6eed5
PA
14713 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14714 "swbreak-feature", "swbreak-feature", 0);
14715
14716 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14717 "hwbreak-feature", "hwbreak-feature", 0);
14718
89245bc0
DB
14719 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14720 "fork-event-feature", "fork-event-feature", 0);
14721
14722 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14723 "vfork-event-feature", "vfork-event-feature", 0);
14724
b20a6524
MM
14725 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14726 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14727
750ce8d1
YQ
14728 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14729 "vContSupported", "verbose-resume-supported", 0);
14730
94585166
DB
14731 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14732 "exec-event-feature", "exec-event-feature", 0);
14733
de979965
PA
14734 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14735 "vCtrlC", "ctrl-c", 0);
14736
65706a29
PA
14737 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14738 "QThreadEvents", "thread-events", 0);
14739
f2faf941
PA
14740 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14741 "N stop reply", "no-resumed-stop-reply", 0);
14742
0b736949
DB
14743 /* Assert that we've registered "set remote foo-packet" commands
14744 for all packet configs. */
ca4f7f8b
PA
14745 {
14746 int i;
14747
14748 for (i = 0; i < PACKET_MAX; i++)
14749 {
14750 /* Ideally all configs would have a command associated. Some
14751 still don't though. */
14752 int excepted;
14753
14754 switch (i)
14755 {
14756 case PACKET_QNonStop:
ca4f7f8b
PA
14757 case PACKET_EnableDisableTracepoints_feature:
14758 case PACKET_tracenz_feature:
14759 case PACKET_DisconnectedTracing_feature:
14760 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14761 case PACKET_qCRC:
14762 /* Additions to this list need to be well justified:
14763 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14764 excepted = 1;
14765 break;
14766 default:
14767 excepted = 0;
14768 break;
14769 }
14770
14771 /* This catches both forgetting to add a config command, and
14772 forgetting to remove a packet from the exception list. */
14773 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14774 }
14775 }
14776
37a105a1
DJ
14777 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14778 Z sub-packet has its own set and show commands, but users may
14779 have sets to this variable in their .gdbinit files (or in their
14780 documentation). */
e9e68a56 14781 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14782 &remote_Z_packet_detect, _("\
14783Set use of remote protocol `Z' packets"), _("\
14784Show use of remote protocol `Z' packets "), _("\
3b64bf98 14785When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14786packets."),
e9e68a56 14787 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14788 show_remote_protocol_Z_packet_cmd,
14789 /* FIXME: i18n: Use of remote protocol
14790 `Z' packets is %s. */
e9e68a56 14791 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14792
a6b151f1
DJ
14793 add_prefix_cmd ("remote", class_files, remote_command, _("\
14794Manipulate files on the remote system\n\
14795Transfer files to and from the remote target system."),
14796 &remote_cmdlist, "remote ",
14797 0 /* allow-unknown */, &cmdlist);
14798
14799 add_cmd ("put", class_files, remote_put_command,
14800 _("Copy a local file to the remote system."),
14801 &remote_cmdlist);
14802
14803 add_cmd ("get", class_files, remote_get_command,
14804 _("Copy a remote file to the local system."),
14805 &remote_cmdlist);
14806
14807 add_cmd ("delete", class_files, remote_delete_command,
14808 _("Delete a remote file."),
14809 &remote_cmdlist);
14810
2d717e4f 14811 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14812 &remote_exec_file_var, _("\
2d717e4f 14813Set the remote pathname for \"run\""), _("\
94585166
DB
14814Show the remote pathname for \"run\""), NULL,
14815 set_remote_exec_file,
14816 show_remote_exec_file,
14817 &remote_set_cmdlist,
14818 &remote_show_cmdlist);
2d717e4f 14819
c1e36e3e
PA
14820 add_setshow_boolean_cmd ("range-stepping", class_run,
14821 &use_range_stepping, _("\
14822Enable or disable range stepping."), _("\
14823Show whether target-assisted range stepping is enabled."), _("\
14824If on, and the target supports it, when stepping a source line, GDB\n\
14825tells the target to step the corresponding range of addresses itself instead\n\
14826of issuing multiple single-steps. This speeds up source level\n\
14827stepping. If off, GDB always issues single-steps, even if range\n\
14828stepping is supported by the target. The default is on."),
14829 set_range_stepping,
14830 show_range_stepping,
14831 &setlist,
14832 &showlist);
14833
449092f6
CV
14834 /* Eventually initialize fileio. See fileio.c */
14835 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14836
ba348170 14837 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14838 special ptids with it set to != 0. */
fd79271b
TT
14839 magic_null_ptid = ptid_t (42000, -1, 1);
14840 not_sent_ptid = ptid_t (42000, -2, 1);
14841 any_thread_ptid = ptid_t (42000, 0, 1);
c906108c 14842}
This page took 3.663483 seconds and 4 git commands to generate.