Avoid memcpys in regcache read_part/write_part for full registers.
[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);
6b8edb51
PA
740 void remote_detach_1 (int from_tty, struct inferior *inf);
741
742 char *append_resumption (char *p, char *endp,
743 ptid_t ptid, int step, gdb_signal siggnal);
744 int remote_resume_with_vcont (ptid_t ptid, int step,
745 gdb_signal siggnal);
746
747 void add_current_inferior_and_thread (char *wait_status);
748
749 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
750 int options);
751 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
752 int options);
753
754 ptid_t process_stop_reply (struct stop_reply *stop_reply,
755 target_waitstatus *status);
756
757 void remote_notice_new_inferior (ptid_t currthread, int executing);
758
759 void process_initial_stop_replies (int from_tty);
760
761 void remote_add_thread (ptid_t ptid, bool running, bool executing);
762
763 void btrace_sync_conf (const btrace_config *conf);
764
765 void remote_btrace_maybe_reopen ();
766
767 void remove_new_fork_children (threads_listing_context *context);
768 void kill_new_fork_children (int pid);
769 void discard_pending_stop_replies (struct inferior *inf);
770 int stop_reply_queue_length ();
771
772 void check_pending_events_prevent_wildcard_vcont
773 (int *may_global_wildcard_vcont);
774
775 void discard_pending_stop_replies_in_queue ();
776 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
777 struct stop_reply *queued_stop_reply (ptid_t ptid);
778 int peek_stop_reply (ptid_t ptid);
779 void remote_parse_stop_reply (char *buf, stop_reply *event);
780
781 void remote_stop_ns (ptid_t ptid);
782 void remote_interrupt_as ();
783 void remote_interrupt_ns ();
784
785 char *remote_get_noisy_reply ();
786 int remote_query_attached (int pid);
787 inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
788 int try_open_exec);
789
790 ptid_t remote_current_thread (ptid_t oldpid);
791 ptid_t get_current_thread (char *wait_status);
792
793 void set_thread (ptid_t ptid, int gen);
794 void set_general_thread (ptid_t ptid);
795 void set_continue_thread (ptid_t ptid);
796 void set_general_process ();
797
798 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
799
800 int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
801 gdb_ext_thread_info *info);
802 int remote_get_threadinfo (threadref *threadid, int fieldset,
803 gdb_ext_thread_info *info);
804
805 int parse_threadlist_response (char *pkt, int result_limit,
806 threadref *original_echo,
807 threadref *resultlist,
808 int *doneflag);
809 int remote_get_threadlist (int startflag, threadref *nextthread,
810 int result_limit, int *done, int *result_count,
811 threadref *threadlist);
812
813 int remote_threadlist_iterator (rmt_thread_action stepfunction,
814 void *context, int looplimit);
815
816 int remote_get_threads_with_ql (threads_listing_context *context);
817 int remote_get_threads_with_qxfer (threads_listing_context *context);
818 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
819
820 void extended_remote_restart ();
821
822 void get_offsets ();
823
824 void remote_check_symbols ();
825
826 void remote_supported_packet (const struct protocol_feature *feature,
827 enum packet_support support,
828 const char *argument);
829
830 void remote_query_supported ();
831
832 void remote_packet_size (const protocol_feature *feature,
833 packet_support support, const char *value);
834
835 void remote_serial_quit_handler ();
836
837 void remote_detach_pid (int pid);
838
839 void remote_vcont_probe ();
840
841 void remote_resume_with_hc (ptid_t ptid, int step,
842 gdb_signal siggnal);
843
844 void send_interrupt_sequence ();
845 void interrupt_query ();
846
847 void remote_notif_get_pending_events (notif_client *nc);
848
849 int fetch_register_using_p (struct regcache *regcache,
850 packet_reg *reg);
851 int send_g_packet ();
852 void process_g_packet (struct regcache *regcache);
853 void fetch_registers_using_g (struct regcache *regcache);
854 int store_register_using_P (const struct regcache *regcache,
855 packet_reg *reg);
856 void store_registers_using_G (const struct regcache *regcache);
857
858 void set_remote_traceframe ();
859
860 void check_binary_download (CORE_ADDR addr);
861
862 target_xfer_status remote_write_bytes_aux (const char *header,
863 CORE_ADDR memaddr,
864 const gdb_byte *myaddr,
865 ULONGEST len_units,
866 int unit_size,
867 ULONGEST *xfered_len_units,
868 char packet_format,
869 int use_length);
870
871 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
872 const gdb_byte *myaddr, ULONGEST len,
873 int unit_size, ULONGEST *xfered_len);
874
875 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
876 ULONGEST len_units,
877 int unit_size, ULONGEST *xfered_len_units);
878
879 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
880 ULONGEST memaddr,
881 ULONGEST len,
882 int unit_size,
883 ULONGEST *xfered_len);
884
885 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
886 gdb_byte *myaddr, ULONGEST len,
887 int unit_size,
888 ULONGEST *xfered_len);
889
890 packet_result remote_send_printf (const char *format, ...)
891 ATTRIBUTE_PRINTF (2, 3);
892
893 target_xfer_status remote_flash_write (ULONGEST address,
894 ULONGEST length, ULONGEST *xfered_len,
895 const gdb_byte *data);
896
897 int readchar (int timeout);
898
899 void remote_serial_write (const char *str, int len);
900
901 int putpkt (const char *buf);
902 int putpkt_binary (const char *buf, int cnt);
903
904 void skip_frame ();
905 long read_frame (char **buf_p, long *sizeof_buf);
906 void getpkt (char **buf, long *sizeof_buf, int forever);
907 int getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
908 int expecting_notif, int *is_notif);
909 int getpkt_sane (char **buf, long *sizeof_buf, int forever);
910 int getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
911 int *is_notif);
912 int remote_vkill (int pid);
913 void remote_kill_k ();
914
915 void extended_remote_disable_randomization (int val);
916 int extended_remote_run (const std::string &args);
917
918 void send_environment_packet (const char *action,
919 const char *packet,
920 const char *value);
921
922 void extended_remote_environment_support ();
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
6b8edb51
PA
1731long
1732remote_target::get_memory_write_packet_size ()
11cf8741
JM
1733{
1734 return get_memory_packet_size (&memory_write_packet_config);
1735}
1736
1737static struct memory_packet_config memory_read_packet_config =
1738{
1739 "memory-read-packet-size",
1740};
1741
1742static void
ac88e2de 1743set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1744{
1745 set_memory_packet_size (args, &memory_read_packet_config);
1746}
1747
1748static void
ac88e2de 1749show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1750{
1751 show_memory_packet_size (&memory_read_packet_config);
1752}
1753
6b8edb51
PA
1754long
1755remote_target::get_memory_read_packet_size ()
11cf8741
JM
1756{
1757 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1758
11cf8741
JM
1759 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1760 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1761 increased beyond this. */
1762 if (size > get_remote_packet_size ())
1763 size = get_remote_packet_size ();
11cf8741
JM
1764 return size;
1765}
1766
11cf8741 1767\f
5a2468f5 1768
5a2468f5
JM
1769struct packet_config
1770 {
bb572ddd
DJ
1771 const char *name;
1772 const char *title;
4082afcc
PA
1773
1774 /* If auto, GDB auto-detects support for this packet or feature,
1775 either through qSupported, or by trying the packet and looking
1776 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1777 packet. If false, the packet is disabled. Configs that don't
1778 have an associated command always have this set to auto. */
7f19b9a2 1779 enum auto_boolean detect;
4082afcc
PA
1780
1781 /* Does the target support this packet? */
5a2468f5
JM
1782 enum packet_support support;
1783 };
1784
4082afcc
PA
1785static enum packet_support packet_config_support (struct packet_config *config);
1786static enum packet_support packet_support (int packet);
5a2468f5
JM
1787
1788static void
fba45db2 1789show_packet_config_cmd (struct packet_config *config)
5a2468f5 1790{
a121b7c1 1791 const char *support = "internal-error";
a744cf53 1792
4082afcc 1793 switch (packet_config_support (config))
5a2468f5
JM
1794 {
1795 case PACKET_ENABLE:
1796 support = "enabled";
1797 break;
1798 case PACKET_DISABLE:
1799 support = "disabled";
1800 break;
1801 case PACKET_SUPPORT_UNKNOWN:
1802 support = "unknown";
1803 break;
1804 }
1805 switch (config->detect)
1806 {
7f19b9a2 1807 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1808 printf_filtered (_("Support for the `%s' packet "
1809 "is auto-detected, currently %s.\n"),
37a105a1 1810 config->name, support);
5a2468f5 1811 break;
7f19b9a2
AC
1812 case AUTO_BOOLEAN_TRUE:
1813 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1814 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1815 config->name, support);
8e248173 1816 break;
5a2468f5
JM
1817 }
1818}
1819
1820static void
bb572ddd
DJ
1821add_packet_config_cmd (struct packet_config *config, const char *name,
1822 const char *title, int legacy)
d471ea57 1823{
5a2468f5
JM
1824 char *set_doc;
1825 char *show_doc;
d471ea57 1826 char *cmd_name;
3ed07be4 1827
5a2468f5
JM
1828 config->name = name;
1829 config->title = title;
b435e160
AC
1830 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1831 name, title);
3e43a32a
MS
1832 show_doc = xstrprintf ("Show current use of remote "
1833 "protocol `%s' (%s) packet",
b435e160 1834 name, title);
d471ea57 1835 /* set/show TITLE-packet {auto,on,off} */
b435e160 1836 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1837 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1838 &config->detect, set_doc,
1839 show_doc, NULL, /* help_doc */
4082afcc 1840 NULL,
bb572ddd
DJ
1841 show_remote_protocol_packet_cmd,
1842 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1843 /* The command code copies the documentation strings. */
1844 xfree (set_doc);
1845 xfree (show_doc);
23860348 1846 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1847 if (legacy)
1848 {
1849 char *legacy_name;
a744cf53 1850
b435e160 1851 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1852 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1853 &remote_set_cmdlist);
d471ea57 1854 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1855 &remote_show_cmdlist);
d471ea57 1856 }
5a2468f5
JM
1857}
1858
d471ea57 1859static enum packet_result
a76d924d 1860packet_check_result (const char *buf)
5a2468f5 1861{
d471ea57 1862 if (buf[0] != '\0')
5a2468f5 1863 {
d471ea57 1864 /* The stub recognized the packet request. Check that the
23860348 1865 operation succeeded. */
a76d924d
DJ
1866 if (buf[0] == 'E'
1867 && isxdigit (buf[1]) && isxdigit (buf[2])
1868 && buf[3] == '\0')
1869 /* "Enn" - definitly an error. */
1870 return PACKET_ERROR;
1871
1872 /* Always treat "E." as an error. This will be used for
1873 more verbose error messages, such as E.memtypes. */
1874 if (buf[0] == 'E' && buf[1] == '.')
1875 return PACKET_ERROR;
1876
1877 /* The packet may or may not be OK. Just assume it is. */
1878 return PACKET_OK;
1879 }
1880 else
1881 /* The stub does not support the packet. */
1882 return PACKET_UNKNOWN;
1883}
1884
1885static enum packet_result
1886packet_ok (const char *buf, struct packet_config *config)
1887{
1888 enum packet_result result;
1889
4082afcc
PA
1890 if (config->detect != AUTO_BOOLEAN_TRUE
1891 && config->support == PACKET_DISABLE)
1892 internal_error (__FILE__, __LINE__,
1893 _("packet_ok: attempt to use a disabled packet"));
1894
a76d924d
DJ
1895 result = packet_check_result (buf);
1896 switch (result)
1897 {
1898 case PACKET_OK:
1899 case PACKET_ERROR:
1900 /* The stub recognized the packet request. */
4082afcc 1901 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1902 {
d471ea57
AC
1903 if (remote_debug)
1904 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1905 "Packet %s (%s) is supported\n",
1906 config->name, config->title);
d471ea57 1907 config->support = PACKET_ENABLE;
d471ea57 1908 }
a76d924d
DJ
1909 break;
1910 case PACKET_UNKNOWN:
23860348 1911 /* The stub does not support the packet. */
4082afcc
PA
1912 if (config->detect == AUTO_BOOLEAN_AUTO
1913 && config->support == PACKET_ENABLE)
d471ea57 1914 {
4082afcc
PA
1915 /* If the stub previously indicated that the packet was
1916 supported then there is a protocol error. */
1917 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1918 config->name, config->title);
1919 }
1920 else if (config->detect == AUTO_BOOLEAN_TRUE)
1921 {
1922 /* The user set it wrong. */
1923 error (_("Enabled packet %s (%s) not recognized by stub"),
1924 config->name, config->title);
d471ea57 1925 }
4082afcc
PA
1926
1927 if (remote_debug)
1928 fprintf_unfiltered (gdb_stdlog,
1929 "Packet %s (%s) is NOT supported\n",
1930 config->name, config->title);
1931 config->support = PACKET_DISABLE;
a76d924d 1932 break;
5a2468f5 1933 }
a76d924d
DJ
1934
1935 return result;
5a2468f5
JM
1936}
1937
444abaca
DJ
1938enum {
1939 PACKET_vCont = 0,
1940 PACKET_X,
1941 PACKET_qSymbol,
1942 PACKET_P,
1943 PACKET_p,
1944 PACKET_Z0,
1945 PACKET_Z1,
1946 PACKET_Z2,
1947 PACKET_Z3,
1948 PACKET_Z4,
15a201c8 1949 PACKET_vFile_setfs,
a6b151f1
DJ
1950 PACKET_vFile_open,
1951 PACKET_vFile_pread,
1952 PACKET_vFile_pwrite,
1953 PACKET_vFile_close,
1954 PACKET_vFile_unlink,
b9e7b9c3 1955 PACKET_vFile_readlink,
0a93529c 1956 PACKET_vFile_fstat,
0876f84a 1957 PACKET_qXfer_auxv,
23181151 1958 PACKET_qXfer_features,
c78fa86a 1959 PACKET_qXfer_exec_file,
cfa9d6d9 1960 PACKET_qXfer_libraries,
2268b414 1961 PACKET_qXfer_libraries_svr4,
fd79ecee 1962 PACKET_qXfer_memory_map,
0e7f50da
UW
1963 PACKET_qXfer_spu_read,
1964 PACKET_qXfer_spu_write,
07e059b5 1965 PACKET_qXfer_osdata,
dc146f7c 1966 PACKET_qXfer_threads,
0fb4aa4b 1967 PACKET_qXfer_statictrace_read,
b3b9301e 1968 PACKET_qXfer_traceframe_info,
169081d0 1969 PACKET_qXfer_uib,
711e434b 1970 PACKET_qGetTIBAddr,
444abaca 1971 PACKET_qGetTLSAddr,
be2a5f71 1972 PACKET_qSupported,
bd3eecc3 1973 PACKET_qTStatus,
89be2091 1974 PACKET_QPassSignals,
82075af2 1975 PACKET_QCatchSyscalls,
9b224c5e 1976 PACKET_QProgramSignals,
bc3b087d 1977 PACKET_QSetWorkingDir,
aefd8b33 1978 PACKET_QStartupWithShell,
0a2dde4a
SDJ
1979 PACKET_QEnvironmentHexEncoded,
1980 PACKET_QEnvironmentReset,
1981 PACKET_QEnvironmentUnset,
936d2992 1982 PACKET_qCRC,
08388c79 1983 PACKET_qSearch_memory,
2d717e4f
DJ
1984 PACKET_vAttach,
1985 PACKET_vRun,
a6f3e723 1986 PACKET_QStartNoAckMode,
82f73884 1987 PACKET_vKill,
4aa995e1
PA
1988 PACKET_qXfer_siginfo_read,
1989 PACKET_qXfer_siginfo_write,
0b16c5cf 1990 PACKET_qAttached,
4082afcc
PA
1991
1992 /* Support for conditional tracepoints. */
782b2b07 1993 PACKET_ConditionalTracepoints,
4082afcc
PA
1994
1995 /* Support for target-side breakpoint conditions. */
3788aec7 1996 PACKET_ConditionalBreakpoints,
4082afcc
PA
1997
1998 /* Support for target-side breakpoint commands. */
d3ce09f5 1999 PACKET_BreakpointCommands,
4082afcc
PA
2000
2001 /* Support for fast tracepoints. */
7a697b8d 2002 PACKET_FastTracepoints,
4082afcc
PA
2003
2004 /* Support for static tracepoints. */
0fb4aa4b 2005 PACKET_StaticTracepoints,
4082afcc
PA
2006
2007 /* Support for installing tracepoints while a trace experiment is
2008 running. */
1e4d1764 2009 PACKET_InstallInTrace,
4082afcc 2010
40ab02ce
MS
2011 PACKET_bc,
2012 PACKET_bs,
409873ef 2013 PACKET_TracepointSource,
d914c394 2014 PACKET_QAllow,
78d85199 2015 PACKET_qXfer_fdpic,
03583c20 2016 PACKET_QDisableRandomization,
d1feda86 2017 PACKET_QAgent,
f6f899bf 2018 PACKET_QTBuffer_size,
9accd112
MM
2019 PACKET_Qbtrace_off,
2020 PACKET_Qbtrace_bts,
b20a6524 2021 PACKET_Qbtrace_pt,
9accd112 2022 PACKET_qXfer_btrace,
4082afcc
PA
2023
2024 /* Support for the QNonStop packet. */
2025 PACKET_QNonStop,
2026
65706a29
PA
2027 /* Support for the QThreadEvents packet. */
2028 PACKET_QThreadEvents,
2029
4082afcc
PA
2030 /* Support for multi-process extensions. */
2031 PACKET_multiprocess_feature,
2032
2033 /* Support for enabling and disabling tracepoints while a trace
2034 experiment is running. */
2035 PACKET_EnableDisableTracepoints_feature,
2036
2037 /* Support for collecting strings using the tracenz bytecode. */
2038 PACKET_tracenz_feature,
2039
2040 /* Support for continuing to run a trace experiment while GDB is
2041 disconnected. */
2042 PACKET_DisconnectedTracing_feature,
2043
2044 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2045 PACKET_augmented_libraries_svr4_read_feature,
2046
f4abbc16
MM
2047 /* Support for the qXfer:btrace-conf:read packet. */
2048 PACKET_qXfer_btrace_conf,
2049
d33501a5
MM
2050 /* Support for the Qbtrace-conf:bts:size packet. */
2051 PACKET_Qbtrace_conf_bts_size,
2052
f7e6eed5
PA
2053 /* Support for swbreak+ feature. */
2054 PACKET_swbreak_feature,
2055
2056 /* Support for hwbreak+ feature. */
2057 PACKET_hwbreak_feature,
2058
89245bc0
DB
2059 /* Support for fork events. */
2060 PACKET_fork_event_feature,
2061
2062 /* Support for vfork events. */
2063 PACKET_vfork_event_feature,
2064
b20a6524
MM
2065 /* Support for the Qbtrace-conf:pt:size packet. */
2066 PACKET_Qbtrace_conf_pt_size,
2067
94585166
DB
2068 /* Support for exec events. */
2069 PACKET_exec_event_feature,
2070
750ce8d1
YQ
2071 /* Support for query supported vCont actions. */
2072 PACKET_vContSupported,
2073
de979965
PA
2074 /* Support remote CTRL-C. */
2075 PACKET_vCtrlC,
2076
f2faf941
PA
2077 /* Support TARGET_WAITKIND_NO_RESUMED. */
2078 PACKET_no_resumed,
2079
444abaca
DJ
2080 PACKET_MAX
2081};
506fb367 2082
444abaca 2083static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 2084
f7e6eed5
PA
2085/* Returns the packet's corresponding "set remote foo-packet" command
2086 state. See struct packet_config for more details. */
2087
2088static enum auto_boolean
2089packet_set_cmd_state (int packet)
2090{
2091 return remote_protocol_packets[packet].detect;
2092}
2093
4082afcc
PA
2094/* Returns whether a given packet or feature is supported. This takes
2095 into account the state of the corresponding "set remote foo-packet"
2096 command, which may be used to bypass auto-detection. */
dc8acb97 2097
4082afcc
PA
2098static enum packet_support
2099packet_config_support (struct packet_config *config)
2100{
2101 switch (config->detect)
444abaca 2102 {
4082afcc
PA
2103 case AUTO_BOOLEAN_TRUE:
2104 return PACKET_ENABLE;
2105 case AUTO_BOOLEAN_FALSE:
2106 return PACKET_DISABLE;
2107 case AUTO_BOOLEAN_AUTO:
2108 return config->support;
2109 default:
2110 gdb_assert_not_reached (_("bad switch"));
444abaca 2111 }
4082afcc
PA
2112}
2113
2114/* Same as packet_config_support, but takes the packet's enum value as
2115 argument. */
2116
2117static enum packet_support
2118packet_support (int packet)
2119{
2120 struct packet_config *config = &remote_protocol_packets[packet];
2121
2122 return packet_config_support (config);
dc8acb97
MS
2123}
2124
5a2468f5 2125static void
444abaca
DJ
2126show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2127 struct cmd_list_element *c,
2128 const char *value)
5a2468f5 2129{
444abaca 2130 struct packet_config *packet;
5a2468f5 2131
444abaca
DJ
2132 for (packet = remote_protocol_packets;
2133 packet < &remote_protocol_packets[PACKET_MAX];
2134 packet++)
2135 {
2136 if (&packet->detect == c->var)
2137 {
2138 show_packet_config_cmd (packet);
2139 return;
2140 }
2141 }
9b20d036 2142 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 2143 c->name);
5a2468f5
JM
2144}
2145
d471ea57
AC
2146/* Should we try one of the 'Z' requests? */
2147
2148enum Z_packet_type
2149{
2150 Z_PACKET_SOFTWARE_BP,
2151 Z_PACKET_HARDWARE_BP,
2152 Z_PACKET_WRITE_WP,
2153 Z_PACKET_READ_WP,
2154 Z_PACKET_ACCESS_WP,
2155 NR_Z_PACKET_TYPES
2156};
96baa820 2157
d471ea57 2158/* For compatibility with older distributions. Provide a ``set remote
23860348 2159 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2160
7f19b9a2 2161static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2162
2163static void
eb4c3f4a 2164set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2165 struct cmd_list_element *c)
96baa820 2166{
d471ea57 2167 int i;
a744cf53 2168
d471ea57 2169 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 2170 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
2171}
2172
2173static void
08546159
AC
2174show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2175 struct cmd_list_element *c,
2176 const char *value)
96baa820 2177{
d471ea57 2178 int i;
a744cf53 2179
d471ea57
AC
2180 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2181 {
444abaca 2182 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 2183 }
96baa820
JM
2184}
2185
4082afcc
PA
2186/* Returns true if the multi-process extensions are in effect. */
2187
2188static int
2189remote_multi_process_p (struct remote_state *rs)
2190{
2191 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2192}
2193
de0d863e
DB
2194/* Returns true if fork events are supported. */
2195
2196static int
2197remote_fork_event_p (struct remote_state *rs)
2198{
2199 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2200}
2201
c269dbdb
DB
2202/* Returns true if vfork events are supported. */
2203
2204static int
2205remote_vfork_event_p (struct remote_state *rs)
2206{
2207 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2208}
2209
d46addbb
DB
2210/* Returns true if exec events are supported. */
2211
2212static int
2213remote_exec_event_p (struct remote_state *rs)
2214{
2215 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2216}
2217
cbb8991c
DB
2218/* Insert fork catchpoint target routine. If fork events are enabled
2219 then return success, nothing more to do. */
2220
f6ac5f3d
PA
2221int
2222remote_target::insert_fork_catchpoint (int pid)
cbb8991c
DB
2223{
2224 struct remote_state *rs = get_remote_state ();
2225
2226 return !remote_fork_event_p (rs);
2227}
2228
2229/* Remove fork catchpoint target routine. Nothing to do, just
2230 return success. */
2231
f6ac5f3d
PA
2232int
2233remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2234{
2235 return 0;
2236}
2237
2238/* Insert vfork catchpoint target routine. If vfork events are enabled
2239 then return success, nothing more to do. */
2240
f6ac5f3d
PA
2241int
2242remote_target::insert_vfork_catchpoint (int pid)
cbb8991c
DB
2243{
2244 struct remote_state *rs = get_remote_state ();
2245
2246 return !remote_vfork_event_p (rs);
2247}
2248
2249/* Remove vfork catchpoint target routine. Nothing to do, just
2250 return success. */
2251
f6ac5f3d
PA
2252int
2253remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2254{
2255 return 0;
2256}
2257
d46addbb
DB
2258/* Insert exec catchpoint target routine. If exec events are
2259 enabled, just return success. */
2260
f6ac5f3d
PA
2261int
2262remote_target::insert_exec_catchpoint (int pid)
d46addbb
DB
2263{
2264 struct remote_state *rs = get_remote_state ();
2265
2266 return !remote_exec_event_p (rs);
2267}
2268
2269/* Remove exec catchpoint target routine. Nothing to do, just
2270 return success. */
2271
f6ac5f3d
PA
2272int
2273remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2274{
2275 return 0;
2276}
2277
c906108c
SS
2278\f
2279
79d7f229
PA
2280static ptid_t magic_null_ptid;
2281static ptid_t not_sent_ptid;
2282static ptid_t any_thread_ptid;
2283
0b16c5cf
PA
2284/* Find out if the stub attached to PID (and hence GDB should offer to
2285 detach instead of killing it when bailing out). */
2286
6b8edb51
PA
2287int
2288remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2289{
2290 struct remote_state *rs = get_remote_state ();
bba74b36 2291 size_t size = get_remote_packet_size ();
0b16c5cf 2292
4082afcc 2293 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2294 return 0;
2295
2296 if (remote_multi_process_p (rs))
bba74b36 2297 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 2298 else
bba74b36 2299 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
2300
2301 putpkt (rs->buf);
2302 getpkt (&rs->buf, &rs->buf_size, 0);
2303
2304 switch (packet_ok (rs->buf,
1554e9be 2305 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
2306 {
2307 case PACKET_OK:
2308 if (strcmp (rs->buf, "1") == 0)
2309 return 1;
2310 break;
2311 case PACKET_ERROR:
2312 warning (_("Remote failure reply: %s"), rs->buf);
2313 break;
2314 case PACKET_UNKNOWN:
2315 break;
2316 }
2317
2318 return 0;
2319}
2320
49c62f2e
PA
2321/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2322 has been invented by GDB, instead of reported by the target. Since
2323 we can be connected to a remote system before before knowing about
2324 any inferior, mark the target with execution when we find the first
2325 inferior. If ATTACHED is 1, then we had just attached to this
2326 inferior. If it is 0, then we just created this inferior. If it
2327 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2328 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2329 attempt to open this inferior's executable as the main executable
2330 if no main executable is open already. */
1941c569 2331
6b8edb51
PA
2332inferior *
2333remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2334 int try_open_exec)
1941c569 2335{
1941c569
PA
2336 struct inferior *inf;
2337
0b16c5cf
PA
2338 /* Check whether this process we're learning about is to be
2339 considered attached, or if is to be considered to have been
2340 spawned by the stub. */
2341 if (attached == -1)
2342 attached = remote_query_attached (pid);
2343
f5656ead 2344 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2345 {
2346 /* If the target shares code across all inferiors, then every
2347 attach adds a new inferior. */
2348 inf = add_inferior (pid);
2349
2350 /* ... and every inferior is bound to the same program space.
2351 However, each inferior may still have its own address
2352 space. */
2353 inf->aspace = maybe_new_address_space ();
2354 inf->pspace = current_program_space;
2355 }
2356 else
2357 {
2358 /* In the traditional debugging scenario, there's a 1-1 match
2359 between program/address spaces. We simply bind the inferior
2360 to the program space's address space. */
2361 inf = current_inferior ();
2362 inferior_appeared (inf, pid);
2363 }
1941c569 2364
0b16c5cf 2365 inf->attach_flag = attached;
49c62f2e 2366 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2367
1b6e6f5c
GB
2368 /* If no main executable is currently open then attempt to
2369 open the file that was executed to create this inferior. */
835205d0 2370 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2371 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2372
1941c569
PA
2373 return inf;
2374}
2375
7aabaf9d 2376static remote_thread_info *get_remote_thread_info (thread_info *thread);
85ad3aaf 2377
1941c569
PA
2378/* Add thread PTID to GDB's thread list. Tag it as executing/running
2379 according to RUNNING. */
2380
6b8edb51
PA
2381void
2382remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
c906108c 2383{
b7ea362b 2384 struct remote_state *rs = get_remote_state ();
85ad3aaf 2385 struct thread_info *thread;
b7ea362b
PA
2386
2387 /* GDB historically didn't pull threads in the initial connection
2388 setup. If the remote target doesn't even have a concept of
2389 threads (e.g., a bare-metal target), even if internally we
2390 consider that a single-threaded target, mentioning a new thread
2391 might be confusing to the user. Be silent then, preserving the
2392 age old behavior. */
2393 if (rs->starting_up)
85ad3aaf 2394 thread = add_thread_silent (ptid);
b7ea362b 2395 else
85ad3aaf 2396 thread = add_thread (ptid);
1941c569 2397
7aabaf9d 2398 get_remote_thread_info (thread)->vcont_resumed = executing;
0d5b594f 2399 set_executing (ptid, executing);
1941c569
PA
2400 set_running (ptid, running);
2401}
2402
2403/* Come here when we learn about a thread id from the remote target.
2404 It may be the first time we hear about such thread, so take the
2405 opportunity to add it to GDB's thread list. In case this is the
2406 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2407 GDB's inferior list as well. EXECUTING indicates whether the
2408 thread is (internally) executing or stopped. */
1941c569 2409
6b8edb51
PA
2410void
2411remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 2412{
0d5b594f
PA
2413 /* In non-stop mode, we assume new found threads are (externally)
2414 running until proven otherwise with a stop reply. In all-stop,
2415 we can only get here if all threads are stopped. */
2416 int running = target_is_non_stop_p () ? 1 : 0;
2417
c906108c
SS
2418 /* If this is a new thread, add it to GDB's thread list.
2419 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
2420
2421 if (in_thread_list (currthread) && is_exited (currthread))
2422 {
2423 /* We're seeing an event on a thread id we knew had exited.
2424 This has to be a new thread reusing the old id. Add it. */
0d5b594f 2425 remote_add_thread (currthread, running, executing);
82f73884
PA
2426 return;
2427 }
2428
79d7f229 2429 if (!in_thread_list (currthread))
c0a2216e 2430 {
1941c569 2431 struct inferior *inf = NULL;
bad34192 2432 int pid = ptid_get_pid (currthread);
1941c569 2433
bad34192
PA
2434 if (ptid_is_pid (inferior_ptid)
2435 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
2436 {
2437 /* inferior_ptid has no thread member yet. This can happen
2438 with the vAttach -> remote_wait,"TAAthread:" path if the
2439 stub doesn't support qC. This is the first stop reported
2440 after an attach, so this is the main thread. Update the
2441 ptid in the thread list. */
bad34192
PA
2442 if (in_thread_list (pid_to_ptid (pid)))
2443 thread_change_ptid (inferior_ptid, currthread);
2444 else
2445 {
0d5b594f 2446 remote_add_thread (currthread, running, executing);
bad34192
PA
2447 inferior_ptid = currthread;
2448 }
dc146f7c 2449 return;
c0a2216e 2450 }
82f73884
PA
2451
2452 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
2453 {
2454 /* inferior_ptid is not set yet. This can happen with the
2455 vRun -> remote_wait,"TAAthread:" path if the stub
2456 doesn't support qC. This is the first stop reported
2457 after an attach, so this is the main thread. Update the
2458 ptid in the thread list. */
dc146f7c 2459 thread_change_ptid (inferior_ptid, currthread);
82f73884 2460 return;
c0a2216e 2461 }
82f73884 2462
29c87f7f
PA
2463 /* When connecting to a target remote, or to a target
2464 extended-remote which already was debugging an inferior, we
2465 may not know about it yet. Add it before adding its child
2466 thread, so notifications are emitted in a sensible order. */
2467 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
2468 {
2469 struct remote_state *rs = get_remote_state ();
2470 int fake_pid_p = !remote_multi_process_p (rs);
2471
2472 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 2473 ptid_get_pid (currthread), -1, 1);
49c62f2e 2474 }
29c87f7f 2475
82f73884 2476 /* This is really a new thread. Add it. */
0d5b594f 2477 remote_add_thread (currthread, running, executing);
1941c569
PA
2478
2479 /* If we found a new inferior, let the common code do whatever
2480 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2481 breakpoints), unless we're just setting up an all-stop
2482 connection. */
1941c569 2483 if (inf != NULL)
b7ea362b
PA
2484 {
2485 struct remote_state *rs = get_remote_state ();
2486
6efcd9a8 2487 if (!rs->starting_up)
0d5b594f 2488 notice_new_inferior (currthread, executing, 0);
b7ea362b 2489 }
c0a2216e 2490 }
c906108c
SS
2491}
2492
85ad3aaf 2493/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2494
7aabaf9d
SM
2495static remote_thread_info *
2496get_remote_thread_info (thread_info *thread)
dc146f7c 2497{
85ad3aaf 2498 gdb_assert (thread != NULL);
dc146f7c 2499
85ad3aaf 2500 if (thread->priv == NULL)
7aabaf9d 2501 thread->priv.reset (new remote_thread_info);
dc146f7c 2502
7aabaf9d 2503 return static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2504}
2505
2506/* Return PTID's private thread data, creating it if necessary. */
2507
7aabaf9d
SM
2508static remote_thread_info *
2509get_remote_thread_info (ptid_t ptid)
85ad3aaf
PA
2510{
2511 struct thread_info *info = find_thread_ptid (ptid);
2512
7aabaf9d 2513 return get_remote_thread_info (info);
dc146f7c
VP
2514}
2515
74531fed
PA
2516/* Call this function as a result of
2517 1) A halt indication (T packet) containing a thread id
2518 2) A direct query of currthread
0df8b418 2519 3) Successful execution of set thread */
74531fed
PA
2520
2521static void
47f8a51d 2522record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2523{
47f8a51d 2524 rs->general_thread = currthread;
74531fed
PA
2525}
2526
89be2091
DJ
2527/* If 'QPassSignals' is supported, tell the remote stub what signals
2528 it can simply pass through to the inferior without reporting. */
2529
f6ac5f3d
PA
2530void
2531remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
89be2091 2532{
4082afcc 2533 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2534 {
2535 char *pass_packet, *p;
89be2091 2536 int count = 0, i;
747dc59d 2537 struct remote_state *rs = get_remote_state ();
89be2091
DJ
2538
2539 gdb_assert (numsigs < 256);
2540 for (i = 0; i < numsigs; i++)
2541 {
2455069d 2542 if (pass_signals[i])
89be2091
DJ
2543 count++;
2544 }
224c3ddb 2545 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2546 strcpy (pass_packet, "QPassSignals:");
2547 p = pass_packet + strlen (pass_packet);
2548 for (i = 0; i < numsigs; i++)
2549 {
2455069d 2550 if (pass_signals[i])
89be2091
DJ
2551 {
2552 if (i >= 16)
2553 *p++ = tohex (i >> 4);
2554 *p++ = tohex (i & 15);
2555 if (count)
2556 *p++ = ';';
2557 else
2558 break;
2559 count--;
2560 }
2561 }
2562 *p = 0;
747dc59d 2563 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2564 {
89be2091
DJ
2565 putpkt (pass_packet);
2566 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2567 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2568 if (rs->last_pass_packet)
2569 xfree (rs->last_pass_packet);
2570 rs->last_pass_packet = pass_packet;
89be2091
DJ
2571 }
2572 else
2573 xfree (pass_packet);
2574 }
2575}
2576
82075af2
JS
2577/* If 'QCatchSyscalls' is supported, tell the remote stub
2578 to report syscalls to GDB. */
2579
f6ac5f3d
PA
2580int
2581remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2582 gdb::array_view<const int> syscall_counts)
82075af2 2583{
b80406ac 2584 const char *catch_packet;
82075af2
JS
2585 enum packet_result result;
2586 int n_sysno = 0;
2587
2588 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2589 {
2590 /* Not supported. */
2591 return 1;
2592 }
2593
649a140c 2594 if (needed && any_count == 0)
82075af2 2595 {
649a140c
PA
2596 /* Count how many syscalls are to be caught. */
2597 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2598 {
649a140c 2599 if (syscall_counts[i] != 0)
82075af2
JS
2600 n_sysno++;
2601 }
2602 }
2603
2604 if (remote_debug)
2605 {
2606 fprintf_unfiltered (gdb_stdlog,
2607 "remote_set_syscall_catchpoint "
2608 "pid %d needed %d any_count %d n_sysno %d\n",
2609 pid, needed, any_count, n_sysno);
2610 }
2611
1b81856f 2612 std::string built_packet;
82075af2
JS
2613 if (needed)
2614 {
2615 /* Prepare a packet with the sysno list, assuming max 8+1
2616 characters for a sysno. If the resulting packet size is too
2617 big, fallback on the non-selective packet. */
2618 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2619 built_packet.reserve (maxpktsz);
2620 built_packet = "QCatchSyscalls:1";
649a140c 2621 if (any_count == 0)
82075af2 2622 {
649a140c
PA
2623 /* Add in each syscall to be caught. */
2624 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2625 {
649a140c
PA
2626 if (syscall_counts[i] != 0)
2627 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2628 }
2629 }
1b81856f 2630 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2631 {
2632 /* catch_packet too big. Fallback to less efficient
2633 non selective mode, with GDB doing the filtering. */
b80406ac 2634 catch_packet = "QCatchSyscalls:1";
82075af2 2635 }
b80406ac 2636 else
1b81856f 2637 catch_packet = built_packet.c_str ();
82075af2
JS
2638 }
2639 else
b80406ac 2640 catch_packet = "QCatchSyscalls:0";
82075af2 2641
b80406ac 2642 struct remote_state *rs = get_remote_state ();
82075af2 2643
b80406ac
TT
2644 putpkt (catch_packet);
2645 getpkt (&rs->buf, &rs->buf_size, 0);
2646 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2647 if (result == PACKET_OK)
2648 return 0;
2649 else
2650 return -1;
82075af2
JS
2651}
2652
9b224c5e
PA
2653/* If 'QProgramSignals' is supported, tell the remote stub what
2654 signals it should pass through to the inferior when detaching. */
2655
f6ac5f3d
PA
2656void
2657remote_target::program_signals (int numsigs, unsigned char *signals)
9b224c5e 2658{
4082afcc 2659 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2660 {
2661 char *packet, *p;
2662 int count = 0, i;
5e4a05c4 2663 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2664
2665 gdb_assert (numsigs < 256);
2666 for (i = 0; i < numsigs; i++)
2667 {
2668 if (signals[i])
2669 count++;
2670 }
224c3ddb 2671 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2672 strcpy (packet, "QProgramSignals:");
2673 p = packet + strlen (packet);
2674 for (i = 0; i < numsigs; i++)
2675 {
2676 if (signal_pass_state (i))
2677 {
2678 if (i >= 16)
2679 *p++ = tohex (i >> 4);
2680 *p++ = tohex (i & 15);
2681 if (count)
2682 *p++ = ';';
2683 else
2684 break;
2685 count--;
2686 }
2687 }
2688 *p = 0;
5e4a05c4
TT
2689 if (!rs->last_program_signals_packet
2690 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2691 {
9b224c5e
PA
2692 putpkt (packet);
2693 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2694 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2695 xfree (rs->last_program_signals_packet);
2696 rs->last_program_signals_packet = packet;
9b224c5e
PA
2697 }
2698 else
2699 xfree (packet);
2700 }
2701}
2702
79d7f229
PA
2703/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2704 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2705 thread. If GEN is set, set the general thread, if not, then set
2706 the step/continue thread. */
6b8edb51
PA
2707void
2708remote_target::set_thread (ptid_t ptid, int gen)
c906108c 2709{
d01949b6 2710 struct remote_state *rs = get_remote_state ();
47f8a51d 2711 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2712 char *buf = rs->buf;
79d7f229 2713 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2714
79d7f229 2715 if (ptid_equal (state, ptid))
c906108c
SS
2716 return;
2717
79d7f229
PA
2718 *buf++ = 'H';
2719 *buf++ = gen ? 'g' : 'c';
2720 if (ptid_equal (ptid, magic_null_ptid))
2721 xsnprintf (buf, endbuf - buf, "0");
2722 else if (ptid_equal (ptid, any_thread_ptid))
2723 xsnprintf (buf, endbuf - buf, "0");
2724 else if (ptid_equal (ptid, minus_one_ptid))
2725 xsnprintf (buf, endbuf - buf, "-1");
2726 else
82f73884 2727 write_ptid (buf, endbuf, ptid);
79d7f229 2728 putpkt (rs->buf);
6d820c5c 2729 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2730 if (gen)
47f8a51d 2731 rs->general_thread = ptid;
c906108c 2732 else
47f8a51d 2733 rs->continue_thread = ptid;
c906108c 2734}
79d7f229 2735
6b8edb51
PA
2736void
2737remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
2738{
2739 set_thread (ptid, 1);
2740}
2741
6b8edb51
PA
2742void
2743remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
2744{
2745 set_thread (ptid, 0);
2746}
2747
3c9c4b83
PA
2748/* Change the remote current process. Which thread within the process
2749 ends up selected isn't important, as long as it is the same process
2750 as what INFERIOR_PTID points to.
2751
2752 This comes from that fact that there is no explicit notion of
2753 "selected process" in the protocol. The selected process for
2754 general operations is the process the selected general thread
2755 belongs to. */
2756
6b8edb51
PA
2757void
2758remote_target::set_general_process ()
3c9c4b83
PA
2759{
2760 struct remote_state *rs = get_remote_state ();
2761
2762 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2763 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2764 return;
2765
2766 /* We only need to change the remote current thread if it's pointing
2767 at some other process. */
47f8a51d 2768 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2769 set_general_thread (inferior_ptid);
2770}
2771
c906108c 2772\f
7d1a114c
PA
2773/* Return nonzero if this is the main thread that we made up ourselves
2774 to model non-threaded targets as single-threaded. */
c906108c
SS
2775
2776static int
f6ac5f3d 2777remote_thread_always_alive (ptid_t ptid)
c906108c 2778{
c0a2216e
PA
2779 if (ptid_equal (ptid, magic_null_ptid))
2780 /* The main thread is always alive. */
2781 return 1;
2782
ba348170 2783 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2784 /* The main thread is always alive. This can happen after a
2785 vAttach, if the remote side doesn't support
2786 multi-threading. */
2787 return 1;
2788
7d1a114c
PA
2789 return 0;
2790}
2791
2792/* Return nonzero if the thread PTID is still alive on the remote
2793 system. */
2794
57810aa7 2795bool
f6ac5f3d 2796remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
2797{
2798 struct remote_state *rs = get_remote_state ();
2799 char *p, *endp;
2800
2801 /* Check if this is a thread that we made up ourselves to model
2802 non-threaded targets as single-threaded. */
f6ac5f3d 2803 if (remote_thread_always_alive (ptid))
7d1a114c
PA
2804 return 1;
2805
82f73884
PA
2806 p = rs->buf;
2807 endp = rs->buf + get_remote_packet_size ();
2808
2809 *p++ = 'T';
2810 write_ptid (p, endp, ptid);
2811
2e9f7625 2812 putpkt (rs->buf);
6d820c5c 2813 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2814 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2815}
2816
79efa585
SM
2817/* Return a pointer to a thread name if we know it and NULL otherwise.
2818 The thread_info object owns the memory for the name. */
2819
f6ac5f3d
PA
2820const char *
2821remote_target::thread_name (struct thread_info *info)
79efa585
SM
2822{
2823 if (info->priv != NULL)
a9334058
SM
2824 {
2825 const std::string &name = get_remote_thread_info (info)->name;
2826 return !name.empty () ? name.c_str () : NULL;
2827 }
79efa585
SM
2828
2829 return NULL;
2830}
2831
c906108c
SS
2832/* About these extended threadlist and threadinfo packets. They are
2833 variable length packets but, the fields within them are often fixed
2834 length. They are redundent enough to send over UDP as is the
2835 remote protocol in general. There is a matching unit test module
2836 in libstub. */
2837
23860348 2838/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2839 libstub protocol encoding, and remote.c. It is not particularly
23860348 2840 changable. */
cce74817
JM
2841
2842/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2843 Plan to fix this. */
cce74817 2844
23860348 2845typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2846
9d1f7ab2 2847/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2848 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2849
2850struct gdb_ext_thread_info
c5aa993b 2851 {
23860348 2852 threadref threadid; /* External form of thread reference. */
2bc416ba 2853 int active; /* Has state interesting to GDB?
23860348 2854 regs, stack. */
2bc416ba 2855 char display[256]; /* Brief state display, name,
cedea757 2856 blocked/suspended. */
23860348 2857 char shortname[32]; /* To be used to name threads. */
2bc416ba 2858 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2859 whatever. */
c5aa993b 2860 };
cce74817
JM
2861
2862/* The volume of remote transfers can be limited by submitting
2863 a mask containing bits specifying the desired information.
2864 Use a union of these values as the 'selection' parameter to
0df8b418 2865 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2866
2867#define TAG_THREADID 1
2868#define TAG_EXISTS 2
2869#define TAG_DISPLAY 4
2870#define TAG_THREADNAME 8
c5aa993b 2871#define TAG_MOREDISPLAY 16
cce74817 2872
23860348 2873#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2874
a14ed312 2875static char *unpack_nibble (char *buf, int *val);
cce74817 2876
a14ed312 2877static char *unpack_byte (char *buf, int *value);
cce74817 2878
a14ed312 2879static char *pack_int (char *buf, int value);
cce74817 2880
a14ed312 2881static char *unpack_int (char *buf, int *value);
cce74817 2882
a14ed312 2883static char *unpack_string (char *src, char *dest, int length);
cce74817 2884
23860348 2885static char *pack_threadid (char *pkt, threadref *id);
cce74817 2886
23860348 2887static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2888
23860348 2889void int_to_threadref (threadref *id, int value);
cce74817 2890
23860348 2891static int threadref_to_int (threadref *ref);
cce74817 2892
23860348 2893static void copy_threadref (threadref *dest, threadref *src);
cce74817 2894
23860348 2895static int threadmatch (threadref *dest, threadref *src);
cce74817 2896
2bc416ba 2897static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2898 threadref *id);
cce74817 2899
a14ed312
KB
2900static char *pack_threadlist_request (char *pkt, int startflag,
2901 int threadcount,
23860348 2902 threadref *nextthread);
cce74817 2903
23860348 2904static int remote_newthread_step (threadref *ref, void *context);
cce74817 2905
82f73884
PA
2906
2907/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2908 buffer we're allowed to write to. Returns
2909 BUF+CHARACTERS_WRITTEN. */
2910
6b8edb51
PA
2911char *
2912remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
2913{
2914 int pid, tid;
2915 struct remote_state *rs = get_remote_state ();
2916
2917 if (remote_multi_process_p (rs))
2918 {
2919 pid = ptid_get_pid (ptid);
2920 if (pid < 0)
2921 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2922 else
2923 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2924 }
ba348170 2925 tid = ptid_get_lwp (ptid);
82f73884
PA
2926 if (tid < 0)
2927 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2928 else
2929 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2930
2931 return buf;
2932}
2933
256642e8
PA
2934/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2935 last parsed char. Returns null_ptid if no thread id is found, and
2936 throws an error if the thread id has an invalid format. */
82f73884
PA
2937
2938static ptid_t
256642e8 2939read_ptid (const char *buf, const char **obuf)
82f73884 2940{
256642e8
PA
2941 const char *p = buf;
2942 const char *pp;
82f73884 2943 ULONGEST pid = 0, tid = 0;
82f73884
PA
2944
2945 if (*p == 'p')
2946 {
2947 /* Multi-process ptid. */
2948 pp = unpack_varlen_hex (p + 1, &pid);
2949 if (*pp != '.')
b37520b6 2950 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2951
2952 p = pp;
2953 pp = unpack_varlen_hex (p + 1, &tid);
2954 if (obuf)
2955 *obuf = pp;
ba348170 2956 return ptid_build (pid, tid, 0);
82f73884
PA
2957 }
2958
2959 /* No multi-process. Just a tid. */
2960 pp = unpack_varlen_hex (p, &tid);
2961
c9f35b34
KB
2962 /* Return null_ptid when no thread id is found. */
2963 if (p == pp)
2964 {
2965 if (obuf)
2966 *obuf = pp;
2967 return null_ptid;
2968 }
2969
82f73884 2970 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2971 what's in inferior_ptid, unless it's null at this point. If so,
2972 then since there's no way to know the pid of the reported
2973 threads, use the magic number. */
2974 if (ptid_equal (inferior_ptid, null_ptid))
2975 pid = ptid_get_pid (magic_null_ptid);
2976 else
2977 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2978
2979 if (obuf)
2980 *obuf = pp;
ba348170 2981 return ptid_build (pid, tid, 0);
82f73884
PA
2982}
2983
c906108c 2984static int
fba45db2 2985stubhex (int ch)
c906108c
SS
2986{
2987 if (ch >= 'a' && ch <= 'f')
2988 return ch - 'a' + 10;
2989 if (ch >= '0' && ch <= '9')
2990 return ch - '0';
2991 if (ch >= 'A' && ch <= 'F')
2992 return ch - 'A' + 10;
2993 return -1;
2994}
2995
2996static int
fba45db2 2997stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2998{
2999 int nibble;
3000 int retval = 0;
3001
3002 while (fieldlength)
3003 {
3004 nibble = stubhex (*buff++);
3005 retval |= nibble;
3006 fieldlength--;
3007 if (fieldlength)
3008 retval = retval << 4;
3009 }
3010 return retval;
3011}
3012
c906108c 3013static char *
fba45db2 3014unpack_nibble (char *buf, int *val)
c906108c 3015{
b7589f7d 3016 *val = fromhex (*buf++);
c906108c
SS
3017 return buf;
3018}
3019
c906108c 3020static char *
fba45db2 3021unpack_byte (char *buf, int *value)
c906108c
SS
3022{
3023 *value = stub_unpack_int (buf, 2);
3024 return buf + 2;
3025}
3026
3027static char *
fba45db2 3028pack_int (char *buf, int value)
c906108c
SS
3029{
3030 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3031 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3032 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3033 buf = pack_hex_byte (buf, (value & 0xff));
3034 return buf;
3035}
3036
3037static char *
fba45db2 3038unpack_int (char *buf, int *value)
c906108c
SS
3039{
3040 *value = stub_unpack_int (buf, 8);
3041 return buf + 8;
3042}
3043
23860348 3044#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3045static char *pack_string (char *pkt, char *string);
c906108c
SS
3046
3047static char *
fba45db2 3048pack_string (char *pkt, char *string)
c906108c
SS
3049{
3050 char ch;
3051 int len;
3052
3053 len = strlen (string);
3054 if (len > 200)
23860348 3055 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3056 pkt = pack_hex_byte (pkt, len);
3057 while (len-- > 0)
3058 {
3059 ch = *string++;
3060 if ((ch == '\0') || (ch == '#'))
23860348 3061 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3062 *pkt++ = ch;
3063 }
3064 return pkt;
3065}
3066#endif /* 0 (unused) */
3067
3068static char *
fba45db2 3069unpack_string (char *src, char *dest, int length)
c906108c
SS
3070{
3071 while (length--)
3072 *dest++ = *src++;
3073 *dest = '\0';
3074 return src;
3075}
3076
3077static char *
fba45db2 3078pack_threadid (char *pkt, threadref *id)
c906108c
SS
3079{
3080 char *limit;
3081 unsigned char *altid;
3082
3083 altid = (unsigned char *) id;
3084 limit = pkt + BUF_THREAD_ID_SIZE;
3085 while (pkt < limit)
3086 pkt = pack_hex_byte (pkt, *altid++);
3087 return pkt;
3088}
3089
3090
3091static char *
fba45db2 3092unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
3093{
3094 char *altref;
3095 char *limit = inbuf + BUF_THREAD_ID_SIZE;
3096 int x, y;
3097
3098 altref = (char *) id;
3099
3100 while (inbuf < limit)
3101 {
3102 x = stubhex (*inbuf++);
3103 y = stubhex (*inbuf++);
3104 *altref++ = (x << 4) | y;
3105 }
3106 return inbuf;
3107}
3108
3109/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3110 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3111 to use 64bit thread references internally. This is an adapter
3112 function. */
3113
3114void
fba45db2 3115int_to_threadref (threadref *id, int value)
c906108c
SS
3116{
3117 unsigned char *scan;
3118
3119 scan = (unsigned char *) id;
3120 {
3121 int i = 4;
3122 while (i--)
3123 *scan++ = 0;
3124 }
3125 *scan++ = (value >> 24) & 0xff;
3126 *scan++ = (value >> 16) & 0xff;
3127 *scan++ = (value >> 8) & 0xff;
3128 *scan++ = (value & 0xff);
3129}
3130
3131static int
fba45db2 3132threadref_to_int (threadref *ref)
c906108c
SS
3133{
3134 int i, value = 0;
3135 unsigned char *scan;
3136
cfd77fa1 3137 scan = *ref;
c906108c
SS
3138 scan += 4;
3139 i = 4;
3140 while (i-- > 0)
3141 value = (value << 8) | ((*scan++) & 0xff);
3142 return value;
3143}
3144
3145static void
fba45db2 3146copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3147{
3148 int i;
3149 unsigned char *csrc, *cdest;
3150
3151 csrc = (unsigned char *) src;
3152 cdest = (unsigned char *) dest;
3153 i = 8;
3154 while (i--)
3155 *cdest++ = *csrc++;
3156}
3157
3158static int
fba45db2 3159threadmatch (threadref *dest, threadref *src)
c906108c 3160{
23860348 3161 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3162#if 0
3163 unsigned char *srcp, *destp;
3164 int i, result;
3165 srcp = (char *) src;
3166 destp = (char *) dest;
3167
3168 result = 1;
3169 while (i-- > 0)
3170 result &= (*srcp++ == *destp++) ? 1 : 0;
3171 return result;
3172#endif
3173 return 1;
3174}
3175
3176/*
c5aa993b
JM
3177 threadid:1, # always request threadid
3178 context_exists:2,
3179 display:4,
3180 unique_name:8,
3181 more_display:16
3182 */
c906108c
SS
3183
3184/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3185
3186static char *
fba45db2 3187pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3188{
23860348
MS
3189 *pkt++ = 'q'; /* Info Query */
3190 *pkt++ = 'P'; /* process or thread info */
3191 pkt = pack_int (pkt, mode); /* mode */
c906108c 3192 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3193 *pkt = '\0'; /* terminate */
c906108c
SS
3194 return pkt;
3195}
3196
23860348 3197/* These values tag the fields in a thread info response packet. */
c906108c 3198/* Tagging the fields allows us to request specific fields and to
23860348 3199 add more fields as time goes by. */
c906108c 3200
23860348 3201#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3202#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3203 fetch registers and its stack? */
c5aa993b 3204#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3205#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3206#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3207 the process. */
c906108c 3208
6b8edb51
PA
3209int
3210remote_target::remote_unpack_thread_info_response (char *pkt,
3211 threadref *expectedref,
3212 gdb_ext_thread_info *info)
c906108c 3213{
d01949b6 3214 struct remote_state *rs = get_remote_state ();
c906108c 3215 int mask, length;
cfd77fa1 3216 int tag;
c906108c 3217 threadref ref;
6d820c5c 3218 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
3219 int retval = 1;
3220
23860348 3221 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3222 info->active = 0;
3223 info->display[0] = '\0';
3224 info->shortname[0] = '\0';
3225 info->more_display[0] = '\0';
3226
23860348
MS
3227 /* Assume the characters indicating the packet type have been
3228 stripped. */
c906108c
SS
3229 pkt = unpack_int (pkt, &mask); /* arg mask */
3230 pkt = unpack_threadid (pkt, &ref);
3231
3232 if (mask == 0)
8a3fe4f8 3233 warning (_("Incomplete response to threadinfo request."));
c906108c 3234 if (!threadmatch (&ref, expectedref))
23860348 3235 { /* This is an answer to a different request. */
8a3fe4f8 3236 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3237 return 0;
3238 }
3239 copy_threadref (&info->threadid, &ref);
3240
23860348 3241 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 3242
23860348
MS
3243 /* Packets are terminated with nulls. */
3244 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3245 {
3246 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3247 pkt = unpack_byte (pkt, &length); /* length */
3248 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3249 {
8a3fe4f8 3250 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3251 retval = 0;
3252 break;
3253 }
3254 if (tag == TAG_THREADID)
3255 {
3256 if (length != 16)
3257 {
8a3fe4f8 3258 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3259 retval = 0;
3260 break;
3261 }
3262 pkt = unpack_threadid (pkt, &ref);
3263 mask = mask & ~TAG_THREADID;
3264 continue;
3265 }
3266 if (tag == TAG_EXISTS)
3267 {
3268 info->active = stub_unpack_int (pkt, length);
3269 pkt += length;
3270 mask = mask & ~(TAG_EXISTS);
3271 if (length > 8)
3272 {
8a3fe4f8 3273 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3274 retval = 0;
3275 break;
3276 }
3277 continue;
3278 }
3279 if (tag == TAG_THREADNAME)
3280 {
3281 pkt = unpack_string (pkt, &info->shortname[0], length);
3282 mask = mask & ~TAG_THREADNAME;
3283 continue;
3284 }
3285 if (tag == TAG_DISPLAY)
3286 {
3287 pkt = unpack_string (pkt, &info->display[0], length);
3288 mask = mask & ~TAG_DISPLAY;
3289 continue;
3290 }
3291 if (tag == TAG_MOREDISPLAY)
3292 {
3293 pkt = unpack_string (pkt, &info->more_display[0], length);
3294 mask = mask & ~TAG_MOREDISPLAY;
3295 continue;
3296 }
8a3fe4f8 3297 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3298 break; /* Not a tag we know about. */
c906108c
SS
3299 }
3300 return retval;
3301}
3302
6b8edb51
PA
3303int
3304remote_target::remote_get_threadinfo (threadref *threadid,
3305 int fieldset,
3306 gdb_ext_thread_info *info)
c906108c 3307{
d01949b6 3308 struct remote_state *rs = get_remote_state ();
c906108c 3309 int result;
c906108c 3310
2e9f7625
DJ
3311 pack_threadinfo_request (rs->buf, fieldset, threadid);
3312 putpkt (rs->buf);
6d820c5c 3313 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
3314
3315 if (rs->buf[0] == '\0')
3316 return 0;
3317
2e9f7625 3318 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 3319 threadid, info);
c906108c
SS
3320 return result;
3321}
3322
c906108c
SS
3323/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3324
3325static char *
fba45db2
KB
3326pack_threadlist_request (char *pkt, int startflag, int threadcount,
3327 threadref *nextthread)
c906108c
SS
3328{
3329 *pkt++ = 'q'; /* info query packet */
3330 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3331 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3332 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3333 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3334 *pkt = '\0';
3335 return pkt;
3336}
3337
3338/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3339
6b8edb51
PA
3340int
3341remote_target::parse_threadlist_response (char *pkt, int result_limit,
3342 threadref *original_echo,
3343 threadref *resultlist,
3344 int *doneflag)
c906108c 3345{
d01949b6 3346 struct remote_state *rs = get_remote_state ();
c906108c
SS
3347 char *limit;
3348 int count, resultcount, done;
3349
3350 resultcount = 0;
3351 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 3352 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 3353 /* done parse past here */
c906108c
SS
3354 pkt = unpack_byte (pkt, &count); /* count field */
3355 pkt = unpack_nibble (pkt, &done);
3356 /* The first threadid is the argument threadid. */
3357 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3358 while ((count-- > 0) && (pkt < limit))
3359 {
3360 pkt = unpack_threadid (pkt, resultlist++);
3361 if (resultcount++ >= result_limit)
3362 break;
3363 }
3364 if (doneflag)
3365 *doneflag = done;
3366 return resultcount;
3367}
3368
6dc54d91
PA
3369/* Fetch the next batch of threads from the remote. Returns -1 if the
3370 qL packet is not supported, 0 on error and 1 on success. */
3371
6b8edb51
PA
3372int
3373remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3374 int result_limit, int *done, int *result_count,
3375 threadref *threadlist)
c906108c 3376{
d01949b6 3377 struct remote_state *rs = get_remote_state ();
c906108c
SS
3378 int result = 1;
3379
23860348 3380 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
3381 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3382 >= get_remote_packet_size ())
ea9c271d 3383 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3384
6d820c5c
DJ
3385 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3386 putpkt (rs->buf);
3387 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 3388 if (*rs->buf == '\0')
6dc54d91
PA
3389 {
3390 /* Packet not supported. */
3391 return -1;
3392 }
3393
3394 *result_count =
3395 parse_threadlist_response (rs->buf + 2, result_limit,
3396 &rs->echo_nextthread, threadlist, done);
c906108c 3397
0d031856 3398 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3399 {
23860348
MS
3400 /* FIXME: This is a good reason to drop the packet. */
3401 /* Possably, there is a duplicate response. */
c906108c
SS
3402 /* Possabilities :
3403 retransmit immediatly - race conditions
3404 retransmit after timeout - yes
3405 exit
3406 wait for packet, then exit
3407 */
8a3fe4f8 3408 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3409 return 0; /* I choose simply exiting. */
c906108c
SS
3410 }
3411 if (*result_count <= 0)
3412 {
3413 if (*done != 1)
3414 {
8a3fe4f8 3415 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3416 result = 0;
3417 }
3418 return result; /* break; */
3419 }
3420 if (*result_count > result_limit)
3421 {
3422 *result_count = 0;
8a3fe4f8 3423 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3424 return 0;
3425 }
3426 return result;
3427}
3428
6dc54d91
PA
3429/* Fetch the list of remote threads, with the qL packet, and call
3430 STEPFUNCTION for each thread found. Stops iterating and returns 1
3431 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3432 STEPFUNCTION returns false. If the packet is not supported,
3433 returns -1. */
c906108c 3434
6b8edb51
PA
3435int
3436remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3437 void *context, int looplimit)
c906108c 3438{
0d031856 3439 struct remote_state *rs = get_remote_state ();
c906108c
SS
3440 int done, i, result_count;
3441 int startflag = 1;
3442 int result = 1;
3443 int loopcount = 0;
c906108c
SS
3444
3445 done = 0;
3446 while (!done)
3447 {
3448 if (loopcount++ > looplimit)
3449 {
3450 result = 0;
8a3fe4f8 3451 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3452 break;
3453 }
6dc54d91
PA
3454 result = remote_get_threadlist (startflag, &rs->nextthread,
3455 MAXTHREADLISTRESULTS,
3456 &done, &result_count,
3457 rs->resultthreadlist);
3458 if (result <= 0)
3459 break;
23860348 3460 /* Clear for later iterations. */
c906108c
SS
3461 startflag = 0;
3462 /* Setup to resume next batch of thread references, set nextthread. */
3463 if (result_count >= 1)
0d031856
TT
3464 copy_threadref (&rs->nextthread,
3465 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3466 i = 0;
3467 while (result_count--)
6dc54d91
PA
3468 {
3469 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3470 {
3471 result = 0;
3472 break;
3473 }
3474 }
c906108c
SS
3475 }
3476 return result;
3477}
3478
6dc54d91
PA
3479/* A thread found on the remote target. */
3480
21fe1c75 3481struct thread_item
6dc54d91 3482{
21fe1c75
SM
3483 explicit thread_item (ptid_t ptid_)
3484 : ptid (ptid_)
3485 {}
3486
3487 thread_item (thread_item &&other) = default;
3488 thread_item &operator= (thread_item &&other) = default;
3489
3490 DISABLE_COPY_AND_ASSIGN (thread_item);
3491
6dc54d91
PA
3492 /* The thread's PTID. */
3493 ptid_t ptid;
3494
21fe1c75
SM
3495 /* The thread's extra info. */
3496 std::string extra;
6dc54d91 3497
21fe1c75
SM
3498 /* The thread's name. */
3499 std::string name;
79efa585 3500
6dc54d91 3501 /* The core the thread was running on. -1 if not known. */
21fe1c75 3502 int core = -1;
f6327dcb
KB
3503
3504 /* The thread handle associated with the thread. */
21fe1c75 3505 gdb::byte_vector thread_handle;
21fe1c75 3506};
6dc54d91
PA
3507
3508/* Context passed around to the various methods listing remote
3509 threads. As new threads are found, they're added to the ITEMS
3510 vector. */
3511
3512struct threads_listing_context
3513{
21fe1c75
SM
3514 /* Return true if this object contains an entry for a thread with ptid
3515 PTID. */
6dc54d91 3516
21fe1c75
SM
3517 bool contains_thread (ptid_t ptid) const
3518 {
3519 auto match_ptid = [&] (const thread_item &item)
3520 {
3521 return item.ptid == ptid;
3522 };
80134cf5 3523
21fe1c75
SM
3524 auto it = std::find_if (this->items.begin (),
3525 this->items.end (),
3526 match_ptid);
80134cf5 3527
21fe1c75
SM
3528 return it != this->items.end ();
3529 }
80134cf5 3530
21fe1c75 3531 /* Remove the thread with ptid PTID. */
80134cf5 3532
21fe1c75
SM
3533 void remove_thread (ptid_t ptid)
3534 {
3535 auto match_ptid = [&] (const thread_item &item)
3536 {
3537 return item.ptid == ptid;
3538 };
cbb8991c 3539
21fe1c75
SM
3540 auto it = std::remove_if (this->items.begin (),
3541 this->items.end (),
3542 match_ptid);
cbb8991c 3543
21fe1c75
SM
3544 if (it != this->items.end ())
3545 this->items.erase (it);
3546 }
3547
3548 /* The threads found on the remote target. */
3549 std::vector<thread_item> items;
3550};
cbb8991c 3551
c906108c 3552static int
6dc54d91 3553remote_newthread_step (threadref *ref, void *data)
c906108c 3554{
19ba03f4
SM
3555 struct threads_listing_context *context
3556 = (struct threads_listing_context *) data;
21fe1c75
SM
3557 int pid = inferior_ptid.pid ();
3558 int lwp = threadref_to_int (ref);
3559 ptid_t ptid (pid, lwp);
6dc54d91 3560
21fe1c75 3561 context->items.emplace_back (ptid);
6dc54d91 3562
c906108c
SS
3563 return 1; /* continue iterator */
3564}
3565
3566#define CRAZY_MAX_THREADS 1000
3567
6b8edb51
PA
3568ptid_t
3569remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3570{
d01949b6 3571 struct remote_state *rs = get_remote_state ();
c906108c
SS
3572
3573 putpkt ("qC");
6d820c5c 3574 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3575 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3576 {
256642e8 3577 const char *obuf;
c9f35b34
KB
3578 ptid_t result;
3579
3580 result = read_ptid (&rs->buf[2], &obuf);
3581 if (*obuf != '\0' && remote_debug)
3582 fprintf_unfiltered (gdb_stdlog,
3583 "warning: garbage in qC reply\n");
3584
3585 return result;
3586 }
c906108c
SS
3587 else
3588 return oldpid;
3589}
3590
6dc54d91 3591/* List remote threads using the deprecated qL packet. */
cce74817 3592
6b8edb51
PA
3593int
3594remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3595{
6dc54d91
PA
3596 if (remote_threadlist_iterator (remote_newthread_step, context,
3597 CRAZY_MAX_THREADS) >= 0)
3598 return 1;
3599
3600 return 0;
c906108c
SS
3601}
3602
dc146f7c
VP
3603#if defined(HAVE_LIBEXPAT)
3604
dc146f7c
VP
3605static void
3606start_thread (struct gdb_xml_parser *parser,
3607 const struct gdb_xml_element *element,
4d0fdd9b
SM
3608 void *user_data,
3609 std::vector<gdb_xml_value> &attributes)
dc146f7c 3610{
19ba03f4
SM
3611 struct threads_listing_context *data
3612 = (struct threads_listing_context *) user_data;
3d2c1d41 3613 struct gdb_xml_value *attr;
dc146f7c 3614
4d0fdd9b 3615 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3616 ptid_t ptid = read_ptid (id, NULL);
3617
3618 data->items.emplace_back (ptid);
3619 thread_item &item = data->items.back ();
dc146f7c 3620
3d2c1d41
PA
3621 attr = xml_find_attribute (attributes, "core");
3622 if (attr != NULL)
4d0fdd9b 3623 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3624
79efa585 3625 attr = xml_find_attribute (attributes, "name");
21fe1c75 3626 if (attr != NULL)
4d0fdd9b 3627 item.name = (const char *) attr->value.get ();
79efa585 3628
f6327dcb
KB
3629 attr = xml_find_attribute (attributes, "handle");
3630 if (attr != NULL)
4d0fdd9b 3631 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3632}
3633
3634static void
3635end_thread (struct gdb_xml_parser *parser,
3636 const struct gdb_xml_element *element,
3637 void *user_data, const char *body_text)
3638{
19ba03f4
SM
3639 struct threads_listing_context *data
3640 = (struct threads_listing_context *) user_data;
dc146f7c 3641
21fe1c75
SM
3642 if (body_text != NULL && *body_text != '\0')
3643 data->items.back ().extra = body_text;
dc146f7c
VP
3644}
3645
3646const struct gdb_xml_attribute thread_attributes[] = {
3647 { "id", GDB_XML_AF_NONE, NULL, NULL },
3648 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3649 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3650 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3651 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3652};
3653
3654const struct gdb_xml_element thread_children[] = {
3655 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3656};
3657
3658const struct gdb_xml_element threads_children[] = {
3659 { "thread", thread_attributes, thread_children,
3660 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3661 start_thread, end_thread },
3662 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3663};
3664
3665const struct gdb_xml_element threads_elements[] = {
3666 { "threads", NULL, threads_children,
3667 GDB_XML_EF_NONE, NULL, NULL },
3668 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3669};
3670
3671#endif
3672
6dc54d91 3673/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3674
6b8edb51
PA
3675int
3676remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 3677{
dc146f7c 3678#if defined(HAVE_LIBEXPAT)
4082afcc 3679 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3680 {
9018be22 3681 gdb::optional<gdb::char_vector> xml
6b8edb51 3682 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3683
9018be22 3684 if (xml && (*xml)[0] != '\0')
dc146f7c 3685 {
6dc54d91 3686 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3687 threads_elements, xml->data (), context);
dc146f7c
VP
3688 }
3689
6dc54d91 3690 return 1;
dc146f7c
VP
3691 }
3692#endif
3693
6dc54d91
PA
3694 return 0;
3695}
3696
3697/* List remote threads using qfThreadInfo/qsThreadInfo. */
3698
6b8edb51
PA
3699int
3700remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
3701{
3702 struct remote_state *rs = get_remote_state ();
3703
b80fafe3 3704 if (rs->use_threadinfo_query)
9d1f7ab2 3705 {
256642e8 3706 const char *bufp;
6dc54d91 3707
9d1f7ab2 3708 putpkt ("qfThreadInfo");
6d820c5c 3709 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3710 bufp = rs->buf;
9d1f7ab2 3711 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3712 {
9d1f7ab2
MS
3713 while (*bufp++ == 'm') /* reply contains one or more TID */
3714 {
3715 do
3716 {
21fe1c75
SM
3717 ptid_t ptid = read_ptid (bufp, &bufp);
3718 context->items.emplace_back (ptid);
9d1f7ab2
MS
3719 }
3720 while (*bufp++ == ','); /* comma-separated list */
3721 putpkt ("qsThreadInfo");
6d820c5c 3722 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3723 bufp = rs->buf;
9d1f7ab2 3724 }
6dc54d91
PA
3725 return 1;
3726 }
3727 else
3728 {
3729 /* Packet not recognized. */
3730 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3731 }
3732 }
3733
6dc54d91
PA
3734 return 0;
3735}
3736
e8032dde 3737/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3738 targets. */
3739
f6ac5f3d
PA
3740void
3741remote_target::update_thread_list ()
6dc54d91 3742{
6dc54d91 3743 struct threads_listing_context context;
ab970af1 3744 int got_list = 0;
e8032dde 3745
6dc54d91
PA
3746 /* We have a few different mechanisms to fetch the thread list. Try
3747 them all, starting with the most preferred one first, falling
3748 back to older methods. */
6b8edb51
PA
3749 if (remote_get_threads_with_qxfer (&context)
3750 || remote_get_threads_with_qthreadinfo (&context)
3751 || remote_get_threads_with_ql (&context))
6dc54d91 3752 {
ab970af1
PA
3753 struct thread_info *tp, *tmp;
3754
3755 got_list = 1;
3756
21fe1c75 3757 if (context.items.empty ()
f6ac5f3d 3758 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
3759 {
3760 /* Some targets don't really support threads, but still
3761 reply an (empty) thread list in response to the thread
3762 listing packets, instead of replying "packet not
3763 supported". Exit early so we don't delete the main
3764 thread. */
7d1a114c
PA
3765 return;
3766 }
3767
ab970af1
PA
3768 /* CONTEXT now holds the current thread list on the remote
3769 target end. Delete GDB-side threads no longer found on the
3770 target. */
8a06aea7 3771 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3772 {
21fe1c75 3773 if (!context.contains_thread (tp->ptid))
ab970af1
PA
3774 {
3775 /* Not found. */
3776 delete_thread (tp->ptid);
3777 }
cbb8991c
DB
3778 }
3779
3780 /* Remove any unreported fork child threads from CONTEXT so
3781 that we don't interfere with follow fork, which is where
3782 creation of such threads is handled. */
3783 remove_new_fork_children (&context);
74531fed 3784
ab970af1 3785 /* And now add threads we don't know about yet to our list. */
21fe1c75 3786 for (thread_item &item : context.items)
6dc54d91 3787 {
21fe1c75 3788 if (item.ptid != null_ptid)
6dc54d91 3789 {
6dc54d91 3790 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3791 executing until proven otherwise with a stop reply.
3792 In all-stop, we can only get here if all threads are
6dc54d91 3793 stopped. */
0d5b594f 3794 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3795
21fe1c75 3796 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 3797
7aabaf9d 3798 remote_thread_info *info = get_remote_thread_info (item.ptid);
21fe1c75 3799 info->core = item.core;
7aabaf9d
SM
3800 info->extra = std::move (item.extra);
3801 info->name = std::move (item.name);
3802 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
3803 }
3804 }
3805 }
3806
ab970af1
PA
3807 if (!got_list)
3808 {
3809 /* If no thread listing method is supported, then query whether
3810 each known thread is alive, one by one, with the T packet.
3811 If the target doesn't support threads at all, then this is a
3812 no-op. See remote_thread_alive. */
3813 prune_threads ();
3814 }
9d1f7ab2
MS
3815}
3816
802188a7 3817/*
9d1f7ab2
MS
3818 * Collect a descriptive string about the given thread.
3819 * The target may say anything it wants to about the thread
3820 * (typically info about its blocked / runnable state, name, etc.).
3821 * This string will appear in the info threads display.
802188a7 3822 *
9d1f7ab2
MS
3823 * Optional: targets are not required to implement this function.
3824 */
3825
f6ac5f3d
PA
3826const char *
3827remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 3828{
d01949b6 3829 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3830 int result;
3831 int set;
3832 threadref id;
3833 struct gdb_ext_thread_info threadinfo;
23860348 3834 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3835 int n = 0; /* position in display_buf */
3836
5d93a237 3837 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3838 internal_error (__FILE__, __LINE__,
e2e0b3e5 3839 _("remote_threads_extra_info"));
9d1f7ab2 3840
60e569b9 3841 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3842 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3843 /* This is the main thread which was added by GDB. The remote
3844 server doesn't know about it. */
3845 return NULL;
3846
4082afcc 3847 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3848 {
3849 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3850
7aabaf9d 3851 if (info != NULL && info->priv != NULL)
a9334058
SM
3852 {
3853 const std::string &extra = get_remote_thread_info (info)->extra;
3854 return !extra.empty () ? extra.c_str () : NULL;
3855 }
dc146f7c
VP
3856 else
3857 return NULL;
3858 }
3859
b80fafe3 3860 if (rs->use_threadextra_query)
9d1f7ab2 3861 {
82f73884
PA
3862 char *b = rs->buf;
3863 char *endb = rs->buf + get_remote_packet_size ();
3864
3865 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3866 b += strlen (b);
3867 write_ptid (b, endb, tp->ptid);
3868
2e9f7625 3869 putpkt (rs->buf);
6d820c5c 3870 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3871 if (rs->buf[0] != 0)
9d1f7ab2 3872 {
325fac50 3873 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
2e9f7625 3874 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3875 display_buf [result] = '\0';
9d1f7ab2
MS
3876 return display_buf;
3877 }
0f71a2f6 3878 }
9d1f7ab2
MS
3879
3880 /* If the above query fails, fall back to the old method. */
b80fafe3 3881 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3882 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3883 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3884 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3885 if (remote_get_threadinfo (&id, set, &threadinfo))
3886 if (threadinfo.active)
0f71a2f6 3887 {
9d1f7ab2 3888 if (*threadinfo.shortname)
2bc416ba 3889 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3890 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3891 if (*threadinfo.display)
2bc416ba 3892 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3893 " State: %s,", threadinfo.display);
9d1f7ab2 3894 if (*threadinfo.more_display)
2bc416ba 3895 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3896 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3897
3898 if (n > 0)
c5aa993b 3899 {
23860348 3900 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3901 if (',' == display_buf[n-1])
3902 display_buf[n-1] = ' ';
3903 return display_buf;
c5aa993b 3904 }
0f71a2f6 3905 }
9d1f7ab2 3906 return NULL;
0f71a2f6 3907}
c906108c 3908\f
c5aa993b 3909
f6ac5f3d
PA
3910bool
3911remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3912 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
3913{
3914 struct remote_state *rs = get_remote_state ();
3915 char *p = rs->buf;
3916
bba74b36 3917 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3918 p += strlen (p);
3919 p += hexnumstr (p, addr);
3920 putpkt (rs->buf);
3921 getpkt (&rs->buf, &rs->buf_size, 0);
3922 p = rs->buf;
3923
3924 if (*p == 'E')
3925 error (_("Remote failure reply: %s"), p);
3926
3927 if (*p++ == 'm')
3928 {
256642e8 3929 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 3930 return true;
0fb4aa4b
PA
3931 }
3932
5d9310c4 3933 return false;
0fb4aa4b
PA
3934}
3935
f6ac5f3d
PA
3936std::vector<static_tracepoint_marker>
3937remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
3938{
3939 struct remote_state *rs = get_remote_state ();
5d9310c4 3940 std::vector<static_tracepoint_marker> markers;
256642e8 3941 const char *p;
5d9310c4 3942 static_tracepoint_marker marker;
0fb4aa4b
PA
3943
3944 /* Ask for a first packet of static tracepoint marker
3945 definition. */
3946 putpkt ("qTfSTM");
3947 getpkt (&rs->buf, &rs->buf_size, 0);
3948 p = rs->buf;
3949 if (*p == 'E')
3950 error (_("Remote failure reply: %s"), p);
3951
0fb4aa4b
PA
3952 while (*p++ == 'm')
3953 {
0fb4aa4b
PA
3954 do
3955 {
5d9310c4 3956 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 3957
5d9310c4
SM
3958 if (strid == NULL || marker.str_id == strid)
3959 markers.push_back (std::move (marker));
0fb4aa4b
PA
3960 }
3961 while (*p++ == ','); /* comma-separated list */
3962 /* Ask for another packet of static tracepoint definition. */
3963 putpkt ("qTsSTM");
3964 getpkt (&rs->buf, &rs->buf_size, 0);
3965 p = rs->buf;
3966 }
3967
0fb4aa4b
PA
3968 return markers;
3969}
3970
3971\f
10760264
JB
3972/* Implement the to_get_ada_task_ptid function for the remote targets. */
3973
f6ac5f3d
PA
3974ptid_t
3975remote_target::get_ada_task_ptid (long lwp, long thread)
10760264 3976{
ba348170 3977 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3978}
3979\f
3980
24b06219 3981/* Restart the remote side; this is an extended protocol operation. */
c906108c 3982
6b8edb51
PA
3983void
3984remote_target::extended_remote_restart ()
c906108c 3985{
d01949b6 3986 struct remote_state *rs = get_remote_state ();
c906108c
SS
3987
3988 /* Send the restart command; for reasons I don't understand the
3989 remote side really expects a number after the "R". */
ea9c271d 3990 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3991 putpkt (rs->buf);
c906108c 3992
ad9a8f3f 3993 remote_fileio_reset ();
c906108c
SS
3994}
3995\f
3996/* Clean up connection to a remote debugger. */
3997
f6ac5f3d
PA
3998void
3999remote_target::close ()
c906108c 4000{
048094ac 4001 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4002 terminal_ours ();
ce5ce7ed 4003
ce5ce7ed 4004 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
4005 of all the inferiors and their threads we were controlling.
4006 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4007 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 4008 inferior_ptid = null_ptid;
f67fd822 4009 discard_all_inferiors ();
ce5ce7ed 4010
6b8edb51
PA
4011 trace_reset_local_state ();
4012
4013 delete this;
4014}
4015
4016remote_target::~remote_target ()
4017{
4018 struct remote_state *rs = get_remote_state ();
4019
4020 /* Check for NULL because we may get here with a partially
4021 constructed target/connection. */
4022 if (rs->remote_desc == nullptr)
4023 return;
4024
4025 serial_close (rs->remote_desc);
4026
4027 /* We are destroying the remote target, so we should discard
f48ff2a7 4028 everything of this target. */
6b8edb51 4029 discard_pending_stop_replies_in_queue ();
74531fed 4030
6b8edb51
PA
4031 if (rs->remote_async_inferior_event_token)
4032 delete_async_event_handler (&rs->remote_async_inferior_event_token);
722247f1 4033
5965e028 4034 remote_notif_state_xfree (rs->notif_state);
c906108c
SS
4035}
4036
23860348 4037/* Query the remote side for the text, data and bss offsets. */
c906108c 4038
6b8edb51
PA
4039void
4040remote_target::get_offsets ()
c906108c 4041{
d01949b6 4042 struct remote_state *rs = get_remote_state ();
2e9f7625 4043 char *buf;
085dd6e6 4044 char *ptr;
31d99776
DJ
4045 int lose, num_segments = 0, do_sections, do_segments;
4046 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 4047 struct section_offsets *offs;
31d99776
DJ
4048 struct symfile_segment_data *data;
4049
4050 if (symfile_objfile == NULL)
4051 return;
c906108c
SS
4052
4053 putpkt ("qOffsets");
6d820c5c 4054 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4055 buf = rs->buf;
c906108c
SS
4056
4057 if (buf[0] == '\000')
4058 return; /* Return silently. Stub doesn't support
23860348 4059 this command. */
c906108c
SS
4060 if (buf[0] == 'E')
4061 {
8a3fe4f8 4062 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4063 return;
4064 }
4065
4066 /* Pick up each field in turn. This used to be done with scanf, but
4067 scanf will make trouble if CORE_ADDR size doesn't match
4068 conversion directives correctly. The following code will work
4069 with any size of CORE_ADDR. */
4070 text_addr = data_addr = bss_addr = 0;
4071 ptr = buf;
4072 lose = 0;
4073
61012eef 4074 if (startswith (ptr, "Text="))
c906108c
SS
4075 {
4076 ptr += 5;
4077 /* Don't use strtol, could lose on big values. */
4078 while (*ptr && *ptr != ';')
4079 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4080
61012eef 4081 if (startswith (ptr, ";Data="))
31d99776
DJ
4082 {
4083 ptr += 6;
4084 while (*ptr && *ptr != ';')
4085 data_addr = (data_addr << 4) + fromhex (*ptr++);
4086 }
4087 else
4088 lose = 1;
4089
61012eef 4090 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4091 {
4092 ptr += 5;
4093 while (*ptr && *ptr != ';')
4094 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4095
31d99776
DJ
4096 if (bss_addr != data_addr)
4097 warning (_("Target reported unsupported offsets: %s"), buf);
4098 }
4099 else
4100 lose = 1;
4101 }
61012eef 4102 else if (startswith (ptr, "TextSeg="))
c906108c 4103 {
31d99776
DJ
4104 ptr += 8;
4105 /* Don't use strtol, could lose on big values. */
c906108c 4106 while (*ptr && *ptr != ';')
31d99776
DJ
4107 text_addr = (text_addr << 4) + fromhex (*ptr++);
4108 num_segments = 1;
4109
61012eef 4110 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4111 {
4112 ptr += 9;
4113 while (*ptr && *ptr != ';')
4114 data_addr = (data_addr << 4) + fromhex (*ptr++);
4115 num_segments++;
4116 }
c906108c
SS
4117 }
4118 else
4119 lose = 1;
4120
4121 if (lose)
8a3fe4f8 4122 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4123 else if (*ptr != '\0')
4124 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4125
802188a7 4126 offs = ((struct section_offsets *)
a39a16c4 4127 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 4128 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 4129 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 4130
31d99776
DJ
4131 data = get_symfile_segment_data (symfile_objfile->obfd);
4132 do_segments = (data != NULL);
4133 do_sections = num_segments == 0;
c906108c 4134
28c32713 4135 if (num_segments > 0)
31d99776 4136 {
31d99776
DJ
4137 segments[0] = text_addr;
4138 segments[1] = data_addr;
4139 }
28c32713
JB
4140 /* If we have two segments, we can still try to relocate everything
4141 by assuming that the .text and .data offsets apply to the whole
4142 text and data segments. Convert the offsets given in the packet
4143 to base addresses for symfile_map_offsets_to_segments. */
4144 else if (data && data->num_segments == 2)
4145 {
4146 segments[0] = data->segment_bases[0] + text_addr;
4147 segments[1] = data->segment_bases[1] + data_addr;
4148 num_segments = 2;
4149 }
8d385431
DJ
4150 /* If the object file has only one segment, assume that it is text
4151 rather than data; main programs with no writable data are rare,
4152 but programs with no code are useless. Of course the code might
4153 have ended up in the data segment... to detect that we would need
4154 the permissions here. */
4155 else if (data && data->num_segments == 1)
4156 {
4157 segments[0] = data->segment_bases[0] + text_addr;
4158 num_segments = 1;
4159 }
28c32713
JB
4160 /* There's no way to relocate by segment. */
4161 else
4162 do_segments = 0;
31d99776
DJ
4163
4164 if (do_segments)
4165 {
4166 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4167 offs, num_segments, segments);
4168
4169 if (ret == 0 && !do_sections)
3e43a32a
MS
4170 error (_("Can not handle qOffsets TextSeg "
4171 "response with this symbol file"));
31d99776
DJ
4172
4173 if (ret > 0)
4174 do_sections = 0;
4175 }
c906108c 4176
9ef895d6
DJ
4177 if (data)
4178 free_symfile_segment_data (data);
31d99776
DJ
4179
4180 if (do_sections)
4181 {
4182 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4183
3e43a32a
MS
4184 /* This is a temporary kludge to force data and bss to use the
4185 same offsets because that's what nlmconv does now. The real
4186 solution requires changes to the stub and remote.c that I
4187 don't have time to do right now. */
31d99776
DJ
4188
4189 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4190 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4191 }
c906108c
SS
4192
4193 objfile_relocate (symfile_objfile, offs);
4194}
4195
9a7071a8 4196/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4197
4198void
4199remote_target::send_interrupt_sequence ()
9a7071a8 4200{
5d93a237
TT
4201 struct remote_state *rs = get_remote_state ();
4202
9a7071a8 4203 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4204 remote_serial_write ("\x03", 1);
9a7071a8 4205 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4206 serial_send_break (rs->remote_desc);
9a7071a8
JB
4207 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4208 {
5d93a237 4209 serial_send_break (rs->remote_desc);
c33e31fd 4210 remote_serial_write ("g", 1);
9a7071a8
JB
4211 }
4212 else
4213 internal_error (__FILE__, __LINE__,
4214 _("Invalid value for interrupt_sequence_mode: %s."),
4215 interrupt_sequence_mode);
4216}
4217
3405876a
PA
4218
4219/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4220 and extract the PTID. Returns NULL_PTID if not found. */
4221
4222static ptid_t
4223stop_reply_extract_thread (char *stop_reply)
4224{
4225 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4226 {
256642e8 4227 const char *p;
3405876a
PA
4228
4229 /* Txx r:val ; r:val (...) */
4230 p = &stop_reply[3];
4231
4232 /* Look for "register" named "thread". */
4233 while (*p != '\0')
4234 {
256642e8 4235 const char *p1;
3405876a
PA
4236
4237 p1 = strchr (p, ':');
4238 if (p1 == NULL)
4239 return null_ptid;
4240
4241 if (strncmp (p, "thread", p1 - p) == 0)
4242 return read_ptid (++p1, &p);
4243
4244 p1 = strchr (p, ';');
4245 if (p1 == NULL)
4246 return null_ptid;
4247 p1++;
4248
4249 p = p1;
4250 }
4251 }
4252
4253 return null_ptid;
4254}
4255
b7ea362b
PA
4256/* Determine the remote side's current thread. If we have a stop
4257 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4258 "thread" register we can extract the current thread from. If not,
4259 ask the remote which is the current thread with qC. The former
4260 method avoids a roundtrip. */
4261
6b8edb51
PA
4262ptid_t
4263remote_target::get_current_thread (char *wait_status)
b7ea362b 4264{
6a49a997 4265 ptid_t ptid = null_ptid;
b7ea362b
PA
4266
4267 /* Note we don't use remote_parse_stop_reply as that makes use of
4268 the target architecture, which we haven't yet fully determined at
4269 this point. */
4270 if (wait_status != NULL)
4271 ptid = stop_reply_extract_thread (wait_status);
4272 if (ptid_equal (ptid, null_ptid))
4273 ptid = remote_current_thread (inferior_ptid);
4274
4275 return ptid;
4276}
4277
49c62f2e
PA
4278/* Query the remote target for which is the current thread/process,
4279 add it to our tables, and update INFERIOR_PTID. The caller is
4280 responsible for setting the state such that the remote end is ready
3405876a
PA
4281 to return the current thread.
4282
4283 This function is called after handling the '?' or 'vRun' packets,
4284 whose response is a stop reply from which we can also try
4285 extracting the thread. If the target doesn't support the explicit
4286 qC query, we infer the current thread from that stop reply, passed
4287 in in WAIT_STATUS, which may be NULL. */
49c62f2e 4288
6b8edb51
PA
4289void
4290remote_target::add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
4291{
4292 struct remote_state *rs = get_remote_state ();
4293 int fake_pid_p = 0;
49c62f2e
PA
4294
4295 inferior_ptid = null_ptid;
4296
b7ea362b 4297 /* Now, if we have thread information, update inferior_ptid. */
87215ad1 4298 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4299
87215ad1 4300 if (curr_ptid != null_ptid)
49c62f2e
PA
4301 {
4302 if (!remote_multi_process_p (rs))
4303 fake_pid_p = 1;
49c62f2e
PA
4304 }
4305 else
4306 {
4307 /* Without this, some commands which require an active target
4308 (such as kill) won't work. This variable serves (at least)
4309 double duty as both the pid of the target process (if it has
4310 such), and as a flag indicating that a target is active. */
87215ad1 4311 curr_ptid = magic_null_ptid;
49c62f2e
PA
4312 fake_pid_p = 1;
4313 }
4314
87215ad1 4315 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
49c62f2e 4316
87215ad1
SDJ
4317 /* Add the main thread and switch to it. Don't try reading
4318 registers yet, since we haven't fetched the target description
4319 yet. */
4320 thread_info *tp = add_thread_silent (curr_ptid);
4321 switch_to_thread_no_regs (tp);
49c62f2e
PA
4322}
4323
6efcd9a8
PA
4324/* Print info about a thread that was found already stopped on
4325 connection. */
4326
4327static void
4328print_one_stopped_thread (struct thread_info *thread)
4329{
4330 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4331
4332 switch_to_thread (thread->ptid);
4333 stop_pc = get_frame_pc (get_current_frame ());
4334 set_current_sal_from_frame (get_current_frame ());
4335
4336 thread->suspend.waitstatus_pending_p = 0;
4337
4338 if (ws->kind == TARGET_WAITKIND_STOPPED)
4339 {
4340 enum gdb_signal sig = ws->value.sig;
4341
4342 if (signal_print_state (sig))
76727919 4343 gdb::observers::signal_received.notify (sig);
6efcd9a8 4344 }
76727919 4345 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4346}
4347
221e1a37
PA
4348/* Process all initial stop replies the remote side sent in response
4349 to the ? packet. These indicate threads that were already stopped
4350 on initial connection. We mark these threads as stopped and print
4351 their current frame before giving the user the prompt. */
4352
6b8edb51
PA
4353void
4354remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4355{
4356 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4357 struct inferior *inf;
4358 struct thread_info *thread;
4359 struct thread_info *selected = NULL;
4360 struct thread_info *lowest_stopped = NULL;
4361 struct thread_info *first = NULL;
221e1a37
PA
4362
4363 /* Consume the initial pending events. */
4364 while (pending_stop_replies-- > 0)
4365 {
4366 ptid_t waiton_ptid = minus_one_ptid;
4367 ptid_t event_ptid;
4368 struct target_waitstatus ws;
4369 int ignore_event = 0;
6efcd9a8 4370 struct thread_info *thread;
221e1a37
PA
4371
4372 memset (&ws, 0, sizeof (ws));
4373 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4374 if (remote_debug)
4375 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4376
4377 switch (ws.kind)
4378 {
4379 case TARGET_WAITKIND_IGNORE:
4380 case TARGET_WAITKIND_NO_RESUMED:
4381 case TARGET_WAITKIND_SIGNALLED:
4382 case TARGET_WAITKIND_EXITED:
4383 /* We shouldn't see these, but if we do, just ignore. */
4384 if (remote_debug)
4385 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4386 ignore_event = 1;
4387 break;
4388
4389 case TARGET_WAITKIND_EXECD:
4390 xfree (ws.value.execd_pathname);
4391 break;
4392 default:
4393 break;
4394 }
4395
4396 if (ignore_event)
4397 continue;
4398
6efcd9a8 4399 thread = find_thread_ptid (event_ptid);
221e1a37
PA
4400
4401 if (ws.kind == TARGET_WAITKIND_STOPPED)
4402 {
4403 enum gdb_signal sig = ws.value.sig;
4404
4405 /* Stubs traditionally report SIGTRAP as initial signal,
4406 instead of signal 0. Suppress it. */
4407 if (sig == GDB_SIGNAL_TRAP)
4408 sig = GDB_SIGNAL_0;
6efcd9a8
PA
4409 thread->suspend.stop_signal = sig;
4410 ws.value.sig = sig;
4411 }
221e1a37 4412
6efcd9a8
PA
4413 thread->suspend.waitstatus = ws;
4414
4415 if (ws.kind != TARGET_WAITKIND_STOPPED
4416 || ws.value.sig != GDB_SIGNAL_0)
4417 thread->suspend.waitstatus_pending_p = 1;
4418
4419 set_executing (event_ptid, 0);
4420 set_running (event_ptid, 0);
7aabaf9d 4421 get_remote_thread_info (thread)->vcont_resumed = 0;
6efcd9a8
PA
4422 }
4423
4424 /* "Notice" the new inferiors before anything related to
4425 registers/memory. */
4426 ALL_INFERIORS (inf)
4427 {
4428 if (inf->pid == 0)
4429 continue;
4430
4431 inf->needs_setup = 1;
4432
4433 if (non_stop)
4434 {
4435 thread = any_live_thread_of_process (inf->pid);
4436 notice_new_inferior (thread->ptid,
4437 thread->state == THREAD_RUNNING,
4438 from_tty);
4439 }
4440 }
4441
4442 /* If all-stop on top of non-stop, pause all threads. Note this
4443 records the threads' stop pc, so must be done after "noticing"
4444 the inferiors. */
4445 if (!non_stop)
4446 {
4447 stop_all_threads ();
4448
4449 /* If all threads of an inferior were already stopped, we
4450 haven't setup the inferior yet. */
4451 ALL_INFERIORS (inf)
4452 {
4453 if (inf->pid == 0)
4454 continue;
221e1a37 4455
6efcd9a8
PA
4456 if (inf->needs_setup)
4457 {
4458 thread = any_live_thread_of_process (inf->pid);
4459 switch_to_thread_no_regs (thread);
4460 setup_inferior (0);
4461 }
4462 }
221e1a37 4463 }
6efcd9a8
PA
4464
4465 /* Now go over all threads that are stopped, and print their current
4466 frame. If all-stop, then if there's a signalled thread, pick
4467 that as current. */
4468 ALL_NON_EXITED_THREADS (thread)
4469 {
6efcd9a8
PA
4470 if (first == NULL)
4471 first = thread;
4472
4473 if (!non_stop)
4474 set_running (thread->ptid, 0);
4475 else if (thread->state != THREAD_STOPPED)
4476 continue;
4477
6efcd9a8
PA
4478 if (selected == NULL
4479 && thread->suspend.waitstatus_pending_p)
4480 selected = thread;
4481
5d5658a1
PA
4482 if (lowest_stopped == NULL
4483 || thread->inf->num < lowest_stopped->inf->num
4484 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4485 lowest_stopped = thread;
4486
4487 if (non_stop)
4488 print_one_stopped_thread (thread);
4489 }
4490
4491 /* In all-stop, we only print the status of one thread, and leave
4492 others with their status pending. */
4493 if (!non_stop)
4494 {
4495 thread = selected;
4496 if (thread == NULL)
4497 thread = lowest_stopped;
4498 if (thread == NULL)
4499 thread = first;
4500
4501 print_one_stopped_thread (thread);
4502 }
4503
4504 /* For "info program". */
4505 thread = inferior_thread ();
4506 if (thread->state == THREAD_STOPPED)
4507 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4508}
4509
048094ac
PA
4510/* Start the remote connection and sync state. */
4511
f6ac5f3d
PA
4512void
4513remote_target::start_remote (int from_tty, int extended_p)
c906108c 4514{
c8d104ad
PA
4515 struct remote_state *rs = get_remote_state ();
4516 struct packet_config *noack_config;
2d717e4f 4517 char *wait_status = NULL;
8621d6a9 4518
048094ac
PA
4519 /* Signal other parts that we're going through the initial setup,
4520 and so things may not be stable yet. E.g., we don't try to
4521 install tracepoints until we've relocated symbols. Also, a
4522 Ctrl-C before we're connected and synced up can't interrupt the
4523 target. Instead, it offers to drop the (potentially wedged)
4524 connection. */
4525 rs->starting_up = 1;
4526
522002f9 4527 QUIT;
c906108c 4528
9a7071a8
JB
4529 if (interrupt_on_connect)
4530 send_interrupt_sequence ();
4531
57e12211 4532 /* Ack any packet which the remote side has already sent. */
048094ac 4533 remote_serial_write ("+", 1);
1e51243a 4534
c8d104ad
PA
4535 /* The first packet we send to the target is the optional "supported
4536 packets" request. If the target can answer this, it will tell us
4537 which later probes to skip. */
4538 remote_query_supported ();
4539
d914c394 4540 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4541 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4542 set_permissions ();
d914c394 4543
57809e5e
JK
4544 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4545 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4546 as a reply to known packet. For packet "vFile:setfs:" it is an
4547 invalid reply and GDB would return error in
4548 remote_hostio_set_filesystem, making remote files access impossible.
4549 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4550 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4551 {
4552 const char v_mustreplyempty[] = "vMustReplyEmpty";
4553
4554 putpkt (v_mustreplyempty);
4555 getpkt (&rs->buf, &rs->buf_size, 0);
4556 if (strcmp (rs->buf, "OK") == 0)
4557 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4558 else if (strcmp (rs->buf, "") != 0)
4559 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4560 rs->buf);
4561 }
4562
c8d104ad
PA
4563 /* Next, we possibly activate noack mode.
4564
4565 If the QStartNoAckMode packet configuration is set to AUTO,
4566 enable noack mode if the stub reported a wish for it with
4567 qSupported.
4568
4569 If set to TRUE, then enable noack mode even if the stub didn't
4570 report it in qSupported. If the stub doesn't reply OK, the
4571 session ends with an error.
4572
4573 If FALSE, then don't activate noack mode, regardless of what the
4574 stub claimed should be the default with qSupported. */
4575
4576 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4577 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4578 {
4579 putpkt ("QStartNoAckMode");
4580 getpkt (&rs->buf, &rs->buf_size, 0);
4581 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4582 rs->noack_mode = 1;
4583 }
4584
04bd08de 4585 if (extended_p)
5fe04517
PA
4586 {
4587 /* Tell the remote that we are using the extended protocol. */
4588 putpkt ("!");
4589 getpkt (&rs->buf, &rs->buf_size, 0);
4590 }
4591
9b224c5e
PA
4592 /* Let the target know which signals it is allowed to pass down to
4593 the program. */
4594 update_signals_program_target ();
4595
d962ef82
DJ
4596 /* Next, if the target can specify a description, read it. We do
4597 this before anything involving memory or registers. */
4598 target_find_description ();
4599
6c95b8df
PA
4600 /* Next, now that we know something about the target, update the
4601 address spaces in the program spaces. */
4602 update_address_spaces ();
4603
50c71eaf
PA
4604 /* On OSs where the list of libraries is global to all
4605 processes, we fetch them early. */
f5656ead 4606 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4607 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4608
6efcd9a8 4609 if (target_is_non_stop_p ())
74531fed 4610 {
4082afcc 4611 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4612 error (_("Non-stop mode requested, but remote "
4613 "does not support non-stop"));
74531fed
PA
4614
4615 putpkt ("QNonStop:1");
4616 getpkt (&rs->buf, &rs->buf_size, 0);
4617
4618 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4619 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4620
4621 /* Find about threads and processes the stub is already
4622 controlling. We default to adding them in the running state.
4623 The '?' query below will then tell us about which threads are
4624 stopped. */
f6ac5f3d 4625 this->update_thread_list ();
74531fed 4626 }
4082afcc 4627 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4628 {
4629 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4630 Request it explicitly. */
74531fed
PA
4631 putpkt ("QNonStop:0");
4632 getpkt (&rs->buf, &rs->buf_size, 0);
4633
4634 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4635 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4636 }
4637
a0743c90
YQ
4638 /* Upload TSVs regardless of whether the target is running or not. The
4639 remote stub, such as GDBserver, may have some predefined or builtin
4640 TSVs, even if the target is not running. */
f6ac5f3d 4641 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4642 {
4643 struct uploaded_tsv *uploaded_tsvs = NULL;
4644
f6ac5f3d 4645 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4646 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4647 }
4648
2d717e4f
DJ
4649 /* Check whether the target is running now. */
4650 putpkt ("?");
4651 getpkt (&rs->buf, &rs->buf_size, 0);
4652
6efcd9a8 4653 if (!target_is_non_stop_p ())
2d717e4f 4654 {
74531fed 4655 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4656 {
04bd08de 4657 if (!extended_p)
74531fed 4658 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4659
4660 /* We're connected, but not running. Drop out before we
4661 call start_remote. */
e278ad5b 4662 rs->starting_up = 0;
c35b1492 4663 return;
2d717e4f
DJ
4664 }
4665 else
74531fed 4666 {
74531fed 4667 /* Save the reply for later. */
224c3ddb 4668 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4669 strcpy (wait_status, rs->buf);
4670 }
4671
b7ea362b 4672 /* Fetch thread list. */
e8032dde 4673 target_update_thread_list ();
b7ea362b 4674
74531fed
PA
4675 /* Let the stub know that we want it to return the thread. */
4676 set_continue_thread (minus_one_ptid);
4677
b7ea362b
PA
4678 if (thread_count () == 0)
4679 {
4680 /* Target has no concept of threads at all. GDB treats
4681 non-threaded target as single-threaded; add a main
4682 thread. */
4683 add_current_inferior_and_thread (wait_status);
4684 }
4685 else
4686 {
4687 /* We have thread information; select the thread the target
4688 says should be current. If we're reconnecting to a
4689 multi-threaded program, this will ideally be the thread
4690 that last reported an event before GDB disconnected. */
4691 inferior_ptid = get_current_thread (wait_status);
4692 if (ptid_equal (inferior_ptid, null_ptid))
4693 {
4694 /* Odd... The target was able to list threads, but not
4695 tell us which thread was current (no "thread"
4696 register in T stop reply?). Just pick the first
4697 thread in the thread list then. */
c9f35b34
KB
4698
4699 if (remote_debug)
4700 fprintf_unfiltered (gdb_stdlog,
4701 "warning: couldn't determine remote "
4702 "current thread; picking first in list.\n");
4703
b7ea362b
PA
4704 inferior_ptid = thread_list->ptid;
4705 }
4706 }
74531fed 4707
6e586cc5
YQ
4708 /* init_wait_for_inferior should be called before get_offsets in order
4709 to manage `inserted' flag in bp loc in a correct state.
4710 breakpoint_init_inferior, called from init_wait_for_inferior, set
4711 `inserted' flag to 0, while before breakpoint_re_set, called from
4712 start_remote, set `inserted' flag to 1. In the initialization of
4713 inferior, breakpoint_init_inferior should be called first, and then
4714 breakpoint_re_set can be called. If this order is broken, state of
4715 `inserted' flag is wrong, and cause some problems on breakpoint
4716 manipulation. */
4717 init_wait_for_inferior ();
4718
74531fed
PA
4719 get_offsets (); /* Get text, data & bss offsets. */
4720
d962ef82
DJ
4721 /* If we could not find a description using qXfer, and we know
4722 how to do it some other way, try again. This is not
4723 supported for non-stop; it could be, but it is tricky if
4724 there are no stopped threads when we connect. */
f6ac5f3d 4725 if (remote_read_description_p (this)
f5656ead 4726 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4727 {
4728 target_clear_description ();
4729 target_find_description ();
4730 }
4731
74531fed
PA
4732 /* Use the previously fetched status. */
4733 gdb_assert (wait_status != NULL);
4734 strcpy (rs->buf, wait_status);
4735 rs->cached_wait_status = 1;
4736
f6ac5f3d 4737 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4738 }
4739 else
4740 {
68c97600
PA
4741 /* Clear WFI global state. Do this before finding about new
4742 threads and inferiors, and setting the current inferior.
4743 Otherwise we would clear the proceed status of the current
4744 inferior when we want its stop_soon state to be preserved
4745 (see notice_new_inferior). */
4746 init_wait_for_inferior ();
4747
74531fed
PA
4748 /* In non-stop, we will either get an "OK", meaning that there
4749 are no stopped threads at this time; or, a regular stop
4750 reply. In the latter case, there may be more than one thread
4751 stopped --- we pull them all out using the vStopped
4752 mechanism. */
4753 if (strcmp (rs->buf, "OK") != 0)
4754 {
722247f1 4755 struct notif_client *notif = &notif_client_stop;
2d717e4f 4756
722247f1
YQ
4757 /* remote_notif_get_pending_replies acks this one, and gets
4758 the rest out. */
f48ff2a7 4759 rs->notif_state->pending_event[notif_client_stop.id]
6b8edb51 4760 = remote_notif_parse (this, notif, rs->buf);
722247f1 4761 remote_notif_get_pending_events (notif);
74531fed 4762 }
2d717e4f 4763
74531fed
PA
4764 if (thread_count () == 0)
4765 {
04bd08de 4766 if (!extended_p)
74531fed 4767 error (_("The target is not running (try extended-remote?)"));
82f73884 4768
c35b1492
PA
4769 /* We're connected, but not running. Drop out before we
4770 call start_remote. */
e278ad5b 4771 rs->starting_up = 0;
c35b1492
PA
4772 return;
4773 }
74531fed 4774
74531fed
PA
4775 /* In non-stop mode, any cached wait status will be stored in
4776 the stop reply queue. */
4777 gdb_assert (wait_status == NULL);
f0223081 4778
2455069d 4779 /* Report all signals during attach/startup. */
f6ac5f3d 4780 pass_signals (0, NULL);
221e1a37
PA
4781
4782 /* If there are already stopped threads, mark them stopped and
4783 report their stops before giving the prompt to the user. */
6efcd9a8 4784 process_initial_stop_replies (from_tty);
221e1a37
PA
4785
4786 if (target_can_async_p ())
4787 target_async (1);
74531fed 4788 }
c8d104ad 4789
c8d104ad
PA
4790 /* If we connected to a live target, do some additional setup. */
4791 if (target_has_execution)
4792 {
f4ccffad 4793 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4794 remote_check_symbols ();
c8d104ad 4795 }
50c71eaf 4796
d5551862
SS
4797 /* Possibly the target has been engaged in a trace run started
4798 previously; find out where things are at. */
f6ac5f3d 4799 if (get_trace_status (current_trace_status ()) != -1)
d5551862 4800 {
00bf0b85 4801 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4802
00bf0b85
SS
4803 if (current_trace_status ()->running)
4804 printf_filtered (_("Trace is already running on the target.\n"));
4805
f6ac5f3d 4806 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
4807
4808 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4809 }
4810
c0272db5
TW
4811 /* Possibly the target has been engaged in a btrace record started
4812 previously; find out where things are at. */
4813 remote_btrace_maybe_reopen ();
4814
1e51243a
PA
4815 /* The thread and inferior lists are now synchronized with the
4816 target, our symbols have been relocated, and we're merged the
4817 target's tracepoints with ours. We're done with basic start
4818 up. */
4819 rs->starting_up = 0;
4820
a25a5a45
PA
4821 /* Maybe breakpoints are global and need to be inserted now. */
4822 if (breakpoints_should_be_inserted_now ())
50c71eaf 4823 insert_breakpoints ();
c906108c
SS
4824}
4825
4826/* Open a connection to a remote debugger.
4827 NAME is the filename used for communication. */
4828
f6ac5f3d
PA
4829void
4830remote_target::open (const char *name, int from_tty)
c906108c 4831{
f6ac5f3d 4832 open_1 (name, from_tty, 0);
43ff13b4
JM
4833}
4834
c906108c
SS
4835/* Open a connection to a remote debugger using the extended
4836 remote gdb protocol. NAME is the filename used for communication. */
4837
f6ac5f3d
PA
4838void
4839extended_remote_target::open (const char *name, int from_tty)
c906108c 4840{
f6ac5f3d 4841 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
4842}
4843
ca4f7f8b
PA
4844/* Reset all packets back to "unknown support". Called when opening a
4845 new connection to a remote target. */
c906108c 4846
d471ea57 4847static void
ca4f7f8b 4848reset_all_packet_configs_support (void)
d471ea57
AC
4849{
4850 int i;
a744cf53 4851
444abaca 4852 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4853 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4854}
4855
ca4f7f8b
PA
4856/* Initialize all packet configs. */
4857
4858static void
4859init_all_packet_configs (void)
4860{
4861 int i;
4862
4863 for (i = 0; i < PACKET_MAX; i++)
4864 {
4865 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4866 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4867 }
4868}
4869
23860348 4870/* Symbol look-up. */
dc8acb97 4871
6b8edb51
PA
4872void
4873remote_target::remote_check_symbols ()
dc8acb97
MS
4874{
4875 char *msg, *reply, *tmp;
dc8acb97 4876 int end;
28170b88 4877 long reply_size;
a5c0808e 4878 struct cleanup *old_chain;
dc8acb97 4879
63154eca
PA
4880 /* The remote side has no concept of inferiors that aren't running
4881 yet, it only knows about running processes. If we're connected
4882 but our current inferior is not running, we should not invite the
4883 remote target to request symbol lookups related to its
4884 (unrelated) current process. */
4885 if (!target_has_execution)
4886 return;
4887
4082afcc 4888 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4889 return;
4890
63154eca
PA
4891 /* Make sure the remote is pointing at the right process. Note
4892 there's no way to select "no process". */
3c9c4b83
PA
4893 set_general_process ();
4894
6d820c5c
DJ
4895 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4896 because we need both at the same time. */
224c3ddb 4897 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4898 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4899 reply = (char *) xmalloc (get_remote_packet_size ());
4900 make_cleanup (free_current_contents, &reply);
4901 reply_size = get_remote_packet_size ();
6d820c5c 4902
23860348 4903 /* Invite target to request symbol lookups. */
dc8acb97
MS
4904
4905 putpkt ("qSymbol::");
28170b88
MK
4906 getpkt (&reply, &reply_size, 0);
4907 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4908
61012eef 4909 while (startswith (reply, "qSymbol:"))
dc8acb97 4910 {
77e371c0
TT
4911 struct bound_minimal_symbol sym;
4912
dc8acb97 4913 tmp = &reply[8];
cfd77fa1 4914 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4915 msg[end] = '\0';
4916 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4917 if (sym.minsym == NULL)
ea9c271d 4918 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4919 else
2bbe3cc1 4920 {
f5656ead 4921 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4922 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4923
4924 /* If this is a function address, return the start of code
4925 instead of any data function descriptor. */
f5656ead 4926 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1 4927 sym_addr,
8b88a78e 4928 current_top_target ());
2bbe3cc1
DJ
4929
4930 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4931 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4932 }
4933
dc8acb97 4934 putpkt (msg);
28170b88 4935 getpkt (&reply, &reply_size, 0);
dc8acb97 4936 }
a5c0808e
PA
4937
4938 do_cleanups (old_chain);
dc8acb97
MS
4939}
4940
9db8d71f 4941static struct serial *
baa336ce 4942remote_serial_open (const char *name)
9db8d71f
DJ
4943{
4944 static int udp_warning = 0;
4945
4946 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4947 of in ser-tcp.c, because it is the remote protocol assuming that the
4948 serial connection is reliable and not the serial connection promising
4949 to be. */
61012eef 4950 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4951 {
3e43a32a
MS
4952 warning (_("The remote protocol may be unreliable over UDP.\n"
4953 "Some events may be lost, rendering further debugging "
4954 "impossible."));
9db8d71f
DJ
4955 udp_warning = 1;
4956 }
4957
4958 return serial_open (name);
4959}
4960
d914c394
SS
4961/* Inform the target of our permission settings. The permission flags
4962 work without this, but if the target knows the settings, it can do
4963 a couple things. First, it can add its own check, to catch cases
4964 that somehow manage to get by the permissions checks in target
4965 methods. Second, if the target is wired to disallow particular
4966 settings (for instance, a system in the field that is not set up to
4967 be able to stop at a breakpoint), it can object to any unavailable
4968 permissions. */
4969
4970void
f6ac5f3d 4971remote_target::set_permissions ()
d914c394
SS
4972{
4973 struct remote_state *rs = get_remote_state ();
4974
bba74b36
YQ
4975 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4976 "WriteReg:%x;WriteMem:%x;"
4977 "InsertBreak:%x;InsertTrace:%x;"
4978 "InsertFastTrace:%x;Stop:%x",
4979 may_write_registers, may_write_memory,
4980 may_insert_breakpoints, may_insert_tracepoints,
4981 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4982 putpkt (rs->buf);
4983 getpkt (&rs->buf, &rs->buf_size, 0);
4984
4985 /* If the target didn't like the packet, warn the user. Do not try
4986 to undo the user's settings, that would just be maddening. */
4987 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4988 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4989}
4990
be2a5f71
DJ
4991/* This type describes each known response to the qSupported
4992 packet. */
4993struct protocol_feature
4994{
4995 /* The name of this protocol feature. */
4996 const char *name;
4997
4998 /* The default for this protocol feature. */
4999 enum packet_support default_support;
5000
5001 /* The function to call when this feature is reported, or after
5002 qSupported processing if the feature is not supported.
5003 The first argument points to this structure. The second
5004 argument indicates whether the packet requested support be
5005 enabled, disabled, or probed (or the default, if this function
5006 is being called at the end of processing and this feature was
5007 not reported). The third argument may be NULL; if not NULL, it
5008 is a NUL-terminated string taken from the packet following
5009 this feature's name and an equals sign. */
6b8edb51
PA
5010 void (*func) (remote_target *remote, const struct protocol_feature *,
5011 enum packet_support, const char *);
be2a5f71
DJ
5012
5013 /* The corresponding packet for this feature. Only used if
5014 FUNC is remote_supported_packet. */
5015 int packet;
5016};
5017
be2a5f71 5018static void
6b8edb51
PA
5019remote_supported_packet (remote_target *remote,
5020 const struct protocol_feature *feature,
be2a5f71
DJ
5021 enum packet_support support,
5022 const char *argument)
5023{
5024 if (argument)
5025 {
5026 warning (_("Remote qSupported response supplied an unexpected value for"
5027 " \"%s\"."), feature->name);
5028 return;
5029 }
5030
4082afcc 5031 remote_protocol_packets[feature->packet].support = support;
be2a5f71 5032}
be2a5f71 5033
6b8edb51
PA
5034void
5035remote_target::remote_packet_size (const protocol_feature *feature,
5036 enum packet_support support, const char *value)
be2a5f71
DJ
5037{
5038 struct remote_state *rs = get_remote_state ();
5039
5040 int packet_size;
5041 char *value_end;
5042
5043 if (support != PACKET_ENABLE)
5044 return;
5045
5046 if (value == NULL || *value == '\0')
5047 {
5048 warning (_("Remote target reported \"%s\" without a size."),
5049 feature->name);
5050 return;
5051 }
5052
5053 errno = 0;
5054 packet_size = strtol (value, &value_end, 16);
5055 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5056 {
5057 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5058 feature->name, value);
5059 return;
5060 }
5061
be2a5f71
DJ
5062 /* Record the new maximum packet size. */
5063 rs->explicit_packet_size = packet_size;
5064}
5065
6b8edb51
PA
5066void
5067remote_packet_size (remote_target *remote, const protocol_feature *feature,
5068 enum packet_support support, const char *value)
5069{
5070 remote->remote_packet_size (feature, support, value);
5071}
5072
dc473cfb 5073static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5074 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5075 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5076 PACKET_qXfer_auxv },
c78fa86a
GB
5077 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5078 PACKET_qXfer_exec_file },
23181151
DJ
5079 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5080 PACKET_qXfer_features },
cfa9d6d9
DJ
5081 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5082 PACKET_qXfer_libraries },
2268b414
JK
5083 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5084 PACKET_qXfer_libraries_svr4 },
ced63ec0 5085 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5086 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5087 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5088 PACKET_qXfer_memory_map },
4de6483e
UW
5089 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5090 PACKET_qXfer_spu_read },
5091 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5092 PACKET_qXfer_spu_write },
07e059b5
VP
5093 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5094 PACKET_qXfer_osdata },
dc146f7c
VP
5095 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5096 PACKET_qXfer_threads },
b3b9301e
PA
5097 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5098 PACKET_qXfer_traceframe_info },
89be2091
DJ
5099 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5100 PACKET_QPassSignals },
82075af2
JS
5101 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5102 PACKET_QCatchSyscalls },
9b224c5e
PA
5103 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5104 PACKET_QProgramSignals },
bc3b087d
SDJ
5105 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5106 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5107 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5108 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5109 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5110 PACKET_QEnvironmentHexEncoded },
5111 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5112 PACKET_QEnvironmentReset },
5113 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5114 PACKET_QEnvironmentUnset },
a6f3e723
SL
5115 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5116 PACKET_QStartNoAckMode },
4082afcc
PA
5117 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5118 PACKET_multiprocess_feature },
5119 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5120 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5121 PACKET_qXfer_siginfo_read },
5122 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5123 PACKET_qXfer_siginfo_write },
4082afcc 5124 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5125 PACKET_ConditionalTracepoints },
4082afcc 5126 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5127 PACKET_ConditionalBreakpoints },
4082afcc 5128 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5129 PACKET_BreakpointCommands },
4082afcc 5130 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5131 PACKET_FastTracepoints },
4082afcc 5132 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5133 PACKET_StaticTracepoints },
4082afcc 5134 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5135 PACKET_InstallInTrace},
4082afcc
PA
5136 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5137 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5138 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5139 PACKET_bc },
5140 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5141 PACKET_bs },
409873ef
SS
5142 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5143 PACKET_TracepointSource },
d914c394
SS
5144 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5145 PACKET_QAllow },
4082afcc
PA
5146 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5147 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5148 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5149 PACKET_qXfer_fdpic },
169081d0
TG
5150 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5151 PACKET_qXfer_uib },
03583c20
UW
5152 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5153 PACKET_QDisableRandomization },
d1feda86 5154 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5155 { "QTBuffer:size", PACKET_DISABLE,
5156 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5157 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5158 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5159 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5160 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5161 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5162 PACKET_qXfer_btrace },
5163 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5164 PACKET_qXfer_btrace_conf },
5165 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5166 PACKET_Qbtrace_conf_bts_size },
5167 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5168 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5169 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5170 PACKET_fork_event_feature },
5171 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5172 PACKET_vfork_event_feature },
94585166
DB
5173 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5174 PACKET_exec_event_feature },
b20a6524 5175 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5176 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5177 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5178 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5179 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
5180};
5181
c8d5aac9
L
5182static char *remote_support_xml;
5183
5184/* Register string appended to "xmlRegisters=" in qSupported query. */
5185
5186void
6e39997a 5187register_remote_support_xml (const char *xml)
c8d5aac9
L
5188{
5189#if defined(HAVE_LIBEXPAT)
5190 if (remote_support_xml == NULL)
c4f7c687 5191 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5192 else
5193 {
5194 char *copy = xstrdup (remote_support_xml + 13);
5195 char *p = strtok (copy, ",");
5196
5197 do
5198 {
5199 if (strcmp (p, xml) == 0)
5200 {
5201 /* already there */
5202 xfree (copy);
5203 return;
5204 }
5205 }
5206 while ((p = strtok (NULL, ",")) != NULL);
5207 xfree (copy);
5208
94b0dee1
PA
5209 remote_support_xml = reconcat (remote_support_xml,
5210 remote_support_xml, ",", xml,
5211 (char *) NULL);
c8d5aac9
L
5212 }
5213#endif
5214}
5215
69b6ecb0
TT
5216static void
5217remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5218{
69b6ecb0
TT
5219 if (!msg->empty ())
5220 msg->append (";");
5221 msg->append (append);
c8d5aac9
L
5222}
5223
6b8edb51
PA
5224void
5225remote_target::remote_query_supported ()
be2a5f71
DJ
5226{
5227 struct remote_state *rs = get_remote_state ();
5228 char *next;
5229 int i;
5230 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5231
5232 /* The packet support flags are handled differently for this packet
5233 than for most others. We treat an error, a disabled packet, and
5234 an empty response identically: any features which must be reported
5235 to be used will be automatically disabled. An empty buffer
5236 accomplishes this, since that is also the representation for a list
5237 containing no features. */
5238
5239 rs->buf[0] = 0;
4082afcc 5240 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5241 {
69b6ecb0 5242 std::string q;
c8d5aac9 5243
73b8c1fd 5244 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5245 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5246
f7e6eed5 5247 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5248 remote_query_supported_append (&q, "swbreak+");
f7e6eed5 5249 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5250 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5251
69b6ecb0 5252 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5253
8020350c
DB
5254 if (packet_set_cmd_state (PACKET_fork_event_feature)
5255 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5256 remote_query_supported_append (&q, "fork-events+");
8020350c
DB
5257 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5258 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5259 remote_query_supported_append (&q, "vfork-events+");
8020350c
DB
5260 if (packet_set_cmd_state (PACKET_exec_event_feature)
5261 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5262 remote_query_supported_append (&q, "exec-events+");
89245bc0 5263
750ce8d1 5264 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5265 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5266
65706a29 5267 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5268 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5269
f2faf941 5270 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5271 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5272
b35d5edb
PA
5273 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5274 the qSupported:xmlRegisters=i386 handling. */
7cc244de
PA
5275 if (remote_support_xml != NULL
5276 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
69b6ecb0 5277 remote_query_supported_append (&q, remote_support_xml);
82f73884 5278
69b6ecb0
TT
5279 q = "qSupported:" + q;
5280 putpkt (q.c_str ());
94b0dee1 5281
be2a5f71
DJ
5282 getpkt (&rs->buf, &rs->buf_size, 0);
5283
5284 /* If an error occured, warn, but do not return - just reset the
5285 buffer to empty and go on to disable features. */
5286 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5287 == PACKET_ERROR)
5288 {
5289 warning (_("Remote failure reply: %s"), rs->buf);
5290 rs->buf[0] = 0;
5291 }
5292 }
5293
5294 memset (seen, 0, sizeof (seen));
5295
5296 next = rs->buf;
5297 while (*next)
5298 {
5299 enum packet_support is_supported;
5300 char *p, *end, *name_end, *value;
5301
5302 /* First separate out this item from the rest of the packet. If
5303 there's another item after this, we overwrite the separator
5304 (terminated strings are much easier to work with). */
5305 p = next;
5306 end = strchr (p, ';');
5307 if (end == NULL)
5308 {
5309 end = p + strlen (p);
5310 next = end;
5311 }
5312 else
5313 {
89be2091
DJ
5314 *end = '\0';
5315 next = end + 1;
5316
be2a5f71
DJ
5317 if (end == p)
5318 {
5319 warning (_("empty item in \"qSupported\" response"));
5320 continue;
5321 }
be2a5f71
DJ
5322 }
5323
5324 name_end = strchr (p, '=');
5325 if (name_end)
5326 {
5327 /* This is a name=value entry. */
5328 is_supported = PACKET_ENABLE;
5329 value = name_end + 1;
5330 *name_end = '\0';
5331 }
5332 else
5333 {
5334 value = NULL;
5335 switch (end[-1])
5336 {
5337 case '+':
5338 is_supported = PACKET_ENABLE;
5339 break;
5340
5341 case '-':
5342 is_supported = PACKET_DISABLE;
5343 break;
5344
5345 case '?':
5346 is_supported = PACKET_SUPPORT_UNKNOWN;
5347 break;
5348
5349 default:
3e43a32a
MS
5350 warning (_("unrecognized item \"%s\" "
5351 "in \"qSupported\" response"), p);
be2a5f71
DJ
5352 continue;
5353 }
5354 end[-1] = '\0';
5355 }
5356
5357 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5358 if (strcmp (remote_protocol_features[i].name, p) == 0)
5359 {
5360 const struct protocol_feature *feature;
5361
5362 seen[i] = 1;
5363 feature = &remote_protocol_features[i];
6b8edb51 5364 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5365 break;
5366 }
5367 }
5368
5369 /* If we increased the packet size, make sure to increase the global
5370 buffer size also. We delay this until after parsing the entire
5371 qSupported packet, because this is the same buffer we were
5372 parsing. */
5373 if (rs->buf_size < rs->explicit_packet_size)
5374 {
5375 rs->buf_size = rs->explicit_packet_size;
224c3ddb 5376 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
5377 }
5378
5379 /* Handle the defaults for unmentioned features. */
5380 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5381 if (!seen[i])
5382 {
5383 const struct protocol_feature *feature;
5384
5385 feature = &remote_protocol_features[i];
6b8edb51 5386 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5387 }
5388}
5389
048094ac
PA
5390/* Serial QUIT handler for the remote serial descriptor.
5391
5392 Defers handling a Ctrl-C until we're done with the current
5393 command/response packet sequence, unless:
5394
5395 - We're setting up the connection. Don't send a remote interrupt
5396 request, as we're not fully synced yet. Quit immediately
5397 instead.
5398
5399 - The target has been resumed in the foreground
223ffa71 5400 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5401 packet, and we're blocked waiting for the stop reply, thus a
5402 Ctrl-C should be immediately sent to the target.
5403
5404 - We get a second Ctrl-C while still within the same serial read or
5405 write. In that case the serial is seemingly wedged --- offer to
5406 quit/disconnect.
5407
5408 - We see a second Ctrl-C without target response, after having
5409 previously interrupted the target. In that case the target/stub
5410 is probably wedged --- offer to quit/disconnect.
5411*/
5412
6b8edb51
PA
5413void
5414remote_target::remote_serial_quit_handler ()
048094ac
PA
5415{
5416 struct remote_state *rs = get_remote_state ();
5417
5418 if (check_quit_flag ())
5419 {
5420 /* If we're starting up, we're not fully synced yet. Quit
5421 immediately. */
5422 if (rs->starting_up)
5423 quit ();
5424 else if (rs->got_ctrlc_during_io)
5425 {
5426 if (query (_("The target is not responding to GDB commands.\n"
5427 "Stop debugging it? ")))
5428 remote_unpush_and_throw ();
5429 }
5430 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5431 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5432 interrupt_query ();
5433 /* All-stop protocol, and blocked waiting for stop reply. Send
5434 an interrupt request. */
223ffa71 5435 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5436 target_interrupt ();
048094ac
PA
5437 else
5438 rs->got_ctrlc_during_io = 1;
5439 }
5440}
5441
6b8edb51
PA
5442/* The remote_target that is current while the quit handler is
5443 overridden with remote_serial_quit_handler. */
5444static remote_target *curr_quit_handler_target;
5445
5446static void
5447remote_serial_quit_handler ()
5448{
5449 curr_quit_handler_target->remote_serial_quit_handler ();
5450}
5451
78a095c3
JK
5452/* Remove any of the remote.c targets from target stack. Upper targets depend
5453 on it so remove them first. */
5454
5455static void
5456remote_unpush_target (void)
5457{
915ef8b1 5458 pop_all_targets_at_and_above (process_stratum);
78a095c3 5459}
be2a5f71 5460
048094ac
PA
5461static void
5462remote_unpush_and_throw (void)
5463{
5464 remote_unpush_target ();
5465 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5466}
5467
f6ac5f3d
PA
5468void
5469remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5470{
6b8edb51 5471 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5472
c906108c 5473 if (name == 0)
8a3fe4f8 5474 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5475 "serial device is attached to the remote system\n"
8a3fe4f8 5476 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5477
2d717e4f 5478 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5479 Ask this question first, before target_preopen has a chance to kill
5480 anything. */
6b8edb51 5481 if (curr_remote != NULL && !have_inferiors ())
2d717e4f 5482 {
78a095c3
JK
5483 if (from_tty
5484 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5485 error (_("Still connected."));
5486 }
5487
78a095c3 5488 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5489 target_preopen (from_tty);
5490
ad9a8f3f 5491 remote_fileio_reset ();
1dd41f16
NS
5492 reopen_exec_file ();
5493 reread_symbols ();
5494
6b8edb51
PA
5495 remote_target *remote
5496 = (extended_p ? new extended_remote_target () : new remote_target ());
5497 target_ops_up target_holder (remote);
5498
5499 remote_state *rs = remote->get_remote_state ();
5500
5501 /* See FIXME above. */
5502 if (!target_async_permitted)
5503 rs->wait_forever_enabled_p = 1;
5504
5d93a237
TT
5505 rs->remote_desc = remote_serial_open (name);
5506 if (!rs->remote_desc)
c906108c
SS
5507 perror_with_name (name);
5508
5509 if (baud_rate != -1)
5510 {
5d93a237 5511 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5512 {
9b74d5d3
KB
5513 /* The requested speed could not be set. Error out to
5514 top level after closing remote_desc. Take care to
5515 set remote_desc to NULL to avoid closing remote_desc
5516 more than once. */
5d93a237
TT
5517 serial_close (rs->remote_desc);
5518 rs->remote_desc = NULL;
c906108c
SS
5519 perror_with_name (name);
5520 }
5521 }
5522
236af5e3 5523 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5524 serial_raw (rs->remote_desc);
c906108c
SS
5525
5526 /* If there is something sitting in the buffer we might take it as a
5527 response to a command, which would be bad. */
5d93a237 5528 serial_flush_input (rs->remote_desc);
c906108c
SS
5529
5530 if (from_tty)
5531 {
5532 puts_filtered ("Remote debugging using ");
5533 puts_filtered (name);
5534 puts_filtered ("\n");
5535 }
d9f719f1 5536
6b8edb51
PA
5537 /* Switch to using the remote target now. */
5538 push_target (remote);
5539 /* The target stack owns the target now. */
5540 target_holder.release ();
c906108c 5541
74531fed 5542 /* Register extra event sources in the event loop. */
6b8edb51 5543 rs->remote_async_inferior_event_token
74531fed 5544 = create_async_event_handler (remote_async_inferior_event_handler,
6b8edb51
PA
5545 remote);
5546 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 5547
be2a5f71
DJ
5548 /* Reset the target state; these things will be queried either by
5549 remote_query_supported or as they are needed. */
ca4f7f8b 5550 reset_all_packet_configs_support ();
74531fed 5551 rs->cached_wait_status = 0;
be2a5f71 5552 rs->explicit_packet_size = 0;
a6f3e723 5553 rs->noack_mode = 0;
82f73884 5554 rs->extended = extended_p;
e24a49d8 5555 rs->waiting_for_stop_reply = 0;
3a29589a 5556 rs->ctrlc_pending_p = 0;
048094ac 5557 rs->got_ctrlc_during_io = 0;
802188a7 5558
47f8a51d
TT
5559 rs->general_thread = not_sent_ptid;
5560 rs->continue_thread = not_sent_ptid;
262e1174 5561 rs->remote_traceframe_number = -1;
c906108c 5562
3a00c802
PA
5563 rs->last_resume_exec_dir = EXEC_FORWARD;
5564
9d1f7ab2 5565 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5566 rs->use_threadinfo_query = 1;
5567 rs->use_threadextra_query = 1;
9d1f7ab2 5568
dd194f6b 5569 rs->readahead_cache.invalidate ();
80152258 5570
c6ebd6cf 5571 if (target_async_permitted)
92d1e331 5572 {
92d1e331
DJ
5573 /* FIXME: cagney/1999-09-23: During the initial connection it is
5574 assumed that the target is already ready and able to respond to
0df8b418 5575 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5576 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5577 around this. Eventually a mechanism that allows
92d1e331 5578 wait_for_inferior() to expect/get timeouts will be
23860348 5579 implemented. */
6b8edb51 5580 rs->wait_forever_enabled_p = 0;
92d1e331
DJ
5581 }
5582
23860348 5583 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5584 no_shared_libraries (NULL, 0);
f78f6cf1 5585
74531fed
PA
5586 /* Start afresh. */
5587 init_thread_list ();
5588
36918e70 5589 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5590 target (we'd otherwise be in an inconsistent state) and then
5591 propogate the error on up the exception chain. This ensures that
5592 the caller doesn't stumble along blindly assuming that the
5593 function succeeded. The CLI doesn't have this problem but other
5594 UI's, such as MI do.
36918e70
AC
5595
5596 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5597 this function should return an error indication letting the
ce2826aa 5598 caller restore the previous state. Unfortunately the command
36918e70
AC
5599 ``target remote'' is directly wired to this function making that
5600 impossible. On a positive note, the CLI side of this problem has
5601 been fixed - the function set_cmd_context() makes it possible for
5602 all the ``target ....'' commands to share a common callback
5603 function. See cli-dump.c. */
109c3e39 5604 {
2d717e4f 5605
492d29ea 5606 TRY
04bd08de 5607 {
6b8edb51 5608 remote->start_remote (from_tty, extended_p);
04bd08de 5609 }
492d29ea 5610 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5611 {
c8d104ad
PA
5612 /* Pop the partially set up target - unless something else did
5613 already before throwing the exception. */
6b8edb51 5614 if (ex.error != TARGET_CLOSE_ERROR)
78a095c3 5615 remote_unpush_target ();
109c3e39
AC
5616 throw_exception (ex);
5617 }
492d29ea 5618 END_CATCH
109c3e39 5619 }
c906108c 5620
6b8edb51 5621 remote_btrace_reset (rs);
f4abbc16 5622
c6ebd6cf 5623 if (target_async_permitted)
6b8edb51 5624 rs->wait_forever_enabled_p = 1;
43ff13b4
JM
5625}
5626
de0d863e
DB
5627/* Detach the specified process. */
5628
6b8edb51
PA
5629void
5630remote_target::remote_detach_pid (int pid)
de0d863e
DB
5631{
5632 struct remote_state *rs = get_remote_state ();
5633
5634 if (remote_multi_process_p (rs))
5635 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5636 else
5637 strcpy (rs->buf, "D");
5638
5639 putpkt (rs->buf);
5640 getpkt (&rs->buf, &rs->buf_size, 0);
5641
5642 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5643 ;
5644 else if (rs->buf[0] == '\0')
5645 error (_("Remote doesn't know how to detach"));
5646 else
5647 error (_("Can't detach process."));
5648}
5649
5650/* This detaches a program to which we previously attached, using
5651 inferior_ptid to identify the process. After this is done, GDB
5652 can be used to debug some other program. We better not have left
5653 any breakpoints in the target program or it'll die when it hits
5654 one. */
c906108c 5655
6b8edb51
PA
5656void
5657remote_target::remote_detach_1 (int from_tty, inferior *inf)
c906108c 5658{
82f73884 5659 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5660 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5661 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5662 int is_fork_parent;
c906108c 5663
2d717e4f
DJ
5664 if (!target_has_execution)
5665 error (_("No process to detach from."));
5666
0f48b757 5667 target_announce_detach (from_tty);
7cee1e54 5668
c906108c 5669 /* Tell the remote target to detach. */
de0d863e 5670 remote_detach_pid (pid);
82f73884 5671
8020350c
DB
5672 /* Exit only if this is the only active inferior. */
5673 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5674 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5675
de0d863e
DB
5676 /* Check to see if we are detaching a fork parent. Note that if we
5677 are detaching a fork child, tp == NULL. */
5678 is_fork_parent = (tp != NULL
5679 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5680
5681 /* If doing detach-on-fork, we don't mourn, because that will delete
5682 breakpoints that should be available for the followed inferior. */
5683 if (!is_fork_parent)
f67c0c91 5684 {
249b5733
PA
5685 /* Save the pid as a string before mourning, since that will
5686 unpush the remote target, and we need the string after. */
5687 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
f67c0c91
SDJ
5688
5689 target_mourn_inferior (inferior_ptid);
5690 if (print_inferior_events)
5691 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5692 inf->num, infpid.c_str ());
5693 }
de0d863e
DB
5694 else
5695 {
5696 inferior_ptid = null_ptid;
5697 detach_inferior (pid);
5698 }
2d717e4f
DJ
5699}
5700
f6ac5f3d
PA
5701void
5702remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5703{
6e1e1966 5704 remote_detach_1 (from_tty, inf);
2d717e4f
DJ
5705}
5706
f6ac5f3d
PA
5707void
5708extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5709{
6e1e1966 5710 remote_detach_1 (from_tty, inf);
de0d863e
DB
5711}
5712
5713/* Target follow-fork function for remote targets. On entry, and
5714 at return, the current inferior is the fork parent.
5715
5716 Note that although this is currently only used for extended-remote,
5717 it is named remote_follow_fork in anticipation of using it for the
5718 remote target as well. */
5719
f6ac5f3d
PA
5720int
5721remote_target::follow_fork (int follow_child, int detach_fork)
de0d863e
DB
5722{
5723 struct remote_state *rs = get_remote_state ();
c269dbdb 5724 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5725
c269dbdb
DB
5726 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5727 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5728 {
5729 /* When following the parent and detaching the child, we detach
5730 the child here. For the case of following the child and
5731 detaching the parent, the detach is done in the target-
5732 independent follow fork code in infrun.c. We can't use
5733 target_detach when detaching an unfollowed child because
5734 the client side doesn't know anything about the child. */
5735 if (detach_fork && !follow_child)
5736 {
5737 /* Detach the fork child. */
5738 ptid_t child_ptid;
5739 pid_t child_pid;
5740
5741 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5742 child_pid = ptid_get_pid (child_ptid);
5743
5744 remote_detach_pid (child_pid);
de0d863e
DB
5745 }
5746 }
5747 return 0;
c906108c
SS
5748}
5749
94585166
DB
5750/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5751 in the program space of the new inferior. On entry and at return the
5752 current inferior is the exec'ing inferior. INF is the new exec'd
5753 inferior, which may be the same as the exec'ing inferior unless
5754 follow-exec-mode is "new". */
5755
f6ac5f3d
PA
5756void
5757remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
94585166
DB
5758{
5759 /* We know that this is a target file name, so if it has the "target:"
5760 prefix we strip it off before saving it in the program space. */
5761 if (is_target_filename (execd_pathname))
5762 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5763
5764 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5765}
5766
6ad8ae5c
DJ
5767/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5768
f6ac5f3d
PA
5769void
5770remote_target::disconnect (const char *args, int from_tty)
43ff13b4 5771{
43ff13b4 5772 if (args)
2d717e4f 5773 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5774
8020350c
DB
5775 /* Make sure we unpush even the extended remote targets. Calling
5776 target_mourn_inferior won't unpush, and remote_mourn won't
5777 unpush if there is more than one inferior left. */
f6ac5f3d 5778 unpush_target (this);
8020350c 5779 generic_mourn_inferior ();
2d717e4f 5780
43ff13b4
JM
5781 if (from_tty)
5782 puts_filtered ("Ending remote debugging.\n");
5783}
5784
2d717e4f
DJ
5785/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5786 be chatty about it. */
5787
f6ac5f3d
PA
5788void
5789extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
5790{
5791 struct remote_state *rs = get_remote_state ();
be86555c 5792 int pid;
96ef3384 5793 char *wait_status = NULL;
2d717e4f 5794
74164c56 5795 pid = parse_pid_to_attach (args);
2d717e4f 5796
74164c56
JK
5797 /* Remote PID can be freely equal to getpid, do not check it here the same
5798 way as in other targets. */
2d717e4f 5799
4082afcc 5800 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5801 error (_("This target does not support attaching to a process"));
5802
7cee1e54
PA
5803 if (from_tty)
5804 {
5805 char *exec_file = get_exec_file (0);
5806
5807 if (exec_file)
5808 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5809 target_pid_to_str (pid_to_ptid (pid)));
5810 else
5811 printf_unfiltered (_("Attaching to %s\n"),
5812 target_pid_to_str (pid_to_ptid (pid)));
5813
5814 gdb_flush (gdb_stdout);
5815 }
5816
bba74b36 5817 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5818 putpkt (rs->buf);
5819 getpkt (&rs->buf, &rs->buf_size, 0);
5820
4082afcc
PA
5821 switch (packet_ok (rs->buf,
5822 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5823 {
4082afcc 5824 case PACKET_OK:
6efcd9a8 5825 if (!target_is_non_stop_p ())
74531fed
PA
5826 {
5827 /* Save the reply for later. */
224c3ddb 5828 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5829 strcpy (wait_status, rs->buf);
5830 }
5831 else if (strcmp (rs->buf, "OK") != 0)
5832 error (_("Attaching to %s failed with: %s"),
5833 target_pid_to_str (pid_to_ptid (pid)),
5834 rs->buf);
4082afcc
PA
5835 break;
5836 case PACKET_UNKNOWN:
5837 error (_("This target does not support attaching to a process"));
5838 default:
5839 error (_("Attaching to %s failed"),
5840 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5841 }
2d717e4f 5842
1b6e6f5c 5843 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5844
2d717e4f 5845 inferior_ptid = pid_to_ptid (pid);
79d7f229 5846
6efcd9a8 5847 if (target_is_non_stop_p ())
bad34192
PA
5848 {
5849 struct thread_info *thread;
79d7f229 5850
bad34192 5851 /* Get list of threads. */
f6ac5f3d 5852 update_thread_list ();
82f73884 5853
bad34192
PA
5854 thread = first_thread_of_process (pid);
5855 if (thread)
5856 inferior_ptid = thread->ptid;
5857 else
5858 inferior_ptid = pid_to_ptid (pid);
5859
5860 /* Invalidate our notion of the remote current thread. */
47f8a51d 5861 record_currthread (rs, minus_one_ptid);
bad34192 5862 }
74531fed 5863 else
bad34192
PA
5864 {
5865 /* Now, if we have thread information, update inferior_ptid. */
5866 inferior_ptid = remote_current_thread (inferior_ptid);
5867
5868 /* Add the main thread to the thread list. */
00aecdcf
PA
5869 thread_info *thr = add_thread_silent (inferior_ptid);
5870 /* Don't consider the thread stopped until we've processed the
5871 saved stop reply. */
5872 set_executing (thr->ptid, true);
bad34192 5873 }
c0a2216e 5874
96ef3384
UW
5875 /* Next, if the target can specify a description, read it. We do
5876 this before anything involving memory or registers. */
5877 target_find_description ();
5878
6efcd9a8 5879 if (!target_is_non_stop_p ())
74531fed
PA
5880 {
5881 /* Use the previously fetched status. */
5882 gdb_assert (wait_status != NULL);
5883
5884 if (target_can_async_p ())
5885 {
722247f1 5886 struct notif_event *reply
6b8edb51 5887 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 5888
722247f1 5889 push_stop_reply ((struct stop_reply *) reply);
74531fed 5890
6a3753b3 5891 target_async (1);
74531fed
PA
5892 }
5893 else
5894 {
5895 gdb_assert (wait_status != NULL);
5896 strcpy (rs->buf, wait_status);
5897 rs->cached_wait_status = 1;
5898 }
5899 }
5900 else
5901 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5902}
5903
b9c1d481
AS
5904/* Implementation of the to_post_attach method. */
5905
f6ac5f3d
PA
5906void
5907extended_remote_target::post_attach (int pid)
b9c1d481 5908{
6efcd9a8
PA
5909 /* Get text, data & bss offsets. */
5910 get_offsets ();
5911
b9c1d481
AS
5912 /* In certain cases GDB might not have had the chance to start
5913 symbol lookup up until now. This could happen if the debugged
5914 binary is not using shared libraries, the vsyscall page is not
5915 present (on Linux) and the binary itself hadn't changed since the
5916 debugging process was started. */
5917 if (symfile_objfile != NULL)
5918 remote_check_symbols();
5919}
5920
c906108c 5921\f
506fb367
DJ
5922/* Check for the availability of vCont. This function should also check
5923 the response. */
c906108c 5924
6b8edb51
PA
5925void
5926remote_target::remote_vcont_probe ()
c906108c 5927{
6b8edb51 5928 remote_state *rs = get_remote_state ();
2e9f7625 5929 char *buf;
6d820c5c 5930
2e9f7625
DJ
5931 strcpy (rs->buf, "vCont?");
5932 putpkt (rs->buf);
6d820c5c 5933 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5934 buf = rs->buf;
c906108c 5935
506fb367 5936 /* Make sure that the features we assume are supported. */
61012eef 5937 if (startswith (buf, "vCont"))
506fb367
DJ
5938 {
5939 char *p = &buf[5];
750ce8d1 5940 int support_c, support_C;
506fb367 5941
750ce8d1
YQ
5942 rs->supports_vCont.s = 0;
5943 rs->supports_vCont.S = 0;
506fb367
DJ
5944 support_c = 0;
5945 support_C = 0;
d458bd84 5946 rs->supports_vCont.t = 0;
c1e36e3e 5947 rs->supports_vCont.r = 0;
506fb367
DJ
5948 while (p && *p == ';')
5949 {
5950 p++;
5951 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5952 rs->supports_vCont.s = 1;
506fb367 5953 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5954 rs->supports_vCont.S = 1;
506fb367
DJ
5955 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5956 support_c = 1;
5957 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5958 support_C = 1;
74531fed 5959 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5960 rs->supports_vCont.t = 1;
c1e36e3e
PA
5961 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5962 rs->supports_vCont.r = 1;
506fb367
DJ
5963
5964 p = strchr (p, ';');
5965 }
c906108c 5966
750ce8d1
YQ
5967 /* If c, and C are not all supported, we can't use vCont. Clearing
5968 BUF will make packet_ok disable the packet. */
5969 if (!support_c || !support_C)
506fb367
DJ
5970 buf[0] = 0;
5971 }
c906108c 5972
444abaca 5973 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5974}
c906108c 5975
0d8f58ca
PA
5976/* Helper function for building "vCont" resumptions. Write a
5977 resumption to P. ENDP points to one-passed-the-end of the buffer
5978 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5979 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5980 resumed thread should be single-stepped and/or signalled. If PTID
5981 equals minus_one_ptid, then all threads are resumed; if PTID
5982 represents a process, then all threads of the process are resumed;
5983 the thread to be stepped and/or signalled is given in the global
5984 INFERIOR_PTID. */
5985
6b8edb51
PA
5986char *
5987remote_target::append_resumption (char *p, char *endp,
5988 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
5989{
5990 struct remote_state *rs = get_remote_state ();
5991
a493e3e2 5992 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5993 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5994 else if (step
5995 /* GDB is willing to range step. */
5996 && use_range_stepping
5997 /* Target supports range stepping. */
5998 && rs->supports_vCont.r
5999 /* We don't currently support range stepping multiple
6000 threads with a wildcard (though the protocol allows it,
6001 so stubs shouldn't make an active effort to forbid
6002 it). */
6003 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6004 {
6005 struct thread_info *tp;
6006
6007 if (ptid_equal (ptid, minus_one_ptid))
6008 {
6009 /* If we don't know about the target thread's tid, then
6010 we're resuming magic_null_ptid (see caller). */
6011 tp = find_thread_ptid (magic_null_ptid);
6012 }
6013 else
6014 tp = find_thread_ptid (ptid);
6015 gdb_assert (tp != NULL);
6016
6017 if (tp->control.may_range_step)
6018 {
6019 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6020
6021 p += xsnprintf (p, endp - p, ";r%s,%s",
6022 phex_nz (tp->control.step_range_start,
6023 addr_size),
6024 phex_nz (tp->control.step_range_end,
6025 addr_size));
6026 }
6027 else
6028 p += xsnprintf (p, endp - p, ";s");
6029 }
0d8f58ca
PA
6030 else if (step)
6031 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6032 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6033 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6034 else
6035 p += xsnprintf (p, endp - p, ";c");
6036
6037 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
6038 {
6039 ptid_t nptid;
6040
6041 /* All (-1) threads of process. */
ba348170 6042 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
6043
6044 p += xsnprintf (p, endp - p, ":");
6045 p = write_ptid (p, endp, nptid);
6046 }
6047 else if (!ptid_equal (ptid, minus_one_ptid))
6048 {
6049 p += xsnprintf (p, endp - p, ":");
6050 p = write_ptid (p, endp, ptid);
6051 }
6052
6053 return p;
6054}
6055
799a2abe
PA
6056/* Clear the thread's private info on resume. */
6057
6058static void
6059resume_clear_thread_private_info (struct thread_info *thread)
6060{
6061 if (thread->priv != NULL)
6062 {
7aabaf9d
SM
6063 remote_thread_info *priv = get_remote_thread_info (thread);
6064
6065 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6066 priv->watch_data_address = 0;
799a2abe
PA
6067 }
6068}
6069
e5ef252a
PA
6070/* Append a vCont continue-with-signal action for threads that have a
6071 non-zero stop signal. */
6072
6b8edb51
PA
6073char *
6074remote_target::append_pending_thread_resumptions (char *p, char *endp,
6075 ptid_t ptid)
e5ef252a
PA
6076{
6077 struct thread_info *thread;
6078
034f788c 6079 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
6080 if (ptid_match (thread->ptid, ptid)
6081 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 6082 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
6083 {
6084 p = append_resumption (p, endp, thread->ptid,
6085 0, thread->suspend.stop_signal);
6086 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 6087 resume_clear_thread_private_info (thread);
e5ef252a
PA
6088 }
6089
6090 return p;
6091}
6092
7b68ffbb
PA
6093/* Set the target running, using the packets that use Hc
6094 (c/s/C/S). */
6095
6b8edb51
PA
6096void
6097remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6098 gdb_signal siggnal)
7b68ffbb
PA
6099{
6100 struct remote_state *rs = get_remote_state ();
6101 struct thread_info *thread;
6102 char *buf;
6103
6104 rs->last_sent_signal = siggnal;
6105 rs->last_sent_step = step;
6106
6107 /* The c/s/C/S resume packets use Hc, so set the continue
6108 thread. */
6109 if (ptid_equal (ptid, minus_one_ptid))
6110 set_continue_thread (any_thread_ptid);
6111 else
6112 set_continue_thread (ptid);
6113
6114 ALL_NON_EXITED_THREADS (thread)
6115 resume_clear_thread_private_info (thread);
6116
6117 buf = rs->buf;
6b8edb51 6118 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6119 {
6120 /* We don't pass signals to the target in reverse exec mode. */
6121 if (info_verbose && siggnal != GDB_SIGNAL_0)
6122 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6123 siggnal);
6124
6125 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6126 error (_("Remote reverse-step not supported."));
6127 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6128 error (_("Remote reverse-continue not supported."));
6129
6130 strcpy (buf, step ? "bs" : "bc");
6131 }
6132 else if (siggnal != GDB_SIGNAL_0)
6133 {
6134 buf[0] = step ? 'S' : 'C';
6135 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6136 buf[2] = tohex (((int) siggnal) & 0xf);
6137 buf[3] = '\0';
6138 }
6139 else
6140 strcpy (buf, step ? "s" : "c");
6141
6142 putpkt (buf);
6143}
6144
506fb367
DJ
6145/* Resume the remote inferior by using a "vCont" packet. The thread
6146 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
6147 resumed thread should be single-stepped and/or signalled. If PTID
6148 equals minus_one_ptid, then all threads are resumed; the thread to
6149 be stepped and/or signalled is given in the global INFERIOR_PTID.
6150 This function returns non-zero iff it resumes the inferior.
44eaed12 6151
7b68ffbb
PA
6152 This function issues a strict subset of all possible vCont commands
6153 at the moment. */
44eaed12 6154
6b8edb51
PA
6155int
6156remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6157 enum gdb_signal siggnal)
506fb367
DJ
6158{
6159 struct remote_state *rs = get_remote_state ();
82f73884
PA
6160 char *p;
6161 char *endp;
44eaed12 6162
7b68ffbb 6163 /* No reverse execution actions defined for vCont. */
6b8edb51 6164 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6165 return 0;
6166
4082afcc 6167 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6168 remote_vcont_probe ();
44eaed12 6169
4082afcc 6170 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6171 return 0;
44eaed12 6172
82f73884
PA
6173 p = rs->buf;
6174 endp = rs->buf + get_remote_packet_size ();
6175
506fb367
DJ
6176 /* If we could generate a wider range of packets, we'd have to worry
6177 about overflowing BUF. Should there be a generic
6178 "multi-part-packet" packet? */
6179
0d8f58ca
PA
6180 p += xsnprintf (p, endp - p, "vCont");
6181
79d7f229 6182 if (ptid_equal (ptid, magic_null_ptid))
c906108c 6183 {
79d7f229
PA
6184 /* MAGIC_NULL_PTID means that we don't have any active threads,
6185 so we don't have any TID numbers the inferior will
6186 understand. Make sure to only send forms that do not specify
6187 a TID. */
a9cbf802 6188 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6189 }
0d8f58ca 6190 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 6191 {
0d8f58ca
PA
6192 /* Resume all threads (of all processes, or of a single
6193 process), with preference for INFERIOR_PTID. This assumes
6194 inferior_ptid belongs to the set of all threads we are about
6195 to resume. */
a493e3e2 6196 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6197 {
0d8f58ca
PA
6198 /* Step inferior_ptid, with or without signal. */
6199 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6200 }
0d8f58ca 6201
e5ef252a
PA
6202 /* Also pass down any pending signaled resumption for other
6203 threads not the current. */
6204 p = append_pending_thread_resumptions (p, endp, ptid);
6205
0d8f58ca 6206 /* And continue others without a signal. */
a493e3e2 6207 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6208 }
6209 else
506fb367
DJ
6210 {
6211 /* Scheduler locking; resume only PTID. */
a9cbf802 6212 append_resumption (p, endp, ptid, step, siggnal);
506fb367 6213 }
c906108c 6214
82f73884
PA
6215 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6216 putpkt (rs->buf);
506fb367 6217
6efcd9a8 6218 if (target_is_non_stop_p ())
74531fed
PA
6219 {
6220 /* In non-stop, the stub replies to vCont with "OK". The stop
6221 reply will be reported asynchronously by means of a `%Stop'
6222 notification. */
6223 getpkt (&rs->buf, &rs->buf_size, 0);
6224 if (strcmp (rs->buf, "OK") != 0)
6225 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6226 }
6227
506fb367 6228 return 1;
c906108c 6229}
43ff13b4 6230
506fb367
DJ
6231/* Tell the remote machine to resume. */
6232
f6ac5f3d
PA
6233void
6234remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 6235{
d01949b6 6236 struct remote_state *rs = get_remote_state ();
43ff13b4 6237
85ad3aaf
PA
6238 /* When connected in non-stop mode, the core resumes threads
6239 individually. Resuming remote threads directly in target_resume
6240 would thus result in sending one packet per thread. Instead, to
6241 minimize roundtrip latency, here we just store the resume
6242 request; the actual remote resumption will be done in
6243 target_commit_resume / remote_commit_resume, where we'll be able
6244 to do vCont action coalescing. */
f6ac5f3d 6245 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6246 {
7aabaf9d 6247 remote_thread_info *remote_thr;
85ad3aaf
PA
6248
6249 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
7aabaf9d 6250 remote_thr = get_remote_thread_info (inferior_ptid);
85ad3aaf 6251 else
7aabaf9d
SM
6252 remote_thr = get_remote_thread_info (ptid);
6253
85ad3aaf
PA
6254 remote_thr->last_resume_step = step;
6255 remote_thr->last_resume_sig = siggnal;
6256 return;
6257 }
6258
722247f1
YQ
6259 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6260 (explained in remote-notif.c:handle_notification) so
6261 remote_notif_process is not called. We need find a place where
6262 it is safe to start a 'vNotif' sequence. It is good to do it
6263 before resuming inferior, because inferior was stopped and no RSP
6264 traffic at that moment. */
6efcd9a8 6265 if (!target_is_non_stop_p ())
5965e028 6266 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6267
f6ac5f3d 6268 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6269
7b68ffbb
PA
6270 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6271 if (!remote_resume_with_vcont (ptid, step, siggnal))
6b8edb51 6272 remote_resume_with_hc (ptid, step, siggnal);
43ff13b4 6273
2acceee2 6274 /* We are about to start executing the inferior, let's register it
0df8b418
MS
6275 with the event loop. NOTE: this is the one place where all the
6276 execution commands end up. We could alternatively do this in each
23860348 6277 of the execution commands in infcmd.c. */
2acceee2
JM
6278 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6279 into infcmd.c in order to allow inferior function calls to work
23860348 6280 NOT asynchronously. */
362646f5 6281 if (target_can_async_p ())
6a3753b3 6282 target_async (1);
e24a49d8
PA
6283
6284 /* We've just told the target to resume. The remote server will
6285 wait for the inferior to stop, and then send a stop reply. In
6286 the mean time, we can't start another command/query ourselves
74531fed
PA
6287 because the stub wouldn't be ready to process it. This applies
6288 only to the base all-stop protocol, however. In non-stop (which
6289 only supports vCont), the stub replies with an "OK", and is
6290 immediate able to process further serial input. */
6efcd9a8 6291 if (!target_is_non_stop_p ())
74531fed 6292 rs->waiting_for_stop_reply = 1;
43ff13b4 6293}
85ad3aaf 6294
85ad3aaf
PA
6295static int is_pending_fork_parent_thread (struct thread_info *thread);
6296
6297/* Private per-inferior info for target remote processes. */
6298
089354bb 6299struct remote_inferior : public private_inferior
85ad3aaf
PA
6300{
6301 /* Whether we can send a wildcard vCont for this process. */
089354bb 6302 bool may_wildcard_vcont = true;
85ad3aaf
PA
6303};
6304
089354bb
SM
6305/* Get the remote private inferior data associated to INF. */
6306
6307static remote_inferior *
6308get_remote_inferior (inferior *inf)
6309{
6310 if (inf->priv == NULL)
6311 inf->priv.reset (new remote_inferior);
6312
6313 return static_cast<remote_inferior *> (inf->priv.get ());
6314}
6315
f5db4863 6316/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6317 outgoing packet buffer. This is used to send multiple vCont
6318 packets if we have more actions than would fit a single packet. */
6319
f5db4863 6320class vcont_builder
85ad3aaf 6321{
f5db4863 6322public:
6b8edb51
PA
6323 explicit vcont_builder (remote_target *remote)
6324 : m_remote (remote)
f5db4863
PA
6325 {
6326 restart ();
6327 }
6328
6329 void flush ();
6330 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6331
6332private:
6333 void restart ();
6334
6b8edb51
PA
6335 /* The remote target. */
6336 remote_target *m_remote;
6337
85ad3aaf
PA
6338 /* Pointer to the first action. P points here if no action has been
6339 appended yet. */
f5db4863 6340 char *m_first_action;
85ad3aaf
PA
6341
6342 /* Where the next action will be appended. */
f5db4863 6343 char *m_p;
85ad3aaf
PA
6344
6345 /* The end of the buffer. Must never write past this. */
f5db4863 6346 char *m_endp;
85ad3aaf
PA
6347};
6348
6349/* Prepare the outgoing buffer for a new vCont packet. */
6350
f5db4863
PA
6351void
6352vcont_builder::restart ()
85ad3aaf 6353{
6b8edb51 6354 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6355
f5db4863 6356 m_p = rs->buf;
6b8edb51 6357 m_endp = rs->buf + m_remote->get_remote_packet_size ();
f5db4863
PA
6358 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6359 m_first_action = m_p;
85ad3aaf
PA
6360}
6361
6362/* If the vCont packet being built has any action, send it to the
6363 remote end. */
6364
f5db4863
PA
6365void
6366vcont_builder::flush ()
85ad3aaf
PA
6367{
6368 struct remote_state *rs;
6369
f5db4863 6370 if (m_p == m_first_action)
85ad3aaf
PA
6371 return;
6372
6b8edb51
PA
6373 rs = m_remote->get_remote_state ();
6374 m_remote->putpkt (rs->buf);
6375 m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
85ad3aaf
PA
6376 if (strcmp (rs->buf, "OK") != 0)
6377 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6378}
6379
6380/* The largest action is range-stepping, with its two addresses. This
6381 is more than sufficient. If a new, bigger action is created, it'll
6382 quickly trigger a failed assertion in append_resumption (and we'll
6383 just bump this). */
6384#define MAX_ACTION_SIZE 200
6385
6386/* Append a new vCont action in the outgoing packet being built. If
6387 the action doesn't fit the packet along with previous actions, push
6388 what we've got so far to the remote end and start over a new vCont
6389 packet (with the new action). */
6390
f5db4863
PA
6391void
6392vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6393{
6394 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6395
6b8edb51
PA
6396 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6397 ptid, step, siggnal);
85ad3aaf
PA
6398
6399 /* Check whether this new action would fit in the vCont packet along
6400 with previous actions. If not, send what we've got so far and
6401 start a new vCont packet. */
f5db4863
PA
6402 size_t rsize = endp - buf;
6403 if (rsize > m_endp - m_p)
85ad3aaf 6404 {
f5db4863
PA
6405 flush ();
6406 restart ();
85ad3aaf
PA
6407
6408 /* Should now fit. */
f5db4863 6409 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6410 }
6411
f5db4863
PA
6412 memcpy (m_p, buf, rsize);
6413 m_p += rsize;
6414 *m_p = '\0';
85ad3aaf
PA
6415}
6416
6417/* to_commit_resume implementation. */
6418
f6ac5f3d
PA
6419void
6420remote_target::commit_resume ()
85ad3aaf 6421{
85ad3aaf
PA
6422 struct inferior *inf;
6423 struct thread_info *tp;
6424 int any_process_wildcard;
6425 int may_global_wildcard_vcont;
85ad3aaf
PA
6426
6427 /* If connected in all-stop mode, we'd send the remote resume
6428 request directly from remote_resume. Likewise if
6429 reverse-debugging, as there are no defined vCont actions for
6430 reverse execution. */
f6ac5f3d 6431 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6432 return;
6433
6434 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6435 instead of resuming all threads of each process individually.
6436 However, if any thread of a process must remain halted, we can't
6437 send wildcard resumes and must send one action per thread.
6438
6439 Care must be taken to not resume threads/processes the server
6440 side already told us are stopped, but the core doesn't know about
6441 yet, because the events are still in the vStopped notification
6442 queue. For example:
6443
6444 #1 => vCont s:p1.1;c
6445 #2 <= OK
6446 #3 <= %Stopped T05 p1.1
6447 #4 => vStopped
6448 #5 <= T05 p1.2
6449 #6 => vStopped
6450 #7 <= OK
6451 #8 (infrun handles the stop for p1.1 and continues stepping)
6452 #9 => vCont s:p1.1;c
6453
6454 The last vCont above would resume thread p1.2 by mistake, because
6455 the server has no idea that the event for p1.2 had not been
6456 handled yet.
6457
6458 The server side must similarly ignore resume actions for the
6459 thread that has a pending %Stopped notification (and any other
6460 threads with events pending), until GDB acks the notification
6461 with vStopped. Otherwise, e.g., the following case is
6462 mishandled:
6463
6464 #1 => g (or any other packet)
6465 #2 <= [registers]
6466 #3 <= %Stopped T05 p1.2
6467 #4 => vCont s:p1.1;c
6468 #5 <= OK
6469
6470 Above, the server must not resume thread p1.2. GDB can't know
6471 that p1.2 stopped until it acks the %Stopped notification, and
6472 since from GDB's perspective all threads should be running, it
6473 sends a "c" action.
6474
6475 Finally, special care must also be given to handling fork/vfork
6476 events. A (v)fork event actually tells us that two processes
6477 stopped -- the parent and the child. Until we follow the fork,
6478 we must not resume the child. Therefore, if we have a pending
6479 fork follow, we must not send a global wildcard resume action
6480 (vCont;c). We can still send process-wide wildcards though. */
6481
6482 /* Start by assuming a global wildcard (vCont;c) is possible. */
6483 may_global_wildcard_vcont = 1;
6484
6485 /* And assume every process is individually wildcard-able too. */
6486 ALL_NON_EXITED_INFERIORS (inf)
6487 {
089354bb
SM
6488 remote_inferior *priv = get_remote_inferior (inf);
6489
6490 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6491 }
6492
6493 /* Check for any pending events (not reported or processed yet) and
6494 disable process and global wildcard resumes appropriately. */
6495 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6496
6497 ALL_NON_EXITED_THREADS (tp)
6498 {
6499 /* If a thread of a process is not meant to be resumed, then we
6500 can't wildcard that process. */
6501 if (!tp->executing)
6502 {
089354bb 6503 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6504
6505 /* And if we can't wildcard a process, we can't wildcard
6506 everything either. */
6507 may_global_wildcard_vcont = 0;
6508 continue;
6509 }
6510
6511 /* If a thread is the parent of an unfollowed fork, then we
6512 can't do a global wildcard, as that would resume the fork
6513 child. */
6514 if (is_pending_fork_parent_thread (tp))
6515 may_global_wildcard_vcont = 0;
6516 }
6517
6518 /* Now let's build the vCont packet(s). Actions must be appended
6519 from narrower to wider scopes (thread -> process -> global). If
6520 we end up with too many actions for a single packet vcont_builder
6521 flushes the current vCont packet to the remote side and starts a
6522 new one. */
6b8edb51 6523 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
6524
6525 /* Threads first. */
6526 ALL_NON_EXITED_THREADS (tp)
6527 {
7aabaf9d 6528 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf
PA
6529
6530 if (!tp->executing || remote_thr->vcont_resumed)
6531 continue;
6532
6533 gdb_assert (!thread_is_in_step_over_chain (tp));
6534
6535 if (!remote_thr->last_resume_step
6536 && remote_thr->last_resume_sig == GDB_SIGNAL_0
089354bb 6537 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
85ad3aaf
PA
6538 {
6539 /* We'll send a wildcard resume instead. */
6540 remote_thr->vcont_resumed = 1;
6541 continue;
6542 }
6543
f5db4863 6544 vcont_builder.push_action (tp->ptid,
85ad3aaf
PA
6545 remote_thr->last_resume_step,
6546 remote_thr->last_resume_sig);
6547 remote_thr->vcont_resumed = 1;
6548 }
6549
6550 /* Now check whether we can send any process-wide wildcard. This is
6551 to avoid sending a global wildcard in the case nothing is
6552 supposed to be resumed. */
6553 any_process_wildcard = 0;
6554
6555 ALL_NON_EXITED_INFERIORS (inf)
6556 {
089354bb 6557 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf
PA
6558 {
6559 any_process_wildcard = 1;
6560 break;
6561 }
6562 }
6563
6564 if (any_process_wildcard)
6565 {
6566 /* If all processes are wildcard-able, then send a single "c"
6567 action, otherwise, send an "all (-1) threads of process"
6568 continue action for each running process, if any. */
6569 if (may_global_wildcard_vcont)
6570 {
f5db4863
PA
6571 vcont_builder.push_action (minus_one_ptid,
6572 false, GDB_SIGNAL_0);
85ad3aaf
PA
6573 }
6574 else
6575 {
6576 ALL_NON_EXITED_INFERIORS (inf)
6577 {
089354bb 6578 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6579 {
f5db4863
PA
6580 vcont_builder.push_action (pid_to_ptid (inf->pid),
6581 false, GDB_SIGNAL_0);
85ad3aaf
PA
6582 }
6583 }
6584 }
6585 }
6586
f5db4863 6587 vcont_builder.flush ();
85ad3aaf
PA
6588}
6589
c906108c 6590\f
43ff13b4 6591
74531fed
PA
6592/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6593 thread, all threads of a remote process, or all threads of all
6594 processes. */
6595
6b8edb51
PA
6596void
6597remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
6598{
6599 struct remote_state *rs = get_remote_state ();
6600 char *p = rs->buf;
6601 char *endp = rs->buf + get_remote_packet_size ();
74531fed 6602
4082afcc 6603 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6604 remote_vcont_probe ();
74531fed 6605
d458bd84 6606 if (!rs->supports_vCont.t)
74531fed
PA
6607 error (_("Remote server does not support stopping threads"));
6608
f91d3df5
PA
6609 if (ptid_equal (ptid, minus_one_ptid)
6610 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
6611 p += xsnprintf (p, endp - p, "vCont;t");
6612 else
6613 {
6614 ptid_t nptid;
6615
74531fed
PA
6616 p += xsnprintf (p, endp - p, "vCont;t:");
6617
6618 if (ptid_is_pid (ptid))
6619 /* All (-1) threads of process. */
ba348170 6620 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
6621 else
6622 {
6623 /* Small optimization: if we already have a stop reply for
6624 this thread, no use in telling the stub we want this
6625 stopped. */
6626 if (peek_stop_reply (ptid))
6627 return;
6628
6629 nptid = ptid;
6630 }
6631
a9cbf802 6632 write_ptid (p, endp, nptid);
74531fed
PA
6633 }
6634
6635 /* In non-stop, we get an immediate OK reply. The stop reply will
6636 come in asynchronously by notification. */
6637 putpkt (rs->buf);
6638 getpkt (&rs->buf, &rs->buf_size, 0);
6639 if (strcmp (rs->buf, "OK") != 0)
6640 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6641}
6642
bfedc46a
PA
6643/* All-stop version of target_interrupt. Sends a break or a ^C to
6644 interrupt the remote target. It is undefined which thread of which
6645 process reports the interrupt. */
74531fed 6646
6b8edb51
PA
6647void
6648remote_target::remote_interrupt_as ()
74531fed
PA
6649{
6650 struct remote_state *rs = get_remote_state ();
6651
3a29589a
DJ
6652 rs->ctrlc_pending_p = 1;
6653
74531fed
PA
6654 /* If the inferior is stopped already, but the core didn't know
6655 about it yet, just ignore the request. The cached wait status
6656 will be collected in remote_wait. */
6657 if (rs->cached_wait_status)
6658 return;
6659
9a7071a8
JB
6660 /* Send interrupt_sequence to remote target. */
6661 send_interrupt_sequence ();
74531fed
PA
6662}
6663
de979965
PA
6664/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6665 the remote target. It is undefined which thread of which process
e42de8c7
PA
6666 reports the interrupt. Throws an error if the packet is not
6667 supported by the server. */
de979965 6668
6b8edb51
PA
6669void
6670remote_target::remote_interrupt_ns ()
de979965
PA
6671{
6672 struct remote_state *rs = get_remote_state ();
6673 char *p = rs->buf;
6674 char *endp = rs->buf + get_remote_packet_size ();
6675
6676 xsnprintf (p, endp - p, "vCtrlC");
6677
6678 /* In non-stop, we get an immediate OK reply. The stop reply will
6679 come in asynchronously by notification. */
6680 putpkt (rs->buf);
6681 getpkt (&rs->buf, &rs->buf_size, 0);
6682
6683 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6684 {
6685 case PACKET_OK:
6686 break;
6687 case PACKET_UNKNOWN:
e42de8c7 6688 error (_("No support for interrupting the remote target."));
de979965
PA
6689 case PACKET_ERROR:
6690 error (_("Interrupting target failed: %s"), rs->buf);
6691 }
de979965
PA
6692}
6693
bfedc46a 6694/* Implement the to_stop function for the remote targets. */
74531fed 6695
f6ac5f3d
PA
6696void
6697remote_target::stop (ptid_t ptid)
c906108c 6698{
7a292a7a 6699 if (remote_debug)
0f71a2f6 6700 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6701
6efcd9a8 6702 if (target_is_non_stop_p ())
74531fed 6703 remote_stop_ns (ptid);
c906108c 6704 else
bfedc46a
PA
6705 {
6706 /* We don't currently have a way to transparently pause the
6707 remote target in all-stop mode. Interrupt it instead. */
de979965 6708 remote_interrupt_as ();
bfedc46a
PA
6709 }
6710}
6711
6712/* Implement the to_interrupt function for the remote targets. */
6713
f6ac5f3d
PA
6714void
6715remote_target::interrupt ()
bfedc46a
PA
6716{
6717 if (remote_debug)
6718 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6719
e42de8c7
PA
6720 if (target_is_non_stop_p ())
6721 remote_interrupt_ns ();
bfedc46a 6722 else
e42de8c7 6723 remote_interrupt_as ();
c906108c
SS
6724}
6725
93692b58
PA
6726/* Implement the to_pass_ctrlc function for the remote targets. */
6727
f6ac5f3d
PA
6728void
6729remote_target::pass_ctrlc ()
93692b58
PA
6730{
6731 struct remote_state *rs = get_remote_state ();
6732
6733 if (remote_debug)
6734 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6735
6736 /* If we're starting up, we're not fully synced yet. Quit
6737 immediately. */
6738 if (rs->starting_up)
6739 quit ();
6740 /* If ^C has already been sent once, offer to disconnect. */
6741 else if (rs->ctrlc_pending_p)
6742 interrupt_query ();
6743 else
e671cd59 6744 target_interrupt ();
93692b58
PA
6745}
6746
c906108c
SS
6747/* Ask the user what to do when an interrupt is received. */
6748
6b8edb51
PA
6749void
6750remote_target::interrupt_query ()
c906108c 6751{
abc56d60 6752 struct remote_state *rs = get_remote_state ();
c906108c 6753
abc56d60 6754 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6755 {
abc56d60
PA
6756 if (query (_("The target is not responding to interrupt requests.\n"
6757 "Stop debugging it? ")))
74531fed 6758 {
78a095c3 6759 remote_unpush_target ();
abc56d60 6760 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6761 }
6762 }
abc56d60
PA
6763 else
6764 {
6765 if (query (_("Interrupted while waiting for the program.\n"
6766 "Give up waiting? ")))
6767 quit ();
6768 }
c906108c
SS
6769}
6770
6426a772
JM
6771/* Enable/disable target terminal ownership. Most targets can use
6772 terminal groups to control terminal ownership. Remote targets are
6773 different in that explicit transfer of ownership to/from GDB/target
23860348 6774 is required. */
6426a772 6775
f6ac5f3d
PA
6776void
6777remote_target::terminal_inferior ()
6426a772 6778{
6426a772
JM
6779 /* NOTE: At this point we could also register our selves as the
6780 recipient of all input. Any characters typed could then be
23860348 6781 passed on down to the target. */
6426a772
JM
6782}
6783
f6ac5f3d
PA
6784void
6785remote_target::terminal_ours ()
6426a772 6786{
6426a772
JM
6787}
6788
176a6961 6789static void
917317f4 6790remote_console_output (char *msg)
c906108c
SS
6791{
6792 char *p;
6793
c5aa993b 6794 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6795 {
6796 char tb[2];
6797 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6798
c906108c
SS
6799 tb[0] = c;
6800 tb[1] = 0;
43ff13b4 6801 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6802 }
00db5b94
PA
6803 gdb_flush (gdb_stdtarg);
6804}
74531fed 6805
74531fed
PA
6806DEF_VEC_O(cached_reg_t);
6807
722247f1 6808typedef struct stop_reply
74531fed 6809{
722247f1 6810 struct notif_event base;
74531fed 6811
722247f1 6812 /* The identifier of the thread about this event */
74531fed
PA
6813 ptid_t ptid;
6814
340e3c99 6815 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6816 connection, represented by a remote_state object, is closed,
6817 all the associated stop_reply events should be released. */
6818 struct remote_state *rs;
6819
74531fed
PA
6820 struct target_waitstatus ws;
6821
5cd63fda
PA
6822 /* The architecture associated with the expedited registers. */
6823 gdbarch *arch;
6824
15148d6a
PA
6825 /* Expedited registers. This makes remote debugging a bit more
6826 efficient for those targets that provide critical registers as
6827 part of their normal status mechanism (as another roundtrip to
6828 fetch them is avoided). */
74531fed
PA
6829 VEC(cached_reg_t) *regcache;
6830
f7e6eed5
PA
6831 enum target_stop_reason stop_reason;
6832
74531fed
PA
6833 CORE_ADDR watch_data_address;
6834
dc146f7c 6835 int core;
722247f1 6836} *stop_reply_p;
a744cf53 6837
74531fed
PA
6838static void
6839stop_reply_xfree (struct stop_reply *r)
6840{
f48ff2a7 6841 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6842}
6843
221e1a37
PA
6844/* Return the length of the stop reply queue. */
6845
6b8edb51
PA
6846int
6847remote_target::stop_reply_queue_length ()
221e1a37 6848{
6b8edb51 6849 remote_state *rs = get_remote_state ();
953edf2b 6850 return rs->stop_reply_queue.size ();
221e1a37
PA
6851}
6852
6b8edb51
PA
6853void
6854remote_notif_stop_parse (remote_target *remote,
6855 struct notif_client *self, char *buf,
722247f1
YQ
6856 struct notif_event *event)
6857{
6b8edb51 6858 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
6859}
6860
6861static void
6b8edb51
PA
6862remote_notif_stop_ack (remote_target *remote,
6863 struct notif_client *self, char *buf,
722247f1
YQ
6864 struct notif_event *event)
6865{
6866 struct stop_reply *stop_reply = (struct stop_reply *) event;
6867
6868 /* acknowledge */
6b8edb51 6869 putpkt (remote, self->ack_command);
722247f1
YQ
6870
6871 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6b8edb51 6872 {
722247f1
YQ
6873 /* We got an unknown stop reply. */
6874 error (_("Unknown stop reply"));
6b8edb51 6875 }
722247f1 6876
6b8edb51 6877 remote->push_stop_reply (stop_reply);
722247f1
YQ
6878}
6879
6880static int
6b8edb51
PA
6881remote_notif_stop_can_get_pending_events (remote_target *remote,
6882 struct notif_client *self)
722247f1
YQ
6883{
6884 /* We can't get pending events in remote_notif_process for
6885 notification stop, and we have to do this in remote_wait_ns
6886 instead. If we fetch all queued events from stub, remote stub
6887 may exit and we have no chance to process them back in
6888 remote_wait_ns. */
6b8edb51
PA
6889 remote_state *rs = remote->get_remote_state ();
6890 mark_async_event_handler (rs->remote_async_inferior_event_token);
722247f1
YQ
6891 return 0;
6892}
6893
6894static void
6895stop_reply_dtr (struct notif_event *event)
6896{
6897 struct stop_reply *r = (struct stop_reply *) event;
d1dff226
AH
6898 cached_reg_t *reg;
6899 int ix;
6900
6901 for (ix = 0;
6902 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6903 ix++)
6904 xfree (reg->data);
722247f1
YQ
6905
6906 VEC_free (cached_reg_t, r->regcache);
6907}
6908
6909static struct notif_event *
6910remote_notif_stop_alloc_reply (void)
6911{
8d749320
SM
6912 /* We cast to a pointer to the "base class". */
6913 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6914
6915 r->dtr = stop_reply_dtr;
6916
6917 return r;
6918}
6919
6920/* A client of notification Stop. */
6921
6922struct notif_client notif_client_stop =
6923{
6924 "Stop",
6925 "vStopped",
6926 remote_notif_stop_parse,
6927 remote_notif_stop_ack,
6928 remote_notif_stop_can_get_pending_events,
6929 remote_notif_stop_alloc_reply,
f48ff2a7 6930 REMOTE_NOTIF_STOP,
722247f1
YQ
6931};
6932
85ad3aaf 6933/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6934 the pid of the process that owns the threads we want to check, or
6935 -1 if we want to check all threads. */
6936
6937static int
6938is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6939 ptid_t thread_ptid)
6940{
6941 if (ws->kind == TARGET_WAITKIND_FORKED
6942 || ws->kind == TARGET_WAITKIND_VFORKED)
6943 {
6944 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6945 return 1;
6946 }
6947
6948 return 0;
6949}
6950
85ad3aaf
PA
6951/* Return the thread's pending status used to determine whether the
6952 thread is a fork parent stopped at a fork event. */
6953
6954static struct target_waitstatus *
6955thread_pending_fork_status (struct thread_info *thread)
6956{
6957 if (thread->suspend.waitstatus_pending_p)
6958 return &thread->suspend.waitstatus;
6959 else
6960 return &thread->pending_follow;
6961}
6962
6963/* Determine if THREAD is a pending fork parent thread. */
6964
6965static int
6966is_pending_fork_parent_thread (struct thread_info *thread)
6967{
6968 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6969 int pid = -1;
6970
6971 return is_pending_fork_parent (ws, pid, thread->ptid);
6972}
6973
cbb8991c
DB
6974/* If CONTEXT contains any fork child threads that have not been
6975 reported yet, remove them from the CONTEXT list. If such a
6976 thread exists it is because we are stopped at a fork catchpoint
6977 and have not yet called follow_fork, which will set up the
6978 host-side data structures for the new process. */
6979
6b8edb51
PA
6980void
6981remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c
DB
6982{
6983 struct thread_info * thread;
6984 int pid = -1;
6985 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
6986
6987 /* For any threads stopped at a fork event, remove the corresponding
6988 fork child threads from the CONTEXT list. */
6989 ALL_NON_EXITED_THREADS (thread)
6990 {
85ad3aaf 6991 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
6992
6993 if (is_pending_fork_parent (ws, pid, thread->ptid))
21fe1c75 6994 context->remove_thread (ws->value.related_pid);
cbb8991c
DB
6995 }
6996
6997 /* Check for any pending fork events (not reported or processed yet)
6998 in process PID and remove those fork child threads from the
6999 CONTEXT list as well. */
7000 remote_notif_get_pending_events (notif);
953edf2b
TT
7001 for (auto &event : get_remote_state ()->stop_reply_queue)
7002 if (event->ws.kind == TARGET_WAITKIND_FORKED
7003 || event->ws.kind == TARGET_WAITKIND_VFORKED
7004 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7005 context->remove_thread (event->ws.value.related_pid);
85ad3aaf
PA
7006}
7007
7008/* Check whether any event pending in the vStopped queue would prevent
7009 a global or process wildcard vCont action. Clear
7010 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7011 and clear the event inferior's may_wildcard_vcont flag if we can't
7012 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7013
6b8edb51
PA
7014void
7015remote_target::check_pending_events_prevent_wildcard_vcont
7016 (int *may_global_wildcard)
85ad3aaf
PA
7017{
7018 struct notif_client *notif = &notif_client_stop;
7019
7020 remote_notif_get_pending_events (notif);
953edf2b
TT
7021 for (auto &event : get_remote_state ()->stop_reply_queue)
7022 {
7023 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7024 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7025 continue;
85ad3aaf 7026
953edf2b
TT
7027 if (event->ws.kind == TARGET_WAITKIND_FORKED
7028 || event->ws.kind == TARGET_WAITKIND_VFORKED)
7029 *may_global_wildcard = 0;
722247f1 7030
953edf2b 7031 struct inferior *inf = find_inferior_ptid (event->ptid);
722247f1 7032
953edf2b
TT
7033 /* This may be the first time we heard about this process.
7034 Regardless, we must not do a global wildcard resume, otherwise
7035 we'd resume this process too. */
7036 *may_global_wildcard = 0;
7037 if (inf != NULL)
7038 get_remote_inferior (inf)->may_wildcard_vcont = false;
722247f1 7039 }
722247f1
YQ
7040}
7041
f48ff2a7 7042/* Discard all pending stop replies of inferior INF. */
c906108c 7043
6b8edb51
PA
7044void
7045remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7046{
f48ff2a7
YQ
7047 struct stop_reply *reply;
7048 struct remote_state *rs = get_remote_state ();
7049 struct remote_notif_state *rns = rs->notif_state;
7050
7051 /* This function can be notified when an inferior exists. When the
7052 target is not remote, the notification state is NULL. */
7053 if (rs->remote_desc == NULL)
7054 return;
7055
7056 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7057
74531fed 7058 /* Discard the in-flight notification. */
f48ff2a7 7059 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 7060 {
722247f1 7061 stop_reply_xfree (reply);
f48ff2a7 7062 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 7063 }
c906108c 7064
74531fed
PA
7065 /* Discard the stop replies we have already pulled with
7066 vStopped. */
953edf2b
TT
7067 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7068 rs->stop_reply_queue.end (),
7069 [=] (const stop_reply_up &event)
7070 {
7071 return event->ptid.pid () == inf->pid;
7072 });
7073 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
bcc75809
YQ
7074}
7075
7076/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7077
6b8edb51
PA
7078void
7079remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7080{
6b8edb51 7081 remote_state *rs = get_remote_state ();
f48ff2a7 7082
f48ff2a7
YQ
7083 /* Discard the stop replies we have already pulled with
7084 vStopped. */
953edf2b
TT
7085 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7086 rs->stop_reply_queue.end (),
7087 [=] (const stop_reply_up &event)
7088 {
7089 return event->rs == rs;
7090 });
7091 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
74531fed 7092}
43ff13b4 7093
722247f1
YQ
7094/* Remove the first reply in 'stop_reply_queue' which matches
7095 PTID. */
2e9f7625 7096
6b8edb51
PA
7097struct stop_reply *
7098remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7099{
953edf2b 7100 remote_state *rs = get_remote_state ();
722247f1 7101
953edf2b
TT
7102 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7103 rs->stop_reply_queue.end (),
7104 [=] (const stop_reply_up &event)
7105 {
7106 return event->ptid.matches (ptid);
7107 });
7108 struct stop_reply *result;
7109 if (iter == rs->stop_reply_queue.end ())
7110 result = nullptr;
7111 else
7112 {
7113 result = iter->release ();
7114 rs->stop_reply_queue.erase (iter);
7115 }
722247f1 7116
722247f1
YQ
7117 if (notif_debug)
7118 fprintf_unfiltered (gdb_stdlog,
7119 "notif: discard queued event: 'Stop' in %s\n",
7120 target_pid_to_str (ptid));
a744cf53 7121
953edf2b 7122 return result;
74531fed 7123}
75c99385 7124
74531fed
PA
7125/* Look for a queued stop reply belonging to PTID. If one is found,
7126 remove it from the queue, and return it. Returns NULL if none is
7127 found. If there are still queued events left to process, tell the
7128 event loop to get back to target_wait soon. */
e24a49d8 7129
6b8edb51
PA
7130struct stop_reply *
7131remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7132{
953edf2b 7133 remote_state *rs = get_remote_state ();
722247f1 7134 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7135
953edf2b 7136 if (!rs->stop_reply_queue.empty ())
6b8edb51 7137 {
6b8edb51
PA
7138 /* There's still at least an event left. */
7139 mark_async_event_handler (rs->remote_async_inferior_event_token);
7140 }
74531fed 7141
722247f1 7142 return r;
74531fed
PA
7143}
7144
7145/* Push a fully parsed stop reply in the stop reply queue. Since we
7146 know that we now have at least one queued event left to pass to the
7147 core side, tell the event loop to get back to target_wait soon. */
7148
6b8edb51
PA
7149void
7150remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7151{
6b8edb51 7152 remote_state *rs = get_remote_state ();
953edf2b 7153 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
74531fed 7154
722247f1
YQ
7155 if (notif_debug)
7156 fprintf_unfiltered (gdb_stdlog,
7157 "notif: push 'Stop' %s to queue %d\n",
7158 target_pid_to_str (new_event->ptid),
953edf2b 7159 int (rs->stop_reply_queue.size ()));
74531fed 7160
6b8edb51 7161 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
7162}
7163
7164/* Returns true if we have a stop reply for PTID. */
7165
6b8edb51
PA
7166int
7167remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7168{
6b8edb51 7169 remote_state *rs = get_remote_state ();
953edf2b
TT
7170 for (auto &event : rs->stop_reply_queue)
7171 if (ptid == event->ptid
7172 && event->ws.kind == TARGET_WAITKIND_STOPPED)
7173 return 1;
7174 return 0;
74531fed
PA
7175}
7176
26d56a93
SL
7177/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7178 starting with P and ending with PEND matches PREFIX. */
7179
7180static int
7181strprefix (const char *p, const char *pend, const char *prefix)
7182{
7183 for ( ; p < pend; p++, prefix++)
7184 if (*p != *prefix)
7185 return 0;
7186 return *prefix == '\0';
7187}
7188
74531fed
PA
7189/* Parse the stop reply in BUF. Either the function succeeds, and the
7190 result is stored in EVENT, or throws an error. */
7191
6b8edb51
PA
7192void
7193remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
74531fed 7194{
5cd63fda 7195 remote_arch_state *rsa = NULL;
74531fed 7196 ULONGEST addr;
256642e8 7197 const char *p;
94585166 7198 int skipregs = 0;
74531fed
PA
7199
7200 event->ptid = null_ptid;
bcc75809 7201 event->rs = get_remote_state ();
74531fed
PA
7202 event->ws.kind = TARGET_WAITKIND_IGNORE;
7203 event->ws.value.integer = 0;
f7e6eed5 7204 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 7205 event->regcache = NULL;
dc146f7c 7206 event->core = -1;
74531fed
PA
7207
7208 switch (buf[0])
7209 {
7210 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7211 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7212 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7213 ss = signal number
7214 n... = register number
7215 r... = register contents
7216 */
7217
7218 p = &buf[3]; /* after Txx */
7219 while (*p)
7220 {
256642e8 7221 const char *p1;
cea39f65 7222 int fieldsize;
43ff13b4 7223
1f10ba14
PA
7224 p1 = strchr (p, ':');
7225 if (p1 == NULL)
7226 error (_("Malformed packet(a) (missing colon): %s\n\
7227Packet: '%s'\n"),
7228 p, buf);
7229 if (p == p1)
7230 error (_("Malformed packet(a) (missing register number): %s\n\
7231Packet: '%s'\n"),
7232 p, buf);
3c3bea1c 7233
1f10ba14
PA
7234 /* Some "registers" are actually extended stop information.
7235 Note if you're adding a new entry here: GDB 7.9 and
7236 earlier assume that all register "numbers" that start
7237 with an hex digit are real register numbers. Make sure
7238 the server only sends such a packet if it knows the
7239 client understands it. */
c8e38a49 7240
26d56a93 7241 if (strprefix (p, p1, "thread"))
1f10ba14 7242 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7243 else if (strprefix (p, p1, "syscall_entry"))
7244 {
7245 ULONGEST sysno;
7246
7247 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7248 p = unpack_varlen_hex (++p1, &sysno);
7249 event->ws.value.syscall_number = (int) sysno;
7250 }
7251 else if (strprefix (p, p1, "syscall_return"))
7252 {
7253 ULONGEST sysno;
7254
7255 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7256 p = unpack_varlen_hex (++p1, &sysno);
7257 event->ws.value.syscall_number = (int) sysno;
7258 }
26d56a93
SL
7259 else if (strprefix (p, p1, "watch")
7260 || strprefix (p, p1, "rwatch")
7261 || strprefix (p, p1, "awatch"))
cea39f65 7262 {
f7e6eed5 7263 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7264 p = unpack_varlen_hex (++p1, &addr);
7265 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7266 }
26d56a93 7267 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7268 {
7269 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7270
7271 /* Make sure the stub doesn't forget to indicate support
7272 with qSupported. */
7273 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7274 error (_("Unexpected swbreak stop reason"));
7275
7276 /* The value part is documented as "must be empty",
7277 though we ignore it, in case we ever decide to make
7278 use of it in a backward compatible way. */
8424cc97 7279 p = strchrnul (p1 + 1, ';');
f7e6eed5 7280 }
26d56a93 7281 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7282 {
7283 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7284
7285 /* Make sure the stub doesn't forget to indicate support
7286 with qSupported. */
7287 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7288 error (_("Unexpected hwbreak stop reason"));
7289
7290 /* See above. */
8424cc97 7291 p = strchrnul (p1 + 1, ';');
f7e6eed5 7292 }
26d56a93 7293 else if (strprefix (p, p1, "library"))
cea39f65 7294 {
1f10ba14 7295 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 7296 p = strchrnul (p1 + 1, ';');
1f10ba14 7297 }
26d56a93 7298 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
7299 {
7300 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7301 /* p1 will indicate "begin" or "end", but it makes
7302 no difference for now, so ignore it. */
8424cc97 7303 p = strchrnul (p1 + 1, ';');
1f10ba14 7304 }
26d56a93 7305 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7306 {
7307 ULONGEST c;
a744cf53 7308
1f10ba14
PA
7309 p = unpack_varlen_hex (++p1, &c);
7310 event->core = c;
cea39f65 7311 }
26d56a93 7312 else if (strprefix (p, p1, "fork"))
de0d863e
DB
7313 {
7314 event->ws.value.related_pid = read_ptid (++p1, &p);
7315 event->ws.kind = TARGET_WAITKIND_FORKED;
7316 }
26d56a93 7317 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
7318 {
7319 event->ws.value.related_pid = read_ptid (++p1, &p);
7320 event->ws.kind = TARGET_WAITKIND_VFORKED;
7321 }
26d56a93 7322 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
7323 {
7324 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 7325 p = strchrnul (p1 + 1, ';');
c269dbdb 7326 }
6ab24463 7327 else if (strprefix (p, p1, "exec"))
94585166
DB
7328 {
7329 ULONGEST ignored;
7330 char pathname[PATH_MAX];
7331 int pathlen;
7332
7333 /* Determine the length of the execd pathname. */
7334 p = unpack_varlen_hex (++p1, &ignored);
7335 pathlen = (p - p1) / 2;
7336
7337 /* Save the pathname for event reporting and for
7338 the next run command. */
7339 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7340 pathname[pathlen] = '\0';
7341
7342 /* This is freed during event handling. */
7343 event->ws.value.execd_pathname = xstrdup (pathname);
7344 event->ws.kind = TARGET_WAITKIND_EXECD;
7345
7346 /* Skip the registers included in this packet, since
7347 they may be for an architecture different from the
7348 one used by the original program. */
7349 skipregs = 1;
7350 }
65706a29
PA
7351 else if (strprefix (p, p1, "create"))
7352 {
7353 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 7354 p = strchrnul (p1 + 1, ';');
65706a29 7355 }
cea39f65
MS
7356 else
7357 {
1f10ba14 7358 ULONGEST pnum;
256642e8 7359 const char *p_temp;
1f10ba14 7360
94585166
DB
7361 if (skipregs)
7362 {
8424cc97 7363 p = strchrnul (p1 + 1, ';');
94585166
DB
7364 p++;
7365 continue;
7366 }
7367
1f10ba14
PA
7368 /* Maybe a real ``P'' register number. */
7369 p_temp = unpack_varlen_hex (p, &pnum);
7370 /* If the first invalid character is the colon, we got a
7371 register number. Otherwise, it's an unknown stop
7372 reason. */
7373 if (p_temp == p1)
7374 {
5cd63fda
PA
7375 /* If we haven't parsed the event's thread yet, find
7376 it now, in order to find the architecture of the
7377 reported expedited registers. */
7378 if (event->ptid == null_ptid)
7379 {
7380 const char *thr = strstr (p1 + 1, ";thread:");
7381 if (thr != NULL)
7382 event->ptid = read_ptid (thr + strlen (";thread:"),
7383 NULL);
7384 else
3cada740
PA
7385 {
7386 /* Either the current thread hasn't changed,
7387 or the inferior is not multi-threaded.
7388 The event must be for the thread we last
7389 set as (or learned as being) current. */
7390 event->ptid = event->rs->general_thread;
7391 }
5cd63fda
PA
7392 }
7393
7394 if (rsa == NULL)
7395 {
7396 inferior *inf = (event->ptid == null_ptid
7397 ? NULL
7398 : find_inferior_ptid (event->ptid));
7399 /* If this is the first time we learn anything
7400 about this process, skip the registers
7401 included in this packet, since we don't yet
7402 know which architecture to use to parse them.
7403 We'll determine the architecture later when
7404 we process the stop reply and retrieve the
7405 target description, via
7406 remote_notice_new_inferior ->
7407 post_create_inferior. */
7408 if (inf == NULL)
7409 {
7410 p = strchrnul (p1 + 1, ';');
7411 p++;
7412 continue;
7413 }
7414
7415 event->arch = inf->gdbarch;
9d6eea31 7416 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7417 }
7418
7419 packet_reg *reg
7420 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7421 cached_reg_t cached_reg;
43ff13b4 7422
1f10ba14
PA
7423 if (reg == NULL)
7424 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7425Packet: '%s'\n"),
1f10ba14 7426 hex_string (pnum), p, buf);
c8e38a49 7427
1f10ba14 7428 cached_reg.num = reg->regnum;
d1dff226 7429 cached_reg.data = (gdb_byte *)
5cd63fda 7430 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7431
1f10ba14
PA
7432 p = p1 + 1;
7433 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7434 register_size (event->arch, reg->regnum));
1f10ba14 7435 p += 2 * fieldsize;
5cd63fda 7436 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7437 warning (_("Remote reply is too short: %s"), buf);
74531fed 7438
1f10ba14
PA
7439 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7440 }
7441 else
7442 {
7443 /* Not a number. Silently skip unknown optional
7444 info. */
8424cc97 7445 p = strchrnul (p1 + 1, ';');
1f10ba14 7446 }
cea39f65 7447 }
c8e38a49 7448
cea39f65
MS
7449 if (*p != ';')
7450 error (_("Remote register badly formatted: %s\nhere: %s"),
7451 buf, p);
7452 ++p;
7453 }
5b5596ff
PA
7454
7455 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7456 break;
7457
c8e38a49
PA
7458 /* fall through */
7459 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7460 {
7461 int sig;
7462
7463 event->ws.kind = TARGET_WAITKIND_STOPPED;
7464 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7465 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7466 event->ws.value.sig = (enum gdb_signal) sig;
7467 else
7468 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7469 }
c8e38a49 7470 break;
65706a29
PA
7471 case 'w': /* Thread exited. */
7472 {
256642e8 7473 const char *p;
65706a29
PA
7474 ULONGEST value;
7475
7476 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7477 p = unpack_varlen_hex (&buf[1], &value);
7478 event->ws.value.integer = value;
7479 if (*p != ';')
7480 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7481 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7482 break;
7483 }
c8e38a49
PA
7484 case 'W': /* Target exited. */
7485 case 'X':
7486 {
256642e8 7487 const char *p;
c8e38a49
PA
7488 int pid;
7489 ULONGEST value;
82f73884 7490
c8e38a49
PA
7491 /* GDB used to accept only 2 hex chars here. Stubs should
7492 only send more if they detect GDB supports multi-process
7493 support. */
7494 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7495
c8e38a49
PA
7496 if (buf[0] == 'W')
7497 {
7498 /* The remote process exited. */
74531fed
PA
7499 event->ws.kind = TARGET_WAITKIND_EXITED;
7500 event->ws.value.integer = value;
c8e38a49
PA
7501 }
7502 else
7503 {
7504 /* The remote process exited with a signal. */
74531fed 7505 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7506 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7507 event->ws.value.sig = (enum gdb_signal) value;
7508 else
7509 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7510 }
82f73884 7511
c8e38a49
PA
7512 /* If no process is specified, assume inferior_ptid. */
7513 pid = ptid_get_pid (inferior_ptid);
7514 if (*p == '\0')
7515 ;
7516 else if (*p == ';')
7517 {
7518 p++;
7519
0b24eb2d 7520 if (*p == '\0')
82f73884 7521 ;
61012eef 7522 else if (startswith (p, "process:"))
82f73884 7523 {
c8e38a49 7524 ULONGEST upid;
a744cf53 7525
c8e38a49
PA
7526 p += sizeof ("process:") - 1;
7527 unpack_varlen_hex (p, &upid);
7528 pid = upid;
82f73884
PA
7529 }
7530 else
7531 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7532 }
c8e38a49
PA
7533 else
7534 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
7535 event->ptid = pid_to_ptid (pid);
7536 }
7537 break;
f2faf941
PA
7538 case 'N':
7539 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7540 event->ptid = minus_one_ptid;
7541 break;
74531fed
PA
7542 }
7543
6efcd9a8 7544 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
7545 error (_("No process or thread specified in stop reply: %s"), buf);
7546}
7547
722247f1
YQ
7548/* When the stub wants to tell GDB about a new notification reply, it
7549 sends a notification (%Stop, for example). Those can come it at
7550 any time, hence, we have to make sure that any pending
7551 putpkt/getpkt sequence we're making is finished, before querying
7552 the stub for more events with the corresponding ack command
7553 (vStopped, for example). E.g., if we started a vStopped sequence
7554 immediately upon receiving the notification, something like this
7555 could happen:
74531fed
PA
7556
7557 1.1) --> Hg 1
7558 1.2) <-- OK
7559 1.3) --> g
7560 1.4) <-- %Stop
7561 1.5) --> vStopped
7562 1.6) <-- (registers reply to step #1.3)
7563
7564 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7565 query.
7566
796cb314 7567 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7568 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7569 doing whatever we were doing:
7570
7571 2.1) --> Hg 1
7572 2.2) <-- OK
7573 2.3) --> g
7574 2.4) <-- %Stop
7575 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7576 2.5) <-- (registers reply to step #2.3)
7577
7578 Eventualy after step #2.5, we return to the event loop, which
7579 notices there's an event on the
7580 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7581 associated callback --- the function below. At this point, we're
7582 always safe to start a vStopped sequence. :
7583
7584 2.6) --> vStopped
7585 2.7) <-- T05 thread:2
7586 2.8) --> vStopped
7587 2.9) --> OK
7588*/
7589
722247f1 7590void
6b8edb51 7591remote_target::remote_notif_get_pending_events (notif_client *nc)
74531fed
PA
7592{
7593 struct remote_state *rs = get_remote_state ();
74531fed 7594
f48ff2a7 7595 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7596 {
722247f1
YQ
7597 if (notif_debug)
7598 fprintf_unfiltered (gdb_stdlog,
7599 "notif: process: '%s' ack pending event\n",
7600 nc->name);
74531fed 7601
722247f1 7602 /* acknowledge */
6b8edb51 7603 nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
f48ff2a7 7604 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7605
7606 while (1)
7607 {
7608 getpkt (&rs->buf, &rs->buf_size, 0);
7609 if (strcmp (rs->buf, "OK") == 0)
7610 break;
7611 else
6b8edb51 7612 remote_notif_ack (this, nc, rs->buf);
74531fed
PA
7613 }
7614 }
722247f1
YQ
7615 else
7616 {
7617 if (notif_debug)
7618 fprintf_unfiltered (gdb_stdlog,
7619 "notif: process: '%s' no pending reply\n",
7620 nc->name);
7621 }
74531fed
PA
7622}
7623
6b8edb51
PA
7624/* Wrapper around remote_target::remote_notif_get_pending_events to
7625 avoid having to export the whole remote_target class. */
7626
7627void
7628remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7629{
7630 remote->remote_notif_get_pending_events (nc);
7631}
7632
74531fed
PA
7633/* Called when it is decided that STOP_REPLY holds the info of the
7634 event that is to be returned to the core. This function always
7635 destroys STOP_REPLY. */
7636
6b8edb51
PA
7637ptid_t
7638remote_target::process_stop_reply (struct stop_reply *stop_reply,
7639 struct target_waitstatus *status)
74531fed
PA
7640{
7641 ptid_t ptid;
7642
7643 *status = stop_reply->ws;
7644 ptid = stop_reply->ptid;
7645
7646 /* If no thread/process was reported by the stub, assume the current
7647 inferior. */
7648 if (ptid_equal (ptid, null_ptid))
7649 ptid = inferior_ptid;
7650
5f3563ea 7651 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7652 && status->kind != TARGET_WAITKIND_SIGNALLED
7653 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7654 {
5f3563ea
PA
7655 /* Expedited registers. */
7656 if (stop_reply->regcache)
7657 {
217f1f79 7658 struct regcache *regcache
5cd63fda 7659 = get_thread_arch_regcache (ptid, stop_reply->arch);
5f3563ea
PA
7660 cached_reg_t *reg;
7661 int ix;
7662
7663 for (ix = 0;
d1dff226 7664 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
5f3563ea 7665 ix++)
d1dff226 7666 {
73e1c03f 7667 regcache->raw_supply (reg->num, reg->data);
d1dff226
AH
7668 xfree (reg->data);
7669 }
7670
5f3563ea
PA
7671 VEC_free (cached_reg_t, stop_reply->regcache);
7672 }
74531fed 7673
1941c569 7674 remote_notice_new_inferior (ptid, 0);
7aabaf9d 7675 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
799a2abe
PA
7676 remote_thr->core = stop_reply->core;
7677 remote_thr->stop_reason = stop_reply->stop_reason;
7678 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7679 remote_thr->vcont_resumed = 0;
74531fed
PA
7680 }
7681
74531fed
PA
7682 stop_reply_xfree (stop_reply);
7683 return ptid;
7684}
7685
7686/* The non-stop mode version of target_wait. */
7687
6b8edb51
PA
7688ptid_t
7689remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7690{
7691 struct remote_state *rs = get_remote_state ();
74531fed
PA
7692 struct stop_reply *stop_reply;
7693 int ret;
fee9eda9 7694 int is_notif = 0;
74531fed
PA
7695
7696 /* If in non-stop mode, get out of getpkt even if a
7697 notification is received. */
7698
7699 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7700 0 /* forever */, &is_notif);
74531fed
PA
7701 while (1)
7702 {
fee9eda9 7703 if (ret != -1 && !is_notif)
74531fed
PA
7704 switch (rs->buf[0])
7705 {
7706 case 'E': /* Error of some sort. */
7707 /* We're out of sync with the target now. Did it continue
7708 or not? We can't tell which thread it was in non-stop,
7709 so just ignore this. */
7710 warning (_("Remote failure reply: %s"), rs->buf);
7711 break;
7712 case 'O': /* Console output. */
7713 remote_console_output (rs->buf + 1);
7714 break;
7715 default:
7716 warning (_("Invalid remote reply: %s"), rs->buf);
7717 break;
7718 }
7719
7720 /* Acknowledge a pending stop reply that may have arrived in the
7721 mean time. */
f48ff2a7 7722 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7723 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7724
7725 /* If indeed we noticed a stop reply, we're done. */
7726 stop_reply = queued_stop_reply (ptid);
7727 if (stop_reply != NULL)
7728 return process_stop_reply (stop_reply, status);
7729
47608cb1 7730 /* Still no event. If we're just polling for an event, then
74531fed 7731 return to the event loop. */
47608cb1 7732 if (options & TARGET_WNOHANG)
74531fed
PA
7733 {
7734 status->kind = TARGET_WAITKIND_IGNORE;
7735 return minus_one_ptid;
7736 }
7737
47608cb1 7738 /* Otherwise do a blocking wait. */
74531fed 7739 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7740 1 /* forever */, &is_notif);
74531fed
PA
7741 }
7742}
7743
7744/* Wait until the remote machine stops, then return, storing status in
7745 STATUS just as `wait' would. */
7746
6b8edb51
PA
7747ptid_t
7748remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
74531fed
PA
7749{
7750 struct remote_state *rs = get_remote_state ();
74531fed 7751 ptid_t event_ptid = null_ptid;
cea39f65 7752 char *buf;
74531fed
PA
7753 struct stop_reply *stop_reply;
7754
47608cb1
PA
7755 again:
7756
74531fed
PA
7757 status->kind = TARGET_WAITKIND_IGNORE;
7758 status->value.integer = 0;
7759
7760 stop_reply = queued_stop_reply (ptid);
7761 if (stop_reply != NULL)
7762 return process_stop_reply (stop_reply, status);
7763
7764 if (rs->cached_wait_status)
7765 /* Use the cached wait status, but only once. */
7766 rs->cached_wait_status = 0;
7767 else
7768 {
7769 int ret;
722247f1 7770 int is_notif;
567420d1 7771 int forever = ((options & TARGET_WNOHANG) == 0
6b8edb51 7772 && rs->wait_forever_enabled_p);
567420d1
PA
7773
7774 if (!rs->waiting_for_stop_reply)
7775 {
7776 status->kind = TARGET_WAITKIND_NO_RESUMED;
7777 return minus_one_ptid;
7778 }
74531fed 7779
74531fed
PA
7780 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7781 _never_ wait for ever -> test on target_is_async_p().
7782 However, before we do that we need to ensure that the caller
7783 knows how to take the target into/out of async mode. */
722247f1 7784 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 7785 forever, &is_notif);
722247f1
YQ
7786
7787 /* GDB gets a notification. Return to core as this event is
7788 not interesting. */
7789 if (ret != -1 && is_notif)
7790 return minus_one_ptid;
567420d1
PA
7791
7792 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7793 return minus_one_ptid;
74531fed
PA
7794 }
7795
7796 buf = rs->buf;
7797
3a29589a
DJ
7798 /* Assume that the target has acknowledged Ctrl-C unless we receive
7799 an 'F' or 'O' packet. */
7800 if (buf[0] != 'F' && buf[0] != 'O')
7801 rs->ctrlc_pending_p = 0;
7802
74531fed
PA
7803 switch (buf[0])
7804 {
7805 case 'E': /* Error of some sort. */
7806 /* We're out of sync with the target now. Did it continue or
7807 not? Not is more likely, so report a stop. */
29090fb6
LM
7808 rs->waiting_for_stop_reply = 0;
7809
74531fed
PA
7810 warning (_("Remote failure reply: %s"), buf);
7811 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7812 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7813 break;
7814 case 'F': /* File-I/O request. */
e42e5352
YQ
7815 /* GDB may access the inferior memory while handling the File-I/O
7816 request, but we don't want GDB accessing memory while waiting
7817 for a stop reply. See the comments in putpkt_binary. Set
7818 waiting_for_stop_reply to 0 temporarily. */
7819 rs->waiting_for_stop_reply = 0;
6b8edb51 7820 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
3a29589a 7821 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7822 /* GDB handled the File-I/O request, and the target is running
7823 again. Keep waiting for events. */
7824 rs->waiting_for_stop_reply = 1;
74531fed 7825 break;
f2faf941 7826 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7827 {
29090fb6
LM
7828 struct stop_reply *stop_reply;
7829
7830 /* There is a stop reply to handle. */
7831 rs->waiting_for_stop_reply = 0;
7832
7833 stop_reply
6b8edb51
PA
7834 = (struct stop_reply *) remote_notif_parse (this,
7835 &notif_client_stop,
722247f1 7836 rs->buf);
74531fed 7837
74531fed 7838 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7839 break;
7840 }
7841 case 'O': /* Console output. */
7842 remote_console_output (buf + 1);
c8e38a49
PA
7843 break;
7844 case '\0':
b73be471 7845 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7846 {
7847 /* Zero length reply means that we tried 'S' or 'C' and the
7848 remote system doesn't support it. */
223ffa71 7849 target_terminal::ours_for_output ();
c8e38a49
PA
7850 printf_filtered
7851 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7852 gdb_signal_to_name (rs->last_sent_signal));
7853 rs->last_sent_signal = GDB_SIGNAL_0;
223ffa71 7854 target_terminal::inferior ();
c8e38a49 7855
f5c4fcd9
TT
7856 strcpy (buf, rs->last_sent_step ? "s" : "c");
7857 putpkt (buf);
c8e38a49 7858 break;
43ff13b4 7859 }
86a73007 7860 /* fallthrough */
c8e38a49
PA
7861 default:
7862 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7863 break;
43ff13b4 7864 }
c8e38a49 7865
f2faf941
PA
7866 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7867 return minus_one_ptid;
7868 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7869 {
7870 /* Nothing interesting happened. If we're doing a non-blocking
7871 poll, we're done. Otherwise, go back to waiting. */
7872 if (options & TARGET_WNOHANG)
7873 return minus_one_ptid;
7874 else
7875 goto again;
7876 }
74531fed
PA
7877 else if (status->kind != TARGET_WAITKIND_EXITED
7878 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7879 {
7880 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7881 record_currthread (rs, event_ptid);
82f73884
PA
7882 else
7883 event_ptid = inferior_ptid;
43ff13b4 7884 }
74531fed
PA
7885 else
7886 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7887 record_currthread (rs, minus_one_ptid);
79d7f229 7888
82f73884 7889 return event_ptid;
43ff13b4
JM
7890}
7891
74531fed
PA
7892/* Wait until the remote machine stops, then return, storing status in
7893 STATUS just as `wait' would. */
7894
f6ac5f3d
PA
7895ptid_t
7896remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7897{
7898 ptid_t event_ptid;
7899
6efcd9a8 7900 if (target_is_non_stop_p ())
6b8edb51 7901 event_ptid = wait_ns (ptid, status, options);
74531fed 7902 else
6b8edb51 7903 event_ptid = wait_as (ptid, status, options);
c8e38a49 7904
d9d41e78 7905 if (target_is_async_p ())
c8e38a49 7906 {
6b8edb51
PA
7907 remote_state *rs = get_remote_state ();
7908
74531fed
PA
7909 /* If there are are events left in the queue tell the event loop
7910 to return here. */
953edf2b 7911 if (!rs->stop_reply_queue.empty ())
6b8edb51 7912 mark_async_event_handler (rs->remote_async_inferior_event_token);
c8e38a49 7913 }
c8e38a49
PA
7914
7915 return event_ptid;
7916}
7917
74ca34ce 7918/* Fetch a single register using a 'p' packet. */
c906108c 7919
6b8edb51
PA
7920int
7921remote_target::fetch_register_using_p (struct regcache *regcache,
7922 packet_reg *reg)
b96ec7ac 7923{
ac7936df 7924 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 7925 struct remote_state *rs = get_remote_state ();
2e9f7625 7926 char *buf, *p;
9890e433 7927 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
7928 int i;
7929
4082afcc 7930 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7931 return 0;
7932
7933 if (reg->pnum == -1)
7934 return 0;
7935
2e9f7625 7936 p = rs->buf;
fcad0fa4 7937 *p++ = 'p';
74ca34ce 7938 p += hexnumstr (p, reg->pnum);
fcad0fa4 7939 *p++ = '\0';
1f4437a4
MS
7940 putpkt (rs->buf);
7941 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7942
2e9f7625
DJ
7943 buf = rs->buf;
7944
74ca34ce
DJ
7945 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7946 {
7947 case PACKET_OK:
7948 break;
7949 case PACKET_UNKNOWN:
7950 return 0;
7951 case PACKET_ERROR:
27a9c0bf 7952 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 7953 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
7954 reg->regnum),
7955 buf);
74ca34ce 7956 }
3f9a994c
JB
7957
7958 /* If this register is unfetchable, tell the regcache. */
7959 if (buf[0] == 'x')
8480adf2 7960 {
73e1c03f 7961 regcache->raw_supply (reg->regnum, NULL);
8480adf2 7962 return 1;
b96ec7ac 7963 }
b96ec7ac 7964
3f9a994c
JB
7965 /* Otherwise, parse and supply the value. */
7966 p = buf;
7967 i = 0;
7968 while (p[0] != 0)
7969 {
7970 if (p[1] == 0)
74ca34ce 7971 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7972
7973 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7974 p += 2;
7975 }
73e1c03f 7976 regcache->raw_supply (reg->regnum, regp);
3f9a994c 7977 return 1;
b96ec7ac
AC
7978}
7979
74ca34ce
DJ
7980/* Fetch the registers included in the target's 'g' packet. */
7981
6b8edb51
PA
7982int
7983remote_target::send_g_packet ()
c906108c 7984{
d01949b6 7985 struct remote_state *rs = get_remote_state ();
cea39f65 7986 int buf_len;
c906108c 7987
bba74b36 7988 xsnprintf (rs->buf, get_remote_packet_size (), "g");
b75abf5b
AK
7989 putpkt (rs->buf);
7990 getpkt (&rs->buf, &rs->buf_size, 0);
7991 if (packet_check_result (rs->buf) == PACKET_ERROR)
7992 error (_("Could not read registers; remote failure reply '%s'"),
7993 rs->buf);
c906108c 7994
29709017
DJ
7995 /* We can get out of synch in various cases. If the first character
7996 in the buffer is not a hex character, assume that has happened
7997 and try to fetch another packet to read. */
7998 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7999 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8000 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8001 && rs->buf[0] != 'x') /* New: unavailable register value. */
8002 {
8003 if (remote_debug)
8004 fprintf_unfiltered (gdb_stdlog,
8005 "Bad register packet; fetching a new packet\n");
8006 getpkt (&rs->buf, &rs->buf_size, 0);
8007 }
8008
74ca34ce
DJ
8009 buf_len = strlen (rs->buf);
8010
8011 /* Sanity check the received packet. */
8012 if (buf_len % 2 != 0)
8013 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
8014
8015 return buf_len / 2;
8016}
8017
6b8edb51
PA
8018void
8019remote_target::process_g_packet (struct regcache *regcache)
29709017 8020{
ac7936df 8021 struct gdbarch *gdbarch = regcache->arch ();
29709017 8022 struct remote_state *rs = get_remote_state ();
9d6eea31 8023 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8024 int i, buf_len;
8025 char *p;
8026 char *regs;
8027
8028 buf_len = strlen (rs->buf);
8029
8030 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8031 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827
SM
8032 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8033 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
74ca34ce
DJ
8034
8035 /* Save the size of the packet sent to us by the target. It is used
8036 as a heuristic when determining the max size of packets that the
8037 target can safely receive. */
8038 if (rsa->actual_register_packet_size == 0)
8039 rsa->actual_register_packet_size = buf_len;
8040
8041 /* If this is smaller than we guessed the 'g' packet would be,
8042 update our records. A 'g' reply that doesn't include a register's
8043 value implies either that the register is not available, or that
8044 the 'p' packet must be used. */
8045 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8046 {
9dc193c3 8047 long sizeof_g_packet = buf_len / 2;
74ca34ce 8048
4a22f64d 8049 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8050 {
9dc193c3
LF
8051 long offset = rsa->regs[i].offset;
8052 long reg_size = register_size (gdbarch, i);
8053
74ca34ce
DJ
8054 if (rsa->regs[i].pnum == -1)
8055 continue;
8056
9dc193c3 8057 if (offset >= sizeof_g_packet)
74ca34ce 8058 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8059 else if (offset + reg_size > sizeof_g_packet)
8060 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8061 else
74ca34ce 8062 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8063 }
9dc193c3
LF
8064
8065 /* Looks valid enough, we can assume this is the correct length
8066 for a 'g' packet. It's important not to adjust
8067 rsa->sizeof_g_packet if we have truncated registers otherwise
8068 this "if" won't be run the next time the method is called
8069 with a packet of the same size and one of the internal errors
8070 below will trigger instead. */
8071 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8072 }
b323314b 8073
224c3ddb 8074 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8075
8076 /* Unimplemented registers read as all bits zero. */
ea9c271d 8077 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8078
c906108c
SS
8079 /* Reply describes registers byte by byte, each byte encoded as two
8080 hex characters. Suck them all up, then supply them to the
8081 register cacheing/storage mechanism. */
8082
74ca34ce 8083 p = rs->buf;
ea9c271d 8084 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8085 {
74ca34ce
DJ
8086 if (p[0] == 0 || p[1] == 0)
8087 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8088 internal_error (__FILE__, __LINE__,
9b20d036 8089 _("unexpected end of 'g' packet reply"));
74ca34ce 8090
c906108c 8091 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8092 regs[i] = 0; /* 'x' */
c906108c
SS
8093 else
8094 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8095 p += 2;
8096 }
8097
a744cf53
MS
8098 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8099 {
8100 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8101 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8102
8103 if (r->in_g_packet)
8104 {
9dc193c3 8105 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
a744cf53
MS
8106 /* This shouldn't happen - we adjusted in_g_packet above. */
8107 internal_error (__FILE__, __LINE__,
9b20d036 8108 _("unexpected end of 'g' packet reply"));
a744cf53
MS
8109 else if (rs->buf[r->offset * 2] == 'x')
8110 {
8111 gdb_assert (r->offset * 2 < strlen (rs->buf));
8112 /* The register isn't available, mark it as such (at
8113 the same time setting the value to zero). */
73e1c03f 8114 regcache->raw_supply (r->regnum, NULL);
a744cf53
MS
8115 }
8116 else
73e1c03f 8117 regcache->raw_supply (r->regnum, regs + r->offset);
a744cf53
MS
8118 }
8119 }
c906108c
SS
8120}
8121
6b8edb51
PA
8122void
8123remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8124{
8125 send_g_packet ();
56be3814 8126 process_g_packet (regcache);
29709017
DJ
8127}
8128
e6e4e701
PA
8129/* Make the remote selected traceframe match GDB's selected
8130 traceframe. */
8131
6b8edb51
PA
8132void
8133remote_target::set_remote_traceframe ()
e6e4e701
PA
8134{
8135 int newnum;
262e1174 8136 struct remote_state *rs = get_remote_state ();
e6e4e701 8137
262e1174 8138 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8139 return;
8140
8141 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8142 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8143
8144 newnum = target_trace_find (tfind_number,
8145 get_traceframe_number (), 0, 0, NULL);
8146
8147 /* Should not happen. If it does, all bets are off. */
8148 if (newnum != get_traceframe_number ())
8149 warning (_("could not set remote traceframe"));
8150}
8151
f6ac5f3d
PA
8152void
8153remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8154{
ac7936df 8155 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8156 struct remote_state *rs = get_remote_state ();
8157 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8158 int i;
8159
e6e4e701 8160 set_remote_traceframe ();
222312d3 8161 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8162
8163 if (regnum >= 0)
8164 {
5cd63fda 8165 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8166
74ca34ce
DJ
8167 gdb_assert (reg != NULL);
8168
8169 /* If this register might be in the 'g' packet, try that first -
8170 we are likely to read more than one register. If this is the
8171 first 'g' packet, we might be overly optimistic about its
8172 contents, so fall back to 'p'. */
8173 if (reg->in_g_packet)
8174 {
56be3814 8175 fetch_registers_using_g (regcache);
74ca34ce
DJ
8176 if (reg->in_g_packet)
8177 return;
8178 }
8179
56be3814 8180 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8181 return;
8182
8183 /* This register is not available. */
73e1c03f 8184 regcache->raw_supply (reg->regnum, NULL);
74ca34ce
DJ
8185
8186 return;
8187 }
8188
56be3814 8189 fetch_registers_using_g (regcache);
74ca34ce 8190
5cd63fda 8191 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8192 if (!rsa->regs[i].in_g_packet)
56be3814 8193 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8194 {
8195 /* This register is not available. */
73e1c03f 8196 regcache->raw_supply (i, NULL);
74ca34ce
DJ
8197 }
8198}
8199
c906108c
SS
8200/* Prepare to store registers. Since we may send them all (using a
8201 'G' request), we have to read out the ones we don't want to change
8202 first. */
8203
f6ac5f3d
PA
8204void
8205remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8206{
9d6eea31
PA
8207 struct remote_state *rs = get_remote_state ();
8208 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8209 int i;
cf0e1e0d 8210
c906108c 8211 /* Make sure the entire registers array is valid. */
4082afcc 8212 switch (packet_support (PACKET_P))
5a2468f5
JM
8213 {
8214 case PACKET_DISABLE:
8215 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8216 /* Make sure all the necessary registers are cached. */
ac7936df 8217 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8218 if (rsa->regs[i].in_g_packet)
0b47d985 8219 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
8220 break;
8221 case PACKET_ENABLE:
8222 break;
8223 }
8224}
8225
ad10f812 8226/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8227 packet was not recognized. */
5a2468f5 8228
6b8edb51
PA
8229int
8230remote_target::store_register_using_P (const struct regcache *regcache,
8231 packet_reg *reg)
5a2468f5 8232{
ac7936df 8233 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8234 struct remote_state *rs = get_remote_state ();
5a2468f5 8235 /* Try storing a single register. */
6d820c5c 8236 char *buf = rs->buf;
9890e433 8237 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8238 char *p;
5a2468f5 8239
4082afcc 8240 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8241 return 0;
8242
8243 if (reg->pnum == -1)
8244 return 0;
8245
ea9c271d 8246 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8247 p = buf + strlen (buf);
34a79281 8248 regcache->raw_collect (reg->regnum, regp);
4a22f64d 8249 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
8250 putpkt (rs->buf);
8251 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 8252
74ca34ce
DJ
8253 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8254 {
8255 case PACKET_OK:
8256 return 1;
8257 case PACKET_ERROR:
27a9c0bf
MS
8258 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8259 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
8260 case PACKET_UNKNOWN:
8261 return 0;
8262 default:
8263 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8264 }
c906108c
SS
8265}
8266
23860348
MS
8267/* Store register REGNUM, or all registers if REGNUM == -1, from the
8268 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8269
6b8edb51
PA
8270void
8271remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8272{
d01949b6 8273 struct remote_state *rs = get_remote_state ();
9d6eea31 8274 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8275 gdb_byte *regs;
c906108c
SS
8276 char *p;
8277
193cb69f
AC
8278 /* Extract all the registers in the regcache copying them into a
8279 local buffer. */
8280 {
b323314b 8281 int i;
a744cf53 8282
224c3ddb 8283 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8284 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8285 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8286 {
ea9c271d 8287 struct packet_reg *r = &rsa->regs[i];
a744cf53 8288
b323314b 8289 if (r->in_g_packet)
34a79281 8290 regcache->raw_collect (r->regnum, regs + r->offset);
193cb69f
AC
8291 }
8292 }
c906108c
SS
8293
8294 /* Command describes registers byte by byte,
8295 each byte encoded as two hex characters. */
6d820c5c 8296 p = rs->buf;
193cb69f 8297 *p++ = 'G';
74ca34ce 8298 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
8299 putpkt (rs->buf);
8300 getpkt (&rs->buf, &rs->buf_size, 0);
8301 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
8302 error (_("Could not write registers; remote failure reply '%s'"),
8303 rs->buf);
c906108c 8304}
74ca34ce
DJ
8305
8306/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8307 of the register cache buffer. FIXME: ignores errors. */
8308
f6ac5f3d
PA
8309void
8310remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8311{
5cd63fda 8312 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8313 struct remote_state *rs = get_remote_state ();
8314 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8315 int i;
8316
e6e4e701 8317 set_remote_traceframe ();
222312d3 8318 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8319
8320 if (regnum >= 0)
8321 {
5cd63fda 8322 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8323
74ca34ce
DJ
8324 gdb_assert (reg != NULL);
8325
8326 /* Always prefer to store registers using the 'P' packet if
8327 possible; we often change only a small number of registers.
8328 Sometimes we change a larger number; we'd need help from a
8329 higher layer to know to use 'G'. */
56be3814 8330 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8331 return;
8332
8333 /* For now, don't complain if we have no way to write the
8334 register. GDB loses track of unavailable registers too
8335 easily. Some day, this may be an error. We don't have
0df8b418 8336 any way to read the register, either... */
74ca34ce
DJ
8337 if (!reg->in_g_packet)
8338 return;
8339
56be3814 8340 store_registers_using_G (regcache);
74ca34ce
DJ
8341 return;
8342 }
8343
56be3814 8344 store_registers_using_G (regcache);
74ca34ce 8345
5cd63fda 8346 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8347 if (!rsa->regs[i].in_g_packet)
56be3814 8348 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8349 /* See above for why we do not issue an error here. */
8350 continue;
8351}
c906108c
SS
8352\f
8353
8354/* Return the number of hex digits in num. */
8355
8356static int
fba45db2 8357hexnumlen (ULONGEST num)
c906108c
SS
8358{
8359 int i;
8360
8361 for (i = 0; num != 0; i++)
8362 num >>= 4;
8363
325fac50 8364 return std::max (i, 1);
c906108c
SS
8365}
8366
2df3850c 8367/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8368
8369static int
fba45db2 8370hexnumstr (char *buf, ULONGEST num)
c906108c 8371{
c906108c 8372 int len = hexnumlen (num);
a744cf53 8373
2df3850c
JM
8374 return hexnumnstr (buf, num, len);
8375}
8376
c906108c 8377
2df3850c 8378/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8379
2df3850c 8380static int
fba45db2 8381hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8382{
8383 int i;
8384
8385 buf[width] = '\0';
8386
8387 for (i = width - 1; i >= 0; i--)
c906108c 8388 {
c5aa993b 8389 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8390 num >>= 4;
8391 }
8392
2df3850c 8393 return width;
c906108c
SS
8394}
8395
23860348 8396/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8397
8398static CORE_ADDR
fba45db2 8399remote_address_masked (CORE_ADDR addr)
c906108c 8400{
883b9c6c 8401 unsigned int address_size = remote_address_size;
a744cf53 8402
911c95a5
UW
8403 /* If "remoteaddresssize" was not set, default to target address size. */
8404 if (!address_size)
f5656ead 8405 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8406
8407 if (address_size > 0
8408 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8409 {
8410 /* Only create a mask when that mask can safely be constructed
23860348 8411 in a ULONGEST variable. */
c906108c 8412 ULONGEST mask = 1;
a744cf53 8413
911c95a5 8414 mask = (mask << address_size) - 1;
c906108c
SS
8415 addr &= mask;
8416 }
8417 return addr;
8418}
8419
8420/* Determine whether the remote target supports binary downloading.
8421 This is accomplished by sending a no-op memory write of zero length
8422 to the target at the specified address. It does not suffice to send
23860348
MS
8423 the whole packet, since many stubs strip the eighth bit and
8424 subsequently compute a wrong checksum, which causes real havoc with
8425 remote_write_bytes.
7a292a7a 8426
96baa820 8427 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8428 clean. In cases like this, the user should clear "remote
23860348 8429 X-packet". */
96baa820 8430
6b8edb51
PA
8431void
8432remote_target::check_binary_download (CORE_ADDR addr)
c906108c 8433{
d01949b6 8434 struct remote_state *rs = get_remote_state ();
24b06219 8435
4082afcc 8436 switch (packet_support (PACKET_X))
c906108c 8437 {
96baa820
JM
8438 case PACKET_DISABLE:
8439 break;
8440 case PACKET_ENABLE:
8441 break;
8442 case PACKET_SUPPORT_UNKNOWN:
8443 {
96baa820 8444 char *p;
802188a7 8445
2e9f7625 8446 p = rs->buf;
96baa820
JM
8447 *p++ = 'X';
8448 p += hexnumstr (p, (ULONGEST) addr);
8449 *p++ = ',';
8450 p += hexnumstr (p, (ULONGEST) 0);
8451 *p++ = ':';
8452 *p = '\0';
802188a7 8453
2e9f7625 8454 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8455 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8456
2e9f7625 8457 if (rs->buf[0] == '\0')
96baa820
JM
8458 {
8459 if (remote_debug)
8460 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8461 "binary downloading NOT "
8462 "supported by target\n");
444abaca 8463 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8464 }
8465 else
8466 {
8467 if (remote_debug)
8468 fprintf_unfiltered (gdb_stdlog,
64b9b334 8469 "binary downloading supported by target\n");
444abaca 8470 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8471 }
8472 break;
8473 }
c906108c
SS
8474 }
8475}
8476
124e13d9
SM
8477/* Helper function to resize the payload in order to try to get a good
8478 alignment. We try to write an amount of data such that the next write will
8479 start on an address aligned on REMOTE_ALIGN_WRITES. */
8480
8481static int
8482align_for_efficient_write (int todo, CORE_ADDR memaddr)
8483{
8484 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8485}
8486
c906108c
SS
8487/* Write memory data directly to the remote machine.
8488 This does not inform the data cache; the data cache uses this.
a76d924d 8489 HEADER is the starting part of the packet.
c906108c
SS
8490 MEMADDR is the address in the remote memory space.
8491 MYADDR is the address of the buffer in our space.
124e13d9
SM
8492 LEN_UNITS is the number of addressable units to write.
8493 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8494 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8495 should send data as binary ('X'), or hex-encoded ('M').
8496
8497 The function creates packet of the form
8498 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8499
124e13d9 8500 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8501
8502 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8503 are omitted.
8504
9b409511 8505 Return the transferred status, error or OK (an
124e13d9
SM
8506 'enum target_xfer_status' value). Save the number of addressable units
8507 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8508
8509 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8510 exchange between gdb and the stub could look like (?? in place of the
8511 checksum):
8512
8513 -> $m1000,4#??
8514 <- aaaabbbbccccdddd
8515
8516 -> $M1000,3:eeeeffffeeee#??
8517 <- OK
8518
8519 -> $m1000,4#??
8520 <- eeeeffffeeeedddd */
c906108c 8521
6b8edb51
PA
8522target_xfer_status
8523remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8524 const gdb_byte *myaddr,
8525 ULONGEST len_units,
8526 int unit_size,
8527 ULONGEST *xfered_len_units,
8528 char packet_format, int use_length)
c906108c 8529{
6d820c5c 8530 struct remote_state *rs = get_remote_state ();
cfd77fa1 8531 char *p;
a76d924d
DJ
8532 char *plen = NULL;
8533 int plenlen = 0;
124e13d9
SM
8534 int todo_units;
8535 int units_written;
8536 int payload_capacity_bytes;
8537 int payload_length_bytes;
a76d924d
DJ
8538
8539 if (packet_format != 'X' && packet_format != 'M')
8540 internal_error (__FILE__, __LINE__,
9b20d036 8541 _("remote_write_bytes_aux: bad packet format"));
c906108c 8542
124e13d9 8543 if (len_units == 0)
9b409511 8544 return TARGET_XFER_EOF;
b2182ed2 8545
124e13d9 8546 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8547
6d820c5c
DJ
8548 /* The packet buffer will be large enough for the payload;
8549 get_memory_packet_size ensures this. */
a76d924d 8550 rs->buf[0] = '\0';
c906108c 8551
a257b5bb 8552 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8553 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8554
124e13d9 8555 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8556 if (!use_length)
0df8b418 8557 /* The comma won't be used. */
124e13d9
SM
8558 payload_capacity_bytes += 1;
8559 payload_capacity_bytes -= strlen (header);
8560 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8561
a76d924d 8562 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8563
a76d924d
DJ
8564 strcat (rs->buf, header);
8565 p = rs->buf + strlen (header);
8566
8567 /* Compute a best guess of the number of bytes actually transfered. */
8568 if (packet_format == 'X')
c906108c 8569 {
23860348 8570 /* Best guess at number of bytes that will fit. */
325fac50
PA
8571 todo_units = std::min (len_units,
8572 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8573 if (use_length)
124e13d9 8574 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8575 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8576 }
8577 else
8578 {
124e13d9 8579 /* Number of bytes that will fit. */
325fac50
PA
8580 todo_units
8581 = std::min (len_units,
8582 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8583 if (use_length)
124e13d9 8584 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8585 todo_units = std::min (todo_units,
8586 (payload_capacity_bytes / unit_size) / 2);
917317f4 8587 }
a76d924d 8588
124e13d9 8589 if (todo_units <= 0)
3de11b2e 8590 internal_error (__FILE__, __LINE__,
405f8e94 8591 _("minimum packet size too small to write data"));
802188a7 8592
6765f3e5
DJ
8593 /* If we already need another packet, then try to align the end
8594 of this packet to a useful boundary. */
124e13d9
SM
8595 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8596 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8597
a257b5bb 8598 /* Append "<memaddr>". */
917317f4
JM
8599 memaddr = remote_address_masked (memaddr);
8600 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8601
a76d924d
DJ
8602 if (use_length)
8603 {
8604 /* Append ",". */
8605 *p++ = ',';
802188a7 8606
124e13d9
SM
8607 /* Append the length and retain its location and size. It may need to be
8608 adjusted once the packet body has been created. */
a76d924d 8609 plen = p;
124e13d9 8610 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8611 p += plenlen;
8612 }
a257b5bb
AC
8613
8614 /* Append ":". */
917317f4
JM
8615 *p++ = ':';
8616 *p = '\0';
802188a7 8617
a257b5bb 8618 /* Append the packet body. */
a76d924d 8619 if (packet_format == 'X')
917317f4 8620 {
917317f4
JM
8621 /* Binary mode. Send target system values byte by byte, in
8622 increasing byte addresses. Only escape certain critical
8623 characters. */
124e13d9
SM
8624 payload_length_bytes =
8625 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8626 &units_written, payload_capacity_bytes);
6765f3e5 8627
124e13d9 8628 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8629 a second try to keep the end of the packet aligned. Don't do
8630 this if the packet is tiny. */
124e13d9 8631 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8632 {
124e13d9
SM
8633 int new_todo_units;
8634
8635 new_todo_units = align_for_efficient_write (units_written, memaddr);
8636
8637 if (new_todo_units != units_written)
8638 payload_length_bytes =
8639 remote_escape_output (myaddr, new_todo_units, unit_size,
8640 (gdb_byte *) p, &units_written,
8641 payload_capacity_bytes);
6765f3e5
DJ
8642 }
8643
124e13d9
SM
8644 p += payload_length_bytes;
8645 if (use_length && units_written < todo_units)
c906108c 8646 {
802188a7 8647 /* Escape chars have filled up the buffer prematurely,
124e13d9 8648 and we have actually sent fewer units than planned.
917317f4
JM
8649 Fix-up the length field of the packet. Use the same
8650 number of characters as before. */
124e13d9
SM
8651 plen += hexnumnstr (plen, (ULONGEST) units_written,
8652 plenlen);
917317f4 8653 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8654 }
a76d924d
DJ
8655 }
8656 else
8657 {
917317f4
JM
8658 /* Normal mode: Send target system values byte by byte, in
8659 increasing byte addresses. Each byte is encoded as a two hex
8660 value. */
124e13d9
SM
8661 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8662 units_written = todo_units;
c906108c 8663 }
802188a7 8664
2e9f7625 8665 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8666 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8667
2e9f7625 8668 if (rs->buf[0] == 'E')
00d84524 8669 return TARGET_XFER_E_IO;
802188a7 8670
124e13d9
SM
8671 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8672 send fewer units than we'd planned. */
8673 *xfered_len_units = (ULONGEST) units_written;
92ffd475 8674 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
8675}
8676
a76d924d
DJ
8677/* Write memory data directly to the remote machine.
8678 This does not inform the data cache; the data cache uses this.
8679 MEMADDR is the address in the remote memory space.
8680 MYADDR is the address of the buffer in our space.
8681 LEN is the number of bytes.
8682
9b409511
YQ
8683 Return the transferred status, error or OK (an
8684 'enum target_xfer_status' value). Save the number of bytes
8685 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8686
6b8edb51
PA
8687target_xfer_status
8688remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8689 ULONGEST len, int unit_size,
8690 ULONGEST *xfered_len)
a76d924d 8691{
a121b7c1 8692 const char *packet_format = NULL;
a76d924d
DJ
8693
8694 /* Check whether the target supports binary download. */
8695 check_binary_download (memaddr);
8696
4082afcc 8697 switch (packet_support (PACKET_X))
a76d924d
DJ
8698 {
8699 case PACKET_ENABLE:
8700 packet_format = "X";
8701 break;
8702 case PACKET_DISABLE:
8703 packet_format = "M";
8704 break;
8705 case PACKET_SUPPORT_UNKNOWN:
8706 internal_error (__FILE__, __LINE__,
8707 _("remote_write_bytes: bad internal state"));
8708 default:
8709 internal_error (__FILE__, __LINE__, _("bad switch"));
8710 }
8711
8712 return remote_write_bytes_aux (packet_format,
124e13d9 8713 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8714 packet_format[0], 1);
a76d924d
DJ
8715}
8716
9217e74e
YQ
8717/* Read memory data directly from the remote machine.
8718 This does not use the data cache; the data cache uses this.
8719 MEMADDR is the address in the remote memory space.
8720 MYADDR is the address of the buffer in our space.
124e13d9
SM
8721 LEN_UNITS is the number of addressable memory units to read..
8722 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8723
8724 Return the transferred status, error or OK (an
8725 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8726 transferred in *XFERED_LEN_UNITS.
8727
8728 See the comment of remote_write_bytes_aux for an example of
8729 memory read/write exchange between gdb and the stub. */
9217e74e 8730
6b8edb51
PA
8731target_xfer_status
8732remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8733 ULONGEST len_units,
8734 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8735{
8736 struct remote_state *rs = get_remote_state ();
124e13d9 8737 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8738 char *p;
124e13d9
SM
8739 int todo_units;
8740 int decoded_bytes;
9217e74e 8741
124e13d9 8742 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8743 /* The packet buffer will be large enough for the payload;
8744 get_memory_packet_size ensures this. */
8745
124e13d9 8746 /* Number of units that will fit. */
325fac50
PA
8747 todo_units = std::min (len_units,
8748 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8749
8750 /* Construct "m"<memaddr>","<len>". */
8751 memaddr = remote_address_masked (memaddr);
8752 p = rs->buf;
8753 *p++ = 'm';
8754 p += hexnumstr (p, (ULONGEST) memaddr);
8755 *p++ = ',';
124e13d9 8756 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8757 *p = '\0';
8758 putpkt (rs->buf);
8759 getpkt (&rs->buf, &rs->buf_size, 0);
8760 if (rs->buf[0] == 'E'
8761 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8762 && rs->buf[3] == '\0')
8763 return TARGET_XFER_E_IO;
8764 /* Reply describes memory byte by byte, each byte encoded as two hex
8765 characters. */
8766 p = rs->buf;
124e13d9 8767 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8768 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8769 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 8770 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
8771}
8772
b55fbac4
YQ
8773/* Using the set of read-only target sections of remote, read live
8774 read-only memory.
8acf9577
YQ
8775
8776 For interface/parameters/return description see target.h,
8777 to_xfer_partial. */
8778
6b8edb51
PA
8779target_xfer_status
8780remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8781 ULONGEST memaddr,
8782 ULONGEST len,
8783 int unit_size,
8784 ULONGEST *xfered_len)
8acf9577
YQ
8785{
8786 struct target_section *secp;
8787 struct target_section_table *table;
8788
6b8edb51 8789 secp = target_section_by_addr (this, memaddr);
8acf9577
YQ
8790 if (secp != NULL
8791 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8792 secp->the_bfd_section)
8793 & SEC_READONLY))
8794 {
8795 struct target_section *p;
8796 ULONGEST memend = memaddr + len;
8797
6b8edb51 8798 table = target_get_section_table (this);
8acf9577
YQ
8799
8800 for (p = table->sections; p < table->sections_end; p++)
8801 {
8802 if (memaddr >= p->addr)
8803 {
8804 if (memend <= p->endaddr)
8805 {
8806 /* Entire transfer is within this section. */
124e13d9 8807 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8808 xfered_len);
8acf9577
YQ
8809 }
8810 else if (memaddr >= p->endaddr)
8811 {
8812 /* This section ends before the transfer starts. */
8813 continue;
8814 }
8815 else
8816 {
8817 /* This section overlaps the transfer. Just do half. */
8818 len = p->endaddr - memaddr;
124e13d9 8819 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8820 xfered_len);
8acf9577
YQ
8821 }
8822 }
8823 }
8824 }
8825
8826 return TARGET_XFER_EOF;
8827}
8828
9217e74e
YQ
8829/* Similar to remote_read_bytes_1, but it reads from the remote stub
8830 first if the requested memory is unavailable in traceframe.
8831 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8832
6b8edb51
PA
8833target_xfer_status
8834remote_target::remote_read_bytes (CORE_ADDR memaddr,
8835 gdb_byte *myaddr, ULONGEST len, int unit_size,
8836 ULONGEST *xfered_len)
c906108c 8837{
6b6aa828 8838 if (len == 0)
96c4f946 8839 return TARGET_XFER_EOF;
b2182ed2 8840
8acf9577
YQ
8841 if (get_traceframe_number () != -1)
8842 {
a79b1bc6 8843 std::vector<mem_range> available;
8acf9577
YQ
8844
8845 /* If we fail to get the set of available memory, then the
8846 target does not support querying traceframe info, and so we
8847 attempt reading from the traceframe anyway (assuming the
8848 target implements the old QTro packet then). */
8849 if (traceframe_available_memory (&available, memaddr, len))
8850 {
a79b1bc6 8851 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
8852 {
8853 enum target_xfer_status res;
8854
8855 /* Don't read into the traceframe's available
8856 memory. */
a79b1bc6 8857 if (!available.empty ())
8acf9577
YQ
8858 {
8859 LONGEST oldlen = len;
8860
a79b1bc6 8861 len = available[0].start - memaddr;
8acf9577
YQ
8862 gdb_assert (len <= oldlen);
8863 }
8864
8acf9577 8865 /* This goes through the topmost target again. */
6b8edb51 8866 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 8867 len, unit_size, xfered_len);
8acf9577
YQ
8868 if (res == TARGET_XFER_OK)
8869 return TARGET_XFER_OK;
8870 else
8871 {
8872 /* No use trying further, we know some memory starting
8873 at MEMADDR isn't available. */
8874 *xfered_len = len;
92ffd475
PC
8875 return (*xfered_len != 0) ?
8876 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
8877 }
8878 }
8879
8880 /* Don't try to read more than how much is available, in
8881 case the target implements the deprecated QTro packet to
8882 cater for older GDBs (the target's knowledge of read-only
8883 sections may be outdated by now). */
a79b1bc6 8884 len = available[0].length;
8acf9577
YQ
8885 }
8886 }
8887
124e13d9 8888 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8889}
74531fed 8890
c906108c 8891\f
c906108c 8892
a76d924d
DJ
8893/* Sends a packet with content determined by the printf format string
8894 FORMAT and the remaining arguments, then gets the reply. Returns
8895 whether the packet was a success, a failure, or unknown. */
8896
6b8edb51
PA
8897packet_result
8898remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
8899{
8900 struct remote_state *rs = get_remote_state ();
8901 int max_size = get_remote_packet_size ();
a76d924d 8902 va_list ap;
a744cf53 8903
a76d924d
DJ
8904 va_start (ap, format);
8905
8906 rs->buf[0] = '\0';
8907 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8908 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8909
8910 if (putpkt (rs->buf) < 0)
8911 error (_("Communication problem with target."));
8912
8913 rs->buf[0] = '\0';
8914 getpkt (&rs->buf, &rs->buf_size, 0);
8915
8916 return packet_check_result (rs->buf);
8917}
8918
a76d924d
DJ
8919/* Flash writing can take quite some time. We'll set
8920 effectively infinite timeout for flash operations.
8921 In future, we'll need to decide on a better approach. */
8922static const int remote_flash_timeout = 1000;
8923
f6ac5f3d
PA
8924void
8925remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 8926{
f5656ead 8927 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 8928 enum packet_result ret;
2ec845e7
TT
8929 scoped_restore restore_timeout
8930 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
8931
8932 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8933 phex (address, addr_size),
a76d924d
DJ
8934 phex (length, 4));
8935 switch (ret)
8936 {
8937 case PACKET_UNKNOWN:
8938 error (_("Remote target does not support flash erase"));
8939 case PACKET_ERROR:
8940 error (_("Error erasing flash with vFlashErase packet"));
8941 default:
8942 break;
8943 }
a76d924d
DJ
8944}
8945
6b8edb51
PA
8946target_xfer_status
8947remote_target::remote_flash_write (ULONGEST address,
8948 ULONGEST length, ULONGEST *xfered_len,
8949 const gdb_byte *data)
a76d924d 8950{
2ec845e7
TT
8951 scoped_restore restore_timeout
8952 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8953 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8954 xfered_len,'X', 0);
a76d924d
DJ
8955}
8956
f6ac5f3d
PA
8957void
8958remote_target::flash_done ()
a76d924d 8959{
a76d924d 8960 int ret;
a76d924d 8961
2ec845e7
TT
8962 scoped_restore restore_timeout
8963 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8964
a76d924d 8965 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
8966
8967 switch (ret)
8968 {
8969 case PACKET_UNKNOWN:
8970 error (_("Remote target does not support vFlashDone"));
8971 case PACKET_ERROR:
8972 error (_("Error finishing flash operation"));
8973 default:
8974 break;
8975 }
8976}
8977
f6ac5f3d
PA
8978void
8979remote_target::files_info ()
c906108c
SS
8980{
8981 puts_filtered ("Debugging a target over a serial line.\n");
8982}
8983\f
8984/* Stuff for dealing with the packets which are part of this protocol.
8985 See comment at top of file for details. */
8986
1927e618
PA
8987/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8988 error to higher layers. Called when a serial error is detected.
8989 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8990 the system error message for errno at function entry and final dot
8991 for output compatibility with throw_perror_with_name. */
1927e618
PA
8992
8993static void
8994unpush_and_perror (const char *string)
8995{
d6cb50a2 8996 int saved_errno = errno;
1927e618
PA
8997
8998 remote_unpush_target ();
d6cb50a2
JK
8999 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9000 safe_strerror (saved_errno));
1927e618
PA
9001}
9002
048094ac
PA
9003/* Read a single character from the remote end. The current quit
9004 handler is overridden to avoid quitting in the middle of packet
9005 sequence, as that would break communication with the remote server.
9006 See remote_serial_quit_handler for more detail. */
c906108c 9007
6b8edb51
PA
9008int
9009remote_target::readchar (int timeout)
c906108c
SS
9010{
9011 int ch;
5d93a237 9012 struct remote_state *rs = get_remote_state ();
048094ac 9013
2ec845e7 9014 {
6b8edb51
PA
9015 scoped_restore restore_quit_target
9016 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9017 scoped_restore restore_quit
6b8edb51 9018 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9019
2ec845e7 9020 rs->got_ctrlc_during_io = 0;
c906108c 9021
2ec845e7 9022 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9023
2ec845e7
TT
9024 if (rs->got_ctrlc_during_io)
9025 set_quit_flag ();
9026 }
048094ac 9027
2acceee2 9028 if (ch >= 0)
0876f84a 9029 return ch;
2acceee2
JM
9030
9031 switch ((enum serial_rc) ch)
c906108c
SS
9032 {
9033 case SERIAL_EOF:
78a095c3 9034 remote_unpush_target ();
598d3636 9035 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9036 /* no return */
c906108c 9037 case SERIAL_ERROR:
1927e618
PA
9038 unpush_and_perror (_("Remote communication error. "
9039 "Target disconnected."));
2acceee2 9040 /* no return */
c906108c 9041 case SERIAL_TIMEOUT:
2acceee2 9042 break;
c906108c 9043 }
2acceee2 9044 return ch;
c906108c
SS
9045}
9046
c33e31fd 9047/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9048 writing fails. The current quit handler is overridden to avoid
9049 quitting in the middle of packet sequence, as that would break
9050 communication with the remote server. See
9051 remote_serial_quit_handler for more detail. */
c33e31fd 9052
6b8edb51
PA
9053void
9054remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9055{
5d93a237 9056 struct remote_state *rs = get_remote_state ();
048094ac 9057
6b8edb51
PA
9058 scoped_restore restore_quit_target
9059 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9060 scoped_restore restore_quit
6b8edb51 9061 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9062
9063 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9064
9065 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9066 {
1927e618
PA
9067 unpush_and_perror (_("Remote communication error. "
9068 "Target disconnected."));
c33e31fd 9069 }
048094ac
PA
9070
9071 if (rs->got_ctrlc_during_io)
9072 set_quit_flag ();
c33e31fd
PA
9073}
9074
b3ced9ba
PA
9075/* Return a string representing an escaped version of BUF, of len N.
9076 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9077
b3ced9ba 9078static std::string
6e5abd65
PA
9079escape_buffer (const char *buf, int n)
9080{
d7e74731 9081 string_file stb;
6e5abd65 9082
d7e74731
PA
9083 stb.putstrn (buf, n, '\\');
9084 return std::move (stb.string ());
6e5abd65
PA
9085}
9086
c906108c
SS
9087/* Display a null-terminated packet on stdout, for debugging, using C
9088 string notation. */
9089
9090static void
baa336ce 9091print_packet (const char *buf)
c906108c
SS
9092{
9093 puts_filtered ("\"");
43e526b9 9094 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
9095 puts_filtered ("\"");
9096}
9097
9098int
6b8edb51 9099remote_target::putpkt (const char *buf)
c906108c
SS
9100{
9101 return putpkt_binary (buf, strlen (buf));
9102}
9103
6b8edb51
PA
9104/* Wrapper around remote_target::putpkt to avoid exporting
9105 remote_target. */
9106
9107int
9108putpkt (remote_target *remote, const char *buf)
9109{
9110 return remote->putpkt (buf);
9111}
9112
c906108c 9113/* Send a packet to the remote machine, with error checking. The data
23860348 9114 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9115 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9116 and for a possible /0 if we are debugging (remote_debug) and want
9117 to print the sent packet as a string. */
c906108c 9118
6b8edb51
PA
9119int
9120remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9121{
2d717e4f 9122 struct remote_state *rs = get_remote_state ();
c906108c
SS
9123 int i;
9124 unsigned char csum = 0;
b80406ac
TT
9125 gdb::def_vector<char> data (cnt + 6);
9126 char *buf2 = data.data ();
085dd6e6 9127
c906108c
SS
9128 int ch;
9129 int tcount = 0;
9130 char *p;
9131
e24a49d8
PA
9132 /* Catch cases like trying to read memory or listing threads while
9133 we're waiting for a stop reply. The remote server wouldn't be
9134 ready to handle this request, so we'd hang and timeout. We don't
9135 have to worry about this in synchronous mode, because in that
9136 case it's not possible to issue a command while the target is
74531fed
PA
9137 running. This is not a problem in non-stop mode, because in that
9138 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9139 if (!target_is_non_stop_p ()
9140 && target_is_async_p ()
9141 && rs->waiting_for_stop_reply)
9597b22a
DE
9142 {
9143 error (_("Cannot execute this command while the target is running.\n"
9144 "Use the \"interrupt\" command to stop the target\n"
9145 "and then try again."));
9146 }
e24a49d8 9147
2d717e4f
DJ
9148 /* We're sending out a new packet. Make sure we don't look at a
9149 stale cached response. */
9150 rs->cached_wait_status = 0;
9151
c906108c
SS
9152 /* Copy the packet into buffer BUF2, encapsulating it
9153 and giving it a checksum. */
9154
c906108c
SS
9155 p = buf2;
9156 *p++ = '$';
9157
9158 for (i = 0; i < cnt; i++)
9159 {
9160 csum += buf[i];
9161 *p++ = buf[i];
9162 }
9163 *p++ = '#';
9164 *p++ = tohex ((csum >> 4) & 0xf);
9165 *p++ = tohex (csum & 0xf);
9166
9167 /* Send it over and over until we get a positive ack. */
9168
9169 while (1)
9170 {
9171 int started_error_output = 0;
9172
9173 if (remote_debug)
9174 {
9175 *p = '\0';
b3ced9ba 9176
6f8976bf
YQ
9177 int len = (int) (p - buf2);
9178
9179 std::string str
9180 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9181
9182 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9183
567a3e54
SM
9184 if (len > REMOTE_DEBUG_MAX_CHAR)
9185 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9186 len - REMOTE_DEBUG_MAX_CHAR);
6f8976bf
YQ
9187
9188 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 9189
0f71a2f6 9190 gdb_flush (gdb_stdlog);
c906108c 9191 }
c33e31fd 9192 remote_serial_write (buf2, p - buf2);
c906108c 9193
a6f3e723
SL
9194 /* If this is a no acks version of the remote protocol, send the
9195 packet and move on. */
9196 if (rs->noack_mode)
9197 break;
9198
74531fed
PA
9199 /* Read until either a timeout occurs (-2) or '+' is read.
9200 Handle any notification that arrives in the mean time. */
c906108c
SS
9201 while (1)
9202 {
9203 ch = readchar (remote_timeout);
9204
c5aa993b 9205 if (remote_debug)
c906108c
SS
9206 {
9207 switch (ch)
9208 {
9209 case '+':
1216fa2c 9210 case '-':
c906108c
SS
9211 case SERIAL_TIMEOUT:
9212 case '$':
74531fed 9213 case '%':
c906108c
SS
9214 if (started_error_output)
9215 {
9216 putchar_unfiltered ('\n');
9217 started_error_output = 0;
9218 }
9219 }
9220 }
9221
9222 switch (ch)
9223 {
9224 case '+':
9225 if (remote_debug)
0f71a2f6 9226 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 9227 return 1;
1216fa2c
AC
9228 case '-':
9229 if (remote_debug)
9230 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 9231 /* FALLTHROUGH */
c906108c 9232 case SERIAL_TIMEOUT:
c5aa993b 9233 tcount++;
c906108c 9234 if (tcount > 3)
b80406ac 9235 return 0;
23860348 9236 break; /* Retransmit buffer. */
c906108c
SS
9237 case '$':
9238 {
40e3f985 9239 if (remote_debug)
2bc416ba 9240 fprintf_unfiltered (gdb_stdlog,
23860348 9241 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
9242 /* It's probably an old response sent because an ACK
9243 was lost. Gobble up the packet and ack it so it
9244 doesn't get retransmitted when we resend this
9245 packet. */
6d820c5c 9246 skip_frame ();
c33e31fd 9247 remote_serial_write ("+", 1);
23860348 9248 continue; /* Now, go look for +. */
c906108c 9249 }
74531fed
PA
9250
9251 case '%':
9252 {
9253 int val;
9254
9255 /* If we got a notification, handle it, and go back to looking
9256 for an ack. */
9257 /* We've found the start of a notification. Now
9258 collect the data. */
9259 val = read_frame (&rs->buf, &rs->buf_size);
9260 if (val >= 0)
9261 {
9262 if (remote_debug)
9263 {
b3ced9ba 9264 std::string str = escape_buffer (rs->buf, val);
6e5abd65 9265
6e5abd65
PA
9266 fprintf_unfiltered (gdb_stdlog,
9267 " Notification received: %s\n",
b3ced9ba 9268 str.c_str ());
74531fed 9269 }
5965e028 9270 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
9271 /* We're in sync now, rewait for the ack. */
9272 tcount = 0;
9273 }
9274 else
9275 {
9276 if (remote_debug)
9277 {
9278 if (!started_error_output)
9279 {
9280 started_error_output = 1;
9281 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9282 }
9283 fputc_unfiltered (ch & 0177, gdb_stdlog);
9284 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9285 }
9286 }
9287 continue;
9288 }
9289 /* fall-through */
c906108c
SS
9290 default:
9291 if (remote_debug)
9292 {
9293 if (!started_error_output)
9294 {
9295 started_error_output = 1;
0f71a2f6 9296 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 9297 }
0f71a2f6 9298 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
9299 }
9300 continue;
9301 }
23860348 9302 break; /* Here to retransmit. */
c906108c
SS
9303 }
9304
9305#if 0
9306 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
9307 able to get out next time we call QUIT, without anything as
9308 violent as interrupt_query. If we want to provide a way out of
9309 here without getting to the next QUIT, it should be based on
9310 hitting ^C twice as in remote_wait. */
c906108c
SS
9311 if (quit_flag)
9312 {
9313 quit_flag = 0;
9314 interrupt_query ();
9315 }
9316#endif
9317 }
a5c0808e 9318
a6f3e723 9319 return 0;
c906108c
SS
9320}
9321
6d820c5c
DJ
9322/* Come here after finding the start of a frame when we expected an
9323 ack. Do our best to discard the rest of this packet. */
9324
6b8edb51
PA
9325void
9326remote_target::skip_frame ()
6d820c5c
DJ
9327{
9328 int c;
9329
9330 while (1)
9331 {
9332 c = readchar (remote_timeout);
9333 switch (c)
9334 {
9335 case SERIAL_TIMEOUT:
9336 /* Nothing we can do. */
9337 return;
9338 case '#':
9339 /* Discard the two bytes of checksum and stop. */
9340 c = readchar (remote_timeout);
9341 if (c >= 0)
9342 c = readchar (remote_timeout);
9343
9344 return;
9345 case '*': /* Run length encoding. */
9346 /* Discard the repeat count. */
9347 c = readchar (remote_timeout);
9348 if (c < 0)
9349 return;
9350 break;
9351 default:
9352 /* A regular character. */
9353 break;
9354 }
9355 }
9356}
9357
c906108c 9358/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9359 into *BUF, verifying the checksum, length, and handling run-length
9360 compression. NUL terminate the buffer. If there is not enough room,
9361 expand *BUF using xrealloc.
c906108c 9362
c2d11a7d
JM
9363 Returns -1 on error, number of characters in buffer (ignoring the
9364 trailing NULL) on success. (could be extended to return one of the
23860348 9365 SERIAL status indications). */
c2d11a7d 9366
6b8edb51
PA
9367long
9368remote_target::read_frame (char **buf_p, long *sizeof_buf)
c906108c
SS
9369{
9370 unsigned char csum;
c2d11a7d 9371 long bc;
c906108c 9372 int c;
6d820c5c 9373 char *buf = *buf_p;
a6f3e723 9374 struct remote_state *rs = get_remote_state ();
c906108c
SS
9375
9376 csum = 0;
c2d11a7d 9377 bc = 0;
c906108c
SS
9378
9379 while (1)
9380 {
9381 c = readchar (remote_timeout);
c906108c
SS
9382 switch (c)
9383 {
9384 case SERIAL_TIMEOUT:
9385 if (remote_debug)
0f71a2f6 9386 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 9387 return -1;
c906108c
SS
9388 case '$':
9389 if (remote_debug)
0f71a2f6
JM
9390 fputs_filtered ("Saw new packet start in middle of old one\n",
9391 gdb_stdlog);
23860348 9392 return -1; /* Start a new packet, count retries. */
c906108c
SS
9393 case '#':
9394 {
9395 unsigned char pktcsum;
e1b09194
AC
9396 int check_0 = 0;
9397 int check_1 = 0;
c906108c 9398
c2d11a7d 9399 buf[bc] = '\0';
c906108c 9400
e1b09194
AC
9401 check_0 = readchar (remote_timeout);
9402 if (check_0 >= 0)
9403 check_1 = readchar (remote_timeout);
802188a7 9404
e1b09194
AC
9405 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9406 {
9407 if (remote_debug)
2bc416ba 9408 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 9409 gdb_stdlog);
e1b09194
AC
9410 return -1;
9411 }
9412 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
9413 {
9414 if (remote_debug)
2bc416ba 9415 fputs_filtered ("Communication error in checksum\n",
23860348 9416 gdb_stdlog);
40e3f985
FN
9417 return -1;
9418 }
c906108c 9419
a6f3e723
SL
9420 /* Don't recompute the checksum; with no ack packets we
9421 don't have any way to indicate a packet retransmission
9422 is necessary. */
9423 if (rs->noack_mode)
9424 return bc;
9425
e1b09194 9426 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9427 if (csum == pktcsum)
c2d11a7d 9428 return bc;
c906108c 9429
c5aa993b 9430 if (remote_debug)
c906108c 9431 {
b3ced9ba 9432 std::string str = escape_buffer (buf, bc);
6e5abd65 9433
6e5abd65 9434 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9435 "Bad checksum, sentsum=0x%x, "
9436 "csum=0x%x, buf=%s\n",
b3ced9ba 9437 pktcsum, csum, str.c_str ());
c906108c 9438 }
c2d11a7d 9439 /* Number of characters in buffer ignoring trailing
23860348 9440 NULL. */
c2d11a7d 9441 return -1;
c906108c 9442 }
23860348 9443 case '*': /* Run length encoding. */
c2c6d25f
JM
9444 {
9445 int repeat;
c906108c 9446
a744cf53 9447 csum += c;
b4501125
AC
9448 c = readchar (remote_timeout);
9449 csum += c;
23860348 9450 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9451
23860348 9452 /* The character before ``*'' is repeated. */
c2d11a7d 9453
6d820c5c 9454 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9455 {
6d820c5c
DJ
9456 if (bc + repeat - 1 >= *sizeof_buf - 1)
9457 {
9458 /* Make some more room in the buffer. */
9459 *sizeof_buf += repeat;
224c3ddb 9460 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
9461 buf = *buf_p;
9462 }
9463
c2d11a7d
JM
9464 memset (&buf[bc], buf[bc - 1], repeat);
9465 bc += repeat;
c2c6d25f
JM
9466 continue;
9467 }
9468
c2d11a7d 9469 buf[bc] = '\0';
6d820c5c 9470 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9471 return -1;
c2c6d25f 9472 }
c906108c 9473 default:
6d820c5c 9474 if (bc >= *sizeof_buf - 1)
c906108c 9475 {
6d820c5c
DJ
9476 /* Make some more room in the buffer. */
9477 *sizeof_buf *= 2;
224c3ddb 9478 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 9479 buf = *buf_p;
c906108c
SS
9480 }
9481
6d820c5c
DJ
9482 buf[bc++] = c;
9483 csum += c;
9484 continue;
c906108c
SS
9485 }
9486 }
9487}
9488
9489/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9490 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9491 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9492 rather than timing out; this is used (in synchronous mode) to wait
9493 for a target that is is executing user code to stop. */
d9fcf2fb
JM
9494/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9495 don't have to change all the calls to getpkt to deal with the
9496 return value, because at the moment I don't know what the right
23860348 9497 thing to do it for those. */
6b8edb51 9498
c906108c 9499void
6b8edb51 9500remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
d9fcf2fb 9501{
54887903 9502 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
9503}
9504
9505
9506/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9507 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9508 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9509 rather than timing out; this is used (in synchronous mode) to wait
9510 for a target that is is executing user code to stop. If FOREVER ==
9511 0, this function is allowed to time out gracefully and return an
74531fed
PA
9512 indication of this to the caller. Otherwise return the number of
9513 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
9514 enough reason to return to the caller. *IS_NOTIF is an output
9515 boolean that indicates whether *BUF holds a notification or not
9516 (a regular packet). */
74531fed 9517
6b8edb51
PA
9518int
9519remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9520 int forever, int expecting_notif,
9521 int *is_notif)
c906108c 9522{
2d717e4f 9523 struct remote_state *rs = get_remote_state ();
c906108c
SS
9524 int c;
9525 int tries;
9526 int timeout;
df4b58fe 9527 int val = -1;
c906108c 9528
2d717e4f
DJ
9529 /* We're reading a new response. Make sure we don't look at a
9530 previously cached response. */
9531 rs->cached_wait_status = 0;
9532
6d820c5c 9533 strcpy (*buf, "timeout");
c906108c
SS
9534
9535 if (forever)
74531fed
PA
9536 timeout = watchdog > 0 ? watchdog : -1;
9537 else if (expecting_notif)
9538 timeout = 0; /* There should already be a char in the buffer. If
9539 not, bail out. */
c906108c
SS
9540 else
9541 timeout = remote_timeout;
9542
9543#define MAX_TRIES 3
9544
74531fed
PA
9545 /* Process any number of notifications, and then return when
9546 we get a packet. */
9547 for (;;)
c906108c 9548 {
d9c43928 9549 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9550 times. */
9551 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9552 {
74531fed
PA
9553 /* This can loop forever if the remote side sends us
9554 characters continuously, but if it pauses, we'll get
9555 SERIAL_TIMEOUT from readchar because of timeout. Then
9556 we'll count that as a retry.
9557
9558 Note that even when forever is set, we will only wait
9559 forever prior to the start of a packet. After that, we
9560 expect characters to arrive at a brisk pace. They should
9561 show up within remote_timeout intervals. */
9562 do
9563 c = readchar (timeout);
9564 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9565
9566 if (c == SERIAL_TIMEOUT)
9567 {
74531fed
PA
9568 if (expecting_notif)
9569 return -1; /* Don't complain, it's normal to not get
9570 anything in this case. */
9571
23860348 9572 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9573 {
78a095c3 9574 remote_unpush_target ();
598d3636
JK
9575 throw_error (TARGET_CLOSE_ERROR,
9576 _("Watchdog timeout has expired. "
9577 "Target detached."));
c906108c 9578 }
c906108c 9579 if (remote_debug)
0f71a2f6 9580 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9581 }
74531fed
PA
9582 else
9583 {
9584 /* We've found the start of a packet or notification.
9585 Now collect the data. */
9586 val = read_frame (buf, sizeof_buf);
9587 if (val >= 0)
9588 break;
9589 }
9590
c33e31fd 9591 remote_serial_write ("-", 1);
c906108c 9592 }
c906108c 9593
74531fed
PA
9594 if (tries > MAX_TRIES)
9595 {
9596 /* We have tried hard enough, and just can't receive the
9597 packet/notification. Give up. */
9598 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9599
74531fed
PA
9600 /* Skip the ack char if we're in no-ack mode. */
9601 if (!rs->noack_mode)
c33e31fd 9602 remote_serial_write ("+", 1);
74531fed
PA
9603 return -1;
9604 }
c906108c 9605
74531fed
PA
9606 /* If we got an ordinary packet, return that to our caller. */
9607 if (c == '$')
c906108c
SS
9608 {
9609 if (remote_debug)
43e526b9 9610 {
6f8976bf
YQ
9611 std::string str
9612 = escape_buffer (*buf,
9613 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9614
9615 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9616 str.c_str ());
9617
567a3e54
SM
9618 if (val > REMOTE_DEBUG_MAX_CHAR)
9619 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9620 val - REMOTE_DEBUG_MAX_CHAR);
6e5abd65 9621
6f8976bf 9622 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9623 }
a6f3e723
SL
9624
9625 /* Skip the ack char if we're in no-ack mode. */
9626 if (!rs->noack_mode)
c33e31fd 9627 remote_serial_write ("+", 1);
fee9eda9
YQ
9628 if (is_notif != NULL)
9629 *is_notif = 0;
0876f84a 9630 return val;
c906108c
SS
9631 }
9632
74531fed
PA
9633 /* If we got a notification, handle it, and go back to looking
9634 for a packet. */
9635 else
9636 {
9637 gdb_assert (c == '%');
9638
9639 if (remote_debug)
9640 {
b3ced9ba 9641 std::string str = escape_buffer (*buf, val);
6e5abd65 9642
6e5abd65
PA
9643 fprintf_unfiltered (gdb_stdlog,
9644 " Notification received: %s\n",
b3ced9ba 9645 str.c_str ());
74531fed 9646 }
fee9eda9
YQ
9647 if (is_notif != NULL)
9648 *is_notif = 1;
c906108c 9649
5965e028 9650 handle_notification (rs->notif_state, *buf);
c906108c 9651
74531fed 9652 /* Notifications require no acknowledgement. */
a6f3e723 9653
74531fed 9654 if (expecting_notif)
fee9eda9 9655 return val;
74531fed
PA
9656 }
9657 }
9658}
9659
6b8edb51
PA
9660int
9661remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
74531fed 9662{
fee9eda9 9663 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
9664}
9665
6b8edb51
PA
9666int
9667remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9668 int *is_notif)
74531fed 9669{
fee9eda9
YQ
9670 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9671 is_notif);
c906108c 9672}
74531fed 9673
cbb8991c
DB
9674/* Kill any new fork children of process PID that haven't been
9675 processed by follow_fork. */
9676
6b8edb51
PA
9677void
9678remote_target::kill_new_fork_children (int pid)
cbb8991c 9679{
6b8edb51 9680 remote_state *rs = get_remote_state ();
cbb8991c
DB
9681 struct thread_info *thread;
9682 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
9683
9684 /* Kill the fork child threads of any threads in process PID
9685 that are stopped at a fork event. */
9686 ALL_NON_EXITED_THREADS (thread)
9687 {
9688 struct target_waitstatus *ws = &thread->pending_follow;
9689
9690 if (is_pending_fork_parent (ws, pid, thread->ptid))
9691 {
953edf2b 9692 int child_pid = ws->value.related_pid.pid ();
cbb8991c
DB
9693 int res;
9694
6b8edb51 9695 res = remote_vkill (child_pid);
cbb8991c
DB
9696 if (res != 0)
9697 error (_("Can't kill fork child process %d"), child_pid);
9698 }
9699 }
9700
9701 /* Check for any pending fork events (not reported or processed yet)
9702 in process PID and kill those fork child threads as well. */
9703 remote_notif_get_pending_events (notif);
953edf2b
TT
9704 for (auto &event : rs->stop_reply_queue)
9705 if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9706 {
9707 int child_pid = event->ws.value.related_pid.pid ();
9708 int res;
9709
9710 res = remote_vkill (child_pid);
9711 if (res != 0)
9712 error (_("Can't kill fork child process %d"), child_pid);
9713 }
cbb8991c
DB
9714}
9715
c906108c 9716\f
8020350c
DB
9717/* Target hook to kill the current inferior. */
9718
f6ac5f3d
PA
9719void
9720remote_target::kill ()
43ff13b4 9721{
8020350c
DB
9722 int res = -1;
9723 int pid = ptid_get_pid (inferior_ptid);
9724 struct remote_state *rs = get_remote_state ();
0fdf84ca 9725
8020350c 9726 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9727 {
8020350c
DB
9728 /* If we're stopped while forking and we haven't followed yet,
9729 kill the child task. We need to do this before killing the
9730 parent task because if this is a vfork then the parent will
9731 be sleeping. */
6b8edb51 9732 kill_new_fork_children (pid);
8020350c 9733
6b8edb51 9734 res = remote_vkill (pid);
8020350c 9735 if (res == 0)
0fdf84ca 9736 {
bc1e6c81 9737 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9738 return;
9739 }
8020350c 9740 }
0fdf84ca 9741
8020350c
DB
9742 /* If we are in 'target remote' mode and we are killing the only
9743 inferior, then we will tell gdbserver to exit and unpush the
9744 target. */
9745 if (res == -1 && !remote_multi_process_p (rs)
9746 && number_of_live_inferiors () == 1)
9747 {
9748 remote_kill_k ();
9749
9750 /* We've killed the remote end, we get to mourn it. If we are
9751 not in extended mode, mourning the inferior also unpushes
9752 remote_ops from the target stack, which closes the remote
9753 connection. */
bc1e6c81 9754 target_mourn_inferior (inferior_ptid);
8020350c
DB
9755
9756 return;
0fdf84ca 9757 }
43ff13b4 9758
8020350c 9759 error (_("Can't kill process"));
43ff13b4
JM
9760}
9761
8020350c
DB
9762/* Send a kill request to the target using the 'vKill' packet. */
9763
6b8edb51
PA
9764int
9765remote_target::remote_vkill (int pid)
82f73884 9766{
4082afcc 9767 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9768 return -1;
9769
6b8edb51
PA
9770 remote_state *rs = get_remote_state ();
9771
82f73884 9772 /* Tell the remote target to detach. */
bba74b36 9773 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
9774 putpkt (rs->buf);
9775 getpkt (&rs->buf, &rs->buf_size, 0);
9776
4082afcc
PA
9777 switch (packet_ok (rs->buf,
9778 &remote_protocol_packets[PACKET_vKill]))
9779 {
9780 case PACKET_OK:
9781 return 0;
9782 case PACKET_ERROR:
9783 return 1;
9784 case PACKET_UNKNOWN:
9785 return -1;
9786 default:
9787 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9788 }
82f73884
PA
9789}
9790
8020350c
DB
9791/* Send a kill request to the target using the 'k' packet. */
9792
6b8edb51
PA
9793void
9794remote_target::remote_kill_k ()
82f73884 9795{
8020350c
DB
9796 /* Catch errors so the user can quit from gdb even when we
9797 aren't on speaking terms with the remote system. */
9798 TRY
82f73884 9799 {
82f73884 9800 putpkt ("k");
82f73884 9801 }
8020350c
DB
9802 CATCH (ex, RETURN_MASK_ERROR)
9803 {
9804 if (ex.error == TARGET_CLOSE_ERROR)
9805 {
9806 /* If we got an (EOF) error that caused the target
9807 to go away, then we're done, that's what we wanted.
9808 "k" is susceptible to cause a premature EOF, given
9809 that the remote server isn't actually required to
9810 reply to "k", and it can happen that it doesn't
9811 even get to reply ACK to the "k". */
9812 return;
9813 }
82f73884 9814
8020350c
DB
9815 /* Otherwise, something went wrong. We didn't actually kill
9816 the target. Just propagate the exception, and let the
9817 user or higher layers decide what to do. */
9818 throw_exception (ex);
9819 }
9820 END_CATCH
82f73884
PA
9821}
9822
f6ac5f3d
PA
9823void
9824remote_target::mourn_inferior ()
c906108c 9825{
8020350c 9826 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9827
9607784a
PA
9828 /* We're no longer interested in notification events of an inferior
9829 that exited or was killed/detached. */
9830 discard_pending_stop_replies (current_inferior ());
9831
8020350c
DB
9832 /* In 'target remote' mode with one inferior, we close the connection. */
9833 if (!rs->extended && number_of_live_inferiors () <= 1)
9834 {
f6ac5f3d 9835 unpush_target (this);
c906108c 9836
8020350c
DB
9837 /* remote_close takes care of doing most of the clean up. */
9838 generic_mourn_inferior ();
9839 return;
9840 }
c906108c 9841
e24a49d8
PA
9842 /* In case we got here due to an error, but we're going to stay
9843 connected. */
9844 rs->waiting_for_stop_reply = 0;
9845
dc1981d7
PA
9846 /* If the current general thread belonged to the process we just
9847 detached from or has exited, the remote side current general
9848 thread becomes undefined. Considering a case like this:
9849
9850 - We just got here due to a detach.
9851 - The process that we're detaching from happens to immediately
9852 report a global breakpoint being hit in non-stop mode, in the
9853 same thread we had selected before.
9854 - GDB attaches to this process again.
9855 - This event happens to be the next event we handle.
9856
9857 GDB would consider that the current general thread didn't need to
9858 be set on the stub side (with Hg), since for all it knew,
9859 GENERAL_THREAD hadn't changed.
9860
9861 Notice that although in all-stop mode, the remote server always
9862 sets the current thread to the thread reporting the stop event,
9863 that doesn't happen in non-stop mode; in non-stop, the stub *must
9864 not* change the current thread when reporting a breakpoint hit,
9865 due to the decoupling of event reporting and event handling.
9866
9867 To keep things simple, we always invalidate our notion of the
9868 current thread. */
47f8a51d 9869 record_currthread (rs, minus_one_ptid);
dc1981d7 9870
8020350c 9871 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9872 generic_mourn_inferior ();
9873
d729566a 9874 if (!have_inferiors ())
2d717e4f 9875 {
82f73884
PA
9876 if (!remote_multi_process_p (rs))
9877 {
9878 /* Check whether the target is running now - some remote stubs
9879 automatically restart after kill. */
9880 putpkt ("?");
9881 getpkt (&rs->buf, &rs->buf_size, 0);
9882
9883 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9884 {
3e43a32a
MS
9885 /* Assume that the target has been restarted. Set
9886 inferior_ptid so that bits of core GDB realizes
9887 there's something here, e.g., so that the user can
9888 say "kill" again. */
82f73884
PA
9889 inferior_ptid = magic_null_ptid;
9890 }
82f73884 9891 }
2d717e4f
DJ
9892 }
9893}
c906108c 9894
57810aa7 9895bool
f6ac5f3d 9896extended_remote_target::supports_disable_randomization ()
03583c20 9897{
4082afcc 9898 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9899}
9900
6b8edb51
PA
9901void
9902remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
9903{
9904 struct remote_state *rs = get_remote_state ();
9905 char *reply;
9906
bba74b36
YQ
9907 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9908 val);
03583c20 9909 putpkt (rs->buf);
b6bb3468 9910 reply = remote_get_noisy_reply ();
03583c20
UW
9911 if (*reply == '\0')
9912 error (_("Target does not support QDisableRandomization."));
9913 if (strcmp (reply, "OK") != 0)
9914 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9915}
9916
6b8edb51
PA
9917int
9918remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
9919{
9920 struct remote_state *rs = get_remote_state ();
2d717e4f 9921 int len;
94585166 9922 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9923
2d717e4f
DJ
9924 /* If the user has disabled vRun support, or we have detected that
9925 support is not available, do not try it. */
4082afcc 9926 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9927 return -1;
424163ea 9928
2d717e4f
DJ
9929 strcpy (rs->buf, "vRun;");
9930 len = strlen (rs->buf);
c906108c 9931
2d717e4f
DJ
9932 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9933 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9934 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9935 strlen (remote_exec_file));
2d717e4f 9936
7c5ded6a 9937 if (!args.empty ())
2d717e4f 9938 {
2d717e4f 9939 int i;
2d717e4f 9940
773a1edc 9941 gdb_argv argv (args.c_str ());
2d717e4f
DJ
9942 for (i = 0; argv[i] != NULL; i++)
9943 {
9944 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9945 error (_("Argument list too long for run packet"));
9946 rs->buf[len++] = ';';
9f1b45b0
TT
9947 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9948 strlen (argv[i]));
2d717e4f 9949 }
2d717e4f
DJ
9950 }
9951
9952 rs->buf[len++] = '\0';
9953
9954 putpkt (rs->buf);
9955 getpkt (&rs->buf, &rs->buf_size, 0);
9956
4082afcc 9957 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9958 {
4082afcc 9959 case PACKET_OK:
3405876a 9960 /* We have a wait response. All is well. */
2d717e4f 9961 return 0;
4082afcc
PA
9962 case PACKET_UNKNOWN:
9963 return -1;
9964 case PACKET_ERROR:
2d717e4f
DJ
9965 if (remote_exec_file[0] == '\0')
9966 error (_("Running the default executable on the remote target failed; "
9967 "try \"set remote exec-file\"?"));
9968 else
9969 error (_("Running \"%s\" on the remote target failed"),
9970 remote_exec_file);
4082afcc
PA
9971 default:
9972 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9973 }
c906108c
SS
9974}
9975
0a2dde4a
SDJ
9976/* Helper function to send set/unset environment packets. ACTION is
9977 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9978 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9979 sent. */
9980
6b8edb51
PA
9981void
9982remote_target::send_environment_packet (const char *action,
9983 const char *packet,
9984 const char *value)
0a2dde4a 9985{
6b8edb51
PA
9986 remote_state *rs = get_remote_state ();
9987
0a2dde4a
SDJ
9988 /* Convert the environment variable to an hex string, which
9989 is the best format to be transmitted over the wire. */
9990 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9991 strlen (value));
9992
9993 xsnprintf (rs->buf, get_remote_packet_size (),
9994 "%s:%s", packet, encoded_value.c_str ());
9995
9996 putpkt (rs->buf);
9997 getpkt (&rs->buf, &rs->buf_size, 0);
9998 if (strcmp (rs->buf, "OK") != 0)
9999 warning (_("Unable to %s environment variable '%s' on remote."),
10000 action, value);
10001}
10002
10003/* Helper function to handle the QEnvironment* packets. */
10004
6b8edb51
PA
10005void
10006remote_target::extended_remote_environment_support ()
0a2dde4a 10007{
6b8edb51
PA
10008 remote_state *rs = get_remote_state ();
10009
0a2dde4a
SDJ
10010 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10011 {
10012 putpkt ("QEnvironmentReset");
10013 getpkt (&rs->buf, &rs->buf_size, 0);
10014 if (strcmp (rs->buf, "OK") != 0)
10015 warning (_("Unable to reset environment on remote."));
10016 }
10017
10018 gdb_environ *e = &current_inferior ()->environment;
10019
10020 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10021 for (const std::string &el : e->user_set_env ())
6b8edb51 10022 send_environment_packet ("set", "QEnvironmentHexEncoded",
0a2dde4a
SDJ
10023 el.c_str ());
10024
10025 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10026 for (const std::string &el : e->user_unset_env ())
6b8edb51 10027 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10028}
10029
bc3b087d
SDJ
10030/* Helper function to set the current working directory for the
10031 inferior in the remote target. */
10032
6b8edb51
PA
10033void
10034remote_target::extended_remote_set_inferior_cwd ()
bc3b087d
SDJ
10035{
10036 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10037 {
10038 const char *inferior_cwd = get_inferior_cwd ();
6b8edb51 10039 remote_state *rs = get_remote_state ();
bc3b087d
SDJ
10040
10041 if (inferior_cwd != NULL)
10042 {
10043 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10044 strlen (inferior_cwd));
10045
10046 xsnprintf (rs->buf, get_remote_packet_size (),
10047 "QSetWorkingDir:%s", hexpath.c_str ());
10048 }
10049 else
10050 {
10051 /* An empty inferior_cwd means that the user wants us to
10052 reset the remote server's inferior's cwd. */
10053 xsnprintf (rs->buf, get_remote_packet_size (),
10054 "QSetWorkingDir:");
10055 }
10056
10057 putpkt (rs->buf);
10058 getpkt (&rs->buf, &rs->buf_size, 0);
10059 if (packet_ok (rs->buf,
10060 &remote_protocol_packets[PACKET_QSetWorkingDir])
10061 != PACKET_OK)
10062 error (_("\
10063Remote replied unexpectedly while setting the inferior's working\n\
10064directory: %s"),
10065 rs->buf);
10066
10067 }
10068}
10069
2d717e4f
DJ
10070/* In the extended protocol we want to be able to do things like
10071 "run" and have them basically work as expected. So we need
10072 a special create_inferior function. We support changing the
10073 executable file and the command line arguments, but not the
10074 environment. */
10075
f6ac5f3d
PA
10076void
10077extended_remote_target::create_inferior (const char *exec_file,
10078 const std::string &args,
10079 char **env, int from_tty)
43ff13b4 10080{
3405876a
PA
10081 int run_worked;
10082 char *stop_reply;
10083 struct remote_state *rs = get_remote_state ();
94585166 10084 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10085
43ff13b4 10086 /* If running asynchronously, register the target file descriptor
23860348 10087 with the event loop. */
75c99385 10088 if (target_can_async_p ())
6a3753b3 10089 target_async (1);
43ff13b4 10090
03583c20 10091 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10092 if (supports_disable_randomization ())
03583c20
UW
10093 extended_remote_disable_randomization (disable_randomization);
10094
aefd8b33
SDJ
10095 /* If startup-with-shell is on, we inform gdbserver to start the
10096 remote inferior using a shell. */
10097 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10098 {
10099 xsnprintf (rs->buf, get_remote_packet_size (),
10100 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10101 putpkt (rs->buf);
10102 getpkt (&rs->buf, &rs->buf_size, 0);
10103 if (strcmp (rs->buf, "OK") != 0)
10104 error (_("\
10105Remote replied unexpectedly while setting startup-with-shell: %s"),
10106 rs->buf);
10107 }
10108
6b8edb51 10109 extended_remote_environment_support ();
0a2dde4a 10110
6b8edb51 10111 extended_remote_set_inferior_cwd ();
bc3b087d 10112
43ff13b4 10113 /* Now restart the remote server. */
3405876a
PA
10114 run_worked = extended_remote_run (args) != -1;
10115 if (!run_worked)
2d717e4f
DJ
10116 {
10117 /* vRun was not supported. Fail if we need it to do what the
10118 user requested. */
10119 if (remote_exec_file[0])
10120 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10121 if (!args.empty ())
2d717e4f 10122 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 10123
2d717e4f
DJ
10124 /* Fall back to "R". */
10125 extended_remote_restart ();
10126 }
424163ea 10127
6c95b8df
PA
10128 if (!have_inferiors ())
10129 {
10130 /* Clean up from the last time we ran, before we mark the target
10131 running again. This will mark breakpoints uninserted, and
10132 get_offsets may insert breakpoints. */
10133 init_thread_list ();
10134 init_wait_for_inferior ();
10135 }
45280a52 10136
3405876a
PA
10137 /* vRun's success return is a stop reply. */
10138 stop_reply = run_worked ? rs->buf : NULL;
10139 add_current_inferior_and_thread (stop_reply);
c0a2216e 10140
2d717e4f
DJ
10141 /* Get updated offsets, if the stub uses qOffsets. */
10142 get_offsets ();
2d717e4f 10143}
c906108c 10144\f
c5aa993b 10145
b775012e
LM
10146/* Given a location's target info BP_TGT and the packet buffer BUF, output
10147 the list of conditions (in agent expression bytecode format), if any, the
10148 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10149 started from BUF and ended at BUF_END. */
b775012e
LM
10150
10151static int
10152remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10153 struct bp_target_info *bp_tgt, char *buf,
10154 char *buf_end)
b775012e 10155{
3cde5c42 10156 if (bp_tgt->conditions.empty ())
b775012e
LM
10157 return 0;
10158
10159 buf += strlen (buf);
bba74b36 10160 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10161 buf++;
10162
83621223 10163 /* Send conditions to the target. */
d538e36d 10164 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10165 {
bba74b36 10166 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 10167 buf += strlen (buf);
3cde5c42 10168 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
10169 buf = pack_hex_byte (buf, aexpr->buf[i]);
10170 *buf = '\0';
10171 }
b775012e
LM
10172 return 0;
10173}
10174
d3ce09f5
SS
10175static void
10176remote_add_target_side_commands (struct gdbarch *gdbarch,
10177 struct bp_target_info *bp_tgt, char *buf)
10178{
3cde5c42 10179 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10180 return;
10181
10182 buf += strlen (buf);
10183
10184 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10185 buf += strlen (buf);
10186
10187 /* Concatenate all the agent expressions that are commands into the
10188 cmds parameter. */
df97be55 10189 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
10190 {
10191 sprintf (buf, "X%x,", aexpr->len);
10192 buf += strlen (buf);
3cde5c42 10193 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
10194 buf = pack_hex_byte (buf, aexpr->buf[i]);
10195 *buf = '\0';
10196 }
d3ce09f5
SS
10197}
10198
8181d85f
DJ
10199/* Insert a breakpoint. On targets that have software breakpoint
10200 support, we ask the remote target to do the work; on targets
10201 which don't, we insert a traditional memory breakpoint. */
c906108c 10202
f6ac5f3d
PA
10203int
10204remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10205 struct bp_target_info *bp_tgt)
c906108c 10206{
d471ea57
AC
10207 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10208 If it succeeds, then set the support to PACKET_ENABLE. If it
10209 fails, and the user has explicitly requested the Z support then
23860348 10210 report an error, otherwise, mark it disabled and go on. */
802188a7 10211
4082afcc 10212 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10213 {
0d5ed153 10214 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10215 struct remote_state *rs;
bba74b36 10216 char *p, *endbuf;
4fff2411 10217
28439a30
PA
10218 /* Make sure the remote is pointing at the right process, if
10219 necessary. */
10220 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10221 set_general_process ();
10222
4fff2411
JZ
10223 rs = get_remote_state ();
10224 p = rs->buf;
bba74b36 10225 endbuf = rs->buf + get_remote_packet_size ();
802188a7 10226
96baa820
JM
10227 *(p++) = 'Z';
10228 *(p++) = '0';
10229 *(p++) = ',';
7c0f6dcc 10230 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10231 p += hexnumstr (p, addr);
579c6ad9 10232 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10233
f6ac5f3d 10234 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10235 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10236
f6ac5f3d 10237 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10238 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10239
6d820c5c
DJ
10240 putpkt (rs->buf);
10241 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10242
6d820c5c 10243 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 10244 {
d471ea57
AC
10245 case PACKET_ERROR:
10246 return -1;
10247 case PACKET_OK:
10248 return 0;
10249 case PACKET_UNKNOWN:
10250 break;
96baa820
JM
10251 }
10252 }
c906108c 10253
0000e5cc
PA
10254 /* If this breakpoint has target-side commands but this stub doesn't
10255 support Z0 packets, throw error. */
3cde5c42 10256 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10257 throw_error (NOT_SUPPORTED_ERROR, _("\
10258Target doesn't support breakpoints that have target side commands."));
10259
f6ac5f3d 10260 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10261}
10262
f6ac5f3d
PA
10263int
10264remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10265 struct bp_target_info *bp_tgt,
10266 enum remove_bp_reason reason)
c906108c 10267{
8181d85f 10268 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10269 struct remote_state *rs = get_remote_state ();
96baa820 10270
4082afcc 10271 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10272 {
6d820c5c 10273 char *p = rs->buf;
bba74b36 10274 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 10275
28439a30
PA
10276 /* Make sure the remote is pointing at the right process, if
10277 necessary. */
10278 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10279 set_general_process ();
10280
96baa820
JM
10281 *(p++) = 'z';
10282 *(p++) = '0';
10283 *(p++) = ',';
10284
8181d85f
DJ
10285 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10286 p += hexnumstr (p, addr);
579c6ad9 10287 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10288
6d820c5c
DJ
10289 putpkt (rs->buf);
10290 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10291
6d820c5c 10292 return (rs->buf[0] == 'E');
96baa820
JM
10293 }
10294
f6ac5f3d 10295 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10296}
10297
f486487f 10298static enum Z_packet_type
d471ea57
AC
10299watchpoint_to_Z_packet (int type)
10300{
10301 switch (type)
10302 {
10303 case hw_write:
bb858e6a 10304 return Z_PACKET_WRITE_WP;
d471ea57
AC
10305 break;
10306 case hw_read:
bb858e6a 10307 return Z_PACKET_READ_WP;
d471ea57
AC
10308 break;
10309 case hw_access:
bb858e6a 10310 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10311 break;
10312 default:
8e65ff28 10313 internal_error (__FILE__, __LINE__,
e2e0b3e5 10314 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10315 }
10316}
10317
f6ac5f3d
PA
10318int
10319remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10320 enum target_hw_bp_type type, struct expression *cond)
96baa820 10321{
d01949b6 10322 struct remote_state *rs = get_remote_state ();
bba74b36 10323 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10324 char *p;
d471ea57 10325 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10326
4082afcc 10327 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10328 return 1;
802188a7 10329
28439a30
PA
10330 /* Make sure the remote is pointing at the right process, if
10331 necessary. */
10332 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10333 set_general_process ();
10334
bba74b36 10335 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 10336 p = strchr (rs->buf, '\0');
96baa820
JM
10337 addr = remote_address_masked (addr);
10338 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10339 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10340
6d820c5c
DJ
10341 putpkt (rs->buf);
10342 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10343
6d820c5c 10344 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10345 {
10346 case PACKET_ERROR:
d471ea57 10347 return -1;
85d721b8
PA
10348 case PACKET_UNKNOWN:
10349 return 1;
d471ea57
AC
10350 case PACKET_OK:
10351 return 0;
10352 }
8e65ff28 10353 internal_error (__FILE__, __LINE__,
e2e0b3e5 10354 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10355}
10356
57810aa7 10357bool
f6ac5f3d
PA
10358remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10359 CORE_ADDR start, int length)
283002cf
MR
10360{
10361 CORE_ADDR diff = remote_address_masked (addr - start);
10362
10363 return diff < length;
10364}
10365
d471ea57 10366
f6ac5f3d
PA
10367int
10368remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10369 enum target_hw_bp_type type, struct expression *cond)
96baa820 10370{
d01949b6 10371 struct remote_state *rs = get_remote_state ();
bba74b36 10372 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10373 char *p;
d471ea57
AC
10374 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10375
4082afcc 10376 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10377 return -1;
802188a7 10378
28439a30
PA
10379 /* Make sure the remote is pointing at the right process, if
10380 necessary. */
10381 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10382 set_general_process ();
10383
bba74b36 10384 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 10385 p = strchr (rs->buf, '\0');
96baa820
JM
10386 addr = remote_address_masked (addr);
10387 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10388 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
10389 putpkt (rs->buf);
10390 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10391
6d820c5c 10392 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10393 {
10394 case PACKET_ERROR:
10395 case PACKET_UNKNOWN:
10396 return -1;
10397 case PACKET_OK:
10398 return 0;
10399 }
8e65ff28 10400 internal_error (__FILE__, __LINE__,
e2e0b3e5 10401 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10402}
10403
3c3bea1c 10404
501eef12 10405int remote_hw_watchpoint_limit = -1;
480a3f21 10406int remote_hw_watchpoint_length_limit = -1;
501eef12 10407int remote_hw_breakpoint_limit = -1;
d471ea57 10408
f6ac5f3d
PA
10409int
10410remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10411{
10412 if (remote_hw_watchpoint_length_limit == 0)
10413 return 0;
10414 else if (remote_hw_watchpoint_length_limit < 0)
10415 return 1;
10416 else if (len <= remote_hw_watchpoint_length_limit)
10417 return 1;
10418 else
10419 return 0;
10420}
10421
f6ac5f3d
PA
10422int
10423remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10424{
3c3bea1c
GS
10425 if (type == bp_hardware_breakpoint)
10426 {
10427 if (remote_hw_breakpoint_limit == 0)
10428 return 0;
501eef12
AC
10429 else if (remote_hw_breakpoint_limit < 0)
10430 return 1;
3c3bea1c
GS
10431 else if (cnt <= remote_hw_breakpoint_limit)
10432 return 1;
10433 }
10434 else
10435 {
10436 if (remote_hw_watchpoint_limit == 0)
10437 return 0;
501eef12
AC
10438 else if (remote_hw_watchpoint_limit < 0)
10439 return 1;
3c3bea1c
GS
10440 else if (ot)
10441 return -1;
10442 else if (cnt <= remote_hw_watchpoint_limit)
10443 return 1;
10444 }
10445 return -1;
10446}
10447
f7e6eed5
PA
10448/* The to_stopped_by_sw_breakpoint method of target remote. */
10449
57810aa7 10450bool
f6ac5f3d 10451remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10452{
799a2abe 10453 struct thread_info *thread = inferior_thread ();
f7e6eed5 10454
799a2abe 10455 return (thread->priv != NULL
7aabaf9d
SM
10456 && (get_remote_thread_info (thread)->stop_reason
10457 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10458}
10459
10460/* The to_supports_stopped_by_sw_breakpoint method of target
10461 remote. */
10462
57810aa7 10463bool
f6ac5f3d 10464remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10465{
f7e6eed5
PA
10466 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10467}
10468
10469/* The to_stopped_by_hw_breakpoint method of target remote. */
10470
57810aa7 10471bool
f6ac5f3d 10472remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10473{
799a2abe 10474 struct thread_info *thread = inferior_thread ();
f7e6eed5 10475
799a2abe 10476 return (thread->priv != NULL
7aabaf9d
SM
10477 && (get_remote_thread_info (thread)->stop_reason
10478 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10479}
10480
10481/* The to_supports_stopped_by_hw_breakpoint method of target
10482 remote. */
10483
57810aa7 10484bool
f6ac5f3d 10485remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10486{
f7e6eed5
PA
10487 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10488}
10489
57810aa7 10490bool
f6ac5f3d 10491remote_target::stopped_by_watchpoint ()
3c3bea1c 10492{
799a2abe 10493 struct thread_info *thread = inferior_thread ();
ee154bee 10494
799a2abe 10495 return (thread->priv != NULL
7aabaf9d
SM
10496 && (get_remote_thread_info (thread)->stop_reason
10497 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10498}
10499
57810aa7 10500bool
f6ac5f3d 10501remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10502{
799a2abe 10503 struct thread_info *thread = inferior_thread ();
a744cf53 10504
799a2abe 10505 if (thread->priv != NULL
7aabaf9d
SM
10506 && (get_remote_thread_info (thread)->stop_reason
10507 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10508 {
7aabaf9d 10509 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 10510 return true;
4aa7a7f5
JJ
10511 }
10512
57810aa7 10513 return false;
3c3bea1c
GS
10514}
10515
10516
f6ac5f3d
PA
10517int
10518remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10519 struct bp_target_info *bp_tgt)
3c3bea1c 10520{
0d5ed153 10521 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10522 struct remote_state *rs;
bba74b36 10523 char *p, *endbuf;
dd61ec5c 10524 char *message;
3c3bea1c 10525
4082afcc 10526 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10527 return -1;
2bc416ba 10528
28439a30
PA
10529 /* Make sure the remote is pointing at the right process, if
10530 necessary. */
10531 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10532 set_general_process ();
10533
4fff2411
JZ
10534 rs = get_remote_state ();
10535 p = rs->buf;
bba74b36 10536 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 10537
96baa820
JM
10538 *(p++) = 'Z';
10539 *(p++) = '1';
10540 *(p++) = ',';
802188a7 10541
0d5ed153 10542 addr = remote_address_masked (addr);
96baa820 10543 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10544 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10545
f6ac5f3d 10546 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10547 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10548
f6ac5f3d 10549 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10550 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10551
6d820c5c
DJ
10552 putpkt (rs->buf);
10553 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10554
6d820c5c 10555 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10556 {
10557 case PACKET_ERROR:
dd61ec5c
MW
10558 if (rs->buf[1] == '.')
10559 {
10560 message = strchr (rs->buf + 2, '.');
10561 if (message)
0316657e 10562 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10563 }
10564 return -1;
d471ea57
AC
10565 case PACKET_UNKNOWN:
10566 return -1;
10567 case PACKET_OK:
10568 return 0;
10569 }
8e65ff28 10570 internal_error (__FILE__, __LINE__,
e2e0b3e5 10571 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10572}
10573
d471ea57 10574
f6ac5f3d
PA
10575int
10576remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10577 struct bp_target_info *bp_tgt)
96baa820 10578{
8181d85f 10579 CORE_ADDR addr;
d01949b6 10580 struct remote_state *rs = get_remote_state ();
6d820c5c 10581 char *p = rs->buf;
bba74b36 10582 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 10583
4082afcc 10584 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10585 return -1;
802188a7 10586
28439a30
PA
10587 /* Make sure the remote is pointing at the right process, if
10588 necessary. */
10589 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10590 set_general_process ();
10591
96baa820
JM
10592 *(p++) = 'z';
10593 *(p++) = '1';
10594 *(p++) = ',';
802188a7 10595
8181d85f 10596 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10597 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10598 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10599
6d820c5c
DJ
10600 putpkt (rs->buf);
10601 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 10602
6d820c5c 10603 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10604 {
10605 case PACKET_ERROR:
10606 case PACKET_UNKNOWN:
10607 return -1;
10608 case PACKET_OK:
10609 return 0;
10610 }
8e65ff28 10611 internal_error (__FILE__, __LINE__,
e2e0b3e5 10612 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10613}
96baa820 10614
4a5e7a5b
PA
10615/* Verify memory using the "qCRC:" request. */
10616
f6ac5f3d
PA
10617int
10618remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
10619{
10620 struct remote_state *rs = get_remote_state ();
10621 unsigned long host_crc, target_crc;
10622 char *tmp;
10623
936d2992
PA
10624 /* It doesn't make sense to use qCRC if the remote target is
10625 connected but not running. */
10626 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10627 {
10628 enum packet_result result;
28439a30 10629
936d2992
PA
10630 /* Make sure the remote is pointing at the right process. */
10631 set_general_process ();
4a5e7a5b 10632
936d2992
PA
10633 /* FIXME: assumes lma can fit into long. */
10634 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10635 (long) lma, (long) size);
10636 putpkt (rs->buf);
4a5e7a5b 10637
936d2992
PA
10638 /* Be clever; compute the host_crc before waiting for target
10639 reply. */
10640 host_crc = xcrc32 (data, size, 0xffffffff);
10641
10642 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 10643
936d2992
PA
10644 result = packet_ok (rs->buf,
10645 &remote_protocol_packets[PACKET_qCRC]);
10646 if (result == PACKET_ERROR)
10647 return -1;
10648 else if (result == PACKET_OK)
10649 {
10650 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10651 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10652
936d2992
PA
10653 return (host_crc == target_crc);
10654 }
10655 }
4a5e7a5b 10656
f6ac5f3d 10657 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
10658}
10659
c906108c
SS
10660/* compare-sections command
10661
10662 With no arguments, compares each loadable section in the exec bfd
10663 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10664 Useful for verifying the image on the target against the exec file. */
e514a9d6 10665
c906108c 10666static void
ac88e2de 10667compare_sections_command (const char *args, int from_tty)
c906108c
SS
10668{
10669 asection *s;
ce359b09 10670 const char *sectname;
c906108c
SS
10671 bfd_size_type size;
10672 bfd_vma lma;
10673 int matched = 0;
10674 int mismatched = 0;
4a5e7a5b 10675 int res;
95cf3b38 10676 int read_only = 0;
c906108c
SS
10677
10678 if (!exec_bfd)
8a3fe4f8 10679 error (_("command cannot be used without an exec file"));
c906108c 10680
95cf3b38
DT
10681 if (args != NULL && strcmp (args, "-r") == 0)
10682 {
10683 read_only = 1;
10684 args = NULL;
10685 }
10686
c5aa993b 10687 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10688 {
10689 if (!(s->flags & SEC_LOAD))
0df8b418 10690 continue; /* Skip non-loadable section. */
c906108c 10691
95cf3b38
DT
10692 if (read_only && (s->flags & SEC_READONLY) == 0)
10693 continue; /* Skip writeable sections */
10694
2c500098 10695 size = bfd_get_section_size (s);
c906108c 10696 if (size == 0)
0df8b418 10697 continue; /* Skip zero-length section. */
c906108c 10698
ce359b09 10699 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10700 if (args && strcmp (args, sectname) != 0)
0df8b418 10701 continue; /* Not the section selected by user. */
c906108c 10702
0df8b418 10703 matched = 1; /* Do this section. */
c906108c 10704 lma = s->lma;
c906108c 10705
b80406ac
TT
10706 gdb::byte_vector sectdata (size);
10707 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
c906108c 10708
b80406ac 10709 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
10710
10711 if (res == -1)
5af949e3 10712 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10713 paddress (target_gdbarch (), lma),
10714 paddress (target_gdbarch (), lma + size));
c906108c 10715
5af949e3 10716 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10717 paddress (target_gdbarch (), lma),
10718 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10719 if (res)
c906108c
SS
10720 printf_filtered ("matched.\n");
10721 else
c5aa993b
JM
10722 {
10723 printf_filtered ("MIS-MATCHED!\n");
10724 mismatched++;
10725 }
c906108c
SS
10726 }
10727 if (mismatched > 0)
936d2992 10728 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10729the loaded file\n"));
c906108c 10730 if (args && !matched)
a3f17187 10731 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10732}
10733
0e7f50da
UW
10734/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10735 into remote target. The number of bytes written to the remote
10736 target is returned, or -1 for error. */
10737
6b8edb51
PA
10738target_xfer_status
10739remote_target::remote_write_qxfer (const char *object_name,
10740 const char *annex, const gdb_byte *writebuf,
10741 ULONGEST offset, LONGEST len,
10742 ULONGEST *xfered_len,
10743 struct packet_config *packet)
0e7f50da
UW
10744{
10745 int i, buf_len;
10746 ULONGEST n;
0e7f50da
UW
10747 struct remote_state *rs = get_remote_state ();
10748 int max_size = get_memory_write_packet_size ();
10749
7cc244de 10750 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10751 return TARGET_XFER_E_IO;
0e7f50da
UW
10752
10753 /* Insert header. */
10754 i = snprintf (rs->buf, max_size,
10755 "qXfer:%s:write:%s:%s:",
10756 object_name, annex ? annex : "",
10757 phex_nz (offset, sizeof offset));
10758 max_size -= (i + 1);
10759
10760 /* Escape as much data as fits into rs->buf. */
10761 buf_len = remote_escape_output
124e13d9 10762 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
10763
10764 if (putpkt_binary (rs->buf, i + buf_len) < 0
10765 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10766 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10767 return TARGET_XFER_E_IO;
0e7f50da
UW
10768
10769 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
10770
10771 *xfered_len = n;
92ffd475 10772 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
10773}
10774
0876f84a
DJ
10775/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10776 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10777 number of bytes read is returned, or 0 for EOF, or -1 for error.
10778 The number of bytes read may be less than LEN without indicating an
10779 EOF. PACKET is checked and updated to indicate whether the remote
10780 target supports this object. */
10781
6b8edb51
PA
10782target_xfer_status
10783remote_target::remote_read_qxfer (const char *object_name,
10784 const char *annex,
10785 gdb_byte *readbuf, ULONGEST offset,
10786 LONGEST len,
10787 ULONGEST *xfered_len,
10788 struct packet_config *packet)
0876f84a 10789{
0876f84a 10790 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10791 LONGEST i, n, packet_len;
10792
7cc244de 10793 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10794 return TARGET_XFER_E_IO;
0876f84a
DJ
10795
10796 /* Check whether we've cached an end-of-object packet that matches
10797 this request. */
8e88304f 10798 if (rs->finished_object)
0876f84a 10799 {
8e88304f
TT
10800 if (strcmp (object_name, rs->finished_object) == 0
10801 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10802 && offset == rs->finished_offset)
9b409511
YQ
10803 return TARGET_XFER_EOF;
10804
0876f84a
DJ
10805
10806 /* Otherwise, we're now reading something different. Discard
10807 the cache. */
8e88304f
TT
10808 xfree (rs->finished_object);
10809 xfree (rs->finished_annex);
10810 rs->finished_object = NULL;
10811 rs->finished_annex = NULL;
0876f84a
DJ
10812 }
10813
10814 /* Request only enough to fit in a single packet. The actual data
10815 may not, since we don't know how much of it will need to be escaped;
10816 the target is free to respond with slightly less data. We subtract
10817 five to account for the response type and the protocol frame. */
768adc05 10818 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
0876f84a
DJ
10819 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10820 object_name, annex ? annex : "",
10821 phex_nz (offset, sizeof offset),
10822 phex_nz (n, sizeof n));
10823 i = putpkt (rs->buf);
10824 if (i < 0)
2ed4b548 10825 return TARGET_XFER_E_IO;
0876f84a
DJ
10826
10827 rs->buf[0] = '\0';
10828 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10829 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10830 return TARGET_XFER_E_IO;
0876f84a
DJ
10831
10832 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10833 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10834
10835 /* 'm' means there is (or at least might be) more data after this
10836 batch. That does not make sense unless there's at least one byte
10837 of data in this reply. */
10838 if (rs->buf[0] == 'm' && packet_len == 1)
10839 error (_("Remote qXfer reply contained no data."));
10840
10841 /* Got some data. */
bc20a4af
PA
10842 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10843 packet_len - 1, readbuf, n);
0876f84a
DJ
10844
10845 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10846 or possibly empty. If we have the final block of a non-empty
10847 object, record this fact to bypass a subsequent partial read. */
10848 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10849 {
8e88304f
TT
10850 rs->finished_object = xstrdup (object_name);
10851 rs->finished_annex = xstrdup (annex ? annex : "");
10852 rs->finished_offset = offset + i;
0876f84a
DJ
10853 }
10854
9b409511
YQ
10855 if (i == 0)
10856 return TARGET_XFER_EOF;
10857 else
10858 {
10859 *xfered_len = i;
10860 return TARGET_XFER_OK;
10861 }
0876f84a
DJ
10862}
10863
f6ac5f3d
PA
10864enum target_xfer_status
10865remote_target::xfer_partial (enum target_object object,
10866 const char *annex, gdb_byte *readbuf,
10867 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10868 ULONGEST *xfered_len)
c906108c 10869{
82f73884 10870 struct remote_state *rs;
c906108c 10871 int i;
6d820c5c 10872 char *p2;
1e3ff5ad 10873 char query_type;
124e13d9 10874 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 10875
e6e4e701 10876 set_remote_traceframe ();
82f73884
PA
10877 set_general_thread (inferior_ptid);
10878
10879 rs = get_remote_state ();
10880
b2182ed2 10881 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
10882 if (object == TARGET_OBJECT_MEMORY)
10883 {
2d717e4f
DJ
10884 /* If the remote target is connected but not running, we should
10885 pass this request down to a lower stratum (e.g. the executable
10886 file). */
10887 if (!target_has_execution)
9b409511 10888 return TARGET_XFER_EOF;
2d717e4f 10889
21e3b9b9 10890 if (writebuf != NULL)
124e13d9
SM
10891 return remote_write_bytes (offset, writebuf, len, unit_size,
10892 xfered_len);
21e3b9b9 10893 else
6b8edb51 10894 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 10895 xfered_len);
21e3b9b9
DJ
10896 }
10897
0df8b418 10898 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10899 if (object == TARGET_OBJECT_SPU)
10900 {
10901 if (readbuf)
f6ac5f3d 10902 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
9b409511
YQ
10903 xfered_len, &remote_protocol_packets
10904 [PACKET_qXfer_spu_read]);
0e7f50da 10905 else
f6ac5f3d 10906 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
9b409511
YQ
10907 xfered_len, &remote_protocol_packets
10908 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10909 }
10910
4aa995e1
PA
10911 /* Handle extra signal info using qxfer packets. */
10912 if (object == TARGET_OBJECT_SIGNAL_INFO)
10913 {
10914 if (readbuf)
f6ac5f3d 10915 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
9b409511 10916 xfered_len, &remote_protocol_packets
4aa995e1
PA
10917 [PACKET_qXfer_siginfo_read]);
10918 else
f6ac5f3d 10919 return remote_write_qxfer ("siginfo", annex,
9b409511 10920 writebuf, offset, len, xfered_len,
4aa995e1
PA
10921 &remote_protocol_packets
10922 [PACKET_qXfer_siginfo_write]);
10923 }
10924
0fb4aa4b
PA
10925 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10926 {
10927 if (readbuf)
f6ac5f3d 10928 return remote_read_qxfer ("statictrace", annex,
9b409511 10929 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10930 &remote_protocol_packets
10931 [PACKET_qXfer_statictrace_read]);
10932 else
2ed4b548 10933 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10934 }
10935
a76d924d
DJ
10936 /* Only handle flash writes. */
10937 if (writebuf != NULL)
10938 {
a76d924d
DJ
10939 switch (object)
10940 {
10941 case TARGET_OBJECT_FLASH:
6b8edb51 10942 return remote_flash_write (offset, len, xfered_len,
9b409511 10943 writebuf);
a76d924d
DJ
10944
10945 default:
2ed4b548 10946 return TARGET_XFER_E_IO;
a76d924d
DJ
10947 }
10948 }
4b8a223f 10949
1e3ff5ad
AC
10950 /* Map pre-existing objects onto letters. DO NOT do this for new
10951 objects!!! Instead specify new query packets. */
10952 switch (object)
c906108c 10953 {
1e3ff5ad
AC
10954 case TARGET_OBJECT_AVR:
10955 query_type = 'R';
10956 break;
802188a7
RM
10957
10958 case TARGET_OBJECT_AUXV:
0876f84a 10959 gdb_assert (annex == NULL);
f6ac5f3d 10960 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
9b409511 10961 xfered_len,
0876f84a 10962 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10963
23181151
DJ
10964 case TARGET_OBJECT_AVAILABLE_FEATURES:
10965 return remote_read_qxfer
f6ac5f3d 10966 ("features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10967 &remote_protocol_packets[PACKET_qXfer_features]);
10968
cfa9d6d9
DJ
10969 case TARGET_OBJECT_LIBRARIES:
10970 return remote_read_qxfer
f6ac5f3d 10971 ("libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10972 &remote_protocol_packets[PACKET_qXfer_libraries]);
10973
2268b414
JK
10974 case TARGET_OBJECT_LIBRARIES_SVR4:
10975 return remote_read_qxfer
f6ac5f3d 10976 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10977 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10978
fd79ecee
DJ
10979 case TARGET_OBJECT_MEMORY_MAP:
10980 gdb_assert (annex == NULL);
f6ac5f3d 10981 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
9b409511 10982 xfered_len,
fd79ecee
DJ
10983 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10984
07e059b5
VP
10985 case TARGET_OBJECT_OSDATA:
10986 /* Should only get here if we're connected. */
5d93a237 10987 gdb_assert (rs->remote_desc);
07e059b5 10988 return remote_read_qxfer
f6ac5f3d 10989 ("osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10990 &remote_protocol_packets[PACKET_qXfer_osdata]);
10991
dc146f7c
VP
10992 case TARGET_OBJECT_THREADS:
10993 gdb_assert (annex == NULL);
f6ac5f3d 10994 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
9b409511 10995 xfered_len,
dc146f7c
VP
10996 &remote_protocol_packets[PACKET_qXfer_threads]);
10997
b3b9301e
PA
10998 case TARGET_OBJECT_TRACEFRAME_INFO:
10999 gdb_assert (annex == NULL);
11000 return remote_read_qxfer
f6ac5f3d 11001 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 11002 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
11003
11004 case TARGET_OBJECT_FDPIC:
f6ac5f3d 11005 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
9b409511 11006 xfered_len,
78d85199 11007 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
11008
11009 case TARGET_OBJECT_OPENVMS_UIB:
f6ac5f3d 11010 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
9b409511 11011 xfered_len,
169081d0
TG
11012 &remote_protocol_packets[PACKET_qXfer_uib]);
11013
9accd112 11014 case TARGET_OBJECT_BTRACE:
f6ac5f3d 11015 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
9b409511 11016 xfered_len,
9accd112
MM
11017 &remote_protocol_packets[PACKET_qXfer_btrace]);
11018
f4abbc16 11019 case TARGET_OBJECT_BTRACE_CONF:
f6ac5f3d 11020 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
f4abbc16
MM
11021 len, xfered_len,
11022 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11023
c78fa86a 11024 case TARGET_OBJECT_EXEC_FILE:
f6ac5f3d 11025 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
c78fa86a
GB
11026 len, xfered_len,
11027 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11028
1e3ff5ad 11029 default:
2ed4b548 11030 return TARGET_XFER_E_IO;
c906108c
SS
11031 }
11032
0df8b418 11033 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11034 large enough let the caller deal with it. */
ea9c271d 11035 if (len < get_remote_packet_size ())
2ed4b548 11036 return TARGET_XFER_E_IO;
ea9c271d 11037 len = get_remote_packet_size ();
1e3ff5ad 11038
23860348 11039 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11040 if (!rs->remote_desc)
8a3fe4f8 11041 error (_("remote query is only available after target open"));
c906108c 11042
1e3ff5ad 11043 gdb_assert (annex != NULL);
4b8a223f 11044 gdb_assert (readbuf != NULL);
c906108c 11045
6d820c5c 11046 p2 = rs->buf;
c906108c
SS
11047 *p2++ = 'q';
11048 *p2++ = query_type;
11049
23860348
MS
11050 /* We used one buffer char for the remote protocol q command and
11051 another for the query type. As the remote protocol encapsulation
11052 uses 4 chars plus one extra in case we are debugging
11053 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11054 string. */
c906108c 11055 i = 0;
ea9c271d 11056 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11057 {
1e3ff5ad
AC
11058 /* Bad caller may have sent forbidden characters. */
11059 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11060 *p2++ = annex[i];
c906108c
SS
11061 i++;
11062 }
1e3ff5ad
AC
11063 *p2 = '\0';
11064 gdb_assert (annex[i] == '\0');
c906108c 11065
6d820c5c 11066 i = putpkt (rs->buf);
c5aa993b 11067 if (i < 0)
2ed4b548 11068 return TARGET_XFER_E_IO;
c906108c 11069
6d820c5c
DJ
11070 getpkt (&rs->buf, &rs->buf_size, 0);
11071 strcpy ((char *) readbuf, rs->buf);
c906108c 11072
9b409511 11073 *xfered_len = strlen ((char *) readbuf);
92ffd475 11074 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11075}
11076
09c98b44
DB
11077/* Implementation of to_get_memory_xfer_limit. */
11078
f6ac5f3d
PA
11079ULONGEST
11080remote_target::get_memory_xfer_limit ()
09c98b44
DB
11081{
11082 return get_memory_write_packet_size ();
11083}
11084
f6ac5f3d
PA
11085int
11086remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11087 const gdb_byte *pattern, ULONGEST pattern_len,
11088 CORE_ADDR *found_addrp)
08388c79 11089{
f5656ead 11090 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
11091 struct remote_state *rs = get_remote_state ();
11092 int max_size = get_memory_write_packet_size ();
11093 struct packet_config *packet =
11094 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
11095 /* Number of packet bytes used to encode the pattern;
11096 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11097 int escaped_pattern_len;
0df8b418 11098 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11099 int used_pattern_len;
11100 int i;
11101 int found;
11102 ULONGEST found_addr;
11103
7cc244de
PA
11104 /* Don't go to the target if we don't have to. This is done before
11105 checking packet_config_support to avoid the possibility that a
11106 success for this edge case means the facility works in
11107 general. */
08388c79
DE
11108 if (pattern_len > search_space_len)
11109 return 0;
11110 if (pattern_len == 0)
11111 {
11112 *found_addrp = start_addr;
11113 return 1;
11114 }
11115
11116 /* If we already know the packet isn't supported, fall back to the simple
11117 way of searching memory. */
11118
4082afcc 11119 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
11120 {
11121 /* Target doesn't provided special support, fall back and use the
11122 standard support (copy memory and do the search here). */
f6ac5f3d 11123 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11124 pattern, pattern_len, found_addrp);
11125 }
11126
28439a30
PA
11127 /* Make sure the remote is pointing at the right process. */
11128 set_general_process ();
11129
08388c79
DE
11130 /* Insert header. */
11131 i = snprintf (rs->buf, max_size,
11132 "qSearch:memory:%s;%s;",
5af949e3 11133 phex_nz (start_addr, addr_size),
08388c79
DE
11134 phex_nz (search_space_len, sizeof (search_space_len)));
11135 max_size -= (i + 1);
11136
11137 /* Escape as much data as fits into rs->buf. */
11138 escaped_pattern_len =
124e13d9 11139 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
11140 &used_pattern_len, max_size);
11141
11142 /* Bail if the pattern is too large. */
11143 if (used_pattern_len != pattern_len)
9b20d036 11144 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
11145
11146 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11147 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11148 || packet_ok (rs->buf, packet) != PACKET_OK)
11149 {
11150 /* The request may not have worked because the command is not
11151 supported. If so, fall back to the simple way. */
7cc244de 11152 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79 11153 {
f6ac5f3d 11154 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11155 pattern, pattern_len, found_addrp);
11156 }
11157 return -1;
11158 }
11159
11160 if (rs->buf[0] == '0')
11161 found = 0;
11162 else if (rs->buf[0] == '1')
11163 {
11164 found = 1;
11165 if (rs->buf[1] != ',')
10e0fa18 11166 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
11167 unpack_varlen_hex (rs->buf + 2, &found_addr);
11168 *found_addrp = found_addr;
11169 }
11170 else
10e0fa18 11171 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
11172
11173 return found;
11174}
11175
f6ac5f3d
PA
11176void
11177remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11178{
d01949b6 11179 struct remote_state *rs = get_remote_state ();
2e9f7625 11180 char *p = rs->buf;
96baa820 11181
5d93a237 11182 if (!rs->remote_desc)
8a3fe4f8 11183 error (_("remote rcmd is only available after target open"));
96baa820 11184
23860348 11185 /* Send a NULL command across as an empty command. */
7be570e7
JM
11186 if (command == NULL)
11187 command = "";
11188
23860348 11189 /* The query prefix. */
2e9f7625
DJ
11190 strcpy (rs->buf, "qRcmd,");
11191 p = strchr (rs->buf, '\0');
96baa820 11192
3e43a32a
MS
11193 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11194 > get_remote_packet_size ())
8a3fe4f8 11195 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11196
23860348 11197 /* Encode the actual command. */
a30bf1f1 11198 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11199
6d820c5c 11200 if (putpkt (rs->buf) < 0)
8a3fe4f8 11201 error (_("Communication problem with target."));
96baa820
JM
11202
11203 /* get/display the response */
11204 while (1)
11205 {
2e9f7625
DJ
11206 char *buf;
11207
00bf0b85 11208 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11209 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11210 rs->buf[0] = '\0';
5b37825d
PW
11211 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11212 {
11213 /* Timeout. Continue to (try to) read responses.
11214 This is better than stopping with an error, assuming the stub
11215 is still executing the (long) monitor command.
11216 If needed, the user can interrupt gdb using C-c, obtaining
11217 an effect similar to stop on timeout. */
11218 continue;
11219 }
2e9f7625 11220 buf = rs->buf;
96baa820 11221 if (buf[0] == '\0')
8a3fe4f8 11222 error (_("Target does not support this command."));
96baa820
JM
11223 if (buf[0] == 'O' && buf[1] != 'K')
11224 {
23860348 11225 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11226 continue;
11227 }
11228 if (strcmp (buf, "OK") == 0)
11229 break;
7be570e7
JM
11230 if (strlen (buf) == 3 && buf[0] == 'E'
11231 && isdigit (buf[1]) && isdigit (buf[2]))
11232 {
8a3fe4f8 11233 error (_("Protocol error with Rcmd"));
7be570e7 11234 }
96baa820
JM
11235 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11236 {
11237 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11238
96baa820
JM
11239 fputc_unfiltered (c, outbuf);
11240 }
11241 break;
11242 }
11243}
11244
f6ac5f3d
PA
11245std::vector<mem_region>
11246remote_target::memory_map ()
fd79ecee 11247{
a664f67e 11248 std::vector<mem_region> result;
9018be22 11249 gdb::optional<gdb::char_vector> text
8b88a78e 11250 = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11251
11252 if (text)
9018be22 11253 result = parse_memory_map (text->data ());
fd79ecee
DJ
11254
11255 return result;
11256}
11257
c906108c 11258static void
ac88e2de 11259packet_command (const char *args, int from_tty)
c906108c 11260{
6b8edb51 11261 remote_target *remote = get_current_remote_target ();
c906108c 11262
6b8edb51 11263 if (remote == nullptr)
8a3fe4f8 11264 error (_("command can only be used with remote target"));
c906108c 11265
6b8edb51
PA
11266 remote->packet_command (args, from_tty);
11267}
11268
11269void
11270remote_target::packet_command (const char *args, int from_tty)
11271{
c5aa993b 11272 if (!args)
8a3fe4f8 11273 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
11274
11275 puts_filtered ("sending: ");
11276 print_packet (args);
11277 puts_filtered ("\n");
11278 putpkt (args);
11279
6b8edb51
PA
11280 remote_state *rs = get_remote_state ();
11281
6d820c5c 11282 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 11283 puts_filtered ("received: ");
6d820c5c 11284 print_packet (rs->buf);
c906108c
SS
11285 puts_filtered ("\n");
11286}
11287
11288#if 0
23860348 11289/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11290
a14ed312 11291static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11292
a14ed312 11293static void threadset_test_cmd (char *cmd, int tty);
c906108c 11294
a14ed312 11295static void threadalive_test (char *cmd, int tty);
c906108c 11296
a14ed312 11297static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11298
23860348 11299int get_and_display_threadinfo (threadref *ref);
c906108c 11300
a14ed312 11301static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11302
23860348 11303static int thread_display_step (threadref *ref, void *context);
c906108c 11304
a14ed312 11305static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11306
a14ed312 11307static void init_remote_threadtests (void);
c906108c 11308
23860348 11309#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11310
11311static void
0b39b52e 11312threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11313{
11314 int sample_thread = SAMPLE_THREAD;
11315
a3f17187 11316 printf_filtered (_("Remote threadset test\n"));
79d7f229 11317 set_general_thread (sample_thread);
c906108c
SS
11318}
11319
11320
11321static void
0b39b52e 11322threadalive_test (const char *cmd, int tty)
c906108c
SS
11323{
11324 int sample_thread = SAMPLE_THREAD;
79d7f229 11325 int pid = ptid_get_pid (inferior_ptid);
ba348170 11326 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 11327
79d7f229 11328 if (remote_thread_alive (ptid))
c906108c
SS
11329 printf_filtered ("PASS: Thread alive test\n");
11330 else
11331 printf_filtered ("FAIL: Thread alive test\n");
11332}
11333
23860348 11334void output_threadid (char *title, threadref *ref);
c906108c
SS
11335
11336void
fba45db2 11337output_threadid (char *title, threadref *ref)
c906108c
SS
11338{
11339 char hexid[20];
11340
23860348 11341 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
11342 hexid[16] = 0;
11343 printf_filtered ("%s %s\n", title, (&hexid[0]));
11344}
11345
11346static void
0b39b52e 11347threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11348{
11349 int startflag = 1;
11350 threadref nextthread;
11351 int done, result_count;
11352 threadref threadlist[3];
11353
11354 printf_filtered ("Remote Threadlist test\n");
11355 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11356 &result_count, &threadlist[0]))
11357 printf_filtered ("FAIL: threadlist test\n");
11358 else
11359 {
11360 threadref *scan = threadlist;
11361 threadref *limit = scan + result_count;
11362
11363 while (scan < limit)
11364 output_threadid (" thread ", scan++);
11365 }
11366}
11367
11368void
fba45db2 11369display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11370{
11371 output_threadid ("Threadid: ", &info->threadid);
11372 printf_filtered ("Name: %s\n ", info->shortname);
11373 printf_filtered ("State: %s\n", info->display);
11374 printf_filtered ("other: %s\n\n", info->more_display);
11375}
11376
11377int
fba45db2 11378get_and_display_threadinfo (threadref *ref)
c906108c
SS
11379{
11380 int result;
11381 int set;
11382 struct gdb_ext_thread_info threadinfo;
11383
11384 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11385 | TAG_MOREDISPLAY | TAG_DISPLAY;
11386 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11387 display_thread_info (&threadinfo);
11388 return result;
11389}
11390
11391static void
0b39b52e 11392threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11393{
11394 int athread = SAMPLE_THREAD;
11395 threadref thread;
11396 int set;
11397
11398 int_to_threadref (&thread, athread);
11399 printf_filtered ("Remote Threadinfo test\n");
11400 if (!get_and_display_threadinfo (&thread))
11401 printf_filtered ("FAIL cannot get thread info\n");
11402}
11403
11404static int
fba45db2 11405thread_display_step (threadref *ref, void *context)
c906108c
SS
11406{
11407 /* output_threadid(" threadstep ",ref); *//* simple test */
11408 return get_and_display_threadinfo (ref);
11409}
11410
11411static void
0b39b52e 11412threadlist_update_test_cmd (const char *cmd, int tty)
c906108c
SS
11413{
11414 printf_filtered ("Remote Threadlist update test\n");
11415 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11416}
11417
11418static void
11419init_remote_threadtests (void)
11420{
3e43a32a
MS
11421 add_com ("tlist", class_obscure, threadlist_test_cmd,
11422 _("Fetch and print the remote list of "
11423 "thread identifiers, one pkt only"));
c906108c 11424 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 11425 _("Fetch and display info about one thread"));
c906108c 11426 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 11427 _("Test setting to a different thread"));
c906108c 11428 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 11429 _("Iterate through updating all remote thread info"));
c906108c 11430 add_com ("talive", class_obscure, threadalive_test,
1bedd215 11431 _(" Remote thread alive test "));
c906108c
SS
11432}
11433
11434#endif /* 0 */
11435
f3fb8c85
MS
11436/* Convert a thread ID to a string. Returns the string in a static
11437 buffer. */
11438
f6ac5f3d
PA
11439const char *
11440remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11441{
79d7f229 11442 static char buf[64];
82f73884 11443 struct remote_state *rs = get_remote_state ();
f3fb8c85 11444
7cee1e54
PA
11445 if (ptid_equal (ptid, null_ptid))
11446 return normal_pid_to_str (ptid);
11447 else if (ptid_is_pid (ptid))
ecd0ada5
PA
11448 {
11449 /* Printing an inferior target id. */
11450
11451 /* When multi-process extensions are off, there's no way in the
11452 remote protocol to know the remote process id, if there's any
11453 at all. There's one exception --- when we're connected with
11454 target extended-remote, and we manually attached to a process
11455 with "attach PID". We don't record anywhere a flag that
11456 allows us to distinguish that case from the case of
11457 connecting with extended-remote and the stub already being
11458 attached to a process, and reporting yes to qAttached, hence
11459 no smart special casing here. */
11460 if (!remote_multi_process_p (rs))
11461 {
11462 xsnprintf (buf, sizeof buf, "Remote target");
11463 return buf;
11464 }
11465
11466 return normal_pid_to_str (ptid);
82f73884 11467 }
ecd0ada5 11468 else
79d7f229 11469 {
ecd0ada5
PA
11470 if (ptid_equal (magic_null_ptid, ptid))
11471 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 11472 else if (remote_multi_process_p (rs))
de0d863e
DB
11473 if (ptid_get_lwp (ptid) == 0)
11474 return normal_pid_to_str (ptid);
11475 else
11476 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11477 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
11478 else
11479 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 11480 ptid_get_lwp (ptid));
79d7f229
PA
11481 return buf;
11482 }
f3fb8c85
MS
11483}
11484
38691318
KB
11485/* Get the address of the thread local variable in OBJFILE which is
11486 stored at OFFSET within the thread local storage for thread PTID. */
11487
f6ac5f3d
PA
11488CORE_ADDR
11489remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11490 CORE_ADDR offset)
38691318 11491{
4082afcc 11492 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11493 {
11494 struct remote_state *rs = get_remote_state ();
6d820c5c 11495 char *p = rs->buf;
82f73884 11496 char *endp = rs->buf + get_remote_packet_size ();
571dd617 11497 enum packet_result result;
38691318
KB
11498
11499 strcpy (p, "qGetTLSAddr:");
11500 p += strlen (p);
82f73884 11501 p = write_ptid (p, endp, ptid);
38691318
KB
11502 *p++ = ',';
11503 p += hexnumstr (p, offset);
11504 *p++ = ',';
11505 p += hexnumstr (p, lm);
11506 *p++ = '\0';
11507
6d820c5c
DJ
11508 putpkt (rs->buf);
11509 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
11510 result = packet_ok (rs->buf,
11511 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11512 if (result == PACKET_OK)
38691318
KB
11513 {
11514 ULONGEST result;
11515
6d820c5c 11516 unpack_varlen_hex (rs->buf, &result);
38691318
KB
11517 return result;
11518 }
571dd617 11519 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11520 throw_error (TLS_GENERIC_ERROR,
11521 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11522 else
109c3e39
AC
11523 throw_error (TLS_GENERIC_ERROR,
11524 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11525 }
11526 else
109c3e39
AC
11527 throw_error (TLS_GENERIC_ERROR,
11528 _("TLS not supported or disabled on this target"));
38691318
KB
11529 /* Not reached. */
11530 return 0;
11531}
11532
711e434b
PM
11533/* Provide thread local base, i.e. Thread Information Block address.
11534 Returns 1 if ptid is found and thread_local_base is non zero. */
11535
57810aa7 11536bool
f6ac5f3d 11537remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 11538{
4082afcc 11539 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11540 {
11541 struct remote_state *rs = get_remote_state ();
11542 char *p = rs->buf;
11543 char *endp = rs->buf + get_remote_packet_size ();
11544 enum packet_result result;
11545
11546 strcpy (p, "qGetTIBAddr:");
11547 p += strlen (p);
11548 p = write_ptid (p, endp, ptid);
11549 *p++ = '\0';
11550
11551 putpkt (rs->buf);
11552 getpkt (&rs->buf, &rs->buf_size, 0);
11553 result = packet_ok (rs->buf,
11554 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11555 if (result == PACKET_OK)
11556 {
11557 ULONGEST result;
11558
11559 unpack_varlen_hex (rs->buf, &result);
11560 if (addr)
11561 *addr = (CORE_ADDR) result;
57810aa7 11562 return true;
711e434b
PM
11563 }
11564 else if (result == PACKET_UNKNOWN)
11565 error (_("Remote target doesn't support qGetTIBAddr packet"));
11566 else
11567 error (_("Remote target failed to process qGetTIBAddr request"));
11568 }
11569 else
11570 error (_("qGetTIBAddr not supported or disabled on this target"));
11571 /* Not reached. */
57810aa7 11572 return false;
711e434b
PM
11573}
11574
29709017
DJ
11575/* Support for inferring a target description based on the current
11576 architecture and the size of a 'g' packet. While the 'g' packet
11577 can have any size (since optional registers can be left off the
11578 end), some sizes are easily recognizable given knowledge of the
11579 approximate architecture. */
11580
11581struct remote_g_packet_guess
11582{
11583 int bytes;
11584 const struct target_desc *tdesc;
11585};
11586typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11587DEF_VEC_O(remote_g_packet_guess_s);
11588
11589struct remote_g_packet_data
11590{
11591 VEC(remote_g_packet_guess_s) *guesses;
11592};
11593
11594static struct gdbarch_data *remote_g_packet_data_handle;
11595
11596static void *
11597remote_g_packet_data_init (struct obstack *obstack)
11598{
11599 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11600}
11601
11602void
11603register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11604 const struct target_desc *tdesc)
11605{
11606 struct remote_g_packet_data *data
19ba03f4
SM
11607 = ((struct remote_g_packet_data *)
11608 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11609 struct remote_g_packet_guess new_guess, *guess;
11610 int ix;
11611
11612 gdb_assert (tdesc != NULL);
11613
11614 for (ix = 0;
11615 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11616 ix++)
11617 if (guess->bytes == bytes)
11618 internal_error (__FILE__, __LINE__,
9b20d036 11619 _("Duplicate g packet description added for size %d"),
29709017
DJ
11620 bytes);
11621
11622 new_guess.bytes = bytes;
11623 new_guess.tdesc = tdesc;
11624 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11625}
11626
d962ef82
DJ
11627/* Return 1 if remote_read_description would do anything on this target
11628 and architecture, 0 otherwise. */
11629
11630static int
11631remote_read_description_p (struct target_ops *target)
11632{
11633 struct remote_g_packet_data *data
19ba03f4
SM
11634 = ((struct remote_g_packet_data *)
11635 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
11636
11637 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11638 return 1;
11639
11640 return 0;
11641}
11642
f6ac5f3d
PA
11643const struct target_desc *
11644remote_target::read_description ()
29709017
DJ
11645{
11646 struct remote_g_packet_data *data
19ba03f4
SM
11647 = ((struct remote_g_packet_data *)
11648 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11649
d962ef82
DJ
11650 /* Do not try this during initial connection, when we do not know
11651 whether there is a running but stopped thread. */
11652 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
b6a8c27b 11653 return beneath ()->read_description ();
d962ef82 11654
29709017
DJ
11655 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11656 {
11657 struct remote_g_packet_guess *guess;
11658 int ix;
11659 int bytes = send_g_packet ();
11660
11661 for (ix = 0;
11662 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11663 ix++)
11664 if (guess->bytes == bytes)
11665 return guess->tdesc;
11666
11667 /* We discard the g packet. A minor optimization would be to
11668 hold on to it, and fill the register cache once we have selected
11669 an architecture, but it's too tricky to do safely. */
11670 }
11671
b6a8c27b 11672 return beneath ()->read_description ();
29709017
DJ
11673}
11674
a6b151f1
DJ
11675/* Remote file transfer support. This is host-initiated I/O, not
11676 target-initiated; for target-initiated, see remote-fileio.c. */
11677
11678/* If *LEFT is at least the length of STRING, copy STRING to
11679 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11680 decrease *LEFT. Otherwise raise an error. */
11681
11682static void
a121b7c1 11683remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11684{
11685 int len = strlen (string);
11686
11687 if (len > *left)
11688 error (_("Packet too long for target."));
11689
11690 memcpy (*buffer, string, len);
11691 *buffer += len;
11692 *left -= len;
11693
11694 /* NUL-terminate the buffer as a convenience, if there is
11695 room. */
11696 if (*left)
11697 **buffer = '\0';
11698}
11699
11700/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11701 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11702 decrease *LEFT. Otherwise raise an error. */
11703
11704static void
11705remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11706 int len)
11707{
11708 if (2 * len > *left)
11709 error (_("Packet too long for target."));
11710
11711 bin2hex (bytes, *buffer, len);
11712 *buffer += 2 * len;
11713 *left -= 2 * len;
11714
11715 /* NUL-terminate the buffer as a convenience, if there is
11716 room. */
11717 if (*left)
11718 **buffer = '\0';
11719}
11720
11721/* If *LEFT is large enough, convert VALUE to hex and add it to
11722 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11723 decrease *LEFT. Otherwise raise an error. */
11724
11725static void
11726remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11727{
11728 int len = hexnumlen (value);
11729
11730 if (len > *left)
11731 error (_("Packet too long for target."));
11732
11733 hexnumstr (*buffer, value);
11734 *buffer += len;
11735 *left -= len;
11736
11737 /* NUL-terminate the buffer as a convenience, if there is
11738 room. */
11739 if (*left)
11740 **buffer = '\0';
11741}
11742
11743/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11744 value, *REMOTE_ERRNO to the remote error number or zero if none
11745 was included, and *ATTACHMENT to point to the start of the annex
11746 if any. The length of the packet isn't needed here; there may
11747 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11748
11749 Return 0 if the packet could be parsed, -1 if it could not. If
11750 -1 is returned, the other variables may not be initialized. */
11751
11752static int
11753remote_hostio_parse_result (char *buffer, int *retcode,
11754 int *remote_errno, char **attachment)
11755{
11756 char *p, *p2;
11757
11758 *remote_errno = 0;
11759 *attachment = NULL;
11760
11761 if (buffer[0] != 'F')
11762 return -1;
11763
11764 errno = 0;
11765 *retcode = strtol (&buffer[1], &p, 16);
11766 if (errno != 0 || p == &buffer[1])
11767 return -1;
11768
11769 /* Check for ",errno". */
11770 if (*p == ',')
11771 {
11772 errno = 0;
11773 *remote_errno = strtol (p + 1, &p2, 16);
11774 if (errno != 0 || p + 1 == p2)
11775 return -1;
11776 p = p2;
11777 }
11778
11779 /* Check for ";attachment". If there is no attachment, the
11780 packet should end here. */
11781 if (*p == ';')
11782 {
11783 *attachment = p + 1;
11784 return 0;
11785 }
11786 else if (*p == '\0')
11787 return 0;
11788 else
11789 return -1;
11790}
11791
11792/* Send a prepared I/O packet to the target and read its response.
11793 The prepared packet is in the global RS->BUF before this function
11794 is called, and the answer is there when we return.
11795
11796 COMMAND_BYTES is the length of the request to send, which may include
11797 binary data. WHICH_PACKET is the packet configuration to check
11798 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11799 is set to the error number and -1 is returned. Otherwise the value
11800 returned by the function is returned.
11801
11802 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11803 attachment is expected; an error will be reported if there's a
11804 mismatch. If one is found, *ATTACHMENT will be set to point into
11805 the packet buffer and *ATTACHMENT_LEN will be set to the
11806 attachment's length. */
11807
6b8edb51
PA
11808int
11809remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11810 int *remote_errno, char **attachment,
11811 int *attachment_len)
a6b151f1
DJ
11812{
11813 struct remote_state *rs = get_remote_state ();
11814 int ret, bytes_read;
11815 char *attachment_tmp;
11816
20db9c52 11817 if (packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11818 {
11819 *remote_errno = FILEIO_ENOSYS;
11820 return -1;
11821 }
11822
11823 putpkt_binary (rs->buf, command_bytes);
11824 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11825
11826 /* If it timed out, something is wrong. Don't try to parse the
11827 buffer. */
11828 if (bytes_read < 0)
11829 {
11830 *remote_errno = FILEIO_EINVAL;
11831 return -1;
11832 }
11833
11834 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11835 {
11836 case PACKET_ERROR:
11837 *remote_errno = FILEIO_EINVAL;
11838 return -1;
11839 case PACKET_UNKNOWN:
11840 *remote_errno = FILEIO_ENOSYS;
11841 return -1;
11842 case PACKET_OK:
11843 break;
11844 }
11845
11846 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11847 &attachment_tmp))
11848 {
11849 *remote_errno = FILEIO_EINVAL;
11850 return -1;
11851 }
11852
11853 /* Make sure we saw an attachment if and only if we expected one. */
11854 if ((attachment_tmp == NULL && attachment != NULL)
11855 || (attachment_tmp != NULL && attachment == NULL))
11856 {
11857 *remote_errno = FILEIO_EINVAL;
11858 return -1;
11859 }
11860
11861 /* If an attachment was found, it must point into the packet buffer;
11862 work out how many bytes there were. */
11863 if (attachment_tmp != NULL)
11864 {
11865 *attachment = attachment_tmp;
11866 *attachment_len = bytes_read - (*attachment - rs->buf);
11867 }
11868
11869 return ret;
11870}
11871
dd194f6b 11872/* See declaration.h. */
80152258 11873
dd194f6b
PA
11874void
11875readahead_cache::invalidate ()
80152258 11876{
dd194f6b 11877 this->fd = -1;
80152258
PA
11878}
11879
dd194f6b 11880/* See declaration.h. */
80152258 11881
dd194f6b
PA
11882void
11883readahead_cache::invalidate_fd (int fd)
80152258 11884{
dd194f6b
PA
11885 if (this->fd == fd)
11886 this->fd = -1;
80152258
PA
11887}
11888
15a201c8
GB
11889/* Set the filesystem remote_hostio functions that take FILENAME
11890 arguments will use. Return 0 on success, or -1 if an error
11891 occurs (and set *REMOTE_ERRNO). */
11892
6b8edb51
PA
11893int
11894remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11895 int *remote_errno)
15a201c8
GB
11896{
11897 struct remote_state *rs = get_remote_state ();
11898 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11899 char *p = rs->buf;
11900 int left = get_remote_packet_size () - 1;
11901 char arg[9];
11902 int ret;
11903
11904 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11905 return 0;
11906
11907 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11908 return 0;
11909
11910 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11911
11912 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11913 remote_buffer_add_string (&p, &left, arg);
11914
11915 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11916 remote_errno, NULL, NULL);
11917
11918 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11919 return 0;
11920
11921 if (ret == 0)
11922 rs->fs_pid = required_pid;
11923
11924 return ret;
11925}
11926
12e2a5fd 11927/* Implementation of to_fileio_open. */
a6b151f1 11928
6b8edb51
PA
11929int
11930remote_target::remote_hostio_open (inferior *inf, const char *filename,
11931 int flags, int mode, int warn_if_slow,
11932 int *remote_errno)
a6b151f1
DJ
11933{
11934 struct remote_state *rs = get_remote_state ();
11935 char *p = rs->buf;
11936 int left = get_remote_packet_size () - 1;
11937
4313b8c0
GB
11938 if (warn_if_slow)
11939 {
11940 static int warning_issued = 0;
11941
11942 printf_unfiltered (_("Reading %s from remote target...\n"),
11943 filename);
11944
11945 if (!warning_issued)
11946 {
11947 warning (_("File transfers from remote targets can be slow."
11948 " Use \"set sysroot\" to access files locally"
11949 " instead."));
11950 warning_issued = 1;
11951 }
11952 }
11953
15a201c8
GB
11954 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11955 return -1;
11956
a6b151f1
DJ
11957 remote_buffer_add_string (&p, &left, "vFile:open:");
11958
11959 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11960 strlen (filename));
11961 remote_buffer_add_string (&p, &left, ",");
11962
11963 remote_buffer_add_int (&p, &left, flags);
11964 remote_buffer_add_string (&p, &left, ",");
11965
11966 remote_buffer_add_int (&p, &left, mode);
11967
11968 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11969 remote_errno, NULL, NULL);
11970}
11971
f6ac5f3d
PA
11972int
11973remote_target::fileio_open (struct inferior *inf, const char *filename,
11974 int flags, int mode, int warn_if_slow,
11975 int *remote_errno)
11976{
6b8edb51 11977 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
11978 remote_errno);
11979}
11980
12e2a5fd 11981/* Implementation of to_fileio_pwrite. */
a6b151f1 11982
6b8edb51
PA
11983int
11984remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
11985 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11986{
11987 struct remote_state *rs = get_remote_state ();
11988 char *p = rs->buf;
11989 int left = get_remote_packet_size ();
11990 int out_len;
11991
dd194f6b 11992 rs->readahead_cache.invalidate_fd (fd);
80152258 11993
a6b151f1
DJ
11994 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11995
11996 remote_buffer_add_int (&p, &left, fd);
11997 remote_buffer_add_string (&p, &left, ",");
11998
11999 remote_buffer_add_int (&p, &left, offset);
12000 remote_buffer_add_string (&p, &left, ",");
12001
124e13d9 12002 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
12003 get_remote_packet_size () - (p - rs->buf));
12004
12005 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12006 remote_errno, NULL, NULL);
12007}
12008
f6ac5f3d
PA
12009int
12010remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12011 ULONGEST offset, int *remote_errno)
12012{
6b8edb51 12013 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12014}
12015
80152258
PA
12016/* Helper for the implementation of to_fileio_pread. Read the file
12017 from the remote side with vFile:pread. */
a6b151f1 12018
6b8edb51
PA
12019int
12020remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12021 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12022{
12023 struct remote_state *rs = get_remote_state ();
12024 char *p = rs->buf;
12025 char *attachment;
12026 int left = get_remote_packet_size ();
12027 int ret, attachment_len;
12028 int read_len;
12029
12030 remote_buffer_add_string (&p, &left, "vFile:pread:");
12031
12032 remote_buffer_add_int (&p, &left, fd);
12033 remote_buffer_add_string (&p, &left, ",");
12034
12035 remote_buffer_add_int (&p, &left, len);
12036 remote_buffer_add_string (&p, &left, ",");
12037
12038 remote_buffer_add_int (&p, &left, offset);
12039
12040 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12041 remote_errno, &attachment,
12042 &attachment_len);
12043
12044 if (ret < 0)
12045 return ret;
12046
bc20a4af 12047 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12048 read_buf, len);
12049 if (read_len != ret)
12050 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12051
12052 return ret;
12053}
12054
dd194f6b 12055/* See declaration.h. */
80152258 12056
dd194f6b
PA
12057int
12058readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12059 ULONGEST offset)
80152258 12060{
dd194f6b
PA
12061 if (this->fd == fd
12062 && this->offset <= offset
12063 && offset < this->offset + this->bufsize)
80152258 12064 {
dd194f6b 12065 ULONGEST max = this->offset + this->bufsize;
80152258
PA
12066
12067 if (offset + len > max)
12068 len = max - offset;
12069
dd194f6b 12070 memcpy (read_buf, this->buf + offset - this->offset, len);
80152258
PA
12071 return len;
12072 }
12073
12074 return 0;
12075}
12076
12077/* Implementation of to_fileio_pread. */
12078
6b8edb51
PA
12079int
12080remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12081 ULONGEST offset, int *remote_errno)
80152258
PA
12082{
12083 int ret;
12084 struct remote_state *rs = get_remote_state ();
dd194f6b 12085 readahead_cache *cache = &rs->readahead_cache;
80152258 12086
dd194f6b 12087 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12088 if (ret > 0)
12089 {
12090 cache->hit_count++;
12091
12092 if (remote_debug)
12093 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12094 pulongest (cache->hit_count));
12095 return ret;
12096 }
12097
12098 cache->miss_count++;
12099 if (remote_debug)
12100 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12101 pulongest (cache->miss_count));
12102
12103 cache->fd = fd;
12104 cache->offset = offset;
12105 cache->bufsize = get_remote_packet_size ();
224c3ddb 12106 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258 12107
6b8edb51 12108 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
80152258
PA
12109 cache->offset, remote_errno);
12110 if (ret <= 0)
12111 {
dd194f6b 12112 cache->invalidate_fd (fd);
80152258
PA
12113 return ret;
12114 }
12115
12116 cache->bufsize = ret;
dd194f6b 12117 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12118}
12119
f6ac5f3d
PA
12120int
12121remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12122 ULONGEST offset, int *remote_errno)
12123{
6b8edb51 12124 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12125}
12126
12e2a5fd 12127/* Implementation of to_fileio_close. */
a6b151f1 12128
6b8edb51
PA
12129int
12130remote_target::remote_hostio_close (int fd, int *remote_errno)
a6b151f1
DJ
12131{
12132 struct remote_state *rs = get_remote_state ();
12133 char *p = rs->buf;
12134 int left = get_remote_packet_size () - 1;
12135
dd194f6b 12136 rs->readahead_cache.invalidate_fd (fd);
80152258 12137
a6b151f1
DJ
12138 remote_buffer_add_string (&p, &left, "vFile:close:");
12139
12140 remote_buffer_add_int (&p, &left, fd);
12141
12142 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12143 remote_errno, NULL, NULL);
12144}
12145
f6ac5f3d
PA
12146int
12147remote_target::fileio_close (int fd, int *remote_errno)
12148{
6b8edb51 12149 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12150}
12151
12e2a5fd 12152/* Implementation of to_fileio_unlink. */
a6b151f1 12153
6b8edb51
PA
12154int
12155remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12156 int *remote_errno)
a6b151f1
DJ
12157{
12158 struct remote_state *rs = get_remote_state ();
12159 char *p = rs->buf;
12160 int left = get_remote_packet_size () - 1;
12161
15a201c8
GB
12162 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12163 return -1;
12164
a6b151f1
DJ
12165 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12166
12167 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12168 strlen (filename));
12169
12170 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12171 remote_errno, NULL, NULL);
12172}
12173
f6ac5f3d
PA
12174int
12175remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12176 int *remote_errno)
12177{
6b8edb51 12178 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12179}
12180
12e2a5fd 12181/* Implementation of to_fileio_readlink. */
b9e7b9c3 12182
f6ac5f3d
PA
12183gdb::optional<std::string>
12184remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12185 int *remote_errno)
b9e7b9c3
UW
12186{
12187 struct remote_state *rs = get_remote_state ();
12188 char *p = rs->buf;
12189 char *attachment;
12190 int left = get_remote_packet_size ();
12191 int len, attachment_len;
12192 int read_len;
b9e7b9c3 12193
15a201c8 12194 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12195 return {};
15a201c8 12196
b9e7b9c3
UW
12197 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12198
12199 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12200 strlen (filename));
12201
12202 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12203 remote_errno, &attachment,
12204 &attachment_len);
12205
12206 if (len < 0)
e0d3522b 12207 return {};
b9e7b9c3 12208
e0d3522b 12209 std::string ret (len, '\0');
b9e7b9c3 12210
bc20a4af 12211 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12212 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12213 if (read_len != len)
12214 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12215
b9e7b9c3
UW
12216 return ret;
12217}
12218
12e2a5fd 12219/* Implementation of to_fileio_fstat. */
0a93529c 12220
f6ac5f3d
PA
12221int
12222remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
0a93529c
GB
12223{
12224 struct remote_state *rs = get_remote_state ();
12225 char *p = rs->buf;
12226 int left = get_remote_packet_size ();
12227 int attachment_len, ret;
12228 char *attachment;
12229 struct fio_stat fst;
12230 int read_len;
12231
464b0089
GB
12232 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12233
12234 remote_buffer_add_int (&p, &left, fd);
12235
12236 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12237 remote_errno, &attachment,
12238 &attachment_len);
12239 if (ret < 0)
0a93529c 12240 {
464b0089
GB
12241 if (*remote_errno != FILEIO_ENOSYS)
12242 return ret;
12243
0a93529c
GB
12244 /* Strictly we should return -1, ENOSYS here, but when
12245 "set sysroot remote:" was implemented in August 2008
12246 BFD's need for a stat function was sidestepped with
12247 this hack. This was not remedied until March 2015
12248 so we retain the previous behavior to avoid breaking
12249 compatibility.
12250
12251 Note that the memset is a March 2015 addition; older
12252 GDBs set st_size *and nothing else* so the structure
12253 would have garbage in all other fields. This might
12254 break something but retaining the previous behavior
12255 here would be just too wrong. */
12256
12257 memset (st, 0, sizeof (struct stat));
12258 st->st_size = INT_MAX;
12259 return 0;
12260 }
12261
0a93529c
GB
12262 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12263 (gdb_byte *) &fst, sizeof (fst));
12264
12265 if (read_len != ret)
12266 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12267
12268 if (read_len != sizeof (fst))
12269 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12270 read_len, (int) sizeof (fst));
12271
12272 remote_fileio_to_host_stat (&fst, st);
12273
12274 return 0;
12275}
12276
12e2a5fd 12277/* Implementation of to_filesystem_is_local. */
e3dd7556 12278
57810aa7 12279bool
f6ac5f3d 12280remote_target::filesystem_is_local ()
e3dd7556
GB
12281{
12282 /* Valgrind GDB presents itself as a remote target but works
12283 on the local filesystem: it does not implement remote get
12284 and users are not expected to set a sysroot. To handle
12285 this case we treat the remote filesystem as local if the
12286 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12287 does not support vFile:open. */
a3be80c3 12288 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
12289 {
12290 enum packet_support ps = packet_support (PACKET_vFile_open);
12291
12292 if (ps == PACKET_SUPPORT_UNKNOWN)
12293 {
12294 int fd, remote_errno;
12295
12296 /* Try opening a file to probe support. The supplied
12297 filename is irrelevant, we only care about whether
12298 the stub recognizes the packet or not. */
6b8edb51 12299 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12300 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12301 &remote_errno);
12302
12303 if (fd >= 0)
6b8edb51 12304 remote_hostio_close (fd, &remote_errno);
e3dd7556
GB
12305
12306 ps = packet_support (PACKET_vFile_open);
12307 }
12308
12309 if (ps == PACKET_DISABLE)
12310 {
12311 static int warning_issued = 0;
12312
12313 if (!warning_issued)
12314 {
12315 warning (_("remote target does not support file"
12316 " transfer, attempting to access files"
12317 " from local filesystem."));
12318 warning_issued = 1;
12319 }
12320
57810aa7 12321 return true;
e3dd7556
GB
12322 }
12323 }
12324
57810aa7 12325 return false;
e3dd7556
GB
12326}
12327
a6b151f1
DJ
12328static int
12329remote_fileio_errno_to_host (int errnum)
12330{
12331 switch (errnum)
12332 {
12333 case FILEIO_EPERM:
12334 return EPERM;
12335 case FILEIO_ENOENT:
12336 return ENOENT;
12337 case FILEIO_EINTR:
12338 return EINTR;
12339 case FILEIO_EIO:
12340 return EIO;
12341 case FILEIO_EBADF:
12342 return EBADF;
12343 case FILEIO_EACCES:
12344 return EACCES;
12345 case FILEIO_EFAULT:
12346 return EFAULT;
12347 case FILEIO_EBUSY:
12348 return EBUSY;
12349 case FILEIO_EEXIST:
12350 return EEXIST;
12351 case FILEIO_ENODEV:
12352 return ENODEV;
12353 case FILEIO_ENOTDIR:
12354 return ENOTDIR;
12355 case FILEIO_EISDIR:
12356 return EISDIR;
12357 case FILEIO_EINVAL:
12358 return EINVAL;
12359 case FILEIO_ENFILE:
12360 return ENFILE;
12361 case FILEIO_EMFILE:
12362 return EMFILE;
12363 case FILEIO_EFBIG:
12364 return EFBIG;
12365 case FILEIO_ENOSPC:
12366 return ENOSPC;
12367 case FILEIO_ESPIPE:
12368 return ESPIPE;
12369 case FILEIO_EROFS:
12370 return EROFS;
12371 case FILEIO_ENOSYS:
12372 return ENOSYS;
12373 case FILEIO_ENAMETOOLONG:
12374 return ENAMETOOLONG;
12375 }
12376 return -1;
12377}
12378
12379static char *
12380remote_hostio_error (int errnum)
12381{
12382 int host_error = remote_fileio_errno_to_host (errnum);
12383
12384 if (host_error == -1)
12385 error (_("Unknown remote I/O error %d"), errnum);
12386 else
12387 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12388}
12389
440b7aec
PA
12390/* A RAII wrapper around a remote file descriptor. */
12391
12392class scoped_remote_fd
a6b151f1 12393{
440b7aec 12394public:
6b8edb51
PA
12395 scoped_remote_fd (remote_target *remote, int fd)
12396 : m_remote (remote), m_fd (fd)
440b7aec
PA
12397 {
12398 }
a6b151f1 12399
440b7aec
PA
12400 ~scoped_remote_fd ()
12401 {
12402 if (m_fd != -1)
12403 {
12404 try
12405 {
12406 int remote_errno;
6b8edb51 12407 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12408 }
12409 catch (...)
12410 {
12411 /* Swallow exception before it escapes the dtor. If
12412 something goes wrong, likely the connection is gone,
12413 and there's nothing else that can be done. */
12414 }
12415 }
12416 }
12417
12418 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12419
12420 /* Release ownership of the file descriptor, and return it. */
12421 int release () noexcept
12422 {
12423 int fd = m_fd;
12424 m_fd = -1;
12425 return fd;
12426 }
12427
12428 /* Return the owned file descriptor. */
12429 int get () const noexcept
12430 {
12431 return m_fd;
12432 }
12433
12434private:
6b8edb51
PA
12435 /* The remote target. */
12436 remote_target *m_remote;
12437
440b7aec
PA
12438 /* The owned remote I/O file descriptor. */
12439 int m_fd;
12440};
a6b151f1
DJ
12441
12442void
12443remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12444{
12445 remote_target *remote = get_current_remote_target ();
12446
12447 if (remote == nullptr)
12448 error (_("command can only be used with remote target"));
12449
12450 remote->remote_file_put (local_file, remote_file, from_tty);
12451}
12452
12453void
12454remote_target::remote_file_put (const char *local_file, const char *remote_file,
12455 int from_tty)
a6b151f1 12456{
440b7aec 12457 int retcode, remote_errno, bytes, io_size;
a6b151f1
DJ
12458 int bytes_in_buffer;
12459 int saw_eof;
12460 ULONGEST offset;
a6b151f1 12461
d419f42d 12462 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12463 if (file == NULL)
12464 perror_with_name (local_file);
a6b151f1 12465
440b7aec 12466 scoped_remote_fd fd
6b8edb51
PA
12467 (this, remote_hostio_open (NULL,
12468 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12469 | FILEIO_O_TRUNC),
12470 0700, 0, &remote_errno));
440b7aec 12471 if (fd.get () == -1)
a6b151f1
DJ
12472 remote_hostio_error (remote_errno);
12473
12474 /* Send up to this many bytes at once. They won't all fit in the
12475 remote packet limit, so we'll transfer slightly fewer. */
12476 io_size = get_remote_packet_size ();
5ca3b260 12477 gdb::byte_vector buffer (io_size);
a6b151f1 12478
a6b151f1
DJ
12479 bytes_in_buffer = 0;
12480 saw_eof = 0;
12481 offset = 0;
12482 while (bytes_in_buffer || !saw_eof)
12483 {
12484 if (!saw_eof)
12485 {
5ca3b260 12486 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 12487 io_size - bytes_in_buffer,
d419f42d 12488 file.get ());
a6b151f1
DJ
12489 if (bytes == 0)
12490 {
d419f42d 12491 if (ferror (file.get ()))
a6b151f1
DJ
12492 error (_("Error reading %s."), local_file);
12493 else
12494 {
12495 /* EOF. Unless there is something still in the
12496 buffer from the last iteration, we are done. */
12497 saw_eof = 1;
12498 if (bytes_in_buffer == 0)
12499 break;
12500 }
12501 }
12502 }
12503 else
12504 bytes = 0;
12505
12506 bytes += bytes_in_buffer;
12507 bytes_in_buffer = 0;
12508
5ca3b260 12509 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 12510 offset, &remote_errno);
a6b151f1
DJ
12511
12512 if (retcode < 0)
12513 remote_hostio_error (remote_errno);
12514 else if (retcode == 0)
12515 error (_("Remote write of %d bytes returned 0!"), bytes);
12516 else if (retcode < bytes)
12517 {
12518 /* Short write. Save the rest of the read data for the next
12519 write. */
12520 bytes_in_buffer = bytes - retcode;
5ca3b260 12521 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
12522 }
12523
12524 offset += retcode;
12525 }
12526
6b8edb51 12527 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12528 remote_hostio_error (remote_errno);
12529
12530 if (from_tty)
12531 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
a6b151f1
DJ
12532}
12533
12534void
12535remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
12536{
12537 remote_target *remote = get_current_remote_target ();
12538
12539 if (remote == nullptr)
12540 error (_("command can only be used with remote target"));
12541
12542 remote->remote_file_get (remote_file, local_file, from_tty);
12543}
12544
12545void
12546remote_target::remote_file_get (const char *remote_file, const char *local_file,
12547 int from_tty)
a6b151f1 12548{
440b7aec 12549 int remote_errno, bytes, io_size;
a6b151f1 12550 ULONGEST offset;
a6b151f1 12551
440b7aec 12552 scoped_remote_fd fd
6b8edb51
PA
12553 (this, remote_hostio_open (NULL,
12554 remote_file, FILEIO_O_RDONLY, 0, 0,
12555 &remote_errno));
440b7aec 12556 if (fd.get () == -1)
a6b151f1
DJ
12557 remote_hostio_error (remote_errno);
12558
d419f42d 12559 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12560 if (file == NULL)
12561 perror_with_name (local_file);
a6b151f1
DJ
12562
12563 /* Send up to this many bytes at once. They won't all fit in the
12564 remote packet limit, so we'll transfer slightly fewer. */
12565 io_size = get_remote_packet_size ();
5ca3b260 12566 gdb::byte_vector buffer (io_size);
a6b151f1 12567
a6b151f1
DJ
12568 offset = 0;
12569 while (1)
12570 {
5ca3b260 12571 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 12572 &remote_errno);
a6b151f1
DJ
12573 if (bytes == 0)
12574 /* Success, but no bytes, means end-of-file. */
12575 break;
12576 if (bytes == -1)
12577 remote_hostio_error (remote_errno);
12578
12579 offset += bytes;
12580
5ca3b260 12581 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
12582 if (bytes == 0)
12583 perror_with_name (local_file);
12584 }
12585
6b8edb51 12586 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12587 remote_hostio_error (remote_errno);
12588
12589 if (from_tty)
12590 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
a6b151f1
DJ
12591}
12592
12593void
12594remote_file_delete (const char *remote_file, int from_tty)
12595{
6b8edb51 12596 remote_target *remote = get_current_remote_target ();
a6b151f1 12597
6b8edb51 12598 if (remote == nullptr)
a6b151f1
DJ
12599 error (_("command can only be used with remote target"));
12600
6b8edb51
PA
12601 remote->remote_file_delete (remote_file, from_tty);
12602}
12603
12604void
12605remote_target::remote_file_delete (const char *remote_file, int from_tty)
12606{
12607 int retcode, remote_errno;
12608
12609 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
12610 if (retcode == -1)
12611 remote_hostio_error (remote_errno);
12612
12613 if (from_tty)
12614 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12615}
12616
12617static void
ac88e2de 12618remote_put_command (const char *args, int from_tty)
a6b151f1 12619{
d1a41061
PP
12620 if (args == NULL)
12621 error_no_arg (_("file to put"));
12622
773a1edc 12623 gdb_argv argv (args);
a6b151f1
DJ
12624 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12625 error (_("Invalid parameters to remote put"));
12626
12627 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12628}
12629
12630static void
ac88e2de 12631remote_get_command (const char *args, int from_tty)
a6b151f1 12632{
d1a41061
PP
12633 if (args == NULL)
12634 error_no_arg (_("file to get"));
12635
773a1edc 12636 gdb_argv argv (args);
a6b151f1
DJ
12637 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12638 error (_("Invalid parameters to remote get"));
12639
12640 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12641}
12642
12643static void
ac88e2de 12644remote_delete_command (const char *args, int from_tty)
a6b151f1 12645{
d1a41061
PP
12646 if (args == NULL)
12647 error_no_arg (_("file to delete"));
12648
773a1edc 12649 gdb_argv argv (args);
a6b151f1
DJ
12650 if (argv[0] == NULL || argv[1] != NULL)
12651 error (_("Invalid parameters to remote delete"));
12652
12653 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12654}
12655
12656static void
981a3fb3 12657remote_command (const char *args, int from_tty)
a6b151f1 12658{
635c7e8a 12659 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12660}
12661
57810aa7 12662bool
f6ac5f3d 12663remote_target::can_execute_reverse ()
b2175913 12664{
4082afcc
PA
12665 if (packet_support (PACKET_bs) == PACKET_ENABLE
12666 || packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 12667 return true;
40ab02ce 12668 else
57810aa7 12669 return false;
b2175913
MS
12670}
12671
57810aa7 12672bool
f6ac5f3d 12673remote_target::supports_non_stop ()
74531fed 12674{
57810aa7 12675 return true;
74531fed
PA
12676}
12677
57810aa7 12678bool
f6ac5f3d 12679remote_target::supports_disable_randomization ()
03583c20
UW
12680{
12681 /* Only supported in extended mode. */
57810aa7 12682 return false;
03583c20
UW
12683}
12684
57810aa7 12685bool
f6ac5f3d 12686remote_target::supports_multi_process ()
8a305172
PA
12687{
12688 struct remote_state *rs = get_remote_state ();
a744cf53 12689
8020350c 12690 return remote_multi_process_p (rs);
8a305172
PA
12691}
12692
70221824 12693static int
f6ac5f3d 12694remote_supports_cond_tracepoints ()
782b2b07 12695{
4082afcc 12696 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12697}
12698
57810aa7 12699bool
f6ac5f3d 12700remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 12701{
4082afcc 12702 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12703}
12704
70221824 12705static int
f6ac5f3d 12706remote_supports_fast_tracepoints ()
7a697b8d 12707{
4082afcc 12708 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12709}
12710
0fb4aa4b 12711static int
f6ac5f3d 12712remote_supports_static_tracepoints ()
0fb4aa4b 12713{
4082afcc 12714 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12715}
12716
1e4d1764 12717static int
f6ac5f3d 12718remote_supports_install_in_trace ()
1e4d1764 12719{
4082afcc 12720 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12721}
12722
57810aa7 12723bool
f6ac5f3d 12724remote_target::supports_enable_disable_tracepoint ()
d248b706 12725{
4082afcc
PA
12726 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12727 == PACKET_ENABLE);
d248b706
KY
12728}
12729
57810aa7 12730bool
f6ac5f3d 12731remote_target::supports_string_tracing ()
3065dfb6 12732{
4082afcc 12733 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12734}
12735
57810aa7 12736bool
f6ac5f3d 12737remote_target::can_run_breakpoint_commands ()
d3ce09f5 12738{
4082afcc 12739 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12740}
12741
f6ac5f3d
PA
12742void
12743remote_target::trace_init ()
35b1e5cc 12744{
b6bb3468
PA
12745 struct remote_state *rs = get_remote_state ();
12746
35b1e5cc 12747 putpkt ("QTinit");
b6bb3468
PA
12748 remote_get_noisy_reply ();
12749 if (strcmp (rs->buf, "OK") != 0)
35b1e5cc
SS
12750 error (_("Target does not support this command."));
12751}
12752
409873ef
SS
12753/* Recursive routine to walk through command list including loops, and
12754 download packets for each command. */
12755
6b8edb51
PA
12756void
12757remote_target::remote_download_command_source (int num, ULONGEST addr,
12758 struct command_line *cmds)
409873ef
SS
12759{
12760 struct remote_state *rs = get_remote_state ();
12761 struct command_line *cmd;
12762
12763 for (cmd = cmds; cmd; cmd = cmd->next)
12764 {
0df8b418 12765 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12766 strcpy (rs->buf, "QTDPsrc:");
12767 encode_source_string (num, addr, "cmd", cmd->line,
12768 rs->buf + strlen (rs->buf),
12769 rs->buf_size - strlen (rs->buf));
12770 putpkt (rs->buf);
b6bb3468
PA
12771 remote_get_noisy_reply ();
12772 if (strcmp (rs->buf, "OK"))
409873ef
SS
12773 warning (_("Target does not support source download."));
12774
12775 if (cmd->control_type == while_control
12776 || cmd->control_type == while_stepping_control)
12777 {
12973681 12778 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 12779
0df8b418 12780 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12781 strcpy (rs->buf, "QTDPsrc:");
12782 encode_source_string (num, addr, "cmd", "end",
12783 rs->buf + strlen (rs->buf),
12784 rs->buf_size - strlen (rs->buf));
12785 putpkt (rs->buf);
b6bb3468
PA
12786 remote_get_noisy_reply ();
12787 if (strcmp (rs->buf, "OK"))
409873ef
SS
12788 warning (_("Target does not support source download."));
12789 }
12790 }
12791}
12792
f6ac5f3d
PA
12793void
12794remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc 12795{
bba74b36 12796#define BUF_SIZE 2048
e8ba3115 12797
35b1e5cc 12798 CORE_ADDR tpaddr;
409873ef 12799 char addrbuf[40];
bba74b36 12800 char buf[BUF_SIZE];
b44ec619
SM
12801 std::vector<std::string> tdp_actions;
12802 std::vector<std::string> stepping_actions;
35b1e5cc 12803 char *pkt;
e8ba3115 12804 struct breakpoint *b = loc->owner;
d9b3f62e 12805 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 12806 struct remote_state *rs = get_remote_state ();
35b1e5cc 12807
dc673c81 12808 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12809
12810 tpaddr = loc->address;
12811 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
12812 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12813 addrbuf, /* address */
12814 (b->enable_state == bp_enabled ? 'E' : 'D'),
12815 t->step_count, t->pass_count);
e8ba3115
YQ
12816 /* Fast tracepoints are mostly handled by the target, but we can
12817 tell the target how big of an instruction block should be moved
12818 around. */
12819 if (b->type == bp_fast_tracepoint)
12820 {
12821 /* Only test for support at download time; we may not know
12822 target capabilities at definition time. */
12823 if (remote_supports_fast_tracepoints ())
35b1e5cc 12824 {
6b940e6a
PL
12825 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12826 NULL))
bba74b36 12827 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 12828 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 12829 else
e8ba3115
YQ
12830 /* If it passed validation at definition but fails now,
12831 something is very wrong. */
12832 internal_error (__FILE__, __LINE__,
12833 _("Fast tracepoint not "
12834 "valid during download"));
35b1e5cc 12835 }
e8ba3115
YQ
12836 else
12837 /* Fast tracepoints are functionally identical to regular
12838 tracepoints, so don't take lack of support as a reason to
12839 give up on the trace run. */
12840 warning (_("Target does not support fast tracepoints, "
12841 "downloading %d as regular tracepoint"), b->number);
12842 }
12843 else if (b->type == bp_static_tracepoint)
12844 {
12845 /* Only test for support at download time; we may not know
12846 target capabilities at definition time. */
12847 if (remote_supports_static_tracepoints ())
0fb4aa4b 12848 {
e8ba3115 12849 struct static_tracepoint_marker marker;
0fb4aa4b 12850
e8ba3115
YQ
12851 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12852 strcat (buf, ":S");
0fb4aa4b 12853 else
e8ba3115 12854 error (_("Static tracepoint not valid during download"));
0fb4aa4b 12855 }
e8ba3115
YQ
12856 else
12857 /* Fast tracepoints are functionally identical to regular
12858 tracepoints, so don't take lack of support as a reason
12859 to give up on the trace run. */
12860 error (_("Target does not support static tracepoints"));
12861 }
12862 /* If the tracepoint has a conditional, make it into an agent
12863 expression and append to the definition. */
12864 if (loc->cond)
12865 {
12866 /* Only test support at download time, we may not know target
12867 capabilities at definition time. */
12868 if (remote_supports_cond_tracepoints ())
35b1e5cc 12869 {
833177a4 12870 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
bba74b36
YQ
12871 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12872 aexpr->len);
e8ba3115 12873 pkt = buf + strlen (buf);
b44ec619 12874 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
12875 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12876 *pkt = '\0';
35b1e5cc 12877 }
e8ba3115
YQ
12878 else
12879 warning (_("Target does not support conditional tracepoints, "
12880 "ignoring tp %d cond"), b->number);
12881 }
35b1e5cc 12882
d9b3f62e 12883 if (b->commands || *default_collect)
e8ba3115
YQ
12884 strcat (buf, "-");
12885 putpkt (buf);
b6bb3468
PA
12886 remote_get_noisy_reply ();
12887 if (strcmp (rs->buf, "OK"))
e8ba3115 12888 error (_("Target does not support tracepoints."));
35b1e5cc 12889
e8ba3115 12890 /* do_single_steps (t); */
b44ec619
SM
12891 for (auto action_it = tdp_actions.begin ();
12892 action_it != tdp_actions.end (); action_it++)
e8ba3115 12893 {
b44ec619
SM
12894 QUIT; /* Allow user to bail out with ^C. */
12895
12896 bool has_more = (action_it != tdp_actions.end ()
12897 || !stepping_actions.empty ());
12898
12899 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12900 b->number, addrbuf, /* address */
12901 action_it->c_str (),
12902 has_more ? '-' : 0);
12903 putpkt (buf);
12904 remote_get_noisy_reply ();
12905 if (strcmp (rs->buf, "OK"))
12906 error (_("Error on target while setting tracepoints."));
e8ba3115 12907 }
409873ef 12908
b44ec619
SM
12909 for (auto action_it = stepping_actions.begin ();
12910 action_it != stepping_actions.end (); action_it++)
12911 {
12912 QUIT; /* Allow user to bail out with ^C. */
12913
12914 bool is_first = action_it == stepping_actions.begin ();
12915 bool has_more = action_it != stepping_actions.end ();
12916
12917 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12918 b->number, addrbuf, /* address */
12919 is_first ? "S" : "",
12920 action_it->c_str (),
12921 has_more ? "-" : "");
12922 putpkt (buf);
12923 remote_get_noisy_reply ();
12924 if (strcmp (rs->buf, "OK"))
12925 error (_("Error on target while setting tracepoints."));
12926 }
12927
4082afcc 12928 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 12929 {
f00aae0f 12930 if (b->location != NULL)
409873ef 12931 {
e8ba3115 12932 strcpy (buf, "QTDPsrc:");
f00aae0f 12933 encode_source_string (b->number, loc->address, "at",
d28cd78a 12934 event_location_to_string (b->location.get ()),
f00aae0f 12935 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115 12936 putpkt (buf);
b6bb3468
PA
12937 remote_get_noisy_reply ();
12938 if (strcmp (rs->buf, "OK"))
e8ba3115 12939 warning (_("Target does not support source download."));
409873ef 12940 }
e8ba3115
YQ
12941 if (b->cond_string)
12942 {
12943 strcpy (buf, "QTDPsrc:");
12944 encode_source_string (b->number, loc->address,
12945 "cond", b->cond_string, buf + strlen (buf),
12946 2048 - strlen (buf));
12947 putpkt (buf);
b6bb3468
PA
12948 remote_get_noisy_reply ();
12949 if (strcmp (rs->buf, "OK"))
e8ba3115
YQ
12950 warning (_("Target does not support source download."));
12951 }
12952 remote_download_command_source (b->number, loc->address,
12953 breakpoint_commands (b));
35b1e5cc 12954 }
35b1e5cc
SS
12955}
12956
57810aa7 12957bool
f6ac5f3d 12958remote_target::can_download_tracepoint ()
1e4d1764 12959{
1e51243a
PA
12960 struct remote_state *rs = get_remote_state ();
12961 struct trace_status *ts;
12962 int status;
12963
12964 /* Don't try to install tracepoints until we've relocated our
12965 symbols, and fetched and merged the target's tracepoint list with
12966 ours. */
12967 if (rs->starting_up)
57810aa7 12968 return false;
1e51243a
PA
12969
12970 ts = current_trace_status ();
f6ac5f3d 12971 status = get_trace_status (ts);
1e4d1764
YQ
12972
12973 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 12974 return false;
1e4d1764
YQ
12975
12976 /* If we are in a tracing experiment, but remote stub doesn't support
12977 installing tracepoint in trace, we have to return. */
12978 if (!remote_supports_install_in_trace ())
57810aa7 12979 return false;
1e4d1764 12980
57810aa7 12981 return true;
1e4d1764
YQ
12982}
12983
12984
f6ac5f3d
PA
12985void
12986remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
12987{
12988 struct remote_state *rs = get_remote_state ();
00bf0b85 12989 char *p;
35b1e5cc 12990
bba74b36 12991 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
12992 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12993 tsv.builtin);
00bf0b85 12994 p = rs->buf + strlen (rs->buf);
c252925c 12995 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
00bf0b85 12996 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 12997 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 12998 *p++ = '\0';
35b1e5cc 12999 putpkt (rs->buf);
b6bb3468
PA
13000 remote_get_noisy_reply ();
13001 if (*rs->buf == '\0')
ad91cd99 13002 error (_("Target does not support this command."));
b6bb3468 13003 if (strcmp (rs->buf, "OK") != 0)
ad91cd99 13004 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13005}
13006
f6ac5f3d
PA
13007void
13008remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13009{
13010 struct remote_state *rs = get_remote_state ();
13011 char addr_buf[40];
13012
13013 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
13014 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13015 location->owner->number, addr_buf);
d248b706 13016 putpkt (rs->buf);
b6bb3468 13017 remote_get_noisy_reply ();
d248b706
KY
13018 if (*rs->buf == '\0')
13019 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13020 if (strcmp (rs->buf, "OK") != 0)
13021 error (_("Error on target while enabling tracepoint."));
13022}
13023
f6ac5f3d
PA
13024void
13025remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13026{
13027 struct remote_state *rs = get_remote_state ();
13028 char addr_buf[40];
13029
13030 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
13031 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13032 location->owner->number, addr_buf);
d248b706 13033 putpkt (rs->buf);
b6bb3468 13034 remote_get_noisy_reply ();
d248b706
KY
13035 if (*rs->buf == '\0')
13036 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13037 if (strcmp (rs->buf, "OK") != 0)
13038 error (_("Error on target while disabling tracepoint."));
13039}
13040
f6ac5f3d
PA
13041void
13042remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13043{
13044 asection *s;
81b9b86e 13045 bfd *abfd = NULL;
35b1e5cc 13046 bfd_size_type size;
608bcef2 13047 bfd_vma vma;
35b1e5cc 13048 int anysecs = 0;
c2fa21f1 13049 int offset = 0;
35b1e5cc
SS
13050
13051 if (!exec_bfd)
13052 return; /* No information to give. */
13053
b6bb3468
PA
13054 struct remote_state *rs = get_remote_state ();
13055
13056 strcpy (rs->buf, "QTro");
13057 offset = strlen (rs->buf);
35b1e5cc
SS
13058 for (s = exec_bfd->sections; s; s = s->next)
13059 {
13060 char tmp1[40], tmp2[40];
c2fa21f1 13061 int sec_length;
35b1e5cc
SS
13062
13063 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 13064 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
13065 (s->flags & SEC_READONLY) == 0)
13066 continue;
13067
13068 anysecs = 1;
81b9b86e 13069 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 13070 size = bfd_get_section_size (s);
608bcef2
HZ
13071 sprintf_vma (tmp1, vma);
13072 sprintf_vma (tmp2, vma + size);
c2fa21f1 13073 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
b6bb3468 13074 if (offset + sec_length + 1 > rs->buf_size)
c2fa21f1 13075 {
4082afcc 13076 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 13077 warning (_("\
c2fa21f1
HZ
13078Too many sections for read-only sections definition packet."));
13079 break;
13080 }
b6bb3468 13081 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
bba74b36 13082 tmp1, tmp2);
c2fa21f1 13083 offset += sec_length;
35b1e5cc
SS
13084 }
13085 if (anysecs)
13086 {
b6bb3468
PA
13087 putpkt (rs->buf);
13088 getpkt (&rs->buf, &rs->buf_size, 0);
35b1e5cc
SS
13089 }
13090}
13091
f6ac5f3d
PA
13092void
13093remote_target::trace_start ()
35b1e5cc 13094{
b6bb3468
PA
13095 struct remote_state *rs = get_remote_state ();
13096
35b1e5cc 13097 putpkt ("QTStart");
b6bb3468
PA
13098 remote_get_noisy_reply ();
13099 if (*rs->buf == '\0')
ad91cd99 13100 error (_("Target does not support this command."));
b6bb3468
PA
13101 if (strcmp (rs->buf, "OK") != 0)
13102 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
13103}
13104
f6ac5f3d
PA
13105int
13106remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13107{
953b98d1 13108 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13109 char *p = NULL;
0df8b418 13110 /* FIXME we need to get register block size some other way. */
00bf0b85 13111 extern int trace_regblock_size;
bd3eecc3 13112 enum packet_result result;
b6bb3468 13113 struct remote_state *rs = get_remote_state ();
bd3eecc3 13114
4082afcc 13115 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13116 return -1;
a744cf53 13117
5cd63fda 13118 trace_regblock_size
9d6eea31 13119 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 13120
049dc89b
JK
13121 putpkt ("qTStatus");
13122
492d29ea 13123 TRY
67f41397 13124 {
b6bb3468 13125 p = remote_get_noisy_reply ();
67f41397 13126 }
492d29ea 13127 CATCH (ex, RETURN_MASK_ERROR)
67f41397 13128 {
598d3636
JK
13129 if (ex.error != TARGET_CLOSE_ERROR)
13130 {
13131 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13132 return -1;
13133 }
13134 throw_exception (ex);
67f41397 13135 }
492d29ea 13136 END_CATCH
00bf0b85 13137
bd3eecc3
PA
13138 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13139
00bf0b85 13140 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13141 if (result == PACKET_UNKNOWN)
00bf0b85 13142 return -1;
35b1e5cc 13143
00bf0b85 13144 /* We're working with a live target. */
f5911ea1 13145 ts->filename = NULL;
00bf0b85 13146
00bf0b85 13147 if (*p++ != 'T')
b6bb3468 13148 error (_("Bogus trace status reply from target: %s"), rs->buf);
35b1e5cc 13149
84cebc4a
YQ
13150 /* Function 'parse_trace_status' sets default value of each field of
13151 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13152 parse_trace_status (p, ts);
13153
13154 return ts->running;
35b1e5cc
SS
13155}
13156
f6ac5f3d
PA
13157void
13158remote_target::get_tracepoint_status (struct breakpoint *bp,
13159 struct uploaded_tp *utp)
f196051f
SS
13160{
13161 struct remote_state *rs = get_remote_state ();
f196051f
SS
13162 char *reply;
13163 struct bp_location *loc;
13164 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 13165 size_t size = get_remote_packet_size ();
f196051f
SS
13166
13167 if (tp)
13168 {
c1fc2657 13169 tp->hit_count = 0;
f196051f 13170 tp->traceframe_usage = 0;
c1fc2657 13171 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
13172 {
13173 /* If the tracepoint was never downloaded, don't go asking for
13174 any status. */
13175 if (tp->number_on_target == 0)
13176 continue;
bba74b36
YQ
13177 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13178 phex_nz (loc->address, 0));
f196051f 13179 putpkt (rs->buf);
b6bb3468 13180 reply = remote_get_noisy_reply ();
f196051f
SS
13181 if (reply && *reply)
13182 {
13183 if (*reply == 'V')
13184 parse_tracepoint_status (reply + 1, bp, utp);
13185 }
13186 }
13187 }
13188 else if (utp)
13189 {
13190 utp->hit_count = 0;
13191 utp->traceframe_usage = 0;
bba74b36
YQ
13192 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13193 phex_nz (utp->addr, 0));
f196051f 13194 putpkt (rs->buf);
b6bb3468 13195 reply = remote_get_noisy_reply ();
f196051f
SS
13196 if (reply && *reply)
13197 {
13198 if (*reply == 'V')
13199 parse_tracepoint_status (reply + 1, bp, utp);
13200 }
13201 }
13202}
13203
f6ac5f3d
PA
13204void
13205remote_target::trace_stop ()
35b1e5cc 13206{
b6bb3468
PA
13207 struct remote_state *rs = get_remote_state ();
13208
35b1e5cc 13209 putpkt ("QTStop");
b6bb3468
PA
13210 remote_get_noisy_reply ();
13211 if (*rs->buf == '\0')
ad91cd99 13212 error (_("Target does not support this command."));
b6bb3468
PA
13213 if (strcmp (rs->buf, "OK") != 0)
13214 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
13215}
13216
f6ac5f3d
PA
13217int
13218remote_target::trace_find (enum trace_find_type type, int num,
13219 CORE_ADDR addr1, CORE_ADDR addr2,
13220 int *tpp)
35b1e5cc
SS
13221{
13222 struct remote_state *rs = get_remote_state ();
bba74b36 13223 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
13224 char *p, *reply;
13225 int target_frameno = -1, target_tracept = -1;
13226
e6e4e701
PA
13227 /* Lookups other than by absolute frame number depend on the current
13228 trace selected, so make sure it is correct on the remote end
13229 first. */
13230 if (type != tfind_number)
13231 set_remote_traceframe ();
13232
35b1e5cc
SS
13233 p = rs->buf;
13234 strcpy (p, "QTFrame:");
13235 p = strchr (p, '\0');
13236 switch (type)
13237 {
13238 case tfind_number:
bba74b36 13239 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13240 break;
13241 case tfind_pc:
bba74b36 13242 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13243 break;
13244 case tfind_tp:
bba74b36 13245 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13246 break;
13247 case tfind_range:
bba74b36
YQ
13248 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13249 phex_nz (addr2, 0));
35b1e5cc
SS
13250 break;
13251 case tfind_outside:
bba74b36
YQ
13252 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13253 phex_nz (addr2, 0));
35b1e5cc
SS
13254 break;
13255 default:
9b20d036 13256 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13257 }
13258
13259 putpkt (rs->buf);
b6bb3468 13260 reply = remote_get_noisy_reply ();
ad91cd99
PA
13261 if (*reply == '\0')
13262 error (_("Target does not support this command."));
35b1e5cc
SS
13263
13264 while (reply && *reply)
13265 switch (*reply)
13266 {
13267 case 'F':
f197e0f1
VP
13268 p = ++reply;
13269 target_frameno = (int) strtol (p, &reply, 16);
13270 if (reply == p)
13271 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13272 /* Don't update our remote traceframe number cache on failure
13273 to select a remote traceframe. */
f197e0f1
VP
13274 if (target_frameno == -1)
13275 return -1;
35b1e5cc
SS
13276 break;
13277 case 'T':
f197e0f1
VP
13278 p = ++reply;
13279 target_tracept = (int) strtol (p, &reply, 16);
13280 if (reply == p)
13281 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13282 break;
13283 case 'O': /* "OK"? */
13284 if (reply[1] == 'K' && reply[2] == '\0')
13285 reply += 2;
13286 else
13287 error (_("Bogus reply from target: %s"), reply);
13288 break;
13289 default:
13290 error (_("Bogus reply from target: %s"), reply);
13291 }
13292 if (tpp)
13293 *tpp = target_tracept;
e6e4e701 13294
262e1174 13295 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13296 return target_frameno;
13297}
13298
57810aa7 13299bool
f6ac5f3d 13300remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13301{
13302 struct remote_state *rs = get_remote_state ();
13303 char *reply;
13304 ULONGEST uval;
13305
e6e4e701
PA
13306 set_remote_traceframe ();
13307
bba74b36 13308 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13309 putpkt (rs->buf);
b6bb3468 13310 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13311 if (reply && *reply)
13312 {
13313 if (*reply == 'V')
13314 {
13315 unpack_varlen_hex (reply + 1, &uval);
13316 *val = (LONGEST) uval;
57810aa7 13317 return true;
35b1e5cc
SS
13318 }
13319 }
57810aa7 13320 return false;
35b1e5cc
SS
13321}
13322
f6ac5f3d
PA
13323int
13324remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13325{
13326 struct remote_state *rs = get_remote_state ();
13327 char *p, *reply;
13328
13329 p = rs->buf;
13330 strcpy (p, "QTSave:");
13331 p += strlen (p);
13332 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13333 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13334 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13335 *p++ = '\0';
13336 putpkt (rs->buf);
b6bb3468 13337 reply = remote_get_noisy_reply ();
d6c5869f 13338 if (*reply == '\0')
ad91cd99
PA
13339 error (_("Target does not support this command."));
13340 if (strcmp (reply, "OK") != 0)
13341 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13342 return 0;
13343}
13344
13345/* This is basically a memory transfer, but needs to be its own packet
13346 because we don't know how the target actually organizes its trace
13347 memory, plus we want to be able to ask for as much as possible, but
13348 not be unhappy if we don't get as much as we ask for. */
13349
f6ac5f3d
PA
13350LONGEST
13351remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13352{
13353 struct remote_state *rs = get_remote_state ();
13354 char *reply;
13355 char *p;
13356 int rslt;
13357
13358 p = rs->buf;
13359 strcpy (p, "qTBuffer:");
13360 p += strlen (p);
13361 p += hexnumstr (p, offset);
13362 *p++ = ',';
13363 p += hexnumstr (p, len);
13364 *p++ = '\0';
13365
13366 putpkt (rs->buf);
b6bb3468 13367 reply = remote_get_noisy_reply ();
00bf0b85
SS
13368 if (reply && *reply)
13369 {
13370 /* 'l' by itself means we're at the end of the buffer and
13371 there is nothing more to get. */
13372 if (*reply == 'l')
13373 return 0;
13374
13375 /* Convert the reply into binary. Limit the number of bytes to
13376 convert according to our passed-in buffer size, rather than
13377 what was returned in the packet; if the target is
13378 unexpectedly generous and gives us a bigger reply than we
13379 asked for, we don't want to crash. */
b6bb3468 13380 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13381 return rslt;
13382 }
13383
13384 /* Something went wrong, flag as an error. */
13385 return -1;
13386}
13387
f6ac5f3d
PA
13388void
13389remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13390{
13391 struct remote_state *rs = get_remote_state ();
13392
4082afcc 13393 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 13394 {
ad91cd99
PA
13395 char *reply;
13396
bba74b36 13397 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 13398 putpkt (rs->buf);
b6bb3468 13399 reply = remote_get_noisy_reply ();
ad91cd99 13400 if (*reply == '\0')
33da3f1c 13401 error (_("Target does not support this command."));
ad91cd99
PA
13402 if (strcmp (reply, "OK") != 0)
13403 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13404 }
13405 else if (val)
13406 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13407}
13408
f6ac5f3d
PA
13409int
13410remote_target::core_of_thread (ptid_t ptid)
dc146f7c
VP
13411{
13412 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 13413
7aabaf9d
SM
13414 if (info != NULL && info->priv != NULL)
13415 return get_remote_thread_info (info)->core;
13416
dc146f7c
VP
13417 return -1;
13418}
13419
f6ac5f3d
PA
13420void
13421remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13422{
13423 struct remote_state *rs = get_remote_state ();
ad91cd99 13424 char *reply;
4daf5ac0 13425
bba74b36 13426 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 13427 putpkt (rs->buf);
b6bb3468 13428 reply = remote_get_noisy_reply ();
ad91cd99 13429 if (*reply == '\0')
4daf5ac0 13430 error (_("Target does not support this command."));
ad91cd99
PA
13431 if (strcmp (reply, "OK") != 0)
13432 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13433}
13434
f6ac5f3d
PA
13435traceframe_info_up
13436remote_target::traceframe_info ()
b3b9301e 13437{
9018be22 13438 gdb::optional<gdb::char_vector> text
8b88a78e 13439 = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13440 NULL);
9018be22
SM
13441 if (text)
13442 return parse_traceframe_info (text->data ());
b3b9301e
PA
13443
13444 return NULL;
13445}
13446
405f8e94
SS
13447/* Handle the qTMinFTPILen packet. Returns the minimum length of
13448 instruction on which a fast tracepoint may be placed. Returns -1
13449 if the packet is not supported, and 0 if the minimum instruction
13450 length is unknown. */
13451
f6ac5f3d
PA
13452int
13453remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13454{
13455 struct remote_state *rs = get_remote_state ();
13456 char *reply;
13457
e886a173
PA
13458 /* If we're not debugging a process yet, the IPA can't be
13459 loaded. */
13460 if (!target_has_execution)
13461 return 0;
13462
13463 /* Make sure the remote is pointing at the right process. */
13464 set_general_process ();
13465
bba74b36 13466 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13467 putpkt (rs->buf);
b6bb3468 13468 reply = remote_get_noisy_reply ();
405f8e94
SS
13469 if (*reply == '\0')
13470 return -1;
13471 else
13472 {
13473 ULONGEST min_insn_len;
13474
13475 unpack_varlen_hex (reply, &min_insn_len);
13476
13477 return (int) min_insn_len;
13478 }
13479}
13480
f6ac5f3d
PA
13481void
13482remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13483{
4082afcc 13484 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13485 {
13486 struct remote_state *rs = get_remote_state ();
13487 char *buf = rs->buf;
13488 char *endbuf = rs->buf + get_remote_packet_size ();
13489 enum packet_result result;
13490
13491 gdb_assert (val >= 0 || val == -1);
13492 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13493 /* Send -1 as literal "-1" to avoid host size dependency. */
13494 if (val < 0)
13495 {
13496 *buf++ = '-';
13497 buf += hexnumstr (buf, (ULONGEST) -val);
13498 }
13499 else
13500 buf += hexnumstr (buf, (ULONGEST) val);
13501
13502 putpkt (rs->buf);
b6bb3468 13503 remote_get_noisy_reply ();
f6f899bf
HAQ
13504 result = packet_ok (rs->buf,
13505 &remote_protocol_packets[PACKET_QTBuffer_size]);
13506
13507 if (result != PACKET_OK)
13508 warning (_("Bogus reply from target: %s"), rs->buf);
13509 }
13510}
13511
57810aa7 13512bool
f6ac5f3d
PA
13513remote_target::set_trace_notes (const char *user, const char *notes,
13514 const char *stop_notes)
f196051f
SS
13515{
13516 struct remote_state *rs = get_remote_state ();
13517 char *reply;
13518 char *buf = rs->buf;
13519 char *endbuf = rs->buf + get_remote_packet_size ();
13520 int nbytes;
13521
13522 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13523 if (user)
13524 {
13525 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13526 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13527 buf += 2 * nbytes;
13528 *buf++ = ';';
13529 }
13530 if (notes)
13531 {
13532 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13533 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13534 buf += 2 * nbytes;
13535 *buf++ = ';';
13536 }
13537 if (stop_notes)
13538 {
13539 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13540 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13541 buf += 2 * nbytes;
13542 *buf++ = ';';
13543 }
13544 /* Ensure the buffer is terminated. */
13545 *buf = '\0';
13546
13547 putpkt (rs->buf);
b6bb3468 13548 reply = remote_get_noisy_reply ();
f196051f 13549 if (*reply == '\0')
57810aa7 13550 return false;
f196051f
SS
13551
13552 if (strcmp (reply, "OK") != 0)
13553 error (_("Bogus reply from target: %s"), reply);
13554
57810aa7 13555 return true;
f196051f
SS
13556}
13557
57810aa7
PA
13558bool
13559remote_target::use_agent (bool use)
d1feda86 13560{
4082afcc 13561 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13562 {
13563 struct remote_state *rs = get_remote_state ();
13564
13565 /* If the stub supports QAgent. */
bba74b36 13566 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
13567 putpkt (rs->buf);
13568 getpkt (&rs->buf, &rs->buf_size, 0);
13569
13570 if (strcmp (rs->buf, "OK") == 0)
13571 {
f6ac5f3d 13572 ::use_agent = use;
57810aa7 13573 return true;
d1feda86
YQ
13574 }
13575 }
13576
57810aa7 13577 return false;
d1feda86
YQ
13578}
13579
57810aa7 13580bool
f6ac5f3d 13581remote_target::can_use_agent ()
d1feda86 13582{
4082afcc 13583 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13584}
13585
9accd112
MM
13586struct btrace_target_info
13587{
13588 /* The ptid of the traced thread. */
13589 ptid_t ptid;
f4abbc16
MM
13590
13591 /* The obtained branch trace configuration. */
13592 struct btrace_config conf;
9accd112
MM
13593};
13594
f4abbc16
MM
13595/* Reset our idea of our target's btrace configuration. */
13596
13597static void
6b8edb51 13598remote_btrace_reset (remote_state *rs)
f4abbc16 13599{
f4abbc16
MM
13600 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13601}
13602
f4abbc16
MM
13603/* Synchronize the configuration with the target. */
13604
6b8edb51
PA
13605void
13606remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 13607{
d33501a5
MM
13608 struct packet_config *packet;
13609 struct remote_state *rs;
13610 char *buf, *pos, *endbuf;
13611
13612 rs = get_remote_state ();
13613 buf = rs->buf;
13614 endbuf = buf + get_remote_packet_size ();
13615
13616 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13617 if (packet_config_support (packet) == PACKET_ENABLE
13618 && conf->bts.size != rs->btrace_config.bts.size)
13619 {
13620 pos = buf;
13621 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13622 conf->bts.size);
13623
13624 putpkt (buf);
13625 getpkt (&buf, &rs->buf_size, 0);
13626
13627 if (packet_ok (buf, packet) == PACKET_ERROR)
13628 {
13629 if (buf[0] == 'E' && buf[1] == '.')
13630 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13631 else
13632 error (_("Failed to configure the BTS buffer size."));
13633 }
13634
13635 rs->btrace_config.bts.size = conf->bts.size;
13636 }
b20a6524
MM
13637
13638 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13639 if (packet_config_support (packet) == PACKET_ENABLE
13640 && conf->pt.size != rs->btrace_config.pt.size)
13641 {
13642 pos = buf;
13643 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13644 conf->pt.size);
13645
13646 putpkt (buf);
13647 getpkt (&buf, &rs->buf_size, 0);
13648
13649 if (packet_ok (buf, packet) == PACKET_ERROR)
13650 {
13651 if (buf[0] == 'E' && buf[1] == '.')
13652 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13653 else
13654 error (_("Failed to configure the trace buffer size."));
13655 }
13656
13657 rs->btrace_config.pt.size = conf->pt.size;
13658 }
f4abbc16
MM
13659}
13660
13661/* Read the current thread's btrace configuration from the target and
13662 store it into CONF. */
13663
13664static void
13665btrace_read_config (struct btrace_config *conf)
13666{
9018be22 13667 gdb::optional<gdb::char_vector> xml
8b88a78e 13668 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
13669 if (xml)
13670 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
13671}
13672
c0272db5
TW
13673/* Maybe reopen target btrace. */
13674
6b8edb51
PA
13675void
13676remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
13677{
13678 struct remote_state *rs = get_remote_state ();
c0272db5
TW
13679 struct thread_info *tp;
13680 int btrace_target_pushed = 0;
13681 int warned = 0;
13682
5ed8105e
PA
13683 scoped_restore_current_thread restore_thread;
13684
c0272db5
TW
13685 ALL_NON_EXITED_THREADS (tp)
13686 {
13687 set_general_thread (tp->ptid);
13688
13689 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13690 btrace_read_config (&rs->btrace_config);
13691
13692 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13693 continue;
13694
13695#if !defined (HAVE_LIBIPT)
13696 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13697 {
13698 if (!warned)
13699 {
13700 warned = 1;
c4e12631
MM
13701 warning (_("Target is recording using Intel Processor Trace "
13702 "but support was disabled at compile time."));
c0272db5
TW
13703 }
13704
13705 continue;
13706 }
13707#endif /* !defined (HAVE_LIBIPT) */
13708
13709 /* Push target, once, but before anything else happens. This way our
13710 changes to the threads will be cleaned up by unpushing the target
13711 in case btrace_read_config () throws. */
13712 if (!btrace_target_pushed)
13713 {
13714 btrace_target_pushed = 1;
13715 record_btrace_push_target ();
13716 printf_filtered (_("Target is recording using %s.\n"),
13717 btrace_format_string (rs->btrace_config.format));
13718 }
13719
13720 tp->btrace.target = XCNEW (struct btrace_target_info);
13721 tp->btrace.target->ptid = tp->ptid;
13722 tp->btrace.target->conf = rs->btrace_config;
13723 }
c0272db5
TW
13724}
13725
9accd112
MM
13726/* Enable branch tracing. */
13727
f6ac5f3d
PA
13728struct btrace_target_info *
13729remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
9accd112
MM
13730{
13731 struct btrace_target_info *tinfo = NULL;
b20a6524 13732 struct packet_config *packet = NULL;
9accd112
MM
13733 struct remote_state *rs = get_remote_state ();
13734 char *buf = rs->buf;
13735 char *endbuf = rs->buf + get_remote_packet_size ();
13736
b20a6524
MM
13737 switch (conf->format)
13738 {
13739 case BTRACE_FORMAT_BTS:
13740 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13741 break;
13742
13743 case BTRACE_FORMAT_PT:
13744 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13745 break;
13746 }
13747
13748 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13749 error (_("Target does not support branch tracing."));
13750
f4abbc16
MM
13751 btrace_sync_conf (conf);
13752
9accd112
MM
13753 set_general_thread (ptid);
13754
13755 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13756 putpkt (rs->buf);
13757 getpkt (&rs->buf, &rs->buf_size, 0);
13758
13759 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13760 {
13761 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13762 error (_("Could not enable branch tracing for %s: %s"),
13763 target_pid_to_str (ptid), rs->buf + 2);
13764 else
13765 error (_("Could not enable branch tracing for %s."),
13766 target_pid_to_str (ptid));
13767 }
13768
8d749320 13769 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13770 tinfo->ptid = ptid;
13771
f4abbc16
MM
13772 /* If we fail to read the configuration, we lose some information, but the
13773 tracing itself is not impacted. */
492d29ea
PA
13774 TRY
13775 {
13776 btrace_read_config (&tinfo->conf);
13777 }
13778 CATCH (err, RETURN_MASK_ERROR)
13779 {
13780 if (err.message != NULL)
13781 warning ("%s", err.message);
13782 }
13783 END_CATCH
f4abbc16 13784
9accd112
MM
13785 return tinfo;
13786}
13787
13788/* Disable branch tracing. */
13789
f6ac5f3d
PA
13790void
13791remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13792{
13793 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13794 struct remote_state *rs = get_remote_state ();
13795 char *buf = rs->buf;
13796 char *endbuf = rs->buf + get_remote_packet_size ();
13797
4082afcc 13798 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13799 error (_("Target does not support branch tracing."));
13800
13801 set_general_thread (tinfo->ptid);
13802
13803 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13804 putpkt (rs->buf);
13805 getpkt (&rs->buf, &rs->buf_size, 0);
13806
13807 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13808 {
13809 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13810 error (_("Could not disable branch tracing for %s: %s"),
13811 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13812 else
13813 error (_("Could not disable branch tracing for %s."),
13814 target_pid_to_str (tinfo->ptid));
13815 }
13816
13817 xfree (tinfo);
13818}
13819
13820/* Teardown branch tracing. */
13821
f6ac5f3d
PA
13822void
13823remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13824{
13825 /* We must not talk to the target during teardown. */
13826 xfree (tinfo);
13827}
13828
13829/* Read the branch trace. */
13830
f6ac5f3d
PA
13831enum btrace_error
13832remote_target::read_btrace (struct btrace_data *btrace,
13833 struct btrace_target_info *tinfo,
13834 enum btrace_read_type type)
9accd112
MM
13835{
13836 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 13837 const char *annex;
9accd112 13838
4082afcc 13839 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13840 error (_("Target does not support branch tracing."));
13841
13842#if !defined(HAVE_LIBEXPAT)
13843 error (_("Cannot process branch tracing result. XML parsing not supported."));
13844#endif
13845
13846 switch (type)
13847 {
864089d2 13848 case BTRACE_READ_ALL:
9accd112
MM
13849 annex = "all";
13850 break;
864089d2 13851 case BTRACE_READ_NEW:
9accd112
MM
13852 annex = "new";
13853 break;
969c39fb
MM
13854 case BTRACE_READ_DELTA:
13855 annex = "delta";
13856 break;
9accd112
MM
13857 default:
13858 internal_error (__FILE__, __LINE__,
13859 _("Bad branch tracing read type: %u."),
13860 (unsigned int) type);
13861 }
13862
9018be22 13863 gdb::optional<gdb::char_vector> xml
8b88a78e 13864 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
9018be22 13865 if (!xml)
969c39fb 13866 return BTRACE_ERR_UNKNOWN;
9accd112 13867
9018be22 13868 parse_xml_btrace (btrace, xml->data ());
9accd112 13869
969c39fb 13870 return BTRACE_ERR_NONE;
9accd112
MM
13871}
13872
f6ac5f3d
PA
13873const struct btrace_config *
13874remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
13875{
13876 return &tinfo->conf;
13877}
13878
57810aa7 13879bool
f6ac5f3d 13880remote_target::augmented_libraries_svr4_read ()
ced63ec0 13881{
4082afcc
PA
13882 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13883 == PACKET_ENABLE);
ced63ec0
GB
13884}
13885
9dd130a0
TT
13886/* Implementation of to_load. */
13887
f6ac5f3d
PA
13888void
13889remote_target::load (const char *name, int from_tty)
9dd130a0
TT
13890{
13891 generic_load (name, from_tty);
13892}
13893
c78fa86a
GB
13894/* Accepts an integer PID; returns a string representing a file that
13895 can be opened on the remote side to get the symbols for the child
13896 process. Returns NULL if the operation is not supported. */
13897
f6ac5f3d
PA
13898char *
13899remote_target::pid_to_exec_file (int pid)
c78fa86a 13900{
9018be22 13901 static gdb::optional<gdb::char_vector> filename;
835205d0
GB
13902 struct inferior *inf;
13903 char *annex = NULL;
c78fa86a
GB
13904
13905 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13906 return NULL;
13907
835205d0
GB
13908 inf = find_inferior_pid (pid);
13909 if (inf == NULL)
13910 internal_error (__FILE__, __LINE__,
13911 _("not currently attached to process %d"), pid);
13912
13913 if (!inf->fake_pid_p)
13914 {
13915 const int annex_size = 9;
13916
224c3ddb 13917 annex = (char *) alloca (annex_size);
835205d0
GB
13918 xsnprintf (annex, annex_size, "%x", pid);
13919 }
13920
8b88a78e 13921 filename = target_read_stralloc (current_top_target (),
c78fa86a
GB
13922 TARGET_OBJECT_EXEC_FILE, annex);
13923
9018be22 13924 return filename ? filename->data () : nullptr;
c78fa86a
GB
13925}
13926
750ce8d1
YQ
13927/* Implement the to_can_do_single_step target_ops method. */
13928
f6ac5f3d
PA
13929int
13930remote_target::can_do_single_step ()
750ce8d1
YQ
13931{
13932 /* We can only tell whether target supports single step or not by
13933 supported s and S vCont actions if the stub supports vContSupported
13934 feature. If the stub doesn't support vContSupported feature,
13935 we have conservatively to think target doesn't supports single
13936 step. */
13937 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13938 {
13939 struct remote_state *rs = get_remote_state ();
13940
13941 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 13942 remote_vcont_probe ();
750ce8d1
YQ
13943
13944 return rs->supports_vCont.s && rs->supports_vCont.S;
13945 }
13946 else
13947 return 0;
13948}
13949
3a00c802
PA
13950/* Implementation of the to_execution_direction method for the remote
13951 target. */
13952
f6ac5f3d
PA
13953enum exec_direction_kind
13954remote_target::execution_direction ()
3a00c802
PA
13955{
13956 struct remote_state *rs = get_remote_state ();
13957
13958 return rs->last_resume_exec_dir;
13959}
13960
f6327dcb
KB
13961/* Return pointer to the thread_info struct which corresponds to
13962 THREAD_HANDLE (having length HANDLE_LEN). */
13963
f6ac5f3d
PA
13964thread_info *
13965remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13966 int handle_len,
13967 inferior *inf)
f6327dcb
KB
13968{
13969 struct thread_info *tp;
13970
13971 ALL_NON_EXITED_THREADS (tp)
13972 {
7aabaf9d 13973 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
13974
13975 if (tp->inf == inf && priv != NULL)
13976 {
7aabaf9d 13977 if (handle_len != priv->thread_handle.size ())
f6327dcb 13978 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
7aabaf9d
SM
13979 handle_len, priv->thread_handle.size ());
13980 if (memcmp (thread_handle, priv->thread_handle.data (),
f6327dcb
KB
13981 handle_len) == 0)
13982 return tp;
13983 }
13984 }
13985
13986 return NULL;
13987}
13988
57810aa7 13989bool
f6ac5f3d 13990remote_target::can_async_p ()
6426a772 13991{
5d93a237
TT
13992 struct remote_state *rs = get_remote_state ();
13993
3015c064
SM
13994 /* We don't go async if the user has explicitly prevented it with the
13995 "maint set target-async" command. */
c6ebd6cf 13996 if (!target_async_permitted)
57810aa7 13997 return false;
75c99385 13998
23860348 13999 /* We're async whenever the serial device is. */
5d93a237 14000 return serial_can_async_p (rs->remote_desc);
6426a772
JM
14001}
14002
57810aa7 14003bool
f6ac5f3d 14004remote_target::is_async_p ()
6426a772 14005{
5d93a237
TT
14006 struct remote_state *rs = get_remote_state ();
14007
c6ebd6cf 14008 if (!target_async_permitted)
75c99385 14009 /* We only enable async when the user specifically asks for it. */
57810aa7 14010 return false;
75c99385 14011
23860348 14012 /* We're async whenever the serial device is. */
5d93a237 14013 return serial_is_async_p (rs->remote_desc);
6426a772
JM
14014}
14015
2acceee2
JM
14016/* Pass the SERIAL event on and up to the client. One day this code
14017 will be able to delay notifying the client of an event until the
23860348 14018 point where an entire packet has been received. */
2acceee2 14019
2acceee2
JM
14020static serial_event_ftype remote_async_serial_handler;
14021
6426a772 14022static void
819cc324 14023remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14024{
2acceee2
JM
14025 /* Don't propogate error information up to the client. Instead let
14026 the client find out about the error by querying the target. */
6a3753b3 14027 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
14028}
14029
74531fed
PA
14030static void
14031remote_async_inferior_event_handler (gdb_client_data data)
14032{
6b8edb51 14033 inferior_event_handler (INF_REG_EVENT, data);
74531fed
PA
14034}
14035
f6ac5f3d
PA
14036void
14037remote_target::async (int enable)
2acceee2 14038{
5d93a237
TT
14039 struct remote_state *rs = get_remote_state ();
14040
6a3753b3 14041 if (enable)
2acceee2 14042 {
88b496c3 14043 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14044
14045 /* If there are pending events in the stop reply queue tell the
14046 event loop to process them. */
953edf2b 14047 if (!rs->stop_reply_queue.empty ())
6b8edb51 14048 mark_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14049 /* For simplicity, below we clear the pending events token
14050 without remembering whether it is marked, so here we always
14051 mark it. If there's actually no pending notification to
14052 process, this ends up being a no-op (other than a spurious
14053 event-loop wakeup). */
14054 if (target_is_non_stop_p ())
14055 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14056 }
14057 else
b7d2e916
PA
14058 {
14059 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14060 /* If the core is disabling async, it doesn't want to be
14061 disturbed with target events. Clear all async event sources
14062 too. */
6b8edb51 14063 clear_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14064 if (target_is_non_stop_p ())
14065 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14066 }
6426a772
JM
14067}
14068
65706a29
PA
14069/* Implementation of the to_thread_events method. */
14070
f6ac5f3d
PA
14071void
14072remote_target::thread_events (int enable)
65706a29
PA
14073{
14074 struct remote_state *rs = get_remote_state ();
14075 size_t size = get_remote_packet_size ();
65706a29
PA
14076
14077 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14078 return;
14079
14080 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14081 putpkt (rs->buf);
14082 getpkt (&rs->buf, &rs->buf_size, 0);
14083
14084 switch (packet_ok (rs->buf,
14085 &remote_protocol_packets[PACKET_QThreadEvents]))
14086 {
14087 case PACKET_OK:
14088 if (strcmp (rs->buf, "OK") != 0)
14089 error (_("Remote refused setting thread events: %s"), rs->buf);
14090 break;
14091 case PACKET_ERROR:
14092 warning (_("Remote failure reply: %s"), rs->buf);
14093 break;
14094 case PACKET_UNKNOWN:
14095 break;
14096 }
14097}
14098
5a2468f5 14099static void
981a3fb3 14100set_remote_cmd (const char *args, int from_tty)
5a2468f5 14101{
635c7e8a 14102 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
14103}
14104
d471ea57 14105static void
981a3fb3 14106show_remote_cmd (const char *args, int from_tty)
d471ea57 14107{
37a105a1 14108 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14109 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14110 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14111 struct ui_out *uiout = current_uiout;
37a105a1 14112
2e783024 14113 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14114 for (; list != NULL; list = list->next)
14115 if (strcmp (list->name, "Z-packet") == 0)
14116 continue;
427c3a89
DJ
14117 else if (list->type == not_set_cmd)
14118 /* Alias commands are exactly like the original, except they
14119 don't have the normal type. */
14120 continue;
14121 else
37a105a1 14122 {
2e783024 14123 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14124
112e8700
SM
14125 uiout->field_string ("name", list->name);
14126 uiout->text (": ");
427c3a89 14127 if (list->type == show_cmd)
f5c4fcd9 14128 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14129 else
14130 cmd_func (list, NULL, from_tty);
37a105a1 14131 }
d471ea57 14132}
5a2468f5 14133
0f71a2f6 14134
23860348 14135/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
14136static void
14137remote_new_objfile (struct objfile *objfile)
14138{
6b8edb51 14139 remote_target *remote = get_current_remote_target ();
5d93a237 14140
6b8edb51
PA
14141 if (remote != NULL) /* Have a remote connection. */
14142 remote->remote_check_symbols ();
dc8acb97
MS
14143}
14144
00bf0b85
SS
14145/* Pull all the tracepoints defined on the target and create local
14146 data structures representing them. We don't want to create real
14147 tracepoints yet, we don't want to mess up the user's existing
14148 collection. */
14149
f6ac5f3d
PA
14150int
14151remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 14152{
00bf0b85
SS
14153 struct remote_state *rs = get_remote_state ();
14154 char *p;
d5551862 14155
00bf0b85
SS
14156 /* Ask for a first packet of tracepoint definition. */
14157 putpkt ("qTfP");
14158 getpkt (&rs->buf, &rs->buf_size, 0);
14159 p = rs->buf;
14160 while (*p && *p != 'l')
d5551862 14161 {
00bf0b85
SS
14162 parse_tracepoint_definition (p, utpp);
14163 /* Ask for another packet of tracepoint definition. */
14164 putpkt ("qTsP");
14165 getpkt (&rs->buf, &rs->buf_size, 0);
14166 p = rs->buf;
d5551862 14167 }
00bf0b85 14168 return 0;
d5551862
SS
14169}
14170
f6ac5f3d
PA
14171int
14172remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 14173{
00bf0b85 14174 struct remote_state *rs = get_remote_state ();
d5551862 14175 char *p;
d5551862 14176
00bf0b85
SS
14177 /* Ask for a first packet of variable definition. */
14178 putpkt ("qTfV");
d5551862
SS
14179 getpkt (&rs->buf, &rs->buf_size, 0);
14180 p = rs->buf;
00bf0b85 14181 while (*p && *p != 'l')
d5551862 14182 {
00bf0b85
SS
14183 parse_tsv_definition (p, utsvp);
14184 /* Ask for another packet of variable definition. */
14185 putpkt ("qTsV");
d5551862
SS
14186 getpkt (&rs->buf, &rs->buf_size, 0);
14187 p = rs->buf;
14188 }
00bf0b85 14189 return 0;
d5551862
SS
14190}
14191
c1e36e3e
PA
14192/* The "set/show range-stepping" show hook. */
14193
14194static void
14195show_range_stepping (struct ui_file *file, int from_tty,
14196 struct cmd_list_element *c,
14197 const char *value)
14198{
14199 fprintf_filtered (file,
14200 _("Debugger's willingness to use range stepping "
14201 "is %s.\n"), value);
14202}
14203
6b8edb51
PA
14204/* Return true if the vCont;r action is supported by the remote
14205 stub. */
14206
14207bool
14208remote_target::vcont_r_supported ()
14209{
14210 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14211 remote_vcont_probe ();
14212
14213 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14214 && get_remote_state ()->supports_vCont.r);
14215}
14216
c1e36e3e
PA
14217/* The "set/show range-stepping" set hook. */
14218
14219static void
eb4c3f4a 14220set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
14221 struct cmd_list_element *c)
14222{
6b8edb51
PA
14223 /* When enabling, check whether range stepping is actually supported
14224 by the target, and warn if not. */
c1e36e3e
PA
14225 if (use_range_stepping)
14226 {
6b8edb51
PA
14227 remote_target *remote = get_current_remote_target ();
14228 if (remote == NULL
14229 || !remote->vcont_r_supported ())
14230 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
14231 }
14232}
14233
c906108c 14234void
fba45db2 14235_initialize_remote (void)
c906108c 14236{
9a7071a8 14237 struct cmd_list_element *cmd;
6f937416 14238 const char *cmd_name;
ea9c271d 14239
0f71a2f6 14240 /* architecture specific data */
29709017
DJ
14241 remote_g_packet_data_handle =
14242 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14243
94585166
DB
14244 remote_pspace_data
14245 = register_program_space_data_with_cleanup (NULL,
14246 remote_pspace_data_cleanup);
14247
d9f719f1
PA
14248 add_target (remote_target_info, remote_target::open);
14249 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 14250
dc8acb97 14251 /* Hook into new objfile notification. */
76727919 14252 gdb::observers::new_objfile.attach (remote_new_objfile);
dc8acb97 14253
c906108c
SS
14254#if 0
14255 init_remote_threadtests ();
14256#endif
14257
23860348 14258 /* set/show remote ... */
d471ea57 14259
1bedd215 14260 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
14261Remote protocol specific variables\n\
14262Configure various remote-protocol specific variables such as\n\
1bedd215 14263the packets being used"),
cff3e48b 14264 &remote_set_cmdlist, "set remote ",
23860348 14265 0 /* allow-unknown */, &setlist);
1bedd215 14266 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
14267Remote protocol specific variables\n\
14268Configure various remote-protocol specific variables such as\n\
1bedd215 14269the packets being used"),
cff3e48b 14270 &remote_show_cmdlist, "show remote ",
23860348 14271 0 /* allow-unknown */, &showlist);
5a2468f5 14272
1a966eab
AC
14273 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14274Compare section data on target to the exec file.\n\
95cf3b38
DT
14275Argument is a single section name (default: all loaded sections).\n\
14276To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14277 &cmdlist);
14278
1a966eab
AC
14279 add_cmd ("packet", class_maintenance, packet_command, _("\
14280Send an arbitrary packet to a remote target.\n\
c906108c
SS
14281 maintenance packet TEXT\n\
14282If GDB is talking to an inferior via the GDB serial protocol, then\n\
14283this command sends the string TEXT to the inferior, and displays the\n\
14284response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14285terminating `#' character and checksum."),
c906108c
SS
14286 &maintenancelist);
14287
7915a72c
AC
14288 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14289Set whether to send break if interrupted."), _("\
14290Show whether to send break if interrupted."), _("\
14291If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14292 set_remotebreak, show_remotebreak,
e707bbc2 14293 &setlist, &showlist);
9a7071a8
JB
14294 cmd_name = "remotebreak";
14295 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14296 deprecate_cmd (cmd, "set remote interrupt-sequence");
14297 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14298 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14299 deprecate_cmd (cmd, "show remote interrupt-sequence");
14300
14301 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14302 interrupt_sequence_modes, &interrupt_sequence_mode,
14303 _("\
9a7071a8
JB
14304Set interrupt sequence to remote target."), _("\
14305Show interrupt sequence to remote target."), _("\
14306Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14307 NULL, show_interrupt_sequence,
14308 &remote_set_cmdlist,
14309 &remote_show_cmdlist);
14310
14311 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14312 &interrupt_on_connect, _("\
14313Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14314Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14315If set, interrupt sequence is sent to remote target."),
14316 NULL, NULL,
14317 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14318
23860348 14319 /* Install commands for configuring memory read/write packets. */
11cf8741 14320
1a966eab
AC
14321 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14322Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14323 &setlist);
1a966eab
AC
14324 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14325Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14326 &showlist);
14327 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14328 set_memory_write_packet_size, _("\
14329Set the maximum number of bytes per memory-write packet.\n\
14330Specify the number of bytes in a packet or 0 (zero) for the\n\
14331default packet size. The actual limit is further reduced\n\
14332dependent on the target. Specify ``fixed'' to disable the\n\
14333further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14334 &remote_set_cmdlist);
14335 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14336 set_memory_read_packet_size, _("\
14337Set the maximum number of bytes per memory-read packet.\n\
14338Specify the number of bytes in a packet or 0 (zero) for the\n\
14339default packet size. The actual limit is further reduced\n\
14340dependent on the target. Specify ``fixed'' to disable the\n\
14341further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14342 &remote_set_cmdlist);
14343 add_cmd ("memory-write-packet-size", no_class,
14344 show_memory_write_packet_size,
1a966eab 14345 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14346 &remote_show_cmdlist);
14347 add_cmd ("memory-read-packet-size", no_class,
14348 show_memory_read_packet_size,
1a966eab 14349 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14350 &remote_show_cmdlist);
c906108c 14351
b3f42336 14352 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14353 &remote_hw_watchpoint_limit, _("\
14354Set the maximum number of target hardware watchpoints."), _("\
14355Show the maximum number of target hardware watchpoints."), _("\
14356Specify a negative limit for unlimited."),
3e43a32a
MS
14357 NULL, NULL, /* FIXME: i18n: The maximum
14358 number of target hardware
14359 watchpoints is %s. */
b3f42336 14360 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
14361 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14362 &remote_hw_watchpoint_length_limit, _("\
14363Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14364Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14365Specify a negative limit for unlimited."),
14366 NULL, NULL, /* FIXME: i18n: The maximum
14367 length (in bytes) of a target
14368 hardware watchpoint is %s. */
14369 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 14370 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14371 &remote_hw_breakpoint_limit, _("\
14372Set the maximum number of target hardware breakpoints."), _("\
14373Show the maximum number of target hardware breakpoints."), _("\
14374Specify a negative limit for unlimited."),
3e43a32a
MS
14375 NULL, NULL, /* FIXME: i18n: The maximum
14376 number of target hardware
14377 breakpoints is %s. */
b3f42336 14378 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14379
1b493192
PA
14380 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14381 &remote_address_size, _("\
4d28ad1e
AC
14382Set the maximum size of the address (in bits) in a memory packet."), _("\
14383Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14384 NULL,
14385 NULL, /* FIXME: i18n: */
14386 &setlist, &showlist);
c906108c 14387
ca4f7f8b
PA
14388 init_all_packet_configs ();
14389
444abaca 14390 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14391 "X", "binary-download", 1);
0f71a2f6 14392
444abaca 14393 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14394 "vCont", "verbose-resume", 0);
506fb367 14395
89be2091
DJ
14396 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14397 "QPassSignals", "pass-signals", 0);
14398
82075af2
JS
14399 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14400 "QCatchSyscalls", "catch-syscalls", 0);
14401
9b224c5e
PA
14402 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14403 "QProgramSignals", "program-signals", 0);
14404
bc3b087d
SDJ
14405 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14406 "QSetWorkingDir", "set-working-dir", 0);
14407
aefd8b33
SDJ
14408 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14409 "QStartupWithShell", "startup-with-shell", 0);
14410
0a2dde4a
SDJ
14411 add_packet_config_cmd (&remote_protocol_packets
14412 [PACKET_QEnvironmentHexEncoded],
14413 "QEnvironmentHexEncoded", "environment-hex-encoded",
14414 0);
14415
14416 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14417 "QEnvironmentReset", "environment-reset",
14418 0);
14419
14420 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14421 "QEnvironmentUnset", "environment-unset",
14422 0);
14423
444abaca 14424 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14425 "qSymbol", "symbol-lookup", 0);
dc8acb97 14426
444abaca 14427 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14428 "P", "set-register", 1);
d471ea57 14429
444abaca 14430 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14431 "p", "fetch-register", 1);
b96ec7ac 14432
444abaca 14433 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14434 "Z0", "software-breakpoint", 0);
d471ea57 14435
444abaca 14436 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14437 "Z1", "hardware-breakpoint", 0);
d471ea57 14438
444abaca 14439 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14440 "Z2", "write-watchpoint", 0);
d471ea57 14441
444abaca 14442 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14443 "Z3", "read-watchpoint", 0);
d471ea57 14444
444abaca 14445 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14446 "Z4", "access-watchpoint", 0);
d471ea57 14447
0876f84a
DJ
14448 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14449 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14450
c78fa86a
GB
14451 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14452 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14453
23181151
DJ
14454 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14455 "qXfer:features:read", "target-features", 0);
14456
cfa9d6d9
DJ
14457 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14458 "qXfer:libraries:read", "library-info", 0);
14459
2268b414
JK
14460 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14461 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14462
fd79ecee
DJ
14463 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14464 "qXfer:memory-map:read", "memory-map", 0);
14465
0e7f50da
UW
14466 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14467 "qXfer:spu:read", "read-spu-object", 0);
14468
14469 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14470 "qXfer:spu:write", "write-spu-object", 0);
14471
07e059b5
VP
14472 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14473 "qXfer:osdata:read", "osdata", 0);
14474
dc146f7c
VP
14475 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14476 "qXfer:threads:read", "threads", 0);
14477
4aa995e1
PA
14478 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14479 "qXfer:siginfo:read", "read-siginfo-object", 0);
14480
14481 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14482 "qXfer:siginfo:write", "write-siginfo-object", 0);
14483
b3b9301e
PA
14484 add_packet_config_cmd
14485 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14486 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14487
169081d0
TG
14488 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14489 "qXfer:uib:read", "unwind-info-block", 0);
14490
444abaca 14491 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14492 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14493 0);
14494
711e434b
PM
14495 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14496 "qGetTIBAddr", "get-thread-information-block-address",
14497 0);
14498
40ab02ce
MS
14499 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14500 "bc", "reverse-continue", 0);
14501
14502 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14503 "bs", "reverse-step", 0);
14504
be2a5f71
DJ
14505 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14506 "qSupported", "supported-packets", 0);
14507
08388c79
DE
14508 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14509 "qSearch:memory", "search-memory", 0);
14510
bd3eecc3
PA
14511 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14512 "qTStatus", "trace-status", 0);
14513
15a201c8
GB
14514 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14515 "vFile:setfs", "hostio-setfs", 0);
14516
a6b151f1
DJ
14517 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14518 "vFile:open", "hostio-open", 0);
14519
14520 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14521 "vFile:pread", "hostio-pread", 0);
14522
14523 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14524 "vFile:pwrite", "hostio-pwrite", 0);
14525
14526 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14527 "vFile:close", "hostio-close", 0);
14528
14529 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14530 "vFile:unlink", "hostio-unlink", 0);
14531
b9e7b9c3
UW
14532 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14533 "vFile:readlink", "hostio-readlink", 0);
14534
0a93529c
GB
14535 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14536 "vFile:fstat", "hostio-fstat", 0);
14537
2d717e4f
DJ
14538 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14539 "vAttach", "attach", 0);
14540
14541 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14542 "vRun", "run", 0);
14543
a6f3e723
SL
14544 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14545 "QStartNoAckMode", "noack", 0);
14546
82f73884
PA
14547 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14548 "vKill", "kill", 0);
14549
0b16c5cf
PA
14550 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14551 "qAttached", "query-attached", 0);
14552
782b2b07 14553 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14554 "ConditionalTracepoints",
14555 "conditional-tracepoints", 0);
3788aec7
LM
14556
14557 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14558 "ConditionalBreakpoints",
14559 "conditional-breakpoints", 0);
14560
d3ce09f5
SS
14561 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14562 "BreakpointCommands",
14563 "breakpoint-commands", 0);
14564
7a697b8d
SS
14565 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14566 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14567
409873ef
SS
14568 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14569 "TracepointSource", "TracepointSource", 0);
14570
d914c394
SS
14571 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14572 "QAllow", "allow", 0);
14573
0fb4aa4b
PA
14574 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14575 "StaticTracepoints", "static-tracepoints", 0);
14576
1e4d1764
YQ
14577 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14578 "InstallInTrace", "install-in-trace", 0);
14579
0fb4aa4b
PA
14580 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14581 "qXfer:statictrace:read", "read-sdata-object", 0);
14582
78d85199
YQ
14583 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14584 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14585
03583c20
UW
14586 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14587 "QDisableRandomization", "disable-randomization", 0);
14588
d1feda86
YQ
14589 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14590 "QAgent", "agent", 0);
14591
f6f899bf
HAQ
14592 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14593 "QTBuffer:size", "trace-buffer-size", 0);
14594
9accd112
MM
14595 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14596 "Qbtrace:off", "disable-btrace", 0);
14597
14598 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14599 "Qbtrace:bts", "enable-btrace-bts", 0);
14600
14601 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14602 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14603
14604 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14605 "qXfer:btrace", "read-btrace", 0);
14606
f4abbc16
MM
14607 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14608 "qXfer:btrace-conf", "read-btrace-conf", 0);
14609
d33501a5
MM
14610 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14611 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14612
73b8c1fd
PA
14613 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14614 "multiprocess-feature", "multiprocess-feature", 0);
14615
f7e6eed5
PA
14616 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14617 "swbreak-feature", "swbreak-feature", 0);
14618
14619 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14620 "hwbreak-feature", "hwbreak-feature", 0);
14621
89245bc0
DB
14622 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14623 "fork-event-feature", "fork-event-feature", 0);
14624
14625 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14626 "vfork-event-feature", "vfork-event-feature", 0);
14627
b20a6524
MM
14628 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14629 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14630
750ce8d1
YQ
14631 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14632 "vContSupported", "verbose-resume-supported", 0);
14633
94585166
DB
14634 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14635 "exec-event-feature", "exec-event-feature", 0);
14636
de979965
PA
14637 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14638 "vCtrlC", "ctrl-c", 0);
14639
65706a29
PA
14640 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14641 "QThreadEvents", "thread-events", 0);
14642
f2faf941
PA
14643 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14644 "N stop reply", "no-resumed-stop-reply", 0);
14645
0b736949
DB
14646 /* Assert that we've registered "set remote foo-packet" commands
14647 for all packet configs. */
ca4f7f8b
PA
14648 {
14649 int i;
14650
14651 for (i = 0; i < PACKET_MAX; i++)
14652 {
14653 /* Ideally all configs would have a command associated. Some
14654 still don't though. */
14655 int excepted;
14656
14657 switch (i)
14658 {
14659 case PACKET_QNonStop:
ca4f7f8b
PA
14660 case PACKET_EnableDisableTracepoints_feature:
14661 case PACKET_tracenz_feature:
14662 case PACKET_DisconnectedTracing_feature:
14663 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14664 case PACKET_qCRC:
14665 /* Additions to this list need to be well justified:
14666 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14667 excepted = 1;
14668 break;
14669 default:
14670 excepted = 0;
14671 break;
14672 }
14673
14674 /* This catches both forgetting to add a config command, and
14675 forgetting to remove a packet from the exception list. */
14676 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14677 }
14678 }
14679
37a105a1
DJ
14680 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14681 Z sub-packet has its own set and show commands, but users may
14682 have sets to this variable in their .gdbinit files (or in their
14683 documentation). */
e9e68a56 14684 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14685 &remote_Z_packet_detect, _("\
14686Set use of remote protocol `Z' packets"), _("\
14687Show use of remote protocol `Z' packets "), _("\
3b64bf98 14688When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14689packets."),
e9e68a56 14690 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14691 show_remote_protocol_Z_packet_cmd,
14692 /* FIXME: i18n: Use of remote protocol
14693 `Z' packets is %s. */
e9e68a56 14694 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14695
a6b151f1
DJ
14696 add_prefix_cmd ("remote", class_files, remote_command, _("\
14697Manipulate files on the remote system\n\
14698Transfer files to and from the remote target system."),
14699 &remote_cmdlist, "remote ",
14700 0 /* allow-unknown */, &cmdlist);
14701
14702 add_cmd ("put", class_files, remote_put_command,
14703 _("Copy a local file to the remote system."),
14704 &remote_cmdlist);
14705
14706 add_cmd ("get", class_files, remote_get_command,
14707 _("Copy a remote file to the local system."),
14708 &remote_cmdlist);
14709
14710 add_cmd ("delete", class_files, remote_delete_command,
14711 _("Delete a remote file."),
14712 &remote_cmdlist);
14713
2d717e4f 14714 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14715 &remote_exec_file_var, _("\
2d717e4f 14716Set the remote pathname for \"run\""), _("\
94585166
DB
14717Show the remote pathname for \"run\""), NULL,
14718 set_remote_exec_file,
14719 show_remote_exec_file,
14720 &remote_set_cmdlist,
14721 &remote_show_cmdlist);
2d717e4f 14722
c1e36e3e
PA
14723 add_setshow_boolean_cmd ("range-stepping", class_run,
14724 &use_range_stepping, _("\
14725Enable or disable range stepping."), _("\
14726Show whether target-assisted range stepping is enabled."), _("\
14727If on, and the target supports it, when stepping a source line, GDB\n\
14728tells the target to step the corresponding range of addresses itself instead\n\
14729of issuing multiple single-steps. This speeds up source level\n\
14730stepping. If off, GDB always issues single-steps, even if range\n\
14731stepping is supported by the target. The default is on."),
14732 set_range_stepping,
14733 show_range_stepping,
14734 &setlist,
14735 &showlist);
14736
449092f6
CV
14737 /* Eventually initialize fileio. See fileio.c */
14738 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14739
ba348170 14740 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14741 special ptids with it set to != 0. */
ba348170
PA
14742 magic_null_ptid = ptid_build (42000, -1, 1);
14743 not_sent_ptid = ptid_build (42000, -2, 1);
14744 any_thread_ptid = ptid_build (42000, 0, 1);
c906108c 14745}
This page took 3.454621 seconds and 4 git commands to generate.