]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
kvx: fix kvx_reassemble_bundle index 8 out of bounds
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
213516ef 3 Copyright (C) 1988-2023 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"
3b3dac9b 30#include "process-stratum-target.h"
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
c906108c 33#include "gdbthread.h"
c2c6d25f 34#include "remote.h"
722247f1 35#include "remote-notif.h"
4e052eda 36#include "regcache.h"
fd0407d6 37#include "value.h"
76727919 38#include "observable.h"
a77053c2 39#include "solib.h"
37a105a1
DJ
40#include "cli/cli-decode.h"
41#include "cli/cli-setshow.h"
424163ea 42#include "target-descriptions.h"
a4453b7e 43#include "gdb_bfd.h"
268a13a5
TT
44#include "gdbsupport/filestuff.h"
45#include "gdbsupport/rsp-low.h"
6b940e6a 46#include "disasm.h"
f00aae0f 47#include "location.h"
c906108c 48
268a13a5 49#include "gdbsupport/gdb_sys_time.h"
c906108c 50
400b5eca 51#include "gdbsupport/event-loop.h"
c2c6d25f 52#include "event-top.h"
2acceee2 53#include "inf-loop.h"
43ff13b4 54
c906108c
SS
55#include <signal.h>
56#include "serial.h"
57
7e10abd1 58#include "gdbcore.h"
6240bebf 59
449092f6 60#include "remote-fileio.h"
198f946f 61#include "gdbsupport/fileio.h"
53ce3c39 62#include <sys/stat.h>
dc146f7c 63#include "xml-support.h"
449092f6 64
fd79ecee
DJ
65#include "memory-map.h"
66
35b1e5cc
SS
67#include "tracepoint.h"
68#include "ax.h"
69#include "ax-gdb.h"
268a13a5 70#include "gdbsupport/agent.h"
9accd112 71#include "btrace.h"
c0272db5 72#include "record-btrace.h"
268a13a5
TT
73#include "gdbsupport/scoped_restore.h"
74#include "gdbsupport/environ.h"
75#include "gdbsupport/byte-vector.h"
4a72de73 76#include "gdbsupport/search.h"
39ef2f62 77#include <algorithm>
ff52c073 78#include <iterator>
9d6eea31 79#include <unordered_map>
93b54c8e 80#include "async-event.h"
754487e2 81#include "gdbsupport/selftest.h"
35b1e5cc 82
f6ac5f3d
PA
83/* The remote target. */
84
d9f719f1
PA
85static const char remote_doc[] = N_("\
86Use a remote computer via a serial line, using a gdb-specific protocol.\n\
87Specify the serial device it is connected to\n\
88(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
89
cda09ec9
SM
90/* See remote.h */
91
02349803 92bool remote_debug = false;
cda09ec9 93
6b8edb51
PA
94#define OPAQUETHREADBYTES 8
95
96/* a 64 bit opaque identifier */
97typedef unsigned char threadref[OPAQUETHREADBYTES];
98
99struct gdb_ext_thread_info;
100struct threads_listing_context;
101typedef int (*rmt_thread_action) (threadref *ref, void *context);
102struct protocol_feature;
103struct packet_reg;
104
105struct stop_reply;
32603266 106typedef std::unique_ptr<stop_reply> stop_reply_up;
6b8edb51
PA
107
108/* Generic configuration support for packets the stub optionally
109 supports. Allows the user to specify the use of the packet as well
110 as allowing GDB to auto-detect support in the remote stub. */
111
112enum packet_support
113 {
114 PACKET_SUPPORT_UNKNOWN = 0,
115 PACKET_ENABLE,
116 PACKET_DISABLE
117 };
118
ff52c073
CS
119/* Convert the packet support auto_boolean to a name used for gdb printing. */
120
121static const char *
122get_packet_support_name (auto_boolean support)
123{
124 switch (support)
125 {
126 case AUTO_BOOLEAN_TRUE:
127 return "on";
128 case AUTO_BOOLEAN_FALSE:
129 return "off";
130 case AUTO_BOOLEAN_AUTO:
131 return "auto";
132 default:
133 gdb_assert_not_reached ("invalid var_auto_boolean");
134 }
135}
136
137/* Convert the target type (future remote target or currently connected target)
138 to a name used for gdb printing. */
139
140static const char *
141get_target_type_name (bool target_connected)
142{
143 if (target_connected)
144 return _("on the current remote target");
145 else
146 return _("on future remote targets");
147}
148
6b8edb51
PA
149/* Analyze a packet's return value and update the packet config
150 accordingly. */
151
152enum packet_result
153{
154 PACKET_ERROR,
155 PACKET_OK,
156 PACKET_UNKNOWN
157};
158
ff52c073
CS
159/* Enumeration of packets for a remote target. */
160
161enum {
162 PACKET_vCont = 0,
163 PACKET_X,
164 PACKET_qSymbol,
165 PACKET_P,
166 PACKET_p,
167 PACKET_Z0,
168 PACKET_Z1,
169 PACKET_Z2,
170 PACKET_Z3,
171 PACKET_Z4,
172 PACKET_vFile_setfs,
173 PACKET_vFile_open,
174 PACKET_vFile_pread,
175 PACKET_vFile_pwrite,
176 PACKET_vFile_close,
177 PACKET_vFile_unlink,
178 PACKET_vFile_readlink,
179 PACKET_vFile_fstat,
180 PACKET_qXfer_auxv,
181 PACKET_qXfer_features,
182 PACKET_qXfer_exec_file,
183 PACKET_qXfer_libraries,
184 PACKET_qXfer_libraries_svr4,
185 PACKET_qXfer_memory_map,
186 PACKET_qXfer_osdata,
187 PACKET_qXfer_threads,
188 PACKET_qXfer_statictrace_read,
189 PACKET_qXfer_traceframe_info,
190 PACKET_qXfer_uib,
191 PACKET_qGetTIBAddr,
192 PACKET_qGetTLSAddr,
193 PACKET_qSupported,
194 PACKET_qTStatus,
195 PACKET_QPassSignals,
196 PACKET_QCatchSyscalls,
197 PACKET_QProgramSignals,
198 PACKET_QSetWorkingDir,
199 PACKET_QStartupWithShell,
200 PACKET_QEnvironmentHexEncoded,
201 PACKET_QEnvironmentReset,
202 PACKET_QEnvironmentUnset,
203 PACKET_qCRC,
204 PACKET_qSearch_memory,
205 PACKET_vAttach,
206 PACKET_vRun,
207 PACKET_QStartNoAckMode,
208 PACKET_vKill,
209 PACKET_qXfer_siginfo_read,
210 PACKET_qXfer_siginfo_write,
211 PACKET_qAttached,
212
213 /* Support for conditional tracepoints. */
214 PACKET_ConditionalTracepoints,
215
216 /* Support for target-side breakpoint conditions. */
217 PACKET_ConditionalBreakpoints,
218
219 /* Support for target-side breakpoint commands. */
220 PACKET_BreakpointCommands,
221
222 /* Support for fast tracepoints. */
223 PACKET_FastTracepoints,
224
225 /* Support for static tracepoints. */
226 PACKET_StaticTracepoints,
227
228 /* Support for installing tracepoints while a trace experiment is
229 running. */
230 PACKET_InstallInTrace,
231
232 PACKET_bc,
233 PACKET_bs,
234 PACKET_TracepointSource,
235 PACKET_QAllow,
236 PACKET_qXfer_fdpic,
237 PACKET_QDisableRandomization,
238 PACKET_QAgent,
239 PACKET_QTBuffer_size,
240 PACKET_Qbtrace_off,
241 PACKET_Qbtrace_bts,
242 PACKET_Qbtrace_pt,
243 PACKET_qXfer_btrace,
244
245 /* Support for the QNonStop packet. */
246 PACKET_QNonStop,
247
248 /* Support for the QThreadEvents packet. */
249 PACKET_QThreadEvents,
250
251 /* Support for multi-process extensions. */
252 PACKET_multiprocess_feature,
253
254 /* Support for enabling and disabling tracepoints while a trace
255 experiment is running. */
256 PACKET_EnableDisableTracepoints_feature,
257
258 /* Support for collecting strings using the tracenz bytecode. */
259 PACKET_tracenz_feature,
260
261 /* Support for continuing to run a trace experiment while GDB is
262 disconnected. */
263 PACKET_DisconnectedTracing_feature,
264
265 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
266 PACKET_augmented_libraries_svr4_read_feature,
267
268 /* Support for the qXfer:btrace-conf:read packet. */
269 PACKET_qXfer_btrace_conf,
270
271 /* Support for the Qbtrace-conf:bts:size packet. */
272 PACKET_Qbtrace_conf_bts_size,
273
274 /* Support for swbreak+ feature. */
275 PACKET_swbreak_feature,
276
277 /* Support for hwbreak+ feature. */
278 PACKET_hwbreak_feature,
279
280 /* Support for fork events. */
281 PACKET_fork_event_feature,
282
283 /* Support for vfork events. */
284 PACKET_vfork_event_feature,
285
286 /* Support for the Qbtrace-conf:pt:size packet. */
287 PACKET_Qbtrace_conf_pt_size,
288
289 /* Support for exec events. */
290 PACKET_exec_event_feature,
291
292 /* Support for query supported vCont actions. */
293 PACKET_vContSupported,
294
295 /* Support remote CTRL-C. */
296 PACKET_vCtrlC,
297
298 /* Support TARGET_WAITKIND_NO_RESUMED. */
299 PACKET_no_resumed,
300
301 /* Support for memory tagging, allocation tag fetch/store
302 packets and the tag violation stop replies. */
303 PACKET_memory_tagging_feature,
304
305 PACKET_MAX
306};
307
6b8edb51 308struct threads_listing_context;
3c69da40
PA
309
310/* Stub vCont actions support.
311
312 Each field is a boolean flag indicating whether the stub reports
313 support for the corresponding action. */
314
315struct vCont_action_support
316{
317 /* vCont;t */
318 bool t = false;
319
320 /* vCont;r */
321 bool r = false;
322
323 /* vCont;s */
324 bool s = false;
325
326 /* vCont;S */
327 bool S = false;
328};
329
405feb71 330/* About this many threadids fit in a packet. */
3c69da40
PA
331
332#define MAXTHREADLISTRESULTS 32
333
334/* Data for the vFile:pread readahead cache. */
335
336struct readahead_cache
337{
338 /* Invalidate the readahead cache. */
339 void invalidate ();
340
341 /* Invalidate the readahead cache if it is holding data for FD. */
342 void invalidate_fd (int fd);
343
344 /* Serve pread from the readahead cache. Returns number of bytes
345 read, or 0 if the request can't be served from the cache. */
346 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
347
348 /* The file descriptor for the file that is being cached. -1 if the
349 cache is invalid. */
350 int fd = -1;
351
352 /* The offset into the file that the cache buffer corresponds
353 to. */
354 ULONGEST offset = 0;
355
356 /* The buffer holding the cache contents. */
6b19f38a 357 gdb::byte_vector buf;
3c69da40
PA
358
359 /* Cache hit and miss counters. */
360 ULONGEST hit_count = 0;
361 ULONGEST miss_count = 0;
362};
363
364/* Description of the remote protocol for a given architecture. */
365
366struct packet_reg
367{
368 long offset; /* Offset into G packet. */
369 long regnum; /* GDB's internal register number. */
370 LONGEST pnum; /* Remote protocol register number. */
371 int in_g_packet; /* Always part of G packet. */
372 /* long size in bytes; == register_size (target_gdbarch (), regnum);
373 at present. */
374 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
375 at present. */
376};
377
378struct remote_arch_state
379{
380 explicit remote_arch_state (struct gdbarch *gdbarch);
381
382 /* Description of the remote protocol registers. */
383 long sizeof_g_packet;
384
385 /* Description of the remote protocol registers indexed by REGNUM
386 (making an array gdbarch_num_regs in size). */
387 std::unique_ptr<packet_reg[]> regs;
388
389 /* This is the size (in chars) of the first response to the ``g''
390 packet. It is used as a heuristic when determining the maximum
391 size of memory-read and memory-write packets. A target will
392 typically only reserve a buffer large enough to hold the ``g''
393 packet. The size does not include packet overhead (headers and
394 trailers). */
395 long actual_register_packet_size;
396
397 /* This is the maximum size (in chars) of a non read/write packet.
398 It is also used as a cap on the size of read/write packets. */
399 long remote_packet_size;
400};
401
402/* Description of the remote protocol state for the currently
403 connected target. This is per-target state, and independent of the
404 selected architecture. */
405
406class remote_state
407{
408public:
409
410 remote_state ();
411 ~remote_state ();
412
413 /* Get the remote arch state for GDBARCH. */
414 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
415
416public: /* data */
417
418 /* A buffer to use for incoming packets, and its current size. The
419 buffer is grown dynamically for larger incoming packets.
420 Outgoing packets may also be constructed in this buffer.
8d64371b 421 The size of the buffer is always at least REMOTE_PACKET_SIZE;
3c69da40
PA
422 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
423 packets. */
8d64371b 424 gdb::char_vector buf;
3c69da40
PA
425
426 /* True if we're going through initial connection setup (finding out
427 about the remote side's threads, relocating symbols, etc.). */
428 bool starting_up = false;
429
430 /* If we negotiated packet size explicitly (and thus can bypass
431 heuristics for the largest packet size that will not overflow
432 a buffer in the stub), this will be set to that packet size.
433 Otherwise zero, meaning to use the guessed size. */
434 long explicit_packet_size = 0;
435
3c69da40
PA
436 /* True, if in no ack mode. That is, neither GDB nor the stub will
437 expect acks from each other. The connection is assumed to be
438 reliable. */
439 bool noack_mode = false;
440
441 /* True if we're connected in extended remote mode. */
442 bool extended = false;
443
444 /* True if we resumed the target and we're waiting for the target to
445 stop. In the mean time, we can't start another command/query.
446 The remote server wouldn't be ready to process it, so we'd
447 timeout waiting for a reply that would never come and eventually
448 we'd close the connection. This can happen in asynchronous mode
449 because we allow GDB commands while the target is running. */
450 bool waiting_for_stop_reply = false;
451
452 /* The status of the stub support for the various vCont actions. */
453 vCont_action_support supports_vCont;
454
455 /* True if the user has pressed Ctrl-C, but the target hasn't
456 responded to that. */
457 bool ctrlc_pending_p = false;
458
459 /* True if we saw a Ctrl-C while reading or writing from/to the
460 remote descriptor. At that point it is not safe to send a remote
461 interrupt packet, so we instead remember we saw the Ctrl-C and
462 process it once we're done with sending/receiving the current
463 packet, which should be shortly. If however that takes too long,
464 and the user presses Ctrl-C again, we offer to disconnect. */
465 bool got_ctrlc_during_io = false;
466
467 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
468 remote_open knows that we don't have a file open when the program
469 starts. */
470 struct serial *remote_desc = nullptr;
471
472 /* These are the threads which we last sent to the remote system. The
473 TID member will be -1 for all or -2 for not sent yet. */
474 ptid_t general_thread = null_ptid;
475 ptid_t continue_thread = null_ptid;
476
477 /* This is the traceframe which we last selected on the remote system.
478 It will be -1 if no traceframe is selected. */
479 int remote_traceframe_number = -1;
480
481 char *last_pass_packet = nullptr;
482
483 /* The last QProgramSignals packet sent to the target. We bypass
484 sending a new program signals list down to the target if the new
485 packet is exactly the same as the last we sent. IOW, we only let
486 the target know about program signals list changes. */
487 char *last_program_signals_packet = nullptr;
488
489 gdb_signal last_sent_signal = GDB_SIGNAL_0;
490
491 bool last_sent_step = false;
492
493 /* The execution direction of the last resume we got. */
494 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
495
496 char *finished_object = nullptr;
497 char *finished_annex = nullptr;
498 ULONGEST finished_offset = 0;
499
500 /* Should we try the 'ThreadInfo' query packet?
501
502 This variable (NOT available to the user: auto-detect only!)
503 determines whether GDB will use the new, simpler "ThreadInfo"
504 query or the older, more complex syntax for thread queries.
505 This is an auto-detect variable (set to true at each connect,
506 and set to false when the target fails to recognize it). */
507 bool use_threadinfo_query = false;
508 bool use_threadextra_query = false;
509
510 threadref echo_nextthread {};
511 threadref nextthread {};
512 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
513
514 /* The state of remote notification. */
515 struct remote_notif_state *notif_state = nullptr;
516
517 /* The branch trace configuration. */
518 struct btrace_config btrace_config {};
519
520 /* The argument to the last "vFile:setfs:" packet we sent, used
521 to avoid sending repeated unnecessary "vFile:setfs:" packets.
522 Initialized to -1 to indicate that no "vFile:setfs:" packet
523 has yet been sent. */
524 int fs_pid = -1;
525
526 /* A readahead cache for vFile:pread. Often, reading a binary
527 involves a sequence of small reads. E.g., when parsing an ELF
528 file. A readahead cache helps mostly the case of remote
529 debugging on a connection with higher latency, due to the
530 request/reply nature of the RSP. We only cache data for a single
531 file descriptor at a time. */
532 struct readahead_cache readahead_cache;
533
534 /* The list of already fetched and acknowledged stop events. This
535 queue is used for notification Stop, and other notifications
536 don't need queue for their events, because the notification
537 events of Stop can't be consumed immediately, so that events
538 should be queued first, and be consumed by remote_wait_{ns,as}
539 one per time. Other notifications can consume their events
540 immediately, so queue is not needed for them. */
953edf2b 541 std::vector<stop_reply_up> stop_reply_queue;
3c69da40
PA
542
543 /* Asynchronous signal handle registered as event loop source for
544 when we have pending events ready to be passed to the core. */
545 struct async_event_handler *remote_async_inferior_event_token = nullptr;
546
547 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
548 ``forever'' still use the normal timeout mechanism. This is
549 currently used by the ASYNC code to guarentee that target reads
550 during the initial connect always time-out. Once getpkt has been
551 modified to return a timeout indication and, in turn
552 remote_wait()/wait_for_inferior() have gained a timeout parameter
553 this can go away. */
554 int wait_forever_enabled_p = 1;
555
556private:
557 /* Mapping of remote protocol data for each gdbarch. Usually there
558 is only one entry here, though we may see more with stubs that
559 support multi-process. */
560 std::unordered_map<struct gdbarch *, remote_arch_state>
561 m_arch_states;
562};
6b8edb51 563
d9f719f1
PA
564static const target_info remote_target_info = {
565 "remote",
ae9adb36 566 N_("Remote target using gdb-specific protocol"),
d9f719f1
PA
567 remote_doc
568};
569
ff52c073
CS
570/* Description of a remote packet. */
571
572struct packet_description
573{
574 /* Name of the packet used for gdb output. */
575 const char *name;
576
577 /* Title of the packet, used by the set/show remote name-packet
578 commands to identify the individual packages and gdb output. */
579 const char *title;
580};
581
582/* Configuration of a remote packet. */
583
584struct packet_config
585{
586 /* If auto, GDB auto-detects support for this packet or feature,
587 either through qSupported, or by trying the packet and looking
588 at the response. If true, GDB assumes the target supports this
589 packet. If false, the packet is disabled. Configs that don't
590 have an associated command always have this set to auto. */
591 enum auto_boolean detect;
592
593 /* Does the target support this packet? */
594 enum packet_support support;
595};
596
fe4c3ca0
CS
597/* User configurable variables for the number of characters in a
598 memory read/write packet. MIN (rsa->remote_packet_size,
599 rsa->sizeof_g_packet) is the default. Some targets need smaller
600 values (fifo overruns, et.al.) and some users need larger values
601 (speed up transfers). The variables ``preferred_*'' (the user
602 request), ``current_*'' (what was actually set) and ``forced_*''
603 (Positive - a soft limit, negative - a hard limit). */
604
605struct memory_packet_config
606{
607 const char *name;
608 long size;
609 int fixed_p;
610};
611
612/* These global variables contain the default configuration for every new
613 remote_feature object. */
614static memory_packet_config memory_read_packet_config =
615{
616 "memory-read-packet-size",
617};
618static memory_packet_config memory_write_packet_config =
619{
620 "memory-write-packet-size",
621};
622
ff52c073
CS
623/* This global array contains packet descriptions (name and title). */
624static packet_description packets_descriptions[PACKET_MAX];
625/* This global array contains the default configuration for every new
626 per-remote target array. */
627static packet_config remote_protocol_packets[PACKET_MAX];
628
629/* Description of a remote target's features. It stores the configuration
630 and provides functions to determine supported features of the target. */
631
632struct remote_features
633{
634 remote_features ()
635 {
fe4c3ca0
CS
636 m_memory_read_packet_config = memory_read_packet_config;
637 m_memory_write_packet_config = memory_write_packet_config;
638
ff52c073
CS
639 std::copy (std::begin (remote_protocol_packets),
640 std::end (remote_protocol_packets),
641 std::begin (m_protocol_packets));
642 }
643 ~remote_features () = default;
644
645 DISABLE_COPY_AND_ASSIGN (remote_features);
646
647 /* Returns whether a given packet defined by its enum value is supported. */
648 enum packet_support packet_support (int) const;
649
650 /* Returns the packet's corresponding "set remote foo-packet" command
651 state. See struct packet_config for more details. */
652 enum auto_boolean packet_set_cmd_state (int packet) const
653 { return m_protocol_packets[packet].detect; }
654
655 /* Returns true if the multi-process extensions are in effect. */
656 int remote_multi_process_p () const
657 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
658
659 /* Returns true if fork events are supported. */
660 int remote_fork_event_p () const
661 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
662
663 /* Returns true if vfork events are supported. */
664 int remote_vfork_event_p () const
665 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
666
667 /* Returns true if exec events are supported. */
668 int remote_exec_event_p () const
669 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
670
671 /* Returns true if memory tagging is supported, false otherwise. */
672 bool remote_memory_tagging_p () const
673 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
674
675 /* Reset all packets back to "unknown support". Called when opening a
676 new connection to a remote target. */
677 void reset_all_packet_configs_support ();
678
679/* Check result value in BUF for packet WHICH_PACKET and update the packet's
680 support configuration accordingly. */
681 packet_result packet_ok (const char *buf, const int which_packet);
682 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
683
fe4c3ca0
CS
684 /* Configuration of a remote target's memory read packet. */
685 memory_packet_config m_memory_read_packet_config;
686 /* Configuration of a remote target's memory write packet. */
687 memory_packet_config m_memory_write_packet_config;
688
ff52c073
CS
689 /* The per-remote target array which stores a remote's packet
690 configurations. */
691 packet_config m_protocol_packets[PACKET_MAX];
692};
693
3b3dac9b 694class remote_target : public process_stratum_target
f6ac5f3d
PA
695{
696public:
3b3dac9b 697 remote_target () = default;
6b8edb51 698 ~remote_target () override;
f6ac5f3d 699
d9f719f1
PA
700 const target_info &info () const override
701 { return remote_target_info; }
f6ac5f3d 702
121b3efd
PA
703 const char *connection_string () override;
704
f6ac5f3d
PA
705 thread_control_capabilities get_thread_control_capabilities () override
706 { return tc_schedlock; }
707
d9f719f1
PA
708 /* Open a remote connection. */
709 static void open (const char *, int);
710
f6ac5f3d
PA
711 void close () override;
712
713 void detach (inferior *, int) override;
714 void disconnect (const char *, int) override;
715
1192f124 716 void commit_resumed () override;
f6ac5f3d 717 void resume (ptid_t, int, enum gdb_signal) override;
b60cea74 718 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
b4b1a226 719 bool has_pending_events () override;
f6ac5f3d
PA
720
721 void fetch_registers (struct regcache *, int) override;
722 void store_registers (struct regcache *, int) override;
723 void prepare_to_store (struct regcache *) override;
724
f6ac5f3d
PA
725 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
726
727 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
728 enum remove_bp_reason) override;
729
730
57810aa7
PA
731 bool stopped_by_sw_breakpoint () override;
732 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 733
57810aa7 734 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 735
57810aa7 736 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 737
57810aa7 738 bool stopped_by_watchpoint () override;
f6ac5f3d 739
57810aa7 740 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 741
57810aa7 742 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
743
744 int can_use_hw_breakpoint (enum bptype, int, int) override;
745
746 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
747
748 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
749
750 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
751
752 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
753 struct expression *) override;
754
755 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
756 struct expression *) override;
757
758 void kill () override;
759
760 void load (const char *, int) override;
761
762 void mourn_inferior () override;
763
adc6a863 764 void pass_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d
PA
765
766 int set_syscall_catchpoint (int, bool, int,
767 gdb::array_view<const int>) override;
768
adc6a863 769 void program_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d 770
57810aa7 771 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
772
773 const char *thread_name (struct thread_info *) override;
774
775 void update_thread_list () override;
776
a068643d 777 std::string pid_to_str (ptid_t) override;
f6ac5f3d
PA
778
779 const char *extra_thread_info (struct thread_info *) override;
780
c80e29db 781 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
f6ac5f3d
PA
782
783 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
784 int handle_len,
785 inferior *inf) override;
786
3d6c6204
KB
787 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
788 override;
789
f6ac5f3d
PA
790 void stop (ptid_t) override;
791
792 void interrupt () override;
793
794 void pass_ctrlc () override;
795
796 enum target_xfer_status xfer_partial (enum target_object object,
797 const char *annex,
798 gdb_byte *readbuf,
799 const gdb_byte *writebuf,
800 ULONGEST offset, ULONGEST len,
801 ULONGEST *xfered_len) override;
802
803 ULONGEST get_memory_xfer_limit () override;
804
805 void rcmd (const char *command, struct ui_file *output) override;
806
0e90c441 807 const char *pid_to_exec_file (int pid) override;
f6ac5f3d
PA
808
809 void log_command (const char *cmd) override
810 {
811 serial_log_command (this, cmd);
812 }
813
814 CORE_ADDR get_thread_local_address (ptid_t ptid,
815 CORE_ADDR load_module_addr,
816 CORE_ADDR offset) override;
817
57810aa7 818 bool can_execute_reverse () override;
f6ac5f3d
PA
819
820 std::vector<mem_region> memory_map () override;
821
822 void flash_erase (ULONGEST address, LONGEST length) override;
823
824 void flash_done () override;
825
826 const struct target_desc *read_description () override;
827
828 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
829 const gdb_byte *pattern, ULONGEST pattern_len,
830 CORE_ADDR *found_addrp) override;
831
57810aa7 832 bool can_async_p () override;
f6ac5f3d 833
57810aa7 834 bool is_async_p () override;
f6ac5f3d 835
4a570176 836 void async (bool) override;
f6ac5f3d 837
5b6d1e4f
PA
838 int async_wait_fd () override;
839
f6ac5f3d
PA
840 void thread_events (int) override;
841
842 int can_do_single_step () override;
843
844 void terminal_inferior () override;
845
846 void terminal_ours () override;
847
57810aa7 848 bool supports_non_stop () override;
f6ac5f3d 849
57810aa7 850 bool supports_multi_process () override;
f6ac5f3d 851
57810aa7 852 bool supports_disable_randomization () override;
f6ac5f3d 853
57810aa7 854 bool filesystem_is_local () override;
f6ac5f3d
PA
855
856
857 int fileio_open (struct inferior *inf, const char *filename,
858 int flags, int mode, int warn_if_slow,
b872057a 859 fileio_error *target_errno) override;
f6ac5f3d
PA
860
861 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 862 ULONGEST offset, fileio_error *target_errno) override;
f6ac5f3d
PA
863
864 int fileio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 865 ULONGEST offset, fileio_error *target_errno) override;
f6ac5f3d 866
b872057a 867 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
f6ac5f3d 868
b872057a 869 int fileio_close (int fd, fileio_error *target_errno) override;
f6ac5f3d
PA
870
871 int fileio_unlink (struct inferior *inf,
872 const char *filename,
b872057a 873 fileio_error *target_errno) override;
f6ac5f3d
PA
874
875 gdb::optional<std::string>
876 fileio_readlink (struct inferior *inf,
877 const char *filename,
b872057a 878 fileio_error *target_errno) override;
f6ac5f3d 879
57810aa7 880 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 881
57810aa7 882 bool supports_string_tracing () override;
f6ac5f3d 883
ff52c073
CS
884 int remote_supports_cond_tracepoints ();
885
57810aa7 886 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 887
ff52c073
CS
888 int remote_supports_fast_tracepoints ();
889
890 int remote_supports_static_tracepoints ();
891
892 int remote_supports_install_in_trace ();
893
57810aa7 894 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
895
896 void trace_init () override;
897
898 void download_tracepoint (struct bp_location *location) override;
899
57810aa7 900 bool can_download_tracepoint () override;
f6ac5f3d
PA
901
902 void download_trace_state_variable (const trace_state_variable &tsv) override;
903
904 void enable_tracepoint (struct bp_location *location) override;
905
906 void disable_tracepoint (struct bp_location *location) override;
907
908 void trace_set_readonly_regions () override;
909
910 void trace_start () override;
911
912 int get_trace_status (struct trace_status *ts) override;
913
914 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
915 override;
916
917 void trace_stop () override;
918
919 int trace_find (enum trace_find_type type, int num,
920 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
921
57810aa7 922 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
923
924 int save_trace_data (const char *filename) override;
925
926 int upload_tracepoints (struct uploaded_tp **utpp) override;
927
928 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
929
930 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
931
932 int get_min_fast_tracepoint_insn_len () override;
933
934 void set_disconnected_tracing (int val) override;
935
936 void set_circular_trace_buffer (int val) override;
937
938 void set_trace_buffer_size (LONGEST val) override;
939
57810aa7
PA
940 bool set_trace_notes (const char *user, const char *notes,
941 const char *stopnotes) override;
f6ac5f3d
PA
942
943 int core_of_thread (ptid_t ptid) override;
944
945 int verify_memory (const gdb_byte *data,
946 CORE_ADDR memaddr, ULONGEST size) override;
947
948
57810aa7 949 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
950
951 void set_permissions () override;
952
953 bool static_tracepoint_marker_at (CORE_ADDR,
954 struct static_tracepoint_marker *marker)
955 override;
956
957 std::vector<static_tracepoint_marker>
958 static_tracepoint_markers_by_strid (const char *id) override;
959
960 traceframe_info_up traceframe_info () override;
961
57810aa7
PA
962 bool use_agent (bool use) override;
963 bool can_use_agent () override;
f6ac5f3d 964
696c0d5e
MM
965 struct btrace_target_info *
966 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
f6ac5f3d
PA
967
968 void disable_btrace (struct btrace_target_info *tinfo) override;
969
970 void teardown_btrace (struct btrace_target_info *tinfo) override;
971
972 enum btrace_error read_btrace (struct btrace_data *data,
973 struct btrace_target_info *btinfo,
974 enum btrace_read_type type) override;
975
976 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 977 bool augmented_libraries_svr4_read () override;
82d1f134 978 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
294c36eb 979 void follow_exec (inferior *, ptid_t, const char *) override;
f6ac5f3d
PA
980 int insert_fork_catchpoint (int) override;
981 int remove_fork_catchpoint (int) override;
982 int insert_vfork_catchpoint (int) override;
983 int remove_vfork_catchpoint (int) override;
984 int insert_exec_catchpoint (int) override;
985 int remove_exec_catchpoint (int) override;
986 enum exec_direction_kind execution_direction () override;
987
dbe692af
LM
988 bool supports_memory_tagging () override;
989
990 bool fetch_memtags (CORE_ADDR address, size_t len,
991 gdb::byte_vector &tags, int type) override;
992
993 bool store_memtags (CORE_ADDR address, size_t len,
994 const gdb::byte_vector &tags, int type) override;
995
6b8edb51
PA
996public: /* Remote specific methods. */
997
998 void remote_download_command_source (int num, ULONGEST addr,
999 struct command_line *cmds);
1000
1001 void remote_file_put (const char *local_file, const char *remote_file,
1002 int from_tty);
1003 void remote_file_get (const char *remote_file, const char *local_file,
1004 int from_tty);
1005 void remote_file_delete (const char *remote_file, int from_tty);
1006
1007 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 1008 ULONGEST offset, fileio_error *remote_errno);
6b8edb51 1009 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 1010 ULONGEST offset, fileio_error *remote_errno);
6b8edb51 1011 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
b872057a 1012 ULONGEST offset, fileio_error *remote_errno);
6b8edb51
PA
1013
1014 int remote_hostio_send_command (int command_bytes, int which_packet,
b872057a 1015 fileio_error *remote_errno, const char **attachment,
6b8edb51
PA
1016 int *attachment_len);
1017 int remote_hostio_set_filesystem (struct inferior *inf,
b872057a 1018 fileio_error *remote_errno);
6b8edb51
PA
1019 /* We should get rid of this and use fileio_open directly. */
1020 int remote_hostio_open (struct inferior *inf, const char *filename,
1021 int flags, int mode, int warn_if_slow,
b872057a
SM
1022 fileio_error *remote_errno);
1023 int remote_hostio_close (int fd, fileio_error *remote_errno);
6b8edb51
PA
1024
1025 int remote_hostio_unlink (inferior *inf, const char *filename,
b872057a 1026 fileio_error *remote_errno);
6b8edb51
PA
1027
1028 struct remote_state *get_remote_state ();
1029
1030 long get_remote_packet_size (void);
1031 long get_memory_packet_size (struct memory_packet_config *config);
1032
1033 long get_memory_write_packet_size ();
1034 long get_memory_read_packet_size ();
1035
1036 char *append_pending_thread_resumptions (char *p, char *endp,
1037 ptid_t ptid);
d9f719f1 1038 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d 1039 void start_remote (int from_tty, int extended_p);
00431a78 1040 void remote_detach_1 (struct inferior *inf, int from_tty);
6b8edb51
PA
1041
1042 char *append_resumption (char *p, char *endp,
1043 ptid_t ptid, int step, gdb_signal siggnal);
d51926f0 1044 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
6b8edb51
PA
1045 gdb_signal siggnal);
1046
64d38fdd 1047 thread_info *add_current_inferior_and_thread (const char *wait_status);
6b8edb51
PA
1048
1049 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
b60cea74 1050 target_wait_flags options);
6b8edb51 1051 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
b60cea74 1052 target_wait_flags options);
6b8edb51
PA
1053
1054 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1055 target_waitstatus *status);
1056
8f66807b 1057 ptid_t select_thread_for_ambiguous_stop_reply
c272a98c 1058 (const struct target_waitstatus &status);
8f66807b 1059
8a82de58 1060 void remote_notice_new_inferior (ptid_t currthread, bool executing);
6b8edb51 1061
1edb66d8 1062 void print_one_stopped_thread (thread_info *thread);
6b8edb51
PA
1063 void process_initial_stop_replies (int from_tty);
1064
b622494e
AB
1065 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1066 bool silent_p);
6b8edb51
PA
1067
1068 void btrace_sync_conf (const btrace_config *conf);
1069
1070 void remote_btrace_maybe_reopen ();
1071
1072 void remove_new_fork_children (threads_listing_context *context);
28561a65 1073 void kill_new_fork_children (inferior *inf);
6b8edb51
PA
1074 void discard_pending_stop_replies (struct inferior *inf);
1075 int stop_reply_queue_length ();
1076
1077 void check_pending_events_prevent_wildcard_vcont
2f63ec5c 1078 (bool *may_global_wildcard_vcont);
6b8edb51
PA
1079
1080 void discard_pending_stop_replies_in_queue ();
1081 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1082 struct stop_reply *queued_stop_reply (ptid_t ptid);
1083 int peek_stop_reply (ptid_t ptid);
bb277751 1084 void remote_parse_stop_reply (const char *buf, stop_reply *event);
6b8edb51
PA
1085
1086 void remote_stop_ns (ptid_t ptid);
1087 void remote_interrupt_as ();
1088 void remote_interrupt_ns ();
1089
1090 char *remote_get_noisy_reply ();
1091 int remote_query_attached (int pid);
9ab8741a 1092 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51
PA
1093 int try_open_exec);
1094
1095 ptid_t remote_current_thread (ptid_t oldpid);
e3b2741b 1096 ptid_t get_current_thread (const char *wait_status);
6b8edb51
PA
1097
1098 void set_thread (ptid_t ptid, int gen);
1099 void set_general_thread (ptid_t ptid);
1100 void set_continue_thread (ptid_t ptid);
1101 void set_general_process ();
1102
1103 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1104
cecb1912 1105 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
6b8edb51
PA
1106 gdb_ext_thread_info *info);
1107 int remote_get_threadinfo (threadref *threadid, int fieldset,
1108 gdb_ext_thread_info *info);
1109
cecb1912 1110 int parse_threadlist_response (const char *pkt, int result_limit,
6b8edb51
PA
1111 threadref *original_echo,
1112 threadref *resultlist,
1113 int *doneflag);
1114 int remote_get_threadlist (int startflag, threadref *nextthread,
1115 int result_limit, int *done, int *result_count,
1116 threadref *threadlist);
1117
1118 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1119 void *context, int looplimit);
1120
1121 int remote_get_threads_with_ql (threads_listing_context *context);
1122 int remote_get_threads_with_qxfer (threads_listing_context *context);
1123 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1124
1125 void extended_remote_restart ();
1126
1127 void get_offsets ();
1128
1129 void remote_check_symbols ();
1130
1131 void remote_supported_packet (const struct protocol_feature *feature,
1132 enum packet_support support,
1133 const char *argument);
1134
1135 void remote_query_supported ();
1136
1137 void remote_packet_size (const protocol_feature *feature,
1138 packet_support support, const char *value);
1139
1140 void remote_serial_quit_handler ();
1141
1142 void remote_detach_pid (int pid);
1143
1144 void remote_vcont_probe ();
1145
1146 void remote_resume_with_hc (ptid_t ptid, int step,
1147 gdb_signal siggnal);
1148
1149 void send_interrupt_sequence ();
1150 void interrupt_query ();
1151
42938c1a 1152 void remote_notif_get_pending_events (const notif_client *nc);
6b8edb51
PA
1153
1154 int fetch_register_using_p (struct regcache *regcache,
1155 packet_reg *reg);
1156 int send_g_packet ();
1157 void process_g_packet (struct regcache *regcache);
1158 void fetch_registers_using_g (struct regcache *regcache);
1159 int store_register_using_P (const struct regcache *regcache,
1160 packet_reg *reg);
1161 void store_registers_using_G (const struct regcache *regcache);
1162
1163 void set_remote_traceframe ();
1164
1165 void check_binary_download (CORE_ADDR addr);
1166
1167 target_xfer_status remote_write_bytes_aux (const char *header,
1168 CORE_ADDR memaddr,
1169 const gdb_byte *myaddr,
1170 ULONGEST len_units,
1171 int unit_size,
1172 ULONGEST *xfered_len_units,
1173 char packet_format,
1174 int use_length);
1175
1176 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1177 const gdb_byte *myaddr, ULONGEST len,
1178 int unit_size, ULONGEST *xfered_len);
1179
1180 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1181 ULONGEST len_units,
1182 int unit_size, ULONGEST *xfered_len_units);
1183
1184 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1185 ULONGEST memaddr,
1186 ULONGEST len,
1187 int unit_size,
1188 ULONGEST *xfered_len);
1189
1190 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1191 gdb_byte *myaddr, ULONGEST len,
1192 int unit_size,
1193 ULONGEST *xfered_len);
1194
1195 packet_result remote_send_printf (const char *format, ...)
1196 ATTRIBUTE_PRINTF (2, 3);
1197
1198 target_xfer_status remote_flash_write (ULONGEST address,
1199 ULONGEST length, ULONGEST *xfered_len,
1200 const gdb_byte *data);
1201
1202 int readchar (int timeout);
1203
1204 void remote_serial_write (const char *str, int len);
1205
1206 int putpkt (const char *buf);
1207 int putpkt_binary (const char *buf, int cnt);
1208
8d64371b
TT
1209 int putpkt (const gdb::char_vector &buf)
1210 {
1211 return putpkt (buf.data ());
1212 }
1213
6b8edb51 1214 void skip_frame ();
8d64371b
TT
1215 long read_frame (gdb::char_vector *buf_p);
1216 void getpkt (gdb::char_vector *buf, int forever);
1217 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
6b8edb51 1218 int expecting_notif, int *is_notif);
8d64371b
TT
1219 int getpkt_sane (gdb::char_vector *buf, int forever);
1220 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
6b8edb51
PA
1221 int *is_notif);
1222 int remote_vkill (int pid);
1223 void remote_kill_k ();
1224
1225 void extended_remote_disable_randomization (int val);
1226 int extended_remote_run (const std::string &args);
1227
1228 void send_environment_packet (const char *action,
1229 const char *packet,
1230 const char *value);
1231
1232 void extended_remote_environment_support ();
3c69da40 1233 void extended_remote_set_inferior_cwd ();
80152258 1234
3c69da40
PA
1235 target_xfer_status remote_write_qxfer (const char *object_name,
1236 const char *annex,
1237 const gdb_byte *writebuf,
1238 ULONGEST offset, LONGEST len,
1239 ULONGEST *xfered_len,
ff52c073 1240 const unsigned int which_packet);
43c3a0e4 1241
3c69da40
PA
1242 target_xfer_status remote_read_qxfer (const char *object_name,
1243 const char *annex,
1244 gdb_byte *readbuf, ULONGEST offset,
1245 LONGEST len,
1246 ULONGEST *xfered_len,
ff52c073 1247 const unsigned int which_packet);
43c3a0e4 1248
3c69da40 1249 void push_stop_reply (struct stop_reply *new_event);
43c3a0e4 1250
3c69da40 1251 bool vcont_r_supported ();
43c3a0e4 1252
ff52c073
CS
1253 remote_features m_features;
1254
288712bb
AB
1255private:
1256
1257 bool start_remote_1 (int from_tty, int extended_p);
43c3a0e4 1258
3c69da40
PA
1259 /* The remote state. Don't reference this directly. Use the
1260 get_remote_state method instead. */
1261 remote_state m_remote_state;
43c3a0e4
PA
1262};
1263
3c69da40
PA
1264static const target_info extended_remote_target_info = {
1265 "extended-remote",
ae9adb36 1266 N_("Extended remote target using gdb-specific protocol"),
3c69da40
PA
1267 remote_doc
1268};
ea9c271d 1269
3c69da40
PA
1270/* Set up the extended remote target by extending the standard remote
1271 target and adding to it. */
1272
1273class extended_remote_target final : public remote_target
ea9c271d 1274{
9d6eea31 1275public:
3c69da40
PA
1276 const target_info &info () const override
1277 { return extended_remote_target_info; }
9d6eea31 1278
3c69da40
PA
1279 /* Open an extended-remote connection. */
1280 static void open (const char *, int);
de44f5a7 1281
3c69da40
PA
1282 bool can_create_inferior () override { return true; }
1283 void create_inferior (const char *, const std::string &,
1284 char **, int) override;
9d6eea31 1285
3c69da40 1286 void detach (inferior *, int) override;
9d6eea31 1287
3c69da40
PA
1288 bool can_attach () override { return true; }
1289 void attach (const char *, int) override;
be2a5f71 1290
3c69da40
PA
1291 void post_attach (int) override;
1292 bool supports_disable_randomization () override;
1293};
1e51243a 1294
a4543480
SM
1295struct stop_reply : public notif_event
1296{
1297 ~stop_reply ();
1298
1299 /* The identifier of the thread about this event */
1300 ptid_t ptid;
1301
1302 /* The remote state this event is associated with. When the remote
1303 connection, represented by a remote_state object, is closed,
1304 all the associated stop_reply events should be released. */
1305 struct remote_state *rs;
1306
1307 struct target_waitstatus ws;
1308
1309 /* The architecture associated with the expedited registers. */
1310 gdbarch *arch;
1311
1312 /* Expedited registers. This makes remote debugging a bit more
1313 efficient for those targets that provide critical registers as
1314 part of their normal status mechanism (as another roundtrip to
1315 fetch them is avoided). */
1316 std::vector<cached_reg_t> regcache;
1317
1318 enum target_stop_reason stop_reason;
1319
1320 CORE_ADDR watch_data_address;
1321
1322 int core;
1323};
1324
06c7226e
SM
1325/* Return TARGET as a remote_target if it is one, else nullptr. */
1326
1327static remote_target *
1328as_remote_target (process_stratum_target *target)
1329{
1330 return dynamic_cast<remote_target *> (target);
1331}
1332
24b2de7b
AB
1333/* See remote.h. */
1334
1335bool
1336is_remote_target (process_stratum_target *target)
1337{
06c7226e 1338 return as_remote_target (target) != nullptr;
24b2de7b
AB
1339}
1340
3c69da40 1341/* Per-program-space data key. */
08b8a139 1342static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
7b4a314f 1343 remote_pspace_data;
2d717e4f 1344
3c69da40
PA
1345/* The variable registered as the control variable used by the
1346 remote exec-file commands. While the remote exec-file setting is
1347 per-program-space, the set/show machinery uses this as the
1348 location of the remote exec-file value. */
e0700ba4 1349static std::string remote_exec_file_var;
a6f3e723 1350
3c69da40
PA
1351/* The size to align memory write packets, when practical. The protocol
1352 does not guarantee any alignment, and gdb will generate short
1353 writes and unaligned writes, but even as a best-effort attempt this
1354 can improve bulk transfers. For instance, if a write is misaligned
1355 relative to the target's data bus, the stub may need to make an extra
1356 round trip fetching data from the target. This doesn't make a
1357 huge difference, but it's easy to do, so we try to be helpful.
82f73884 1358
3c69da40
PA
1359 The alignment chosen is arbitrary; usually data bus width is
1360 important here, not the possibly larger cache line size. */
1361enum { REMOTE_ALIGN_WRITES = 16 };
82f73884 1362
3c69da40 1363/* Prototypes for local functions. */
74531fed 1364
3c69da40 1365static int hexnumlen (ULONGEST num);
782b2b07 1366
3c69da40 1367static int stubhex (int ch);
5d93a237 1368
3c69da40 1369static int hexnumstr (char *, ULONGEST);
048094ac 1370
3c69da40 1371static int hexnumnstr (char *, ULONGEST, int);
47f8a51d 1372
3c69da40 1373static CORE_ADDR remote_address_masked (CORE_ADDR);
262e1174 1374
cecb1912 1375static int stub_unpack_int (const char *buff, int fieldlength);
5e4a05c4 1376
ff52c073
CS
1377static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1378 cmd_list_element *c);
1379
1380static void show_packet_config_cmd (ui_file *file,
1381 const unsigned int which_packet,
1382 remote_target *remote);
b73be471 1383
3c69da40
PA
1384static void show_remote_protocol_packet_cmd (struct ui_file *file,
1385 int from_tty,
1386 struct cmd_list_element *c,
1387 const char *value);
8e88304f 1388
3c69da40 1389static ptid_t read_ptid (const char *buf, const char **obuf);
3a00c802 1390
3c69da40 1391static void remote_async_inferior_event_handler (gdb_client_data);
b80fafe3 1392
eefce37f 1393static bool remote_read_description_p (struct target_ops *target);
88b496c3 1394
05be00a8 1395static void remote_console_output (const char *msg);
5965e028 1396
3c69da40 1397static void remote_btrace_reset (remote_state *rs);
f4abbc16 1398
5b6d1e4f 1399static void remote_unpush_and_throw (remote_target *target);
15a201c8 1400
3c69da40 1401/* For "remote". */
80152258 1402
3c69da40 1403static struct cmd_list_element *remote_cmdlist;
9d6eea31 1404
3c69da40 1405/* For "set remote" and "show remote". */
6b8edb51 1406
3c69da40
PA
1407static struct cmd_list_element *remote_set_cmdlist;
1408static struct cmd_list_element *remote_show_cmdlist;
6b8edb51 1409
3c69da40 1410/* Controls whether GDB is willing to use range stepping. */
6b8edb51 1411
491144b5 1412static bool use_range_stepping = true;
3c69da40 1413
c9d22089
SM
1414/* From the remote target's point of view, each thread is in one of these three
1415 states. */
1416enum class resume_state
1417{
1418 /* Not resumed - we haven't been asked to resume this thread. */
1419 NOT_RESUMED,
1420
1421 /* We have been asked to resume this thread, but haven't sent a vCont action
1422 for it yet. We'll need to consider it next time commit_resume is
1423 called. */
1424 RESUMED_PENDING_VCONT,
1425
1426 /* We have been asked to resume this thread, and we have sent a vCont action
1427 for it. */
1428 RESUMED,
1429};
1430
1431/* Information about a thread's pending vCont-resume. Used when a thread is in
1432 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1433 stores this information which is then picked up by
1434 remote_target::commit_resume to know which is the proper action for this
1435 thread to include in the vCont packet. */
1436struct resumed_pending_vcont_info
1437{
1438 /* True if the last resume call for this thread was a step request, false
1439 if a continue request. */
1440 bool step;
1441
1442 /* The signal specified in the last resume call for this thread. */
1443 gdb_signal sig;
1444};
1445
7aabaf9d
SM
1446/* Private data that we'll store in (struct thread_info)->priv. */
1447struct remote_thread_info : public private_thread_info
dc146f7c 1448{
7aabaf9d
SM
1449 std::string extra;
1450 std::string name;
1451 int core = -1;
799a2abe 1452
f6327dcb
KB
1453 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1454 sequence of bytes. */
7aabaf9d 1455 gdb::byte_vector thread_handle;
f6327dcb 1456
799a2abe 1457 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1458 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1459
1460 /* This is set to the data address of the access causing the target
1461 to stop for a watchpoint. */
7aabaf9d 1462 CORE_ADDR watch_data_address = 0;
85ad3aaf 1463
c9d22089 1464 /* Get the thread's resume state. */
a6c11cbb 1465 enum resume_state get_resume_state () const
c9d22089
SM
1466 {
1467 return m_resume_state;
1468 }
1469
1470 /* Put the thread in the NOT_RESUMED state. */
1471 void set_not_resumed ()
1472 {
1473 m_resume_state = resume_state::NOT_RESUMED;
1474 }
85ad3aaf 1475
c9d22089
SM
1476 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1477 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1478 {
1479 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1480 m_resumed_pending_vcont_info.step = step;
1481 m_resumed_pending_vcont_info.sig = sig;
1482 }
85ad3aaf 1483
c9d22089 1484 /* Get the information this thread's pending vCont-resumption.
85ad3aaf 1485
c9d22089
SM
1486 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1487 state. */
1488 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1489 {
1490 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1491
1492 return m_resumed_pending_vcont_info;
1493 }
1494
1495 /* Put the thread in the VCONT_RESUMED state. */
1496 void set_resumed ()
1497 {
1498 m_resume_state = resume_state::RESUMED;
1499 }
1500
1501private:
1502 /* Resume state for this thread. This is used to implement vCont action
1503 coalescing (only when the target operates in non-stop mode).
1504
1505 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1506 which notes that this thread must be considered in the next commit_resume
1507 call.
1508
1509 remote_target::commit_resume sends a vCont packet with actions for the
1510 threads in the RESUMED_PENDING_VCONT state and moves them to the
1511 VCONT_RESUMED state.
1512
1513 When reporting a stop to the core for a thread, that thread is moved back
1514 to the NOT_RESUMED state. */
1515 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1516
1517 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1518 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
dc146f7c
VP
1519};
1520
de44f5a7 1521remote_state::remote_state ()
8d64371b 1522 : buf (400)
de44f5a7 1523{
de44f5a7
PA
1524}
1525
1526remote_state::~remote_state ()
1527{
1528 xfree (this->last_pass_packet);
1529 xfree (this->last_program_signals_packet);
de44f5a7
PA
1530 xfree (this->finished_object);
1531 xfree (this->finished_annex);
cf792862
TT
1532}
1533
35b1e5cc
SS
1534/* Utility: generate error from an incoming stub packet. */
1535static void
1536trace_error (char *buf)
1537{
1538 if (*buf++ != 'E')
1539 return; /* not an error msg */
1540 switch (*buf)
1541 {
1542 case '1': /* malformed packet error */
1543 if (*++buf == '0') /* general case: */
1544 error (_("remote.c: error in outgoing packet."));
1545 else
1546 error (_("remote.c: error in outgoing packet at field #%ld."),
1547 strtol (buf, NULL, 16));
35b1e5cc
SS
1548 default:
1549 error (_("Target returns error code '%s'."), buf);
1550 }
1551}
1552
1553/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1554
6b8edb51
PA
1555char *
1556remote_target::remote_get_noisy_reply ()
35b1e5cc 1557{
b6bb3468
PA
1558 struct remote_state *rs = get_remote_state ();
1559
35b1e5cc
SS
1560 do /* Loop on reply from remote stub. */
1561 {
1562 char *buf;
a744cf53 1563
0df8b418 1564 QUIT; /* Allow user to bail out with ^C. */
8d64371b
TT
1565 getpkt (&rs->buf, 0);
1566 buf = rs->buf.data ();
ad91cd99 1567 if (buf[0] == 'E')
35b1e5cc 1568 trace_error (buf);
61012eef 1569 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1570 {
1571 ULONGEST ul;
1572 CORE_ADDR from, to, org_to;
256642e8 1573 const char *p, *pp;
dde08ee1 1574 int adjusted_size = 0;
7556d4a4 1575 int relocated = 0;
dde08ee1
PA
1576
1577 p = buf + strlen ("qRelocInsn:");
1578 pp = unpack_varlen_hex (p, &ul);
1579 if (*pp != ';')
cb91c06a 1580 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1581 from = ul;
1582
1583 p = pp + 1;
a9cbf802 1584 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1585 to = ul;
1586
1587 org_to = to;
1588
a70b8144 1589 try
dde08ee1 1590 {
f5656ead 1591 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 1592 relocated = 1;
dde08ee1 1593 }
230d2906 1594 catch (const gdb_exception &ex)
7556d4a4
PA
1595 {
1596 if (ex.error == MEMORY_ERROR)
1597 {
1598 /* Propagate memory errors silently back to the
1599 target. The stub may have limited the range of
1600 addresses we can write to, for example. */
1601 }
1602 else
1603 {
1604 /* Something unexpectedly bad happened. Be verbose
1605 so we can tell what, and propagate the error back
1606 to the stub, so it doesn't get stuck waiting for
1607 a response. */
1608 exception_fprintf (gdb_stderr, ex,
1609 _("warning: relocating instruction: "));
1610 }
1611 putpkt ("E01");
1612 }
1613
1614 if (relocated)
dde08ee1
PA
1615 {
1616 adjusted_size = to - org_to;
1617
8d64371b 1618 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1619 putpkt (buf);
1620 }
dde08ee1 1621 }
ad91cd99 1622 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
1623 remote_console_output (buf + 1); /* 'O' message from stub */
1624 else
0df8b418 1625 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1626 }
1627 while (1);
1628}
3c3bea1c 1629
9d6eea31
PA
1630struct remote_arch_state *
1631remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1632{
43c3a0e4
PA
1633 remote_arch_state *rsa;
1634
1635 auto it = this->m_arch_states.find (gdbarch);
1636 if (it == this->m_arch_states.end ())
9d6eea31 1637 {
43c3a0e4
PA
1638 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1639 std::forward_as_tuple (gdbarch),
1640 std::forward_as_tuple (gdbarch));
1641 rsa = &p.first->second;
9d6eea31
PA
1642
1643 /* Make sure that the packet buffer is plenty big enough for
1644 this architecture. */
8d64371b
TT
1645 if (this->buf.size () < rsa->remote_packet_size)
1646 this->buf.resize (2 * rsa->remote_packet_size);
9d6eea31 1647 }
43c3a0e4
PA
1648 else
1649 rsa = &it->second;
1650
1651 return rsa;
d01949b6
AC
1652}
1653
0b83947e
DJ
1654/* Fetch the global remote target state. */
1655
6b8edb51
PA
1656remote_state *
1657remote_target::get_remote_state ()
0b83947e
DJ
1658{
1659 /* Make sure that the remote architecture state has been
1660 initialized, because doing so might reallocate rs->buf. Any
1661 function which calls getpkt also needs to be mindful of changes
1662 to rs->buf, but this call limits the number of places which run
1663 into trouble. */
3c69da40 1664 m_remote_state.get_remote_arch_state (target_gdbarch ());
0b83947e 1665
3c69da40 1666 return &m_remote_state;
0b83947e
DJ
1667}
1668
94585166
DB
1669/* Fetch the remote exec-file from the current program space. */
1670
1671static const char *
1672get_remote_exec_file (void)
1673{
1674 char *remote_exec_file;
1675
7b4a314f 1676 remote_exec_file = remote_pspace_data.get (current_program_space);
94585166
DB
1677 if (remote_exec_file == NULL)
1678 return "";
1679
1680 return remote_exec_file;
1681}
1682
1683/* Set the remote exec file for PSPACE. */
1684
1685static void
1686set_pspace_remote_exec_file (struct program_space *pspace,
7b4a314f 1687 const char *remote_exec_file)
94585166 1688{
7b4a314f 1689 char *old_file = remote_pspace_data.get (pspace);
94585166
DB
1690
1691 xfree (old_file);
7b4a314f 1692 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
94585166
DB
1693}
1694
1695/* The "set/show remote exec-file" set command hook. */
1696
1697static void
eb4c3f4a 1698set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1699 struct cmd_list_element *c)
1700{
e0700ba4
SM
1701 set_pspace_remote_exec_file (current_program_space,
1702 remote_exec_file_var.c_str ());
94585166
DB
1703}
1704
1705/* The "set/show remote exec-file" show command hook. */
1706
1707static void
1708show_remote_exec_file (struct ui_file *file, int from_tty,
1709 struct cmd_list_element *cmd, const char *value)
1710{
6cb06a8c 1711 gdb_printf (file, "%s\n", get_remote_exec_file ());
94585166
DB
1712}
1713
c21236dc
PA
1714static int
1715map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1716{
74ca34ce 1717 int regnum, num_remote_regs, offset;
74ca34ce 1718 struct packet_reg **remote_regs;
ea9c271d 1719
4a22f64d 1720 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1721 {
c21236dc 1722 struct packet_reg *r = &regs[regnum];
baef701f 1723
4a22f64d 1724 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1725 /* Do not try to fetch zero-sized (placeholder) registers. */
1726 r->pnum = -1;
1727 else
1728 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1729
b323314b 1730 r->regnum = regnum;
74ca34ce
DJ
1731 }
1732
1733 /* Define the g/G packet format as the contents of each register
1734 with a remote protocol number, in order of ascending protocol
1735 number. */
1736
224c3ddb 1737 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1738 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1739 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1740 regnum++)
c21236dc
PA
1741 if (regs[regnum].pnum != -1)
1742 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1743
39ef2f62
CB
1744 std::sort (remote_regs, remote_regs + num_remote_regs,
1745 [] (const packet_reg *a, const packet_reg *b)
1746 { return a->pnum < b->pnum; });
74ca34ce
DJ
1747
1748 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1749 {
1750 remote_regs[regnum]->in_g_packet = 1;
1751 remote_regs[regnum]->offset = offset;
4a22f64d 1752 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1753 }
1754
c21236dc
PA
1755 return offset;
1756}
1757
1758/* Given the architecture described by GDBARCH, return the remote
1759 protocol register's number and the register's offset in the g/G
1760 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1761 If the target does not have a mapping for REGNUM, return false,
1762 otherwise, return true. */
1763
1764int
1765remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1766 int *pnum, int *poffset)
1767{
c21236dc
PA
1768 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1769
b80406ac 1770 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1771
b80406ac 1772 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1773
1774 *pnum = regs[regnum].pnum;
1775 *poffset = regs[regnum].offset;
1776
c21236dc
PA
1777 return *pnum != -1;
1778}
1779
9d6eea31 1780remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1781{
c21236dc
PA
1782 /* Use the architecture to build a regnum<->pnum table, which will be
1783 1:1 unless a feature set specifies otherwise. */
9d6eea31 1784 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1785
74ca34ce
DJ
1786 /* Record the maximum possible size of the g packet - it may turn out
1787 to be smaller. */
9d6eea31
PA
1788 this->sizeof_g_packet
1789 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1790
0df8b418 1791 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1792 remote stubs have a hardwired buffer size of 400 bytes
1793 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1794 as the maximum packet-size to ensure that the packet and an extra
1795 NUL character can always fit in the buffer. This stops GDB
1796 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1797 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1798 this->remote_packet_size = 400 - 1;
d01949b6 1799
ea9c271d 1800 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1801 this->actual_register_packet_size = 0;
ea9c271d
DJ
1802
1803 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1804 default, adjust the size accordingly. Remember that each byte is
1805 encoded as two characters. 32 is the overhead for the packet
1806 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1807 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1808 little. */
9d6eea31
PA
1809 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1810 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1811}
1812
6b8edb51
PA
1813/* Get a pointer to the current remote target. If not connected to a
1814 remote target, return NULL. */
1815
1816static remote_target *
1817get_current_remote_target ()
1818{
5b6d1e4f 1819 target_ops *proc_target = current_inferior ()->process_target ();
6b8edb51
PA
1820 return dynamic_cast<remote_target *> (proc_target);
1821}
1822
ea9c271d
DJ
1823/* Return the current allowed size of a remote packet. This is
1824 inferred from the current architecture, and should be used to
1825 limit the length of outgoing packets. */
6b8edb51
PA
1826long
1827remote_target::get_remote_packet_size ()
ea9c271d 1828{
be2a5f71 1829 struct remote_state *rs = get_remote_state ();
9d6eea31 1830 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1831
be2a5f71
DJ
1832 if (rs->explicit_packet_size)
1833 return rs->explicit_packet_size;
1834
ea9c271d 1835 return rsa->remote_packet_size;
d01949b6
AC
1836}
1837
ad10f812 1838static struct packet_reg *
5cd63fda
PA
1839packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1840 long regnum)
ad10f812 1841{
5cd63fda 1842 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1843 return NULL;
1844 else
ad10f812 1845 {
ea9c271d 1846 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1847
b323314b
AC
1848 gdb_assert (r->regnum == regnum);
1849 return r;
ad10f812 1850 }
ad10f812
AC
1851}
1852
1853static struct packet_reg *
5cd63fda
PA
1854packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1855 LONGEST pnum)
ad10f812 1856{
b323314b 1857 int i;
a744cf53 1858
5cd63fda 1859 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1860 {
ea9c271d 1861 struct packet_reg *r = &rsa->regs[i];
a744cf53 1862
b323314b
AC
1863 if (r->pnum == pnum)
1864 return r;
ad10f812
AC
1865 }
1866 return NULL;
d01949b6
AC
1867}
1868
9a7071a8
JB
1869/* Allow the user to specify what sequence to send to the remote
1870 when he requests a program interruption: Although ^C is usually
1871 what remote systems expect (this is the default, here), it is
1872 sometimes preferable to send a break. On other systems such
1873 as the Linux kernel, a break followed by g, which is Magic SysRq g
1874 is required in order to interrupt the execution. */
1875const char interrupt_sequence_control_c[] = "Ctrl-C";
1876const char interrupt_sequence_break[] = "BREAK";
1877const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1878static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1879 {
1880 interrupt_sequence_control_c,
1881 interrupt_sequence_break,
1882 interrupt_sequence_break_g,
1883 NULL
1884 };
1885static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1886
1887static void
1888show_interrupt_sequence (struct ui_file *file, int from_tty,
1889 struct cmd_list_element *c,
1890 const char *value)
1891{
1892 if (interrupt_sequence_mode == interrupt_sequence_control_c)
6cb06a8c
TT
1893 gdb_printf (file,
1894 _("Send the ASCII ETX character (Ctrl-c) "
1895 "to the remote target to interrupt the "
1896 "execution of the program.\n"));
9a7071a8 1897 else if (interrupt_sequence_mode == interrupt_sequence_break)
6cb06a8c
TT
1898 gdb_printf (file,
1899 _("send a break signal to the remote target "
1900 "to interrupt the execution of the program.\n"));
9a7071a8 1901 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
6cb06a8c
TT
1902 gdb_printf (file,
1903 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1904 "the remote target to interrupt the execution "
1905 "of Linux kernel.\n"));
9a7071a8 1906 else
f34652de 1907 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
9a7071a8
JB
1908 interrupt_sequence_mode);
1909}
6426a772 1910
9a7071a8
JB
1911/* This boolean variable specifies whether interrupt_sequence is sent
1912 to the remote target when gdb connects to it.
1913 This is mostly needed when you debug the Linux kernel: The Linux kernel
1914 expects BREAK g which is Magic SysRq g for connecting gdb. */
491144b5 1915static bool interrupt_on_connect = false;
c906108c 1916
9a7071a8
JB
1917/* This variable is used to implement the "set/show remotebreak" commands.
1918 Since these commands are now deprecated in favor of "set/show remote
1919 interrupt-sequence", it no longer has any effect on the code. */
491144b5 1920static bool remote_break;
c906108c 1921
9a7071a8 1922static void
eb4c3f4a 1923set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1924{
1925 if (remote_break)
1926 interrupt_sequence_mode = interrupt_sequence_break;
1927 else
1928 interrupt_sequence_mode = interrupt_sequence_control_c;
1929}
1930
1931static void
1932show_remotebreak (struct ui_file *file, int from_tty,
1933 struct cmd_list_element *c,
1934 const char *value)
1935{
1936}
1937
c906108c
SS
1938/* This variable sets the number of bits in an address that are to be
1939 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1940 leading zeros, the entire address would be sent. This variable
c906108c
SS
1941 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1942 initial implementation of remote.c restricted the address sent in
1943 memory packets to ``host::sizeof long'' bytes - (typically 32
1944 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1945 address was never sent. Since fixing this bug may cause a break in
85102364 1946 some remote targets this variable is principally provided to
23860348 1947 facilitate backward compatibility. */
c906108c 1948
883b9c6c 1949static unsigned int remote_address_size;
c906108c 1950
11cf8741 1951\f
cc0be08f
PA
1952/* The default max memory-write-packet-size, when the setting is
1953 "fixed". The 16k is historical. (It came from older GDB's using
1954 alloca for buffers and the knowledge (folklore?) that some hosts
1955 don't cope very well with large alloca calls.) */
1956#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
1957
1958/* The minimum remote packet size for memory transfers. Ensures we
1959 can write at least one byte. */
1960#define MIN_MEMORY_PACKET_SIZE 20
1961
cc0be08f
PA
1962/* Get the memory packet size, assuming it is fixed. */
1963
1964static long
1965get_fixed_memory_packet_size (struct memory_packet_config *config)
1966{
1967 gdb_assert (config->fixed_p);
1968
1969 if (config->size <= 0)
1970 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1971 else
1972 return config->size;
1973}
1974
11cf8741
JM
1975/* Compute the current size of a read/write packet. Since this makes
1976 use of ``actual_register_packet_size'' the computation is dynamic. */
1977
6b8edb51
PA
1978long
1979remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 1980{
d01949b6 1981 struct remote_state *rs = get_remote_state ();
9d6eea31 1982 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1983
11cf8741
JM
1984 long what_they_get;
1985 if (config->fixed_p)
cc0be08f 1986 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
1987 else
1988 {
ea9c271d 1989 what_they_get = get_remote_packet_size ();
23860348 1990 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1991 if (config->size > 0
1992 && what_they_get > config->size)
1993 what_they_get = config->size;
be2a5f71
DJ
1994
1995 /* Limit it to the size of the targets ``g'' response unless we have
1996 permission from the stub to use a larger packet size. */
1997 if (rs->explicit_packet_size == 0
1998 && rsa->actual_register_packet_size > 0
1999 && what_they_get > rsa->actual_register_packet_size)
2000 what_they_get = rsa->actual_register_packet_size;
11cf8741 2001 }
a5c0808e
PA
2002 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2003 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
2004
2005 /* Make sure there is room in the global buffer for this packet
2006 (including its trailing NUL byte). */
8d64371b
TT
2007 if (rs->buf.size () < what_they_get + 1)
2008 rs->buf.resize (2 * what_they_get);
6d820c5c 2009
11cf8741
JM
2010 return what_they_get;
2011}
2012
0df8b418 2013/* Update the size of a read/write packet. If they user wants
23860348 2014 something really big then do a sanity check. */
11cf8741
JM
2015
2016static void
fe4c3ca0
CS
2017set_memory_packet_size (const char *args, struct memory_packet_config *config,
2018 bool target_connected)
11cf8741
JM
2019{
2020 int fixed_p = config->fixed_p;
2021 long size = config->size;
a744cf53 2022
11cf8741 2023 if (args == NULL)
fe4c3ca0 2024 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
11cf8741
JM
2025 else if (strcmp (args, "hard") == 0
2026 || strcmp (args, "fixed") == 0)
2027 fixed_p = 1;
2028 else if (strcmp (args, "soft") == 0
2029 || strcmp (args, "limit") == 0)
2030 fixed_p = 0;
2031 else
2032 {
2033 char *end;
a744cf53 2034
11cf8741
JM
2035 size = strtoul (args, &end, 0);
2036 if (args == end)
8a3fe4f8 2037 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
2038
2039 /* Instead of explicitly capping the size of a packet to or
2040 disallowing it, the user is allowed to set the size to
2041 something arbitrarily large. */
11cf8741 2042 }
a5c0808e 2043
23860348 2044 /* Extra checks? */
11cf8741
JM
2045 if (fixed_p && !config->fixed_p)
2046 {
cc0be08f
PA
2047 /* So that the query shows the correct value. */
2048 long query_size = (size <= 0
2049 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2050 : size);
2051
fe4c3ca0
CS
2052 if (target_connected
2053 && !query (_("The target may not be able to correctly handle a %s\n"
2054 "of %ld bytes. Change the packet size? "),
2055 config->name, query_size))
2056 error (_("Packet size not changed."));
2057 else if (!target_connected
2058 && !query (_("Future remote targets may not be able to "
2059 "correctly handle a %s\nof %ld bytes. Change the "
2060 "packet size for future remote targets? "),
2061 config->name, query_size))
8a3fe4f8 2062 error (_("Packet size not changed."));
11cf8741 2063 }
23860348 2064 /* Update the config. */
11cf8741
JM
2065 config->fixed_p = fixed_p;
2066 config->size = size;
fe4c3ca0
CS
2067
2068 const char *target_type = get_target_type_name (target_connected);
2069 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2070 args);
2071
11cf8741
JM
2072}
2073
fe4c3ca0
CS
2074/* Show the memory-read or write-packet size configuration CONFIG of the
2075 target REMOTE. If REMOTE is nullptr, the default configuration for future
2076 remote targets should be passed in CONFIG. */
2077
11cf8741 2078static void
fe4c3ca0 2079show_memory_packet_size (memory_packet_config *config, remote_target *remote)
11cf8741 2080{
fe4c3ca0
CS
2081 const char *target_type = get_target_type_name (remote != nullptr);
2082
cc0be08f 2083 if (config->size == 0)
fe4c3ca0 2084 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
cc0be08f 2085 else
fe4c3ca0
CS
2086 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2087 config->size);
2088
11cf8741 2089 if (config->fixed_p)
6cb06a8c
TT
2090 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2091 get_fixed_memory_packet_size (config));
11cf8741 2092 else
cc0be08f 2093 {
fe4c3ca0 2094 if (remote != nullptr)
6cb06a8c
TT
2095 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2096 remote->get_memory_packet_size (config));
cc0be08f 2097 else
0426ad51
TT
2098 gdb_puts ("The actual limit will be further reduced "
2099 "dependent on the target.\n");
cc0be08f 2100 }
11cf8741
JM
2101}
2102
fe4c3ca0
CS
2103/* Configure the memory-write-packet size of the currently selected target. If
2104 no target is available, the default configuration for future remote targets
2105 is configured. */
11cf8741
JM
2106
2107static void
ac88e2de 2108set_memory_write_packet_size (const char *args, int from_tty)
11cf8741 2109{
fe4c3ca0
CS
2110 remote_target *remote = get_current_remote_target ();
2111 if (remote != nullptr)
2112 {
2113 set_memory_packet_size
2114 (args, &remote->m_features.m_memory_write_packet_config, true);
2115 }
2116 else
2117 {
2118 memory_packet_config* config = &memory_write_packet_config;
2119 set_memory_packet_size (args, config, false);
2120 }
11cf8741
JM
2121}
2122
fe4c3ca0
CS
2123/* Display the memory-write-packet size of the currently selected target. If
2124 no target is available, the default configuration for future remote targets
2125 is shown. */
2126
11cf8741 2127static void
ac88e2de 2128show_memory_write_packet_size (const char *args, int from_tty)
11cf8741 2129{
fe4c3ca0
CS
2130 remote_target *remote = get_current_remote_target ();
2131 if (remote != nullptr)
2132 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2133 remote);
2134 else
2135 show_memory_packet_size (&memory_write_packet_config, nullptr);
11cf8741
JM
2136}
2137
055303e2
AB
2138/* Show the number of hardware watchpoints that can be used. */
2139
2140static void
2141show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2142 struct cmd_list_element *c,
2143 const char *value)
2144{
6cb06a8c
TT
2145 gdb_printf (file, _("The maximum number of target hardware "
2146 "watchpoints is %s.\n"), value);
055303e2
AB
2147}
2148
2149/* Show the length limit (in bytes) for hardware watchpoints. */
2150
2151static void
2152show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2153 struct cmd_list_element *c,
2154 const char *value)
2155{
6cb06a8c
TT
2156 gdb_printf (file, _("The maximum length (in bytes) of a target "
2157 "hardware watchpoint is %s.\n"), value);
055303e2
AB
2158}
2159
2160/* Show the number of hardware breakpoints that can be used. */
2161
2162static void
2163show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2164 struct cmd_list_element *c,
2165 const char *value)
2166{
6cb06a8c
TT
2167 gdb_printf (file, _("The maximum number of target hardware "
2168 "breakpoints is %s.\n"), value);
055303e2
AB
2169}
2170
6cc8564b
LM
2171/* Controls the maximum number of characters to display in the debug output
2172 for each remote packet. The remaining characters are omitted. */
2173
2174static int remote_packet_max_chars = 512;
2175
2176/* Show the maximum number of characters to display for each remote packet
2177 when remote debugging is enabled. */
2178
2179static void
2180show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2181 struct cmd_list_element *c,
2182 const char *value)
2183{
6cb06a8c
TT
2184 gdb_printf (file, _("Number of remote packet characters to "
2185 "display is %s.\n"), value);
6cc8564b
LM
2186}
2187
6b8edb51
PA
2188long
2189remote_target::get_memory_write_packet_size ()
11cf8741 2190{
fe4c3ca0 2191 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
11cf8741
JM
2192}
2193
fe4c3ca0
CS
2194/* Configure the memory-read-packet size of the currently selected target. If
2195 no target is available, the default configuration for future remote targets
2196 is adapted. */
11cf8741
JM
2197
2198static void
ac88e2de 2199set_memory_read_packet_size (const char *args, int from_tty)
11cf8741 2200{
fe4c3ca0
CS
2201 remote_target *remote = get_current_remote_target ();
2202 if (remote != nullptr)
2203 set_memory_packet_size
2204 (args, &remote->m_features.m_memory_read_packet_config, true);
2205 else
2206 {
2207 memory_packet_config* config = &memory_read_packet_config;
2208 set_memory_packet_size (args, config, false);
2209 }
2210
11cf8741
JM
2211}
2212
fe4c3ca0
CS
2213/* Display the memory-read-packet size of the currently selected target. If
2214 no target is available, the default configuration for future remote targets
2215 is shown. */
2216
11cf8741 2217static void
ac88e2de 2218show_memory_read_packet_size (const char *args, int from_tty)
11cf8741 2219{
fe4c3ca0
CS
2220 remote_target *remote = get_current_remote_target ();
2221 if (remote != nullptr)
2222 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2223 remote);
2224 else
2225 show_memory_packet_size (&memory_read_packet_config, nullptr);
11cf8741
JM
2226}
2227
6b8edb51
PA
2228long
2229remote_target::get_memory_read_packet_size ()
11cf8741 2230{
fe4c3ca0 2231 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
a744cf53 2232
11cf8741
JM
2233 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2234 extra buffer size argument before the memory read size can be
ea9c271d
DJ
2235 increased beyond this. */
2236 if (size > get_remote_packet_size ())
2237 size = get_remote_packet_size ();
11cf8741
JM
2238 return size;
2239}
2240
ff52c073 2241static enum packet_support packet_config_support (const packet_config *config);
5a2468f5 2242
4082afcc 2243
ff52c073
CS
2244static void
2245set_remote_protocol_packet_cmd (const char *args, int from_tty,
2246 cmd_list_element *c)
2247{
2248 remote_target *remote = get_current_remote_target ();
2249 gdb_assert (c->var.has_value ());
4082afcc 2250
ff52c073
CS
2251 auto *default_config = static_cast<packet_config *> (c->context ());
2252 const int packet_idx = std::distance (remote_protocol_packets,
2253 default_config);
fcef6471 2254
ff52c073
CS
2255 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2256 {
2257 const char *name = packets_descriptions[packet_idx].name;
2258 const auto_boolean value = c->var->get<auto_boolean> ();
2259 const char *support = get_packet_support_name (value);
2260 const char *target_type = get_target_type_name (remote != nullptr);
5a2468f5 2261
ff52c073
CS
2262 if (remote != nullptr)
2263 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2264 else
2265 remote_protocol_packets[packet_idx].detect = value;
2266
2267 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2268 target_type, support);
2269 return;
2270 }
2271
2272 internal_error (_("Could not find config for %s"), c->name);
2273}
5a2468f5
JM
2274
2275static void
ff52c073
CS
2276show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2277 remote_target *remote)
5a2468f5 2278{
a121b7c1 2279 const char *support = "internal-error";
ff52c073
CS
2280 const char *target_type = get_target_type_name (remote != nullptr);
2281
2282 packet_config *config;
2283 if (remote != nullptr)
2284 config = &remote->m_features.m_protocol_packets[which_packet];
2285 else
2286 config = &remote_protocol_packets[which_packet];
a744cf53 2287
4082afcc 2288 switch (packet_config_support (config))
5a2468f5
JM
2289 {
2290 case PACKET_ENABLE:
2291 support = "enabled";
2292 break;
2293 case PACKET_DISABLE:
2294 support = "disabled";
2295 break;
2296 case PACKET_SUPPORT_UNKNOWN:
2297 support = "unknown";
2298 break;
2299 }
2300 switch (config->detect)
2301 {
7f19b9a2 2302 case AUTO_BOOLEAN_AUTO:
6cb06a8c 2303 gdb_printf (file,
ff52c073
CS
2304 _("Support for the '%s' packet %s is \"auto\", "
2305 "currently %s.\n"),
2306 packets_descriptions[which_packet].name, target_type,
2307 support);
5a2468f5 2308 break;
7f19b9a2
AC
2309 case AUTO_BOOLEAN_TRUE:
2310 case AUTO_BOOLEAN_FALSE:
6cb06a8c 2311 gdb_printf (file,
ff52c073
CS
2312 _("Support for the '%s' packet %s is \"%s\".\n"),
2313 packets_descriptions[which_packet].name, target_type,
2314 get_packet_support_name (config->detect));
8e248173 2315 break;
5a2468f5
JM
2316 }
2317}
2318
2319static void
ff52c073 2320add_packet_config_cmd (const unsigned int which_packet, const char *name,
bb572ddd 2321 const char *title, int legacy)
d471ea57 2322{
ff52c073
CS
2323 packets_descriptions[which_packet].name = name;
2324 packets_descriptions[which_packet].title = title;
2325
2326 packet_config *config = &remote_protocol_packets[which_packet];
2327
8579fd13
AB
2328 gdb::unique_xmalloc_ptr<char> set_doc
2329 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2330 name, title);
2331 gdb::unique_xmalloc_ptr<char> show_doc
2332 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2333 name, title);
d471ea57 2334 /* set/show TITLE-packet {auto,on,off} */
8579fd13 2335 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
5e84b7ee 2336 set_show_commands cmds
8579fd13
AB
2337 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2338 &config->detect, set_doc.get (),
2339 show_doc.get (), NULL, /* help_doc */
ff52c073 2340 set_remote_protocol_packet_cmd,
5e84b7ee
SM
2341 show_remote_protocol_packet_cmd,
2342 &remote_set_cmdlist, &remote_show_cmdlist);
ff52c073
CS
2343 cmds.show->set_context (config);
2344 cmds.set->set_context (config);
5e84b7ee 2345
23860348 2346 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
2347 if (legacy)
2348 {
5f21c7aa
AB
2349 /* It's not clear who should take ownership of the LEGACY_NAME string
2350 created below, so, for now, place the string into a static vector
2351 which ensures the strings is released when GDB exits. */
2352 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2353 gdb::unique_xmalloc_ptr<char> legacy_name
8579fd13
AB
2354 = xstrprintf ("%s-packet", name);
2355 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
bb572ddd 2356 &remote_set_cmdlist);
8579fd13 2357 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
bb572ddd 2358 &remote_show_cmdlist);
5f21c7aa 2359 legacy_names.emplace_back (std::move (legacy_name));
d471ea57 2360 }
5a2468f5
JM
2361}
2362
d471ea57 2363static enum packet_result
a76d924d 2364packet_check_result (const char *buf)
5a2468f5 2365{
d471ea57 2366 if (buf[0] != '\0')
5a2468f5 2367 {
d471ea57 2368 /* The stub recognized the packet request. Check that the
23860348 2369 operation succeeded. */
a76d924d
DJ
2370 if (buf[0] == 'E'
2371 && isxdigit (buf[1]) && isxdigit (buf[2])
2372 && buf[3] == '\0')
85102364 2373 /* "Enn" - definitely an error. */
a76d924d
DJ
2374 return PACKET_ERROR;
2375
2376 /* Always treat "E." as an error. This will be used for
2377 more verbose error messages, such as E.memtypes. */
2378 if (buf[0] == 'E' && buf[1] == '.')
2379 return PACKET_ERROR;
2380
2381 /* The packet may or may not be OK. Just assume it is. */
2382 return PACKET_OK;
2383 }
2384 else
2385 /* The stub does not support the packet. */
2386 return PACKET_UNKNOWN;
2387}
2388
8d64371b
TT
2389static enum packet_result
2390packet_check_result (const gdb::char_vector &buf)
2391{
2392 return packet_check_result (buf.data ());
2393}
2394
ff52c073
CS
2395packet_result
2396remote_features::packet_ok (const char *buf, const int which_packet)
a76d924d 2397{
ff52c073
CS
2398 packet_config *config = &m_protocol_packets[which_packet];
2399 packet_description *descr = &packets_descriptions[which_packet];
2400
a76d924d
DJ
2401 enum packet_result result;
2402
4082afcc
PA
2403 if (config->detect != AUTO_BOOLEAN_TRUE
2404 && config->support == PACKET_DISABLE)
f34652de 2405 internal_error (_("packet_ok: attempt to use a disabled packet"));
4082afcc 2406
a76d924d
DJ
2407 result = packet_check_result (buf);
2408 switch (result)
2409 {
2410 case PACKET_OK:
2411 case PACKET_ERROR:
2412 /* The stub recognized the packet request. */
4082afcc 2413 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 2414 {
2189c312 2415 remote_debug_printf ("Packet %s (%s) is supported",
ff52c073 2416 descr->name, descr->title);
d471ea57 2417 config->support = PACKET_ENABLE;
d471ea57 2418 }
a76d924d
DJ
2419 break;
2420 case PACKET_UNKNOWN:
23860348 2421 /* The stub does not support the packet. */
4082afcc
PA
2422 if (config->detect == AUTO_BOOLEAN_AUTO
2423 && config->support == PACKET_ENABLE)
d471ea57 2424 {
4082afcc
PA
2425 /* If the stub previously indicated that the packet was
2426 supported then there is a protocol error. */
2427 error (_("Protocol error: %s (%s) conflicting enabled responses."),
ff52c073 2428 descr->name, descr->title);
4082afcc
PA
2429 }
2430 else if (config->detect == AUTO_BOOLEAN_TRUE)
2431 {
2432 /* The user set it wrong. */
2433 error (_("Enabled packet %s (%s) not recognized by stub"),
ff52c073 2434 descr->name, descr->title);
d471ea57 2435 }
4082afcc 2436
ff52c073
CS
2437 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2438 descr->title);
4082afcc 2439 config->support = PACKET_DISABLE;
a76d924d 2440 break;
5a2468f5 2441 }
a76d924d
DJ
2442
2443 return result;
5a2468f5
JM
2444}
2445
ff52c073
CS
2446packet_result
2447remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
f7e6eed5 2448{
ff52c073 2449 return packet_ok (buf.data (), which_packet);
f7e6eed5
PA
2450}
2451
4082afcc
PA
2452/* Returns whether a given packet or feature is supported. This takes
2453 into account the state of the corresponding "set remote foo-packet"
2454 command, which may be used to bypass auto-detection. */
dc8acb97 2455
4082afcc 2456static enum packet_support
ff52c073 2457packet_config_support (const packet_config *config)
4082afcc
PA
2458{
2459 switch (config->detect)
444abaca 2460 {
4082afcc
PA
2461 case AUTO_BOOLEAN_TRUE:
2462 return PACKET_ENABLE;
2463 case AUTO_BOOLEAN_FALSE:
2464 return PACKET_DISABLE;
2465 case AUTO_BOOLEAN_AUTO:
2466 return config->support;
2467 default:
557b4d76 2468 gdb_assert_not_reached ("bad switch");
444abaca 2469 }
4082afcc
PA
2470}
2471
ff52c073
CS
2472packet_support
2473remote_features::packet_support (int packet) const
4082afcc 2474{
ff52c073 2475 const packet_config *config = &m_protocol_packets[packet];
4082afcc 2476 return packet_config_support (config);
dc8acb97
MS
2477}
2478
5a2468f5 2479static void
444abaca
DJ
2480show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2481 struct cmd_list_element *c,
2482 const char *value)
5a2468f5 2483{
ff52c073 2484 remote_target *remote = get_current_remote_target ();
1d7fe7f0 2485 gdb_assert (c->var.has_value ());
5a2468f5 2486
ff52c073
CS
2487 auto *default_config = static_cast<packet_config *> (c->context ());
2488 const int packet_idx = std::distance (remote_protocol_packets,
2489 default_config);
2490
2491 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
444abaca 2492 {
ff52c073
CS
2493 show_packet_config_cmd (file, packet_idx, remote);
2494 return;
444abaca 2495 }
ff52c073 2496 internal_error (_("Could not find config for %s"), c->name);
5a2468f5
JM
2497}
2498
d471ea57
AC
2499/* Should we try one of the 'Z' requests? */
2500
2501enum Z_packet_type
2502{
2503 Z_PACKET_SOFTWARE_BP,
2504 Z_PACKET_HARDWARE_BP,
2505 Z_PACKET_WRITE_WP,
2506 Z_PACKET_READ_WP,
2507 Z_PACKET_ACCESS_WP,
2508 NR_Z_PACKET_TYPES
2509};
96baa820 2510
d471ea57 2511/* For compatibility with older distributions. Provide a ``set remote
23860348 2512 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2513
7f19b9a2 2514static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2515
2516static void
eb4c3f4a 2517set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2518 struct cmd_list_element *c)
96baa820 2519{
ff52c073 2520 remote_target *remote = get_current_remote_target ();
d471ea57 2521 int i;
a744cf53 2522
d471ea57 2523 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
ff52c073
CS
2524 {
2525 if (remote != nullptr)
2526 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2527 = remote_Z_packet_detect;
2528 else
2529 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2530 }
2531
2532 const char *support = get_packet_support_name (remote_Z_packet_detect);
2533 const char *target_type = get_target_type_name (remote != nullptr);
2534 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2535 support);
2536
96baa820
JM
2537}
2538
2539static void
08546159
AC
2540show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2541 struct cmd_list_element *c,
2542 const char *value)
96baa820 2543{
ff52c073 2544 remote_target *remote = get_current_remote_target ();
d471ea57 2545 int i;
a744cf53 2546
d471ea57 2547 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
ff52c073 2548 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2c2e7f87
LM
2549}
2550
cbb8991c
DB
2551/* Insert fork catchpoint target routine. If fork events are enabled
2552 then return success, nothing more to do. */
2553
f6ac5f3d
PA
2554int
2555remote_target::insert_fork_catchpoint (int pid)
cbb8991c 2556{
ff52c073 2557 return !m_features.remote_fork_event_p ();
cbb8991c
DB
2558}
2559
2560/* Remove fork catchpoint target routine. Nothing to do, just
2561 return success. */
2562
f6ac5f3d
PA
2563int
2564remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2565{
2566 return 0;
2567}
2568
2569/* Insert vfork catchpoint target routine. If vfork events are enabled
2570 then return success, nothing more to do. */
2571
f6ac5f3d
PA
2572int
2573remote_target::insert_vfork_catchpoint (int pid)
cbb8991c 2574{
ff52c073 2575 return !m_features.remote_vfork_event_p ();
cbb8991c
DB
2576}
2577
2578/* Remove vfork catchpoint target routine. Nothing to do, just
2579 return success. */
2580
f6ac5f3d
PA
2581int
2582remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2583{
2584 return 0;
2585}
2586
d46addbb
DB
2587/* Insert exec catchpoint target routine. If exec events are
2588 enabled, just return success. */
2589
f6ac5f3d
PA
2590int
2591remote_target::insert_exec_catchpoint (int pid)
d46addbb 2592{
ff52c073 2593 return !m_features.remote_exec_event_p ();
d46addbb
DB
2594}
2595
2596/* Remove exec catchpoint target routine. Nothing to do, just
2597 return success. */
2598
f6ac5f3d
PA
2599int
2600remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2601{
2602 return 0;
2603}
2604
c906108c
SS
2605\f
2606
ffdd69cf
TT
2607/* Take advantage of the fact that the TID field is not used, to tag
2608 special ptids with it set to != 0. */
2609static const ptid_t magic_null_ptid (42000, -1, 1);
2610static const ptid_t not_sent_ptid (42000, -2, 1);
2611static const ptid_t any_thread_ptid (42000, 0, 1);
79d7f229 2612
0b16c5cf
PA
2613/* Find out if the stub attached to PID (and hence GDB should offer to
2614 detach instead of killing it when bailing out). */
2615
6b8edb51
PA
2616int
2617remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2618{
2619 struct remote_state *rs = get_remote_state ();
bba74b36 2620 size_t size = get_remote_packet_size ();
0b16c5cf 2621
ff52c073 2622 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2623 return 0;
2624
ff52c073 2625 if (m_features.remote_multi_process_p ())
8d64371b 2626 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
0b16c5cf 2627 else
8d64371b 2628 xsnprintf (rs->buf.data (), size, "qAttached");
0b16c5cf
PA
2629
2630 putpkt (rs->buf);
8d64371b 2631 getpkt (&rs->buf, 0);
0b16c5cf 2632
ff52c073 2633 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
0b16c5cf
PA
2634 {
2635 case PACKET_OK:
8d64371b 2636 if (strcmp (rs->buf.data (), "1") == 0)
0b16c5cf
PA
2637 return 1;
2638 break;
2639 case PACKET_ERROR:
8d64371b 2640 warning (_("Remote failure reply: %s"), rs->buf.data ());
0b16c5cf
PA
2641 break;
2642 case PACKET_UNKNOWN:
2643 break;
2644 }
2645
2646 return 0;
2647}
2648
49c62f2e
PA
2649/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2650 has been invented by GDB, instead of reported by the target. Since
2651 we can be connected to a remote system before before knowing about
2652 any inferior, mark the target with execution when we find the first
2653 inferior. If ATTACHED is 1, then we had just attached to this
2654 inferior. If it is 0, then we just created this inferior. If it
2655 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2656 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2657 attempt to open this inferior's executable as the main executable
2658 if no main executable is open already. */
1941c569 2659
6b8edb51 2660inferior *
9ab8741a 2661remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51 2662 int try_open_exec)
1941c569 2663{
1941c569
PA
2664 struct inferior *inf;
2665
0b16c5cf
PA
2666 /* Check whether this process we're learning about is to be
2667 considered attached, or if is to be considered to have been
2668 spawned by the stub. */
2669 if (attached == -1)
2670 attached = remote_query_attached (pid);
2671
f5656ead 2672 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2673 {
2674 /* If the target shares code across all inferiors, then every
2675 attach adds a new inferior. */
2676 inf = add_inferior (pid);
2677
2678 /* ... and every inferior is bound to the same program space.
2679 However, each inferior may still have its own address
2680 space. */
2681 inf->aspace = maybe_new_address_space ();
2682 inf->pspace = current_program_space;
2683 }
2684 else
2685 {
2686 /* In the traditional debugging scenario, there's a 1-1 match
2687 between program/address spaces. We simply bind the inferior
2688 to the program space's address space. */
2689 inf = current_inferior ();
78f2c40a
PA
2690
2691 /* However, if the current inferior is already bound to a
2692 process, find some other empty inferior. */
2693 if (inf->pid != 0)
2694 {
2695 inf = nullptr;
2696 for (inferior *it : all_inferiors ())
2697 if (it->pid == 0)
2698 {
2699 inf = it;
2700 break;
2701 }
2702 }
2703 if (inf == nullptr)
2704 {
2705 /* Since all inferiors were already bound to a process, add
2706 a new inferior. */
2707 inf = add_inferior_with_spaces ();
2708 }
2709 switch_to_inferior_no_thread (inf);
02980c56 2710 inf->push_target (this);
6c95b8df
PA
2711 inferior_appeared (inf, pid);
2712 }
1941c569 2713
0b16c5cf 2714 inf->attach_flag = attached;
49c62f2e 2715 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2716
1b6e6f5c
GB
2717 /* If no main executable is currently open then attempt to
2718 open the file that was executed to create this inferior. */
835205d0 2719 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2720 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2721
a2fedca9
PW
2722 /* Check for exec file mismatch, and let the user solve it. */
2723 validate_exec_file (1);
2724
1941c569
PA
2725 return inf;
2726}
2727
7aabaf9d 2728static remote_thread_info *get_remote_thread_info (thread_info *thread);
5b6d1e4f
PA
2729static remote_thread_info *get_remote_thread_info (remote_target *target,
2730 ptid_t ptid);
85ad3aaf 2731
1941c569 2732/* Add thread PTID to GDB's thread list. Tag it as executing/running
b622494e
AB
2733 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2734 remote_state::starting_up flag) is true then the new thread is added
2735 silently, otherwise the new thread will be announced to the user. */
1941c569 2736
00431a78 2737thread_info *
b622494e
AB
2738remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2739 bool silent_p)
c906108c 2740{
b7ea362b 2741 struct remote_state *rs = get_remote_state ();
85ad3aaf 2742 struct thread_info *thread;
b7ea362b
PA
2743
2744 /* GDB historically didn't pull threads in the initial connection
2745 setup. If the remote target doesn't even have a concept of
2746 threads (e.g., a bare-metal target), even if internally we
2747 consider that a single-threaded target, mentioning a new thread
2748 might be confusing to the user. Be silent then, preserving the
2749 age old behavior. */
b622494e 2750 if (rs->starting_up || silent_p)
5b6d1e4f 2751 thread = add_thread_silent (this, ptid);
b7ea362b 2752 else
5b6d1e4f 2753 thread = add_thread (this, ptid);
1941c569 2754
c9d22089
SM
2755 /* We start by assuming threads are resumed. That state then gets updated
2756 when we process a matching stop reply. */
2757 get_remote_thread_info (thread)->set_resumed ();
2758
5b6d1e4f
PA
2759 set_executing (this, ptid, executing);
2760 set_running (this, ptid, running);
00431a78
PA
2761
2762 return thread;
1941c569
PA
2763}
2764
2765/* Come here when we learn about a thread id from the remote target.
2766 It may be the first time we hear about such thread, so take the
2767 opportunity to add it to GDB's thread list. In case this is the
2768 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2769 GDB's inferior list as well. EXECUTING indicates whether the
2770 thread is (internally) executing or stopped. */
1941c569 2771
6b8edb51 2772void
8a82de58 2773remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
1941c569 2774{
0d5b594f
PA
2775 /* In non-stop mode, we assume new found threads are (externally)
2776 running until proven otherwise with a stop reply. In all-stop,
2777 we can only get here if all threads are stopped. */
8a82de58 2778 bool running = target_is_non_stop_p ();
0d5b594f 2779
c906108c
SS
2780 /* If this is a new thread, add it to GDB's thread list.
2781 If we leave it up to WFI to do this, bad things will happen. */
82f73884 2782
9213a6d7 2783 thread_info *tp = this->find_thread (currthread);
00431a78 2784 if (tp != NULL && tp->state == THREAD_EXITED)
82f73884
PA
2785 {
2786 /* We're seeing an event on a thread id we knew had exited.
2787 This has to be a new thread reusing the old id. Add it. */
b622494e 2788 remote_add_thread (currthread, running, executing, false);
82f73884
PA
2789 return;
2790 }
2791
5b6d1e4f 2792 if (!in_thread_list (this, currthread))
c0a2216e 2793 {
1941c569 2794 struct inferior *inf = NULL;
e99b03dc 2795 int pid = currthread.pid ();
1941c569 2796
0e998d96 2797 if (inferior_ptid.is_pid ()
e99b03dc 2798 && pid == inferior_ptid.pid ())
c0a2216e
PA
2799 {
2800 /* inferior_ptid has no thread member yet. This can happen
2801 with the vAttach -> remote_wait,"TAAthread:" path if the
2802 stub doesn't support qC. This is the first stop reported
2803 after an attach, so this is the main thread. Update the
2804 ptid in the thread list. */
5b6d1e4f
PA
2805 if (in_thread_list (this, ptid_t (pid)))
2806 thread_change_ptid (this, inferior_ptid, currthread);
bad34192
PA
2807 else
2808 {
0ac55310 2809 thread_info *thr
b622494e 2810 = remote_add_thread (currthread, running, executing, false);
0ac55310 2811 switch_to_thread (thr);
bad34192 2812 }
dc146f7c 2813 return;
c0a2216e 2814 }
82f73884 2815
d7e15655 2816 if (magic_null_ptid == inferior_ptid)
c0a2216e
PA
2817 {
2818 /* inferior_ptid is not set yet. This can happen with the
2819 vRun -> remote_wait,"TAAthread:" path if the stub
2820 doesn't support qC. This is the first stop reported
2821 after an attach, so this is the main thread. Update the
2822 ptid in the thread list. */
5b6d1e4f 2823 thread_change_ptid (this, inferior_ptid, currthread);
82f73884 2824 return;
c0a2216e 2825 }
82f73884 2826
29c87f7f
PA
2827 /* When connecting to a target remote, or to a target
2828 extended-remote which already was debugging an inferior, we
2829 may not know about it yet. Add it before adding its child
2830 thread, so notifications are emitted in a sensible order. */
5b6d1e4f 2831 if (find_inferior_pid (this, currthread.pid ()) == NULL)
49c62f2e 2832 {
ff52c073 2833 bool fake_pid_p = !m_features.remote_multi_process_p ();
49c62f2e
PA
2834
2835 inf = remote_add_inferior (fake_pid_p,
e99b03dc 2836 currthread.pid (), -1, 1);
49c62f2e 2837 }
29c87f7f 2838
82f73884 2839 /* This is really a new thread. Add it. */
00431a78 2840 thread_info *new_thr
b622494e 2841 = remote_add_thread (currthread, running, executing, false);
1941c569
PA
2842
2843 /* If we found a new inferior, let the common code do whatever
2844 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2845 breakpoints), unless we're just setting up an all-stop
2846 connection. */
1941c569 2847 if (inf != NULL)
b7ea362b
PA
2848 {
2849 struct remote_state *rs = get_remote_state ();
2850
6efcd9a8 2851 if (!rs->starting_up)
00431a78 2852 notice_new_inferior (new_thr, executing, 0);
b7ea362b 2853 }
c0a2216e 2854 }
c906108c
SS
2855}
2856
85ad3aaf 2857/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2858
7aabaf9d
SM
2859static remote_thread_info *
2860get_remote_thread_info (thread_info *thread)
dc146f7c 2861{
85ad3aaf 2862 gdb_assert (thread != NULL);
dc146f7c 2863
85ad3aaf 2864 if (thread->priv == NULL)
7aabaf9d 2865 thread->priv.reset (new remote_thread_info);
dc146f7c 2866
98ed24fb 2867 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2868}
2869
5b6d1e4f
PA
2870/* Return PTID's private thread data, creating it if necessary. */
2871
7aabaf9d 2872static remote_thread_info *
5b6d1e4f 2873get_remote_thread_info (remote_target *target, ptid_t ptid)
85ad3aaf 2874{
9213a6d7 2875 thread_info *thr = target->find_thread (ptid);
00431a78 2876 return get_remote_thread_info (thr);
dc146f7c
VP
2877}
2878
74531fed
PA
2879/* Call this function as a result of
2880 1) A halt indication (T packet) containing a thread id
2881 2) A direct query of currthread
0df8b418 2882 3) Successful execution of set thread */
74531fed
PA
2883
2884static void
47f8a51d 2885record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2886{
47f8a51d 2887 rs->general_thread = currthread;
74531fed
PA
2888}
2889
89be2091
DJ
2890/* If 'QPassSignals' is supported, tell the remote stub what signals
2891 it can simply pass through to the inferior without reporting. */
2892
f6ac5f3d 2893void
adc6a863 2894remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
89be2091 2895{
ff52c073 2896 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2897 {
2898 char *pass_packet, *p;
adc6a863 2899 int count = 0;
747dc59d 2900 struct remote_state *rs = get_remote_state ();
89be2091 2901
adc6a863
PA
2902 gdb_assert (pass_signals.size () < 256);
2903 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2904 {
2455069d 2905 if (pass_signals[i])
89be2091
DJ
2906 count++;
2907 }
224c3ddb 2908 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2909 strcpy (pass_packet, "QPassSignals:");
2910 p = pass_packet + strlen (pass_packet);
adc6a863 2911 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2912 {
2455069d 2913 if (pass_signals[i])
89be2091
DJ
2914 {
2915 if (i >= 16)
2916 *p++ = tohex (i >> 4);
2917 *p++ = tohex (i & 15);
2918 if (count)
2919 *p++ = ';';
2920 else
2921 break;
2922 count--;
2923 }
2924 }
2925 *p = 0;
747dc59d 2926 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2927 {
89be2091 2928 putpkt (pass_packet);
8d64371b 2929 getpkt (&rs->buf, 0);
ff52c073 2930 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
84d53fa9 2931 xfree (rs->last_pass_packet);
747dc59d 2932 rs->last_pass_packet = pass_packet;
89be2091
DJ
2933 }
2934 else
2935 xfree (pass_packet);
2936 }
2937}
2938
82075af2
JS
2939/* If 'QCatchSyscalls' is supported, tell the remote stub
2940 to report syscalls to GDB. */
2941
f6ac5f3d
PA
2942int
2943remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2944 gdb::array_view<const int> syscall_counts)
82075af2 2945{
b80406ac 2946 const char *catch_packet;
82075af2
JS
2947 enum packet_result result;
2948 int n_sysno = 0;
2949
ff52c073 2950 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
82075af2
JS
2951 {
2952 /* Not supported. */
2953 return 1;
2954 }
2955
649a140c 2956 if (needed && any_count == 0)
82075af2 2957 {
649a140c
PA
2958 /* Count how many syscalls are to be caught. */
2959 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2960 {
649a140c 2961 if (syscall_counts[i] != 0)
82075af2
JS
2962 n_sysno++;
2963 }
2964 }
2965
2189c312
SM
2966 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2967 pid, needed, any_count, n_sysno);
82075af2 2968
1b81856f 2969 std::string built_packet;
82075af2
JS
2970 if (needed)
2971 {
2972 /* Prepare a packet with the sysno list, assuming max 8+1
2973 characters for a sysno. If the resulting packet size is too
2974 big, fallback on the non-selective packet. */
2975 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2976 built_packet.reserve (maxpktsz);
2977 built_packet = "QCatchSyscalls:1";
649a140c 2978 if (any_count == 0)
82075af2 2979 {
649a140c
PA
2980 /* Add in each syscall to be caught. */
2981 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2982 {
649a140c
PA
2983 if (syscall_counts[i] != 0)
2984 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2985 }
2986 }
1b81856f 2987 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2988 {
2989 /* catch_packet too big. Fallback to less efficient
2990 non selective mode, with GDB doing the filtering. */
b80406ac 2991 catch_packet = "QCatchSyscalls:1";
82075af2 2992 }
b80406ac 2993 else
1b81856f 2994 catch_packet = built_packet.c_str ();
82075af2
JS
2995 }
2996 else
b80406ac 2997 catch_packet = "QCatchSyscalls:0";
82075af2 2998
b80406ac 2999 struct remote_state *rs = get_remote_state ();
82075af2 3000
b80406ac 3001 putpkt (catch_packet);
8d64371b 3002 getpkt (&rs->buf, 0);
ff52c073 3003 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
b80406ac
TT
3004 if (result == PACKET_OK)
3005 return 0;
3006 else
3007 return -1;
82075af2
JS
3008}
3009
9b224c5e
PA
3010/* If 'QProgramSignals' is supported, tell the remote stub what
3011 signals it should pass through to the inferior when detaching. */
3012
f6ac5f3d 3013void
adc6a863 3014remote_target::program_signals (gdb::array_view<const unsigned char> signals)
9b224c5e 3015{
ff52c073 3016 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
3017 {
3018 char *packet, *p;
adc6a863 3019 int count = 0;
5e4a05c4 3020 struct remote_state *rs = get_remote_state ();
9b224c5e 3021
adc6a863
PA
3022 gdb_assert (signals.size () < 256);
3023 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
3024 {
3025 if (signals[i])
3026 count++;
3027 }
224c3ddb 3028 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
3029 strcpy (packet, "QProgramSignals:");
3030 p = packet + strlen (packet);
adc6a863 3031 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
3032 {
3033 if (signal_pass_state (i))
3034 {
3035 if (i >= 16)
3036 *p++ = tohex (i >> 4);
3037 *p++ = tohex (i & 15);
3038 if (count)
3039 *p++ = ';';
3040 else
3041 break;
3042 count--;
3043 }
3044 }
3045 *p = 0;
5e4a05c4
TT
3046 if (!rs->last_program_signals_packet
3047 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 3048 {
9b224c5e 3049 putpkt (packet);
8d64371b 3050 getpkt (&rs->buf, 0);
ff52c073 3051 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
5e4a05c4
TT
3052 xfree (rs->last_program_signals_packet);
3053 rs->last_program_signals_packet = packet;
9b224c5e
PA
3054 }
3055 else
3056 xfree (packet);
3057 }
3058}
3059
79d7f229
PA
3060/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3061 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3062 thread. If GEN is set, set the general thread, if not, then set
3063 the step/continue thread. */
6b8edb51
PA
3064void
3065remote_target::set_thread (ptid_t ptid, int gen)
c906108c 3066{
d01949b6 3067 struct remote_state *rs = get_remote_state ();
47f8a51d 3068 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
8d64371b
TT
3069 char *buf = rs->buf.data ();
3070 char *endbuf = buf + get_remote_packet_size ();
c906108c 3071
d7e15655 3072 if (state == ptid)
c906108c
SS
3073 return;
3074
79d7f229
PA
3075 *buf++ = 'H';
3076 *buf++ = gen ? 'g' : 'c';
d7e15655 3077 if (ptid == magic_null_ptid)
79d7f229 3078 xsnprintf (buf, endbuf - buf, "0");
d7e15655 3079 else if (ptid == any_thread_ptid)
79d7f229 3080 xsnprintf (buf, endbuf - buf, "0");
d7e15655 3081 else if (ptid == minus_one_ptid)
79d7f229
PA
3082 xsnprintf (buf, endbuf - buf, "-1");
3083 else
82f73884 3084 write_ptid (buf, endbuf, ptid);
79d7f229 3085 putpkt (rs->buf);
8d64371b 3086 getpkt (&rs->buf, 0);
c906108c 3087 if (gen)
47f8a51d 3088 rs->general_thread = ptid;
c906108c 3089 else
47f8a51d 3090 rs->continue_thread = ptid;
c906108c 3091}
79d7f229 3092
6b8edb51
PA
3093void
3094remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
3095{
3096 set_thread (ptid, 1);
3097}
3098
6b8edb51
PA
3099void
3100remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
3101{
3102 set_thread (ptid, 0);
3103}
3104
3c9c4b83
PA
3105/* Change the remote current process. Which thread within the process
3106 ends up selected isn't important, as long as it is the same process
3107 as what INFERIOR_PTID points to.
3108
3109 This comes from that fact that there is no explicit notion of
3110 "selected process" in the protocol. The selected process for
3111 general operations is the process the selected general thread
3112 belongs to. */
3113
6b8edb51
PA
3114void
3115remote_target::set_general_process ()
3c9c4b83 3116{
3c9c4b83 3117 /* If the remote can't handle multiple processes, don't bother. */
ff52c073 3118 if (!m_features.remote_multi_process_p ())
3c9c4b83
PA
3119 return;
3120
ff52c073
CS
3121 remote_state *rs = get_remote_state ();
3122
3c9c4b83
PA
3123 /* We only need to change the remote current thread if it's pointing
3124 at some other process. */
e99b03dc 3125 if (rs->general_thread.pid () != inferior_ptid.pid ())
3c9c4b83
PA
3126 set_general_thread (inferior_ptid);
3127}
3128
c906108c 3129\f
7d1a114c
PA
3130/* Return nonzero if this is the main thread that we made up ourselves
3131 to model non-threaded targets as single-threaded. */
c906108c
SS
3132
3133static int
f6ac5f3d 3134remote_thread_always_alive (ptid_t ptid)
c906108c 3135{
d7e15655 3136 if (ptid == magic_null_ptid)
c0a2216e
PA
3137 /* The main thread is always alive. */
3138 return 1;
3139
e38504b3 3140 if (ptid.pid () != 0 && ptid.lwp () == 0)
c0a2216e
PA
3141 /* The main thread is always alive. This can happen after a
3142 vAttach, if the remote side doesn't support
3143 multi-threading. */
3144 return 1;
3145
7d1a114c
PA
3146 return 0;
3147}
3148
3149/* Return nonzero if the thread PTID is still alive on the remote
3150 system. */
3151
57810aa7 3152bool
f6ac5f3d 3153remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
3154{
3155 struct remote_state *rs = get_remote_state ();
3156 char *p, *endp;
3157
3158 /* Check if this is a thread that we made up ourselves to model
3159 non-threaded targets as single-threaded. */
f6ac5f3d 3160 if (remote_thread_always_alive (ptid))
7d1a114c
PA
3161 return 1;
3162
8d64371b
TT
3163 p = rs->buf.data ();
3164 endp = p + get_remote_packet_size ();
82f73884
PA
3165
3166 *p++ = 'T';
3167 write_ptid (p, endp, ptid);
3168
2e9f7625 3169 putpkt (rs->buf);
8d64371b 3170 getpkt (&rs->buf, 0);
2e9f7625 3171 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
3172}
3173
79efa585
SM
3174/* Return a pointer to a thread name if we know it and NULL otherwise.
3175 The thread_info object owns the memory for the name. */
3176
f6ac5f3d
PA
3177const char *
3178remote_target::thread_name (struct thread_info *info)
79efa585
SM
3179{
3180 if (info->priv != NULL)
a9334058
SM
3181 {
3182 const std::string &name = get_remote_thread_info (info)->name;
3183 return !name.empty () ? name.c_str () : NULL;
3184 }
79efa585
SM
3185
3186 return NULL;
3187}
3188
c906108c
SS
3189/* About these extended threadlist and threadinfo packets. They are
3190 variable length packets but, the fields within them are often fixed
30baf67b 3191 length. They are redundant enough to send over UDP as is the
c906108c
SS
3192 remote protocol in general. There is a matching unit test module
3193 in libstub. */
3194
23860348 3195/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 3196 libstub protocol encoding, and remote.c. It is not particularly
33b5899f 3197 changeable. */
cce74817
JM
3198
3199/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 3200 Plan to fix this. */
cce74817 3201
23860348 3202typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 3203
9d1f7ab2 3204/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 3205 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
3206
3207struct gdb_ext_thread_info
c5aa993b 3208 {
23860348 3209 threadref threadid; /* External form of thread reference. */
2bc416ba 3210 int active; /* Has state interesting to GDB?
23860348 3211 regs, stack. */
2bc416ba 3212 char display[256]; /* Brief state display, name,
cedea757 3213 blocked/suspended. */
23860348 3214 char shortname[32]; /* To be used to name threads. */
2bc416ba 3215 char more_display[256]; /* Long info, statistics, queue depth,
23860348 3216 whatever. */
c5aa993b 3217 };
cce74817
JM
3218
3219/* The volume of remote transfers can be limited by submitting
3220 a mask containing bits specifying the desired information.
3221 Use a union of these values as the 'selection' parameter to
0df8b418 3222 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
3223
3224#define TAG_THREADID 1
3225#define TAG_EXISTS 2
3226#define TAG_DISPLAY 4
3227#define TAG_THREADNAME 8
c5aa993b 3228#define TAG_MOREDISPLAY 16
cce74817 3229
23860348 3230#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 3231
cecb1912 3232static const char *unpack_nibble (const char *buf, int *val);
cce74817 3233
cecb1912 3234static const char *unpack_byte (const char *buf, int *value);
cce74817 3235
a14ed312 3236static char *pack_int (char *buf, int value);
cce74817 3237
cecb1912 3238static const char *unpack_int (const char *buf, int *value);
cce74817 3239
cecb1912 3240static const char *unpack_string (const char *src, char *dest, int length);
cce74817 3241
23860348 3242static char *pack_threadid (char *pkt, threadref *id);
cce74817 3243
cecb1912 3244static const char *unpack_threadid (const char *inbuf, threadref *id);
cce74817 3245
23860348 3246void int_to_threadref (threadref *id, int value);
cce74817 3247
23860348 3248static int threadref_to_int (threadref *ref);
cce74817 3249
23860348 3250static void copy_threadref (threadref *dest, threadref *src);
cce74817 3251
23860348 3252static int threadmatch (threadref *dest, threadref *src);
cce74817 3253
2bc416ba 3254static char *pack_threadinfo_request (char *pkt, int mode,
23860348 3255 threadref *id);
cce74817 3256
a14ed312
KB
3257static char *pack_threadlist_request (char *pkt, int startflag,
3258 int threadcount,
23860348 3259 threadref *nextthread);
cce74817 3260
23860348 3261static int remote_newthread_step (threadref *ref, void *context);
cce74817 3262
82f73884
PA
3263
3264/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3265 buffer we're allowed to write to. Returns
3266 BUF+CHARACTERS_WRITTEN. */
3267
6b8edb51
PA
3268char *
3269remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
3270{
3271 int pid, tid;
82f73884 3272
ff52c073 3273 if (m_features.remote_multi_process_p ())
82f73884 3274 {
e99b03dc 3275 pid = ptid.pid ();
82f73884
PA
3276 if (pid < 0)
3277 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3278 else
3279 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3280 }
e38504b3 3281 tid = ptid.lwp ();
82f73884
PA
3282 if (tid < 0)
3283 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3284 else
3285 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3286
3287 return buf;
3288}
3289
256642e8
PA
3290/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3291 last parsed char. Returns null_ptid if no thread id is found, and
3292 throws an error if the thread id has an invalid format. */
82f73884
PA
3293
3294static ptid_t
256642e8 3295read_ptid (const char *buf, const char **obuf)
82f73884 3296{
256642e8
PA
3297 const char *p = buf;
3298 const char *pp;
82f73884 3299 ULONGEST pid = 0, tid = 0;
82f73884
PA
3300
3301 if (*p == 'p')
3302 {
3303 /* Multi-process ptid. */
3304 pp = unpack_varlen_hex (p + 1, &pid);
3305 if (*pp != '.')
b37520b6 3306 error (_("invalid remote ptid: %s"), p);
82f73884
PA
3307
3308 p = pp;
3309 pp = unpack_varlen_hex (p + 1, &tid);
3310 if (obuf)
3311 *obuf = pp;
184ea2f7 3312 return ptid_t (pid, tid);
82f73884
PA
3313 }
3314
3315 /* No multi-process. Just a tid. */
3316 pp = unpack_varlen_hex (p, &tid);
3317
c9f35b34
KB
3318 /* Return null_ptid when no thread id is found. */
3319 if (p == pp)
3320 {
3321 if (obuf)
3322 *obuf = pp;
3323 return null_ptid;
3324 }
3325
2f761de2
TBA
3326 /* Since the stub is not sending a process id, default to what's
3327 current_inferior, unless it doesn't have a PID yet. If so,
ca19bf23
PA
3328 then since there's no way to know the pid of the reported
3329 threads, use the magic number. */
2f761de2
TBA
3330 inferior *inf = current_inferior ();
3331 if (inf->pid == 0)
e99b03dc 3332 pid = magic_null_ptid.pid ();
ca19bf23 3333 else
2f761de2 3334 pid = inf->pid;
82f73884
PA
3335
3336 if (obuf)
3337 *obuf = pp;
184ea2f7 3338 return ptid_t (pid, tid);
82f73884
PA
3339}
3340
c906108c 3341static int
fba45db2 3342stubhex (int ch)
c906108c
SS
3343{
3344 if (ch >= 'a' && ch <= 'f')
3345 return ch - 'a' + 10;
3346 if (ch >= '0' && ch <= '9')
3347 return ch - '0';
3348 if (ch >= 'A' && ch <= 'F')
3349 return ch - 'A' + 10;
3350 return -1;
3351}
3352
3353static int
cecb1912 3354stub_unpack_int (const char *buff, int fieldlength)
c906108c
SS
3355{
3356 int nibble;
3357 int retval = 0;
3358
3359 while (fieldlength)
3360 {
3361 nibble = stubhex (*buff++);
3362 retval |= nibble;
3363 fieldlength--;
3364 if (fieldlength)
3365 retval = retval << 4;
3366 }
3367 return retval;
3368}
3369
cecb1912
SM
3370static const char *
3371unpack_nibble (const char *buf, int *val)
c906108c 3372{
b7589f7d 3373 *val = fromhex (*buf++);
c906108c
SS
3374 return buf;
3375}
3376
cecb1912
SM
3377static const char *
3378unpack_byte (const char *buf, int *value)
c906108c
SS
3379{
3380 *value = stub_unpack_int (buf, 2);
3381 return buf + 2;
3382}
3383
3384static char *
fba45db2 3385pack_int (char *buf, int value)
c906108c
SS
3386{
3387 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3388 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3389 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3390 buf = pack_hex_byte (buf, (value & 0xff));
3391 return buf;
3392}
3393
cecb1912
SM
3394static const char *
3395unpack_int (const char *buf, int *value)
c906108c
SS
3396{
3397 *value = stub_unpack_int (buf, 8);
3398 return buf + 8;
3399}
3400
23860348 3401#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3402static char *pack_string (char *pkt, char *string);
c906108c
SS
3403
3404static char *
fba45db2 3405pack_string (char *pkt, char *string)
c906108c
SS
3406{
3407 char ch;
3408 int len;
3409
3410 len = strlen (string);
3411 if (len > 200)
23860348 3412 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3413 pkt = pack_hex_byte (pkt, len);
3414 while (len-- > 0)
3415 {
3416 ch = *string++;
3417 if ((ch == '\0') || (ch == '#'))
23860348 3418 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3419 *pkt++ = ch;
3420 }
3421 return pkt;
3422}
3423#endif /* 0 (unused) */
3424
cecb1912
SM
3425static const char *
3426unpack_string (const char *src, char *dest, int length)
c906108c
SS
3427{
3428 while (length--)
3429 *dest++ = *src++;
3430 *dest = '\0';
3431 return src;
3432}
3433
3434static char *
fba45db2 3435pack_threadid (char *pkt, threadref *id)
c906108c
SS
3436{
3437 char *limit;
3438 unsigned char *altid;
3439
3440 altid = (unsigned char *) id;
3441 limit = pkt + BUF_THREAD_ID_SIZE;
3442 while (pkt < limit)
3443 pkt = pack_hex_byte (pkt, *altid++);
3444 return pkt;
3445}
3446
3447
cecb1912
SM
3448static const char *
3449unpack_threadid (const char *inbuf, threadref *id)
c906108c
SS
3450{
3451 char *altref;
cecb1912 3452 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
c906108c
SS
3453 int x, y;
3454
3455 altref = (char *) id;
3456
3457 while (inbuf < limit)
3458 {
3459 x = stubhex (*inbuf++);
3460 y = stubhex (*inbuf++);
3461 *altref++ = (x << 4) | y;
3462 }
3463 return inbuf;
3464}
3465
3466/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3467 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3468 to use 64bit thread references internally. This is an adapter
3469 function. */
3470
3471void
fba45db2 3472int_to_threadref (threadref *id, int value)
c906108c
SS
3473{
3474 unsigned char *scan;
3475
3476 scan = (unsigned char *) id;
3477 {
3478 int i = 4;
3479 while (i--)
3480 *scan++ = 0;
3481 }
3482 *scan++ = (value >> 24) & 0xff;
3483 *scan++ = (value >> 16) & 0xff;
3484 *scan++ = (value >> 8) & 0xff;
3485 *scan++ = (value & 0xff);
3486}
3487
3488static int
fba45db2 3489threadref_to_int (threadref *ref)
c906108c
SS
3490{
3491 int i, value = 0;
3492 unsigned char *scan;
3493
cfd77fa1 3494 scan = *ref;
c906108c
SS
3495 scan += 4;
3496 i = 4;
3497 while (i-- > 0)
3498 value = (value << 8) | ((*scan++) & 0xff);
3499 return value;
3500}
3501
3502static void
fba45db2 3503copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3504{
3505 int i;
3506 unsigned char *csrc, *cdest;
3507
3508 csrc = (unsigned char *) src;
3509 cdest = (unsigned char *) dest;
3510 i = 8;
3511 while (i--)
3512 *cdest++ = *csrc++;
3513}
3514
3515static int
fba45db2 3516threadmatch (threadref *dest, threadref *src)
c906108c 3517{
23860348 3518 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3519#if 0
3520 unsigned char *srcp, *destp;
3521 int i, result;
3522 srcp = (char *) src;
3523 destp = (char *) dest;
3524
3525 result = 1;
3526 while (i-- > 0)
3527 result &= (*srcp++ == *destp++) ? 1 : 0;
3528 return result;
3529#endif
3530 return 1;
3531}
3532
3533/*
c5aa993b
JM
3534 threadid:1, # always request threadid
3535 context_exists:2,
3536 display:4,
3537 unique_name:8,
3538 more_display:16
3539 */
c906108c
SS
3540
3541/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3542
3543static char *
fba45db2 3544pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3545{
23860348
MS
3546 *pkt++ = 'q'; /* Info Query */
3547 *pkt++ = 'P'; /* process or thread info */
3548 pkt = pack_int (pkt, mode); /* mode */
c906108c 3549 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3550 *pkt = '\0'; /* terminate */
c906108c
SS
3551 return pkt;
3552}
3553
23860348 3554/* These values tag the fields in a thread info response packet. */
c906108c 3555/* Tagging the fields allows us to request specific fields and to
23860348 3556 add more fields as time goes by. */
c906108c 3557
23860348 3558#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3559#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3560 fetch registers and its stack? */
c5aa993b 3561#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3562#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3563#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3564 the process. */
c906108c 3565
6b8edb51 3566int
cecb1912 3567remote_target::remote_unpack_thread_info_response (const char *pkt,
6b8edb51
PA
3568 threadref *expectedref,
3569 gdb_ext_thread_info *info)
c906108c 3570{
d01949b6 3571 struct remote_state *rs = get_remote_state ();
c906108c 3572 int mask, length;
cfd77fa1 3573 int tag;
c906108c 3574 threadref ref;
cecb1912 3575 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
c906108c
SS
3576 int retval = 1;
3577
23860348 3578 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3579 info->active = 0;
3580 info->display[0] = '\0';
3581 info->shortname[0] = '\0';
3582 info->more_display[0] = '\0';
3583
23860348
MS
3584 /* Assume the characters indicating the packet type have been
3585 stripped. */
c906108c
SS
3586 pkt = unpack_int (pkt, &mask); /* arg mask */
3587 pkt = unpack_threadid (pkt, &ref);
3588
3589 if (mask == 0)
8a3fe4f8 3590 warning (_("Incomplete response to threadinfo request."));
c906108c 3591 if (!threadmatch (&ref, expectedref))
23860348 3592 { /* This is an answer to a different request. */
8a3fe4f8 3593 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3594 return 0;
3595 }
3596 copy_threadref (&info->threadid, &ref);
3597
405feb71 3598 /* Loop on tagged fields , try to bail if something goes wrong. */
c906108c 3599
23860348
MS
3600 /* Packets are terminated with nulls. */
3601 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3602 {
3603 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3604 pkt = unpack_byte (pkt, &length); /* length */
3605 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3606 {
8a3fe4f8 3607 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3608 retval = 0;
3609 break;
3610 }
3611 if (tag == TAG_THREADID)
3612 {
3613 if (length != 16)
3614 {
8a3fe4f8 3615 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3616 retval = 0;
3617 break;
3618 }
3619 pkt = unpack_threadid (pkt, &ref);
3620 mask = mask & ~TAG_THREADID;
3621 continue;
3622 }
3623 if (tag == TAG_EXISTS)
3624 {
3625 info->active = stub_unpack_int (pkt, length);
3626 pkt += length;
3627 mask = mask & ~(TAG_EXISTS);
3628 if (length > 8)
3629 {
8a3fe4f8 3630 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3631 retval = 0;
3632 break;
3633 }
3634 continue;
3635 }
3636 if (tag == TAG_THREADNAME)
3637 {
3638 pkt = unpack_string (pkt, &info->shortname[0], length);
3639 mask = mask & ~TAG_THREADNAME;
3640 continue;
3641 }
3642 if (tag == TAG_DISPLAY)
3643 {
3644 pkt = unpack_string (pkt, &info->display[0], length);
3645 mask = mask & ~TAG_DISPLAY;
3646 continue;
3647 }
3648 if (tag == TAG_MOREDISPLAY)
3649 {
3650 pkt = unpack_string (pkt, &info->more_display[0], length);
3651 mask = mask & ~TAG_MOREDISPLAY;
3652 continue;
3653 }
8a3fe4f8 3654 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3655 break; /* Not a tag we know about. */
c906108c
SS
3656 }
3657 return retval;
3658}
3659
6b8edb51
PA
3660int
3661remote_target::remote_get_threadinfo (threadref *threadid,
3662 int fieldset,
3663 gdb_ext_thread_info *info)
c906108c 3664{
d01949b6 3665 struct remote_state *rs = get_remote_state ();
c906108c 3666 int result;
c906108c 3667
8d64371b 3668 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
2e9f7625 3669 putpkt (rs->buf);
8d64371b 3670 getpkt (&rs->buf, 0);
3084dd77
PA
3671
3672 if (rs->buf[0] == '\0')
3673 return 0;
3674
8d64371b 3675 result = remote_unpack_thread_info_response (&rs->buf[2],
23860348 3676 threadid, info);
c906108c
SS
3677 return result;
3678}
3679
c906108c
SS
3680/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3681
3682static char *
fba45db2
KB
3683pack_threadlist_request (char *pkt, int startflag, int threadcount,
3684 threadref *nextthread)
c906108c
SS
3685{
3686 *pkt++ = 'q'; /* info query packet */
3687 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3688 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3689 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3690 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3691 *pkt = '\0';
3692 return pkt;
3693}
3694
3695/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3696
6b8edb51 3697int
cecb1912 3698remote_target::parse_threadlist_response (const char *pkt, int result_limit,
6b8edb51
PA
3699 threadref *original_echo,
3700 threadref *resultlist,
3701 int *doneflag)
c906108c 3702{
d01949b6 3703 struct remote_state *rs = get_remote_state ();
c906108c
SS
3704 int count, resultcount, done;
3705
3706 resultcount = 0;
3707 /* Assume the 'q' and 'M chars have been stripped. */
cecb1912 3708 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
23860348 3709 /* done parse past here */
c906108c
SS
3710 pkt = unpack_byte (pkt, &count); /* count field */
3711 pkt = unpack_nibble (pkt, &done);
3712 /* The first threadid is the argument threadid. */
3713 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3714 while ((count-- > 0) && (pkt < limit))
3715 {
3716 pkt = unpack_threadid (pkt, resultlist++);
3717 if (resultcount++ >= result_limit)
3718 break;
3719 }
3720 if (doneflag)
3721 *doneflag = done;
3722 return resultcount;
3723}
3724
6dc54d91
PA
3725/* Fetch the next batch of threads from the remote. Returns -1 if the
3726 qL packet is not supported, 0 on error and 1 on success. */
3727
6b8edb51
PA
3728int
3729remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3730 int result_limit, int *done, int *result_count,
3731 threadref *threadlist)
c906108c 3732{
d01949b6 3733 struct remote_state *rs = get_remote_state ();
c906108c
SS
3734 int result = 1;
3735
405feb71 3736 /* Truncate result limit to be smaller than the packet size. */
3e43a32a
MS
3737 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3738 >= get_remote_packet_size ())
ea9c271d 3739 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3740
8d64371b
TT
3741 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3742 nextthread);
6d820c5c 3743 putpkt (rs->buf);
8d64371b
TT
3744 getpkt (&rs->buf, 0);
3745 if (rs->buf[0] == '\0')
6dc54d91
PA
3746 {
3747 /* Packet not supported. */
3748 return -1;
3749 }
3750
3751 *result_count =
8d64371b 3752 parse_threadlist_response (&rs->buf[2], result_limit,
6dc54d91 3753 &rs->echo_nextthread, threadlist, done);
c906108c 3754
0d031856 3755 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3756 {
23860348 3757 /* FIXME: This is a good reason to drop the packet. */
405feb71
TV
3758 /* Possibly, there is a duplicate response. */
3759 /* Possibilities :
dda83cd7
SM
3760 retransmit immediatly - race conditions
3761 retransmit after timeout - yes
3762 exit
3763 wait for packet, then exit
c906108c 3764 */
8a3fe4f8 3765 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3766 return 0; /* I choose simply exiting. */
c906108c
SS
3767 }
3768 if (*result_count <= 0)
3769 {
3770 if (*done != 1)
3771 {
8a3fe4f8 3772 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3773 result = 0;
3774 }
3775 return result; /* break; */
3776 }
3777 if (*result_count > result_limit)
3778 {
3779 *result_count = 0;
8a3fe4f8 3780 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3781 return 0;
3782 }
3783 return result;
3784}
3785
6dc54d91
PA
3786/* Fetch the list of remote threads, with the qL packet, and call
3787 STEPFUNCTION for each thread found. Stops iterating and returns 1
3788 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3789 STEPFUNCTION returns false. If the packet is not supported,
3790 returns -1. */
c906108c 3791
6b8edb51
PA
3792int
3793remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3794 void *context, int looplimit)
c906108c 3795{
0d031856 3796 struct remote_state *rs = get_remote_state ();
c906108c
SS
3797 int done, i, result_count;
3798 int startflag = 1;
3799 int result = 1;
3800 int loopcount = 0;
c906108c
SS
3801
3802 done = 0;
3803 while (!done)
3804 {
3805 if (loopcount++ > looplimit)
3806 {
3807 result = 0;
8a3fe4f8 3808 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3809 break;
3810 }
6dc54d91
PA
3811 result = remote_get_threadlist (startflag, &rs->nextthread,
3812 MAXTHREADLISTRESULTS,
3813 &done, &result_count,
3814 rs->resultthreadlist);
3815 if (result <= 0)
3816 break;
23860348 3817 /* Clear for later iterations. */
c906108c
SS
3818 startflag = 0;
3819 /* Setup to resume next batch of thread references, set nextthread. */
3820 if (result_count >= 1)
0d031856
TT
3821 copy_threadref (&rs->nextthread,
3822 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3823 i = 0;
3824 while (result_count--)
6dc54d91
PA
3825 {
3826 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3827 {
3828 result = 0;
3829 break;
3830 }
3831 }
c906108c
SS
3832 }
3833 return result;
3834}
3835
6dc54d91
PA
3836/* A thread found on the remote target. */
3837
21fe1c75 3838struct thread_item
6dc54d91 3839{
21fe1c75
SM
3840 explicit thread_item (ptid_t ptid_)
3841 : ptid (ptid_)
3842 {}
3843
3844 thread_item (thread_item &&other) = default;
3845 thread_item &operator= (thread_item &&other) = default;
3846
3847 DISABLE_COPY_AND_ASSIGN (thread_item);
3848
6dc54d91
PA
3849 /* The thread's PTID. */
3850 ptid_t ptid;
3851
21fe1c75
SM
3852 /* The thread's extra info. */
3853 std::string extra;
6dc54d91 3854
21fe1c75
SM
3855 /* The thread's name. */
3856 std::string name;
79efa585 3857
6dc54d91 3858 /* The core the thread was running on. -1 if not known. */
21fe1c75 3859 int core = -1;
f6327dcb
KB
3860
3861 /* The thread handle associated with the thread. */
21fe1c75 3862 gdb::byte_vector thread_handle;
21fe1c75 3863};
6dc54d91
PA
3864
3865/* Context passed around to the various methods listing remote
3866 threads. As new threads are found, they're added to the ITEMS
3867 vector. */
3868
3869struct threads_listing_context
3870{
21fe1c75
SM
3871 /* Return true if this object contains an entry for a thread with ptid
3872 PTID. */
6dc54d91 3873
21fe1c75
SM
3874 bool contains_thread (ptid_t ptid) const
3875 {
3876 auto match_ptid = [&] (const thread_item &item)
3877 {
3878 return item.ptid == ptid;
3879 };
80134cf5 3880
21fe1c75
SM
3881 auto it = std::find_if (this->items.begin (),
3882 this->items.end (),
3883 match_ptid);
80134cf5 3884
21fe1c75
SM
3885 return it != this->items.end ();
3886 }
80134cf5 3887
21fe1c75 3888 /* Remove the thread with ptid PTID. */
80134cf5 3889
21fe1c75
SM
3890 void remove_thread (ptid_t ptid)
3891 {
3892 auto match_ptid = [&] (const thread_item &item)
3893 {
dda83cd7 3894 return item.ptid == ptid;
21fe1c75 3895 };
cbb8991c 3896
21fe1c75
SM
3897 auto it = std::remove_if (this->items.begin (),
3898 this->items.end (),
3899 match_ptid);
cbb8991c 3900
21fe1c75
SM
3901 if (it != this->items.end ())
3902 this->items.erase (it);
3903 }
3904
3905 /* The threads found on the remote target. */
3906 std::vector<thread_item> items;
3907};
cbb8991c 3908
c906108c 3909static int
6dc54d91 3910remote_newthread_step (threadref *ref, void *data)
c906108c 3911{
19ba03f4
SM
3912 struct threads_listing_context *context
3913 = (struct threads_listing_context *) data;
21fe1c75
SM
3914 int pid = inferior_ptid.pid ();
3915 int lwp = threadref_to_int (ref);
3916 ptid_t ptid (pid, lwp);
6dc54d91 3917
21fe1c75 3918 context->items.emplace_back (ptid);
6dc54d91 3919
c906108c
SS
3920 return 1; /* continue iterator */
3921}
3922
3923#define CRAZY_MAX_THREADS 1000
3924
6b8edb51
PA
3925ptid_t
3926remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3927{
d01949b6 3928 struct remote_state *rs = get_remote_state ();
c906108c
SS
3929
3930 putpkt ("qC");
8d64371b 3931 getpkt (&rs->buf, 0);
2e9f7625 3932 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3933 {
256642e8 3934 const char *obuf;
c9f35b34
KB
3935 ptid_t result;
3936
3937 result = read_ptid (&rs->buf[2], &obuf);
2189c312
SM
3938 if (*obuf != '\0')
3939 remote_debug_printf ("warning: garbage in qC reply");
c9f35b34
KB
3940
3941 return result;
3942 }
c906108c
SS
3943 else
3944 return oldpid;
3945}
3946
6dc54d91 3947/* List remote threads using the deprecated qL packet. */
cce74817 3948
6b8edb51
PA
3949int
3950remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3951{
6dc54d91
PA
3952 if (remote_threadlist_iterator (remote_newthread_step, context,
3953 CRAZY_MAX_THREADS) >= 0)
3954 return 1;
3955
3956 return 0;
c906108c
SS
3957}
3958
dc146f7c
VP
3959#if defined(HAVE_LIBEXPAT)
3960
dc146f7c
VP
3961static void
3962start_thread (struct gdb_xml_parser *parser,
3963 const struct gdb_xml_element *element,
4d0fdd9b
SM
3964 void *user_data,
3965 std::vector<gdb_xml_value> &attributes)
dc146f7c 3966{
19ba03f4
SM
3967 struct threads_listing_context *data
3968 = (struct threads_listing_context *) user_data;
3d2c1d41 3969 struct gdb_xml_value *attr;
dc146f7c 3970
4d0fdd9b 3971 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3972 ptid_t ptid = read_ptid (id, NULL);
3973
3974 data->items.emplace_back (ptid);
3975 thread_item &item = data->items.back ();
dc146f7c 3976
3d2c1d41
PA
3977 attr = xml_find_attribute (attributes, "core");
3978 if (attr != NULL)
4d0fdd9b 3979 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3980
79efa585 3981 attr = xml_find_attribute (attributes, "name");
21fe1c75 3982 if (attr != NULL)
4d0fdd9b 3983 item.name = (const char *) attr->value.get ();
79efa585 3984
f6327dcb
KB
3985 attr = xml_find_attribute (attributes, "handle");
3986 if (attr != NULL)
4d0fdd9b 3987 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3988}
3989
3990static void
3991end_thread (struct gdb_xml_parser *parser,
3992 const struct gdb_xml_element *element,
3993 void *user_data, const char *body_text)
3994{
19ba03f4
SM
3995 struct threads_listing_context *data
3996 = (struct threads_listing_context *) user_data;
dc146f7c 3997
21fe1c75
SM
3998 if (body_text != NULL && *body_text != '\0')
3999 data->items.back ().extra = body_text;
dc146f7c
VP
4000}
4001
4002const struct gdb_xml_attribute thread_attributes[] = {
4003 { "id", GDB_XML_AF_NONE, NULL, NULL },
4004 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 4005 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 4006 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
4007 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4008};
4009
4010const struct gdb_xml_element thread_children[] = {
4011 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4012};
4013
4014const struct gdb_xml_element threads_children[] = {
4015 { "thread", thread_attributes, thread_children,
4016 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4017 start_thread, end_thread },
4018 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4019};
4020
4021const struct gdb_xml_element threads_elements[] = {
4022 { "threads", NULL, threads_children,
4023 GDB_XML_EF_NONE, NULL, NULL },
4024 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4025};
4026
4027#endif
4028
6dc54d91 4029/* List remote threads using qXfer:threads:read. */
9d1f7ab2 4030
6b8edb51
PA
4031int
4032remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 4033{
dc146f7c 4034#if defined(HAVE_LIBEXPAT)
ff52c073 4035 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 4036 {
9018be22 4037 gdb::optional<gdb::char_vector> xml
6b8edb51 4038 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 4039
9018be22 4040 if (xml && (*xml)[0] != '\0')
dc146f7c 4041 {
6dc54d91 4042 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 4043 threads_elements, xml->data (), context);
dc146f7c
VP
4044 }
4045
6dc54d91 4046 return 1;
dc146f7c
VP
4047 }
4048#endif
4049
6dc54d91
PA
4050 return 0;
4051}
4052
4053/* List remote threads using qfThreadInfo/qsThreadInfo. */
4054
6b8edb51
PA
4055int
4056remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
4057{
4058 struct remote_state *rs = get_remote_state ();
4059
b80fafe3 4060 if (rs->use_threadinfo_query)
9d1f7ab2 4061 {
256642e8 4062 const char *bufp;
6dc54d91 4063
9d1f7ab2 4064 putpkt ("qfThreadInfo");
8d64371b
TT
4065 getpkt (&rs->buf, 0);
4066 bufp = rs->buf.data ();
9d1f7ab2 4067 if (bufp[0] != '\0') /* q packet recognized */
802188a7 4068 {
9d1f7ab2
MS
4069 while (*bufp++ == 'm') /* reply contains one or more TID */
4070 {
4071 do
4072 {
21fe1c75
SM
4073 ptid_t ptid = read_ptid (bufp, &bufp);
4074 context->items.emplace_back (ptid);
9d1f7ab2
MS
4075 }
4076 while (*bufp++ == ','); /* comma-separated list */
4077 putpkt ("qsThreadInfo");
8d64371b
TT
4078 getpkt (&rs->buf, 0);
4079 bufp = rs->buf.data ();
9d1f7ab2 4080 }
6dc54d91
PA
4081 return 1;
4082 }
4083 else
4084 {
4085 /* Packet not recognized. */
4086 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
4087 }
4088 }
4089
6dc54d91
PA
4090 return 0;
4091}
4092
a05575d3
TBA
4093/* Return true if INF only has one non-exited thread. */
4094
4095static bool
4096has_single_non_exited_thread (inferior *inf)
4097{
4098 int count = 0;
4099 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4100 if (++count > 1)
4101 break;
4102 return count == 1;
4103}
4104
e8032dde 4105/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
4106 targets. */
4107
f6ac5f3d
PA
4108void
4109remote_target::update_thread_list ()
6dc54d91 4110{
6dc54d91 4111 struct threads_listing_context context;
ab970af1 4112 int got_list = 0;
e8032dde 4113
6dc54d91
PA
4114 /* We have a few different mechanisms to fetch the thread list. Try
4115 them all, starting with the most preferred one first, falling
4116 back to older methods. */
6b8edb51
PA
4117 if (remote_get_threads_with_qxfer (&context)
4118 || remote_get_threads_with_qthreadinfo (&context)
4119 || remote_get_threads_with_ql (&context))
6dc54d91 4120 {
ab970af1
PA
4121 got_list = 1;
4122
21fe1c75 4123 if (context.items.empty ()
f6ac5f3d 4124 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
4125 {
4126 /* Some targets don't really support threads, but still
4127 reply an (empty) thread list in response to the thread
4128 listing packets, instead of replying "packet not
4129 supported". Exit early so we don't delete the main
4130 thread. */
7d1a114c
PA
4131 return;
4132 }
4133
ab970af1
PA
4134 /* CONTEXT now holds the current thread list on the remote
4135 target end. Delete GDB-side threads no longer found on the
4136 target. */
08036331 4137 for (thread_info *tp : all_threads_safe ())
cbb8991c 4138 {
5b6d1e4f
PA
4139 if (tp->inf->process_target () != this)
4140 continue;
4141
21fe1c75 4142 if (!context.contains_thread (tp->ptid))
ab970af1 4143 {
a05575d3
TBA
4144 /* Do not remove the thread if it is the last thread in
4145 the inferior. This situation happens when we have a
4146 pending exit process status to process. Otherwise we
4147 may end up with a seemingly live inferior (i.e. pid
4148 != 0) that has no threads. */
4149 if (has_single_non_exited_thread (tp->inf))
4150 continue;
4151
ab970af1 4152 /* Not found. */
00431a78 4153 delete_thread (tp);
ab970af1 4154 }
cbb8991c
DB
4155 }
4156
4157 /* Remove any unreported fork child threads from CONTEXT so
4158 that we don't interfere with follow fork, which is where
4159 creation of such threads is handled. */
4160 remove_new_fork_children (&context);
74531fed 4161
ab970af1 4162 /* And now add threads we don't know about yet to our list. */
21fe1c75 4163 for (thread_item &item : context.items)
6dc54d91 4164 {
21fe1c75 4165 if (item.ptid != null_ptid)
6dc54d91 4166 {
6dc54d91 4167 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
4168 executing until proven otherwise with a stop reply.
4169 In all-stop, we can only get here if all threads are
6dc54d91 4170 stopped. */
8a82de58 4171 bool executing = target_is_non_stop_p ();
6dc54d91 4172
21fe1c75 4173 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 4174
9213a6d7 4175 thread_info *tp = this->find_thread (item.ptid);
00431a78 4176 remote_thread_info *info = get_remote_thread_info (tp);
21fe1c75 4177 info->core = item.core;
7aabaf9d
SM
4178 info->extra = std::move (item.extra);
4179 info->name = std::move (item.name);
4180 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
4181 }
4182 }
4183 }
4184
ab970af1
PA
4185 if (!got_list)
4186 {
4187 /* If no thread listing method is supported, then query whether
4188 each known thread is alive, one by one, with the T packet.
4189 If the target doesn't support threads at all, then this is a
4190 no-op. See remote_thread_alive. */
4191 prune_threads ();
4192 }
9d1f7ab2
MS
4193}
4194
802188a7 4195/*
9d1f7ab2
MS
4196 * Collect a descriptive string about the given thread.
4197 * The target may say anything it wants to about the thread
4198 * (typically info about its blocked / runnable state, name, etc.).
4199 * This string will appear in the info threads display.
802188a7 4200 *
9d1f7ab2
MS
4201 * Optional: targets are not required to implement this function.
4202 */
4203
f6ac5f3d
PA
4204const char *
4205remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 4206{
d01949b6 4207 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
4208 int set;
4209 threadref id;
4210 struct gdb_ext_thread_info threadinfo;
9d1f7ab2 4211
5d93a237 4212 if (rs->remote_desc == 0) /* paranoia */
f34652de 4213 internal_error (_("remote_threads_extra_info"));
9d1f7ab2 4214
d7e15655 4215 if (tp->ptid == magic_null_ptid
e38504b3 4216 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
60e569b9
PA
4217 /* This is the main thread which was added by GDB. The remote
4218 server doesn't know about it. */
4219 return NULL;
4220
c76a8ea3
PA
4221 std::string &extra = get_remote_thread_info (tp)->extra;
4222
4223 /* If already have cached info, use it. */
4224 if (!extra.empty ())
4225 return extra.c_str ();
4226
ff52c073 4227 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 4228 {
c76a8ea3
PA
4229 /* If we're using qXfer:threads:read, then the extra info is
4230 included in the XML. So if we didn't have anything cached,
4231 it's because there's really no extra info. */
4232 return NULL;
dc146f7c
VP
4233 }
4234
b80fafe3 4235 if (rs->use_threadextra_query)
9d1f7ab2 4236 {
8d64371b
TT
4237 char *b = rs->buf.data ();
4238 char *endb = b + get_remote_packet_size ();
82f73884
PA
4239
4240 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4241 b += strlen (b);
4242 write_ptid (b, endb, tp->ptid);
4243
2e9f7625 4244 putpkt (rs->buf);
8d64371b 4245 getpkt (&rs->buf, 0);
2e9f7625 4246 if (rs->buf[0] != 0)
9d1f7ab2 4247 {
8d64371b
TT
4248 extra.resize (strlen (rs->buf.data ()) / 2);
4249 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
c76a8ea3 4250 return extra.c_str ();
9d1f7ab2 4251 }
0f71a2f6 4252 }
9d1f7ab2
MS
4253
4254 /* If the above query fails, fall back to the old method. */
b80fafe3 4255 rs->use_threadextra_query = 0;
9d1f7ab2
MS
4256 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4257 | TAG_MOREDISPLAY | TAG_DISPLAY;
e38504b3 4258 int_to_threadref (&id, tp->ptid.lwp ());
9d1f7ab2
MS
4259 if (remote_get_threadinfo (&id, set, &threadinfo))
4260 if (threadinfo.active)
0f71a2f6 4261 {
9d1f7ab2 4262 if (*threadinfo.shortname)
c76a8ea3 4263 string_appendf (extra, " Name: %s", threadinfo.shortname);
9d1f7ab2 4264 if (*threadinfo.display)
c76a8ea3
PA
4265 {
4266 if (!extra.empty ())
4267 extra += ',';
4268 string_appendf (extra, " State: %s", threadinfo.display);
4269 }
9d1f7ab2 4270 if (*threadinfo.more_display)
c5aa993b 4271 {
c76a8ea3
PA
4272 if (!extra.empty ())
4273 extra += ',';
4274 string_appendf (extra, " Priority: %s", threadinfo.more_display);
c5aa993b 4275 }
c76a8ea3 4276 return extra.c_str ();
0f71a2f6 4277 }
9d1f7ab2 4278 return NULL;
0f71a2f6 4279}
c906108c 4280\f
c5aa993b 4281
f6ac5f3d
PA
4282bool
4283remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4284 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
4285{
4286 struct remote_state *rs = get_remote_state ();
8d64371b 4287 char *p = rs->buf.data ();
0fb4aa4b 4288
bba74b36 4289 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
4290 p += strlen (p);
4291 p += hexnumstr (p, addr);
4292 putpkt (rs->buf);
8d64371b
TT
4293 getpkt (&rs->buf, 0);
4294 p = rs->buf.data ();
0fb4aa4b
PA
4295
4296 if (*p == 'E')
4297 error (_("Remote failure reply: %s"), p);
4298
4299 if (*p++ == 'm')
4300 {
256642e8 4301 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 4302 return true;
0fb4aa4b
PA
4303 }
4304
5d9310c4 4305 return false;
0fb4aa4b
PA
4306}
4307
f6ac5f3d
PA
4308std::vector<static_tracepoint_marker>
4309remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
4310{
4311 struct remote_state *rs = get_remote_state ();
5d9310c4 4312 std::vector<static_tracepoint_marker> markers;
256642e8 4313 const char *p;
5d9310c4 4314 static_tracepoint_marker marker;
0fb4aa4b
PA
4315
4316 /* Ask for a first packet of static tracepoint marker
4317 definition. */
4318 putpkt ("qTfSTM");
8d64371b
TT
4319 getpkt (&rs->buf, 0);
4320 p = rs->buf.data ();
0fb4aa4b
PA
4321 if (*p == 'E')
4322 error (_("Remote failure reply: %s"), p);
4323
0fb4aa4b
PA
4324 while (*p++ == 'm')
4325 {
0fb4aa4b
PA
4326 do
4327 {
5d9310c4 4328 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 4329
5d9310c4
SM
4330 if (strid == NULL || marker.str_id == strid)
4331 markers.push_back (std::move (marker));
0fb4aa4b
PA
4332 }
4333 while (*p++ == ','); /* comma-separated list */
4334 /* Ask for another packet of static tracepoint definition. */
4335 putpkt ("qTsSTM");
8d64371b
TT
4336 getpkt (&rs->buf, 0);
4337 p = rs->buf.data ();
0fb4aa4b
PA
4338 }
4339
0fb4aa4b
PA
4340 return markers;
4341}
4342
4343\f
10760264
JB
4344/* Implement the to_get_ada_task_ptid function for the remote targets. */
4345
f6ac5f3d 4346ptid_t
c80e29db 4347remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
10760264 4348{
184ea2f7 4349 return ptid_t (inferior_ptid.pid (), lwp);
10760264
JB
4350}
4351\f
4352
24b06219 4353/* Restart the remote side; this is an extended protocol operation. */
c906108c 4354
6b8edb51
PA
4355void
4356remote_target::extended_remote_restart ()
c906108c 4357{
d01949b6 4358 struct remote_state *rs = get_remote_state ();
c906108c
SS
4359
4360 /* Send the restart command; for reasons I don't understand the
4361 remote side really expects a number after the "R". */
8d64371b 4362 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
6d820c5c 4363 putpkt (rs->buf);
c906108c 4364
ad9a8f3f 4365 remote_fileio_reset ();
c906108c
SS
4366}
4367\f
4368/* Clean up connection to a remote debugger. */
4369
f6ac5f3d
PA
4370void
4371remote_target::close ()
c906108c 4372{
048094ac 4373 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4374 terminal_ours ();
ce5ce7ed 4375
6b8edb51
PA
4376 trace_reset_local_state ();
4377
4378 delete this;
4379}
4380
4381remote_target::~remote_target ()
4382{
4383 struct remote_state *rs = get_remote_state ();
4384
4385 /* Check for NULL because we may get here with a partially
4386 constructed target/connection. */
4387 if (rs->remote_desc == nullptr)
4388 return;
4389
4390 serial_close (rs->remote_desc);
4391
4392 /* We are destroying the remote target, so we should discard
f48ff2a7 4393 everything of this target. */
6b8edb51 4394 discard_pending_stop_replies_in_queue ();
74531fed 4395
6b8edb51
PA
4396 if (rs->remote_async_inferior_event_token)
4397 delete_async_event_handler (&rs->remote_async_inferior_event_token);
722247f1 4398
97dfbadd 4399 delete rs->notif_state;
c906108c
SS
4400}
4401
23860348 4402/* Query the remote side for the text, data and bss offsets. */
c906108c 4403
6b8edb51
PA
4404void
4405remote_target::get_offsets ()
c906108c 4406{
d01949b6 4407 struct remote_state *rs = get_remote_state ();
2e9f7625 4408 char *buf;
085dd6e6 4409 char *ptr;
31d99776
DJ
4410 int lose, num_segments = 0, do_sections, do_segments;
4411 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
31d99776 4412
a42d7dd8 4413 if (current_program_space->symfile_object_file == NULL)
31d99776 4414 return;
c906108c
SS
4415
4416 putpkt ("qOffsets");
8d64371b
TT
4417 getpkt (&rs->buf, 0);
4418 buf = rs->buf.data ();
c906108c
SS
4419
4420 if (buf[0] == '\000')
4421 return; /* Return silently. Stub doesn't support
23860348 4422 this command. */
c906108c
SS
4423 if (buf[0] == 'E')
4424 {
8a3fe4f8 4425 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4426 return;
4427 }
4428
4429 /* Pick up each field in turn. This used to be done with scanf, but
4430 scanf will make trouble if CORE_ADDR size doesn't match
4431 conversion directives correctly. The following code will work
4432 with any size of CORE_ADDR. */
4433 text_addr = data_addr = bss_addr = 0;
4434 ptr = buf;
4435 lose = 0;
4436
61012eef 4437 if (startswith (ptr, "Text="))
c906108c
SS
4438 {
4439 ptr += 5;
4440 /* Don't use strtol, could lose on big values. */
4441 while (*ptr && *ptr != ';')
4442 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4443
61012eef 4444 if (startswith (ptr, ";Data="))
31d99776
DJ
4445 {
4446 ptr += 6;
4447 while (*ptr && *ptr != ';')
4448 data_addr = (data_addr << 4) + fromhex (*ptr++);
4449 }
4450 else
4451 lose = 1;
4452
61012eef 4453 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4454 {
4455 ptr += 5;
4456 while (*ptr && *ptr != ';')
4457 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4458
31d99776
DJ
4459 if (bss_addr != data_addr)
4460 warning (_("Target reported unsupported offsets: %s"), buf);
4461 }
4462 else
4463 lose = 1;
4464 }
61012eef 4465 else if (startswith (ptr, "TextSeg="))
c906108c 4466 {
31d99776
DJ
4467 ptr += 8;
4468 /* Don't use strtol, could lose on big values. */
c906108c 4469 while (*ptr && *ptr != ';')
31d99776
DJ
4470 text_addr = (text_addr << 4) + fromhex (*ptr++);
4471 num_segments = 1;
4472
61012eef 4473 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4474 {
4475 ptr += 9;
4476 while (*ptr && *ptr != ';')
4477 data_addr = (data_addr << 4) + fromhex (*ptr++);
4478 num_segments++;
4479 }
c906108c
SS
4480 }
4481 else
4482 lose = 1;
4483
4484 if (lose)
8a3fe4f8 4485 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4486 else if (*ptr != '\0')
4487 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4488
a42d7dd8
TT
4489 objfile *objf = current_program_space->symfile_object_file;
4490 section_offsets offs = objf->section_offsets;
c906108c 4491
98badbfd 4492 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
31d99776
DJ
4493 do_segments = (data != NULL);
4494 do_sections = num_segments == 0;
c906108c 4495
28c32713 4496 if (num_segments > 0)
31d99776 4497 {
31d99776
DJ
4498 segments[0] = text_addr;
4499 segments[1] = data_addr;
4500 }
28c32713
JB
4501 /* If we have two segments, we can still try to relocate everything
4502 by assuming that the .text and .data offsets apply to the whole
4503 text and data segments. Convert the offsets given in the packet
4504 to base addresses for symfile_map_offsets_to_segments. */
68b888ff 4505 else if (data != nullptr && data->segments.size () == 2)
28c32713 4506 {
68b888ff
SM
4507 segments[0] = data->segments[0].base + text_addr;
4508 segments[1] = data->segments[1].base + data_addr;
28c32713
JB
4509 num_segments = 2;
4510 }
8d385431
DJ
4511 /* If the object file has only one segment, assume that it is text
4512 rather than data; main programs with no writable data are rare,
4513 but programs with no code are useless. Of course the code might
4514 have ended up in the data segment... to detect that we would need
4515 the permissions here. */
68b888ff 4516 else if (data && data->segments.size () == 1)
8d385431 4517 {
68b888ff 4518 segments[0] = data->segments[0].base + text_addr;
8d385431
DJ
4519 num_segments = 1;
4520 }
28c32713
JB
4521 /* There's no way to relocate by segment. */
4522 else
4523 do_segments = 0;
31d99776
DJ
4524
4525 if (do_segments)
4526 {
98badbfd 4527 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
62982abd
SM
4528 data.get (), offs,
4529 num_segments, segments);
31d99776
DJ
4530
4531 if (ret == 0 && !do_sections)
3e43a32a
MS
4532 error (_("Can not handle qOffsets TextSeg "
4533 "response with this symbol file"));
31d99776
DJ
4534
4535 if (ret > 0)
4536 do_sections = 0;
4537 }
c906108c 4538
31d99776
DJ
4539 if (do_sections)
4540 {
a42d7dd8 4541 offs[SECT_OFF_TEXT (objf)] = text_addr;
31d99776 4542
3e43a32a
MS
4543 /* This is a temporary kludge to force data and bss to use the
4544 same offsets because that's what nlmconv does now. The real
4545 solution requires changes to the stub and remote.c that I
4546 don't have time to do right now. */
31d99776 4547
a42d7dd8
TT
4548 offs[SECT_OFF_DATA (objf)] = data_addr;
4549 offs[SECT_OFF_BSS (objf)] = data_addr;
31d99776 4550 }
c906108c 4551
a42d7dd8 4552 objfile_relocate (objf, offs);
c906108c
SS
4553}
4554
9a7071a8 4555/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4556
4557void
4558remote_target::send_interrupt_sequence ()
9a7071a8 4559{
5d93a237
TT
4560 struct remote_state *rs = get_remote_state ();
4561
9a7071a8 4562 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4563 remote_serial_write ("\x03", 1);
9a7071a8 4564 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4565 serial_send_break (rs->remote_desc);
9a7071a8
JB
4566 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4567 {
5d93a237 4568 serial_send_break (rs->remote_desc);
c33e31fd 4569 remote_serial_write ("g", 1);
9a7071a8
JB
4570 }
4571 else
f34652de 4572 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
9a7071a8
JB
4573 interrupt_sequence_mode);
4574}
4575
3405876a
PA
4576
4577/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4578 and extract the PTID. Returns NULL_PTID if not found. */
4579
4580static ptid_t
e3b2741b 4581stop_reply_extract_thread (const char *stop_reply)
3405876a
PA
4582{
4583 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4584 {
256642e8 4585 const char *p;
3405876a
PA
4586
4587 /* Txx r:val ; r:val (...) */
4588 p = &stop_reply[3];
4589
4590 /* Look for "register" named "thread". */
4591 while (*p != '\0')
4592 {
256642e8 4593 const char *p1;
3405876a
PA
4594
4595 p1 = strchr (p, ':');
4596 if (p1 == NULL)
4597 return null_ptid;
4598
4599 if (strncmp (p, "thread", p1 - p) == 0)
4600 return read_ptid (++p1, &p);
4601
4602 p1 = strchr (p, ';');
4603 if (p1 == NULL)
4604 return null_ptid;
4605 p1++;
4606
4607 p = p1;
4608 }
4609 }
4610
4611 return null_ptid;
4612}
4613
b7ea362b
PA
4614/* Determine the remote side's current thread. If we have a stop
4615 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4616 "thread" register we can extract the current thread from. If not,
4617 ask the remote which is the current thread with qC. The former
4618 method avoids a roundtrip. */
4619
6b8edb51 4620ptid_t
e3b2741b 4621remote_target::get_current_thread (const char *wait_status)
b7ea362b 4622{
6a49a997 4623 ptid_t ptid = null_ptid;
b7ea362b
PA
4624
4625 /* Note we don't use remote_parse_stop_reply as that makes use of
4626 the target architecture, which we haven't yet fully determined at
4627 this point. */
4628 if (wait_status != NULL)
4629 ptid = stop_reply_extract_thread (wait_status);
d7e15655 4630 if (ptid == null_ptid)
b7ea362b
PA
4631 ptid = remote_current_thread (inferior_ptid);
4632
4633 return ptid;
4634}
4635
49c62f2e
PA
4636/* Query the remote target for which is the current thread/process,
4637 add it to our tables, and update INFERIOR_PTID. The caller is
4638 responsible for setting the state such that the remote end is ready
3405876a
PA
4639 to return the current thread.
4640
4641 This function is called after handling the '?' or 'vRun' packets,
4642 whose response is a stop reply from which we can also try
4643 extracting the thread. If the target doesn't support the explicit
4644 qC query, we infer the current thread from that stop reply, passed
64d38fdd 4645 in in WAIT_STATUS, which may be NULL.
49c62f2e 4646
64d38fdd
JM
4647 The function returns pointer to the main thread of the inferior. */
4648
4649thread_info *
e3b2741b 4650remote_target::add_current_inferior_and_thread (const char *wait_status)
49c62f2e 4651{
9ab8741a 4652 bool fake_pid_p = false;
49c62f2e 4653
0ac55310 4654 switch_to_no_thread ();
49c62f2e 4655
0ac55310
PA
4656 /* Now, if we have thread information, update the current thread's
4657 ptid. */
87215ad1 4658 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4659
87215ad1 4660 if (curr_ptid != null_ptid)
49c62f2e 4661 {
ff52c073 4662 if (!m_features.remote_multi_process_p ())
9ab8741a 4663 fake_pid_p = true;
49c62f2e
PA
4664 }
4665 else
4666 {
4667 /* Without this, some commands which require an active target
4668 (such as kill) won't work. This variable serves (at least)
4669 double duty as both the pid of the target process (if it has
4670 such), and as a flag indicating that a target is active. */
87215ad1 4671 curr_ptid = magic_null_ptid;
9ab8741a 4672 fake_pid_p = true;
49c62f2e
PA
4673 }
4674
e99b03dc 4675 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
49c62f2e 4676
87215ad1
SDJ
4677 /* Add the main thread and switch to it. Don't try reading
4678 registers yet, since we haven't fetched the target description
4679 yet. */
5b6d1e4f 4680 thread_info *tp = add_thread_silent (this, curr_ptid);
87215ad1 4681 switch_to_thread_no_regs (tp);
64d38fdd
JM
4682
4683 return tp;
49c62f2e
PA
4684}
4685
6efcd9a8
PA
4686/* Print info about a thread that was found already stopped on
4687 connection. */
4688
1edb66d8
SM
4689void
4690remote_target::print_one_stopped_thread (thread_info *thread)
6efcd9a8 4691{
1edb66d8
SM
4692 target_waitstatus ws;
4693
4694 /* If there is a pending waitstatus, use it. If there isn't it's because
4695 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4696 and process_initial_stop_replies decided it wasn't interesting to save
4697 and report to the core. */
4698 if (thread->has_pending_waitstatus ())
4699 {
4700 ws = thread->pending_waitstatus ();
4701 thread->clear_pending_waitstatus ();
4702 }
4703 else
4704 {
183be222 4705 ws.set_stopped (GDB_SIGNAL_0);
1edb66d8 4706 }
6efcd9a8 4707
00431a78 4708 switch_to_thread (thread);
1edb66d8 4709 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
6efcd9a8
PA
4710 set_current_sal_from_frame (get_current_frame ());
4711
1edb66d8
SM
4712 /* For "info program". */
4713 set_last_target_status (this, thread->ptid, ws);
6efcd9a8 4714
183be222 4715 if (ws.kind () == TARGET_WAITKIND_STOPPED)
6efcd9a8 4716 {
183be222 4717 enum gdb_signal sig = ws.sig ();
6efcd9a8
PA
4718
4719 if (signal_print_state (sig))
3f75a984 4720 notify_signal_received (sig);
6efcd9a8 4721 }
87829267
SM
4722
4723 notify_normal_stop (nullptr, 1);
6efcd9a8
PA
4724}
4725
221e1a37
PA
4726/* Process all initial stop replies the remote side sent in response
4727 to the ? packet. These indicate threads that were already stopped
4728 on initial connection. We mark these threads as stopped and print
4729 their current frame before giving the user the prompt. */
4730
6b8edb51
PA
4731void
4732remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4733{
4734 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4735 struct thread_info *selected = NULL;
4736 struct thread_info *lowest_stopped = NULL;
4737 struct thread_info *first = NULL;
221e1a37 4738
1edb66d8
SM
4739 /* This is only used when the target is non-stop. */
4740 gdb_assert (target_is_non_stop_p ());
4741
221e1a37
PA
4742 /* Consume the initial pending events. */
4743 while (pending_stop_replies-- > 0)
4744 {
4745 ptid_t waiton_ptid = minus_one_ptid;
4746 ptid_t event_ptid;
4747 struct target_waitstatus ws;
4748 int ignore_event = 0;
4749
221e1a37
PA
4750 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4751 if (remote_debug)
c272a98c 4752 print_target_wait_results (waiton_ptid, event_ptid, ws);
221e1a37 4753
183be222 4754 switch (ws.kind ())
221e1a37
PA
4755 {
4756 case TARGET_WAITKIND_IGNORE:
4757 case TARGET_WAITKIND_NO_RESUMED:
4758 case TARGET_WAITKIND_SIGNALLED:
4759 case TARGET_WAITKIND_EXITED:
4760 /* We shouldn't see these, but if we do, just ignore. */
2189c312 4761 remote_debug_printf ("event ignored");
221e1a37
PA
4762 ignore_event = 1;
4763 break;
4764
221e1a37
PA
4765 default:
4766 break;
4767 }
4768
4769 if (ignore_event)
4770 continue;
4771
9213a6d7 4772 thread_info *evthread = this->find_thread (event_ptid);
221e1a37 4773
183be222 4774 if (ws.kind () == TARGET_WAITKIND_STOPPED)
221e1a37 4775 {
183be222 4776 enum gdb_signal sig = ws.sig ();
221e1a37
PA
4777
4778 /* Stubs traditionally report SIGTRAP as initial signal,
4779 instead of signal 0. Suppress it. */
4780 if (sig == GDB_SIGNAL_TRAP)
4781 sig = GDB_SIGNAL_0;
1edb66d8 4782 evthread->set_stop_signal (sig);
183be222 4783 ws.set_stopped (sig);
6efcd9a8 4784 }
221e1a37 4785
183be222
SM
4786 if (ws.kind () != TARGET_WAITKIND_STOPPED
4787 || ws.sig () != GDB_SIGNAL_0)
1edb66d8 4788 evthread->set_pending_waitstatus (ws);
6efcd9a8 4789
719546c4
SM
4790 set_executing (this, event_ptid, false);
4791 set_running (this, event_ptid, false);
c9d22089 4792 get_remote_thread_info (evthread)->set_not_resumed ();
6efcd9a8
PA
4793 }
4794
4795 /* "Notice" the new inferiors before anything related to
4796 registers/memory. */
5b6d1e4f 4797 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4798 {
30220b46 4799 inf->needs_setup = true;
6efcd9a8
PA
4800
4801 if (non_stop)
4802 {
08036331 4803 thread_info *thread = any_live_thread_of_inferior (inf);
00431a78 4804 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
6efcd9a8
PA
4805 from_tty);
4806 }
4807 }
4808
4809 /* If all-stop on top of non-stop, pause all threads. Note this
4810 records the threads' stop pc, so must be done after "noticing"
4811 the inferiors. */
4812 if (!non_stop)
4813 {
abe8cab7
SM
4814 {
4815 /* At this point, the remote target is not async. It needs to be for
4816 the poll in stop_all_threads to consider events from it, so enable
4817 it temporarily. */
4818 gdb_assert (!this->is_async_p ());
4a570176
TT
4819 SCOPE_EXIT { target_async (false); };
4820 target_async (true);
4f5539f0 4821 stop_all_threads ("remote connect in all-stop");
abe8cab7 4822 }
6efcd9a8
PA
4823
4824 /* If all threads of an inferior were already stopped, we
4825 haven't setup the inferior yet. */
5b6d1e4f 4826 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4827 {
6efcd9a8
PA
4828 if (inf->needs_setup)
4829 {
08036331 4830 thread_info *thread = any_live_thread_of_inferior (inf);
6efcd9a8
PA
4831 switch_to_thread_no_regs (thread);
4832 setup_inferior (0);
4833 }
4834 }
221e1a37 4835 }
6efcd9a8
PA
4836
4837 /* Now go over all threads that are stopped, and print their current
4838 frame. If all-stop, then if there's a signalled thread, pick
4839 that as current. */
5b6d1e4f 4840 for (thread_info *thread : all_non_exited_threads (this))
6efcd9a8 4841 {
6efcd9a8
PA
4842 if (first == NULL)
4843 first = thread;
4844
4845 if (!non_stop)
00431a78 4846 thread->set_running (false);
6efcd9a8
PA
4847 else if (thread->state != THREAD_STOPPED)
4848 continue;
4849
1edb66d8 4850 if (selected == nullptr && thread->has_pending_waitstatus ())
6efcd9a8
PA
4851 selected = thread;
4852
5d5658a1
PA
4853 if (lowest_stopped == NULL
4854 || thread->inf->num < lowest_stopped->inf->num
4855 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4856 lowest_stopped = thread;
4857
4858 if (non_stop)
4859 print_one_stopped_thread (thread);
4860 }
4861
4862 /* In all-stop, we only print the status of one thread, and leave
4863 others with their status pending. */
4864 if (!non_stop)
4865 {
08036331 4866 thread_info *thread = selected;
6efcd9a8
PA
4867 if (thread == NULL)
4868 thread = lowest_stopped;
4869 if (thread == NULL)
4870 thread = first;
4871
4872 print_one_stopped_thread (thread);
4873 }
221e1a37
PA
4874}
4875
45664f16 4876/* Mark a remote_target as starting (by setting the starting_up flag within
7a34f66b
AB
4877 its remote_state) for the lifetime of this object. The reference count
4878 on the remote target is temporarily incremented, to prevent the target
4879 being deleted under our feet. */
4880
4881struct scoped_mark_target_starting
4882{
4883 /* Constructor, TARGET is the target to be marked as starting, its
4884 reference count will be incremented. */
4885 scoped_mark_target_starting (remote_target *target)
45664f16
AB
4886 : m_remote_target (remote_target_ref::new_reference (target)),
4887 m_restore_starting_up (set_starting_up_flag (target))
4888 { /* Nothing. */ }
4889
4890private:
7a34f66b 4891
45664f16
AB
4892 /* Helper function, set the starting_up flag on TARGET and return an
4893 object which, when it goes out of scope, will restore the previous
4894 value of the starting_up flag. */
4895 static scoped_restore_tmpl<bool>
4896 set_starting_up_flag (remote_target *target)
7a34f66b 4897 {
45664f16
AB
4898 remote_state *rs = target->get_remote_state ();
4899 gdb_assert (!rs->starting_up);
4900 return make_scoped_restore (&rs->starting_up, true);
7a34f66b
AB
4901 }
4902
45664f16
AB
4903 /* A gdb::ref_ptr pointer to a remote_target. */
4904 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4905
4906 /* A reference to the target on which we are operating. */
4907 remote_target_ref m_remote_target;
7a34f66b 4908
45664f16
AB
4909 /* An object which restores the previous value of the starting_up flag
4910 when it goes out of scope. */
4911 scoped_restore_tmpl<bool> m_restore_starting_up;
7a34f66b
AB
4912};
4913
288712bb
AB
4914/* Helper for remote_target::start_remote, start the remote connection and
4915 sync state. Return true if everything goes OK, otherwise, return false.
4916 This function exists so that the scoped_restore created within it will
4917 expire before we return to remote_target::start_remote. */
048094ac 4918
288712bb
AB
4919bool
4920remote_target::start_remote_1 (int from_tty, int extended_p)
c906108c 4921{
2189c312
SM
4922 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4923
c8d104ad 4924 struct remote_state *rs = get_remote_state ();
8621d6a9 4925
048094ac
PA
4926 /* Signal other parts that we're going through the initial setup,
4927 and so things may not be stable yet. E.g., we don't try to
4928 install tracepoints until we've relocated symbols. Also, a
4929 Ctrl-C before we're connected and synced up can't interrupt the
4930 target. Instead, it offers to drop the (potentially wedged)
4931 connection. */
7a34f66b 4932 scoped_mark_target_starting target_is_starting (this);
048094ac 4933
522002f9 4934 QUIT;
c906108c 4935
9a7071a8
JB
4936 if (interrupt_on_connect)
4937 send_interrupt_sequence ();
4938
57e12211 4939 /* Ack any packet which the remote side has already sent. */
048094ac 4940 remote_serial_write ("+", 1);
1e51243a 4941
c8d104ad
PA
4942 /* The first packet we send to the target is the optional "supported
4943 packets" request. If the target can answer this, it will tell us
4944 which later probes to skip. */
4945 remote_query_supported ();
4946
34f0de5a
CS
4947 /* Check vCont support and set the remote state's vCont_action_support
4948 attribute. */
4949 remote_vcont_probe ();
4950
d914c394 4951 /* If the stub wants to get a QAllow, compose one and send it. */
ff52c073 4952 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4953 set_permissions ();
d914c394 4954
57809e5e
JK
4955 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4956 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4957 as a reply to known packet. For packet "vFile:setfs:" it is an
4958 invalid reply and GDB would return error in
4959 remote_hostio_set_filesystem, making remote files access impossible.
4960 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4961 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4962 {
4963 const char v_mustreplyempty[] = "vMustReplyEmpty";
4964
4965 putpkt (v_mustreplyempty);
8d64371b
TT
4966 getpkt (&rs->buf, 0);
4967 if (strcmp (rs->buf.data (), "OK") == 0)
ff52c073
CS
4968 {
4969 m_features.m_protocol_packets[PACKET_vFile_setfs].support
4970 = PACKET_DISABLE;
4971 }
8d64371b 4972 else if (strcmp (rs->buf.data (), "") != 0)
57809e5e 4973 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
8d64371b 4974 rs->buf.data ());
57809e5e
JK
4975 }
4976
c8d104ad
PA
4977 /* Next, we possibly activate noack mode.
4978
4979 If the QStartNoAckMode packet configuration is set to AUTO,
4980 enable noack mode if the stub reported a wish for it with
4981 qSupported.
4982
4983 If set to TRUE, then enable noack mode even if the stub didn't
4984 report it in qSupported. If the stub doesn't reply OK, the
4985 session ends with an error.
4986
4987 If FALSE, then don't activate noack mode, regardless of what the
4988 stub claimed should be the default with qSupported. */
4989
ff52c073 4990 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
c8d104ad
PA
4991 {
4992 putpkt ("QStartNoAckMode");
8d64371b 4993 getpkt (&rs->buf, 0);
ff52c073 4994 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
c8d104ad
PA
4995 rs->noack_mode = 1;
4996 }
4997
04bd08de 4998 if (extended_p)
5fe04517
PA
4999 {
5000 /* Tell the remote that we are using the extended protocol. */
5001 putpkt ("!");
8d64371b 5002 getpkt (&rs->buf, 0);
5fe04517
PA
5003 }
5004
9b224c5e
PA
5005 /* Let the target know which signals it is allowed to pass down to
5006 the program. */
5007 update_signals_program_target ();
5008
d962ef82
DJ
5009 /* Next, if the target can specify a description, read it. We do
5010 this before anything involving memory or registers. */
5011 target_find_description ();
5012
6c95b8df
PA
5013 /* Next, now that we know something about the target, update the
5014 address spaces in the program spaces. */
5015 update_address_spaces ();
5016
50c71eaf
PA
5017 /* On OSs where the list of libraries is global to all
5018 processes, we fetch them early. */
f5656ead 5019 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 5020 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 5021
6efcd9a8 5022 if (target_is_non_stop_p ())
74531fed 5023 {
ff52c073 5024 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
5025 error (_("Non-stop mode requested, but remote "
5026 "does not support non-stop"));
74531fed
PA
5027
5028 putpkt ("QNonStop:1");
8d64371b 5029 getpkt (&rs->buf, 0);
74531fed 5030
8d64371b
TT
5031 if (strcmp (rs->buf.data (), "OK") != 0)
5032 error (_("Remote refused setting non-stop mode with: %s"),
5033 rs->buf.data ());
74531fed
PA
5034
5035 /* Find about threads and processes the stub is already
5036 controlling. We default to adding them in the running state.
5037 The '?' query below will then tell us about which threads are
5038 stopped. */
f6ac5f3d 5039 this->update_thread_list ();
74531fed 5040 }
ff52c073 5041 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
5042 {
5043 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 5044 Request it explicitly. */
74531fed 5045 putpkt ("QNonStop:0");
8d64371b 5046 getpkt (&rs->buf, 0);
74531fed 5047
8d64371b
TT
5048 if (strcmp (rs->buf.data (), "OK") != 0)
5049 error (_("Remote refused setting all-stop mode with: %s"),
5050 rs->buf.data ());
74531fed
PA
5051 }
5052
a0743c90
YQ
5053 /* Upload TSVs regardless of whether the target is running or not. The
5054 remote stub, such as GDBserver, may have some predefined or builtin
5055 TSVs, even if the target is not running. */
f6ac5f3d 5056 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
5057 {
5058 struct uploaded_tsv *uploaded_tsvs = NULL;
5059
f6ac5f3d 5060 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
5061 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5062 }
5063
2d717e4f
DJ
5064 /* Check whether the target is running now. */
5065 putpkt ("?");
8d64371b 5066 getpkt (&rs->buf, 0);
2d717e4f 5067
6efcd9a8 5068 if (!target_is_non_stop_p ())
2d717e4f 5069 {
b5c8f22d
SM
5070 char *wait_status = NULL;
5071
74531fed 5072 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 5073 {
04bd08de 5074 if (!extended_p)
74531fed 5075 error (_("The target is not running (try extended-remote?)"));
288712bb 5076 return false;
2d717e4f
DJ
5077 }
5078 else
74531fed 5079 {
74531fed 5080 /* Save the reply for later. */
8d64371b
TT
5081 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5082 strcpy (wait_status, rs->buf.data ());
74531fed
PA
5083 }
5084
b7ea362b 5085 /* Fetch thread list. */
e8032dde 5086 target_update_thread_list ();
b7ea362b 5087
74531fed
PA
5088 /* Let the stub know that we want it to return the thread. */
5089 set_continue_thread (minus_one_ptid);
5090
5b6d1e4f 5091 if (thread_count (this) == 0)
b7ea362b
PA
5092 {
5093 /* Target has no concept of threads at all. GDB treats
5094 non-threaded target as single-threaded; add a main
5095 thread. */
64d38fdd
JM
5096 thread_info *tp = add_current_inferior_and_thread (wait_status);
5097 get_remote_thread_info (tp)->set_resumed ();
b7ea362b
PA
5098 }
5099 else
5100 {
5101 /* We have thread information; select the thread the target
5102 says should be current. If we're reconnecting to a
5103 multi-threaded program, this will ideally be the thread
5104 that last reported an event before GDB disconnected. */
75c6c844
PA
5105 ptid_t curr_thread = get_current_thread (wait_status);
5106 if (curr_thread == null_ptid)
b7ea362b
PA
5107 {
5108 /* Odd... The target was able to list threads, but not
5109 tell us which thread was current (no "thread"
5110 register in T stop reply?). Just pick the first
5111 thread in the thread list then. */
2189c312
SM
5112
5113 remote_debug_printf ("warning: couldn't determine remote "
5114 "current thread; picking first in list.");
c9f35b34 5115
5b6d1e4f
PA
5116 for (thread_info *tp : all_non_exited_threads (this,
5117 minus_one_ptid))
75c6c844
PA
5118 {
5119 switch_to_thread (tp);
5120 break;
5121 }
b7ea362b 5122 }
75c6c844 5123 else
9213a6d7 5124 switch_to_thread (this->find_thread (curr_thread));
b7ea362b 5125 }
74531fed 5126
6e586cc5
YQ
5127 /* init_wait_for_inferior should be called before get_offsets in order
5128 to manage `inserted' flag in bp loc in a correct state.
5129 breakpoint_init_inferior, called from init_wait_for_inferior, set
5130 `inserted' flag to 0, while before breakpoint_re_set, called from
5131 start_remote, set `inserted' flag to 1. In the initialization of
5132 inferior, breakpoint_init_inferior should be called first, and then
5133 breakpoint_re_set can be called. If this order is broken, state of
5134 `inserted' flag is wrong, and cause some problems on breakpoint
5135 manipulation. */
5136 init_wait_for_inferior ();
5137
74531fed
PA
5138 get_offsets (); /* Get text, data & bss offsets. */
5139
d962ef82
DJ
5140 /* If we could not find a description using qXfer, and we know
5141 how to do it some other way, try again. This is not
5142 supported for non-stop; it could be, but it is tricky if
5143 there are no stopped threads when we connect. */
f6ac5f3d 5144 if (remote_read_description_p (this)
f5656ead 5145 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
5146 {
5147 target_clear_description ();
5148 target_find_description ();
5149 }
5150
74531fed
PA
5151 /* Use the previously fetched status. */
5152 gdb_assert (wait_status != NULL);
4f626cad
AB
5153 struct notif_event *reply
5154 = remote_notif_parse (this, &notif_client_stop, wait_status);
5155 push_stop_reply ((struct stop_reply *) reply);
74531fed 5156
f6ac5f3d 5157 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
5158 }
5159 else
5160 {
68c97600
PA
5161 /* Clear WFI global state. Do this before finding about new
5162 threads and inferiors, and setting the current inferior.
5163 Otherwise we would clear the proceed status of the current
5164 inferior when we want its stop_soon state to be preserved
5165 (see notice_new_inferior). */
5166 init_wait_for_inferior ();
5167
74531fed
PA
5168 /* In non-stop, we will either get an "OK", meaning that there
5169 are no stopped threads at this time; or, a regular stop
5170 reply. In the latter case, there may be more than one thread
5171 stopped --- we pull them all out using the vStopped
5172 mechanism. */
8d64371b 5173 if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 5174 {
42938c1a 5175 const notif_client *notif = &notif_client_stop;
2d717e4f 5176
722247f1
YQ
5177 /* remote_notif_get_pending_replies acks this one, and gets
5178 the rest out. */
f48ff2a7 5179 rs->notif_state->pending_event[notif_client_stop.id]
8d64371b 5180 = remote_notif_parse (this, notif, rs->buf.data ());
722247f1 5181 remote_notif_get_pending_events (notif);
74531fed 5182 }
2d717e4f 5183
5b6d1e4f 5184 if (thread_count (this) == 0)
74531fed 5185 {
04bd08de 5186 if (!extended_p)
74531fed 5187 error (_("The target is not running (try extended-remote?)"));
288712bb 5188 return false;
c35b1492 5189 }
74531fed 5190
2455069d 5191 /* Report all signals during attach/startup. */
adc6a863 5192 pass_signals ({});
221e1a37
PA
5193
5194 /* If there are already stopped threads, mark them stopped and
5195 report their stops before giving the prompt to the user. */
6efcd9a8 5196 process_initial_stop_replies (from_tty);
221e1a37
PA
5197
5198 if (target_can_async_p ())
4a570176 5199 target_async (true);
74531fed 5200 }
c8d104ad 5201
901e4e8d
SM
5202 /* Give the target a chance to look up symbols. */
5203 for (inferior *inf : all_inferiors (this))
c8d104ad 5204 {
901e4e8d
SM
5205 /* The inferiors that exist at this point were created from what
5206 was found already running on the remote side, so we know they
5207 have execution. */
5208 gdb_assert (this->has_execution (inf));
5209
a42d7dd8 5210 /* No use without a symbol-file. */
901e4e8d
SM
5211 if (inf->pspace->symfile_object_file == nullptr)
5212 continue;
5213
5214 /* Need to switch to a specific thread, because remote_check_symbols
287de656 5215 uses INFERIOR_PTID to set the general thread. */
901e4e8d
SM
5216 scoped_restore_current_thread restore_thread;
5217 thread_info *thread = any_thread_of_inferior (inf);
5218 switch_to_thread (thread);
5219 this->remote_check_symbols ();
c8d104ad 5220 }
50c71eaf 5221
d5551862
SS
5222 /* Possibly the target has been engaged in a trace run started
5223 previously; find out where things are at. */
f6ac5f3d 5224 if (get_trace_status (current_trace_status ()) != -1)
d5551862 5225 {
00bf0b85 5226 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 5227
00bf0b85 5228 if (current_trace_status ()->running)
6cb06a8c 5229 gdb_printf (_("Trace is already running on the target.\n"));
00bf0b85 5230
f6ac5f3d 5231 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
5232
5233 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
5234 }
5235
c0272db5
TW
5236 /* Possibly the target has been engaged in a btrace record started
5237 previously; find out where things are at. */
5238 remote_btrace_maybe_reopen ();
5239
288712bb
AB
5240 return true;
5241}
5242
5243/* Start the remote connection and sync state. */
1e51243a 5244
288712bb
AB
5245void
5246remote_target::start_remote (int from_tty, int extended_p)
5247{
5248 if (start_remote_1 (from_tty, extended_p)
5249 && breakpoints_should_be_inserted_now ())
50c71eaf 5250 insert_breakpoints ();
c906108c
SS
5251}
5252
121b3efd
PA
5253const char *
5254remote_target::connection_string ()
5255{
5256 remote_state *rs = get_remote_state ();
5257
5258 if (rs->remote_desc->name != NULL)
5259 return rs->remote_desc->name;
5260 else
5261 return NULL;
5262}
5263
c906108c
SS
5264/* Open a connection to a remote debugger.
5265 NAME is the filename used for communication. */
5266
f6ac5f3d
PA
5267void
5268remote_target::open (const char *name, int from_tty)
c906108c 5269{
f6ac5f3d 5270 open_1 (name, from_tty, 0);
43ff13b4
JM
5271}
5272
c906108c
SS
5273/* Open a connection to a remote debugger using the extended
5274 remote gdb protocol. NAME is the filename used for communication. */
5275
f6ac5f3d
PA
5276void
5277extended_remote_target::open (const char *name, int from_tty)
c906108c 5278{
f6ac5f3d 5279 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
5280}
5281
ff52c073
CS
5282void
5283remote_features::reset_all_packet_configs_support ()
d471ea57
AC
5284{
5285 int i;
a744cf53 5286
444abaca 5287 for (i = 0; i < PACKET_MAX; i++)
ff52c073 5288 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
5289}
5290
ca4f7f8b
PA
5291/* Initialize all packet configs. */
5292
5293static void
5294init_all_packet_configs (void)
5295{
5296 int i;
5297
5298 for (i = 0; i < PACKET_MAX; i++)
5299 {
5300 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5301 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5302 }
5303}
5304
23860348 5305/* Symbol look-up. */
dc8acb97 5306
6b8edb51
PA
5307void
5308remote_target::remote_check_symbols ()
dc8acb97 5309{
8d64371b 5310 char *tmp;
dc8acb97
MS
5311 int end;
5312
06c7226e
SM
5313 /* It doesn't make sense to send a qSymbol packet for an inferior that
5314 doesn't have execution, because the remote side doesn't know about
5315 inferiors without execution. */
5316 gdb_assert (target_has_execution ());
63154eca 5317
ff52c073 5318 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
5319 return;
5320
63154eca
PA
5321 /* Make sure the remote is pointing at the right process. Note
5322 there's no way to select "no process". */
3c9c4b83
PA
5323 set_general_process ();
5324
6d820c5c
DJ
5325 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5326 because we need both at the same time. */
66644cd3 5327 gdb::char_vector msg (get_remote_packet_size ());
8d64371b 5328 gdb::char_vector reply (get_remote_packet_size ());
6d820c5c 5329
23860348 5330 /* Invite target to request symbol lookups. */
dc8acb97
MS
5331
5332 putpkt ("qSymbol::");
8d64371b 5333 getpkt (&reply, 0);
ff52c073 5334 m_features.packet_ok (reply, PACKET_qSymbol);
dc8acb97 5335
8d64371b 5336 while (startswith (reply.data (), "qSymbol:"))
dc8acb97 5337 {
77e371c0
TT
5338 struct bound_minimal_symbol sym;
5339
dc8acb97 5340 tmp = &reply[8];
66644cd3
AB
5341 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5342 strlen (tmp) / 2);
dc8acb97 5343 msg[end] = '\0';
66644cd3 5344 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
3b7344d5 5345 if (sym.minsym == NULL)
66644cd3
AB
5346 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5347 &reply[8]);
dc8acb97 5348 else
2bbe3cc1 5349 {
f5656ead 5350 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4aeddc50 5351 CORE_ADDR sym_addr = sym.value_address ();
2bbe3cc1
DJ
5352
5353 /* If this is a function address, return the start of code
5354 instead of any data function descriptor. */
328d42d8
SM
5355 sym_addr = gdbarch_convert_from_func_ptr_addr
5356 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
2bbe3cc1 5357
66644cd3 5358 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 5359 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1 5360 }
66644cd3
AB
5361
5362 putpkt (msg.data ());
8d64371b 5363 getpkt (&reply, 0);
dc8acb97
MS
5364 }
5365}
5366
9db8d71f 5367static struct serial *
baa336ce 5368remote_serial_open (const char *name)
9db8d71f
DJ
5369{
5370 static int udp_warning = 0;
5371
5372 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5373 of in ser-tcp.c, because it is the remote protocol assuming that the
5374 serial connection is reliable and not the serial connection promising
5375 to be. */
61012eef 5376 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 5377 {
3e43a32a
MS
5378 warning (_("The remote protocol may be unreliable over UDP.\n"
5379 "Some events may be lost, rendering further debugging "
5380 "impossible."));
9db8d71f
DJ
5381 udp_warning = 1;
5382 }
5383
5384 return serial_open (name);
5385}
5386
d914c394
SS
5387/* Inform the target of our permission settings. The permission flags
5388 work without this, but if the target knows the settings, it can do
5389 a couple things. First, it can add its own check, to catch cases
5390 that somehow manage to get by the permissions checks in target
5391 methods. Second, if the target is wired to disallow particular
5392 settings (for instance, a system in the field that is not set up to
5393 be able to stop at a breakpoint), it can object to any unavailable
5394 permissions. */
5395
5396void
f6ac5f3d 5397remote_target::set_permissions ()
d914c394
SS
5398{
5399 struct remote_state *rs = get_remote_state ();
5400
8d64371b 5401 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
bba74b36
YQ
5402 "WriteReg:%x;WriteMem:%x;"
5403 "InsertBreak:%x;InsertTrace:%x;"
5404 "InsertFastTrace:%x;Stop:%x",
5405 may_write_registers, may_write_memory,
5406 may_insert_breakpoints, may_insert_tracepoints,
5407 may_insert_fast_tracepoints, may_stop);
d914c394 5408 putpkt (rs->buf);
8d64371b 5409 getpkt (&rs->buf, 0);
d914c394
SS
5410
5411 /* If the target didn't like the packet, warn the user. Do not try
5412 to undo the user's settings, that would just be maddening. */
8d64371b
TT
5413 if (strcmp (rs->buf.data (), "OK") != 0)
5414 warning (_("Remote refused setting permissions with: %s"),
5415 rs->buf.data ());
d914c394
SS
5416}
5417
be2a5f71
DJ
5418/* This type describes each known response to the qSupported
5419 packet. */
5420struct protocol_feature
5421{
5422 /* The name of this protocol feature. */
5423 const char *name;
5424
5425 /* The default for this protocol feature. */
5426 enum packet_support default_support;
5427
5428 /* The function to call when this feature is reported, or after
5429 qSupported processing if the feature is not supported.
5430 The first argument points to this structure. The second
5431 argument indicates whether the packet requested support be
5432 enabled, disabled, or probed (or the default, if this function
5433 is being called at the end of processing and this feature was
5434 not reported). The third argument may be NULL; if not NULL, it
5435 is a NUL-terminated string taken from the packet following
5436 this feature's name and an equals sign. */
6b8edb51
PA
5437 void (*func) (remote_target *remote, const struct protocol_feature *,
5438 enum packet_support, const char *);
be2a5f71
DJ
5439
5440 /* The corresponding packet for this feature. Only used if
5441 FUNC is remote_supported_packet. */
5442 int packet;
5443};
5444
be2a5f71 5445static void
6b8edb51
PA
5446remote_supported_packet (remote_target *remote,
5447 const struct protocol_feature *feature,
be2a5f71
DJ
5448 enum packet_support support,
5449 const char *argument)
5450{
5451 if (argument)
5452 {
5453 warning (_("Remote qSupported response supplied an unexpected value for"
5454 " \"%s\"."), feature->name);
5455 return;
5456 }
5457
ff52c073 5458 remote->m_features.m_protocol_packets[feature->packet].support = support;
be2a5f71 5459}
be2a5f71 5460
6b8edb51
PA
5461void
5462remote_target::remote_packet_size (const protocol_feature *feature,
5463 enum packet_support support, const char *value)
be2a5f71
DJ
5464{
5465 struct remote_state *rs = get_remote_state ();
5466
5467 int packet_size;
5468 char *value_end;
5469
5470 if (support != PACKET_ENABLE)
5471 return;
5472
5473 if (value == NULL || *value == '\0')
5474 {
5475 warning (_("Remote target reported \"%s\" without a size."),
5476 feature->name);
5477 return;
5478 }
5479
5480 errno = 0;
5481 packet_size = strtol (value, &value_end, 16);
5482 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5483 {
5484 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5485 feature->name, value);
5486 return;
5487 }
5488
be2a5f71
DJ
5489 /* Record the new maximum packet size. */
5490 rs->explicit_packet_size = packet_size;
5491}
5492
cb8c24b6 5493static void
6b8edb51
PA
5494remote_packet_size (remote_target *remote, const protocol_feature *feature,
5495 enum packet_support support, const char *value)
5496{
5497 remote->remote_packet_size (feature, support, value);
5498}
5499
dc473cfb 5500static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5501 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5502 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5503 PACKET_qXfer_auxv },
c78fa86a
GB
5504 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5505 PACKET_qXfer_exec_file },
23181151
DJ
5506 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5507 PACKET_qXfer_features },
cfa9d6d9
DJ
5508 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5509 PACKET_qXfer_libraries },
2268b414
JK
5510 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5511 PACKET_qXfer_libraries_svr4 },
ced63ec0 5512 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5513 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5514 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5515 PACKET_qXfer_memory_map },
07e059b5
VP
5516 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5517 PACKET_qXfer_osdata },
dc146f7c
VP
5518 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5519 PACKET_qXfer_threads },
b3b9301e
PA
5520 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5521 PACKET_qXfer_traceframe_info },
89be2091
DJ
5522 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5523 PACKET_QPassSignals },
82075af2
JS
5524 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5525 PACKET_QCatchSyscalls },
9b224c5e
PA
5526 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5527 PACKET_QProgramSignals },
bc3b087d
SDJ
5528 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5529 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5530 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5531 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5532 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5533 PACKET_QEnvironmentHexEncoded },
5534 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5535 PACKET_QEnvironmentReset },
5536 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5537 PACKET_QEnvironmentUnset },
a6f3e723
SL
5538 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5539 PACKET_QStartNoAckMode },
4082afcc
PA
5540 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5541 PACKET_multiprocess_feature },
5542 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5543 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5544 PACKET_qXfer_siginfo_read },
5545 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5546 PACKET_qXfer_siginfo_write },
4082afcc 5547 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5548 PACKET_ConditionalTracepoints },
4082afcc 5549 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5550 PACKET_ConditionalBreakpoints },
4082afcc 5551 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5552 PACKET_BreakpointCommands },
4082afcc 5553 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5554 PACKET_FastTracepoints },
4082afcc 5555 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5556 PACKET_StaticTracepoints },
4082afcc 5557 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5558 PACKET_InstallInTrace},
4082afcc
PA
5559 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5560 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5561 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5562 PACKET_bc },
5563 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5564 PACKET_bs },
409873ef
SS
5565 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5566 PACKET_TracepointSource },
d914c394
SS
5567 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5568 PACKET_QAllow },
4082afcc
PA
5569 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5570 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5571 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5572 PACKET_qXfer_fdpic },
169081d0
TG
5573 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5574 PACKET_qXfer_uib },
03583c20
UW
5575 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5576 PACKET_QDisableRandomization },
d1feda86 5577 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5578 { "QTBuffer:size", PACKET_DISABLE,
5579 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5580 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5581 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5582 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5583 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5584 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5585 PACKET_qXfer_btrace },
5586 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5587 PACKET_qXfer_btrace_conf },
5588 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5589 PACKET_Qbtrace_conf_bts_size },
5590 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5591 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5592 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5593 PACKET_fork_event_feature },
5594 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5595 PACKET_vfork_event_feature },
94585166
DB
5596 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5597 PACKET_exec_event_feature },
b20a6524 5598 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5599 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5600 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5601 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5602 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
2c2e7f87
LM
5603 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5604 PACKET_memory_tagging_feature },
be2a5f71
DJ
5605};
5606
c8d5aac9
L
5607static char *remote_support_xml;
5608
5609/* Register string appended to "xmlRegisters=" in qSupported query. */
5610
5611void
6e39997a 5612register_remote_support_xml (const char *xml)
c8d5aac9
L
5613{
5614#if defined(HAVE_LIBEXPAT)
5615 if (remote_support_xml == NULL)
c4f7c687 5616 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5617 else
5618 {
5619 char *copy = xstrdup (remote_support_xml + 13);
ca3a04f6
CB
5620 char *saveptr;
5621 char *p = strtok_r (copy, ",", &saveptr);
c8d5aac9
L
5622
5623 do
5624 {
5625 if (strcmp (p, xml) == 0)
5626 {
5627 /* already there */
5628 xfree (copy);
5629 return;
5630 }
5631 }
ca3a04f6 5632 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
c8d5aac9
L
5633 xfree (copy);
5634
94b0dee1
PA
5635 remote_support_xml = reconcat (remote_support_xml,
5636 remote_support_xml, ",", xml,
5637 (char *) NULL);
c8d5aac9
L
5638 }
5639#endif
5640}
5641
69b6ecb0
TT
5642static void
5643remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5644{
69b6ecb0
TT
5645 if (!msg->empty ())
5646 msg->append (";");
5647 msg->append (append);
c8d5aac9
L
5648}
5649
6b8edb51
PA
5650void
5651remote_target::remote_query_supported ()
be2a5f71
DJ
5652{
5653 struct remote_state *rs = get_remote_state ();
5654 char *next;
5655 int i;
5656 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5657
5658 /* The packet support flags are handled differently for this packet
5659 than for most others. We treat an error, a disabled packet, and
5660 an empty response identically: any features which must be reported
5661 to be used will be automatically disabled. An empty buffer
5662 accomplishes this, since that is also the representation for a list
5663 containing no features. */
5664
5665 rs->buf[0] = 0;
ff52c073 5666 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5667 {
69b6ecb0 5668 std::string q;
c8d5aac9 5669
ff52c073
CS
5670 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5671 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5672 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5673
ff52c073
CS
5674 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5675 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5676 remote_query_supported_append (&q, "swbreak+");
ff52c073
CS
5677
5678 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5679 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5680 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5681
69b6ecb0 5682 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5683
ff52c073 5684 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
8020350c 5685 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5686 remote_query_supported_append (&q, "fork-events+");
ff52c073
CS
5687
5688 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
8020350c 5689 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5690 remote_query_supported_append (&q, "vfork-events+");
ff52c073
CS
5691
5692 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
8020350c 5693 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5694 remote_query_supported_append (&q, "exec-events+");
89245bc0 5695
ff52c073
CS
5696 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5697 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5698 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5699
ff52c073
CS
5700 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5701 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5702 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5703
ff52c073
CS
5704 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5705 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5706 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5707
ff52c073 5708 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
2c2e7f87
LM
5709 != AUTO_BOOLEAN_FALSE)
5710 remote_query_supported_append (&q, "memory-tagging+");
5711
b35d5edb
PA
5712 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5713 the qSupported:xmlRegisters=i386 handling. */
7cc244de 5714 if (remote_support_xml != NULL
ff52c073
CS
5715 && (m_features.packet_support (PACKET_qXfer_features)
5716 != PACKET_DISABLE))
69b6ecb0 5717 remote_query_supported_append (&q, remote_support_xml);
82f73884 5718
69b6ecb0
TT
5719 q = "qSupported:" + q;
5720 putpkt (q.c_str ());
94b0dee1 5721
8d64371b 5722 getpkt (&rs->buf, 0);
be2a5f71 5723
33b5899f 5724 /* If an error occurred, warn, but do not return - just reset the
be2a5f71 5725 buffer to empty and go on to disable features. */
ff52c073 5726 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
be2a5f71 5727 {
8d64371b 5728 warning (_("Remote failure reply: %s"), rs->buf.data ());
be2a5f71
DJ
5729 rs->buf[0] = 0;
5730 }
5731 }
5732
5733 memset (seen, 0, sizeof (seen));
5734
8d64371b 5735 next = rs->buf.data ();
be2a5f71
DJ
5736 while (*next)
5737 {
5738 enum packet_support is_supported;
5739 char *p, *end, *name_end, *value;
5740
5741 /* First separate out this item from the rest of the packet. If
5742 there's another item after this, we overwrite the separator
5743 (terminated strings are much easier to work with). */
5744 p = next;
5745 end = strchr (p, ';');
5746 if (end == NULL)
5747 {
5748 end = p + strlen (p);
5749 next = end;
5750 }
5751 else
5752 {
89be2091
DJ
5753 *end = '\0';
5754 next = end + 1;
5755
be2a5f71
DJ
5756 if (end == p)
5757 {
5758 warning (_("empty item in \"qSupported\" response"));
5759 continue;
5760 }
be2a5f71
DJ
5761 }
5762
5763 name_end = strchr (p, '=');
5764 if (name_end)
5765 {
5766 /* This is a name=value entry. */
5767 is_supported = PACKET_ENABLE;
5768 value = name_end + 1;
5769 *name_end = '\0';
5770 }
5771 else
5772 {
5773 value = NULL;
5774 switch (end[-1])
5775 {
5776 case '+':
5777 is_supported = PACKET_ENABLE;
5778 break;
5779
5780 case '-':
5781 is_supported = PACKET_DISABLE;
5782 break;
5783
5784 case '?':
5785 is_supported = PACKET_SUPPORT_UNKNOWN;
5786 break;
5787
5788 default:
3e43a32a
MS
5789 warning (_("unrecognized item \"%s\" "
5790 "in \"qSupported\" response"), p);
be2a5f71
DJ
5791 continue;
5792 }
5793 end[-1] = '\0';
5794 }
5795
5796 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5797 if (strcmp (remote_protocol_features[i].name, p) == 0)
5798 {
5799 const struct protocol_feature *feature;
5800
5801 seen[i] = 1;
5802 feature = &remote_protocol_features[i];
6b8edb51 5803 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5804 break;
5805 }
5806 }
5807
5808 /* If we increased the packet size, make sure to increase the global
5809 buffer size also. We delay this until after parsing the entire
5810 qSupported packet, because this is the same buffer we were
5811 parsing. */
8d64371b
TT
5812 if (rs->buf.size () < rs->explicit_packet_size)
5813 rs->buf.resize (rs->explicit_packet_size);
be2a5f71
DJ
5814
5815 /* Handle the defaults for unmentioned features. */
5816 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5817 if (!seen[i])
5818 {
5819 const struct protocol_feature *feature;
5820
5821 feature = &remote_protocol_features[i];
6b8edb51 5822 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5823 }
5824}
5825
048094ac
PA
5826/* Serial QUIT handler for the remote serial descriptor.
5827
5828 Defers handling a Ctrl-C until we're done with the current
5829 command/response packet sequence, unless:
5830
5831 - We're setting up the connection. Don't send a remote interrupt
5832 request, as we're not fully synced yet. Quit immediately
5833 instead.
5834
5835 - The target has been resumed in the foreground
223ffa71 5836 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5837 packet, and we're blocked waiting for the stop reply, thus a
5838 Ctrl-C should be immediately sent to the target.
5839
5840 - We get a second Ctrl-C while still within the same serial read or
5841 write. In that case the serial is seemingly wedged --- offer to
5842 quit/disconnect.
5843
5844 - We see a second Ctrl-C without target response, after having
5845 previously interrupted the target. In that case the target/stub
5846 is probably wedged --- offer to quit/disconnect.
5847*/
5848
6b8edb51
PA
5849void
5850remote_target::remote_serial_quit_handler ()
048094ac
PA
5851{
5852 struct remote_state *rs = get_remote_state ();
5853
5854 if (check_quit_flag ())
5855 {
5856 /* If we're starting up, we're not fully synced yet. Quit
5857 immediately. */
5858 if (rs->starting_up)
5859 quit ();
5860 else if (rs->got_ctrlc_during_io)
5861 {
5862 if (query (_("The target is not responding to GDB commands.\n"
5863 "Stop debugging it? ")))
5b6d1e4f 5864 remote_unpush_and_throw (this);
048094ac
PA
5865 }
5866 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5867 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5868 interrupt_query ();
5869 /* All-stop protocol, and blocked waiting for stop reply. Send
5870 an interrupt request. */
223ffa71 5871 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5872 target_interrupt ();
048094ac
PA
5873 else
5874 rs->got_ctrlc_during_io = 1;
5875 }
5876}
5877
6b8edb51
PA
5878/* The remote_target that is current while the quit handler is
5879 overridden with remote_serial_quit_handler. */
5880static remote_target *curr_quit_handler_target;
5881
5882static void
5883remote_serial_quit_handler ()
5884{
5885 curr_quit_handler_target->remote_serial_quit_handler ();
5886}
5887
5b6d1e4f
PA
5888/* Remove the remote target from the target stack of each inferior
5889 that is using it. Upper targets depend on it so remove them
5890 first. */
78a095c3
JK
5891
5892static void
5b6d1e4f 5893remote_unpush_target (remote_target *target)
78a095c3 5894{
5b6d1e4f
PA
5895 /* We have to unpush the target from all inferiors, even those that
5896 aren't running. */
5897 scoped_restore_current_inferior restore_current_inferior;
5898
5899 for (inferior *inf : all_inferiors (target))
5900 {
5901 switch_to_inferior_no_thread (inf);
c8181f70 5902 inf->pop_all_targets_at_and_above (process_stratum);
5b6d1e4f
PA
5903 generic_mourn_inferior ();
5904 }
d7cb0ef3
PA
5905
5906 /* Don't rely on target_close doing this when the target is popped
5907 from the last remote inferior above, because something may be
5908 holding a reference to the target higher up on the stack, meaning
5909 target_close won't be called yet. We lost the connection to the
5910 target, so clear these now, otherwise we may later throw
5911 TARGET_CLOSE_ERROR while trying to tell the remote target to
5912 close the file. */
5913 fileio_handles_invalidate_target (target);
78a095c3 5914}
be2a5f71 5915
048094ac 5916static void
5b6d1e4f 5917remote_unpush_and_throw (remote_target *target)
048094ac 5918{
5b6d1e4f 5919 remote_unpush_target (target);
048094ac
PA
5920 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5921}
5922
f6ac5f3d
PA
5923void
5924remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5925{
6b8edb51 5926 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5927
c906108c 5928 if (name == 0)
8a3fe4f8 5929 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5930 "serial device is attached to the remote system\n"
8a3fe4f8 5931 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5932
2d717e4f 5933 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5934 Ask this question first, before target_preopen has a chance to kill
5935 anything. */
55f6301a 5936 if (curr_remote != NULL && !target_has_execution ())
2d717e4f 5937 {
78a095c3
JK
5938 if (from_tty
5939 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5940 error (_("Still connected."));
5941 }
5942
78a095c3 5943 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5944 target_preopen (from_tty);
5945
ad9a8f3f 5946 remote_fileio_reset ();
1dd41f16 5947 reopen_exec_file ();
9dec38d3 5948 reread_symbols (from_tty);
1dd41f16 5949
6b8edb51
PA
5950 remote_target *remote
5951 = (extended_p ? new extended_remote_target () : new remote_target ());
5952 target_ops_up target_holder (remote);
5953
5954 remote_state *rs = remote->get_remote_state ();
5955
5956 /* See FIXME above. */
5957 if (!target_async_permitted)
5958 rs->wait_forever_enabled_p = 1;
5959
5d93a237
TT
5960 rs->remote_desc = remote_serial_open (name);
5961 if (!rs->remote_desc)
c906108c
SS
5962 perror_with_name (name);
5963
5964 if (baud_rate != -1)
5965 {
5d93a237 5966 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5967 {
9b74d5d3
KB
5968 /* The requested speed could not be set. Error out to
5969 top level after closing remote_desc. Take care to
5970 set remote_desc to NULL to avoid closing remote_desc
5971 more than once. */
5d93a237
TT
5972 serial_close (rs->remote_desc);
5973 rs->remote_desc = NULL;
c906108c
SS
5974 perror_with_name (name);
5975 }
5976 }
5977
236af5e3 5978 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5979 serial_raw (rs->remote_desc);
c906108c
SS
5980
5981 /* If there is something sitting in the buffer we might take it as a
5982 response to a command, which would be bad. */
5d93a237 5983 serial_flush_input (rs->remote_desc);
c906108c
SS
5984
5985 if (from_tty)
5986 {
0426ad51
TT
5987 gdb_puts ("Remote debugging using ");
5988 gdb_puts (name);
5989 gdb_puts ("\n");
c906108c 5990 }
d9f719f1 5991
6b8edb51 5992 /* Switch to using the remote target now. */
02980c56 5993 current_inferior ()->push_target (std::move (target_holder));
c906108c 5994
74531fed 5995 /* Register extra event sources in the event loop. */
6b8edb51 5996 rs->remote_async_inferior_event_token
baa8575b 5997 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
db20ebdf 5998 "remote");
6b8edb51 5999 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 6000
be2a5f71
DJ
6001 /* Reset the target state; these things will be queried either by
6002 remote_query_supported or as they are needed. */
ff52c073 6003 remote->m_features.reset_all_packet_configs_support ();
be2a5f71 6004 rs->explicit_packet_size = 0;
a6f3e723 6005 rs->noack_mode = 0;
82f73884 6006 rs->extended = extended_p;
e24a49d8 6007 rs->waiting_for_stop_reply = 0;
3a29589a 6008 rs->ctrlc_pending_p = 0;
048094ac 6009 rs->got_ctrlc_during_io = 0;
802188a7 6010
47f8a51d
TT
6011 rs->general_thread = not_sent_ptid;
6012 rs->continue_thread = not_sent_ptid;
262e1174 6013 rs->remote_traceframe_number = -1;
c906108c 6014
3a00c802
PA
6015 rs->last_resume_exec_dir = EXEC_FORWARD;
6016
9d1f7ab2 6017 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
6018 rs->use_threadinfo_query = 1;
6019 rs->use_threadextra_query = 1;
9d1f7ab2 6020
dd194f6b 6021 rs->readahead_cache.invalidate ();
80152258 6022
c6ebd6cf 6023 if (target_async_permitted)
92d1e331 6024 {
92d1e331
DJ
6025 /* FIXME: cagney/1999-09-23: During the initial connection it is
6026 assumed that the target is already ready and able to respond to
0df8b418 6027 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 6028 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 6029 around this. Eventually a mechanism that allows
92d1e331 6030 wait_for_inferior() to expect/get timeouts will be
23860348 6031 implemented. */
6b8edb51 6032 rs->wait_forever_enabled_p = 0;
92d1e331
DJ
6033 }
6034
23860348 6035 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 6036 no_shared_libraries (NULL, 0);
f78f6cf1 6037
36918e70 6038 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
6039 target (we'd otherwise be in an inconsistent state) and then
6040 propogate the error on up the exception chain. This ensures that
6041 the caller doesn't stumble along blindly assuming that the
6042 function succeeded. The CLI doesn't have this problem but other
6043 UI's, such as MI do.
36918e70
AC
6044
6045 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6046 this function should return an error indication letting the
ce2826aa 6047 caller restore the previous state. Unfortunately the command
36918e70
AC
6048 ``target remote'' is directly wired to this function making that
6049 impossible. On a positive note, the CLI side of this problem has
6050 been fixed - the function set_cmd_context() makes it possible for
6051 all the ``target ....'' commands to share a common callback
6052 function. See cli-dump.c. */
109c3e39 6053 {
2d717e4f 6054
a70b8144 6055 try
04bd08de 6056 {
6b8edb51 6057 remote->start_remote (from_tty, extended_p);
04bd08de 6058 }
230d2906 6059 catch (const gdb_exception &ex)
109c3e39 6060 {
c8d104ad
PA
6061 /* Pop the partially set up target - unless something else did
6062 already before throwing the exception. */
6b8edb51 6063 if (ex.error != TARGET_CLOSE_ERROR)
5b6d1e4f 6064 remote_unpush_target (remote);
eedc3f4f 6065 throw;
109c3e39
AC
6066 }
6067 }
c906108c 6068
6b8edb51 6069 remote_btrace_reset (rs);
f4abbc16 6070
c6ebd6cf 6071 if (target_async_permitted)
6b8edb51 6072 rs->wait_forever_enabled_p = 1;
43ff13b4
JM
6073}
6074
28561a65 6075/* Determine if WS represents a fork status. */
a4543480 6076
28561a65
SM
6077static bool
6078is_fork_status (target_waitkind kind)
a4543480 6079{
28561a65
SM
6080 return (kind == TARGET_WAITKIND_FORKED
6081 || kind == TARGET_WAITKIND_VFORKED);
a4543480
SM
6082}
6083
28561a65
SM
6084/* Return THREAD's pending status if it is a pending fork parent, else
6085 return nullptr. */
a4543480 6086
28561a65 6087static const target_waitstatus *
a4543480
SM
6088thread_pending_fork_status (struct thread_info *thread)
6089{
28561a65
SM
6090 const target_waitstatus &ws
6091 = (thread->has_pending_waitstatus ()
6092 ? thread->pending_waitstatus ()
6093 : thread->pending_follow);
a4543480 6094
28561a65
SM
6095 if (!is_fork_status (ws.kind ()))
6096 return nullptr;
a4543480 6097
28561a65 6098 return &ws;
a4543480
SM
6099}
6100
de0d863e
DB
6101/* Detach the specified process. */
6102
6b8edb51
PA
6103void
6104remote_target::remote_detach_pid (int pid)
de0d863e
DB
6105{
6106 struct remote_state *rs = get_remote_state ();
6107
4c7333b3
PA
6108 /* This should not be necessary, but the handling for D;PID in
6109 GDBserver versions prior to 8.2 incorrectly assumes that the
6110 selected process points to the same process we're detaching,
6111 leading to misbehavior (and possibly GDBserver crashing) when it
6112 does not. Since it's easy and cheap, work around it by forcing
6113 GDBserver to select GDB's current process. */
6114 set_general_process ();
6115
ff52c073 6116 if (m_features.remote_multi_process_p ())
8d64371b 6117 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
de0d863e 6118 else
8d64371b 6119 strcpy (rs->buf.data (), "D");
de0d863e
DB
6120
6121 putpkt (rs->buf);
8d64371b 6122 getpkt (&rs->buf, 0);
de0d863e
DB
6123
6124 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6125 ;
6126 else if (rs->buf[0] == '\0')
6127 error (_("Remote doesn't know how to detach"));
6128 else
6129 error (_("Can't detach process."));
6130}
6131
6132/* This detaches a program to which we previously attached, using
6133 inferior_ptid to identify the process. After this is done, GDB
6134 can be used to debug some other program. We better not have left
6135 any breakpoints in the target program or it'll die when it hits
6136 one. */
c906108c 6137
6b8edb51 6138void
00431a78 6139remote_target::remote_detach_1 (inferior *inf, int from_tty)
c906108c 6140{
e99b03dc 6141 int pid = inferior_ptid.pid ();
d01949b6 6142 struct remote_state *rs = get_remote_state ();
de0d863e 6143 int is_fork_parent;
c906108c 6144
55f6301a 6145 if (!target_has_execution ())
2d717e4f
DJ
6146 error (_("No process to detach from."));
6147
0f48b757 6148 target_announce_detach (from_tty);
7cee1e54 6149
e87f0fe8
PA
6150 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
6151 {
6152 /* If we're in breakpoints-always-inserted mode, or the inferior
6153 is running, we have to remove breakpoints before detaching.
6154 We don't do this in common code instead because not all
6155 targets support removing breakpoints while the target is
6156 running. The remote target / gdbserver does, though. */
6157 remove_breakpoints_inf (current_inferior ());
6158 }
6159
c906108c 6160 /* Tell the remote target to detach. */
de0d863e 6161 remote_detach_pid (pid);
82f73884 6162
8020350c 6163 /* Exit only if this is the only active inferior. */
5b6d1e4f 6164 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
0426ad51 6165 gdb_puts (_("Ending remote debugging.\n"));
82f73884 6166
df5ad102
SM
6167 /* See if any thread of the inferior we are detaching has a pending fork
6168 status. In that case, we must detach from the child resulting from
6169 that fork. */
6170 for (thread_info *thread : inf->non_exited_threads ())
6171 {
6172 const target_waitstatus *ws = thread_pending_fork_status (thread);
6173
6174 if (ws == nullptr)
6175 continue;
6176
6177 remote_detach_pid (ws->child_ptid ().pid ());
6178 }
6179
6180 /* Check also for any pending fork events in the stop reply queue. */
6181 remote_notif_get_pending_events (&notif_client_stop);
6182 for (stop_reply_up &reply : rs->stop_reply_queue)
6183 {
6184 if (reply->ptid.pid () != pid)
6185 continue;
6186
6187 if (!is_fork_status (reply->ws.kind ()))
6188 continue;
6189
6190 remote_detach_pid (reply->ws.child_ptid ().pid ());
6191 }
6192
9213a6d7 6193 thread_info *tp = this->find_thread (inferior_ptid);
00431a78 6194
de0d863e
DB
6195 /* Check to see if we are detaching a fork parent. Note that if we
6196 are detaching a fork child, tp == NULL. */
6197 is_fork_parent = (tp != NULL
183be222 6198 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
de0d863e
DB
6199
6200 /* If doing detach-on-fork, we don't mourn, because that will delete
6201 breakpoints that should be available for the followed inferior. */
6202 if (!is_fork_parent)
f67c0c91 6203 {
249b5733
PA
6204 /* Save the pid as a string before mourning, since that will
6205 unpush the remote target, and we need the string after. */
f2907e49 6206 std::string infpid = target_pid_to_str (ptid_t (pid));
f67c0c91
SDJ
6207
6208 target_mourn_inferior (inferior_ptid);
6209 if (print_inferior_events)
6cb06a8c
TT
6210 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6211 inf->num, infpid.c_str ());
f67c0c91 6212 }
de0d863e
DB
6213 else
6214 {
0ac55310 6215 switch_to_no_thread ();
00431a78 6216 detach_inferior (current_inferior ());
de0d863e 6217 }
2d717e4f
DJ
6218}
6219
f6ac5f3d
PA
6220void
6221remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6222{
00431a78 6223 remote_detach_1 (inf, from_tty);
2d717e4f
DJ
6224}
6225
f6ac5f3d
PA
6226void
6227extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6228{
00431a78 6229 remote_detach_1 (inf, from_tty);
de0d863e
DB
6230}
6231
6232/* Target follow-fork function for remote targets. On entry, and
6233 at return, the current inferior is the fork parent.
6234
6235 Note that although this is currently only used for extended-remote,
6236 it is named remote_follow_fork in anticipation of using it for the
6237 remote target as well. */
6238
e97007b6 6239void
82d1f134
SM
6240remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6241 target_waitkind fork_kind, bool follow_child,
6242 bool detach_fork)
de0d863e 6243{
82d1f134
SM
6244 process_stratum_target::follow_fork (child_inf, child_ptid,
6245 fork_kind, follow_child, detach_fork);
6246
ff52c073
CS
6247 if ((fork_kind == TARGET_WAITKIND_FORKED
6248 && m_features.remote_fork_event_p ())
6249 || (fork_kind == TARGET_WAITKIND_VFORKED
6250 && m_features.remote_vfork_event_p ()))
de0d863e
DB
6251 {
6252 /* When following the parent and detaching the child, we detach
6253 the child here. For the case of following the child and
6254 detaching the parent, the detach is done in the target-
6255 independent follow fork code in infrun.c. We can't use
6256 target_detach when detaching an unfollowed child because
6257 the client side doesn't know anything about the child. */
6258 if (detach_fork && !follow_child)
6259 {
6260 /* Detach the fork child. */
3a849a34 6261 remote_detach_pid (child_ptid.pid ());
de0d863e
DB
6262 }
6263 }
c906108c
SS
6264}
6265
94585166 6266/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
294c36eb 6267 in the program space of the new inferior. */
94585166 6268
f6ac5f3d 6269void
294c36eb
SM
6270remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6271 const char *execd_pathname)
94585166 6272{
294c36eb
SM
6273 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6274
94585166
DB
6275 /* We know that this is a target file name, so if it has the "target:"
6276 prefix we strip it off before saving it in the program space. */
6277 if (is_target_filename (execd_pathname))
6278 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6279
294c36eb 6280 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
94585166
DB
6281}
6282
6ad8ae5c
DJ
6283/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6284
f6ac5f3d
PA
6285void
6286remote_target::disconnect (const char *args, int from_tty)
43ff13b4 6287{
43ff13b4 6288 if (args)
2d717e4f 6289 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 6290
8020350c 6291 /* Make sure we unpush even the extended remote targets. Calling
5b6d1e4f
PA
6292 target_mourn_inferior won't unpush, and
6293 remote_target::mourn_inferior won't unpush if there is more than
6294 one inferior left. */
6295 remote_unpush_target (this);
2d717e4f 6296
43ff13b4 6297 if (from_tty)
0426ad51 6298 gdb_puts ("Ending remote debugging.\n");
43ff13b4
JM
6299}
6300
2d717e4f
DJ
6301/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6302 be chatty about it. */
6303
f6ac5f3d
PA
6304void
6305extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
6306{
6307 struct remote_state *rs = get_remote_state ();
be86555c 6308 int pid;
96ef3384 6309 char *wait_status = NULL;
2d717e4f 6310
74164c56 6311 pid = parse_pid_to_attach (args);
2d717e4f 6312
74164c56
JK
6313 /* Remote PID can be freely equal to getpid, do not check it here the same
6314 way as in other targets. */
2d717e4f 6315
ff52c073 6316 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
6317 error (_("This target does not support attaching to a process"));
6318
bc521517 6319 target_announce_attach (from_tty, pid);
7cee1e54 6320
8d64371b 6321 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f 6322 putpkt (rs->buf);
8d64371b 6323 getpkt (&rs->buf, 0);
2d717e4f 6324
ff52c073 6325 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
2d717e4f 6326 {
4082afcc 6327 case PACKET_OK:
6efcd9a8 6328 if (!target_is_non_stop_p ())
74531fed
PA
6329 {
6330 /* Save the reply for later. */
8d64371b
TT
6331 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6332 strcpy (wait_status, rs->buf.data ());
74531fed 6333 }
8d64371b 6334 else if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 6335 error (_("Attaching to %s failed with: %s"),
a068643d 6336 target_pid_to_str (ptid_t (pid)).c_str (),
8d64371b 6337 rs->buf.data ());
4082afcc
PA
6338 break;
6339 case PACKET_UNKNOWN:
6340 error (_("This target does not support attaching to a process"));
6341 default:
50fa3001
SDJ
6342 error (_("Attaching to %s failed"),
6343 target_pid_to_str (ptid_t (pid)).c_str ());
2d717e4f 6344 }
2d717e4f 6345
0ac55310 6346 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
bad34192 6347
f2907e49 6348 inferior_ptid = ptid_t (pid);
79d7f229 6349
6efcd9a8 6350 if (target_is_non_stop_p ())
bad34192 6351 {
bad34192 6352 /* Get list of threads. */
f6ac5f3d 6353 update_thread_list ();
82f73884 6354
0ac55310
PA
6355 thread_info *thread = first_thread_of_inferior (current_inferior ());
6356 if (thread != nullptr)
6357 switch_to_thread (thread);
bad34192
PA
6358
6359 /* Invalidate our notion of the remote current thread. */
47f8a51d 6360 record_currthread (rs, minus_one_ptid);
bad34192 6361 }
74531fed 6362 else
bad34192 6363 {
0ac55310
PA
6364 /* Now, if we have thread information, update the main thread's
6365 ptid. */
6366 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
bad34192 6367
b622494e
AB
6368 /* Add the main thread to the thread list. We add the thread
6369 silently in this case (the final true parameter). */
6370 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
0ac55310
PA
6371
6372 switch_to_thread (thr);
bad34192 6373 }
c0a2216e 6374
96ef3384
UW
6375 /* Next, if the target can specify a description, read it. We do
6376 this before anything involving memory or registers. */
6377 target_find_description ();
6378
6efcd9a8 6379 if (!target_is_non_stop_p ())
74531fed
PA
6380 {
6381 /* Use the previously fetched status. */
6382 gdb_assert (wait_status != NULL);
6383
4f626cad
AB
6384 struct notif_event *reply
6385 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 6386
4f626cad 6387 push_stop_reply ((struct stop_reply *) reply);
74531fed
PA
6388 }
6389 else
621cc310
PA
6390 {
6391 gdb_assert (wait_status == NULL);
6392
6393 gdb_assert (target_can_async_p ());
621cc310 6394 }
2d717e4f
DJ
6395}
6396
b9c1d481
AS
6397/* Implementation of the to_post_attach method. */
6398
f6ac5f3d
PA
6399void
6400extended_remote_target::post_attach (int pid)
b9c1d481 6401{
6efcd9a8
PA
6402 /* Get text, data & bss offsets. */
6403 get_offsets ();
6404
b9c1d481
AS
6405 /* In certain cases GDB might not have had the chance to start
6406 symbol lookup up until now. This could happen if the debugged
6407 binary is not using shared libraries, the vsyscall page is not
6408 present (on Linux) and the binary itself hadn't changed since the
6409 debugging process was started. */
a42d7dd8 6410 if (current_program_space->symfile_object_file != NULL)
b9c1d481
AS
6411 remote_check_symbols();
6412}
6413
c906108c 6414\f
506fb367
DJ
6415/* Check for the availability of vCont. This function should also check
6416 the response. */
c906108c 6417
6b8edb51
PA
6418void
6419remote_target::remote_vcont_probe ()
c906108c 6420{
6b8edb51 6421 remote_state *rs = get_remote_state ();
2e9f7625 6422 char *buf;
6d820c5c 6423
8d64371b 6424 strcpy (rs->buf.data (), "vCont?");
2e9f7625 6425 putpkt (rs->buf);
8d64371b
TT
6426 getpkt (&rs->buf, 0);
6427 buf = rs->buf.data ();
c906108c 6428
506fb367 6429 /* Make sure that the features we assume are supported. */
61012eef 6430 if (startswith (buf, "vCont"))
506fb367
DJ
6431 {
6432 char *p = &buf[5];
750ce8d1 6433 int support_c, support_C;
506fb367 6434
750ce8d1
YQ
6435 rs->supports_vCont.s = 0;
6436 rs->supports_vCont.S = 0;
506fb367
DJ
6437 support_c = 0;
6438 support_C = 0;
d458bd84 6439 rs->supports_vCont.t = 0;
c1e36e3e 6440 rs->supports_vCont.r = 0;
506fb367
DJ
6441 while (p && *p == ';')
6442 {
6443 p++;
6444 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6445 rs->supports_vCont.s = 1;
506fb367 6446 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6447 rs->supports_vCont.S = 1;
506fb367
DJ
6448 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6449 support_c = 1;
6450 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6451 support_C = 1;
74531fed 6452 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 6453 rs->supports_vCont.t = 1;
c1e36e3e
PA
6454 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6455 rs->supports_vCont.r = 1;
506fb367
DJ
6456
6457 p = strchr (p, ';');
6458 }
c906108c 6459
750ce8d1
YQ
6460 /* If c, and C are not all supported, we can't use vCont. Clearing
6461 BUF will make packet_ok disable the packet. */
6462 if (!support_c || !support_C)
506fb367
DJ
6463 buf[0] = 0;
6464 }
c906108c 6465
ff52c073 6466 m_features.packet_ok (rs->buf, PACKET_vCont);
506fb367 6467}
c906108c 6468
0d8f58ca
PA
6469/* Helper function for building "vCont" resumptions. Write a
6470 resumption to P. ENDP points to one-passed-the-end of the buffer
6471 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6472 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6473 resumed thread should be single-stepped and/or signalled. If PTID
6474 equals minus_one_ptid, then all threads are resumed; if PTID
d51926f0
PA
6475 represents a process, then all threads of the process are
6476 resumed. */
0d8f58ca 6477
6b8edb51
PA
6478char *
6479remote_target::append_resumption (char *p, char *endp,
6480 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
6481{
6482 struct remote_state *rs = get_remote_state ();
6483
a493e3e2 6484 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 6485 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
6486 else if (step
6487 /* GDB is willing to range step. */
6488 && use_range_stepping
6489 /* Target supports range stepping. */
6490 && rs->supports_vCont.r
6491 /* We don't currently support range stepping multiple
6492 threads with a wildcard (though the protocol allows it,
6493 so stubs shouldn't make an active effort to forbid
6494 it). */
ff52c073 6495 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
c1e36e3e
PA
6496 {
6497 struct thread_info *tp;
6498
d7e15655 6499 if (ptid == minus_one_ptid)
c1e36e3e
PA
6500 {
6501 /* If we don't know about the target thread's tid, then
6502 we're resuming magic_null_ptid (see caller). */
9213a6d7 6503 tp = this->find_thread (magic_null_ptid);
c1e36e3e
PA
6504 }
6505 else
9213a6d7 6506 tp = this->find_thread (ptid);
c1e36e3e
PA
6507 gdb_assert (tp != NULL);
6508
6509 if (tp->control.may_range_step)
6510 {
6511 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6512
6513 p += xsnprintf (p, endp - p, ";r%s,%s",
6514 phex_nz (tp->control.step_range_start,
6515 addr_size),
6516 phex_nz (tp->control.step_range_end,
6517 addr_size));
6518 }
6519 else
6520 p += xsnprintf (p, endp - p, ";s");
6521 }
0d8f58ca
PA
6522 else if (step)
6523 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6524 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6525 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6526 else
6527 p += xsnprintf (p, endp - p, ";c");
6528
ff52c073 6529 if (m_features.remote_multi_process_p () && ptid.is_pid ())
0d8f58ca
PA
6530 {
6531 ptid_t nptid;
6532
6533 /* All (-1) threads of process. */
184ea2f7 6534 nptid = ptid_t (ptid.pid (), -1);
0d8f58ca
PA
6535
6536 p += xsnprintf (p, endp - p, ":");
6537 p = write_ptid (p, endp, nptid);
6538 }
d7e15655 6539 else if (ptid != minus_one_ptid)
0d8f58ca
PA
6540 {
6541 p += xsnprintf (p, endp - p, ":");
6542 p = write_ptid (p, endp, ptid);
6543 }
6544
6545 return p;
6546}
6547
799a2abe
PA
6548/* Clear the thread's private info on resume. */
6549
6550static void
6551resume_clear_thread_private_info (struct thread_info *thread)
6552{
6553 if (thread->priv != NULL)
6554 {
7aabaf9d
SM
6555 remote_thread_info *priv = get_remote_thread_info (thread);
6556
6557 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6558 priv->watch_data_address = 0;
799a2abe
PA
6559 }
6560}
6561
e5ef252a
PA
6562/* Append a vCont continue-with-signal action for threads that have a
6563 non-zero stop signal. */
6564
6b8edb51
PA
6565char *
6566remote_target::append_pending_thread_resumptions (char *p, char *endp,
6567 ptid_t ptid)
e5ef252a 6568{
5b6d1e4f 6569 for (thread_info *thread : all_non_exited_threads (this, ptid))
08036331 6570 if (inferior_ptid != thread->ptid
1edb66d8 6571 && thread->stop_signal () != GDB_SIGNAL_0)
e5ef252a
PA
6572 {
6573 p = append_resumption (p, endp, thread->ptid,
1edb66d8
SM
6574 0, thread->stop_signal ());
6575 thread->set_stop_signal (GDB_SIGNAL_0);
799a2abe 6576 resume_clear_thread_private_info (thread);
e5ef252a
PA
6577 }
6578
6579 return p;
6580}
6581
7b68ffbb
PA
6582/* Set the target running, using the packets that use Hc
6583 (c/s/C/S). */
6584
6b8edb51
PA
6585void
6586remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6587 gdb_signal siggnal)
7b68ffbb
PA
6588{
6589 struct remote_state *rs = get_remote_state ();
7b68ffbb
PA
6590 char *buf;
6591
6592 rs->last_sent_signal = siggnal;
6593 rs->last_sent_step = step;
6594
6595 /* The c/s/C/S resume packets use Hc, so set the continue
6596 thread. */
d7e15655 6597 if (ptid == minus_one_ptid)
7b68ffbb
PA
6598 set_continue_thread (any_thread_ptid);
6599 else
6600 set_continue_thread (ptid);
6601
5b6d1e4f 6602 for (thread_info *thread : all_non_exited_threads (this))
7b68ffbb
PA
6603 resume_clear_thread_private_info (thread);
6604
8d64371b 6605 buf = rs->buf.data ();
6b8edb51 6606 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6607 {
6608 /* We don't pass signals to the target in reverse exec mode. */
6609 if (info_verbose && siggnal != GDB_SIGNAL_0)
6610 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6611 siggnal);
6612
ff52c073 6613 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
7b68ffbb 6614 error (_("Remote reverse-step not supported."));
ff52c073 6615 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
7b68ffbb
PA
6616 error (_("Remote reverse-continue not supported."));
6617
6618 strcpy (buf, step ? "bs" : "bc");
6619 }
6620 else if (siggnal != GDB_SIGNAL_0)
6621 {
6622 buf[0] = step ? 'S' : 'C';
6623 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6624 buf[2] = tohex (((int) siggnal) & 0xf);
6625 buf[3] = '\0';
6626 }
6627 else
6628 strcpy (buf, step ? "s" : "c");
6629
6630 putpkt (buf);
6631}
6632
d51926f0
PA
6633/* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6634 STEP, and SIGGNAL have the same meaning as in target_resume. This
6635 function returns non-zero iff it resumes the inferior.
44eaed12 6636
7b68ffbb
PA
6637 This function issues a strict subset of all possible vCont commands
6638 at the moment. */
44eaed12 6639
6b8edb51 6640int
d51926f0 6641remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6b8edb51 6642 enum gdb_signal siggnal)
506fb367
DJ
6643{
6644 struct remote_state *rs = get_remote_state ();
82f73884
PA
6645 char *p;
6646 char *endp;
44eaed12 6647
7b68ffbb 6648 /* No reverse execution actions defined for vCont. */
6b8edb51 6649 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6650 return 0;
6651
ff52c073 6652 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6653 return 0;
44eaed12 6654
8d64371b
TT
6655 p = rs->buf.data ();
6656 endp = p + get_remote_packet_size ();
82f73884 6657
506fb367
DJ
6658 /* If we could generate a wider range of packets, we'd have to worry
6659 about overflowing BUF. Should there be a generic
6660 "multi-part-packet" packet? */
6661
0d8f58ca
PA
6662 p += xsnprintf (p, endp - p, "vCont");
6663
d51926f0 6664 if (scope_ptid == magic_null_ptid)
c906108c 6665 {
79d7f229
PA
6666 /* MAGIC_NULL_PTID means that we don't have any active threads,
6667 so we don't have any TID numbers the inferior will
6668 understand. Make sure to only send forms that do not specify
6669 a TID. */
a9cbf802 6670 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6671 }
d51926f0 6672 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
506fb367 6673 {
0d8f58ca
PA
6674 /* Resume all threads (of all processes, or of a single
6675 process), with preference for INFERIOR_PTID. This assumes
6676 inferior_ptid belongs to the set of all threads we are about
6677 to resume. */
a493e3e2 6678 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6679 {
0d8f58ca
PA
6680 /* Step inferior_ptid, with or without signal. */
6681 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6682 }
0d8f58ca 6683
e5ef252a
PA
6684 /* Also pass down any pending signaled resumption for other
6685 threads not the current. */
d51926f0 6686 p = append_pending_thread_resumptions (p, endp, scope_ptid);
e5ef252a 6687
0d8f58ca 6688 /* And continue others without a signal. */
d51926f0 6689 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6690 }
6691 else
506fb367 6692 {
d51926f0
PA
6693 /* Scheduler locking; resume only SCOPE_PTID. */
6694 append_resumption (p, endp, scope_ptid, step, siggnal);
506fb367 6695 }
c906108c 6696
8d64371b 6697 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
82f73884 6698 putpkt (rs->buf);
506fb367 6699
6efcd9a8 6700 if (target_is_non_stop_p ())
74531fed
PA
6701 {
6702 /* In non-stop, the stub replies to vCont with "OK". The stop
6703 reply will be reported asynchronously by means of a `%Stop'
6704 notification. */
8d64371b
TT
6705 getpkt (&rs->buf, 0);
6706 if (strcmp (rs->buf.data (), "OK") != 0)
6707 error (_("Unexpected vCont reply in non-stop mode: %s"),
6708 rs->buf.data ());
74531fed
PA
6709 }
6710
506fb367 6711 return 1;
c906108c 6712}
43ff13b4 6713
506fb367
DJ
6714/* Tell the remote machine to resume. */
6715
f6ac5f3d 6716void
d51926f0 6717remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
43ff13b4 6718{
d01949b6 6719 struct remote_state *rs = get_remote_state ();
43ff13b4 6720
85ad3aaf
PA
6721 /* When connected in non-stop mode, the core resumes threads
6722 individually. Resuming remote threads directly in target_resume
6723 would thus result in sending one packet per thread. Instead, to
6724 minimize roundtrip latency, here we just store the resume
c9d22089
SM
6725 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6726 resumption will be done in remote_target::commit_resume, where we'll be
6727 able to do vCont action coalescing. */
f6ac5f3d 6728 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6729 {
d51926f0
PA
6730 remote_thread_info *remote_thr
6731 = get_remote_thread_info (inferior_thread ());
7aabaf9d 6732
c9d22089 6733 /* We don't expect the core to ask to resume an already resumed (from
287de656 6734 its point of view) thread. */
a6c11cbb 6735 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
c9d22089
SM
6736
6737 remote_thr->set_resumed_pending_vcont (step, siggnal);
d51926f0
PA
6738
6739 /* There's actually nothing that says that the core can't
6740 request a wildcard resume in non-stop mode, though. It's
6741 just that we know it doesn't currently, so we don't bother
6742 with it. */
6743 gdb_assert (scope_ptid == inferior_ptid);
85ad3aaf
PA
6744 return;
6745 }
6746
722247f1
YQ
6747 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6748 (explained in remote-notif.c:handle_notification) so
6749 remote_notif_process is not called. We need find a place where
6750 it is safe to start a 'vNotif' sequence. It is good to do it
6751 before resuming inferior, because inferior was stopped and no RSP
6752 traffic at that moment. */
6efcd9a8 6753 if (!target_is_non_stop_p ())
5965e028 6754 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6755
f6ac5f3d 6756 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6757
7b68ffbb 6758 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
d51926f0
PA
6759 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6760 remote_resume_with_hc (scope_ptid, step, siggnal);
43ff13b4 6761
c9d22089 6762 /* Update resumed state tracked by the remote target. */
d51926f0 6763 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
c9d22089
SM
6764 get_remote_thread_info (tp)->set_resumed ();
6765
e24a49d8
PA
6766 /* We've just told the target to resume. The remote server will
6767 wait for the inferior to stop, and then send a stop reply. In
6768 the mean time, we can't start another command/query ourselves
74531fed
PA
6769 because the stub wouldn't be ready to process it. This applies
6770 only to the base all-stop protocol, however. In non-stop (which
6771 only supports vCont), the stub replies with an "OK", and is
6772 immediate able to process further serial input. */
6efcd9a8 6773 if (!target_is_non_stop_p ())
74531fed 6774 rs->waiting_for_stop_reply = 1;
43ff13b4 6775}
85ad3aaf 6776
85ad3aaf
PA
6777/* Private per-inferior info for target remote processes. */
6778
089354bb 6779struct remote_inferior : public private_inferior
85ad3aaf
PA
6780{
6781 /* Whether we can send a wildcard vCont for this process. */
089354bb 6782 bool may_wildcard_vcont = true;
85ad3aaf
PA
6783};
6784
089354bb
SM
6785/* Get the remote private inferior data associated to INF. */
6786
6787static remote_inferior *
6788get_remote_inferior (inferior *inf)
6789{
6790 if (inf->priv == NULL)
6791 inf->priv.reset (new remote_inferior);
6792
98ed24fb 6793 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
089354bb
SM
6794}
6795
f5db4863 6796/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6797 outgoing packet buffer. This is used to send multiple vCont
6798 packets if we have more actions than would fit a single packet. */
6799
f5db4863 6800class vcont_builder
85ad3aaf 6801{
f5db4863 6802public:
6b8edb51
PA
6803 explicit vcont_builder (remote_target *remote)
6804 : m_remote (remote)
f5db4863
PA
6805 {
6806 restart ();
6807 }
6808
6809 void flush ();
6810 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6811
6812private:
6813 void restart ();
6814
6b8edb51
PA
6815 /* The remote target. */
6816 remote_target *m_remote;
6817
85ad3aaf
PA
6818 /* Pointer to the first action. P points here if no action has been
6819 appended yet. */
f5db4863 6820 char *m_first_action;
85ad3aaf
PA
6821
6822 /* Where the next action will be appended. */
f5db4863 6823 char *m_p;
85ad3aaf
PA
6824
6825 /* The end of the buffer. Must never write past this. */
f5db4863 6826 char *m_endp;
85ad3aaf
PA
6827};
6828
6829/* Prepare the outgoing buffer for a new vCont packet. */
6830
f5db4863
PA
6831void
6832vcont_builder::restart ()
85ad3aaf 6833{
6b8edb51 6834 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6835
8d64371b
TT
6836 m_p = rs->buf.data ();
6837 m_endp = m_p + m_remote->get_remote_packet_size ();
f5db4863
PA
6838 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6839 m_first_action = m_p;
85ad3aaf
PA
6840}
6841
6842/* If the vCont packet being built has any action, send it to the
6843 remote end. */
6844
f5db4863
PA
6845void
6846vcont_builder::flush ()
85ad3aaf
PA
6847{
6848 struct remote_state *rs;
6849
f5db4863 6850 if (m_p == m_first_action)
85ad3aaf
PA
6851 return;
6852
6b8edb51
PA
6853 rs = m_remote->get_remote_state ();
6854 m_remote->putpkt (rs->buf);
8d64371b
TT
6855 m_remote->getpkt (&rs->buf, 0);
6856 if (strcmp (rs->buf.data (), "OK") != 0)
6857 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
85ad3aaf
PA
6858}
6859
6860/* The largest action is range-stepping, with its two addresses. This
6861 is more than sufficient. If a new, bigger action is created, it'll
6862 quickly trigger a failed assertion in append_resumption (and we'll
6863 just bump this). */
6864#define MAX_ACTION_SIZE 200
6865
6866/* Append a new vCont action in the outgoing packet being built. If
6867 the action doesn't fit the packet along with previous actions, push
6868 what we've got so far to the remote end and start over a new vCont
6869 packet (with the new action). */
6870
f5db4863
PA
6871void
6872vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6873{
6874 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6875
6b8edb51
PA
6876 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6877 ptid, step, siggnal);
85ad3aaf
PA
6878
6879 /* Check whether this new action would fit in the vCont packet along
6880 with previous actions. If not, send what we've got so far and
6881 start a new vCont packet. */
f5db4863
PA
6882 size_t rsize = endp - buf;
6883 if (rsize > m_endp - m_p)
85ad3aaf 6884 {
f5db4863
PA
6885 flush ();
6886 restart ();
85ad3aaf
PA
6887
6888 /* Should now fit. */
f5db4863 6889 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6890 }
6891
f5db4863
PA
6892 memcpy (m_p, buf, rsize);
6893 m_p += rsize;
6894 *m_p = '\0';
85ad3aaf
PA
6895}
6896
6897/* to_commit_resume implementation. */
6898
f6ac5f3d 6899void
1192f124 6900remote_target::commit_resumed ()
85ad3aaf 6901{
85ad3aaf
PA
6902 /* If connected in all-stop mode, we'd send the remote resume
6903 request directly from remote_resume. Likewise if
6904 reverse-debugging, as there are no defined vCont actions for
6905 reverse execution. */
f6ac5f3d 6906 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6907 return;
6908
6909 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6910 instead of resuming all threads of each process individually.
6911 However, if any thread of a process must remain halted, we can't
6912 send wildcard resumes and must send one action per thread.
6913
6914 Care must be taken to not resume threads/processes the server
6915 side already told us are stopped, but the core doesn't know about
6916 yet, because the events are still in the vStopped notification
6917 queue. For example:
6918
6919 #1 => vCont s:p1.1;c
6920 #2 <= OK
6921 #3 <= %Stopped T05 p1.1
6922 #4 => vStopped
6923 #5 <= T05 p1.2
6924 #6 => vStopped
6925 #7 <= OK
6926 #8 (infrun handles the stop for p1.1 and continues stepping)
6927 #9 => vCont s:p1.1;c
6928
6929 The last vCont above would resume thread p1.2 by mistake, because
6930 the server has no idea that the event for p1.2 had not been
6931 handled yet.
6932
6933 The server side must similarly ignore resume actions for the
6934 thread that has a pending %Stopped notification (and any other
6935 threads with events pending), until GDB acks the notification
6936 with vStopped. Otherwise, e.g., the following case is
6937 mishandled:
6938
6939 #1 => g (or any other packet)
6940 #2 <= [registers]
6941 #3 <= %Stopped T05 p1.2
6942 #4 => vCont s:p1.1;c
6943 #5 <= OK
6944
6945 Above, the server must not resume thread p1.2. GDB can't know
6946 that p1.2 stopped until it acks the %Stopped notification, and
6947 since from GDB's perspective all threads should be running, it
6948 sends a "c" action.
6949
6950 Finally, special care must also be given to handling fork/vfork
6951 events. A (v)fork event actually tells us that two processes
6952 stopped -- the parent and the child. Until we follow the fork,
6953 we must not resume the child. Therefore, if we have a pending
6954 fork follow, we must not send a global wildcard resume action
6955 (vCont;c). We can still send process-wide wildcards though. */
6956
6957 /* Start by assuming a global wildcard (vCont;c) is possible. */
2f63ec5c 6958 bool may_global_wildcard_vcont = true;
85ad3aaf
PA
6959
6960 /* And assume every process is individually wildcard-able too. */
5b6d1e4f 6961 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6962 {
089354bb
SM
6963 remote_inferior *priv = get_remote_inferior (inf);
6964
6965 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6966 }
6967
6968 /* Check for any pending events (not reported or processed yet) and
6969 disable process and global wildcard resumes appropriately. */
6970 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6971
1192f124
SM
6972 bool any_pending_vcont_resume = false;
6973
5b6d1e4f 6974 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 6975 {
c9d22089
SM
6976 remote_thread_info *priv = get_remote_thread_info (tp);
6977
85ad3aaf
PA
6978 /* If a thread of a process is not meant to be resumed, then we
6979 can't wildcard that process. */
a6c11cbb 6980 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
85ad3aaf 6981 {
089354bb 6982 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6983
6984 /* And if we can't wildcard a process, we can't wildcard
6985 everything either. */
2f63ec5c 6986 may_global_wildcard_vcont = false;
85ad3aaf
PA
6987 continue;
6988 }
6989
1192f124
SM
6990 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6991 any_pending_vcont_resume = true;
6992
85ad3aaf
PA
6993 /* If a thread is the parent of an unfollowed fork, then we
6994 can't do a global wildcard, as that would resume the fork
6995 child. */
28561a65 6996 if (thread_pending_fork_status (tp) != nullptr)
2f63ec5c 6997 may_global_wildcard_vcont = false;
85ad3aaf
PA
6998 }
6999
1192f124
SM
7000 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7001 do. */
7002 if (!any_pending_vcont_resume)
7003 return;
7004
85ad3aaf
PA
7005 /* Now let's build the vCont packet(s). Actions must be appended
7006 from narrower to wider scopes (thread -> process -> global). If
7007 we end up with too many actions for a single packet vcont_builder
7008 flushes the current vCont packet to the remote side and starts a
7009 new one. */
6b8edb51 7010 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
7011
7012 /* Threads first. */
5b6d1e4f 7013 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 7014 {
7aabaf9d 7015 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf 7016
c9d22089
SM
7017 /* If the thread was previously vCont-resumed, no need to send a specific
7018 action for it. If we didn't receive a resume request for it, don't
7019 send an action for it either. */
a6c11cbb 7020 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
85ad3aaf
PA
7021 continue;
7022
7023 gdb_assert (!thread_is_in_step_over_chain (tp));
7024
1192f124 7025 /* We should never be commit-resuming a thread that has a stop reply.
287de656 7026 Otherwise, we would end up reporting a stop event for a thread while
1192f124
SM
7027 it is running on the remote target. */
7028 remote_state *rs = get_remote_state ();
7029 for (const auto &stop_reply : rs->stop_reply_queue)
7030 gdb_assert (stop_reply->ptid != tp->ptid);
7031
c9d22089
SM
7032 const resumed_pending_vcont_info &info
7033 = remote_thr->resumed_pending_vcont_info ();
85ad3aaf 7034
c9d22089 7035 /* Check if we need to send a specific action for this thread. If not,
287de656 7036 it will be included in a wildcard resume instead. */
c9d22089
SM
7037 if (info.step || info.sig != GDB_SIGNAL_0
7038 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7039 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7040
7041 remote_thr->set_resumed ();
85ad3aaf
PA
7042 }
7043
7044 /* Now check whether we can send any process-wide wildcard. This is
7045 to avoid sending a global wildcard in the case nothing is
7046 supposed to be resumed. */
2f63ec5c 7047 bool any_process_wildcard = false;
85ad3aaf 7048
5b6d1e4f 7049 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 7050 {
089354bb 7051 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 7052 {
2f63ec5c 7053 any_process_wildcard = true;
85ad3aaf
PA
7054 break;
7055 }
7056 }
7057
7058 if (any_process_wildcard)
7059 {
7060 /* If all processes are wildcard-able, then send a single "c"
7061 action, otherwise, send an "all (-1) threads of process"
7062 continue action for each running process, if any. */
7063 if (may_global_wildcard_vcont)
7064 {
f5db4863
PA
7065 vcont_builder.push_action (minus_one_ptid,
7066 false, GDB_SIGNAL_0);
85ad3aaf
PA
7067 }
7068 else
7069 {
5b6d1e4f 7070 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 7071 {
089354bb 7072 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 7073 {
f2907e49 7074 vcont_builder.push_action (ptid_t (inf->pid),
f5db4863 7075 false, GDB_SIGNAL_0);
85ad3aaf
PA
7076 }
7077 }
7078 }
7079 }
7080
f5db4863 7081 vcont_builder.flush ();
85ad3aaf
PA
7082}
7083
b4b1a226
SM
7084/* Implementation of target_has_pending_events. */
7085
7086bool
7087remote_target::has_pending_events ()
7088{
7089 if (target_can_async_p ())
7090 {
7091 remote_state *rs = get_remote_state ();
7092
7093 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
7094 return true;
7095
7096 /* Note that BUFCNT can be negative, indicating sticky
7097 error. */
7098 if (rs->remote_desc->bufcnt != 0)
7099 return true;
7100 }
7101 return false;
7102}
7103
c906108c 7104\f
43ff13b4 7105
74531fed
PA
7106/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7107 thread, all threads of a remote process, or all threads of all
7108 processes. */
7109
6b8edb51
PA
7110void
7111remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
7112{
7113 struct remote_state *rs = get_remote_state ();
8d64371b
TT
7114 char *p = rs->buf.data ();
7115 char *endp = p + get_remote_packet_size ();
74531fed 7116
1192f124
SM
7117 /* If any thread that needs to stop was resumed but pending a vCont
7118 resume, generate a phony stop_reply. However, first check
7119 whether the thread wasn't resumed with a signal. Generating a
7120 phony stop in that case would result in losing the signal. */
7121 bool needs_commit = false;
7122 for (thread_info *tp : all_non_exited_threads (this, ptid))
7123 {
7124 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7125
7126 if (remote_thr->get_resume_state ()
7127 == resume_state::RESUMED_PENDING_VCONT)
7128 {
7129 const resumed_pending_vcont_info &info
7130 = remote_thr->resumed_pending_vcont_info ();
7131 if (info.sig != GDB_SIGNAL_0)
7132 {
7133 /* This signal must be forwarded to the inferior. We
7134 could commit-resume just this thread, but its simpler
7135 to just commit-resume everything. */
7136 needs_commit = true;
7137 break;
7138 }
7139 }
7140 }
7141
7142 if (needs_commit)
7143 commit_resumed ();
7144 else
7145 for (thread_info *tp : all_non_exited_threads (this, ptid))
7146 {
7147 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7148
7149 if (remote_thr->get_resume_state ()
7150 == resume_state::RESUMED_PENDING_VCONT)
7151 {
7152 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
96bbe3ef
TT
7153 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7154 tp->ptid.lwp (),
7155 pulongest (tp->ptid.tid ()));
1192f124
SM
7156
7157 /* Check that the thread wasn't resumed with a signal.
7158 Generating a phony stop would result in losing the
7159 signal. */
7160 const resumed_pending_vcont_info &info
7161 = remote_thr->resumed_pending_vcont_info ();
7162 gdb_assert (info.sig == GDB_SIGNAL_0);
7163
7164 stop_reply *sr = new stop_reply ();
7165 sr->ptid = tp->ptid;
7166 sr->rs = rs;
183be222 7167 sr->ws.set_stopped (GDB_SIGNAL_0);
1192f124
SM
7168 sr->arch = tp->inf->gdbarch;
7169 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7170 sr->watch_data_address = 0;
7171 sr->core = 0;
7172 this->push_stop_reply (sr);
7173
7174 /* Pretend that this thread was actually resumed on the
7175 remote target, then stopped. If we leave it in the
7176 RESUMED_PENDING_VCONT state and the commit_resumed
7177 method is called while the stop reply is still in the
7178 queue, we'll end up reporting a stop event to the core
7179 for that thread while it is running on the remote
7180 target... that would be bad. */
7181 remote_thr->set_resumed ();
7182 }
7183 }
7184
d458bd84 7185 if (!rs->supports_vCont.t)
74531fed
PA
7186 error (_("Remote server does not support stopping threads"));
7187
d7e15655 7188 if (ptid == minus_one_ptid
ff52c073 7189 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
74531fed
PA
7190 p += xsnprintf (p, endp - p, "vCont;t");
7191 else
7192 {
7193 ptid_t nptid;
7194
74531fed
PA
7195 p += xsnprintf (p, endp - p, "vCont;t:");
7196
0e998d96 7197 if (ptid.is_pid ())
74531fed 7198 /* All (-1) threads of process. */
184ea2f7 7199 nptid = ptid_t (ptid.pid (), -1);
74531fed
PA
7200 else
7201 {
7202 /* Small optimization: if we already have a stop reply for
7203 this thread, no use in telling the stub we want this
7204 stopped. */
7205 if (peek_stop_reply (ptid))
7206 return;
7207
7208 nptid = ptid;
7209 }
7210
a9cbf802 7211 write_ptid (p, endp, nptid);
74531fed
PA
7212 }
7213
7214 /* In non-stop, we get an immediate OK reply. The stop reply will
7215 come in asynchronously by notification. */
7216 putpkt (rs->buf);
8d64371b
TT
7217 getpkt (&rs->buf, 0);
7218 if (strcmp (rs->buf.data (), "OK") != 0)
a068643d 7219 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
8d64371b 7220 rs->buf.data ());
74531fed
PA
7221}
7222
bfedc46a
PA
7223/* All-stop version of target_interrupt. Sends a break or a ^C to
7224 interrupt the remote target. It is undefined which thread of which
7225 process reports the interrupt. */
74531fed 7226
6b8edb51
PA
7227void
7228remote_target::remote_interrupt_as ()
74531fed
PA
7229{
7230 struct remote_state *rs = get_remote_state ();
7231
3a29589a
DJ
7232 rs->ctrlc_pending_p = 1;
7233
74531fed 7234 /* If the inferior is stopped already, but the core didn't know
4f626cad 7235 about it yet, just ignore the request. The pending stop events
74531fed 7236 will be collected in remote_wait. */
4f626cad 7237 if (stop_reply_queue_length () > 0)
74531fed
PA
7238 return;
7239
9a7071a8
JB
7240 /* Send interrupt_sequence to remote target. */
7241 send_interrupt_sequence ();
74531fed
PA
7242}
7243
de979965
PA
7244/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7245 the remote target. It is undefined which thread of which process
e42de8c7
PA
7246 reports the interrupt. Throws an error if the packet is not
7247 supported by the server. */
de979965 7248
6b8edb51
PA
7249void
7250remote_target::remote_interrupt_ns ()
de979965
PA
7251{
7252 struct remote_state *rs = get_remote_state ();
8d64371b
TT
7253 char *p = rs->buf.data ();
7254 char *endp = p + get_remote_packet_size ();
de979965
PA
7255
7256 xsnprintf (p, endp - p, "vCtrlC");
7257
7258 /* In non-stop, we get an immediate OK reply. The stop reply will
7259 come in asynchronously by notification. */
7260 putpkt (rs->buf);
8d64371b 7261 getpkt (&rs->buf, 0);
de979965 7262
ff52c073 7263 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
de979965
PA
7264 {
7265 case PACKET_OK:
7266 break;
7267 case PACKET_UNKNOWN:
e42de8c7 7268 error (_("No support for interrupting the remote target."));
de979965 7269 case PACKET_ERROR:
8d64371b 7270 error (_("Interrupting target failed: %s"), rs->buf.data ());
de979965 7271 }
de979965
PA
7272}
7273
bfedc46a 7274/* Implement the to_stop function for the remote targets. */
74531fed 7275
f6ac5f3d
PA
7276void
7277remote_target::stop (ptid_t ptid)
c906108c 7278{
2189c312 7279 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
c906108c 7280
6efcd9a8 7281 if (target_is_non_stop_p ())
74531fed 7282 remote_stop_ns (ptid);
c906108c 7283 else
bfedc46a
PA
7284 {
7285 /* We don't currently have a way to transparently pause the
7286 remote target in all-stop mode. Interrupt it instead. */
de979965 7287 remote_interrupt_as ();
bfedc46a
PA
7288 }
7289}
7290
7291/* Implement the to_interrupt function for the remote targets. */
7292
f6ac5f3d
PA
7293void
7294remote_target::interrupt ()
bfedc46a 7295{
2189c312 7296 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
bfedc46a 7297
e42de8c7
PA
7298 if (target_is_non_stop_p ())
7299 remote_interrupt_ns ();
bfedc46a 7300 else
e42de8c7 7301 remote_interrupt_as ();
c906108c
SS
7302}
7303
93692b58
PA
7304/* Implement the to_pass_ctrlc function for the remote targets. */
7305
f6ac5f3d
PA
7306void
7307remote_target::pass_ctrlc ()
93692b58 7308{
2189c312 7309 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
93692b58 7310
2189c312 7311 struct remote_state *rs = get_remote_state ();
93692b58
PA
7312
7313 /* If we're starting up, we're not fully synced yet. Quit
7314 immediately. */
7315 if (rs->starting_up)
7316 quit ();
7317 /* If ^C has already been sent once, offer to disconnect. */
7318 else if (rs->ctrlc_pending_p)
7319 interrupt_query ();
7320 else
e671cd59 7321 target_interrupt ();
93692b58
PA
7322}
7323
c906108c
SS
7324/* Ask the user what to do when an interrupt is received. */
7325
6b8edb51
PA
7326void
7327remote_target::interrupt_query ()
c906108c 7328{
abc56d60 7329 struct remote_state *rs = get_remote_state ();
c906108c 7330
abc56d60 7331 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 7332 {
abc56d60
PA
7333 if (query (_("The target is not responding to interrupt requests.\n"
7334 "Stop debugging it? ")))
74531fed 7335 {
5b6d1e4f 7336 remote_unpush_target (this);
abc56d60 7337 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
7338 }
7339 }
abc56d60
PA
7340 else
7341 {
7342 if (query (_("Interrupted while waiting for the program.\n"
7343 "Give up waiting? ")))
7344 quit ();
7345 }
c906108c
SS
7346}
7347
6426a772
JM
7348/* Enable/disable target terminal ownership. Most targets can use
7349 terminal groups to control terminal ownership. Remote targets are
7350 different in that explicit transfer of ownership to/from GDB/target
23860348 7351 is required. */
6426a772 7352
f6ac5f3d
PA
7353void
7354remote_target::terminal_inferior ()
6426a772 7355{
6426a772
JM
7356 /* NOTE: At this point we could also register our selves as the
7357 recipient of all input. Any characters typed could then be
23860348 7358 passed on down to the target. */
6426a772
JM
7359}
7360
f6ac5f3d
PA
7361void
7362remote_target::terminal_ours ()
6426a772 7363{
6426a772
JM
7364}
7365
176a6961 7366static void
05be00a8 7367remote_console_output (const char *msg)
c906108c 7368{
05be00a8 7369 const char *p;
c906108c 7370
c5aa993b 7371 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
7372 {
7373 char tb[2];
7374 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 7375
c906108c
SS
7376 tb[0] = c;
7377 tb[1] = 0;
da5bd37e 7378 gdb_stdtarg->puts (tb);
c906108c 7379 }
da5bd37e 7380 gdb_stdtarg->flush ();
00db5b94 7381}
74531fed 7382
221e1a37
PA
7383/* Return the length of the stop reply queue. */
7384
6b8edb51
PA
7385int
7386remote_target::stop_reply_queue_length ()
221e1a37 7387{
6b8edb51 7388 remote_state *rs = get_remote_state ();
953edf2b 7389 return rs->stop_reply_queue.size ();
221e1a37
PA
7390}
7391
cb8c24b6 7392static void
6b8edb51 7393remote_notif_stop_parse (remote_target *remote,
42938c1a 7394 const notif_client *self, const char *buf,
722247f1
YQ
7395 struct notif_event *event)
7396{
6b8edb51 7397 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
7398}
7399
7400static void
6b8edb51 7401remote_notif_stop_ack (remote_target *remote,
42938c1a 7402 const notif_client *self, const char *buf,
722247f1
YQ
7403 struct notif_event *event)
7404{
7405 struct stop_reply *stop_reply = (struct stop_reply *) event;
7406
7407 /* acknowledge */
6b8edb51 7408 putpkt (remote, self->ack_command);
722247f1 7409
b0083dd7
PA
7410 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7411 the notification. It was left in the queue because we need to
7412 acknowledge it and pull the rest of the notifications out. */
183be222 7413 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
b0083dd7 7414 remote->push_stop_reply (stop_reply);
722247f1
YQ
7415}
7416
7417static int
6b8edb51 7418remote_notif_stop_can_get_pending_events (remote_target *remote,
42938c1a 7419 const notif_client *self)
722247f1
YQ
7420{
7421 /* We can't get pending events in remote_notif_process for
7422 notification stop, and we have to do this in remote_wait_ns
7423 instead. If we fetch all queued events from stub, remote stub
7424 may exit and we have no chance to process them back in
7425 remote_wait_ns. */
6b8edb51
PA
7426 remote_state *rs = remote->get_remote_state ();
7427 mark_async_event_handler (rs->remote_async_inferior_event_token);
722247f1
YQ
7428 return 0;
7429}
7430
32603266 7431stop_reply::~stop_reply ()
722247f1 7432{
32603266
TT
7433 for (cached_reg_t &reg : regcache)
7434 xfree (reg.data);
722247f1
YQ
7435}
7436
32603266
TT
7437static notif_event_up
7438remote_notif_stop_alloc_reply ()
722247f1 7439{
32603266 7440 return notif_event_up (new struct stop_reply ());
722247f1
YQ
7441}
7442
7443/* A client of notification Stop. */
7444
42938c1a 7445const notif_client notif_client_stop =
722247f1
YQ
7446{
7447 "Stop",
7448 "vStopped",
7449 remote_notif_stop_parse,
7450 remote_notif_stop_ack,
7451 remote_notif_stop_can_get_pending_events,
7452 remote_notif_stop_alloc_reply,
f48ff2a7 7453 REMOTE_NOTIF_STOP,
722247f1
YQ
7454};
7455
cbb8991c
DB
7456/* If CONTEXT contains any fork child threads that have not been
7457 reported yet, remove them from the CONTEXT list. If such a
7458 thread exists it is because we are stopped at a fork catchpoint
7459 and have not yet called follow_fork, which will set up the
7460 host-side data structures for the new process. */
7461
6b8edb51
PA
7462void
7463remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c 7464{
42938c1a 7465 const notif_client *notif = &notif_client_stop;
cbb8991c
DB
7466
7467 /* For any threads stopped at a fork event, remove the corresponding
7468 fork child threads from the CONTEXT list. */
5b6d1e4f 7469 for (thread_info *thread : all_non_exited_threads (this))
cbb8991c 7470 {
28561a65
SM
7471 const target_waitstatus *ws = thread_pending_fork_status (thread);
7472
7473 if (ws == nullptr)
7474 continue;
cbb8991c 7475
28561a65 7476 context->remove_thread (ws->child_ptid ());
cbb8991c
DB
7477 }
7478
7479 /* Check for any pending fork events (not reported or processed yet)
7480 in process PID and remove those fork child threads from the
7481 CONTEXT list as well. */
7482 remote_notif_get_pending_events (notif);
953edf2b 7483 for (auto &event : get_remote_state ()->stop_reply_queue)
183be222 7484 if (event->ws.kind () == TARGET_WAITKIND_FORKED
3890f02a 7485 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
183be222 7486 context->remove_thread (event->ws.child_ptid ());
3890f02a
SM
7487 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7488 context->remove_thread (event->ptid);
85ad3aaf
PA
7489}
7490
2f63ec5c
AB
7491/* Check whether any event pending in the vStopped queue would prevent a
7492 global or process wildcard vCont action. Set *may_global_wildcard to
7493 false if we can't do a global wildcard (vCont;c), and clear the event
7494 inferior's may_wildcard_vcont flag if we can't do a process-wide
7495 wildcard resume (vCont;c:pPID.-1). */
85ad3aaf 7496
6b8edb51
PA
7497void
7498remote_target::check_pending_events_prevent_wildcard_vcont
2f63ec5c 7499 (bool *may_global_wildcard)
85ad3aaf 7500{
42938c1a 7501 const notif_client *notif = &notif_client_stop;
85ad3aaf
PA
7502
7503 remote_notif_get_pending_events (notif);
953edf2b
TT
7504 for (auto &event : get_remote_state ()->stop_reply_queue)
7505 {
183be222
SM
7506 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7507 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
953edf2b 7508 continue;
85ad3aaf 7509
183be222
SM
7510 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7511 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
2f63ec5c 7512 *may_global_wildcard = false;
722247f1 7513
953edf2b
TT
7514 /* This may be the first time we heard about this process.
7515 Regardless, we must not do a global wildcard resume, otherwise
7516 we'd resume this process too. */
2f63ec5c 7517 *may_global_wildcard = false;
323fd5b9
PA
7518 if (event->ptid != null_ptid)
7519 {
7520 inferior *inf = find_inferior_ptid (this, event->ptid);
7521 if (inf != NULL)
7522 get_remote_inferior (inf)->may_wildcard_vcont = false;
7523 }
722247f1 7524 }
722247f1
YQ
7525}
7526
f48ff2a7 7527/* Discard all pending stop replies of inferior INF. */
c906108c 7528
6b8edb51
PA
7529void
7530remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7531{
f48ff2a7
YQ
7532 struct stop_reply *reply;
7533 struct remote_state *rs = get_remote_state ();
7534 struct remote_notif_state *rns = rs->notif_state;
7535
7536 /* This function can be notified when an inferior exists. When the
7537 target is not remote, the notification state is NULL. */
7538 if (rs->remote_desc == NULL)
7539 return;
7540
7541 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7542
74531fed 7543 /* Discard the in-flight notification. */
e99b03dc 7544 if (reply != NULL && reply->ptid.pid () == inf->pid)
74531fed 7545 {
b0083dd7
PA
7546 /* Leave the notification pending, since the server expects that
7547 we acknowledge it with vStopped. But clear its contents, so
7548 that later on when we acknowledge it, we also discard it. */
df5ad102
SM
7549 remote_debug_printf
7550 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7551 reply->ptid.to_string().c_str(),
7552 reply->ws.to_string ().c_str ());
183be222 7553 reply->ws.set_ignore ();
74531fed 7554 }
c906108c 7555
74531fed
PA
7556 /* Discard the stop replies we have already pulled with
7557 vStopped. */
953edf2b
TT
7558 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7559 rs->stop_reply_queue.end (),
7560 [=] (const stop_reply_up &event)
7561 {
7562 return event->ptid.pid () == inf->pid;
7563 });
df5ad102
SM
7564 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7565 remote_debug_printf
7566 ("discarding queued stop reply: ptid: %s, ws: %s\n",
1720b64f
AB
7567 (*it)->ptid.to_string().c_str(),
7568 (*it)->ws.to_string ().c_str ());
953edf2b 7569 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
bcc75809
YQ
7570}
7571
7572/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7573
6b8edb51
PA
7574void
7575remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7576{
6b8edb51 7577 remote_state *rs = get_remote_state ();
f48ff2a7 7578
f48ff2a7
YQ
7579 /* Discard the stop replies we have already pulled with
7580 vStopped. */
953edf2b
TT
7581 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7582 rs->stop_reply_queue.end (),
7583 [=] (const stop_reply_up &event)
7584 {
7585 return event->rs == rs;
7586 });
7587 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
74531fed 7588}
43ff13b4 7589
722247f1
YQ
7590/* Remove the first reply in 'stop_reply_queue' which matches
7591 PTID. */
2e9f7625 7592
6b8edb51
PA
7593struct stop_reply *
7594remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7595{
953edf2b 7596 remote_state *rs = get_remote_state ();
722247f1 7597
953edf2b
TT
7598 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7599 rs->stop_reply_queue.end (),
7600 [=] (const stop_reply_up &event)
7601 {
7602 return event->ptid.matches (ptid);
7603 });
7604 struct stop_reply *result;
7605 if (iter == rs->stop_reply_queue.end ())
7606 result = nullptr;
7607 else
7608 {
7609 result = iter->release ();
7610 rs->stop_reply_queue.erase (iter);
7611 }
722247f1 7612
722247f1 7613 if (notif_debug)
6cb06a8c
TT
7614 gdb_printf (gdb_stdlog,
7615 "notif: discard queued event: 'Stop' in %s\n",
7616 ptid.to_string ().c_str ());
a744cf53 7617
953edf2b 7618 return result;
74531fed 7619}
75c99385 7620
74531fed
PA
7621/* Look for a queued stop reply belonging to PTID. If one is found,
7622 remove it from the queue, and return it. Returns NULL if none is
7623 found. If there are still queued events left to process, tell the
7624 event loop to get back to target_wait soon. */
e24a49d8 7625
6b8edb51
PA
7626struct stop_reply *
7627remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7628{
953edf2b 7629 remote_state *rs = get_remote_state ();
722247f1 7630 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7631
4f626cad 7632 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
6b8edb51 7633 {
6b8edb51
PA
7634 /* There's still at least an event left. */
7635 mark_async_event_handler (rs->remote_async_inferior_event_token);
7636 }
74531fed 7637
722247f1 7638 return r;
74531fed
PA
7639}
7640
7641/* Push a fully parsed stop reply in the stop reply queue. Since we
7642 know that we now have at least one queued event left to pass to the
7643 core side, tell the event loop to get back to target_wait soon. */
7644
6b8edb51
PA
7645void
7646remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7647{
6b8edb51 7648 remote_state *rs = get_remote_state ();
953edf2b 7649 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
74531fed 7650
722247f1 7651 if (notif_debug)
6cb06a8c
TT
7652 gdb_printf (gdb_stdlog,
7653 "notif: push 'Stop' %s to queue %d\n",
7654 new_event->ptid.to_string ().c_str (),
7655 int (rs->stop_reply_queue.size ()));
74531fed 7656
4f626cad
AB
7657 /* Mark the pending event queue only if async mode is currently enabled.
7658 If async mode is not currently enabled, then, if it later becomes
7659 enabled, and there are events in this queue, we will mark the event
7660 token at that point, see remote_target::async. */
7661 if (target_is_async_p ())
7662 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
7663}
7664
7665/* Returns true if we have a stop reply for PTID. */
7666
6b8edb51
PA
7667int
7668remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7669{
6b8edb51 7670 remote_state *rs = get_remote_state ();
953edf2b
TT
7671 for (auto &event : rs->stop_reply_queue)
7672 if (ptid == event->ptid
183be222 7673 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
953edf2b
TT
7674 return 1;
7675 return 0;
74531fed
PA
7676}
7677
26d56a93
SL
7678/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7679 starting with P and ending with PEND matches PREFIX. */
7680
7681static int
7682strprefix (const char *p, const char *pend, const char *prefix)
7683{
7684 for ( ; p < pend; p++, prefix++)
7685 if (*p != *prefix)
7686 return 0;
7687 return *prefix == '\0';
7688}
7689
74531fed
PA
7690/* Parse the stop reply in BUF. Either the function succeeds, and the
7691 result is stored in EVENT, or throws an error. */
7692
6b8edb51 7693void
bb277751 7694remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
74531fed 7695{
5cd63fda 7696 remote_arch_state *rsa = NULL;
74531fed 7697 ULONGEST addr;
256642e8 7698 const char *p;
94585166 7699 int skipregs = 0;
74531fed
PA
7700
7701 event->ptid = null_ptid;
bcc75809 7702 event->rs = get_remote_state ();
183be222 7703 event->ws.set_ignore ();
f7e6eed5 7704 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
32603266 7705 event->regcache.clear ();
dc146f7c 7706 event->core = -1;
74531fed
PA
7707
7708 switch (buf[0])
7709 {
7710 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7711 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7712 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7713 ss = signal number
7714 n... = register number
7715 r... = register contents
7716 */
7717
7718 p = &buf[3]; /* after Txx */
7719 while (*p)
7720 {
256642e8 7721 const char *p1;
cea39f65 7722 int fieldsize;
43ff13b4 7723
1f10ba14
PA
7724 p1 = strchr (p, ':');
7725 if (p1 == NULL)
7726 error (_("Malformed packet(a) (missing colon): %s\n\
7727Packet: '%s'\n"),
7728 p, buf);
7729 if (p == p1)
7730 error (_("Malformed packet(a) (missing register number): %s\n\
7731Packet: '%s'\n"),
7732 p, buf);
3c3bea1c 7733
1f10ba14
PA
7734 /* Some "registers" are actually extended stop information.
7735 Note if you're adding a new entry here: GDB 7.9 and
7736 earlier assume that all register "numbers" that start
7737 with an hex digit are real register numbers. Make sure
7738 the server only sends such a packet if it knows the
7739 client understands it. */
c8e38a49 7740
26d56a93 7741 if (strprefix (p, p1, "thread"))
1f10ba14 7742 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7743 else if (strprefix (p, p1, "syscall_entry"))
7744 {
7745 ULONGEST sysno;
7746
82075af2 7747 p = unpack_varlen_hex (++p1, &sysno);
183be222 7748 event->ws.set_syscall_entry ((int) sysno);
82075af2
JS
7749 }
7750 else if (strprefix (p, p1, "syscall_return"))
7751 {
7752 ULONGEST sysno;
7753
82075af2 7754 p = unpack_varlen_hex (++p1, &sysno);
183be222 7755 event->ws.set_syscall_return ((int) sysno);
82075af2 7756 }
26d56a93
SL
7757 else if (strprefix (p, p1, "watch")
7758 || strprefix (p, p1, "rwatch")
7759 || strprefix (p, p1, "awatch"))
cea39f65 7760 {
f7e6eed5 7761 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7762 p = unpack_varlen_hex (++p1, &addr);
7763 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7764 }
26d56a93 7765 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7766 {
7767 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7768
7769 /* Make sure the stub doesn't forget to indicate support
7770 with qSupported. */
ff52c073
CS
7771 if (m_features.packet_support (PACKET_swbreak_feature)
7772 != PACKET_ENABLE)
f7e6eed5
PA
7773 error (_("Unexpected swbreak stop reason"));
7774
7775 /* The value part is documented as "must be empty",
7776 though we ignore it, in case we ever decide to make
7777 use of it in a backward compatible way. */
8424cc97 7778 p = strchrnul (p1 + 1, ';');
f7e6eed5 7779 }
26d56a93 7780 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7781 {
7782 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7783
7784 /* Make sure the stub doesn't forget to indicate support
7785 with qSupported. */
ff52c073
CS
7786 if (m_features.packet_support (PACKET_hwbreak_feature)
7787 != PACKET_ENABLE)
f7e6eed5
PA
7788 error (_("Unexpected hwbreak stop reason"));
7789
7790 /* See above. */
8424cc97 7791 p = strchrnul (p1 + 1, ';');
f7e6eed5 7792 }
26d56a93 7793 else if (strprefix (p, p1, "library"))
cea39f65 7794 {
183be222 7795 event->ws.set_loaded ();
8424cc97 7796 p = strchrnul (p1 + 1, ';');
1f10ba14 7797 }
26d56a93 7798 else if (strprefix (p, p1, "replaylog"))
1f10ba14 7799 {
183be222 7800 event->ws.set_no_history ();
1f10ba14
PA
7801 /* p1 will indicate "begin" or "end", but it makes
7802 no difference for now, so ignore it. */
8424cc97 7803 p = strchrnul (p1 + 1, ';');
1f10ba14 7804 }
26d56a93 7805 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7806 {
7807 ULONGEST c;
a744cf53 7808
1f10ba14
PA
7809 p = unpack_varlen_hex (++p1, &c);
7810 event->core = c;
cea39f65 7811 }
26d56a93 7812 else if (strprefix (p, p1, "fork"))
183be222 7813 event->ws.set_forked (read_ptid (++p1, &p));
26d56a93 7814 else if (strprefix (p, p1, "vfork"))
183be222 7815 event->ws.set_vforked (read_ptid (++p1, &p));
26d56a93 7816 else if (strprefix (p, p1, "vforkdone"))
c269dbdb 7817 {
183be222 7818 event->ws.set_vfork_done ();
8424cc97 7819 p = strchrnul (p1 + 1, ';');
c269dbdb 7820 }
6ab24463 7821 else if (strprefix (p, p1, "exec"))
94585166
DB
7822 {
7823 ULONGEST ignored;
94585166
DB
7824 int pathlen;
7825
7826 /* Determine the length of the execd pathname. */
7827 p = unpack_varlen_hex (++p1, &ignored);
7828 pathlen = (p - p1) / 2;
7829
7830 /* Save the pathname for event reporting and for
7831 the next run command. */
183be222 7832 gdb::unique_xmalloc_ptr<char> pathname
c6321f19
TT
7833 ((char *) xmalloc (pathlen + 1));
7834 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
183be222 7835 pathname.get ()[pathlen] = '\0';
94585166
DB
7836
7837 /* This is freed during event handling. */
183be222 7838 event->ws.set_execd (std::move (pathname));
94585166
DB
7839
7840 /* Skip the registers included in this packet, since
7841 they may be for an architecture different from the
7842 one used by the original program. */
7843 skipregs = 1;
7844 }
65706a29
PA
7845 else if (strprefix (p, p1, "create"))
7846 {
183be222 7847 event->ws.set_thread_created ();
8424cc97 7848 p = strchrnul (p1 + 1, ';');
65706a29 7849 }
cea39f65
MS
7850 else
7851 {
1f10ba14 7852 ULONGEST pnum;
256642e8 7853 const char *p_temp;
1f10ba14 7854
94585166
DB
7855 if (skipregs)
7856 {
8424cc97 7857 p = strchrnul (p1 + 1, ';');
94585166
DB
7858 p++;
7859 continue;
7860 }
7861
1f10ba14
PA
7862 /* Maybe a real ``P'' register number. */
7863 p_temp = unpack_varlen_hex (p, &pnum);
7864 /* If the first invalid character is the colon, we got a
7865 register number. Otherwise, it's an unknown stop
7866 reason. */
7867 if (p_temp == p1)
7868 {
5cd63fda
PA
7869 /* If we haven't parsed the event's thread yet, find
7870 it now, in order to find the architecture of the
7871 reported expedited registers. */
7872 if (event->ptid == null_ptid)
7873 {
24ed6739
AB
7874 /* If there is no thread-id information then leave
7875 the event->ptid as null_ptid. Later in
7876 process_stop_reply we will pick a suitable
7877 thread. */
5cd63fda
PA
7878 const char *thr = strstr (p1 + 1, ";thread:");
7879 if (thr != NULL)
7880 event->ptid = read_ptid (thr + strlen (";thread:"),
7881 NULL);
5cd63fda
PA
7882 }
7883
7884 if (rsa == NULL)
7885 {
5b6d1e4f
PA
7886 inferior *inf
7887 = (event->ptid == null_ptid
7888 ? NULL
7889 : find_inferior_ptid (this, event->ptid));
5cd63fda
PA
7890 /* If this is the first time we learn anything
7891 about this process, skip the registers
7892 included in this packet, since we don't yet
7893 know which architecture to use to parse them.
7894 We'll determine the architecture later when
7895 we process the stop reply and retrieve the
7896 target description, via
7897 remote_notice_new_inferior ->
7898 post_create_inferior. */
7899 if (inf == NULL)
7900 {
7901 p = strchrnul (p1 + 1, ';');
7902 p++;
7903 continue;
7904 }
7905
7906 event->arch = inf->gdbarch;
9d6eea31 7907 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7908 }
7909
7910 packet_reg *reg
7911 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7912 cached_reg_t cached_reg;
43ff13b4 7913
1f10ba14
PA
7914 if (reg == NULL)
7915 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7916Packet: '%s'\n"),
1f10ba14 7917 hex_string (pnum), p, buf);
c8e38a49 7918
1f10ba14 7919 cached_reg.num = reg->regnum;
d1dff226 7920 cached_reg.data = (gdb_byte *)
5cd63fda 7921 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7922
1f10ba14
PA
7923 p = p1 + 1;
7924 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7925 register_size (event->arch, reg->regnum));
1f10ba14 7926 p += 2 * fieldsize;
5cd63fda 7927 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7928 warning (_("Remote reply is too short: %s"), buf);
74531fed 7929
32603266 7930 event->regcache.push_back (cached_reg);
1f10ba14
PA
7931 }
7932 else
7933 {
7934 /* Not a number. Silently skip unknown optional
7935 info. */
8424cc97 7936 p = strchrnul (p1 + 1, ';');
1f10ba14 7937 }
cea39f65 7938 }
c8e38a49 7939
cea39f65
MS
7940 if (*p != ';')
7941 error (_("Remote register badly formatted: %s\nhere: %s"),
7942 buf, p);
7943 ++p;
7944 }
5b5596ff 7945
183be222 7946 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
5b5596ff
PA
7947 break;
7948
c8e38a49
PA
7949 /* fall through */
7950 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7951 {
7952 int sig;
7953
3a09da41
PA
7954 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7955 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
183be222 7956 event->ws.set_stopped ((enum gdb_signal) sig);
3a09da41 7957 else
183be222 7958 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
3a09da41 7959 }
c8e38a49 7960 break;
65706a29
PA
7961 case 'w': /* Thread exited. */
7962 {
65706a29
PA
7963 ULONGEST value;
7964
65706a29 7965 p = unpack_varlen_hex (&buf[1], &value);
183be222 7966 event->ws.set_thread_exited (value);
65706a29
PA
7967 if (*p != ';')
7968 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7969 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7970 break;
7971 }
c8e38a49
PA
7972 case 'W': /* Target exited. */
7973 case 'X':
7974 {
c8e38a49 7975 ULONGEST value;
82f73884 7976
c8e38a49
PA
7977 /* GDB used to accept only 2 hex chars here. Stubs should
7978 only send more if they detect GDB supports multi-process
7979 support. */
7980 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7981
c8e38a49
PA
7982 if (buf[0] == 'W')
7983 {
7984 /* The remote process exited. */
183be222 7985 event->ws.set_exited (value);
c8e38a49
PA
7986 }
7987 else
7988 {
7989 /* The remote process exited with a signal. */
3a09da41 7990 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
183be222 7991 event->ws.set_signalled ((enum gdb_signal) value);
3a09da41 7992 else
183be222 7993 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
c8e38a49 7994 }
82f73884 7995
e7af6c70
TBA
7996 /* If no process is specified, return null_ptid, and let the
7997 caller figure out the right process to use. */
7998 int pid = 0;
c8e38a49
PA
7999 if (*p == '\0')
8000 ;
8001 else if (*p == ';')
8002 {
8003 p++;
8004
0b24eb2d 8005 if (*p == '\0')
82f73884 8006 ;
61012eef 8007 else if (startswith (p, "process:"))
82f73884 8008 {
c8e38a49 8009 ULONGEST upid;
a744cf53 8010
c8e38a49
PA
8011 p += sizeof ("process:") - 1;
8012 unpack_varlen_hex (p, &upid);
8013 pid = upid;
82f73884
PA
8014 }
8015 else
8016 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 8017 }
c8e38a49
PA
8018 else
8019 error (_("unknown stop reply packet: %s"), buf);
f2907e49 8020 event->ptid = ptid_t (pid);
74531fed
PA
8021 }
8022 break;
f2faf941 8023 case 'N':
183be222 8024 event->ws.set_no_resumed ();
f2faf941
PA
8025 event->ptid = minus_one_ptid;
8026 break;
74531fed 8027 }
74531fed
PA
8028}
8029
722247f1
YQ
8030/* When the stub wants to tell GDB about a new notification reply, it
8031 sends a notification (%Stop, for example). Those can come it at
8032 any time, hence, we have to make sure that any pending
8033 putpkt/getpkt sequence we're making is finished, before querying
8034 the stub for more events with the corresponding ack command
8035 (vStopped, for example). E.g., if we started a vStopped sequence
8036 immediately upon receiving the notification, something like this
8037 could happen:
74531fed
PA
8038
8039 1.1) --> Hg 1
8040 1.2) <-- OK
8041 1.3) --> g
8042 1.4) <-- %Stop
8043 1.5) --> vStopped
8044 1.6) <-- (registers reply to step #1.3)
8045
8046 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8047 query.
8048
796cb314 8049 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
8050 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8051 doing whatever we were doing:
8052
8053 2.1) --> Hg 1
8054 2.2) <-- OK
8055 2.3) --> g
8056 2.4) <-- %Stop
8057 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8058 2.5) <-- (registers reply to step #2.3)
8059
85102364 8060 Eventually after step #2.5, we return to the event loop, which
74531fed
PA
8061 notices there's an event on the
8062 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8063 associated callback --- the function below. At this point, we're
8064 always safe to start a vStopped sequence. :
8065
8066 2.6) --> vStopped
8067 2.7) <-- T05 thread:2
8068 2.8) --> vStopped
8069 2.9) --> OK
8070*/
8071
722247f1 8072void
42938c1a 8073remote_target::remote_notif_get_pending_events (const notif_client *nc)
74531fed
PA
8074{
8075 struct remote_state *rs = get_remote_state ();
74531fed 8076
f48ff2a7 8077 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 8078 {
722247f1 8079 if (notif_debug)
6cb06a8c
TT
8080 gdb_printf (gdb_stdlog,
8081 "notif: process: '%s' ack pending event\n",
8082 nc->name);
74531fed 8083
722247f1 8084 /* acknowledge */
8d64371b
TT
8085 nc->ack (this, nc, rs->buf.data (),
8086 rs->notif_state->pending_event[nc->id]);
f48ff2a7 8087 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
8088
8089 while (1)
8090 {
8d64371b
TT
8091 getpkt (&rs->buf, 0);
8092 if (strcmp (rs->buf.data (), "OK") == 0)
74531fed
PA
8093 break;
8094 else
8d64371b 8095 remote_notif_ack (this, nc, rs->buf.data ());
74531fed
PA
8096 }
8097 }
722247f1
YQ
8098 else
8099 {
8100 if (notif_debug)
6cb06a8c
TT
8101 gdb_printf (gdb_stdlog,
8102 "notif: process: '%s' no pending reply\n",
8103 nc->name);
722247f1 8104 }
74531fed
PA
8105}
8106
6b8edb51
PA
8107/* Wrapper around remote_target::remote_notif_get_pending_events to
8108 avoid having to export the whole remote_target class. */
8109
8110void
42938c1a 8111remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
6b8edb51
PA
8112{
8113 remote->remote_notif_get_pending_events (nc);
8114}
8115
8f66807b
AB
8116/* Called from process_stop_reply when the stop packet we are responding
8117 to didn't include a process-id or thread-id. STATUS is the stop event
8118 we are responding to.
8119
8120 It is the task of this function to select a suitable thread (or process)
8121 and return its ptid, this is the thread (or process) we will assume the
8122 stop event came from.
8123
8124 In some cases there isn't really any choice about which thread (or
8125 process) is selected, a basic remote with a single process containing a
8126 single thread might choose not to send any process-id or thread-id in
8127 its stop packets, this function will select and return the one and only
8128 thread.
8129
8130 However, if a target supports multiple threads (or processes) and still
8131 doesn't include a thread-id (or process-id) in its stop packet then
8132 first, this is a badly behaving target, and second, we're going to have
8133 to select a thread (or process) at random and use that. This function
8134 will print a warning to the user if it detects that there is the
8135 possibility that GDB is guessing which thread (or process) to
8136 report.
8137
8138 Note that this is called before GDB fetches the updated thread list from the
8139 target. So it's possible for the stop reply to be ambiguous and for GDB to
8140 not realize it. For example, if there's initially one thread, the target
8141 spawns a second thread, and then sends a stop reply without an id that
8142 concerns the first thread. GDB will assume the stop reply is about the
8143 first thread - the only thread it knows about - without printing a warning.
8144 Anyway, if the remote meant for the stop reply to be about the second thread,
8145 then it would be really broken, because GDB doesn't know about that thread
8146 yet. */
74531fed 8147
6b8edb51 8148ptid_t
8f66807b 8149remote_target::select_thread_for_ambiguous_stop_reply
c272a98c 8150 (const target_waitstatus &status)
74531fed 8151{
4351271e
AB
8152 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8153
8f66807b
AB
8154 /* Some stop events apply to all threads in an inferior, while others
8155 only apply to a single thread. */
8156 bool process_wide_stop
c272a98c
SM
8157 = (status.kind () == TARGET_WAITKIND_EXITED
8158 || status.kind () == TARGET_WAITKIND_SIGNALLED);
74531fed 8159
4351271e
AB
8160 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8161
8f66807b
AB
8162 thread_info *first_resumed_thread = nullptr;
8163 bool ambiguous = false;
74531fed 8164
8f66807b
AB
8165 /* Consider all non-exited threads of the target, find the first resumed
8166 one. */
8167 for (thread_info *thr : all_non_exited_threads (this))
24ed6739 8168 {
8f66807b 8169 remote_thread_info *remote_thr = get_remote_thread_info (thr);
cada5fc9 8170
a6c11cbb 8171 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8f66807b 8172 continue;
24ed6739 8173
8f66807b
AB
8174 if (first_resumed_thread == nullptr)
8175 first_resumed_thread = thr;
8176 else if (!process_wide_stop
8177 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8178 ambiguous = true;
8179 }
8180
b622494e
AB
8181 gdb_assert (first_resumed_thread != nullptr);
8182
4351271e
AB
8183 remote_debug_printf ("first resumed thread is %s",
8184 pid_to_str (first_resumed_thread->ptid).c_str ());
8185 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8186
8f66807b
AB
8187 /* Warn if the remote target is sending ambiguous stop replies. */
8188 if (ambiguous)
8189 {
8190 static bool warned = false;
8191
8192 if (!warned)
8193 {
8194 /* If you are seeing this warning then the remote target has
8195 stopped without specifying a thread-id, but the target
8196 does have multiple threads (or inferiors), and so GDB is
8197 having to guess which thread stopped.
8198
8199 Examples of what might cause this are the target sending
8200 and 'S' stop packet, or a 'T' stop packet and not
8201 including a thread-id.
8202
8203 Additionally, the target might send a 'W' or 'X packet
8204 without including a process-id, when the target has
8205 multiple running inferiors. */
8206 if (process_wide_stop)
8207 warning (_("multi-inferior target stopped without "
8208 "sending a process-id, using first "
8209 "non-exited inferior"));
cada5fc9 8210 else
8f66807b
AB
8211 warning (_("multi-threaded target stopped without "
8212 "sending a thread-id, using first "
8213 "non-exited thread"));
8214 warned = true;
24ed6739 8215 }
24ed6739 8216 }
74531fed 8217
8f66807b
AB
8218 /* If this is a stop for all threads then don't use a particular threads
8219 ptid, instead create a new ptid where only the pid field is set. */
8220 if (process_wide_stop)
8221 return ptid_t (first_resumed_thread->ptid.pid ());
8222 else
8223 return first_resumed_thread->ptid;
8224}
8225
8226/* Called when it is decided that STOP_REPLY holds the info of the
8227 event that is to be returned to the core. This function always
8228 destroys STOP_REPLY. */
8229
8230ptid_t
8231remote_target::process_stop_reply (struct stop_reply *stop_reply,
8232 struct target_waitstatus *status)
8233{
8234 *status = stop_reply->ws;
8235 ptid_t ptid = stop_reply->ptid;
8236
8237 /* If no thread/process was reported by the stub then select a suitable
8238 thread/process. */
8239 if (ptid == null_ptid)
c272a98c 8240 ptid = select_thread_for_ambiguous_stop_reply (*status);
8f66807b
AB
8241 gdb_assert (ptid != null_ptid);
8242
183be222
SM
8243 if (status->kind () != TARGET_WAITKIND_EXITED
8244 && status->kind () != TARGET_WAITKIND_SIGNALLED
8245 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
74531fed 8246 {
5f3563ea 8247 /* Expedited registers. */
32603266 8248 if (!stop_reply->regcache.empty ())
5f3563ea 8249 {
217f1f79 8250 struct regcache *regcache
5b6d1e4f 8251 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
5f3563ea 8252
32603266
TT
8253 for (cached_reg_t &reg : stop_reply->regcache)
8254 {
8255 regcache->raw_supply (reg.num, reg.data);
8256 xfree (reg.data);
8257 }
d1dff226 8258
32603266 8259 stop_reply->regcache.clear ();
5f3563ea 8260 }
74531fed 8261
8a82de58 8262 remote_notice_new_inferior (ptid, false);
5b6d1e4f 8263 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
799a2abe
PA
8264 remote_thr->core = stop_reply->core;
8265 remote_thr->stop_reason = stop_reply->stop_reason;
8266 remote_thr->watch_data_address = stop_reply->watch_data_address;
c9d22089
SM
8267
8268 if (target_is_non_stop_p ())
8269 {
8270 /* If the target works in non-stop mode, a stop-reply indicates that
8271 only this thread stopped. */
8272 remote_thr->set_not_resumed ();
8273 }
8274 else
8275 {
8276 /* If the target works in all-stop mode, a stop-reply indicates that
8277 all the target's threads stopped. */
8278 for (thread_info *tp : all_non_exited_threads (this))
8279 get_remote_thread_info (tp)->set_not_resumed ();
8280 }
74531fed
PA
8281 }
8282
32603266 8283 delete stop_reply;
74531fed
PA
8284 return ptid;
8285}
8286
8287/* The non-stop mode version of target_wait. */
8288
6b8edb51 8289ptid_t
b60cea74
TT
8290remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8291 target_wait_flags options)
74531fed
PA
8292{
8293 struct remote_state *rs = get_remote_state ();
74531fed
PA
8294 struct stop_reply *stop_reply;
8295 int ret;
fee9eda9 8296 int is_notif = 0;
74531fed
PA
8297
8298 /* If in non-stop mode, get out of getpkt even if a
8299 notification is received. */
8300
8d64371b 8301 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
74531fed
PA
8302 while (1)
8303 {
fee9eda9 8304 if (ret != -1 && !is_notif)
74531fed
PA
8305 switch (rs->buf[0])
8306 {
8307 case 'E': /* Error of some sort. */
8308 /* We're out of sync with the target now. Did it continue
8309 or not? We can't tell which thread it was in non-stop,
8310 so just ignore this. */
8d64371b 8311 warning (_("Remote failure reply: %s"), rs->buf.data ());
74531fed
PA
8312 break;
8313 case 'O': /* Console output. */
8d64371b 8314 remote_console_output (&rs->buf[1]);
74531fed
PA
8315 break;
8316 default:
8d64371b 8317 warning (_("Invalid remote reply: %s"), rs->buf.data ());
74531fed
PA
8318 break;
8319 }
8320
8321 /* Acknowledge a pending stop reply that may have arrived in the
8322 mean time. */
f48ff2a7 8323 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 8324 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
8325
8326 /* If indeed we noticed a stop reply, we're done. */
8327 stop_reply = queued_stop_reply (ptid);
8328 if (stop_reply != NULL)
8329 return process_stop_reply (stop_reply, status);
8330
47608cb1 8331 /* Still no event. If we're just polling for an event, then
74531fed 8332 return to the event loop. */
47608cb1 8333 if (options & TARGET_WNOHANG)
74531fed 8334 {
183be222 8335 status->set_ignore ();
74531fed
PA
8336 return minus_one_ptid;
8337 }
8338
47608cb1 8339 /* Otherwise do a blocking wait. */
8d64371b 8340 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
74531fed
PA
8341 }
8342}
8343
31ba933e
PA
8344/* Return the first resumed thread. */
8345
8346static ptid_t
5b6d1e4f 8347first_remote_resumed_thread (remote_target *target)
31ba933e 8348{
5b6d1e4f 8349 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
7846f3aa 8350 if (tp->resumed ())
31ba933e
PA
8351 return tp->ptid;
8352 return null_ptid;
8353}
8354
74531fed
PA
8355/* Wait until the remote machine stops, then return, storing status in
8356 STATUS just as `wait' would. */
8357
6b8edb51 8358ptid_t
b60cea74
TT
8359remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8360 target_wait_flags options)
74531fed
PA
8361{
8362 struct remote_state *rs = get_remote_state ();
74531fed 8363 ptid_t event_ptid = null_ptid;
cea39f65 8364 char *buf;
74531fed
PA
8365 struct stop_reply *stop_reply;
8366
47608cb1
PA
8367 again:
8368
183be222 8369 status->set_ignore ();
74531fed
PA
8370
8371 stop_reply = queued_stop_reply (ptid);
8372 if (stop_reply != NULL)
4f626cad
AB
8373 {
8374 /* None of the paths that push a stop reply onto the queue should
8375 have set the waiting_for_stop_reply flag. */
8376 gdb_assert (!rs->waiting_for_stop_reply);
8377 event_ptid = process_stop_reply (stop_reply, status);
8378 }
74531fed
PA
8379 else
8380 {
567420d1 8381 int forever = ((options & TARGET_WNOHANG) == 0
6b8edb51 8382 && rs->wait_forever_enabled_p);
567420d1
PA
8383
8384 if (!rs->waiting_for_stop_reply)
8385 {
183be222 8386 status->set_no_resumed ();
567420d1
PA
8387 return minus_one_ptid;
8388 }
74531fed 8389
74531fed
PA
8390 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8391 _never_ wait for ever -> test on target_is_async_p().
8392 However, before we do that we need to ensure that the caller
8393 knows how to take the target into/out of async mode. */
4f626cad
AB
8394 int is_notif;
8395 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
722247f1
YQ
8396
8397 /* GDB gets a notification. Return to core as this event is
8398 not interesting. */
8399 if (ret != -1 && is_notif)
8400 return minus_one_ptid;
567420d1
PA
8401
8402 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8403 return minus_one_ptid;
74531fed 8404
4f626cad 8405 buf = rs->buf.data ();
74531fed 8406
4f626cad
AB
8407 /* Assume that the target has acknowledged Ctrl-C unless we receive
8408 an 'F' or 'O' packet. */
8409 if (buf[0] != 'F' && buf[0] != 'O')
8410 rs->ctrlc_pending_p = 0;
3a29589a 8411
4f626cad
AB
8412 switch (buf[0])
8413 {
8414 case 'E': /* Error of some sort. */
8415 /* We're out of sync with the target now. Did it continue or
8416 not? Not is more likely, so report a stop. */
8417 rs->waiting_for_stop_reply = 0;
29090fb6 8418
4f626cad
AB
8419 warning (_("Remote failure reply: %s"), buf);
8420 status->set_stopped (GDB_SIGNAL_0);
8421 break;
8422 case 'F': /* File-I/O request. */
8423 /* GDB may access the inferior memory while handling the File-I/O
8424 request, but we don't want GDB accessing memory while waiting
8425 for a stop reply. See the comments in putpkt_binary. Set
8426 waiting_for_stop_reply to 0 temporarily. */
8427 rs->waiting_for_stop_reply = 0;
8428 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8429 rs->ctrlc_pending_p = 0;
8430 /* GDB handled the File-I/O request, and the target is running
8431 again. Keep waiting for events. */
8432 rs->waiting_for_stop_reply = 1;
8433 break;
8434 case 'N': case 'T': case 'S': case 'X': case 'W':
8435 {
8436 /* There is a stop reply to handle. */
8437 rs->waiting_for_stop_reply = 0;
29090fb6 8438
4f626cad
AB
8439 stop_reply
8440 = (struct stop_reply *) remote_notif_parse (this,
8441 &notif_client_stop,
8442 rs->buf.data ());
74531fed 8443
4f626cad
AB
8444 event_ptid = process_stop_reply (stop_reply, status);
8445 break;
8446 }
8447 case 'O': /* Console output. */
8448 remote_console_output (buf + 1);
8449 break;
8450 case '\0':
8451 if (rs->last_sent_signal != GDB_SIGNAL_0)
8452 {
8453 /* Zero length reply means that we tried 'S' or 'C' and the
8454 remote system doesn't support it. */
8455 target_terminal::ours_for_output ();
6cb06a8c 8456 gdb_printf
4f626cad
AB
8457 ("Can't send signals to this remote system. %s not sent.\n",
8458 gdb_signal_to_name (rs->last_sent_signal));
8459 rs->last_sent_signal = GDB_SIGNAL_0;
8460 target_terminal::inferior ();
8461
8462 strcpy (buf, rs->last_sent_step ? "s" : "c");
8463 putpkt (buf);
8464 break;
8465 }
8466 /* fallthrough */
8467 default:
8468 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 8469 break;
43ff13b4
JM
8470 }
8471 }
c8e38a49 8472
183be222 8473 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
f2faf941 8474 return minus_one_ptid;
183be222 8475 else if (status->kind () == TARGET_WAITKIND_IGNORE)
47608cb1
PA
8476 {
8477 /* Nothing interesting happened. If we're doing a non-blocking
8478 poll, we're done. Otherwise, go back to waiting. */
8479 if (options & TARGET_WNOHANG)
8480 return minus_one_ptid;
8481 else
8482 goto again;
8483 }
183be222
SM
8484 else if (status->kind () != TARGET_WAITKIND_EXITED
8485 && status->kind () != TARGET_WAITKIND_SIGNALLED)
82f73884 8486 {
d7e15655 8487 if (event_ptid != null_ptid)
47f8a51d 8488 record_currthread (rs, event_ptid);
82f73884 8489 else
5b6d1e4f 8490 event_ptid = first_remote_resumed_thread (this);
43ff13b4 8491 }
74531fed 8492 else
e7af6c70
TBA
8493 {
8494 /* A process exit. Invalidate our notion of current thread. */
8495 record_currthread (rs, minus_one_ptid);
8496 /* It's possible that the packet did not include a pid. */
8497 if (event_ptid == null_ptid)
5b6d1e4f 8498 event_ptid = first_remote_resumed_thread (this);
e7af6c70
TBA
8499 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8500 if (event_ptid == null_ptid)
8501 event_ptid = magic_null_ptid;
8502 }
79d7f229 8503
82f73884 8504 return event_ptid;
43ff13b4
JM
8505}
8506
74531fed
PA
8507/* Wait until the remote machine stops, then return, storing status in
8508 STATUS just as `wait' would. */
8509
f6ac5f3d 8510ptid_t
b60cea74
TT
8511remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8512 target_wait_flags options)
c8e38a49 8513{
2189c312
SM
8514 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8515
baa8575b
SM
8516 remote_state *rs = get_remote_state ();
8517
8518 /* Start by clearing the flag that asks for our wait method to be called,
8d34471f
AB
8519 we'll mark it again at the end if needed. If the target is not in
8520 async mode then the async token should not be marked. */
baa8575b
SM
8521 if (target_is_async_p ())
8522 clear_async_event_handler (rs->remote_async_inferior_event_token);
8d34471f
AB
8523 else
8524 gdb_assert (!async_event_handler_marked
8525 (rs->remote_async_inferior_event_token));
baa8575b 8526
c8e38a49
PA
8527 ptid_t event_ptid;
8528
6efcd9a8 8529 if (target_is_non_stop_p ())
6b8edb51 8530 event_ptid = wait_ns (ptid, status, options);
74531fed 8531 else
6b8edb51 8532 event_ptid = wait_as (ptid, status, options);
c8e38a49 8533
d9d41e78 8534 if (target_is_async_p ())
c8e38a49 8535 {
baa8575b
SM
8536 /* If there are events left in the queue, or unacknowledged
8537 notifications, then tell the event loop to call us again. */
8538 if (!rs->stop_reply_queue.empty ()
8539 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
6b8edb51 8540 mark_async_event_handler (rs->remote_async_inferior_event_token);
c8e38a49 8541 }
c8e38a49
PA
8542
8543 return event_ptid;
8544}
8545
74ca34ce 8546/* Fetch a single register using a 'p' packet. */
c906108c 8547
6b8edb51
PA
8548int
8549remote_target::fetch_register_using_p (struct regcache *regcache,
8550 packet_reg *reg)
b96ec7ac 8551{
ac7936df 8552 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 8553 struct remote_state *rs = get_remote_state ();
2e9f7625 8554 char *buf, *p;
9890e433 8555 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
8556 int i;
8557
ff52c073 8558 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
8559 return 0;
8560
8561 if (reg->pnum == -1)
8562 return 0;
8563
8d64371b 8564 p = rs->buf.data ();
fcad0fa4 8565 *p++ = 'p';
74ca34ce 8566 p += hexnumstr (p, reg->pnum);
fcad0fa4 8567 *p++ = '\0';
1f4437a4 8568 putpkt (rs->buf);
8d64371b 8569 getpkt (&rs->buf, 0);
3f9a994c 8570
8d64371b 8571 buf = rs->buf.data ();
2e9f7625 8572
ff52c073 8573 switch (m_features.packet_ok (rs->buf, PACKET_p))
74ca34ce
DJ
8574 {
8575 case PACKET_OK:
8576 break;
8577 case PACKET_UNKNOWN:
8578 return 0;
8579 case PACKET_ERROR:
27a9c0bf 8580 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 8581 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
8582 reg->regnum),
8583 buf);
74ca34ce 8584 }
3f9a994c
JB
8585
8586 /* If this register is unfetchable, tell the regcache. */
8587 if (buf[0] == 'x')
8480adf2 8588 {
73e1c03f 8589 regcache->raw_supply (reg->regnum, NULL);
8480adf2 8590 return 1;
b96ec7ac 8591 }
b96ec7ac 8592
3f9a994c
JB
8593 /* Otherwise, parse and supply the value. */
8594 p = buf;
8595 i = 0;
8596 while (p[0] != 0)
8597 {
8598 if (p[1] == 0)
74ca34ce 8599 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
8600
8601 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8602 p += 2;
8603 }
73e1c03f 8604 regcache->raw_supply (reg->regnum, regp);
3f9a994c 8605 return 1;
b96ec7ac
AC
8606}
8607
74ca34ce
DJ
8608/* Fetch the registers included in the target's 'g' packet. */
8609
6b8edb51
PA
8610int
8611remote_target::send_g_packet ()
c906108c 8612{
d01949b6 8613 struct remote_state *rs = get_remote_state ();
cea39f65 8614 int buf_len;
c906108c 8615
8d64371b 8616 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
b75abf5b 8617 putpkt (rs->buf);
8d64371b 8618 getpkt (&rs->buf, 0);
b75abf5b
AK
8619 if (packet_check_result (rs->buf) == PACKET_ERROR)
8620 error (_("Could not read registers; remote failure reply '%s'"),
dda83cd7 8621 rs->buf.data ());
c906108c 8622
29709017
DJ
8623 /* We can get out of synch in various cases. If the first character
8624 in the buffer is not a hex character, assume that has happened
8625 and try to fetch another packet to read. */
8626 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8627 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8628 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8629 && rs->buf[0] != 'x') /* New: unavailable register value. */
8630 {
2189c312 8631 remote_debug_printf ("Bad register packet; fetching a new packet");
8d64371b 8632 getpkt (&rs->buf, 0);
29709017
DJ
8633 }
8634
8d64371b 8635 buf_len = strlen (rs->buf.data ());
74ca34ce
DJ
8636
8637 /* Sanity check the received packet. */
8638 if (buf_len % 2 != 0)
8d64371b 8639 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
29709017
DJ
8640
8641 return buf_len / 2;
8642}
8643
6b8edb51
PA
8644void
8645remote_target::process_g_packet (struct regcache *regcache)
29709017 8646{
ac7936df 8647 struct gdbarch *gdbarch = regcache->arch ();
29709017 8648 struct remote_state *rs = get_remote_state ();
9d6eea31 8649 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8650 int i, buf_len;
8651 char *p;
8652 char *regs;
8653
8d64371b 8654 buf_len = strlen (rs->buf.data ());
29709017
DJ
8655
8656 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8657 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827 8658 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8d64371b
TT
8659 "bytes): %s"),
8660 rsa->sizeof_g_packet, buf_len / 2,
8661 rs->buf.data ());
74ca34ce
DJ
8662
8663 /* Save the size of the packet sent to us by the target. It is used
8664 as a heuristic when determining the max size of packets that the
8665 target can safely receive. */
8666 if (rsa->actual_register_packet_size == 0)
8667 rsa->actual_register_packet_size = buf_len;
8668
8669 /* If this is smaller than we guessed the 'g' packet would be,
8670 update our records. A 'g' reply that doesn't include a register's
8671 value implies either that the register is not available, or that
8672 the 'p' packet must be used. */
8673 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8674 {
9dc193c3 8675 long sizeof_g_packet = buf_len / 2;
74ca34ce 8676
4a22f64d 8677 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8678 {
9dc193c3
LF
8679 long offset = rsa->regs[i].offset;
8680 long reg_size = register_size (gdbarch, i);
8681
74ca34ce
DJ
8682 if (rsa->regs[i].pnum == -1)
8683 continue;
8684
9dc193c3 8685 if (offset >= sizeof_g_packet)
74ca34ce 8686 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8687 else if (offset + reg_size > sizeof_g_packet)
8688 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8689 else
74ca34ce 8690 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8691 }
9dc193c3
LF
8692
8693 /* Looks valid enough, we can assume this is the correct length
dda83cd7
SM
8694 for a 'g' packet. It's important not to adjust
8695 rsa->sizeof_g_packet if we have truncated registers otherwise
8696 this "if" won't be run the next time the method is called
8697 with a packet of the same size and one of the internal errors
8698 below will trigger instead. */
9dc193c3 8699 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8700 }
b323314b 8701
224c3ddb 8702 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8703
8704 /* Unimplemented registers read as all bits zero. */
ea9c271d 8705 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8706
c906108c
SS
8707 /* Reply describes registers byte by byte, each byte encoded as two
8708 hex characters. Suck them all up, then supply them to the
8709 register cacheing/storage mechanism. */
8710
8d64371b 8711 p = rs->buf.data ();
ea9c271d 8712 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8713 {
74ca34ce
DJ
8714 if (p[0] == 0 || p[1] == 0)
8715 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
f34652de 8716 internal_error (_("unexpected end of 'g' packet reply"));
74ca34ce 8717
c906108c 8718 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8719 regs[i] = 0; /* 'x' */
c906108c
SS
8720 else
8721 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8722 p += 2;
8723 }
8724
a744cf53
MS
8725 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8726 {
8727 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8728 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8729
8730 if (r->in_g_packet)
8731 {
8d64371b 8732 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
a744cf53 8733 /* This shouldn't happen - we adjusted in_g_packet above. */
f34652de 8734 internal_error (_("unexpected end of 'g' packet reply"));
a744cf53
MS
8735 else if (rs->buf[r->offset * 2] == 'x')
8736 {
8d64371b 8737 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
a744cf53
MS
8738 /* The register isn't available, mark it as such (at
8739 the same time setting the value to zero). */
73e1c03f 8740 regcache->raw_supply (r->regnum, NULL);
a744cf53
MS
8741 }
8742 else
73e1c03f 8743 regcache->raw_supply (r->regnum, regs + r->offset);
a744cf53
MS
8744 }
8745 }
c906108c
SS
8746}
8747
6b8edb51
PA
8748void
8749remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8750{
8751 send_g_packet ();
56be3814 8752 process_g_packet (regcache);
29709017
DJ
8753}
8754
e6e4e701
PA
8755/* Make the remote selected traceframe match GDB's selected
8756 traceframe. */
8757
6b8edb51
PA
8758void
8759remote_target::set_remote_traceframe ()
e6e4e701
PA
8760{
8761 int newnum;
262e1174 8762 struct remote_state *rs = get_remote_state ();
e6e4e701 8763
262e1174 8764 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8765 return;
8766
8767 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8768 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8769
8770 newnum = target_trace_find (tfind_number,
8771 get_traceframe_number (), 0, 0, NULL);
8772
8773 /* Should not happen. If it does, all bets are off. */
8774 if (newnum != get_traceframe_number ())
8775 warning (_("could not set remote traceframe"));
8776}
8777
f6ac5f3d
PA
8778void
8779remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8780{
ac7936df 8781 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8782 struct remote_state *rs = get_remote_state ();
8783 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8784 int i;
8785
e6e4e701 8786 set_remote_traceframe ();
222312d3 8787 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8788
8789 if (regnum >= 0)
8790 {
5cd63fda 8791 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8792
74ca34ce
DJ
8793 gdb_assert (reg != NULL);
8794
8795 /* If this register might be in the 'g' packet, try that first -
8796 we are likely to read more than one register. If this is the
8797 first 'g' packet, we might be overly optimistic about its
8798 contents, so fall back to 'p'. */
8799 if (reg->in_g_packet)
8800 {
56be3814 8801 fetch_registers_using_g (regcache);
74ca34ce
DJ
8802 if (reg->in_g_packet)
8803 return;
8804 }
8805
56be3814 8806 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8807 return;
8808
8809 /* This register is not available. */
73e1c03f 8810 regcache->raw_supply (reg->regnum, NULL);
74ca34ce
DJ
8811
8812 return;
8813 }
8814
56be3814 8815 fetch_registers_using_g (regcache);
74ca34ce 8816
5cd63fda 8817 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8818 if (!rsa->regs[i].in_g_packet)
56be3814 8819 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8820 {
8821 /* This register is not available. */
73e1c03f 8822 regcache->raw_supply (i, NULL);
74ca34ce
DJ
8823 }
8824}
8825
c906108c
SS
8826/* Prepare to store registers. Since we may send them all (using a
8827 'G' request), we have to read out the ones we don't want to change
8828 first. */
8829
f6ac5f3d
PA
8830void
8831remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8832{
9d6eea31
PA
8833 struct remote_state *rs = get_remote_state ();
8834 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8835 int i;
cf0e1e0d 8836
c906108c 8837 /* Make sure the entire registers array is valid. */
ff52c073 8838 switch (m_features.packet_support (PACKET_P))
5a2468f5
JM
8839 {
8840 case PACKET_DISABLE:
8841 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8842 /* Make sure all the necessary registers are cached. */
ac7936df 8843 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8844 if (rsa->regs[i].in_g_packet)
0b47d985 8845 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
8846 break;
8847 case PACKET_ENABLE:
8848 break;
8849 }
8850}
8851
ad10f812 8852/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8853 packet was not recognized. */
5a2468f5 8854
6b8edb51
PA
8855int
8856remote_target::store_register_using_P (const struct regcache *regcache,
8857 packet_reg *reg)
5a2468f5 8858{
ac7936df 8859 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8860 struct remote_state *rs = get_remote_state ();
5a2468f5 8861 /* Try storing a single register. */
8d64371b 8862 char *buf = rs->buf.data ();
9890e433 8863 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8864 char *p;
5a2468f5 8865
ff52c073 8866 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8867 return 0;
8868
8869 if (reg->pnum == -1)
8870 return 0;
8871
ea9c271d 8872 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8873 p = buf + strlen (buf);
34a79281 8874 regcache->raw_collect (reg->regnum, regp);
4a22f64d 8875 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4 8876 putpkt (rs->buf);
8d64371b 8877 getpkt (&rs->buf, 0);
5a2468f5 8878
ff52c073 8879 switch (m_features.packet_ok (rs->buf, PACKET_P))
74ca34ce
DJ
8880 {
8881 case PACKET_OK:
8882 return 1;
8883 case PACKET_ERROR:
27a9c0bf 8884 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8d64371b 8885 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
74ca34ce
DJ
8886 case PACKET_UNKNOWN:
8887 return 0;
8888 default:
f34652de 8889 internal_error (_("Bad result from packet_ok"));
74ca34ce 8890 }
c906108c
SS
8891}
8892
23860348
MS
8893/* Store register REGNUM, or all registers if REGNUM == -1, from the
8894 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8895
6b8edb51
PA
8896void
8897remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8898{
d01949b6 8899 struct remote_state *rs = get_remote_state ();
9d6eea31 8900 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8901 gdb_byte *regs;
c906108c
SS
8902 char *p;
8903
193cb69f
AC
8904 /* Extract all the registers in the regcache copying them into a
8905 local buffer. */
8906 {
b323314b 8907 int i;
a744cf53 8908
224c3ddb 8909 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8910 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8911 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8912 {
ea9c271d 8913 struct packet_reg *r = &rsa->regs[i];
a744cf53 8914
b323314b 8915 if (r->in_g_packet)
34a79281 8916 regcache->raw_collect (r->regnum, regs + r->offset);
193cb69f
AC
8917 }
8918 }
c906108c
SS
8919
8920 /* Command describes registers byte by byte,
8921 each byte encoded as two hex characters. */
8d64371b 8922 p = rs->buf.data ();
193cb69f 8923 *p++ = 'G';
74ca34ce 8924 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4 8925 putpkt (rs->buf);
8d64371b 8926 getpkt (&rs->buf, 0);
1f4437a4 8927 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf 8928 error (_("Could not write registers; remote failure reply '%s'"),
8d64371b 8929 rs->buf.data ());
c906108c 8930}
74ca34ce
DJ
8931
8932/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8933 of the register cache buffer. FIXME: ignores errors. */
8934
f6ac5f3d
PA
8935void
8936remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8937{
5cd63fda 8938 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8939 struct remote_state *rs = get_remote_state ();
8940 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8941 int i;
8942
e6e4e701 8943 set_remote_traceframe ();
222312d3 8944 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8945
8946 if (regnum >= 0)
8947 {
5cd63fda 8948 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8949
74ca34ce
DJ
8950 gdb_assert (reg != NULL);
8951
8952 /* Always prefer to store registers using the 'P' packet if
8953 possible; we often change only a small number of registers.
8954 Sometimes we change a larger number; we'd need help from a
8955 higher layer to know to use 'G'. */
56be3814 8956 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8957 return;
8958
8959 /* For now, don't complain if we have no way to write the
8960 register. GDB loses track of unavailable registers too
8961 easily. Some day, this may be an error. We don't have
0df8b418 8962 any way to read the register, either... */
74ca34ce
DJ
8963 if (!reg->in_g_packet)
8964 return;
8965
56be3814 8966 store_registers_using_G (regcache);
74ca34ce
DJ
8967 return;
8968 }
8969
56be3814 8970 store_registers_using_G (regcache);
74ca34ce 8971
5cd63fda 8972 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8973 if (!rsa->regs[i].in_g_packet)
56be3814 8974 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8975 /* See above for why we do not issue an error here. */
8976 continue;
8977}
c906108c
SS
8978\f
8979
8980/* Return the number of hex digits in num. */
8981
8982static int
fba45db2 8983hexnumlen (ULONGEST num)
c906108c
SS
8984{
8985 int i;
8986
8987 for (i = 0; num != 0; i++)
8988 num >>= 4;
8989
325fac50 8990 return std::max (i, 1);
c906108c
SS
8991}
8992
2df3850c 8993/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8994
8995static int
fba45db2 8996hexnumstr (char *buf, ULONGEST num)
c906108c 8997{
c906108c 8998 int len = hexnumlen (num);
a744cf53 8999
2df3850c
JM
9000 return hexnumnstr (buf, num, len);
9001}
9002
c906108c 9003
2df3850c 9004/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 9005
2df3850c 9006static int
fba45db2 9007hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
9008{
9009 int i;
9010
9011 buf[width] = '\0';
9012
9013 for (i = width - 1; i >= 0; i--)
c906108c 9014 {
c5aa993b 9015 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
9016 num >>= 4;
9017 }
9018
2df3850c 9019 return width;
c906108c
SS
9020}
9021
23860348 9022/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
9023
9024static CORE_ADDR
fba45db2 9025remote_address_masked (CORE_ADDR addr)
c906108c 9026{
883b9c6c 9027 unsigned int address_size = remote_address_size;
a744cf53 9028
911c95a5
UW
9029 /* If "remoteaddresssize" was not set, default to target address size. */
9030 if (!address_size)
f5656ead 9031 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
9032
9033 if (address_size > 0
9034 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
9035 {
9036 /* Only create a mask when that mask can safely be constructed
dda83cd7 9037 in a ULONGEST variable. */
c906108c 9038 ULONGEST mask = 1;
a744cf53 9039
911c95a5 9040 mask = (mask << address_size) - 1;
c906108c
SS
9041 addr &= mask;
9042 }
9043 return addr;
9044}
9045
9046/* Determine whether the remote target supports binary downloading.
9047 This is accomplished by sending a no-op memory write of zero length
9048 to the target at the specified address. It does not suffice to send
23860348
MS
9049 the whole packet, since many stubs strip the eighth bit and
9050 subsequently compute a wrong checksum, which causes real havoc with
9051 remote_write_bytes.
7a292a7a 9052
96baa820 9053 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 9054 clean. In cases like this, the user should clear "remote
23860348 9055 X-packet". */
96baa820 9056
6b8edb51
PA
9057void
9058remote_target::check_binary_download (CORE_ADDR addr)
c906108c 9059{
d01949b6 9060 struct remote_state *rs = get_remote_state ();
24b06219 9061
ff52c073 9062 switch (m_features.packet_support (PACKET_X))
c906108c 9063 {
96baa820
JM
9064 case PACKET_DISABLE:
9065 break;
9066 case PACKET_ENABLE:
9067 break;
9068 case PACKET_SUPPORT_UNKNOWN:
9069 {
96baa820 9070 char *p;
802188a7 9071
8d64371b 9072 p = rs->buf.data ();
96baa820
JM
9073 *p++ = 'X';
9074 p += hexnumstr (p, (ULONGEST) addr);
9075 *p++ = ',';
9076 p += hexnumstr (p, (ULONGEST) 0);
9077 *p++ = ':';
9078 *p = '\0';
802188a7 9079
8d64371b
TT
9080 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9081 getpkt (&rs->buf, 0);
c906108c 9082
2e9f7625 9083 if (rs->buf[0] == '\0')
96baa820 9084 {
2189c312 9085 remote_debug_printf ("binary downloading NOT supported by target");
ff52c073 9086 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
9087 }
9088 else
9089 {
2189c312 9090 remote_debug_printf ("binary downloading supported by target");
ff52c073 9091 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
9092 }
9093 break;
9094 }
c906108c
SS
9095 }
9096}
9097
124e13d9
SM
9098/* Helper function to resize the payload in order to try to get a good
9099 alignment. We try to write an amount of data such that the next write will
9100 start on an address aligned on REMOTE_ALIGN_WRITES. */
9101
9102static int
9103align_for_efficient_write (int todo, CORE_ADDR memaddr)
9104{
9105 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9106}
9107
c906108c
SS
9108/* Write memory data directly to the remote machine.
9109 This does not inform the data cache; the data cache uses this.
a76d924d 9110 HEADER is the starting part of the packet.
c906108c
SS
9111 MEMADDR is the address in the remote memory space.
9112 MYADDR is the address of the buffer in our space.
124e13d9
SM
9113 LEN_UNITS is the number of addressable units to write.
9114 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
9115 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9116 should send data as binary ('X'), or hex-encoded ('M').
9117
9118 The function creates packet of the form
9119 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9120
124e13d9 9121 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
9122
9123 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9124 are omitted.
9125
9b409511 9126 Return the transferred status, error or OK (an
124e13d9
SM
9127 'enum target_xfer_status' value). Save the number of addressable units
9128 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9129
9130 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9131 exchange between gdb and the stub could look like (?? in place of the
9132 checksum):
9133
9134 -> $m1000,4#??
9135 <- aaaabbbbccccdddd
9136
9137 -> $M1000,3:eeeeffffeeee#??
9138 <- OK
9139
9140 -> $m1000,4#??
9141 <- eeeeffffeeeedddd */
c906108c 9142
6b8edb51
PA
9143target_xfer_status
9144remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9145 const gdb_byte *myaddr,
9146 ULONGEST len_units,
9147 int unit_size,
9148 ULONGEST *xfered_len_units,
9149 char packet_format, int use_length)
c906108c 9150{
6d820c5c 9151 struct remote_state *rs = get_remote_state ();
cfd77fa1 9152 char *p;
a76d924d
DJ
9153 char *plen = NULL;
9154 int plenlen = 0;
124e13d9
SM
9155 int todo_units;
9156 int units_written;
9157 int payload_capacity_bytes;
9158 int payload_length_bytes;
a76d924d
DJ
9159
9160 if (packet_format != 'X' && packet_format != 'M')
f34652de 9161 internal_error (_("remote_write_bytes_aux: bad packet format"));
c906108c 9162
124e13d9 9163 if (len_units == 0)
9b409511 9164 return TARGET_XFER_EOF;
b2182ed2 9165
124e13d9 9166 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 9167
6d820c5c
DJ
9168 /* The packet buffer will be large enough for the payload;
9169 get_memory_packet_size ensures this. */
a76d924d 9170 rs->buf[0] = '\0';
c906108c 9171
a257b5bb 9172 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
9173 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9174
124e13d9 9175 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 9176 if (!use_length)
0df8b418 9177 /* The comma won't be used. */
124e13d9
SM
9178 payload_capacity_bytes += 1;
9179 payload_capacity_bytes -= strlen (header);
9180 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 9181
a76d924d 9182 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 9183
8d64371b
TT
9184 strcat (rs->buf.data (), header);
9185 p = rs->buf.data () + strlen (header);
a76d924d
DJ
9186
9187 /* Compute a best guess of the number of bytes actually transfered. */
9188 if (packet_format == 'X')
c906108c 9189 {
23860348 9190 /* Best guess at number of bytes that will fit. */
325fac50
PA
9191 todo_units = std::min (len_units,
9192 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 9193 if (use_length)
124e13d9 9194 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 9195 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
9196 }
9197 else
9198 {
124e13d9 9199 /* Number of bytes that will fit. */
325fac50
PA
9200 todo_units
9201 = std::min (len_units,
9202 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 9203 if (use_length)
124e13d9 9204 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
9205 todo_units = std::min (todo_units,
9206 (payload_capacity_bytes / unit_size) / 2);
917317f4 9207 }
a76d924d 9208
124e13d9 9209 if (todo_units <= 0)
f34652de 9210 internal_error (_("minimum packet size too small to write data"));
802188a7 9211
6765f3e5
DJ
9212 /* If we already need another packet, then try to align the end
9213 of this packet to a useful boundary. */
124e13d9
SM
9214 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9215 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 9216
a257b5bb 9217 /* Append "<memaddr>". */
917317f4
JM
9218 memaddr = remote_address_masked (memaddr);
9219 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 9220
a76d924d
DJ
9221 if (use_length)
9222 {
9223 /* Append ",". */
9224 *p++ = ',';
802188a7 9225
124e13d9 9226 /* Append the length and retain its location and size. It may need to be
dda83cd7 9227 adjusted once the packet body has been created. */
a76d924d 9228 plen = p;
124e13d9 9229 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
9230 p += plenlen;
9231 }
a257b5bb
AC
9232
9233 /* Append ":". */
917317f4
JM
9234 *p++ = ':';
9235 *p = '\0';
802188a7 9236
a257b5bb 9237 /* Append the packet body. */
a76d924d 9238 if (packet_format == 'X')
917317f4 9239 {
917317f4
JM
9240 /* Binary mode. Send target system values byte by byte, in
9241 increasing byte addresses. Only escape certain critical
9242 characters. */
124e13d9
SM
9243 payload_length_bytes =
9244 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9245 &units_written, payload_capacity_bytes);
6765f3e5 9246
124e13d9 9247 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
9248 a second try to keep the end of the packet aligned. Don't do
9249 this if the packet is tiny. */
124e13d9 9250 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 9251 {
124e13d9
SM
9252 int new_todo_units;
9253
9254 new_todo_units = align_for_efficient_write (units_written, memaddr);
9255
9256 if (new_todo_units != units_written)
9257 payload_length_bytes =
9258 remote_escape_output (myaddr, new_todo_units, unit_size,
9259 (gdb_byte *) p, &units_written,
9260 payload_capacity_bytes);
6765f3e5
DJ
9261 }
9262
124e13d9
SM
9263 p += payload_length_bytes;
9264 if (use_length && units_written < todo_units)
c906108c 9265 {
802188a7 9266 /* Escape chars have filled up the buffer prematurely,
124e13d9 9267 and we have actually sent fewer units than planned.
917317f4
JM
9268 Fix-up the length field of the packet. Use the same
9269 number of characters as before. */
124e13d9
SM
9270 plen += hexnumnstr (plen, (ULONGEST) units_written,
9271 plenlen);
917317f4 9272 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 9273 }
a76d924d
DJ
9274 }
9275 else
9276 {
917317f4
JM
9277 /* Normal mode: Send target system values byte by byte, in
9278 increasing byte addresses. Each byte is encoded as a two hex
9279 value. */
124e13d9
SM
9280 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9281 units_written = todo_units;
c906108c 9282 }
802188a7 9283
8d64371b
TT
9284 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9285 getpkt (&rs->buf, 0);
802188a7 9286
2e9f7625 9287 if (rs->buf[0] == 'E')
00d84524 9288 return TARGET_XFER_E_IO;
802188a7 9289
124e13d9
SM
9290 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9291 send fewer units than we'd planned. */
9292 *xfered_len_units = (ULONGEST) units_written;
92ffd475 9293 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
9294}
9295
a76d924d
DJ
9296/* Write memory data directly to the remote machine.
9297 This does not inform the data cache; the data cache uses this.
9298 MEMADDR is the address in the remote memory space.
9299 MYADDR is the address of the buffer in our space.
9300 LEN is the number of bytes.
9301
9b409511
YQ
9302 Return the transferred status, error or OK (an
9303 'enum target_xfer_status' value). Save the number of bytes
9304 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 9305
6b8edb51
PA
9306target_xfer_status
9307remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9308 ULONGEST len, int unit_size,
9309 ULONGEST *xfered_len)
a76d924d 9310{
a121b7c1 9311 const char *packet_format = NULL;
a76d924d
DJ
9312
9313 /* Check whether the target supports binary download. */
9314 check_binary_download (memaddr);
9315
ff52c073 9316 switch (m_features.packet_support (PACKET_X))
a76d924d
DJ
9317 {
9318 case PACKET_ENABLE:
9319 packet_format = "X";
9320 break;
9321 case PACKET_DISABLE:
9322 packet_format = "M";
9323 break;
9324 case PACKET_SUPPORT_UNKNOWN:
f34652de 9325 internal_error (_("remote_write_bytes: bad internal state"));
a76d924d 9326 default:
f34652de 9327 internal_error (_("bad switch"));
a76d924d
DJ
9328 }
9329
9330 return remote_write_bytes_aux (packet_format,
124e13d9 9331 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 9332 packet_format[0], 1);
a76d924d
DJ
9333}
9334
9217e74e
YQ
9335/* Read memory data directly from the remote machine.
9336 This does not use the data cache; the data cache uses this.
9337 MEMADDR is the address in the remote memory space.
9338 MYADDR is the address of the buffer in our space.
124e13d9
SM
9339 LEN_UNITS is the number of addressable memory units to read..
9340 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
9341
9342 Return the transferred status, error or OK (an
9343 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
9344 transferred in *XFERED_LEN_UNITS.
9345
9346 See the comment of remote_write_bytes_aux for an example of
9347 memory read/write exchange between gdb and the stub. */
9217e74e 9348
6b8edb51
PA
9349target_xfer_status
9350remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9351 ULONGEST len_units,
9352 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
9353{
9354 struct remote_state *rs = get_remote_state ();
124e13d9 9355 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 9356 char *p;
124e13d9
SM
9357 int todo_units;
9358 int decoded_bytes;
9217e74e 9359
124e13d9 9360 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
9361 /* The packet buffer will be large enough for the payload;
9362 get_memory_packet_size ensures this. */
9363
124e13d9 9364 /* Number of units that will fit. */
325fac50
PA
9365 todo_units = std::min (len_units,
9366 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
9367
9368 /* Construct "m"<memaddr>","<len>". */
9369 memaddr = remote_address_masked (memaddr);
8d64371b 9370 p = rs->buf.data ();
9217e74e
YQ
9371 *p++ = 'm';
9372 p += hexnumstr (p, (ULONGEST) memaddr);
9373 *p++ = ',';
124e13d9 9374 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
9375 *p = '\0';
9376 putpkt (rs->buf);
8d64371b 9377 getpkt (&rs->buf, 0);
9217e74e
YQ
9378 if (rs->buf[0] == 'E'
9379 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9380 && rs->buf[3] == '\0')
9381 return TARGET_XFER_E_IO;
9382 /* Reply describes memory byte by byte, each byte encoded as two hex
9383 characters. */
8d64371b 9384 p = rs->buf.data ();
124e13d9 9385 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 9386 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 9387 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 9388 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
9389}
9390
b55fbac4
YQ
9391/* Using the set of read-only target sections of remote, read live
9392 read-only memory.
8acf9577
YQ
9393
9394 For interface/parameters/return description see target.h,
9395 to_xfer_partial. */
9396
6b8edb51
PA
9397target_xfer_status
9398remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9399 ULONGEST memaddr,
9400 ULONGEST len,
9401 int unit_size,
9402 ULONGEST *xfered_len)
8acf9577 9403{
19cf757a 9404 const struct target_section *secp;
8acf9577 9405
6b8edb51 9406 secp = target_section_by_addr (this, memaddr);
8acf9577 9407 if (secp != NULL
fd361982 9408 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
8acf9577 9409 {
8acf9577
YQ
9410 ULONGEST memend = memaddr + len;
9411
19cf757a
AB
9412 const target_section_table *table = target_get_section_table (this);
9413 for (const target_section &p : *table)
8acf9577 9414 {
bb2a6777 9415 if (memaddr >= p.addr)
8acf9577 9416 {
bb2a6777 9417 if (memend <= p.endaddr)
8acf9577
YQ
9418 {
9419 /* Entire transfer is within this section. */
124e13d9 9420 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9421 xfered_len);
8acf9577 9422 }
bb2a6777 9423 else if (memaddr >= p.endaddr)
8acf9577
YQ
9424 {
9425 /* This section ends before the transfer starts. */
9426 continue;
9427 }
9428 else
9429 {
9430 /* This section overlaps the transfer. Just do half. */
bb2a6777 9431 len = p.endaddr - memaddr;
124e13d9 9432 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9433 xfered_len);
8acf9577
YQ
9434 }
9435 }
9436 }
9437 }
9438
9439 return TARGET_XFER_EOF;
9440}
9441
9217e74e
YQ
9442/* Similar to remote_read_bytes_1, but it reads from the remote stub
9443 first if the requested memory is unavailable in traceframe.
9444 Otherwise, fall back to remote_read_bytes_1. */
c906108c 9445
6b8edb51
PA
9446target_xfer_status
9447remote_target::remote_read_bytes (CORE_ADDR memaddr,
9448 gdb_byte *myaddr, ULONGEST len, int unit_size,
9449 ULONGEST *xfered_len)
c906108c 9450{
6b6aa828 9451 if (len == 0)
96c4f946 9452 return TARGET_XFER_EOF;
b2182ed2 9453
8acf9577
YQ
9454 if (get_traceframe_number () != -1)
9455 {
a79b1bc6 9456 std::vector<mem_range> available;
8acf9577
YQ
9457
9458 /* If we fail to get the set of available memory, then the
9459 target does not support querying traceframe info, and so we
9460 attempt reading from the traceframe anyway (assuming the
9461 target implements the old QTro packet then). */
9462 if (traceframe_available_memory (&available, memaddr, len))
9463 {
a79b1bc6 9464 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
9465 {
9466 enum target_xfer_status res;
9467
9468 /* Don't read into the traceframe's available
9469 memory. */
a79b1bc6 9470 if (!available.empty ())
8acf9577
YQ
9471 {
9472 LONGEST oldlen = len;
9473
a79b1bc6 9474 len = available[0].start - memaddr;
8acf9577
YQ
9475 gdb_assert (len <= oldlen);
9476 }
9477
8acf9577 9478 /* This goes through the topmost target again. */
6b8edb51 9479 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 9480 len, unit_size, xfered_len);
8acf9577
YQ
9481 if (res == TARGET_XFER_OK)
9482 return TARGET_XFER_OK;
9483 else
9484 {
9485 /* No use trying further, we know some memory starting
9486 at MEMADDR isn't available. */
9487 *xfered_len = len;
92ffd475
PC
9488 return (*xfered_len != 0) ?
9489 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
9490 }
9491 }
9492
9493 /* Don't try to read more than how much is available, in
9494 case the target implements the deprecated QTro packet to
9495 cater for older GDBs (the target's knowledge of read-only
9496 sections may be outdated by now). */
a79b1bc6 9497 len = available[0].length;
8acf9577
YQ
9498 }
9499 }
9500
124e13d9 9501 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 9502}
74531fed 9503
c906108c 9504\f
c906108c 9505
a76d924d
DJ
9506/* Sends a packet with content determined by the printf format string
9507 FORMAT and the remaining arguments, then gets the reply. Returns
9508 whether the packet was a success, a failure, or unknown. */
9509
6b8edb51
PA
9510packet_result
9511remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
9512{
9513 struct remote_state *rs = get_remote_state ();
9514 int max_size = get_remote_packet_size ();
a76d924d 9515 va_list ap;
a744cf53 9516
a76d924d
DJ
9517 va_start (ap, format);
9518
9519 rs->buf[0] = '\0';
8d64371b 9520 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
33b031ce
GB
9521
9522 va_end (ap);
9523
9524 if (size >= max_size)
f34652de 9525 internal_error (_("Too long remote packet."));
a76d924d
DJ
9526
9527 if (putpkt (rs->buf) < 0)
9528 error (_("Communication problem with target."));
9529
9530 rs->buf[0] = '\0';
8d64371b 9531 getpkt (&rs->buf, 0);
a76d924d
DJ
9532
9533 return packet_check_result (rs->buf);
9534}
9535
a76d924d
DJ
9536/* Flash writing can take quite some time. We'll set
9537 effectively infinite timeout for flash operations.
9538 In future, we'll need to decide on a better approach. */
9539static const int remote_flash_timeout = 1000;
9540
f6ac5f3d
PA
9541void
9542remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 9543{
f5656ead 9544 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 9545 enum packet_result ret;
2ec845e7
TT
9546 scoped_restore restore_timeout
9547 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
9548
9549 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 9550 phex (address, addr_size),
a76d924d
DJ
9551 phex (length, 4));
9552 switch (ret)
9553 {
9554 case PACKET_UNKNOWN:
9555 error (_("Remote target does not support flash erase"));
9556 case PACKET_ERROR:
9557 error (_("Error erasing flash with vFlashErase packet"));
9558 default:
9559 break;
9560 }
a76d924d
DJ
9561}
9562
6b8edb51
PA
9563target_xfer_status
9564remote_target::remote_flash_write (ULONGEST address,
9565 ULONGEST length, ULONGEST *xfered_len,
9566 const gdb_byte *data)
a76d924d 9567{
2ec845e7
TT
9568 scoped_restore restore_timeout
9569 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9570 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9571 xfered_len,'X', 0);
a76d924d
DJ
9572}
9573
f6ac5f3d
PA
9574void
9575remote_target::flash_done ()
a76d924d 9576{
a76d924d 9577 int ret;
a76d924d 9578
2ec845e7
TT
9579 scoped_restore restore_timeout
9580 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9581
a76d924d 9582 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
9583
9584 switch (ret)
9585 {
9586 case PACKET_UNKNOWN:
9587 error (_("Remote target does not support vFlashDone"));
9588 case PACKET_ERROR:
9589 error (_("Error finishing flash operation"));
9590 default:
9591 break;
9592 }
9593}
9594
c906108c
SS
9595\f
9596/* Stuff for dealing with the packets which are part of this protocol.
9597 See comment at top of file for details. */
9598
1927e618
PA
9599/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9600 error to higher layers. Called when a serial error is detected.
9601 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
9602 the system error message for errno at function entry and final dot
9603 for output compatibility with throw_perror_with_name. */
1927e618
PA
9604
9605static void
5b6d1e4f 9606unpush_and_perror (remote_target *target, const char *string)
1927e618 9607{
d6cb50a2 9608 int saved_errno = errno;
1927e618 9609
5b6d1e4f 9610 remote_unpush_target (target);
d6cb50a2
JK
9611 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9612 safe_strerror (saved_errno));
1927e618
PA
9613}
9614
048094ac
PA
9615/* Read a single character from the remote end. The current quit
9616 handler is overridden to avoid quitting in the middle of packet
9617 sequence, as that would break communication with the remote server.
9618 See remote_serial_quit_handler for more detail. */
c906108c 9619
6b8edb51
PA
9620int
9621remote_target::readchar (int timeout)
c906108c
SS
9622{
9623 int ch;
5d93a237 9624 struct remote_state *rs = get_remote_state ();
048094ac 9625
2ec845e7 9626 {
6b8edb51
PA
9627 scoped_restore restore_quit_target
9628 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9629 scoped_restore restore_quit
6b8edb51 9630 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9631
2ec845e7 9632 rs->got_ctrlc_during_io = 0;
c906108c 9633
2ec845e7 9634 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9635
2ec845e7
TT
9636 if (rs->got_ctrlc_during_io)
9637 set_quit_flag ();
9638 }
048094ac 9639
2acceee2 9640 if (ch >= 0)
0876f84a 9641 return ch;
2acceee2
JM
9642
9643 switch ((enum serial_rc) ch)
c906108c
SS
9644 {
9645 case SERIAL_EOF:
5b6d1e4f 9646 remote_unpush_target (this);
598d3636 9647 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9648 /* no return */
c906108c 9649 case SERIAL_ERROR:
5b6d1e4f 9650 unpush_and_perror (this, _("Remote communication error. "
c8f6fc92 9651 "Target disconnected"));
2acceee2 9652 /* no return */
c906108c 9653 case SERIAL_TIMEOUT:
2acceee2 9654 break;
c906108c 9655 }
2acceee2 9656 return ch;
c906108c
SS
9657}
9658
c33e31fd 9659/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9660 writing fails. The current quit handler is overridden to avoid
9661 quitting in the middle of packet sequence, as that would break
9662 communication with the remote server. See
9663 remote_serial_quit_handler for more detail. */
c33e31fd 9664
6b8edb51
PA
9665void
9666remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9667{
5d93a237 9668 struct remote_state *rs = get_remote_state ();
048094ac 9669
6b8edb51
PA
9670 scoped_restore restore_quit_target
9671 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9672 scoped_restore restore_quit
6b8edb51 9673 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9674
9675 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9676
9677 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9678 {
5b6d1e4f 9679 unpush_and_perror (this, _("Remote communication error. "
c8f6fc92 9680 "Target disconnected"));
c33e31fd 9681 }
048094ac
PA
9682
9683 if (rs->got_ctrlc_during_io)
9684 set_quit_flag ();
c33e31fd
PA
9685}
9686
b3ced9ba
PA
9687/* Return a string representing an escaped version of BUF, of len N.
9688 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9689
b3ced9ba 9690static std::string
6e5abd65
PA
9691escape_buffer (const char *buf, int n)
9692{
d7e74731 9693 string_file stb;
6e5abd65 9694
d7e74731 9695 stb.putstrn (buf, n, '\\');
5d10a204 9696 return stb.release ();
6e5abd65
PA
9697}
9698
c906108c 9699int
6b8edb51 9700remote_target::putpkt (const char *buf)
c906108c
SS
9701{
9702 return putpkt_binary (buf, strlen (buf));
9703}
9704
6b8edb51
PA
9705/* Wrapper around remote_target::putpkt to avoid exporting
9706 remote_target. */
9707
9708int
9709putpkt (remote_target *remote, const char *buf)
9710{
9711 return remote->putpkt (buf);
9712}
9713
c906108c 9714/* Send a packet to the remote machine, with error checking. The data
23860348 9715 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9716 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9717 and for a possible /0 if we are debugging (remote_debug) and want
9718 to print the sent packet as a string. */
c906108c 9719
6b8edb51
PA
9720int
9721remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9722{
2d717e4f 9723 struct remote_state *rs = get_remote_state ();
c906108c
SS
9724 int i;
9725 unsigned char csum = 0;
b80406ac
TT
9726 gdb::def_vector<char> data (cnt + 6);
9727 char *buf2 = data.data ();
085dd6e6 9728
c906108c
SS
9729 int ch;
9730 int tcount = 0;
9731 char *p;
9732
e24a49d8
PA
9733 /* Catch cases like trying to read memory or listing threads while
9734 we're waiting for a stop reply. The remote server wouldn't be
9735 ready to handle this request, so we'd hang and timeout. We don't
9736 have to worry about this in synchronous mode, because in that
9737 case it's not possible to issue a command while the target is
74531fed
PA
9738 running. This is not a problem in non-stop mode, because in that
9739 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9740 if (!target_is_non_stop_p ()
9741 && target_is_async_p ()
9742 && rs->waiting_for_stop_reply)
9597b22a
DE
9743 {
9744 error (_("Cannot execute this command while the target is running.\n"
9745 "Use the \"interrupt\" command to stop the target\n"
9746 "and then try again."));
9747 }
e24a49d8 9748
c906108c
SS
9749 /* Copy the packet into buffer BUF2, encapsulating it
9750 and giving it a checksum. */
9751
c906108c
SS
9752 p = buf2;
9753 *p++ = '$';
9754
9755 for (i = 0; i < cnt; i++)
9756 {
9757 csum += buf[i];
9758 *p++ = buf[i];
9759 }
9760 *p++ = '#';
9761 *p++ = tohex ((csum >> 4) & 0xf);
9762 *p++ = tohex (csum & 0xf);
9763
9764 /* Send it over and over until we get a positive ack. */
9765
9766 while (1)
9767 {
c906108c
SS
9768 if (remote_debug)
9769 {
9770 *p = '\0';
b3ced9ba 9771
6f8976bf 9772 int len = (int) (p - buf2);
6cc8564b
LM
9773 int max_chars;
9774
9775 if (remote_packet_max_chars < 0)
9776 max_chars = len;
9777 else
9778 max_chars = remote_packet_max_chars;
6f8976bf
YQ
9779
9780 std::string str
6cc8564b 9781 = escape_buffer (buf2, std::min (len, max_chars));
6f8976bf 9782
6cc8564b 9783 if (len > max_chars)
2189c312
SM
9784 remote_debug_printf_nofunc
9785 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9786 len - max_chars);
9787 else
9788 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
c906108c 9789 }
c33e31fd 9790 remote_serial_write (buf2, p - buf2);
c906108c 9791
a6f3e723
SL
9792 /* If this is a no acks version of the remote protocol, send the
9793 packet and move on. */
9794 if (rs->noack_mode)
dda83cd7 9795 break;
a6f3e723 9796
74531fed
PA
9797 /* Read until either a timeout occurs (-2) or '+' is read.
9798 Handle any notification that arrives in the mean time. */
c906108c
SS
9799 while (1)
9800 {
9801 ch = readchar (remote_timeout);
9802
c906108c
SS
9803 switch (ch)
9804 {
9805 case '+':
2189c312 9806 remote_debug_printf_nofunc ("Received Ack");
c906108c 9807 return 1;
1216fa2c 9808 case '-':
2189c312 9809 remote_debug_printf_nofunc ("Received Nak");
a17d146e 9810 /* FALLTHROUGH */
c906108c 9811 case SERIAL_TIMEOUT:
c5aa993b 9812 tcount++;
c906108c 9813 if (tcount > 3)
b80406ac 9814 return 0;
23860348 9815 break; /* Retransmit buffer. */
c906108c
SS
9816 case '$':
9817 {
2189c312 9818 remote_debug_printf ("Packet instead of Ack, ignoring it");
d6f7abdf
AC
9819 /* It's probably an old response sent because an ACK
9820 was lost. Gobble up the packet and ack it so it
9821 doesn't get retransmitted when we resend this
9822 packet. */
6d820c5c 9823 skip_frame ();
c33e31fd 9824 remote_serial_write ("+", 1);
23860348 9825 continue; /* Now, go look for +. */
c906108c 9826 }
74531fed
PA
9827
9828 case '%':
9829 {
9830 int val;
9831
9832 /* If we got a notification, handle it, and go back to looking
9833 for an ack. */
9834 /* We've found the start of a notification. Now
9835 collect the data. */
8d64371b 9836 val = read_frame (&rs->buf);
74531fed
PA
9837 if (val >= 0)
9838 {
2189c312
SM
9839 remote_debug_printf_nofunc
9840 (" Notification received: %s",
9841 escape_buffer (rs->buf.data (), val).c_str ());
6e5abd65 9842
8d64371b 9843 handle_notification (rs->notif_state, rs->buf.data ());
74531fed
PA
9844 /* We're in sync now, rewait for the ack. */
9845 tcount = 0;
9846 }
9847 else
2189c312
SM
9848 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9849 rs->buf.data ());
74531fed
PA
9850 continue;
9851 }
9852 /* fall-through */
c906108c 9853 default:
2189c312
SM
9854 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9855 rs->buf.data ());
c906108c
SS
9856 continue;
9857 }
23860348 9858 break; /* Here to retransmit. */
c906108c
SS
9859 }
9860
9861#if 0
9862 /* This is wrong. If doing a long backtrace, the user should be
dda83cd7
SM
9863 able to get out next time we call QUIT, without anything as
9864 violent as interrupt_query. If we want to provide a way out of
9865 here without getting to the next QUIT, it should be based on
9866 hitting ^C twice as in remote_wait. */
c906108c
SS
9867 if (quit_flag)
9868 {
9869 quit_flag = 0;
9870 interrupt_query ();
9871 }
9872#endif
9873 }
a5c0808e 9874
a6f3e723 9875 return 0;
c906108c
SS
9876}
9877
6d820c5c
DJ
9878/* Come here after finding the start of a frame when we expected an
9879 ack. Do our best to discard the rest of this packet. */
9880
6b8edb51
PA
9881void
9882remote_target::skip_frame ()
6d820c5c
DJ
9883{
9884 int c;
9885
9886 while (1)
9887 {
9888 c = readchar (remote_timeout);
9889 switch (c)
9890 {
9891 case SERIAL_TIMEOUT:
9892 /* Nothing we can do. */
9893 return;
9894 case '#':
9895 /* Discard the two bytes of checksum and stop. */
9896 c = readchar (remote_timeout);
9897 if (c >= 0)
9898 c = readchar (remote_timeout);
9899
9900 return;
9901 case '*': /* Run length encoding. */
9902 /* Discard the repeat count. */
9903 c = readchar (remote_timeout);
9904 if (c < 0)
9905 return;
9906 break;
9907 default:
9908 /* A regular character. */
9909 break;
9910 }
9911 }
9912}
9913
c906108c 9914/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9915 into *BUF, verifying the checksum, length, and handling run-length
9916 compression. NUL terminate the buffer. If there is not enough room,
8d64371b 9917 expand *BUF.
c906108c 9918
c2d11a7d
JM
9919 Returns -1 on error, number of characters in buffer (ignoring the
9920 trailing NULL) on success. (could be extended to return one of the
23860348 9921 SERIAL status indications). */
c2d11a7d 9922
6b8edb51 9923long
8d64371b 9924remote_target::read_frame (gdb::char_vector *buf_p)
c906108c
SS
9925{
9926 unsigned char csum;
c2d11a7d 9927 long bc;
c906108c 9928 int c;
8d64371b 9929 char *buf = buf_p->data ();
a6f3e723 9930 struct remote_state *rs = get_remote_state ();
c906108c
SS
9931
9932 csum = 0;
c2d11a7d 9933 bc = 0;
c906108c
SS
9934
9935 while (1)
9936 {
9937 c = readchar (remote_timeout);
c906108c
SS
9938 switch (c)
9939 {
9940 case SERIAL_TIMEOUT:
2189c312 9941 remote_debug_printf ("Timeout in mid-packet, retrying");
c2d11a7d 9942 return -1;
2189c312 9943
c906108c 9944 case '$':
2189c312 9945 remote_debug_printf ("Saw new packet start in middle of old one");
23860348 9946 return -1; /* Start a new packet, count retries. */
2189c312 9947
c906108c
SS
9948 case '#':
9949 {
9950 unsigned char pktcsum;
e1b09194
AC
9951 int check_0 = 0;
9952 int check_1 = 0;
c906108c 9953
c2d11a7d 9954 buf[bc] = '\0';
c906108c 9955
e1b09194
AC
9956 check_0 = readchar (remote_timeout);
9957 if (check_0 >= 0)
9958 check_1 = readchar (remote_timeout);
802188a7 9959
e1b09194
AC
9960 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9961 {
2189c312 9962 remote_debug_printf ("Timeout in checksum, retrying");
e1b09194
AC
9963 return -1;
9964 }
9965 else if (check_0 < 0 || check_1 < 0)
40e3f985 9966 {
2189c312 9967 remote_debug_printf ("Communication error in checksum");
40e3f985
FN
9968 return -1;
9969 }
c906108c 9970
a6f3e723
SL
9971 /* Don't recompute the checksum; with no ack packets we
9972 don't have any way to indicate a packet retransmission
9973 is necessary. */
9974 if (rs->noack_mode)
9975 return bc;
9976
e1b09194 9977 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9978 if (csum == pktcsum)
dda83cd7 9979 return bc;
c906108c 9980
2189c312
SM
9981 remote_debug_printf
9982 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9983 pktcsum, csum, escape_buffer (buf, bc).c_str ());
6e5abd65 9984
c2d11a7d 9985 /* Number of characters in buffer ignoring trailing
dda83cd7 9986 NULL. */
c2d11a7d 9987 return -1;
c906108c 9988 }
23860348 9989 case '*': /* Run length encoding. */
dda83cd7 9990 {
c2c6d25f 9991 int repeat;
c906108c 9992
24b21115 9993 csum += c;
b4501125
AC
9994 c = readchar (remote_timeout);
9995 csum += c;
23860348 9996 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9997
23860348 9998 /* The character before ``*'' is repeated. */
c2d11a7d 9999
6d820c5c 10000 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 10001 {
8d64371b 10002 if (bc + repeat - 1 >= buf_p->size () - 1)
6d820c5c
DJ
10003 {
10004 /* Make some more room in the buffer. */
8d64371b
TT
10005 buf_p->resize (buf_p->size () + repeat);
10006 buf = buf_p->data ();
6d820c5c
DJ
10007 }
10008
c2d11a7d
JM
10009 memset (&buf[bc], buf[bc - 1], repeat);
10010 bc += repeat;
c2c6d25f
JM
10011 continue;
10012 }
10013
c2d11a7d 10014 buf[bc] = '\0';
6cb06a8c 10015 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 10016 return -1;
c2c6d25f 10017 }
c906108c 10018 default:
8d64371b 10019 if (bc >= buf_p->size () - 1)
c906108c 10020 {
6d820c5c 10021 /* Make some more room in the buffer. */
8d64371b
TT
10022 buf_p->resize (buf_p->size () * 2);
10023 buf = buf_p->data ();
c906108c
SS
10024 }
10025
6d820c5c
DJ
10026 buf[bc++] = c;
10027 csum += c;
10028 continue;
c906108c
SS
10029 }
10030 }
10031}
10032
ed2b7c17
TT
10033/* Set this to the maximum number of seconds to wait instead of waiting forever
10034 in target_wait(). If this timer times out, then it generates an error and
10035 the command is aborted. This replaces most of the need for timeouts in the
10036 GDB test suite, and makes it possible to distinguish between a hung target
10037 and one with slow communications. */
10038
10039static int watchdog = 0;
10040static void
10041show_watchdog (struct ui_file *file, int from_tty,
10042 struct cmd_list_element *c, const char *value)
10043{
6cb06a8c 10044 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
ed2b7c17
TT
10045}
10046
c906108c 10047/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
10048 store it in *BUF. Resize *BUF if necessary to hold the result. If
10049 FOREVER, wait forever rather than timing out; this is used (in
10050 synchronous mode) to wait for a target that is is executing user
10051 code to stop. */
d9fcf2fb
JM
10052/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
10053 don't have to change all the calls to getpkt to deal with the
10054 return value, because at the moment I don't know what the right
23860348 10055 thing to do it for those. */
6b8edb51 10056
c906108c 10057void
8d64371b 10058remote_target::getpkt (gdb::char_vector *buf, int forever)
d9fcf2fb 10059{
8d64371b 10060 getpkt_sane (buf, forever);
d9fcf2fb
JM
10061}
10062
10063
10064/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
10065 store it in *BUF. Resize *BUF if necessary to hold the result. If
10066 FOREVER, wait forever rather than timing out; this is used (in
10067 synchronous mode) to wait for a target that is is executing user
10068 code to stop. If FOREVER == 0, this function is allowed to time
10069 out gracefully and return an indication of this to the caller.
10070 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
10071 consider receiving a notification enough reason to return to the
10072 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
10073 holds a notification or not (a regular packet). */
74531fed 10074
6b8edb51 10075int
8d64371b 10076remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
6b8edb51
PA
10077 int forever, int expecting_notif,
10078 int *is_notif)
c906108c 10079{
2d717e4f 10080 struct remote_state *rs = get_remote_state ();
c906108c
SS
10081 int c;
10082 int tries;
10083 int timeout;
df4b58fe 10084 int val = -1;
c906108c 10085
8d64371b 10086 strcpy (buf->data (), "timeout");
c906108c
SS
10087
10088 if (forever)
74531fed
PA
10089 timeout = watchdog > 0 ? watchdog : -1;
10090 else if (expecting_notif)
10091 timeout = 0; /* There should already be a char in the buffer. If
10092 not, bail out. */
c906108c
SS
10093 else
10094 timeout = remote_timeout;
10095
10096#define MAX_TRIES 3
10097
74531fed
PA
10098 /* Process any number of notifications, and then return when
10099 we get a packet. */
10100 for (;;)
c906108c 10101 {
d9c43928 10102 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
10103 times. */
10104 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 10105 {
74531fed
PA
10106 /* This can loop forever if the remote side sends us
10107 characters continuously, but if it pauses, we'll get
10108 SERIAL_TIMEOUT from readchar because of timeout. Then
10109 we'll count that as a retry.
10110
10111 Note that even when forever is set, we will only wait
10112 forever prior to the start of a packet. After that, we
10113 expect characters to arrive at a brisk pace. They should
10114 show up within remote_timeout intervals. */
10115 do
10116 c = readchar (timeout);
10117 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
10118
10119 if (c == SERIAL_TIMEOUT)
10120 {
74531fed
PA
10121 if (expecting_notif)
10122 return -1; /* Don't complain, it's normal to not get
10123 anything in this case. */
10124
23860348 10125 if (forever) /* Watchdog went off? Kill the target. */
c906108c 10126 {
5b6d1e4f 10127 remote_unpush_target (this);
598d3636
JK
10128 throw_error (TARGET_CLOSE_ERROR,
10129 _("Watchdog timeout has expired. "
10130 "Target detached."));
c906108c 10131 }
2189c312
SM
10132
10133 remote_debug_printf ("Timed out.");
c906108c 10134 }
74531fed
PA
10135 else
10136 {
10137 /* We've found the start of a packet or notification.
10138 Now collect the data. */
8d64371b 10139 val = read_frame (buf);
74531fed
PA
10140 if (val >= 0)
10141 break;
10142 }
10143
c33e31fd 10144 remote_serial_write ("-", 1);
c906108c 10145 }
c906108c 10146
74531fed
PA
10147 if (tries > MAX_TRIES)
10148 {
10149 /* We have tried hard enough, and just can't receive the
10150 packet/notification. Give up. */
6cb06a8c 10151 gdb_printf (_("Ignoring packet error, continuing...\n"));
c906108c 10152
74531fed
PA
10153 /* Skip the ack char if we're in no-ack mode. */
10154 if (!rs->noack_mode)
c33e31fd 10155 remote_serial_write ("+", 1);
74531fed
PA
10156 return -1;
10157 }
c906108c 10158
74531fed
PA
10159 /* If we got an ordinary packet, return that to our caller. */
10160 if (c == '$')
c906108c
SS
10161 {
10162 if (remote_debug)
43e526b9 10163 {
6cc8564b
LM
10164 int max_chars;
10165
10166 if (remote_packet_max_chars < 0)
10167 max_chars = val;
10168 else
10169 max_chars = remote_packet_max_chars;
10170
6f8976bf 10171 std::string str
8d64371b 10172 = escape_buffer (buf->data (),
6cc8564b 10173 std::min (val, max_chars));
6f8976bf 10174
6cc8564b 10175 if (val > max_chars)
2189c312
SM
10176 remote_debug_printf_nofunc
10177 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10178 val - max_chars);
10179 else
10180 remote_debug_printf_nofunc ("Packet received: %s",
10181 str.c_str ());
43e526b9 10182 }
a6f3e723
SL
10183
10184 /* Skip the ack char if we're in no-ack mode. */
10185 if (!rs->noack_mode)
c33e31fd 10186 remote_serial_write ("+", 1);
fee9eda9
YQ
10187 if (is_notif != NULL)
10188 *is_notif = 0;
0876f84a 10189 return val;
c906108c
SS
10190 }
10191
74531fed
PA
10192 /* If we got a notification, handle it, and go back to looking
10193 for a packet. */
10194 else
10195 {
10196 gdb_assert (c == '%');
10197
2189c312
SM
10198 remote_debug_printf_nofunc
10199 (" Notification received: %s",
10200 escape_buffer (buf->data (), val).c_str ());
6e5abd65 10201
fee9eda9
YQ
10202 if (is_notif != NULL)
10203 *is_notif = 1;
c906108c 10204
8d64371b 10205 handle_notification (rs->notif_state, buf->data ());
c906108c 10206
74531fed 10207 /* Notifications require no acknowledgement. */
a6f3e723 10208
74531fed 10209 if (expecting_notif)
fee9eda9 10210 return val;
74531fed
PA
10211 }
10212 }
10213}
10214
6b8edb51 10215int
8d64371b 10216remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
74531fed 10217{
8d64371b 10218 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
74531fed
PA
10219}
10220
6b8edb51 10221int
8d64371b 10222remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
6b8edb51 10223 int *is_notif)
74531fed 10224{
8d64371b 10225 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
c906108c 10226}
74531fed 10227
28561a65 10228/* Kill any new fork children of inferior INF that haven't been
cbb8991c
DB
10229 processed by follow_fork. */
10230
6b8edb51 10231void
28561a65 10232remote_target::kill_new_fork_children (inferior *inf)
cbb8991c 10233{
6b8edb51 10234 remote_state *rs = get_remote_state ();
42938c1a 10235 const notif_client *notif = &notif_client_stop;
cbb8991c 10236
28561a65
SM
10237 /* Kill the fork child threads of any threads in inferior INF that are stopped
10238 at a fork event. */
10239 for (thread_info *thread : inf->non_exited_threads ())
cbb8991c 10240 {
28561a65 10241 const target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c 10242
28561a65
SM
10243 if (ws == nullptr)
10244 continue;
cbb8991c 10245
28561a65
SM
10246 int child_pid = ws->child_ptid ().pid ();
10247 int res = remote_vkill (child_pid);
10248
10249 if (res != 0)
10250 error (_("Can't kill fork child process %d"), child_pid);
cbb8991c
DB
10251 }
10252
10253 /* Check for any pending fork events (not reported or processed yet)
28561a65 10254 in inferior INF and kill those fork child threads as well. */
cbb8991c 10255 remote_notif_get_pending_events (notif);
953edf2b 10256 for (auto &event : rs->stop_reply_queue)
28561a65
SM
10257 {
10258 if (event->ptid.pid () != inf->pid)
10259 continue;
953edf2b 10260
28561a65
SM
10261 if (!is_fork_status (event->ws.kind ()))
10262 continue;
10263
10264 int child_pid = event->ws.child_ptid ().pid ();
10265 int res = remote_vkill (child_pid);
10266
10267 if (res != 0)
10268 error (_("Can't kill fork child process %d"), child_pid);
10269 }
cbb8991c
DB
10270}
10271
c906108c 10272\f
8020350c
DB
10273/* Target hook to kill the current inferior. */
10274
f6ac5f3d
PA
10275void
10276remote_target::kill ()
43ff13b4 10277{
8020350c 10278 int res = -1;
28561a65 10279 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
0fdf84ca 10280
28561a65
SM
10281 gdb_assert (inf != nullptr);
10282
ff52c073 10283 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 10284 {
8020350c
DB
10285 /* If we're stopped while forking and we haven't followed yet,
10286 kill the child task. We need to do this before killing the
10287 parent task because if this is a vfork then the parent will
10288 be sleeping. */
28561a65 10289 kill_new_fork_children (inf);
8020350c 10290
28561a65 10291 res = remote_vkill (inf->pid);
8020350c 10292 if (res == 0)
0fdf84ca 10293 {
bc1e6c81 10294 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
10295 return;
10296 }
8020350c 10297 }
0fdf84ca 10298
8020350c
DB
10299 /* If we are in 'target remote' mode and we are killing the only
10300 inferior, then we will tell gdbserver to exit and unpush the
10301 target. */
ff52c073 10302 if (res == -1 && !m_features.remote_multi_process_p ()
5b6d1e4f 10303 && number_of_live_inferiors (this) == 1)
8020350c
DB
10304 {
10305 remote_kill_k ();
10306
10307 /* We've killed the remote end, we get to mourn it. If we are
10308 not in extended mode, mourning the inferior also unpushes
10309 remote_ops from the target stack, which closes the remote
10310 connection. */
bc1e6c81 10311 target_mourn_inferior (inferior_ptid);
8020350c
DB
10312
10313 return;
0fdf84ca 10314 }
43ff13b4 10315
8020350c 10316 error (_("Can't kill process"));
43ff13b4
JM
10317}
10318
8020350c
DB
10319/* Send a kill request to the target using the 'vKill' packet. */
10320
6b8edb51
PA
10321int
10322remote_target::remote_vkill (int pid)
82f73884 10323{
ff52c073 10324 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
10325 return -1;
10326
6b8edb51
PA
10327 remote_state *rs = get_remote_state ();
10328
82f73884 10329 /* Tell the remote target to detach. */
8d64371b 10330 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
82f73884 10331 putpkt (rs->buf);
8d64371b 10332 getpkt (&rs->buf, 0);
82f73884 10333
ff52c073 10334 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
4082afcc
PA
10335 {
10336 case PACKET_OK:
10337 return 0;
10338 case PACKET_ERROR:
10339 return 1;
10340 case PACKET_UNKNOWN:
10341 return -1;
10342 default:
f34652de 10343 internal_error (_("Bad result from packet_ok"));
4082afcc 10344 }
82f73884
PA
10345}
10346
8020350c
DB
10347/* Send a kill request to the target using the 'k' packet. */
10348
6b8edb51
PA
10349void
10350remote_target::remote_kill_k ()
82f73884 10351{
8020350c
DB
10352 /* Catch errors so the user can quit from gdb even when we
10353 aren't on speaking terms with the remote system. */
a70b8144 10354 try
82f73884 10355 {
82f73884 10356 putpkt ("k");
82f73884 10357 }
230d2906 10358 catch (const gdb_exception_error &ex)
8020350c
DB
10359 {
10360 if (ex.error == TARGET_CLOSE_ERROR)
10361 {
10362 /* If we got an (EOF) error that caused the target
10363 to go away, then we're done, that's what we wanted.
10364 "k" is susceptible to cause a premature EOF, given
10365 that the remote server isn't actually required to
10366 reply to "k", and it can happen that it doesn't
10367 even get to reply ACK to the "k". */
10368 return;
10369 }
82f73884 10370
8020350c
DB
10371 /* Otherwise, something went wrong. We didn't actually kill
10372 the target. Just propagate the exception, and let the
10373 user or higher layers decide what to do. */
eedc3f4f 10374 throw;
8020350c 10375 }
82f73884
PA
10376}
10377
f6ac5f3d
PA
10378void
10379remote_target::mourn_inferior ()
c906108c 10380{
8020350c 10381 struct remote_state *rs = get_remote_state ();
ce5ce7ed 10382
9607784a
PA
10383 /* We're no longer interested in notification events of an inferior
10384 that exited or was killed/detached. */
10385 discard_pending_stop_replies (current_inferior ());
10386
8020350c 10387 /* In 'target remote' mode with one inferior, we close the connection. */
5b6d1e4f 10388 if (!rs->extended && number_of_live_inferiors (this) <= 1)
8020350c 10389 {
5b6d1e4f 10390 remote_unpush_target (this);
8020350c
DB
10391 return;
10392 }
c906108c 10393
e24a49d8
PA
10394 /* In case we got here due to an error, but we're going to stay
10395 connected. */
10396 rs->waiting_for_stop_reply = 0;
10397
dc1981d7
PA
10398 /* If the current general thread belonged to the process we just
10399 detached from or has exited, the remote side current general
10400 thread becomes undefined. Considering a case like this:
10401
10402 - We just got here due to a detach.
10403 - The process that we're detaching from happens to immediately
10404 report a global breakpoint being hit in non-stop mode, in the
10405 same thread we had selected before.
10406 - GDB attaches to this process again.
10407 - This event happens to be the next event we handle.
10408
10409 GDB would consider that the current general thread didn't need to
10410 be set on the stub side (with Hg), since for all it knew,
10411 GENERAL_THREAD hadn't changed.
10412
10413 Notice that although in all-stop mode, the remote server always
10414 sets the current thread to the thread reporting the stop event,
10415 that doesn't happen in non-stop mode; in non-stop, the stub *must
10416 not* change the current thread when reporting a breakpoint hit,
10417 due to the decoupling of event reporting and event handling.
10418
10419 To keep things simple, we always invalidate our notion of the
10420 current thread. */
47f8a51d 10421 record_currthread (rs, minus_one_ptid);
dc1981d7 10422
8020350c 10423 /* Call common code to mark the inferior as not running. */
48aa3c27 10424 generic_mourn_inferior ();
2d717e4f 10425}
c906108c 10426
57810aa7 10427bool
f6ac5f3d 10428extended_remote_target::supports_disable_randomization ()
03583c20 10429{
ff52c073
CS
10430 return (m_features.packet_support (PACKET_QDisableRandomization)
10431 == PACKET_ENABLE);
03583c20
UW
10432}
10433
6b8edb51
PA
10434void
10435remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
10436{
10437 struct remote_state *rs = get_remote_state ();
10438 char *reply;
10439
8d64371b
TT
10440 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10441 "QDisableRandomization:%x", val);
03583c20 10442 putpkt (rs->buf);
b6bb3468 10443 reply = remote_get_noisy_reply ();
03583c20
UW
10444 if (*reply == '\0')
10445 error (_("Target does not support QDisableRandomization."));
10446 if (strcmp (reply, "OK") != 0)
10447 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10448}
10449
6b8edb51
PA
10450int
10451remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
10452{
10453 struct remote_state *rs = get_remote_state ();
2d717e4f 10454 int len;
94585166 10455 const char *remote_exec_file = get_remote_exec_file ();
c906108c 10456
2d717e4f
DJ
10457 /* If the user has disabled vRun support, or we have detected that
10458 support is not available, do not try it. */
ff52c073 10459 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 10460 return -1;
424163ea 10461
8d64371b
TT
10462 strcpy (rs->buf.data (), "vRun;");
10463 len = strlen (rs->buf.data ());
c906108c 10464
2d717e4f
DJ
10465 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10466 error (_("Remote file name too long for run packet"));
8d64371b 10467 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
9f1b45b0 10468 strlen (remote_exec_file));
2d717e4f 10469
7c5ded6a 10470 if (!args.empty ())
2d717e4f 10471 {
2d717e4f 10472 int i;
2d717e4f 10473
773a1edc 10474 gdb_argv argv (args.c_str ());
2d717e4f
DJ
10475 for (i = 0; argv[i] != NULL; i++)
10476 {
10477 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10478 error (_("Argument list too long for run packet"));
10479 rs->buf[len++] = ';';
8d64371b 10480 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
9f1b45b0 10481 strlen (argv[i]));
2d717e4f 10482 }
2d717e4f
DJ
10483 }
10484
10485 rs->buf[len++] = '\0';
10486
10487 putpkt (rs->buf);
8d64371b 10488 getpkt (&rs->buf, 0);
2d717e4f 10489
ff52c073 10490 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
2d717e4f 10491 {
4082afcc 10492 case PACKET_OK:
3405876a 10493 /* We have a wait response. All is well. */
2d717e4f 10494 return 0;
4082afcc
PA
10495 case PACKET_UNKNOWN:
10496 return -1;
10497 case PACKET_ERROR:
2d717e4f
DJ
10498 if (remote_exec_file[0] == '\0')
10499 error (_("Running the default executable on the remote target failed; "
10500 "try \"set remote exec-file\"?"));
10501 else
10502 error (_("Running \"%s\" on the remote target failed"),
10503 remote_exec_file);
4082afcc 10504 default:
557b4d76 10505 gdb_assert_not_reached ("bad switch");
2d717e4f 10506 }
c906108c
SS
10507}
10508
0a2dde4a
SDJ
10509/* Helper function to send set/unset environment packets. ACTION is
10510 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10511 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10512 sent. */
10513
6b8edb51
PA
10514void
10515remote_target::send_environment_packet (const char *action,
10516 const char *packet,
10517 const char *value)
0a2dde4a 10518{
6b8edb51
PA
10519 remote_state *rs = get_remote_state ();
10520
0a2dde4a
SDJ
10521 /* Convert the environment variable to an hex string, which
10522 is the best format to be transmitted over the wire. */
10523 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10524 strlen (value));
10525
8d64371b 10526 xsnprintf (rs->buf.data (), get_remote_packet_size (),
0a2dde4a
SDJ
10527 "%s:%s", packet, encoded_value.c_str ());
10528
10529 putpkt (rs->buf);
8d64371b
TT
10530 getpkt (&rs->buf, 0);
10531 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10532 warning (_("Unable to %s environment variable '%s' on remote."),
10533 action, value);
10534}
10535
10536/* Helper function to handle the QEnvironment* packets. */
10537
6b8edb51
PA
10538void
10539remote_target::extended_remote_environment_support ()
0a2dde4a 10540{
6b8edb51
PA
10541 remote_state *rs = get_remote_state ();
10542
ff52c073 10543 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
0a2dde4a
SDJ
10544 {
10545 putpkt ("QEnvironmentReset");
8d64371b
TT
10546 getpkt (&rs->buf, 0);
10547 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10548 warning (_("Unable to reset environment on remote."));
10549 }
10550
10551 gdb_environ *e = &current_inferior ()->environment;
10552
ff52c073
CS
10553 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10554 != PACKET_DISABLE)
10555 {
10556 for (const std::string &el : e->user_set_env ())
10557 send_environment_packet ("set", "QEnvironmentHexEncoded",
10558 el.c_str ());
10559 }
10560
0a2dde4a 10561
ff52c073 10562 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
0a2dde4a 10563 for (const std::string &el : e->user_unset_env ())
6b8edb51 10564 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10565}
10566
bc3b087d
SDJ
10567/* Helper function to set the current working directory for the
10568 inferior in the remote target. */
10569
6b8edb51
PA
10570void
10571remote_target::extended_remote_set_inferior_cwd ()
bc3b087d 10572{
ff52c073 10573 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
bc3b087d 10574 {
11bd012e 10575 const std::string &inferior_cwd = current_inferior ()->cwd ();
6b8edb51 10576 remote_state *rs = get_remote_state ();
bc3b087d 10577
11bd012e 10578 if (!inferior_cwd.empty ())
bc3b087d 10579 {
11bd012e
SM
10580 std::string hexpath
10581 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10582 inferior_cwd.size ());
bc3b087d 10583
8d64371b 10584 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10585 "QSetWorkingDir:%s", hexpath.c_str ());
10586 }
10587 else
10588 {
10589 /* An empty inferior_cwd means that the user wants us to
10590 reset the remote server's inferior's cwd. */
8d64371b 10591 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10592 "QSetWorkingDir:");
10593 }
10594
10595 putpkt (rs->buf);
8d64371b 10596 getpkt (&rs->buf, 0);
ff52c073 10597 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
bc3b087d
SDJ
10598 error (_("\
10599Remote replied unexpectedly while setting the inferior's working\n\
10600directory: %s"),
8d64371b 10601 rs->buf.data ());
bc3b087d
SDJ
10602
10603 }
10604}
10605
2d717e4f
DJ
10606/* In the extended protocol we want to be able to do things like
10607 "run" and have them basically work as expected. So we need
10608 a special create_inferior function. We support changing the
10609 executable file and the command line arguments, but not the
10610 environment. */
10611
f6ac5f3d
PA
10612void
10613extended_remote_target::create_inferior (const char *exec_file,
10614 const std::string &args,
10615 char **env, int from_tty)
43ff13b4 10616{
3405876a
PA
10617 int run_worked;
10618 char *stop_reply;
10619 struct remote_state *rs = get_remote_state ();
94585166 10620 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10621
43ff13b4 10622 /* If running asynchronously, register the target file descriptor
23860348 10623 with the event loop. */
75c99385 10624 if (target_can_async_p ())
4a570176 10625 target_async (true);
43ff13b4 10626
03583c20 10627 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10628 if (supports_disable_randomization ())
03583c20
UW
10629 extended_remote_disable_randomization (disable_randomization);
10630
aefd8b33
SDJ
10631 /* If startup-with-shell is on, we inform gdbserver to start the
10632 remote inferior using a shell. */
ff52c073 10633 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
aefd8b33 10634 {
8d64371b 10635 xsnprintf (rs->buf.data (), get_remote_packet_size (),
aefd8b33
SDJ
10636 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10637 putpkt (rs->buf);
8d64371b
TT
10638 getpkt (&rs->buf, 0);
10639 if (strcmp (rs->buf.data (), "OK") != 0)
aefd8b33
SDJ
10640 error (_("\
10641Remote replied unexpectedly while setting startup-with-shell: %s"),
8d64371b 10642 rs->buf.data ());
aefd8b33
SDJ
10643 }
10644
6b8edb51 10645 extended_remote_environment_support ();
0a2dde4a 10646
6b8edb51 10647 extended_remote_set_inferior_cwd ();
bc3b087d 10648
43ff13b4 10649 /* Now restart the remote server. */
3405876a
PA
10650 run_worked = extended_remote_run (args) != -1;
10651 if (!run_worked)
2d717e4f
DJ
10652 {
10653 /* vRun was not supported. Fail if we need it to do what the
10654 user requested. */
10655 if (remote_exec_file[0])
10656 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10657 if (!args.empty ())
65e65158 10658 error (_("Remote target does not support \"set args\" or run ARGS"));
43ff13b4 10659
2d717e4f
DJ
10660 /* Fall back to "R". */
10661 extended_remote_restart ();
10662 }
424163ea 10663
3405876a 10664 /* vRun's success return is a stop reply. */
8d64371b 10665 stop_reply = run_worked ? rs->buf.data () : NULL;
3405876a 10666 add_current_inferior_and_thread (stop_reply);
c0a2216e 10667
2d717e4f
DJ
10668 /* Get updated offsets, if the stub uses qOffsets. */
10669 get_offsets ();
2d717e4f 10670}
c906108c 10671\f
c5aa993b 10672
b775012e
LM
10673/* Given a location's target info BP_TGT and the packet buffer BUF, output
10674 the list of conditions (in agent expression bytecode format), if any, the
10675 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10676 started from BUF and ended at BUF_END. */
b775012e
LM
10677
10678static int
10679remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10680 struct bp_target_info *bp_tgt, char *buf,
10681 char *buf_end)
b775012e 10682{
3cde5c42 10683 if (bp_tgt->conditions.empty ())
b775012e
LM
10684 return 0;
10685
10686 buf += strlen (buf);
bba74b36 10687 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10688 buf++;
10689
83621223 10690 /* Send conditions to the target. */
d538e36d 10691 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10692 {
6f96f485 10693 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
b775012e 10694 buf += strlen (buf);
6f96f485 10695 for (int i = 0; i < aexpr->buf.size (); ++i)
b775012e
LM
10696 buf = pack_hex_byte (buf, aexpr->buf[i]);
10697 *buf = '\0';
10698 }
b775012e
LM
10699 return 0;
10700}
10701
d3ce09f5
SS
10702static void
10703remote_add_target_side_commands (struct gdbarch *gdbarch,
10704 struct bp_target_info *bp_tgt, char *buf)
10705{
3cde5c42 10706 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10707 return;
10708
10709 buf += strlen (buf);
10710
10711 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10712 buf += strlen (buf);
10713
10714 /* Concatenate all the agent expressions that are commands into the
10715 cmds parameter. */
df97be55 10716 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5 10717 {
6f96f485 10718 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
d3ce09f5 10719 buf += strlen (buf);
6f96f485 10720 for (int i = 0; i < aexpr->buf.size (); ++i)
d3ce09f5
SS
10721 buf = pack_hex_byte (buf, aexpr->buf[i]);
10722 *buf = '\0';
10723 }
d3ce09f5
SS
10724}
10725
8181d85f
DJ
10726/* Insert a breakpoint. On targets that have software breakpoint
10727 support, we ask the remote target to do the work; on targets
10728 which don't, we insert a traditional memory breakpoint. */
c906108c 10729
f6ac5f3d
PA
10730int
10731remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10732 struct bp_target_info *bp_tgt)
c906108c 10733{
d471ea57
AC
10734 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10735 If it succeeds, then set the support to PACKET_ENABLE. If it
10736 fails, and the user has explicitly requested the Z support then
23860348 10737 report an error, otherwise, mark it disabled and go on. */
802188a7 10738
ff52c073 10739 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10740 {
0d5ed153 10741 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10742 struct remote_state *rs;
bba74b36 10743 char *p, *endbuf;
4fff2411 10744
28439a30
PA
10745 /* Make sure the remote is pointing at the right process, if
10746 necessary. */
10747 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10748 set_general_process ();
10749
4fff2411 10750 rs = get_remote_state ();
8d64371b
TT
10751 p = rs->buf.data ();
10752 endbuf = p + get_remote_packet_size ();
802188a7 10753
96baa820
JM
10754 *(p++) = 'Z';
10755 *(p++) = '0';
10756 *(p++) = ',';
7c0f6dcc 10757 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10758 p += hexnumstr (p, addr);
579c6ad9 10759 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10760
f6ac5f3d 10761 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10762 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10763
f6ac5f3d 10764 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10765 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10766
6d820c5c 10767 putpkt (rs->buf);
8d64371b 10768 getpkt (&rs->buf, 0);
96baa820 10769
ff52c073 10770 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
96baa820 10771 {
d471ea57
AC
10772 case PACKET_ERROR:
10773 return -1;
10774 case PACKET_OK:
10775 return 0;
10776 case PACKET_UNKNOWN:
10777 break;
96baa820
JM
10778 }
10779 }
c906108c 10780
0000e5cc
PA
10781 /* If this breakpoint has target-side commands but this stub doesn't
10782 support Z0 packets, throw error. */
3cde5c42 10783 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10784 throw_error (NOT_SUPPORTED_ERROR, _("\
10785Target doesn't support breakpoints that have target side commands."));
10786
f6ac5f3d 10787 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10788}
10789
f6ac5f3d
PA
10790int
10791remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10792 struct bp_target_info *bp_tgt,
10793 enum remove_bp_reason reason)
c906108c 10794{
8181d85f 10795 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10796 struct remote_state *rs = get_remote_state ();
96baa820 10797
ff52c073 10798 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10799 {
8d64371b
TT
10800 char *p = rs->buf.data ();
10801 char *endbuf = p + get_remote_packet_size ();
802188a7 10802
28439a30
PA
10803 /* Make sure the remote is pointing at the right process, if
10804 necessary. */
10805 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10806 set_general_process ();
10807
96baa820
JM
10808 *(p++) = 'z';
10809 *(p++) = '0';
10810 *(p++) = ',';
10811
8181d85f
DJ
10812 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10813 p += hexnumstr (p, addr);
579c6ad9 10814 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10815
6d820c5c 10816 putpkt (rs->buf);
8d64371b 10817 getpkt (&rs->buf, 0);
96baa820 10818
6d820c5c 10819 return (rs->buf[0] == 'E');
96baa820
JM
10820 }
10821
f6ac5f3d 10822 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10823}
10824
f486487f 10825static enum Z_packet_type
d471ea57
AC
10826watchpoint_to_Z_packet (int type)
10827{
10828 switch (type)
10829 {
10830 case hw_write:
bb858e6a 10831 return Z_PACKET_WRITE_WP;
d471ea57
AC
10832 break;
10833 case hw_read:
bb858e6a 10834 return Z_PACKET_READ_WP;
d471ea57
AC
10835 break;
10836 case hw_access:
bb858e6a 10837 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10838 break;
10839 default:
f34652de 10840 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10841 }
10842}
10843
f6ac5f3d
PA
10844int
10845remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10846 enum target_hw_bp_type type, struct expression *cond)
96baa820 10847{
d01949b6 10848 struct remote_state *rs = get_remote_state ();
8d64371b 10849 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10850 char *p;
d471ea57 10851 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10852
24a601dd
TV
10853 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10854 + to_underlying (packet))) == PACKET_DISABLE)
85d721b8 10855 return 1;
802188a7 10856
28439a30
PA
10857 /* Make sure the remote is pointing at the right process, if
10858 necessary. */
10859 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10860 set_general_process ();
10861
8d64371b
TT
10862 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10863 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10864 addr = remote_address_masked (addr);
10865 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10866 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10867
6d820c5c 10868 putpkt (rs->buf);
8d64371b 10869 getpkt (&rs->buf, 0);
96baa820 10870
24a601dd
TV
10871 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10872 + to_underlying (packet))))
d471ea57
AC
10873 {
10874 case PACKET_ERROR:
d471ea57 10875 return -1;
85d721b8
PA
10876 case PACKET_UNKNOWN:
10877 return 1;
d471ea57
AC
10878 case PACKET_OK:
10879 return 0;
10880 }
f34652de 10881 internal_error (_("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10882}
10883
57810aa7 10884bool
f6ac5f3d
PA
10885remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10886 CORE_ADDR start, int length)
283002cf
MR
10887{
10888 CORE_ADDR diff = remote_address_masked (addr - start);
10889
10890 return diff < length;
10891}
10892
d471ea57 10893
f6ac5f3d
PA
10894int
10895remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10896 enum target_hw_bp_type type, struct expression *cond)
96baa820 10897{
d01949b6 10898 struct remote_state *rs = get_remote_state ();
8d64371b 10899 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10900 char *p;
d471ea57
AC
10901 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10902
24a601dd
TV
10903 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10904 + to_underlying (packet))) == PACKET_DISABLE)
5cffb350 10905 return -1;
802188a7 10906
28439a30
PA
10907 /* Make sure the remote is pointing at the right process, if
10908 necessary. */
10909 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10910 set_general_process ();
10911
8d64371b
TT
10912 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10913 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10914 addr = remote_address_masked (addr);
10915 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10916 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c 10917 putpkt (rs->buf);
8d64371b 10918 getpkt (&rs->buf, 0);
96baa820 10919
24a601dd
TV
10920 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10921 + to_underlying (packet))))
d471ea57
AC
10922 {
10923 case PACKET_ERROR:
10924 case PACKET_UNKNOWN:
10925 return -1;
10926 case PACKET_OK:
10927 return 0;
10928 }
f34652de 10929 internal_error (_("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10930}
10931
3c3bea1c 10932
60fcc1c3
TT
10933static int remote_hw_watchpoint_limit = -1;
10934static int remote_hw_watchpoint_length_limit = -1;
10935static int remote_hw_breakpoint_limit = -1;
d471ea57 10936
f6ac5f3d
PA
10937int
10938remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10939{
10940 if (remote_hw_watchpoint_length_limit == 0)
10941 return 0;
10942 else if (remote_hw_watchpoint_length_limit < 0)
10943 return 1;
10944 else if (len <= remote_hw_watchpoint_length_limit)
10945 return 1;
10946 else
10947 return 0;
10948}
10949
f6ac5f3d
PA
10950int
10951remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10952{
3c3bea1c
GS
10953 if (type == bp_hardware_breakpoint)
10954 {
10955 if (remote_hw_breakpoint_limit == 0)
10956 return 0;
501eef12
AC
10957 else if (remote_hw_breakpoint_limit < 0)
10958 return 1;
3c3bea1c
GS
10959 else if (cnt <= remote_hw_breakpoint_limit)
10960 return 1;
10961 }
10962 else
10963 {
10964 if (remote_hw_watchpoint_limit == 0)
10965 return 0;
501eef12
AC
10966 else if (remote_hw_watchpoint_limit < 0)
10967 return 1;
3c3bea1c
GS
10968 else if (ot)
10969 return -1;
10970 else if (cnt <= remote_hw_watchpoint_limit)
10971 return 1;
10972 }
10973 return -1;
10974}
10975
f7e6eed5
PA
10976/* The to_stopped_by_sw_breakpoint method of target remote. */
10977
57810aa7 10978bool
f6ac5f3d 10979remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10980{
799a2abe 10981 struct thread_info *thread = inferior_thread ();
f7e6eed5 10982
799a2abe 10983 return (thread->priv != NULL
7aabaf9d
SM
10984 && (get_remote_thread_info (thread)->stop_reason
10985 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10986}
10987
10988/* The to_supports_stopped_by_sw_breakpoint method of target
10989 remote. */
10990
57810aa7 10991bool
f6ac5f3d 10992remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10993{
ff52c073 10994 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
f7e6eed5
PA
10995}
10996
10997/* The to_stopped_by_hw_breakpoint method of target remote. */
10998
57810aa7 10999bool
f6ac5f3d 11000remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 11001{
799a2abe 11002 struct thread_info *thread = inferior_thread ();
f7e6eed5 11003
799a2abe 11004 return (thread->priv != NULL
7aabaf9d
SM
11005 && (get_remote_thread_info (thread)->stop_reason
11006 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
11007}
11008
11009/* The to_supports_stopped_by_hw_breakpoint method of target
11010 remote. */
11011
57810aa7 11012bool
f6ac5f3d 11013remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 11014{
ff52c073 11015 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
f7e6eed5
PA
11016}
11017
57810aa7 11018bool
f6ac5f3d 11019remote_target::stopped_by_watchpoint ()
3c3bea1c 11020{
799a2abe 11021 struct thread_info *thread = inferior_thread ();
ee154bee 11022
799a2abe 11023 return (thread->priv != NULL
7aabaf9d
SM
11024 && (get_remote_thread_info (thread)->stop_reason
11025 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
11026}
11027
57810aa7 11028bool
f6ac5f3d 11029remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 11030{
799a2abe 11031 struct thread_info *thread = inferior_thread ();
a744cf53 11032
799a2abe 11033 if (thread->priv != NULL
7aabaf9d
SM
11034 && (get_remote_thread_info (thread)->stop_reason
11035 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 11036 {
7aabaf9d 11037 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 11038 return true;
4aa7a7f5
JJ
11039 }
11040
57810aa7 11041 return false;
3c3bea1c
GS
11042}
11043
11044
f6ac5f3d
PA
11045int
11046remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11047 struct bp_target_info *bp_tgt)
3c3bea1c 11048{
0d5ed153 11049 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 11050 struct remote_state *rs;
bba74b36 11051 char *p, *endbuf;
dd61ec5c 11052 char *message;
3c3bea1c 11053
ff52c073 11054 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 11055 return -1;
2bc416ba 11056
28439a30
PA
11057 /* Make sure the remote is pointing at the right process, if
11058 necessary. */
11059 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
11060 set_general_process ();
11061
4fff2411 11062 rs = get_remote_state ();
8d64371b
TT
11063 p = rs->buf.data ();
11064 endbuf = p + get_remote_packet_size ();
4fff2411 11065
96baa820
JM
11066 *(p++) = 'Z';
11067 *(p++) = '1';
11068 *(p++) = ',';
802188a7 11069
0d5ed153 11070 addr = remote_address_masked (addr);
96baa820 11071 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 11072 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 11073
f6ac5f3d 11074 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 11075 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 11076
f6ac5f3d 11077 if (can_run_breakpoint_commands ())
d3ce09f5
SS
11078 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11079
6d820c5c 11080 putpkt (rs->buf);
8d64371b 11081 getpkt (&rs->buf, 0);
96baa820 11082
ff52c073 11083 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
d471ea57
AC
11084 {
11085 case PACKET_ERROR:
dd61ec5c 11086 if (rs->buf[1] == '.')
dda83cd7
SM
11087 {
11088 message = strchr (&rs->buf[2], '.');
11089 if (message)
11090 error (_("Remote failure reply: %s"), message + 1);
11091 }
dd61ec5c 11092 return -1;
d471ea57
AC
11093 case PACKET_UNKNOWN:
11094 return -1;
11095 case PACKET_OK:
11096 return 0;
11097 }
f34652de 11098 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
11099}
11100
d471ea57 11101
f6ac5f3d
PA
11102int
11103remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11104 struct bp_target_info *bp_tgt)
96baa820 11105{
8181d85f 11106 CORE_ADDR addr;
d01949b6 11107 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11108 char *p = rs->buf.data ();
11109 char *endbuf = p + get_remote_packet_size ();
c8189ed1 11110
ff52c073 11111 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 11112 return -1;
802188a7 11113
28439a30
PA
11114 /* Make sure the remote is pointing at the right process, if
11115 necessary. */
11116 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
11117 set_general_process ();
11118
96baa820
JM
11119 *(p++) = 'z';
11120 *(p++) = '1';
11121 *(p++) = ',';
802188a7 11122
8181d85f 11123 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 11124 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 11125 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 11126
6d820c5c 11127 putpkt (rs->buf);
8d64371b 11128 getpkt (&rs->buf, 0);
802188a7 11129
ff52c073 11130 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
d471ea57
AC
11131 {
11132 case PACKET_ERROR:
11133 case PACKET_UNKNOWN:
11134 return -1;
11135 case PACKET_OK:
11136 return 0;
11137 }
f34652de 11138 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
96baa820 11139}
96baa820 11140
4a5e7a5b
PA
11141/* Verify memory using the "qCRC:" request. */
11142
f6ac5f3d
PA
11143int
11144remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
11145{
11146 struct remote_state *rs = get_remote_state ();
11147 unsigned long host_crc, target_crc;
11148 char *tmp;
11149
936d2992
PA
11150 /* It doesn't make sense to use qCRC if the remote target is
11151 connected but not running. */
55f6301a 11152 if (target_has_execution ()
ff52c073 11153 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
936d2992
PA
11154 {
11155 enum packet_result result;
28439a30 11156
936d2992
PA
11157 /* Make sure the remote is pointing at the right process. */
11158 set_general_process ();
4a5e7a5b 11159
936d2992 11160 /* FIXME: assumes lma can fit into long. */
8d64371b 11161 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
936d2992
PA
11162 (long) lma, (long) size);
11163 putpkt (rs->buf);
4a5e7a5b 11164
936d2992
PA
11165 /* Be clever; compute the host_crc before waiting for target
11166 reply. */
11167 host_crc = xcrc32 (data, size, 0xffffffff);
11168
8d64371b 11169 getpkt (&rs->buf, 0);
4a5e7a5b 11170
ff52c073 11171 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
936d2992
PA
11172 if (result == PACKET_ERROR)
11173 return -1;
11174 else if (result == PACKET_OK)
11175 {
11176 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11177 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 11178
936d2992
PA
11179 return (host_crc == target_crc);
11180 }
11181 }
4a5e7a5b 11182
f6ac5f3d 11183 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
11184}
11185
c906108c
SS
11186/* compare-sections command
11187
11188 With no arguments, compares each loadable section in the exec bfd
11189 with the same memory range on the target, and reports mismatches.
4a5e7a5b 11190 Useful for verifying the image on the target against the exec file. */
e514a9d6 11191
c906108c 11192static void
ac88e2de 11193compare_sections_command (const char *args, int from_tty)
c906108c
SS
11194{
11195 asection *s;
ce359b09 11196 const char *sectname;
c906108c
SS
11197 bfd_size_type size;
11198 bfd_vma lma;
11199 int matched = 0;
11200 int mismatched = 0;
4a5e7a5b 11201 int res;
95cf3b38 11202 int read_only = 0;
c906108c 11203
7e10abd1 11204 if (!current_program_space->exec_bfd ())
8a3fe4f8 11205 error (_("command cannot be used without an exec file"));
c906108c 11206
95cf3b38
DT
11207 if (args != NULL && strcmp (args, "-r") == 0)
11208 {
11209 read_only = 1;
11210 args = NULL;
11211 }
11212
7e10abd1 11213 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
c906108c
SS
11214 {
11215 if (!(s->flags & SEC_LOAD))
0df8b418 11216 continue; /* Skip non-loadable section. */
c906108c 11217
95cf3b38
DT
11218 if (read_only && (s->flags & SEC_READONLY) == 0)
11219 continue; /* Skip writeable sections */
11220
fd361982 11221 size = bfd_section_size (s);
c906108c 11222 if (size == 0)
0df8b418 11223 continue; /* Skip zero-length section. */
c906108c 11224
fd361982 11225 sectname = bfd_section_name (s);
c906108c 11226 if (args && strcmp (args, sectname) != 0)
0df8b418 11227 continue; /* Not the section selected by user. */
c906108c 11228
0df8b418 11229 matched = 1; /* Do this section. */
c906108c 11230 lma = s->lma;
c906108c 11231
b80406ac 11232 gdb::byte_vector sectdata (size);
7e10abd1
TT
11233 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11234 sectdata.data (), 0, size);
c906108c 11235
b80406ac 11236 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
11237
11238 if (res == -1)
5af949e3 11239 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
11240 paddress (target_gdbarch (), lma),
11241 paddress (target_gdbarch (), lma + size));
c906108c 11242
6cb06a8c
TT
11243 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11244 paddress (target_gdbarch (), lma),
11245 paddress (target_gdbarch (), lma + size));
4a5e7a5b 11246 if (res)
6cb06a8c 11247 gdb_printf ("matched.\n");
c906108c 11248 else
c5aa993b 11249 {
6cb06a8c 11250 gdb_printf ("MIS-MATCHED!\n");
c5aa993b
JM
11251 mismatched++;
11252 }
c906108c
SS
11253 }
11254 if (mismatched > 0)
131287d9
AB
11255 warning (_("One or more sections of the target image does "
11256 "not match the loaded file"));
c906108c 11257 if (args && !matched)
6cb06a8c 11258 gdb_printf (_("No loaded section named '%s'.\n"), args);
c906108c
SS
11259}
11260
0e7f50da
UW
11261/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11262 into remote target. The number of bytes written to the remote
11263 target is returned, or -1 for error. */
11264
6b8edb51
PA
11265target_xfer_status
11266remote_target::remote_write_qxfer (const char *object_name,
11267 const char *annex, const gdb_byte *writebuf,
11268 ULONGEST offset, LONGEST len,
11269 ULONGEST *xfered_len,
ff52c073 11270 const unsigned int which_packet)
0e7f50da
UW
11271{
11272 int i, buf_len;
11273 ULONGEST n;
0e7f50da
UW
11274 struct remote_state *rs = get_remote_state ();
11275 int max_size = get_memory_write_packet_size ();
11276
ff52c073 11277 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
2ed4b548 11278 return TARGET_XFER_E_IO;
0e7f50da
UW
11279
11280 /* Insert header. */
8d64371b 11281 i = snprintf (rs->buf.data (), max_size,
0e7f50da
UW
11282 "qXfer:%s:write:%s:%s:",
11283 object_name, annex ? annex : "",
11284 phex_nz (offset, sizeof offset));
11285 max_size -= (i + 1);
11286
11287 /* Escape as much data as fits into rs->buf. */
11288 buf_len = remote_escape_output
8d64371b 11289 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
0e7f50da 11290
8d64371b
TT
11291 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11292 || getpkt_sane (&rs->buf, 0) < 0
ff52c073 11293 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
2ed4b548 11294 return TARGET_XFER_E_IO;
0e7f50da 11295
8d64371b 11296 unpack_varlen_hex (rs->buf.data (), &n);
9b409511
YQ
11297
11298 *xfered_len = n;
92ffd475 11299 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
11300}
11301
0876f84a
DJ
11302/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11303 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11304 number of bytes read is returned, or 0 for EOF, or -1 for error.
11305 The number of bytes read may be less than LEN without indicating an
11306 EOF. PACKET is checked and updated to indicate whether the remote
11307 target supports this object. */
11308
6b8edb51
PA
11309target_xfer_status
11310remote_target::remote_read_qxfer (const char *object_name,
11311 const char *annex,
11312 gdb_byte *readbuf, ULONGEST offset,
11313 LONGEST len,
11314 ULONGEST *xfered_len,
ff52c073 11315 const unsigned int which_packet)
0876f84a 11316{
0876f84a 11317 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
11318 LONGEST i, n, packet_len;
11319
ff52c073 11320 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
2ed4b548 11321 return TARGET_XFER_E_IO;
0876f84a
DJ
11322
11323 /* Check whether we've cached an end-of-object packet that matches
11324 this request. */
8e88304f 11325 if (rs->finished_object)
0876f84a 11326 {
8e88304f
TT
11327 if (strcmp (object_name, rs->finished_object) == 0
11328 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11329 && offset == rs->finished_offset)
9b409511
YQ
11330 return TARGET_XFER_EOF;
11331
0876f84a
DJ
11332
11333 /* Otherwise, we're now reading something different. Discard
11334 the cache. */
8e88304f
TT
11335 xfree (rs->finished_object);
11336 xfree (rs->finished_annex);
11337 rs->finished_object = NULL;
11338 rs->finished_annex = NULL;
0876f84a
DJ
11339 }
11340
11341 /* Request only enough to fit in a single packet. The actual data
11342 may not, since we don't know how much of it will need to be escaped;
11343 the target is free to respond with slightly less data. We subtract
11344 five to account for the response type and the protocol frame. */
768adc05 11345 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
8d64371b
TT
11346 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11347 "qXfer:%s:read:%s:%s,%s",
0876f84a
DJ
11348 object_name, annex ? annex : "",
11349 phex_nz (offset, sizeof offset),
11350 phex_nz (n, sizeof n));
11351 i = putpkt (rs->buf);
11352 if (i < 0)
2ed4b548 11353 return TARGET_XFER_E_IO;
0876f84a
DJ
11354
11355 rs->buf[0] = '\0';
8d64371b 11356 packet_len = getpkt_sane (&rs->buf, 0);
ff52c073
CS
11357 if (packet_len < 0
11358 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
2ed4b548 11359 return TARGET_XFER_E_IO;
0876f84a
DJ
11360
11361 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8d64371b 11362 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
0876f84a
DJ
11363
11364 /* 'm' means there is (or at least might be) more data after this
11365 batch. That does not make sense unless there's at least one byte
11366 of data in this reply. */
11367 if (rs->buf[0] == 'm' && packet_len == 1)
11368 error (_("Remote qXfer reply contained no data."));
11369
11370 /* Got some data. */
8d64371b 11371 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
bc20a4af 11372 packet_len - 1, readbuf, n);
0876f84a
DJ
11373
11374 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
11375 or possibly empty. If we have the final block of a non-empty
11376 object, record this fact to bypass a subsequent partial read. */
11377 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 11378 {
8e88304f
TT
11379 rs->finished_object = xstrdup (object_name);
11380 rs->finished_annex = xstrdup (annex ? annex : "");
11381 rs->finished_offset = offset + i;
0876f84a
DJ
11382 }
11383
9b409511
YQ
11384 if (i == 0)
11385 return TARGET_XFER_EOF;
11386 else
11387 {
11388 *xfered_len = i;
11389 return TARGET_XFER_OK;
11390 }
0876f84a
DJ
11391}
11392
f6ac5f3d
PA
11393enum target_xfer_status
11394remote_target::xfer_partial (enum target_object object,
11395 const char *annex, gdb_byte *readbuf,
11396 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11397 ULONGEST *xfered_len)
c906108c 11398{
82f73884 11399 struct remote_state *rs;
c906108c 11400 int i;
6d820c5c 11401 char *p2;
1e3ff5ad 11402 char query_type;
124e13d9 11403 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 11404
e6e4e701 11405 set_remote_traceframe ();
82f73884
PA
11406 set_general_thread (inferior_ptid);
11407
11408 rs = get_remote_state ();
11409
b2182ed2 11410 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
11411 if (object == TARGET_OBJECT_MEMORY)
11412 {
2d717e4f
DJ
11413 /* If the remote target is connected but not running, we should
11414 pass this request down to a lower stratum (e.g. the executable
11415 file). */
55f6301a 11416 if (!target_has_execution ())
9b409511 11417 return TARGET_XFER_EOF;
2d717e4f 11418
21e3b9b9 11419 if (writebuf != NULL)
124e13d9
SM
11420 return remote_write_bytes (offset, writebuf, len, unit_size,
11421 xfered_len);
21e3b9b9 11422 else
6b8edb51 11423 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 11424 xfered_len);
21e3b9b9
DJ
11425 }
11426
4aa995e1
PA
11427 /* Handle extra signal info using qxfer packets. */
11428 if (object == TARGET_OBJECT_SIGNAL_INFO)
11429 {
11430 if (readbuf)
f6ac5f3d 11431 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
ff52c073 11432 xfered_len, PACKET_qXfer_siginfo_read);
4aa995e1 11433 else
ff52c073
CS
11434 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11435 xfered_len, PACKET_qXfer_siginfo_write);
4aa995e1
PA
11436 }
11437
0fb4aa4b
PA
11438 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11439 {
11440 if (readbuf)
f6ac5f3d 11441 return remote_read_qxfer ("statictrace", annex,
9b409511 11442 readbuf, offset, len, xfered_len,
ff52c073 11443 PACKET_qXfer_statictrace_read);
0fb4aa4b 11444 else
2ed4b548 11445 return TARGET_XFER_E_IO;
0fb4aa4b
PA
11446 }
11447
a76d924d
DJ
11448 /* Only handle flash writes. */
11449 if (writebuf != NULL)
11450 {
a76d924d
DJ
11451 switch (object)
11452 {
11453 case TARGET_OBJECT_FLASH:
6b8edb51 11454 return remote_flash_write (offset, len, xfered_len,
9b409511 11455 writebuf);
a76d924d
DJ
11456
11457 default:
2ed4b548 11458 return TARGET_XFER_E_IO;
a76d924d
DJ
11459 }
11460 }
4b8a223f 11461
1e3ff5ad
AC
11462 /* Map pre-existing objects onto letters. DO NOT do this for new
11463 objects!!! Instead specify new query packets. */
11464 switch (object)
c906108c 11465 {
1e3ff5ad
AC
11466 case TARGET_OBJECT_AVR:
11467 query_type = 'R';
11468 break;
802188a7
RM
11469
11470 case TARGET_OBJECT_AUXV:
0876f84a 11471 gdb_assert (annex == NULL);
ff52c073
CS
11472 return remote_read_qxfer
11473 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
802188a7 11474
23181151
DJ
11475 case TARGET_OBJECT_AVAILABLE_FEATURES:
11476 return remote_read_qxfer
f6ac5f3d 11477 ("features", annex, readbuf, offset, len, xfered_len,
ff52c073 11478 PACKET_qXfer_features);
23181151 11479
cfa9d6d9
DJ
11480 case TARGET_OBJECT_LIBRARIES:
11481 return remote_read_qxfer
f6ac5f3d 11482 ("libraries", annex, readbuf, offset, len, xfered_len,
ff52c073 11483 PACKET_qXfer_libraries);
cfa9d6d9 11484
2268b414
JK
11485 case TARGET_OBJECT_LIBRARIES_SVR4:
11486 return remote_read_qxfer
f6ac5f3d 11487 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
ff52c073 11488 PACKET_qXfer_libraries_svr4);
2268b414 11489
fd79ecee
DJ
11490 case TARGET_OBJECT_MEMORY_MAP:
11491 gdb_assert (annex == NULL);
ff52c073
CS
11492 return remote_read_qxfer
11493 ("memory-map", annex, readbuf, offset, len, xfered_len,
11494 PACKET_qXfer_memory_map);
fd79ecee 11495
07e059b5
VP
11496 case TARGET_OBJECT_OSDATA:
11497 /* Should only get here if we're connected. */
5d93a237 11498 gdb_assert (rs->remote_desc);
07e059b5 11499 return remote_read_qxfer
f6ac5f3d 11500 ("osdata", annex, readbuf, offset, len, xfered_len,
ff52c073 11501 PACKET_qXfer_osdata);
07e059b5 11502
dc146f7c
VP
11503 case TARGET_OBJECT_THREADS:
11504 gdb_assert (annex == NULL);
ff52c073
CS
11505 return remote_read_qxfer
11506 ("threads", annex, readbuf, offset, len, xfered_len,
11507 PACKET_qXfer_threads);
dc146f7c 11508
b3b9301e
PA
11509 case TARGET_OBJECT_TRACEFRAME_INFO:
11510 gdb_assert (annex == NULL);
11511 return remote_read_qxfer
f6ac5f3d 11512 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
ff52c073 11513 PACKET_qXfer_traceframe_info);
78d85199
YQ
11514
11515 case TARGET_OBJECT_FDPIC:
ff52c073
CS
11516 return remote_read_qxfer
11517 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
169081d0
TG
11518
11519 case TARGET_OBJECT_OPENVMS_UIB:
ff52c073
CS
11520 return remote_read_qxfer
11521 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
169081d0 11522
9accd112 11523 case TARGET_OBJECT_BTRACE:
ff52c073
CS
11524 return remote_read_qxfer
11525 ("btrace", annex, readbuf, offset, len, xfered_len,
11526 PACKET_qXfer_btrace);
9accd112 11527
f4abbc16 11528 case TARGET_OBJECT_BTRACE_CONF:
ff52c073
CS
11529 return remote_read_qxfer
11530 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11531 PACKET_qXfer_btrace_conf);
f4abbc16 11532
c78fa86a 11533 case TARGET_OBJECT_EXEC_FILE:
ff52c073
CS
11534 return remote_read_qxfer
11535 ("exec-file", annex, readbuf, offset, len, xfered_len,
11536 PACKET_qXfer_exec_file);
c78fa86a 11537
1e3ff5ad 11538 default:
2ed4b548 11539 return TARGET_XFER_E_IO;
c906108c
SS
11540 }
11541
0df8b418 11542 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11543 large enough let the caller deal with it. */
ea9c271d 11544 if (len < get_remote_packet_size ())
2ed4b548 11545 return TARGET_XFER_E_IO;
ea9c271d 11546 len = get_remote_packet_size ();
1e3ff5ad 11547
23860348 11548 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11549 if (!rs->remote_desc)
8a3fe4f8 11550 error (_("remote query is only available after target open"));
c906108c 11551
1e3ff5ad 11552 gdb_assert (annex != NULL);
4b8a223f 11553 gdb_assert (readbuf != NULL);
c906108c 11554
8d64371b 11555 p2 = rs->buf.data ();
c906108c
SS
11556 *p2++ = 'q';
11557 *p2++ = query_type;
11558
23860348
MS
11559 /* We used one buffer char for the remote protocol q command and
11560 another for the query type. As the remote protocol encapsulation
11561 uses 4 chars plus one extra in case we are debugging
11562 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11563 string. */
c906108c 11564 i = 0;
ea9c271d 11565 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11566 {
1e3ff5ad
AC
11567 /* Bad caller may have sent forbidden characters. */
11568 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11569 *p2++ = annex[i];
c906108c
SS
11570 i++;
11571 }
1e3ff5ad
AC
11572 *p2 = '\0';
11573 gdb_assert (annex[i] == '\0');
c906108c 11574
6d820c5c 11575 i = putpkt (rs->buf);
c5aa993b 11576 if (i < 0)
2ed4b548 11577 return TARGET_XFER_E_IO;
c906108c 11578
8d64371b
TT
11579 getpkt (&rs->buf, 0);
11580 strcpy ((char *) readbuf, rs->buf.data ());
c906108c 11581
9b409511 11582 *xfered_len = strlen ((char *) readbuf);
92ffd475 11583 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11584}
11585
09c98b44
DB
11586/* Implementation of to_get_memory_xfer_limit. */
11587
f6ac5f3d
PA
11588ULONGEST
11589remote_target::get_memory_xfer_limit ()
09c98b44
DB
11590{
11591 return get_memory_write_packet_size ();
11592}
11593
f6ac5f3d
PA
11594int
11595remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11596 const gdb_byte *pattern, ULONGEST pattern_len,
11597 CORE_ADDR *found_addrp)
08388c79 11598{
f5656ead 11599 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
11600 struct remote_state *rs = get_remote_state ();
11601 int max_size = get_memory_write_packet_size ();
ff52c073 11602
0df8b418
MS
11603 /* Number of packet bytes used to encode the pattern;
11604 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11605 int escaped_pattern_len;
0df8b418 11606 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11607 int used_pattern_len;
11608 int i;
11609 int found;
11610 ULONGEST found_addr;
11611
5bd5fecd 11612 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
4a72de73
TT
11613 {
11614 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11615 == len);
11616 };
11617
7cc244de 11618 /* Don't go to the target if we don't have to. This is done before
ff52c073
CS
11619 checking packet_support to avoid the possibility that a success for this
11620 edge case means the facility works in general. */
08388c79
DE
11621 if (pattern_len > search_space_len)
11622 return 0;
11623 if (pattern_len == 0)
11624 {
11625 *found_addrp = start_addr;
11626 return 1;
11627 }
11628
11629 /* If we already know the packet isn't supported, fall back to the simple
11630 way of searching memory. */
11631
ff52c073 11632 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
08388c79
DE
11633 {
11634 /* Target doesn't provided special support, fall back and use the
11635 standard support (copy memory and do the search here). */
4a72de73 11636 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11637 pattern, pattern_len, found_addrp);
11638 }
11639
28439a30
PA
11640 /* Make sure the remote is pointing at the right process. */
11641 set_general_process ();
11642
08388c79 11643 /* Insert header. */
8d64371b 11644 i = snprintf (rs->buf.data (), max_size,
08388c79 11645 "qSearch:memory:%s;%s;",
5af949e3 11646 phex_nz (start_addr, addr_size),
08388c79
DE
11647 phex_nz (search_space_len, sizeof (search_space_len)));
11648 max_size -= (i + 1);
11649
11650 /* Escape as much data as fits into rs->buf. */
11651 escaped_pattern_len =
8d64371b
TT
11652 remote_escape_output (pattern, pattern_len, 1,
11653 (gdb_byte *) rs->buf.data () + i,
08388c79
DE
11654 &used_pattern_len, max_size);
11655
11656 /* Bail if the pattern is too large. */
11657 if (used_pattern_len != pattern_len)
9b20d036 11658 error (_("Pattern is too large to transmit to remote target."));
08388c79 11659
8d64371b
TT
11660 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11661 || getpkt_sane (&rs->buf, 0) < 0
ff52c073 11662 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
08388c79
DE
11663 {
11664 /* The request may not have worked because the command is not
11665 supported. If so, fall back to the simple way. */
ff52c073 11666 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
08388c79 11667 {
4a72de73 11668 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11669 pattern, pattern_len, found_addrp);
11670 }
11671 return -1;
11672 }
11673
11674 if (rs->buf[0] == '0')
11675 found = 0;
11676 else if (rs->buf[0] == '1')
11677 {
11678 found = 1;
11679 if (rs->buf[1] != ',')
8d64371b
TT
11680 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11681 unpack_varlen_hex (&rs->buf[2], &found_addr);
08388c79
DE
11682 *found_addrp = found_addr;
11683 }
11684 else
8d64371b 11685 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
08388c79
DE
11686
11687 return found;
11688}
11689
f6ac5f3d
PA
11690void
11691remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11692{
d01949b6 11693 struct remote_state *rs = get_remote_state ();
8d64371b 11694 char *p = rs->buf.data ();
96baa820 11695
5d93a237 11696 if (!rs->remote_desc)
8a3fe4f8 11697 error (_("remote rcmd is only available after target open"));
96baa820 11698
23860348 11699 /* Send a NULL command across as an empty command. */
7be570e7
JM
11700 if (command == NULL)
11701 command = "";
11702
23860348 11703 /* The query prefix. */
8d64371b
TT
11704 strcpy (rs->buf.data (), "qRcmd,");
11705 p = strchr (rs->buf.data (), '\0');
96baa820 11706
8d64371b 11707 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
3e43a32a 11708 > get_remote_packet_size ())
8a3fe4f8 11709 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11710
23860348 11711 /* Encode the actual command. */
a30bf1f1 11712 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11713
6d820c5c 11714 if (putpkt (rs->buf) < 0)
8a3fe4f8 11715 error (_("Communication problem with target."));
96baa820
JM
11716
11717 /* get/display the response */
11718 while (1)
11719 {
2e9f7625
DJ
11720 char *buf;
11721
00bf0b85 11722 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11723 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11724 rs->buf[0] = '\0';
8d64371b 11725 if (getpkt_sane (&rs->buf, 0) == -1)
dda83cd7
SM
11726 {
11727 /* Timeout. Continue to (try to) read responses.
11728 This is better than stopping with an error, assuming the stub
11729 is still executing the (long) monitor command.
11730 If needed, the user can interrupt gdb using C-c, obtaining
11731 an effect similar to stop on timeout. */
11732 continue;
11733 }
8d64371b 11734 buf = rs->buf.data ();
96baa820 11735 if (buf[0] == '\0')
8a3fe4f8 11736 error (_("Target does not support this command."));
96baa820
JM
11737 if (buf[0] == 'O' && buf[1] != 'K')
11738 {
23860348 11739 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11740 continue;
11741 }
11742 if (strcmp (buf, "OK") == 0)
11743 break;
7be570e7 11744 if (strlen (buf) == 3 && buf[0] == 'E'
d5ce6f2d 11745 && isxdigit (buf[1]) && isxdigit (buf[2]))
7be570e7 11746 {
8a3fe4f8 11747 error (_("Protocol error with Rcmd"));
7be570e7 11748 }
96baa820
JM
11749 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11750 {
11751 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11752
a11ac3b3 11753 gdb_putc (c, outbuf);
96baa820
JM
11754 }
11755 break;
11756 }
11757}
11758
f6ac5f3d
PA
11759std::vector<mem_region>
11760remote_target::memory_map ()
fd79ecee 11761{
a664f67e 11762 std::vector<mem_region> result;
9018be22 11763 gdb::optional<gdb::char_vector> text
328d42d8
SM
11764 = target_read_stralloc (current_inferior ()->top_target (),
11765 TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11766
11767 if (text)
9018be22 11768 result = parse_memory_map (text->data ());
fd79ecee
DJ
11769
11770 return result;
11771}
11772
e5b176f2
AB
11773/* Set of callbacks used to implement the 'maint packet' command. */
11774
11775struct cli_packet_command_callbacks : public send_remote_packet_callbacks
c906108c 11776{
e5b176f2
AB
11777 /* Called before the packet is sent. BUF is the packet content before
11778 the protocol specific prefix, suffix, and escaping is added. */
c906108c 11779
e5b176f2
AB
11780 void sending (gdb::array_view<const char> &buf) override
11781 {
0426ad51 11782 gdb_puts ("sending: ");
e5b176f2 11783 print_packet (buf);
0426ad51 11784 gdb_puts ("\n");
e5b176f2 11785 }
c906108c 11786
e5b176f2
AB
11787 /* Called with BUF, the reply from the remote target. */
11788
11789 void received (gdb::array_view<const char> &buf) override
11790 {
0426ad51 11791 gdb_puts ("received: \"");
e5b176f2 11792 print_packet (buf);
0426ad51 11793 gdb_puts ("\"\n");
e5b176f2
AB
11794 }
11795
11796private:
11797
11798 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11799 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11800
11801 static void
11802 print_packet (gdb::array_view<const char> &buf)
11803 {
11804 string_file stb;
11805
11806 for (int i = 0; i < buf.size (); ++i)
11807 {
11808 gdb_byte c = buf[i];
11809 if (isprint (c))
a11ac3b3 11810 gdb_putc (c, &stb);
e5b176f2 11811 else
6cb06a8c 11812 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
e5b176f2
AB
11813 }
11814
0426ad51 11815 gdb_puts (stb.string ().c_str ());
e5b176f2
AB
11816 }
11817};
11818
11819/* See remote.h. */
6b8edb51
PA
11820
11821void
e5b176f2
AB
11822send_remote_packet (gdb::array_view<const char> &buf,
11823 send_remote_packet_callbacks *callbacks)
6b8edb51 11824{
e5b176f2
AB
11825 if (buf.size () == 0 || buf.data ()[0] == '\0')
11826 error (_("a remote packet must not be empty"));
c906108c 11827
e5b176f2
AB
11828 remote_target *remote = get_current_remote_target ();
11829 if (remote == nullptr)
11830 error (_("packets can only be sent to a remote target"));
c906108c 11831
e5b176f2 11832 callbacks->sending (buf);
6b8edb51 11833
e5b176f2
AB
11834 remote->putpkt_binary (buf.data (), buf.size ());
11835 remote_state *rs = remote->get_remote_state ();
11836 int bytes = remote->getpkt_sane (&rs->buf, 0);
11837
11838 if (bytes < 0)
11839 error (_("error while fetching packet from remote target"));
11840
11841 gdb::array_view<const char> view (&rs->buf[0], bytes);
11842 callbacks->received (view);
11843}
11844
11845/* Entry point for the 'maint packet' command. */
11846
11847static void
11848cli_packet_command (const char *args, int from_tty)
11849{
11850 cli_packet_command_callbacks cb;
11851 gdb::array_view<const char> view
11852 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11853 send_remote_packet (view, &cb);
c906108c
SS
11854}
11855
11856#if 0
23860348 11857/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11858
a14ed312 11859static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11860
a14ed312 11861static void threadset_test_cmd (char *cmd, int tty);
c906108c 11862
a14ed312 11863static void threadalive_test (char *cmd, int tty);
c906108c 11864
a14ed312 11865static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11866
23860348 11867int get_and_display_threadinfo (threadref *ref);
c906108c 11868
a14ed312 11869static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11870
23860348 11871static int thread_display_step (threadref *ref, void *context);
c906108c 11872
a14ed312 11873static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11874
a14ed312 11875static void init_remote_threadtests (void);
c906108c 11876
23860348 11877#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11878
11879static void
0b39b52e 11880threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11881{
11882 int sample_thread = SAMPLE_THREAD;
11883
6cb06a8c 11884 gdb_printf (_("Remote threadset test\n"));
79d7f229 11885 set_general_thread (sample_thread);
c906108c
SS
11886}
11887
11888
11889static void
0b39b52e 11890threadalive_test (const char *cmd, int tty)
c906108c
SS
11891{
11892 int sample_thread = SAMPLE_THREAD;
e99b03dc 11893 int pid = inferior_ptid.pid ();
fd79271b 11894 ptid_t ptid = ptid_t (pid, sample_thread, 0);
c906108c 11895
79d7f229 11896 if (remote_thread_alive (ptid))
6cb06a8c 11897 gdb_printf ("PASS: Thread alive test\n");
c906108c 11898 else
6cb06a8c 11899 gdb_printf ("FAIL: Thread alive test\n");
c906108c
SS
11900}
11901
23860348 11902void output_threadid (char *title, threadref *ref);
c906108c
SS
11903
11904void
fba45db2 11905output_threadid (char *title, threadref *ref)
c906108c
SS
11906{
11907 char hexid[20];
11908
405feb71 11909 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
c906108c 11910 hexid[16] = 0;
6cb06a8c 11911 gdb_printf ("%s %s\n", title, (&hexid[0]));
c906108c
SS
11912}
11913
11914static void
0b39b52e 11915threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11916{
11917 int startflag = 1;
11918 threadref nextthread;
11919 int done, result_count;
11920 threadref threadlist[3];
11921
6cb06a8c 11922 gdb_printf ("Remote Threadlist test\n");
c906108c
SS
11923 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11924 &result_count, &threadlist[0]))
6cb06a8c 11925 gdb_printf ("FAIL: threadlist test\n");
c906108c
SS
11926 else
11927 {
11928 threadref *scan = threadlist;
11929 threadref *limit = scan + result_count;
11930
11931 while (scan < limit)
11932 output_threadid (" thread ", scan++);
11933 }
11934}
11935
11936void
fba45db2 11937display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11938{
11939 output_threadid ("Threadid: ", &info->threadid);
6cb06a8c
TT
11940 gdb_printf ("Name: %s\n ", info->shortname);
11941 gdb_printf ("State: %s\n", info->display);
11942 gdb_printf ("other: %s\n\n", info->more_display);
c906108c
SS
11943}
11944
11945int
fba45db2 11946get_and_display_threadinfo (threadref *ref)
c906108c
SS
11947{
11948 int result;
11949 int set;
11950 struct gdb_ext_thread_info threadinfo;
11951
11952 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11953 | TAG_MOREDISPLAY | TAG_DISPLAY;
11954 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11955 display_thread_info (&threadinfo);
11956 return result;
11957}
11958
11959static void
0b39b52e 11960threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11961{
11962 int athread = SAMPLE_THREAD;
11963 threadref thread;
11964 int set;
11965
11966 int_to_threadref (&thread, athread);
6cb06a8c 11967 gdb_printf ("Remote Threadinfo test\n");
c906108c 11968 if (!get_and_display_threadinfo (&thread))
6cb06a8c 11969 gdb_printf ("FAIL cannot get thread info\n");
c906108c
SS
11970}
11971
11972static int
fba45db2 11973thread_display_step (threadref *ref, void *context)
c906108c
SS
11974{
11975 /* output_threadid(" threadstep ",ref); *//* simple test */
11976 return get_and_display_threadinfo (ref);
11977}
11978
11979static void
0b39b52e 11980threadlist_update_test_cmd (const char *cmd, int tty)
c906108c 11981{
6cb06a8c 11982 gdb_printf ("Remote Threadlist update test\n");
c906108c
SS
11983 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11984}
11985
11986static void
11987init_remote_threadtests (void)
11988{
3e43a32a
MS
11989 add_com ("tlist", class_obscure, threadlist_test_cmd,
11990 _("Fetch and print the remote list of "
590042fc 11991 "thread identifiers, one pkt only."));
c906108c 11992 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
590042fc 11993 _("Fetch and display info about one thread."));
c906108c 11994 add_com ("tset", class_obscure, threadset_test_cmd,
590042fc 11995 _("Test setting to a different thread."));
c906108c 11996 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
590042fc 11997 _("Iterate through updating all remote thread info."));
c906108c 11998 add_com ("talive", class_obscure, threadalive_test,
590042fc 11999 _("Remote thread alive test."));
c906108c
SS
12000}
12001
12002#endif /* 0 */
12003
a068643d 12004/* Convert a thread ID to a string. */
f3fb8c85 12005
a068643d 12006std::string
f6ac5f3d 12007remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 12008{
d7e15655 12009 if (ptid == null_ptid)
7cee1e54 12010 return normal_pid_to_str (ptid);
0e998d96 12011 else if (ptid.is_pid ())
ecd0ada5
PA
12012 {
12013 /* Printing an inferior target id. */
12014
12015 /* When multi-process extensions are off, there's no way in the
12016 remote protocol to know the remote process id, if there's any
12017 at all. There's one exception --- when we're connected with
12018 target extended-remote, and we manually attached to a process
12019 with "attach PID". We don't record anywhere a flag that
12020 allows us to distinguish that case from the case of
12021 connecting with extended-remote and the stub already being
12022 attached to a process, and reporting yes to qAttached, hence
12023 no smart special casing here. */
ff52c073 12024 if (!m_features.remote_multi_process_p ())
a068643d 12025 return "Remote target";
ecd0ada5
PA
12026
12027 return normal_pid_to_str (ptid);
82f73884 12028 }
ecd0ada5 12029 else
79d7f229 12030 {
d7e15655 12031 if (magic_null_ptid == ptid)
a068643d 12032 return "Thread <main>";
ff52c073 12033 else if (m_features.remote_multi_process_p ())
e38504b3 12034 if (ptid.lwp () == 0)
de0d863e
DB
12035 return normal_pid_to_str (ptid);
12036 else
a068643d
TT
12037 return string_printf ("Thread %d.%ld",
12038 ptid.pid (), ptid.lwp ());
ecd0ada5 12039 else
a068643d 12040 return string_printf ("Thread %ld", ptid.lwp ());
79d7f229 12041 }
f3fb8c85
MS
12042}
12043
38691318
KB
12044/* Get the address of the thread local variable in OBJFILE which is
12045 stored at OFFSET within the thread local storage for thread PTID. */
12046
f6ac5f3d
PA
12047CORE_ADDR
12048remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12049 CORE_ADDR offset)
38691318 12050{
ff52c073 12051 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
12052 {
12053 struct remote_state *rs = get_remote_state ();
8d64371b
TT
12054 char *p = rs->buf.data ();
12055 char *endp = p + get_remote_packet_size ();
571dd617 12056 enum packet_result result;
38691318
KB
12057
12058 strcpy (p, "qGetTLSAddr:");
12059 p += strlen (p);
82f73884 12060 p = write_ptid (p, endp, ptid);
38691318
KB
12061 *p++ = ',';
12062 p += hexnumstr (p, offset);
12063 *p++ = ',';
12064 p += hexnumstr (p, lm);
12065 *p++ = '\0';
12066
6d820c5c 12067 putpkt (rs->buf);
8d64371b 12068 getpkt (&rs->buf, 0);
ff52c073 12069 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
571dd617 12070 if (result == PACKET_OK)
38691318 12071 {
b926417a 12072 ULONGEST addr;
38691318 12073
8d64371b 12074 unpack_varlen_hex (rs->buf.data (), &addr);
b926417a 12075 return addr;
38691318 12076 }
571dd617 12077 else if (result == PACKET_UNKNOWN)
109c3e39
AC
12078 throw_error (TLS_GENERIC_ERROR,
12079 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 12080 else
109c3e39
AC
12081 throw_error (TLS_GENERIC_ERROR,
12082 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
12083 }
12084 else
109c3e39
AC
12085 throw_error (TLS_GENERIC_ERROR,
12086 _("TLS not supported or disabled on this target"));
38691318
KB
12087 /* Not reached. */
12088 return 0;
12089}
12090
711e434b
PM
12091/* Provide thread local base, i.e. Thread Information Block address.
12092 Returns 1 if ptid is found and thread_local_base is non zero. */
12093
57810aa7 12094bool
f6ac5f3d 12095remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 12096{
ff52c073 12097 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
12098 {
12099 struct remote_state *rs = get_remote_state ();
8d64371b
TT
12100 char *p = rs->buf.data ();
12101 char *endp = p + get_remote_packet_size ();
711e434b
PM
12102 enum packet_result result;
12103
12104 strcpy (p, "qGetTIBAddr:");
12105 p += strlen (p);
12106 p = write_ptid (p, endp, ptid);
12107 *p++ = '\0';
12108
12109 putpkt (rs->buf);
8d64371b 12110 getpkt (&rs->buf, 0);
ff52c073 12111 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
711e434b
PM
12112 if (result == PACKET_OK)
12113 {
b926417a 12114 ULONGEST val;
8d64371b 12115 unpack_varlen_hex (rs->buf.data (), &val);
711e434b 12116 if (addr)
b926417a 12117 *addr = (CORE_ADDR) val;
57810aa7 12118 return true;
711e434b
PM
12119 }
12120 else if (result == PACKET_UNKNOWN)
12121 error (_("Remote target doesn't support qGetTIBAddr packet"));
12122 else
12123 error (_("Remote target failed to process qGetTIBAddr request"));
12124 }
12125 else
12126 error (_("qGetTIBAddr not supported or disabled on this target"));
12127 /* Not reached. */
57810aa7 12128 return false;
711e434b
PM
12129}
12130
29709017
DJ
12131/* Support for inferring a target description based on the current
12132 architecture and the size of a 'g' packet. While the 'g' packet
12133 can have any size (since optional registers can be left off the
12134 end), some sizes are easily recognizable given knowledge of the
12135 approximate architecture. */
12136
12137struct remote_g_packet_guess
12138{
eefce37f
TT
12139 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12140 : bytes (bytes_),
12141 tdesc (tdesc_)
12142 {
12143 }
12144
29709017
DJ
12145 int bytes;
12146 const struct target_desc *tdesc;
12147};
29709017 12148
cb275538 12149struct remote_g_packet_data
29709017 12150{
eefce37f 12151 std::vector<remote_g_packet_guess> guesses;
29709017
DJ
12152};
12153
cb275538
TT
12154static const registry<gdbarch>::key<struct remote_g_packet_data>
12155 remote_g_packet_data_handle;
29709017 12156
cb275538
TT
12157static struct remote_g_packet_data *
12158get_g_packet_data (struct gdbarch *gdbarch)
29709017 12159{
cb275538
TT
12160 struct remote_g_packet_data *data
12161 = remote_g_packet_data_handle.get (gdbarch);
12162 if (data == nullptr)
12163 data = remote_g_packet_data_handle.emplace (gdbarch);
12164 return data;
29709017
DJ
12165}
12166
12167void
12168register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12169 const struct target_desc *tdesc)
12170{
cb275538 12171 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
29709017
DJ
12172
12173 gdb_assert (tdesc != NULL);
12174
eefce37f
TT
12175 for (const remote_g_packet_guess &guess : data->guesses)
12176 if (guess.bytes == bytes)
f34652de 12177 internal_error (_("Duplicate g packet description added for size %d"),
29709017
DJ
12178 bytes);
12179
eefce37f 12180 data->guesses.emplace_back (bytes, tdesc);
29709017
DJ
12181}
12182
eefce37f
TT
12183/* Return true if remote_read_description would do anything on this target
12184 and architecture, false otherwise. */
d962ef82 12185
eefce37f 12186static bool
d962ef82
DJ
12187remote_read_description_p (struct target_ops *target)
12188{
cb275538 12189 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
d962ef82 12190
eefce37f 12191 return !data->guesses.empty ();
d962ef82
DJ
12192}
12193
f6ac5f3d
PA
12194const struct target_desc *
12195remote_target::read_description ()
29709017 12196{
cb275538 12197 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
29709017 12198
d962ef82
DJ
12199 /* Do not try this during initial connection, when we do not know
12200 whether there is a running but stopped thread. */
55f6301a 12201 if (!target_has_execution () || inferior_ptid == null_ptid)
b6a8c27b 12202 return beneath ()->read_description ();
d962ef82 12203
eefce37f 12204 if (!data->guesses.empty ())
29709017 12205 {
29709017
DJ
12206 int bytes = send_g_packet ();
12207
eefce37f
TT
12208 for (const remote_g_packet_guess &guess : data->guesses)
12209 if (guess.bytes == bytes)
12210 return guess.tdesc;
29709017
DJ
12211
12212 /* We discard the g packet. A minor optimization would be to
12213 hold on to it, and fill the register cache once we have selected
12214 an architecture, but it's too tricky to do safely. */
12215 }
12216
b6a8c27b 12217 return beneath ()->read_description ();
29709017
DJ
12218}
12219
a6b151f1
DJ
12220/* Remote file transfer support. This is host-initiated I/O, not
12221 target-initiated; for target-initiated, see remote-fileio.c. */
12222
12223/* If *LEFT is at least the length of STRING, copy STRING to
12224 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12225 decrease *LEFT. Otherwise raise an error. */
12226
12227static void
a121b7c1 12228remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
12229{
12230 int len = strlen (string);
12231
12232 if (len > *left)
12233 error (_("Packet too long for target."));
12234
12235 memcpy (*buffer, string, len);
12236 *buffer += len;
12237 *left -= len;
12238
12239 /* NUL-terminate the buffer as a convenience, if there is
12240 room. */
12241 if (*left)
12242 **buffer = '\0';
12243}
12244
12245/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12246 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12247 decrease *LEFT. Otherwise raise an error. */
12248
12249static void
12250remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12251 int len)
12252{
12253 if (2 * len > *left)
12254 error (_("Packet too long for target."));
12255
12256 bin2hex (bytes, *buffer, len);
12257 *buffer += 2 * len;
12258 *left -= 2 * len;
12259
12260 /* NUL-terminate the buffer as a convenience, if there is
12261 room. */
12262 if (*left)
12263 **buffer = '\0';
12264}
12265
12266/* If *LEFT is large enough, convert VALUE to hex and add it to
12267 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12268 decrease *LEFT. Otherwise raise an error. */
12269
12270static void
12271remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12272{
12273 int len = hexnumlen (value);
12274
12275 if (len > *left)
12276 error (_("Packet too long for target."));
12277
12278 hexnumstr (*buffer, value);
12279 *buffer += len;
12280 *left -= len;
12281
12282 /* NUL-terminate the buffer as a convenience, if there is
12283 room. */
12284 if (*left)
12285 **buffer = '\0';
12286}
12287
12288/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
b872057a 12289 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
a6b151f1
DJ
12290 was included, and *ATTACHMENT to point to the start of the annex
12291 if any. The length of the packet isn't needed here; there may
12292 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12293
12294 Return 0 if the packet could be parsed, -1 if it could not. If
12295 -1 is returned, the other variables may not be initialized. */
12296
12297static int
aa2838cc 12298remote_hostio_parse_result (const char *buffer, int *retcode,
b872057a 12299 fileio_error *remote_errno, const char **attachment)
a6b151f1
DJ
12300{
12301 char *p, *p2;
12302
b872057a 12303 *remote_errno = FILEIO_SUCCESS;
a6b151f1
DJ
12304 *attachment = NULL;
12305
12306 if (buffer[0] != 'F')
12307 return -1;
12308
12309 errno = 0;
12310 *retcode = strtol (&buffer[1], &p, 16);
12311 if (errno != 0 || p == &buffer[1])
12312 return -1;
12313
12314 /* Check for ",errno". */
12315 if (*p == ',')
12316 {
12317 errno = 0;
b872057a 12318 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
a6b151f1
DJ
12319 if (errno != 0 || p + 1 == p2)
12320 return -1;
12321 p = p2;
12322 }
12323
12324 /* Check for ";attachment". If there is no attachment, the
12325 packet should end here. */
12326 if (*p == ';')
12327 {
12328 *attachment = p + 1;
12329 return 0;
12330 }
12331 else if (*p == '\0')
12332 return 0;
12333 else
12334 return -1;
12335}
12336
12337/* Send a prepared I/O packet to the target and read its response.
12338 The prepared packet is in the global RS->BUF before this function
12339 is called, and the answer is there when we return.
12340
12341 COMMAND_BYTES is the length of the request to send, which may include
12342 binary data. WHICH_PACKET is the packet configuration to check
12343 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12344 is set to the error number and -1 is returned. Otherwise the value
12345 returned by the function is returned.
12346
12347 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12348 attachment is expected; an error will be reported if there's a
12349 mismatch. If one is found, *ATTACHMENT will be set to point into
12350 the packet buffer and *ATTACHMENT_LEN will be set to the
12351 attachment's length. */
12352
6b8edb51
PA
12353int
12354remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
b872057a 12355 fileio_error *remote_errno, const char **attachment,
6b8edb51 12356 int *attachment_len)
a6b151f1
DJ
12357{
12358 struct remote_state *rs = get_remote_state ();
12359 int ret, bytes_read;
aa2838cc 12360 const char *attachment_tmp;
a6b151f1 12361
ff52c073 12362 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
12363 {
12364 *remote_errno = FILEIO_ENOSYS;
12365 return -1;
12366 }
12367
8d64371b
TT
12368 putpkt_binary (rs->buf.data (), command_bytes);
12369 bytes_read = getpkt_sane (&rs->buf, 0);
a6b151f1
DJ
12370
12371 /* If it timed out, something is wrong. Don't try to parse the
12372 buffer. */
12373 if (bytes_read < 0)
12374 {
12375 *remote_errno = FILEIO_EINVAL;
12376 return -1;
12377 }
12378
ff52c073 12379 switch (m_features.packet_ok (rs->buf, which_packet))
a6b151f1
DJ
12380 {
12381 case PACKET_ERROR:
12382 *remote_errno = FILEIO_EINVAL;
12383 return -1;
12384 case PACKET_UNKNOWN:
12385 *remote_errno = FILEIO_ENOSYS;
12386 return -1;
12387 case PACKET_OK:
12388 break;
12389 }
12390
8d64371b 12391 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
a6b151f1
DJ
12392 &attachment_tmp))
12393 {
12394 *remote_errno = FILEIO_EINVAL;
12395 return -1;
12396 }
12397
12398 /* Make sure we saw an attachment if and only if we expected one. */
12399 if ((attachment_tmp == NULL && attachment != NULL)
12400 || (attachment_tmp != NULL && attachment == NULL))
12401 {
12402 *remote_errno = FILEIO_EINVAL;
12403 return -1;
12404 }
12405
12406 /* If an attachment was found, it must point into the packet buffer;
12407 work out how many bytes there were. */
12408 if (attachment_tmp != NULL)
12409 {
12410 *attachment = attachment_tmp;
8d64371b 12411 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
a6b151f1
DJ
12412 }
12413
12414 return ret;
12415}
12416
dd194f6b 12417/* See declaration.h. */
80152258 12418
dd194f6b
PA
12419void
12420readahead_cache::invalidate ()
80152258 12421{
dd194f6b 12422 this->fd = -1;
80152258
PA
12423}
12424
dd194f6b 12425/* See declaration.h. */
80152258 12426
dd194f6b
PA
12427void
12428readahead_cache::invalidate_fd (int fd)
80152258 12429{
dd194f6b
PA
12430 if (this->fd == fd)
12431 this->fd = -1;
80152258
PA
12432}
12433
15a201c8
GB
12434/* Set the filesystem remote_hostio functions that take FILENAME
12435 arguments will use. Return 0 on success, or -1 if an error
12436 occurs (and set *REMOTE_ERRNO). */
12437
6b8edb51
PA
12438int
12439remote_target::remote_hostio_set_filesystem (struct inferior *inf,
b872057a 12440 fileio_error *remote_errno)
15a201c8
GB
12441{
12442 struct remote_state *rs = get_remote_state ();
12443 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
8d64371b 12444 char *p = rs->buf.data ();
15a201c8
GB
12445 int left = get_remote_packet_size () - 1;
12446 char arg[9];
12447 int ret;
12448
ff52c073 12449 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
15a201c8
GB
12450 return 0;
12451
12452 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12453 return 0;
12454
12455 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12456
12457 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12458 remote_buffer_add_string (&p, &left, arg);
12459
8d64371b 12460 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
15a201c8
GB
12461 remote_errno, NULL, NULL);
12462
ff52c073 12463 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
15a201c8
GB
12464 return 0;
12465
12466 if (ret == 0)
12467 rs->fs_pid = required_pid;
12468
12469 return ret;
12470}
12471
12e2a5fd 12472/* Implementation of to_fileio_open. */
a6b151f1 12473
6b8edb51
PA
12474int
12475remote_target::remote_hostio_open (inferior *inf, const char *filename,
12476 int flags, int mode, int warn_if_slow,
b872057a 12477 fileio_error *remote_errno)
a6b151f1
DJ
12478{
12479 struct remote_state *rs = get_remote_state ();
8d64371b 12480 char *p = rs->buf.data ();
a6b151f1
DJ
12481 int left = get_remote_packet_size () - 1;
12482
4313b8c0
GB
12483 if (warn_if_slow)
12484 {
12485 static int warning_issued = 0;
12486
6cb06a8c
TT
12487 gdb_printf (_("Reading %s from remote target...\n"),
12488 filename);
4313b8c0
GB
12489
12490 if (!warning_issued)
12491 {
12492 warning (_("File transfers from remote targets can be slow."
12493 " Use \"set sysroot\" to access files locally"
12494 " instead."));
12495 warning_issued = 1;
12496 }
12497 }
12498
15a201c8
GB
12499 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12500 return -1;
12501
a6b151f1
DJ
12502 remote_buffer_add_string (&p, &left, "vFile:open:");
12503
12504 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12505 strlen (filename));
12506 remote_buffer_add_string (&p, &left, ",");
12507
12508 remote_buffer_add_int (&p, &left, flags);
12509 remote_buffer_add_string (&p, &left, ",");
12510
12511 remote_buffer_add_int (&p, &left, mode);
12512
8d64371b 12513 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
a6b151f1
DJ
12514 remote_errno, NULL, NULL);
12515}
12516
f6ac5f3d
PA
12517int
12518remote_target::fileio_open (struct inferior *inf, const char *filename,
12519 int flags, int mode, int warn_if_slow,
b872057a 12520 fileio_error *remote_errno)
f6ac5f3d 12521{
6b8edb51 12522 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
12523 remote_errno);
12524}
12525
12e2a5fd 12526/* Implementation of to_fileio_pwrite. */
a6b151f1 12527
6b8edb51
PA
12528int
12529remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 12530 ULONGEST offset, fileio_error *remote_errno)
a6b151f1
DJ
12531{
12532 struct remote_state *rs = get_remote_state ();
8d64371b 12533 char *p = rs->buf.data ();
a6b151f1
DJ
12534 int left = get_remote_packet_size ();
12535 int out_len;
12536
dd194f6b 12537 rs->readahead_cache.invalidate_fd (fd);
80152258 12538
a6b151f1
DJ
12539 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12540
12541 remote_buffer_add_int (&p, &left, fd);
12542 remote_buffer_add_string (&p, &left, ",");
12543
12544 remote_buffer_add_int (&p, &left, offset);
12545 remote_buffer_add_string (&p, &left, ",");
12546
124e13d9 12547 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
8d64371b
TT
12548 (get_remote_packet_size ()
12549 - (p - rs->buf.data ())));
a6b151f1 12550
8d64371b 12551 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
a6b151f1
DJ
12552 remote_errno, NULL, NULL);
12553}
12554
f6ac5f3d
PA
12555int
12556remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 12557 ULONGEST offset, fileio_error *remote_errno)
f6ac5f3d 12558{
6b8edb51 12559 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12560}
12561
80152258
PA
12562/* Helper for the implementation of to_fileio_pread. Read the file
12563 from the remote side with vFile:pread. */
a6b151f1 12564
6b8edb51
PA
12565int
12566remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
b872057a 12567 ULONGEST offset, fileio_error *remote_errno)
a6b151f1
DJ
12568{
12569 struct remote_state *rs = get_remote_state ();
8d64371b 12570 char *p = rs->buf.data ();
aa2838cc 12571 const char *attachment;
a6b151f1
DJ
12572 int left = get_remote_packet_size ();
12573 int ret, attachment_len;
12574 int read_len;
12575
12576 remote_buffer_add_string (&p, &left, "vFile:pread:");
12577
12578 remote_buffer_add_int (&p, &left, fd);
12579 remote_buffer_add_string (&p, &left, ",");
12580
12581 remote_buffer_add_int (&p, &left, len);
12582 remote_buffer_add_string (&p, &left, ",");
12583
12584 remote_buffer_add_int (&p, &left, offset);
12585
8d64371b 12586 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
a6b151f1
DJ
12587 remote_errno, &attachment,
12588 &attachment_len);
12589
12590 if (ret < 0)
12591 return ret;
12592
bc20a4af 12593 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12594 read_buf, len);
12595 if (read_len != ret)
12596 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12597
12598 return ret;
12599}
12600
dd194f6b 12601/* See declaration.h. */
80152258 12602
dd194f6b
PA
12603int
12604readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12605 ULONGEST offset)
80152258 12606{
dd194f6b
PA
12607 if (this->fd == fd
12608 && this->offset <= offset
6b19f38a 12609 && offset < this->offset + this->buf.size ())
80152258 12610 {
6b19f38a 12611 ULONGEST max = this->offset + this->buf.size ();
80152258
PA
12612
12613 if (offset + len > max)
12614 len = max - offset;
12615
6b19f38a 12616 memcpy (read_buf, &this->buf[offset - this->offset], len);
80152258
PA
12617 return len;
12618 }
12619
12620 return 0;
12621}
12622
12623/* Implementation of to_fileio_pread. */
12624
6b8edb51
PA
12625int
12626remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 12627 ULONGEST offset, fileio_error *remote_errno)
80152258
PA
12628{
12629 int ret;
12630 struct remote_state *rs = get_remote_state ();
dd194f6b 12631 readahead_cache *cache = &rs->readahead_cache;
80152258 12632
dd194f6b 12633 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12634 if (ret > 0)
12635 {
12636 cache->hit_count++;
12637
2189c312
SM
12638 remote_debug_printf ("readahead cache hit %s",
12639 pulongest (cache->hit_count));
80152258
PA
12640 return ret;
12641 }
12642
12643 cache->miss_count++;
2189c312
SM
12644
12645 remote_debug_printf ("readahead cache miss %s",
12646 pulongest (cache->miss_count));
80152258
PA
12647
12648 cache->fd = fd;
12649 cache->offset = offset;
6b19f38a 12650 cache->buf.resize (get_remote_packet_size ());
80152258 12651
6b19f38a
TT
12652 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12653 cache->buf.size (),
80152258
PA
12654 cache->offset, remote_errno);
12655 if (ret <= 0)
12656 {
dd194f6b 12657 cache->invalidate_fd (fd);
80152258
PA
12658 return ret;
12659 }
12660
6b19f38a 12661 cache->buf.resize (ret);
dd194f6b 12662 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12663}
12664
f6ac5f3d
PA
12665int
12666remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 12667 ULONGEST offset, fileio_error *remote_errno)
f6ac5f3d 12668{
6b8edb51 12669 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12670}
12671
12e2a5fd 12672/* Implementation of to_fileio_close. */
a6b151f1 12673
6b8edb51 12674int
b872057a 12675remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
a6b151f1
DJ
12676{
12677 struct remote_state *rs = get_remote_state ();
8d64371b 12678 char *p = rs->buf.data ();
a6b151f1
DJ
12679 int left = get_remote_packet_size () - 1;
12680
dd194f6b 12681 rs->readahead_cache.invalidate_fd (fd);
80152258 12682
a6b151f1
DJ
12683 remote_buffer_add_string (&p, &left, "vFile:close:");
12684
12685 remote_buffer_add_int (&p, &left, fd);
12686
8d64371b 12687 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
a6b151f1
DJ
12688 remote_errno, NULL, NULL);
12689}
12690
f6ac5f3d 12691int
b872057a 12692remote_target::fileio_close (int fd, fileio_error *remote_errno)
f6ac5f3d 12693{
6b8edb51 12694 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12695}
12696
12e2a5fd 12697/* Implementation of to_fileio_unlink. */
a6b151f1 12698
6b8edb51
PA
12699int
12700remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
b872057a 12701 fileio_error *remote_errno)
a6b151f1
DJ
12702{
12703 struct remote_state *rs = get_remote_state ();
8d64371b 12704 char *p = rs->buf.data ();
a6b151f1
DJ
12705 int left = get_remote_packet_size () - 1;
12706
15a201c8
GB
12707 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12708 return -1;
12709
a6b151f1
DJ
12710 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12711
12712 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12713 strlen (filename));
12714
8d64371b 12715 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
a6b151f1
DJ
12716 remote_errno, NULL, NULL);
12717}
12718
f6ac5f3d
PA
12719int
12720remote_target::fileio_unlink (struct inferior *inf, const char *filename,
b872057a 12721 fileio_error *remote_errno)
f6ac5f3d 12722{
6b8edb51 12723 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12724}
12725
12e2a5fd 12726/* Implementation of to_fileio_readlink. */
b9e7b9c3 12727
f6ac5f3d
PA
12728gdb::optional<std::string>
12729remote_target::fileio_readlink (struct inferior *inf, const char *filename,
b872057a 12730 fileio_error *remote_errno)
b9e7b9c3
UW
12731{
12732 struct remote_state *rs = get_remote_state ();
8d64371b 12733 char *p = rs->buf.data ();
aa2838cc 12734 const char *attachment;
b9e7b9c3
UW
12735 int left = get_remote_packet_size ();
12736 int len, attachment_len;
12737 int read_len;
b9e7b9c3 12738
15a201c8 12739 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12740 return {};
15a201c8 12741
b9e7b9c3
UW
12742 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12743
12744 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12745 strlen (filename));
12746
8d64371b 12747 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
b9e7b9c3
UW
12748 remote_errno, &attachment,
12749 &attachment_len);
12750
12751 if (len < 0)
e0d3522b 12752 return {};
b9e7b9c3 12753
e0d3522b 12754 std::string ret (len, '\0');
b9e7b9c3 12755
bc20a4af 12756 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12757 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12758 if (read_len != len)
12759 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12760
b9e7b9c3
UW
12761 return ret;
12762}
12763
12e2a5fd 12764/* Implementation of to_fileio_fstat. */
0a93529c 12765
f6ac5f3d 12766int
b872057a 12767remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
0a93529c
GB
12768{
12769 struct remote_state *rs = get_remote_state ();
8d64371b 12770 char *p = rs->buf.data ();
0a93529c
GB
12771 int left = get_remote_packet_size ();
12772 int attachment_len, ret;
aa2838cc 12773 const char *attachment;
0a93529c
GB
12774 struct fio_stat fst;
12775 int read_len;
12776
464b0089
GB
12777 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12778
12779 remote_buffer_add_int (&p, &left, fd);
12780
8d64371b 12781 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
464b0089
GB
12782 remote_errno, &attachment,
12783 &attachment_len);
12784 if (ret < 0)
0a93529c 12785 {
464b0089
GB
12786 if (*remote_errno != FILEIO_ENOSYS)
12787 return ret;
12788
0a93529c
GB
12789 /* Strictly we should return -1, ENOSYS here, but when
12790 "set sysroot remote:" was implemented in August 2008
12791 BFD's need for a stat function was sidestepped with
12792 this hack. This was not remedied until March 2015
12793 so we retain the previous behavior to avoid breaking
12794 compatibility.
12795
12796 Note that the memset is a March 2015 addition; older
12797 GDBs set st_size *and nothing else* so the structure
12798 would have garbage in all other fields. This might
12799 break something but retaining the previous behavior
12800 here would be just too wrong. */
12801
12802 memset (st, 0, sizeof (struct stat));
12803 st->st_size = INT_MAX;
12804 return 0;
12805 }
12806
0a93529c
GB
12807 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12808 (gdb_byte *) &fst, sizeof (fst));
12809
12810 if (read_len != ret)
12811 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12812
12813 if (read_len != sizeof (fst))
12814 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12815 read_len, (int) sizeof (fst));
12816
12817 remote_fileio_to_host_stat (&fst, st);
12818
12819 return 0;
12820}
12821
12e2a5fd 12822/* Implementation of to_filesystem_is_local. */
e3dd7556 12823
57810aa7 12824bool
f6ac5f3d 12825remote_target::filesystem_is_local ()
e3dd7556
GB
12826{
12827 /* Valgrind GDB presents itself as a remote target but works
12828 on the local filesystem: it does not implement remote get
12829 and users are not expected to set a sysroot. To handle
12830 this case we treat the remote filesystem as local if the
12831 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12832 does not support vFile:open. */
e0700ba4 12833 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
e3dd7556 12834 {
ff52c073 12835 packet_support ps = m_features.packet_support (PACKET_vFile_open);
e3dd7556
GB
12836
12837 if (ps == PACKET_SUPPORT_UNKNOWN)
12838 {
b872057a
SM
12839 int fd;
12840 fileio_error remote_errno;
e3dd7556
GB
12841
12842 /* Try opening a file to probe support. The supplied
12843 filename is irrelevant, we only care about whether
12844 the stub recognizes the packet or not. */
6b8edb51 12845 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12846 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12847 &remote_errno);
12848
12849 if (fd >= 0)
6b8edb51 12850 remote_hostio_close (fd, &remote_errno);
e3dd7556 12851
ff52c073 12852 ps = m_features.packet_support (PACKET_vFile_open);
e3dd7556
GB
12853 }
12854
12855 if (ps == PACKET_DISABLE)
12856 {
12857 static int warning_issued = 0;
12858
12859 if (!warning_issued)
12860 {
12861 warning (_("remote target does not support file"
12862 " transfer, attempting to access files"
12863 " from local filesystem."));
12864 warning_issued = 1;
12865 }
12866
57810aa7 12867 return true;
e3dd7556
GB
12868 }
12869 }
12870
57810aa7 12871 return false;
e3dd7556
GB
12872}
12873
a6b151f1 12874static char *
b872057a 12875remote_hostio_error (fileio_error errnum)
a6b151f1 12876{
517a63c2 12877 int host_error = fileio_error_to_host (errnum);
a6b151f1
DJ
12878
12879 if (host_error == -1)
12880 error (_("Unknown remote I/O error %d"), errnum);
12881 else
12882 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12883}
12884
440b7aec
PA
12885/* A RAII wrapper around a remote file descriptor. */
12886
12887class scoped_remote_fd
a6b151f1 12888{
440b7aec 12889public:
6b8edb51
PA
12890 scoped_remote_fd (remote_target *remote, int fd)
12891 : m_remote (remote), m_fd (fd)
440b7aec
PA
12892 {
12893 }
a6b151f1 12894
440b7aec
PA
12895 ~scoped_remote_fd ()
12896 {
12897 if (m_fd != -1)
12898 {
12899 try
12900 {
b872057a 12901 fileio_error remote_errno;
6b8edb51 12902 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12903 }
12904 catch (...)
12905 {
12906 /* Swallow exception before it escapes the dtor. If
12907 something goes wrong, likely the connection is gone,
12908 and there's nothing else that can be done. */
12909 }
12910 }
12911 }
12912
12913 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12914
12915 /* Release ownership of the file descriptor, and return it. */
88a774b9 12916 ATTRIBUTE_UNUSED_RESULT int release () noexcept
440b7aec
PA
12917 {
12918 int fd = m_fd;
12919 m_fd = -1;
12920 return fd;
12921 }
12922
12923 /* Return the owned file descriptor. */
12924 int get () const noexcept
12925 {
12926 return m_fd;
12927 }
12928
12929private:
6b8edb51
PA
12930 /* The remote target. */
12931 remote_target *m_remote;
12932
440b7aec
PA
12933 /* The owned remote I/O file descriptor. */
12934 int m_fd;
12935};
a6b151f1
DJ
12936
12937void
12938remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12939{
12940 remote_target *remote = get_current_remote_target ();
12941
12942 if (remote == nullptr)
12943 error (_("command can only be used with remote target"));
12944
12945 remote->remote_file_put (local_file, remote_file, from_tty);
12946}
12947
12948void
12949remote_target::remote_file_put (const char *local_file, const char *remote_file,
12950 int from_tty)
a6b151f1 12951{
b872057a
SM
12952 int retcode, bytes, io_size;
12953 fileio_error remote_errno;
a6b151f1
DJ
12954 int bytes_in_buffer;
12955 int saw_eof;
12956 ULONGEST offset;
a6b151f1 12957
d419f42d 12958 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12959 if (file == NULL)
12960 perror_with_name (local_file);
a6b151f1 12961
440b7aec 12962 scoped_remote_fd fd
6b8edb51
PA
12963 (this, remote_hostio_open (NULL,
12964 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12965 | FILEIO_O_TRUNC),
12966 0700, 0, &remote_errno));
440b7aec 12967 if (fd.get () == -1)
a6b151f1
DJ
12968 remote_hostio_error (remote_errno);
12969
12970 /* Send up to this many bytes at once. They won't all fit in the
12971 remote packet limit, so we'll transfer slightly fewer. */
12972 io_size = get_remote_packet_size ();
5ca3b260 12973 gdb::byte_vector buffer (io_size);
a6b151f1 12974
a6b151f1
DJ
12975 bytes_in_buffer = 0;
12976 saw_eof = 0;
12977 offset = 0;
12978 while (bytes_in_buffer || !saw_eof)
12979 {
12980 if (!saw_eof)
12981 {
5ca3b260 12982 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 12983 io_size - bytes_in_buffer,
d419f42d 12984 file.get ());
a6b151f1
DJ
12985 if (bytes == 0)
12986 {
d419f42d 12987 if (ferror (file.get ()))
a6b151f1
DJ
12988 error (_("Error reading %s."), local_file);
12989 else
12990 {
12991 /* EOF. Unless there is something still in the
12992 buffer from the last iteration, we are done. */
12993 saw_eof = 1;
12994 if (bytes_in_buffer == 0)
12995 break;
12996 }
12997 }
12998 }
12999 else
13000 bytes = 0;
13001
13002 bytes += bytes_in_buffer;
13003 bytes_in_buffer = 0;
13004
5ca3b260 13005 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 13006 offset, &remote_errno);
a6b151f1
DJ
13007
13008 if (retcode < 0)
13009 remote_hostio_error (remote_errno);
13010 else if (retcode == 0)
13011 error (_("Remote write of %d bytes returned 0!"), bytes);
13012 else if (retcode < bytes)
13013 {
13014 /* Short write. Save the rest of the read data for the next
13015 write. */
13016 bytes_in_buffer = bytes - retcode;
5ca3b260 13017 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
13018 }
13019
13020 offset += retcode;
13021 }
13022
6b8edb51 13023 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
13024 remote_hostio_error (remote_errno);
13025
13026 if (from_tty)
6cb06a8c 13027 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
a6b151f1
DJ
13028}
13029
13030void
13031remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
13032{
13033 remote_target *remote = get_current_remote_target ();
13034
13035 if (remote == nullptr)
13036 error (_("command can only be used with remote target"));
13037
13038 remote->remote_file_get (remote_file, local_file, from_tty);
13039}
13040
13041void
13042remote_target::remote_file_get (const char *remote_file, const char *local_file,
13043 int from_tty)
a6b151f1 13044{
b872057a
SM
13045 fileio_error remote_errno;
13046 int bytes, io_size;
a6b151f1 13047 ULONGEST offset;
a6b151f1 13048
440b7aec 13049 scoped_remote_fd fd
6b8edb51
PA
13050 (this, remote_hostio_open (NULL,
13051 remote_file, FILEIO_O_RDONLY, 0, 0,
13052 &remote_errno));
440b7aec 13053 if (fd.get () == -1)
a6b151f1
DJ
13054 remote_hostio_error (remote_errno);
13055
d419f42d 13056 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
13057 if (file == NULL)
13058 perror_with_name (local_file);
a6b151f1
DJ
13059
13060 /* Send up to this many bytes at once. They won't all fit in the
13061 remote packet limit, so we'll transfer slightly fewer. */
13062 io_size = get_remote_packet_size ();
5ca3b260 13063 gdb::byte_vector buffer (io_size);
a6b151f1 13064
a6b151f1
DJ
13065 offset = 0;
13066 while (1)
13067 {
5ca3b260 13068 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 13069 &remote_errno);
a6b151f1
DJ
13070 if (bytes == 0)
13071 /* Success, but no bytes, means end-of-file. */
13072 break;
13073 if (bytes == -1)
13074 remote_hostio_error (remote_errno);
13075
13076 offset += bytes;
13077
5ca3b260 13078 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
13079 if (bytes == 0)
13080 perror_with_name (local_file);
13081 }
13082
6b8edb51 13083 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
13084 remote_hostio_error (remote_errno);
13085
13086 if (from_tty)
6cb06a8c 13087 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
a6b151f1
DJ
13088}
13089
13090void
13091remote_file_delete (const char *remote_file, int from_tty)
13092{
6b8edb51 13093 remote_target *remote = get_current_remote_target ();
a6b151f1 13094
6b8edb51 13095 if (remote == nullptr)
a6b151f1
DJ
13096 error (_("command can only be used with remote target"));
13097
6b8edb51
PA
13098 remote->remote_file_delete (remote_file, from_tty);
13099}
13100
13101void
13102remote_target::remote_file_delete (const char *remote_file, int from_tty)
13103{
b872057a
SM
13104 int retcode;
13105 fileio_error remote_errno;
6b8edb51
PA
13106
13107 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
13108 if (retcode == -1)
13109 remote_hostio_error (remote_errno);
13110
13111 if (from_tty)
6cb06a8c 13112 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
a6b151f1
DJ
13113}
13114
13115static void
ac88e2de 13116remote_put_command (const char *args, int from_tty)
a6b151f1 13117{
d1a41061
PP
13118 if (args == NULL)
13119 error_no_arg (_("file to put"));
13120
773a1edc 13121 gdb_argv argv (args);
a6b151f1
DJ
13122 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13123 error (_("Invalid parameters to remote put"));
13124
13125 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
13126}
13127
13128static void
ac88e2de 13129remote_get_command (const char *args, int from_tty)
a6b151f1 13130{
d1a41061
PP
13131 if (args == NULL)
13132 error_no_arg (_("file to get"));
13133
773a1edc 13134 gdb_argv argv (args);
a6b151f1
DJ
13135 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13136 error (_("Invalid parameters to remote get"));
13137
13138 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
13139}
13140
13141static void
ac88e2de 13142remote_delete_command (const char *args, int from_tty)
a6b151f1 13143{
d1a41061
PP
13144 if (args == NULL)
13145 error_no_arg (_("file to delete"));
13146
773a1edc 13147 gdb_argv argv (args);
a6b151f1
DJ
13148 if (argv[0] == NULL || argv[1] != NULL)
13149 error (_("Invalid parameters to remote delete"));
13150
13151 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
13152}
13153
57810aa7 13154bool
f6ac5f3d 13155remote_target::can_execute_reverse ()
b2175913 13156{
ff52c073
CS
13157 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13158 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 13159 return true;
40ab02ce 13160 else
57810aa7 13161 return false;
b2175913
MS
13162}
13163
57810aa7 13164bool
f6ac5f3d 13165remote_target::supports_non_stop ()
74531fed 13166{
57810aa7 13167 return true;
74531fed
PA
13168}
13169
57810aa7 13170bool
f6ac5f3d 13171remote_target::supports_disable_randomization ()
03583c20
UW
13172{
13173 /* Only supported in extended mode. */
57810aa7 13174 return false;
03583c20
UW
13175}
13176
57810aa7 13177bool
f6ac5f3d 13178remote_target::supports_multi_process ()
8a305172 13179{
ff52c073 13180 return m_features.remote_multi_process_p ();
8a305172
PA
13181}
13182
ff52c073
CS
13183int
13184remote_target::remote_supports_cond_tracepoints ()
782b2b07 13185{
ff52c073
CS
13186 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13187 == PACKET_ENABLE);
782b2b07
SS
13188}
13189
57810aa7 13190bool
f6ac5f3d 13191remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 13192{
ff52c073
CS
13193 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13194 == PACKET_ENABLE);
3788aec7
LM
13195}
13196
ff52c073
CS
13197int
13198remote_target::remote_supports_fast_tracepoints ()
7a697b8d 13199{
ff52c073 13200 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
13201}
13202
ff52c073
CS
13203int
13204remote_target::remote_supports_static_tracepoints ()
0fb4aa4b 13205{
ff52c073 13206 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
13207}
13208
ff52c073
CS
13209int
13210remote_target::remote_supports_install_in_trace ()
1e4d1764 13211{
ff52c073 13212 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
13213}
13214
57810aa7 13215bool
f6ac5f3d 13216remote_target::supports_enable_disable_tracepoint ()
d248b706 13217{
ff52c073 13218 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
4082afcc 13219 == PACKET_ENABLE);
d248b706
KY
13220}
13221
57810aa7 13222bool
f6ac5f3d 13223remote_target::supports_string_tracing ()
3065dfb6 13224{
ff52c073 13225 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
13226}
13227
57810aa7 13228bool
f6ac5f3d 13229remote_target::can_run_breakpoint_commands ()
d3ce09f5 13230{
ff52c073 13231 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
13232}
13233
f6ac5f3d
PA
13234void
13235remote_target::trace_init ()
35b1e5cc 13236{
b6bb3468
PA
13237 struct remote_state *rs = get_remote_state ();
13238
35b1e5cc 13239 putpkt ("QTinit");
b6bb3468 13240 remote_get_noisy_reply ();
8d64371b 13241 if (strcmp (rs->buf.data (), "OK") != 0)
35b1e5cc
SS
13242 error (_("Target does not support this command."));
13243}
13244
409873ef
SS
13245/* Recursive routine to walk through command list including loops, and
13246 download packets for each command. */
13247
6b8edb51
PA
13248void
13249remote_target::remote_download_command_source (int num, ULONGEST addr,
13250 struct command_line *cmds)
409873ef
SS
13251{
13252 struct remote_state *rs = get_remote_state ();
13253 struct command_line *cmd;
13254
13255 for (cmd = cmds; cmd; cmd = cmd->next)
13256 {
0df8b418 13257 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13258 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13259 encode_source_string (num, addr, "cmd", cmd->line,
8d64371b
TT
13260 rs->buf.data () + strlen (rs->buf.data ()),
13261 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13262 putpkt (rs->buf);
b6bb3468 13263 remote_get_noisy_reply ();
8d64371b 13264 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13265 warning (_("Target does not support source download."));
13266
13267 if (cmd->control_type == while_control
13268 || cmd->control_type == while_stepping_control)
13269 {
12973681 13270 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 13271
0df8b418 13272 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13273 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13274 encode_source_string (num, addr, "cmd", "end",
8d64371b
TT
13275 rs->buf.data () + strlen (rs->buf.data ()),
13276 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13277 putpkt (rs->buf);
b6bb3468 13278 remote_get_noisy_reply ();
8d64371b 13279 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13280 warning (_("Target does not support source download."));
13281 }
13282 }
13283}
13284
f6ac5f3d
PA
13285void
13286remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc
SS
13287{
13288 CORE_ADDR tpaddr;
409873ef 13289 char addrbuf[40];
b44ec619
SM
13290 std::vector<std::string> tdp_actions;
13291 std::vector<std::string> stepping_actions;
35b1e5cc 13292 char *pkt;
e8ba3115 13293 struct breakpoint *b = loc->owner;
d9b3f62e 13294 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 13295 struct remote_state *rs = get_remote_state ();
3df3a985 13296 int ret;
ff36536c 13297 const char *err_msg = _("Tracepoint packet too large for target.");
3df3a985
PFC
13298 size_t size_left;
13299
13300 /* We use a buffer other than rs->buf because we'll build strings
13301 across multiple statements, and other statements in between could
13302 modify rs->buf. */
13303 gdb::char_vector buf (get_remote_packet_size ());
35b1e5cc 13304
dc673c81 13305 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
13306
13307 tpaddr = loc->address;
53807e9f 13308 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
3df3a985
PFC
13309 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13310 b->number, addrbuf, /* address */
13311 (b->enable_state == bp_enabled ? 'E' : 'D'),
13312 t->step_count, t->pass_count);
13313
13314 if (ret < 0 || ret >= buf.size ())
a7f25a84 13315 error ("%s", err_msg);
3df3a985 13316
e8ba3115
YQ
13317 /* Fast tracepoints are mostly handled by the target, but we can
13318 tell the target how big of an instruction block should be moved
13319 around. */
13320 if (b->type == bp_fast_tracepoint)
13321 {
13322 /* Only test for support at download time; we may not know
13323 target capabilities at definition time. */
13324 if (remote_supports_fast_tracepoints ())
35b1e5cc 13325 {
6b940e6a
PL
13326 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13327 NULL))
3df3a985
PFC
13328 {
13329 size_left = buf.size () - strlen (buf.data ());
13330 ret = snprintf (buf.data () + strlen (buf.data ()),
13331 size_left, ":F%x",
13332 gdb_insn_length (loc->gdbarch, tpaddr));
13333
13334 if (ret < 0 || ret >= size_left)
a7f25a84 13335 error ("%s", err_msg);
3df3a985 13336 }
35b1e5cc 13337 else
e8ba3115
YQ
13338 /* If it passed validation at definition but fails now,
13339 something is very wrong. */
f34652de 13340 internal_error (_("Fast tracepoint not valid during download"));
35b1e5cc 13341 }
e8ba3115
YQ
13342 else
13343 /* Fast tracepoints are functionally identical to regular
13344 tracepoints, so don't take lack of support as a reason to
13345 give up on the trace run. */
13346 warning (_("Target does not support fast tracepoints, "
13347 "downloading %d as regular tracepoint"), b->number);
13348 }
7b572efb
TT
13349 else if (b->type == bp_static_tracepoint
13350 || b->type == bp_static_marker_tracepoint)
e8ba3115
YQ
13351 {
13352 /* Only test for support at download time; we may not know
13353 target capabilities at definition time. */
13354 if (remote_supports_static_tracepoints ())
0fb4aa4b 13355 {
e8ba3115 13356 struct static_tracepoint_marker marker;
0fb4aa4b 13357
e8ba3115 13358 if (target_static_tracepoint_marker_at (tpaddr, &marker))
3df3a985
PFC
13359 {
13360 size_left = buf.size () - strlen (buf.data ());
13361 ret = snprintf (buf.data () + strlen (buf.data ()),
13362 size_left, ":S");
13363
13364 if (ret < 0 || ret >= size_left)
a7f25a84 13365 error ("%s", err_msg);
3df3a985 13366 }
0fb4aa4b 13367 else
e8ba3115 13368 error (_("Static tracepoint not valid during download"));
0fb4aa4b 13369 }
e8ba3115
YQ
13370 else
13371 /* Fast tracepoints are functionally identical to regular
13372 tracepoints, so don't take lack of support as a reason
13373 to give up on the trace run. */
13374 error (_("Target does not support static tracepoints"));
13375 }
13376 /* If the tracepoint has a conditional, make it into an agent
13377 expression and append to the definition. */
13378 if (loc->cond)
13379 {
13380 /* Only test support at download time, we may not know target
13381 capabilities at definition time. */
13382 if (remote_supports_cond_tracepoints ())
35b1e5cc 13383 {
3df3a985
PFC
13384 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13385 loc->cond.get ());
13386
13387 size_left = buf.size () - strlen (buf.data ());
13388
13389 ret = snprintf (buf.data () + strlen (buf.data ()),
6f96f485 13390 size_left, ":X%x,", (int) aexpr->buf.size ());
3df3a985
PFC
13391
13392 if (ret < 0 || ret >= size_left)
a7f25a84 13393 error ("%s", err_msg);
3df3a985
PFC
13394
13395 size_left = buf.size () - strlen (buf.data ());
13396
13397 /* Two bytes to encode each aexpr byte, plus the terminating
13398 null byte. */
6f96f485 13399 if (aexpr->buf.size () * 2 + 1 > size_left)
a7f25a84 13400 error ("%s", err_msg);
3df3a985
PFC
13401
13402 pkt = buf.data () + strlen (buf.data ());
13403
6f96f485 13404 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
e8ba3115
YQ
13405 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13406 *pkt = '\0';
35b1e5cc 13407 }
e8ba3115
YQ
13408 else
13409 warning (_("Target does not support conditional tracepoints, "
13410 "ignoring tp %d cond"), b->number);
13411 }
35b1e5cc 13412
e0700ba4 13413 if (b->commands || !default_collect.empty ())
3df3a985
PFC
13414 {
13415 size_left = buf.size () - strlen (buf.data ());
13416
13417 ret = snprintf (buf.data () + strlen (buf.data ()),
13418 size_left, "-");
13419
13420 if (ret < 0 || ret >= size_left)
a7f25a84 13421 error ("%s", err_msg);
3df3a985
PFC
13422 }
13423
13424 putpkt (buf.data ());
b6bb3468 13425 remote_get_noisy_reply ();
8d64371b 13426 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13427 error (_("Target does not support tracepoints."));
35b1e5cc 13428
e8ba3115 13429 /* do_single_steps (t); */
b44ec619
SM
13430 for (auto action_it = tdp_actions.begin ();
13431 action_it != tdp_actions.end (); action_it++)
e8ba3115 13432 {
b44ec619
SM
13433 QUIT; /* Allow user to bail out with ^C. */
13434
aa6f3694 13435 bool has_more = ((action_it + 1) != tdp_actions.end ()
b44ec619
SM
13436 || !stepping_actions.empty ());
13437
3df3a985
PFC
13438 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13439 b->number, addrbuf, /* address */
13440 action_it->c_str (),
13441 has_more ? '-' : 0);
13442
13443 if (ret < 0 || ret >= buf.size ())
a7f25a84 13444 error ("%s", err_msg);
3df3a985
PFC
13445
13446 putpkt (buf.data ());
b44ec619 13447 remote_get_noisy_reply ();
8d64371b 13448 if (strcmp (rs->buf.data (), "OK"))
b44ec619 13449 error (_("Error on target while setting tracepoints."));
e8ba3115 13450 }
409873ef 13451
05abfc39
PFC
13452 for (auto action_it = stepping_actions.begin ();
13453 action_it != stepping_actions.end (); action_it++)
13454 {
13455 QUIT; /* Allow user to bail out with ^C. */
13456
13457 bool is_first = action_it == stepping_actions.begin ();
aa6f3694 13458 bool has_more = (action_it + 1) != stepping_actions.end ();
05abfc39 13459
3df3a985
PFC
13460 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13461 b->number, addrbuf, /* address */
13462 is_first ? "S" : "",
13463 action_it->c_str (),
13464 has_more ? "-" : "");
13465
13466 if (ret < 0 || ret >= buf.size ())
a7f25a84 13467 error ("%s", err_msg);
3df3a985
PFC
13468
13469 putpkt (buf.data ());
05abfc39 13470 remote_get_noisy_reply ();
8d64371b 13471 if (strcmp (rs->buf.data (), "OK"))
05abfc39
PFC
13472 error (_("Error on target while setting tracepoints."));
13473 }
b44ec619 13474
ff52c073 13475 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 13476 {
264f9890 13477 if (b->locspec != nullptr)
409873ef 13478 {
3df3a985
PFC
13479 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13480
13481 if (ret < 0 || ret >= buf.size ())
a7f25a84 13482 error ("%s", err_msg);
3df3a985 13483
709438c7 13484 const char *str = b->locspec->to_string ();
264f9890 13485 encode_source_string (b->number, loc->address, "at", str,
3df3a985
PFC
13486 buf.data () + strlen (buf.data ()),
13487 buf.size () - strlen (buf.data ()));
13488 putpkt (buf.data ());
b6bb3468 13489 remote_get_noisy_reply ();
8d64371b 13490 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13491 warning (_("Target does not support source download."));
409873ef 13492 }
e8ba3115
YQ
13493 if (b->cond_string)
13494 {
3df3a985
PFC
13495 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13496
13497 if (ret < 0 || ret >= buf.size ())
a7f25a84 13498 error ("%s", err_msg);
3df3a985 13499
e8ba3115 13500 encode_source_string (b->number, loc->address,
6f781ee3 13501 "cond", b->cond_string.get (),
3df3a985
PFC
13502 buf.data () + strlen (buf.data ()),
13503 buf.size () - strlen (buf.data ()));
13504 putpkt (buf.data ());
b6bb3468 13505 remote_get_noisy_reply ();
8d64371b 13506 if (strcmp (rs->buf.data (), "OK"))
e8ba3115
YQ
13507 warning (_("Target does not support source download."));
13508 }
13509 remote_download_command_source (b->number, loc->address,
13510 breakpoint_commands (b));
35b1e5cc 13511 }
35b1e5cc
SS
13512}
13513
57810aa7 13514bool
f6ac5f3d 13515remote_target::can_download_tracepoint ()
1e4d1764 13516{
1e51243a
PA
13517 struct remote_state *rs = get_remote_state ();
13518 struct trace_status *ts;
13519 int status;
13520
13521 /* Don't try to install tracepoints until we've relocated our
13522 symbols, and fetched and merged the target's tracepoint list with
13523 ours. */
13524 if (rs->starting_up)
57810aa7 13525 return false;
1e51243a
PA
13526
13527 ts = current_trace_status ();
f6ac5f3d 13528 status = get_trace_status (ts);
1e4d1764
YQ
13529
13530 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13531 return false;
1e4d1764
YQ
13532
13533 /* If we are in a tracing experiment, but remote stub doesn't support
13534 installing tracepoint in trace, we have to return. */
13535 if (!remote_supports_install_in_trace ())
57810aa7 13536 return false;
1e4d1764 13537
57810aa7 13538 return true;
1e4d1764
YQ
13539}
13540
13541
f6ac5f3d
PA
13542void
13543remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
13544{
13545 struct remote_state *rs = get_remote_state ();
00bf0b85 13546 char *p;
35b1e5cc 13547
8d64371b 13548 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
13549 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13550 tsv.builtin);
8d64371b
TT
13551 p = rs->buf.data () + strlen (rs->buf.data ());
13552 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13553 >= get_remote_packet_size ())
00bf0b85 13554 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 13555 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 13556 *p++ = '\0';
35b1e5cc 13557 putpkt (rs->buf);
b6bb3468 13558 remote_get_noisy_reply ();
8d64371b 13559 if (rs->buf[0] == '\0')
ad91cd99 13560 error (_("Target does not support this command."));
8d64371b 13561 if (strcmp (rs->buf.data (), "OK") != 0)
ad91cd99 13562 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13563}
13564
f6ac5f3d
PA
13565void
13566remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13567{
13568 struct remote_state *rs = get_remote_state ();
d248b706 13569
8d64371b 13570 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
53807e9f
TT
13571 location->owner->number,
13572 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13573 putpkt (rs->buf);
b6bb3468 13574 remote_get_noisy_reply ();
8d64371b 13575 if (rs->buf[0] == '\0')
d248b706 13576 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
8d64371b 13577 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13578 error (_("Error on target while enabling tracepoint."));
13579}
13580
f6ac5f3d
PA
13581void
13582remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13583{
13584 struct remote_state *rs = get_remote_state ();
d248b706 13585
8d64371b 13586 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
53807e9f
TT
13587 location->owner->number,
13588 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13589 putpkt (rs->buf);
b6bb3468 13590 remote_get_noisy_reply ();
8d64371b 13591 if (rs->buf[0] == '\0')
d248b706 13592 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
8d64371b 13593 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13594 error (_("Error on target while disabling tracepoint."));
13595}
13596
f6ac5f3d
PA
13597void
13598remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13599{
13600 asection *s;
13601 bfd_size_type size;
608bcef2 13602 bfd_vma vma;
35b1e5cc 13603 int anysecs = 0;
c2fa21f1 13604 int offset = 0;
f493c217 13605 bfd *abfd = current_program_space->exec_bfd ();
35b1e5cc 13606
f493c217 13607 if (!abfd)
35b1e5cc
SS
13608 return; /* No information to give. */
13609
b6bb3468
PA
13610 struct remote_state *rs = get_remote_state ();
13611
8d64371b
TT
13612 strcpy (rs->buf.data (), "QTro");
13613 offset = strlen (rs->buf.data ());
f493c217 13614 for (s = abfd->sections; s; s = s->next)
35b1e5cc
SS
13615 {
13616 char tmp1[40], tmp2[40];
c2fa21f1 13617 int sec_length;
35b1e5cc 13618
f493c217
AM
13619 if ((s->flags & SEC_LOAD) == 0
13620 /* || (s->flags & SEC_CODE) == 0 */
13621 || (s->flags & SEC_READONLY) == 0)
35b1e5cc
SS
13622 continue;
13623
13624 anysecs = 1;
fd361982
AM
13625 vma = bfd_section_vma (s);
13626 size = bfd_section_size (s);
f493c217
AM
13627 bfd_sprintf_vma (abfd, tmp1, vma);
13628 bfd_sprintf_vma (abfd, tmp2, vma + size);
c2fa21f1 13629 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
8d64371b 13630 if (offset + sec_length + 1 > rs->buf.size ())
c2fa21f1 13631 {
ff52c073
CS
13632 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13633 != PACKET_ENABLE)
864ac8a7 13634 warning (_("\
c2fa21f1
HZ
13635Too many sections for read-only sections definition packet."));
13636 break;
13637 }
8d64371b 13638 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
bba74b36 13639 tmp1, tmp2);
c2fa21f1 13640 offset += sec_length;
35b1e5cc
SS
13641 }
13642 if (anysecs)
13643 {
b6bb3468 13644 putpkt (rs->buf);
8d64371b 13645 getpkt (&rs->buf, 0);
35b1e5cc
SS
13646 }
13647}
13648
f6ac5f3d
PA
13649void
13650remote_target::trace_start ()
35b1e5cc 13651{
b6bb3468
PA
13652 struct remote_state *rs = get_remote_state ();
13653
35b1e5cc 13654 putpkt ("QTStart");
b6bb3468 13655 remote_get_noisy_reply ();
8d64371b 13656 if (rs->buf[0] == '\0')
ad91cd99 13657 error (_("Target does not support this command."));
8d64371b
TT
13658 if (strcmp (rs->buf.data (), "OK") != 0)
13659 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13660}
13661
f6ac5f3d
PA
13662int
13663remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13664{
953b98d1 13665 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13666 char *p = NULL;
bd3eecc3 13667 enum packet_result result;
b6bb3468 13668 struct remote_state *rs = get_remote_state ();
bd3eecc3 13669
ff52c073 13670 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13671 return -1;
a744cf53 13672
7b9a15e1 13673 /* FIXME we need to get register block size some other way. */
5cd63fda 13674 trace_regblock_size
9d6eea31 13675 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 13676
049dc89b
JK
13677 putpkt ("qTStatus");
13678
a70b8144 13679 try
67f41397 13680 {
b6bb3468 13681 p = remote_get_noisy_reply ();
67f41397 13682 }
230d2906 13683 catch (const gdb_exception_error &ex)
67f41397 13684 {
598d3636
JK
13685 if (ex.error != TARGET_CLOSE_ERROR)
13686 {
13687 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13688 return -1;
13689 }
eedc3f4f 13690 throw;
67f41397 13691 }
00bf0b85 13692
ff52c073 13693 result = m_features.packet_ok (p, PACKET_qTStatus);
bd3eecc3 13694
00bf0b85 13695 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13696 if (result == PACKET_UNKNOWN)
00bf0b85 13697 return -1;
35b1e5cc 13698
00bf0b85 13699 /* We're working with a live target. */
f5911ea1 13700 ts->filename = NULL;
00bf0b85 13701
00bf0b85 13702 if (*p++ != 'T')
8d64371b 13703 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
35b1e5cc 13704
84cebc4a
YQ
13705 /* Function 'parse_trace_status' sets default value of each field of
13706 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13707 parse_trace_status (p, ts);
13708
13709 return ts->running;
35b1e5cc
SS
13710}
13711
f6ac5f3d
PA
13712void
13713remote_target::get_tracepoint_status (struct breakpoint *bp,
13714 struct uploaded_tp *utp)
f196051f
SS
13715{
13716 struct remote_state *rs = get_remote_state ();
f196051f 13717 char *reply;
f196051f 13718 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 13719 size_t size = get_remote_packet_size ();
f196051f
SS
13720
13721 if (tp)
13722 {
c1fc2657 13723 tp->hit_count = 0;
f196051f 13724 tp->traceframe_usage = 0;
b00b30b2 13725 for (bp_location &loc : tp->locations ())
f196051f
SS
13726 {
13727 /* If the tracepoint was never downloaded, don't go asking for
13728 any status. */
13729 if (tp->number_on_target == 0)
13730 continue;
8d64371b 13731 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
b00b30b2 13732 phex_nz (loc.address, 0));
f196051f 13733 putpkt (rs->buf);
b6bb3468 13734 reply = remote_get_noisy_reply ();
f196051f
SS
13735 if (reply && *reply)
13736 {
13737 if (*reply == 'V')
13738 parse_tracepoint_status (reply + 1, bp, utp);
13739 }
13740 }
13741 }
13742 else if (utp)
13743 {
13744 utp->hit_count = 0;
13745 utp->traceframe_usage = 0;
8d64371b 13746 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
bba74b36 13747 phex_nz (utp->addr, 0));
f196051f 13748 putpkt (rs->buf);
b6bb3468 13749 reply = remote_get_noisy_reply ();
f196051f
SS
13750 if (reply && *reply)
13751 {
13752 if (*reply == 'V')
13753 parse_tracepoint_status (reply + 1, bp, utp);
13754 }
13755 }
13756}
13757
f6ac5f3d
PA
13758void
13759remote_target::trace_stop ()
35b1e5cc 13760{
b6bb3468
PA
13761 struct remote_state *rs = get_remote_state ();
13762
35b1e5cc 13763 putpkt ("QTStop");
b6bb3468 13764 remote_get_noisy_reply ();
8d64371b 13765 if (rs->buf[0] == '\0')
ad91cd99 13766 error (_("Target does not support this command."));
8d64371b
TT
13767 if (strcmp (rs->buf.data (), "OK") != 0)
13768 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13769}
13770
f6ac5f3d
PA
13771int
13772remote_target::trace_find (enum trace_find_type type, int num,
13773 CORE_ADDR addr1, CORE_ADDR addr2,
13774 int *tpp)
35b1e5cc
SS
13775{
13776 struct remote_state *rs = get_remote_state ();
8d64371b 13777 char *endbuf = rs->buf.data () + get_remote_packet_size ();
35b1e5cc
SS
13778 char *p, *reply;
13779 int target_frameno = -1, target_tracept = -1;
13780
e6e4e701
PA
13781 /* Lookups other than by absolute frame number depend on the current
13782 trace selected, so make sure it is correct on the remote end
13783 first. */
13784 if (type != tfind_number)
13785 set_remote_traceframe ();
13786
8d64371b 13787 p = rs->buf.data ();
35b1e5cc
SS
13788 strcpy (p, "QTFrame:");
13789 p = strchr (p, '\0');
13790 switch (type)
13791 {
13792 case tfind_number:
bba74b36 13793 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13794 break;
13795 case tfind_pc:
bba74b36 13796 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13797 break;
13798 case tfind_tp:
bba74b36 13799 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13800 break;
13801 case tfind_range:
bba74b36
YQ
13802 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13803 phex_nz (addr2, 0));
35b1e5cc
SS
13804 break;
13805 case tfind_outside:
bba74b36
YQ
13806 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13807 phex_nz (addr2, 0));
35b1e5cc
SS
13808 break;
13809 default:
9b20d036 13810 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13811 }
13812
13813 putpkt (rs->buf);
b6bb3468 13814 reply = remote_get_noisy_reply ();
ad91cd99
PA
13815 if (*reply == '\0')
13816 error (_("Target does not support this command."));
35b1e5cc
SS
13817
13818 while (reply && *reply)
13819 switch (*reply)
13820 {
13821 case 'F':
f197e0f1
VP
13822 p = ++reply;
13823 target_frameno = (int) strtol (p, &reply, 16);
13824 if (reply == p)
13825 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13826 /* Don't update our remote traceframe number cache on failure
13827 to select a remote traceframe. */
f197e0f1
VP
13828 if (target_frameno == -1)
13829 return -1;
35b1e5cc
SS
13830 break;
13831 case 'T':
f197e0f1
VP
13832 p = ++reply;
13833 target_tracept = (int) strtol (p, &reply, 16);
13834 if (reply == p)
13835 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13836 break;
13837 case 'O': /* "OK"? */
13838 if (reply[1] == 'K' && reply[2] == '\0')
13839 reply += 2;
13840 else
13841 error (_("Bogus reply from target: %s"), reply);
13842 break;
13843 default:
13844 error (_("Bogus reply from target: %s"), reply);
13845 }
13846 if (tpp)
13847 *tpp = target_tracept;
e6e4e701 13848
262e1174 13849 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13850 return target_frameno;
13851}
13852
57810aa7 13853bool
f6ac5f3d 13854remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13855{
13856 struct remote_state *rs = get_remote_state ();
13857 char *reply;
13858 ULONGEST uval;
13859
e6e4e701
PA
13860 set_remote_traceframe ();
13861
8d64371b 13862 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13863 putpkt (rs->buf);
b6bb3468 13864 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13865 if (reply && *reply)
13866 {
13867 if (*reply == 'V')
13868 {
13869 unpack_varlen_hex (reply + 1, &uval);
13870 *val = (LONGEST) uval;
57810aa7 13871 return true;
35b1e5cc
SS
13872 }
13873 }
57810aa7 13874 return false;
35b1e5cc
SS
13875}
13876
f6ac5f3d
PA
13877int
13878remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13879{
13880 struct remote_state *rs = get_remote_state ();
13881 char *p, *reply;
13882
8d64371b 13883 p = rs->buf.data ();
00bf0b85
SS
13884 strcpy (p, "QTSave:");
13885 p += strlen (p);
8d64371b
TT
13886 if ((p - rs->buf.data ()) + strlen (filename) * 2
13887 >= get_remote_packet_size ())
00bf0b85 13888 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13889 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13890 *p++ = '\0';
13891 putpkt (rs->buf);
b6bb3468 13892 reply = remote_get_noisy_reply ();
d6c5869f 13893 if (*reply == '\0')
ad91cd99
PA
13894 error (_("Target does not support this command."));
13895 if (strcmp (reply, "OK") != 0)
13896 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13897 return 0;
13898}
13899
13900/* This is basically a memory transfer, but needs to be its own packet
13901 because we don't know how the target actually organizes its trace
13902 memory, plus we want to be able to ask for as much as possible, but
13903 not be unhappy if we don't get as much as we ask for. */
13904
f6ac5f3d
PA
13905LONGEST
13906remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13907{
13908 struct remote_state *rs = get_remote_state ();
13909 char *reply;
13910 char *p;
13911 int rslt;
13912
8d64371b 13913 p = rs->buf.data ();
00bf0b85
SS
13914 strcpy (p, "qTBuffer:");
13915 p += strlen (p);
13916 p += hexnumstr (p, offset);
13917 *p++ = ',';
13918 p += hexnumstr (p, len);
13919 *p++ = '\0';
13920
13921 putpkt (rs->buf);
b6bb3468 13922 reply = remote_get_noisy_reply ();
00bf0b85
SS
13923 if (reply && *reply)
13924 {
13925 /* 'l' by itself means we're at the end of the buffer and
13926 there is nothing more to get. */
13927 if (*reply == 'l')
13928 return 0;
13929
13930 /* Convert the reply into binary. Limit the number of bytes to
13931 convert according to our passed-in buffer size, rather than
13932 what was returned in the packet; if the target is
13933 unexpectedly generous and gives us a bigger reply than we
13934 asked for, we don't want to crash. */
b6bb3468 13935 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13936 return rslt;
13937 }
13938
13939 /* Something went wrong, flag as an error. */
13940 return -1;
13941}
13942
f6ac5f3d
PA
13943void
13944remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13945{
13946 struct remote_state *rs = get_remote_state ();
13947
ff52c073
CS
13948 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
13949 == PACKET_ENABLE)
33da3f1c 13950 {
ad91cd99
PA
13951 char *reply;
13952
8d64371b
TT
13953 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13954 "QTDisconnected:%x", val);
33da3f1c 13955 putpkt (rs->buf);
b6bb3468 13956 reply = remote_get_noisy_reply ();
ad91cd99 13957 if (*reply == '\0')
33da3f1c 13958 error (_("Target does not support this command."));
ad91cd99 13959 if (strcmp (reply, "OK") != 0)
dda83cd7 13960 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13961 }
13962 else if (val)
13963 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13964}
13965
f6ac5f3d
PA
13966int
13967remote_target::core_of_thread (ptid_t ptid)
dc146f7c 13968{
9213a6d7 13969 thread_info *info = this->find_thread (ptid);
a744cf53 13970
7aabaf9d
SM
13971 if (info != NULL && info->priv != NULL)
13972 return get_remote_thread_info (info)->core;
13973
dc146f7c
VP
13974 return -1;
13975}
13976
f6ac5f3d
PA
13977void
13978remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13979{
13980 struct remote_state *rs = get_remote_state ();
ad91cd99 13981 char *reply;
4daf5ac0 13982
8d64371b
TT
13983 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13984 "QTBuffer:circular:%x", val);
4daf5ac0 13985 putpkt (rs->buf);
b6bb3468 13986 reply = remote_get_noisy_reply ();
ad91cd99 13987 if (*reply == '\0')
4daf5ac0 13988 error (_("Target does not support this command."));
ad91cd99
PA
13989 if (strcmp (reply, "OK") != 0)
13990 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13991}
13992
f6ac5f3d
PA
13993traceframe_info_up
13994remote_target::traceframe_info ()
b3b9301e 13995{
9018be22 13996 gdb::optional<gdb::char_vector> text
328d42d8
SM
13997 = target_read_stralloc (current_inferior ()->top_target (),
13998 TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13999 NULL);
9018be22
SM
14000 if (text)
14001 return parse_traceframe_info (text->data ());
b3b9301e
PA
14002
14003 return NULL;
14004}
14005
405f8e94
SS
14006/* Handle the qTMinFTPILen packet. Returns the minimum length of
14007 instruction on which a fast tracepoint may be placed. Returns -1
14008 if the packet is not supported, and 0 if the minimum instruction
14009 length is unknown. */
14010
f6ac5f3d
PA
14011int
14012remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
14013{
14014 struct remote_state *rs = get_remote_state ();
14015 char *reply;
14016
e886a173
PA
14017 /* If we're not debugging a process yet, the IPA can't be
14018 loaded. */
55f6301a 14019 if (!target_has_execution ())
e886a173
PA
14020 return 0;
14021
14022 /* Make sure the remote is pointing at the right process. */
14023 set_general_process ();
14024
8d64371b 14025 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
405f8e94 14026 putpkt (rs->buf);
b6bb3468 14027 reply = remote_get_noisy_reply ();
405f8e94
SS
14028 if (*reply == '\0')
14029 return -1;
14030 else
14031 {
14032 ULONGEST min_insn_len;
14033
14034 unpack_varlen_hex (reply, &min_insn_len);
14035
14036 return (int) min_insn_len;
14037 }
14038}
14039
f6ac5f3d
PA
14040void
14041remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 14042{
ff52c073 14043 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
14044 {
14045 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14046 char *buf = rs->buf.data ();
14047 char *endbuf = buf + get_remote_packet_size ();
f6f899bf
HAQ
14048 enum packet_result result;
14049
14050 gdb_assert (val >= 0 || val == -1);
14051 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14052 /* Send -1 as literal "-1" to avoid host size dependency. */
14053 if (val < 0)
14054 {
14055 *buf++ = '-';
dda83cd7 14056 buf += hexnumstr (buf, (ULONGEST) -val);
f6f899bf
HAQ
14057 }
14058 else
14059 buf += hexnumstr (buf, (ULONGEST) val);
14060
14061 putpkt (rs->buf);
b6bb3468 14062 remote_get_noisy_reply ();
ff52c073 14063 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
f6f899bf
HAQ
14064
14065 if (result != PACKET_OK)
8d64371b 14066 warning (_("Bogus reply from target: %s"), rs->buf.data ());
f6f899bf
HAQ
14067 }
14068}
14069
57810aa7 14070bool
f6ac5f3d
PA
14071remote_target::set_trace_notes (const char *user, const char *notes,
14072 const char *stop_notes)
f196051f
SS
14073{
14074 struct remote_state *rs = get_remote_state ();
14075 char *reply;
8d64371b
TT
14076 char *buf = rs->buf.data ();
14077 char *endbuf = buf + get_remote_packet_size ();
f196051f
SS
14078 int nbytes;
14079
14080 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14081 if (user)
14082 {
14083 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 14084 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
14085 buf += 2 * nbytes;
14086 *buf++ = ';';
14087 }
14088 if (notes)
14089 {
14090 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 14091 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
14092 buf += 2 * nbytes;
14093 *buf++ = ';';
14094 }
14095 if (stop_notes)
14096 {
14097 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 14098 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
14099 buf += 2 * nbytes;
14100 *buf++ = ';';
14101 }
14102 /* Ensure the buffer is terminated. */
14103 *buf = '\0';
14104
14105 putpkt (rs->buf);
b6bb3468 14106 reply = remote_get_noisy_reply ();
f196051f 14107 if (*reply == '\0')
57810aa7 14108 return false;
f196051f
SS
14109
14110 if (strcmp (reply, "OK") != 0)
14111 error (_("Bogus reply from target: %s"), reply);
14112
57810aa7 14113 return true;
f196051f
SS
14114}
14115
57810aa7
PA
14116bool
14117remote_target::use_agent (bool use)
d1feda86 14118{
ff52c073 14119 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
14120 {
14121 struct remote_state *rs = get_remote_state ();
14122
14123 /* If the stub supports QAgent. */
8d64371b 14124 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
d1feda86 14125 putpkt (rs->buf);
8d64371b 14126 getpkt (&rs->buf, 0);
d1feda86 14127
8d64371b 14128 if (strcmp (rs->buf.data (), "OK") == 0)
d1feda86 14129 {
f6ac5f3d 14130 ::use_agent = use;
57810aa7 14131 return true;
d1feda86
YQ
14132 }
14133 }
14134
57810aa7 14135 return false;
d1feda86
YQ
14136}
14137
57810aa7 14138bool
f6ac5f3d 14139remote_target::can_use_agent ()
d1feda86 14140{
ff52c073 14141 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
14142}
14143
9accd112
MM
14144struct btrace_target_info
14145{
14146 /* The ptid of the traced thread. */
14147 ptid_t ptid;
f4abbc16
MM
14148
14149 /* The obtained branch trace configuration. */
14150 struct btrace_config conf;
9accd112
MM
14151};
14152
f4abbc16
MM
14153/* Reset our idea of our target's btrace configuration. */
14154
14155static void
6b8edb51 14156remote_btrace_reset (remote_state *rs)
f4abbc16 14157{
f4abbc16
MM
14158 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14159}
14160
f4abbc16
MM
14161/* Synchronize the configuration with the target. */
14162
6b8edb51
PA
14163void
14164remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 14165{
d33501a5
MM
14166 struct remote_state *rs;
14167 char *buf, *pos, *endbuf;
14168
14169 rs = get_remote_state ();
8d64371b 14170 buf = rs->buf.data ();
d33501a5
MM
14171 endbuf = buf + get_remote_packet_size ();
14172
ff52c073 14173 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
d33501a5
MM
14174 && conf->bts.size != rs->btrace_config.bts.size)
14175 {
14176 pos = buf;
ff52c073
CS
14177 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14178 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
dda83cd7 14179 conf->bts.size);
d33501a5
MM
14180
14181 putpkt (buf);
8d64371b 14182 getpkt (&rs->buf, 0);
d33501a5 14183
ff52c073
CS
14184 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14185 == PACKET_ERROR)
d33501a5
MM
14186 {
14187 if (buf[0] == 'E' && buf[1] == '.')
14188 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14189 else
14190 error (_("Failed to configure the BTS buffer size."));
14191 }
14192
14193 rs->btrace_config.bts.size = conf->bts.size;
14194 }
b20a6524 14195
ff52c073 14196 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
b20a6524
MM
14197 && conf->pt.size != rs->btrace_config.pt.size)
14198 {
14199 pos = buf;
ff52c073
CS
14200 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14201 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
dda83cd7 14202 conf->pt.size);
b20a6524
MM
14203
14204 putpkt (buf);
8d64371b 14205 getpkt (&rs->buf, 0);
b20a6524 14206
ff52c073
CS
14207 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14208 == PACKET_ERROR)
b20a6524
MM
14209 {
14210 if (buf[0] == 'E' && buf[1] == '.')
14211 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14212 else
14213 error (_("Failed to configure the trace buffer size."));
14214 }
14215
14216 rs->btrace_config.pt.size = conf->pt.size;
14217 }
f4abbc16
MM
14218}
14219
0d8cbc5f 14220/* Read TP's btrace configuration from the target and store it into CONF. */
f4abbc16
MM
14221
14222static void
0d8cbc5f 14223btrace_read_config (thread_info *tp, struct btrace_config *conf)
f4abbc16 14224{
0d8cbc5f
MM
14225 /* target_read_stralloc relies on INFERIOR_PTID. */
14226 scoped_restore_current_thread restore_thread;
14227 switch_to_thread (tp);
14228
9018be22 14229 gdb::optional<gdb::char_vector> xml
328d42d8
SM
14230 = target_read_stralloc (current_inferior ()->top_target (),
14231 TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
14232 if (xml)
14233 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
14234}
14235
c0272db5
TW
14236/* Maybe reopen target btrace. */
14237
6b8edb51
PA
14238void
14239remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
14240{
14241 struct remote_state *rs = get_remote_state ();
c0272db5 14242 int btrace_target_pushed = 0;
15766370 14243#if !defined (HAVE_LIBIPT)
c0272db5 14244 int warned = 0;
15766370 14245#endif
c0272db5 14246
aedbe3bb
CM
14247 /* Don't bother walking the entirety of the remote thread list when
14248 we know the feature isn't supported by the remote. */
ff52c073 14249 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
aedbe3bb
CM
14250 return;
14251
5b6d1e4f 14252 for (thread_info *tp : all_non_exited_threads (this))
c0272db5 14253 {
c0272db5 14254 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
0d8cbc5f 14255 btrace_read_config (tp, &rs->btrace_config);
c0272db5
TW
14256
14257 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14258 continue;
14259
14260#if !defined (HAVE_LIBIPT)
14261 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14262 {
14263 if (!warned)
14264 {
14265 warned = 1;
c4e12631
MM
14266 warning (_("Target is recording using Intel Processor Trace "
14267 "but support was disabled at compile time."));
c0272db5
TW
14268 }
14269
14270 continue;
14271 }
14272#endif /* !defined (HAVE_LIBIPT) */
14273
14274 /* Push target, once, but before anything else happens. This way our
14275 changes to the threads will be cleaned up by unpushing the target
14276 in case btrace_read_config () throws. */
14277 if (!btrace_target_pushed)
14278 {
14279 btrace_target_pushed = 1;
14280 record_btrace_push_target ();
6cb06a8c
TT
14281 gdb_printf (_("Target is recording using %s.\n"),
14282 btrace_format_string (rs->btrace_config.format));
c0272db5
TW
14283 }
14284
14285 tp->btrace.target = XCNEW (struct btrace_target_info);
14286 tp->btrace.target->ptid = tp->ptid;
14287 tp->btrace.target->conf = rs->btrace_config;
14288 }
c0272db5
TW
14289}
14290
9accd112
MM
14291/* Enable branch tracing. */
14292
f6ac5f3d 14293struct btrace_target_info *
696c0d5e
MM
14294remote_target::enable_btrace (thread_info *tp,
14295 const struct btrace_config *conf)
9accd112
MM
14296{
14297 struct btrace_target_info *tinfo = NULL;
b20a6524 14298 struct packet_config *packet = NULL;
9accd112 14299 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14300 char *buf = rs->buf.data ();
14301 char *endbuf = buf + get_remote_packet_size ();
9accd112 14302
ff52c073 14303 unsigned int which_packet;
b20a6524
MM
14304 switch (conf->format)
14305 {
14306 case BTRACE_FORMAT_BTS:
ff52c073 14307 which_packet = PACKET_Qbtrace_bts;
b20a6524 14308 break;
b20a6524 14309 case BTRACE_FORMAT_PT:
ff52c073 14310 which_packet = PACKET_Qbtrace_pt;
b20a6524 14311 break;
ff52c073
CS
14312 default:
14313 internal_error (_("Bad branch btrace format: %u."),
14314 (unsigned int) conf->format);
b20a6524
MM
14315 }
14316
ff52c073 14317 packet = &m_features.m_protocol_packets[which_packet];
b20a6524 14318 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
14319 error (_("Target does not support branch tracing."));
14320
f4abbc16
MM
14321 btrace_sync_conf (conf);
14322
696c0d5e 14323 ptid_t ptid = tp->ptid;
9accd112
MM
14324 set_general_thread (ptid);
14325
ff52c073
CS
14326 buf += xsnprintf (buf, endbuf - buf, "%s",
14327 packets_descriptions[which_packet].name);
9accd112 14328 putpkt (rs->buf);
8d64371b 14329 getpkt (&rs->buf, 0);
9accd112 14330
ff52c073 14331 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
9accd112
MM
14332 {
14333 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14334 error (_("Could not enable branch tracing for %s: %s"),
a068643d 14335 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
9accd112
MM
14336 else
14337 error (_("Could not enable branch tracing for %s."),
a068643d 14338 target_pid_to_str (ptid).c_str ());
9accd112
MM
14339 }
14340
8d749320 14341 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
14342 tinfo->ptid = ptid;
14343
f4abbc16
MM
14344 /* If we fail to read the configuration, we lose some information, but the
14345 tracing itself is not impacted. */
a70b8144 14346 try
492d29ea 14347 {
0d8cbc5f 14348 btrace_read_config (tp, &tinfo->conf);
492d29ea 14349 }
230d2906 14350 catch (const gdb_exception_error &err)
492d29ea
PA
14351 {
14352 if (err.message != NULL)
3d6e9d23 14353 warning ("%s", err.what ());
492d29ea 14354 }
f4abbc16 14355
9accd112
MM
14356 return tinfo;
14357}
14358
14359/* Disable branch tracing. */
14360
f6ac5f3d
PA
14361void
14362remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112 14363{
9accd112 14364 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14365 char *buf = rs->buf.data ();
14366 char *endbuf = buf + get_remote_packet_size ();
9accd112 14367
ff52c073 14368 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112
MM
14369 error (_("Target does not support branch tracing."));
14370
14371 set_general_thread (tinfo->ptid);
14372
ff52c073
CS
14373 buf += xsnprintf (buf, endbuf - buf, "%s",
14374 packets_descriptions[PACKET_Qbtrace_off].name);
9accd112 14375 putpkt (rs->buf);
8d64371b 14376 getpkt (&rs->buf, 0);
9accd112 14377
ff52c073 14378 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
9accd112
MM
14379 {
14380 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14381 error (_("Could not disable branch tracing for %s: %s"),
a068643d 14382 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
9accd112
MM
14383 else
14384 error (_("Could not disable branch tracing for %s."),
a068643d 14385 target_pid_to_str (tinfo->ptid).c_str ());
9accd112
MM
14386 }
14387
14388 xfree (tinfo);
14389}
14390
14391/* Teardown branch tracing. */
14392
f6ac5f3d
PA
14393void
14394remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
14395{
14396 /* We must not talk to the target during teardown. */
14397 xfree (tinfo);
14398}
14399
14400/* Read the branch trace. */
14401
f6ac5f3d
PA
14402enum btrace_error
14403remote_target::read_btrace (struct btrace_data *btrace,
14404 struct btrace_target_info *tinfo,
14405 enum btrace_read_type type)
9accd112 14406{
9accd112 14407 const char *annex;
9accd112 14408
ff52c073 14409 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
14410 error (_("Target does not support branch tracing."));
14411
14412#if !defined(HAVE_LIBEXPAT)
14413 error (_("Cannot process branch tracing result. XML parsing not supported."));
14414#endif
14415
14416 switch (type)
14417 {
864089d2 14418 case BTRACE_READ_ALL:
9accd112
MM
14419 annex = "all";
14420 break;
864089d2 14421 case BTRACE_READ_NEW:
9accd112
MM
14422 annex = "new";
14423 break;
969c39fb
MM
14424 case BTRACE_READ_DELTA:
14425 annex = "delta";
14426 break;
9accd112 14427 default:
f34652de 14428 internal_error (_("Bad branch tracing read type: %u."),
9accd112
MM
14429 (unsigned int) type);
14430 }
14431
9018be22 14432 gdb::optional<gdb::char_vector> xml
328d42d8
SM
14433 = target_read_stralloc (current_inferior ()->top_target (),
14434 TARGET_OBJECT_BTRACE, annex);
9018be22 14435 if (!xml)
969c39fb 14436 return BTRACE_ERR_UNKNOWN;
9accd112 14437
9018be22 14438 parse_xml_btrace (btrace, xml->data ());
9accd112 14439
969c39fb 14440 return BTRACE_ERR_NONE;
9accd112
MM
14441}
14442
f6ac5f3d
PA
14443const struct btrace_config *
14444remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
14445{
14446 return &tinfo->conf;
14447}
14448
57810aa7 14449bool
f6ac5f3d 14450remote_target::augmented_libraries_svr4_read ()
ced63ec0 14451{
ff52c073
CS
14452 return
14453 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14454 == PACKET_ENABLE);
ced63ec0
GB
14455}
14456
9dd130a0
TT
14457/* Implementation of to_load. */
14458
f6ac5f3d
PA
14459void
14460remote_target::load (const char *name, int from_tty)
9dd130a0
TT
14461{
14462 generic_load (name, from_tty);
14463}
14464
c78fa86a
GB
14465/* Accepts an integer PID; returns a string representing a file that
14466 can be opened on the remote side to get the symbols for the child
14467 process. Returns NULL if the operation is not supported. */
14468
0e90c441 14469const char *
f6ac5f3d 14470remote_target::pid_to_exec_file (int pid)
c78fa86a 14471{
9018be22 14472 static gdb::optional<gdb::char_vector> filename;
835205d0 14473 char *annex = NULL;
c78fa86a 14474
ff52c073 14475 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
c78fa86a
GB
14476 return NULL;
14477
5b6d1e4f 14478 inferior *inf = find_inferior_pid (this, pid);
835205d0 14479 if (inf == NULL)
f34652de 14480 internal_error (_("not currently attached to process %d"), pid);
835205d0
GB
14481
14482 if (!inf->fake_pid_p)
14483 {
14484 const int annex_size = 9;
14485
224c3ddb 14486 annex = (char *) alloca (annex_size);
835205d0
GB
14487 xsnprintf (annex, annex_size, "%x", pid);
14488 }
14489
328d42d8 14490 filename = target_read_stralloc (current_inferior ()->top_target (),
c78fa86a
GB
14491 TARGET_OBJECT_EXEC_FILE, annex);
14492
9018be22 14493 return filename ? filename->data () : nullptr;
c78fa86a
GB
14494}
14495
750ce8d1
YQ
14496/* Implement the to_can_do_single_step target_ops method. */
14497
f6ac5f3d
PA
14498int
14499remote_target::can_do_single_step ()
750ce8d1
YQ
14500{
14501 /* We can only tell whether target supports single step or not by
14502 supported s and S vCont actions if the stub supports vContSupported
14503 feature. If the stub doesn't support vContSupported feature,
14504 we have conservatively to think target doesn't supports single
14505 step. */
ff52c073 14506 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
750ce8d1
YQ
14507 {
14508 struct remote_state *rs = get_remote_state ();
14509
750ce8d1
YQ
14510 return rs->supports_vCont.s && rs->supports_vCont.S;
14511 }
14512 else
14513 return 0;
14514}
14515
3a00c802
PA
14516/* Implementation of the to_execution_direction method for the remote
14517 target. */
14518
f6ac5f3d
PA
14519enum exec_direction_kind
14520remote_target::execution_direction ()
3a00c802
PA
14521{
14522 struct remote_state *rs = get_remote_state ();
14523
14524 return rs->last_resume_exec_dir;
14525}
14526
f6327dcb
KB
14527/* Return pointer to the thread_info struct which corresponds to
14528 THREAD_HANDLE (having length HANDLE_LEN). */
14529
f6ac5f3d
PA
14530thread_info *
14531remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14532 int handle_len,
14533 inferior *inf)
f6327dcb 14534{
5b6d1e4f 14535 for (thread_info *tp : all_non_exited_threads (this))
f6327dcb 14536 {
7aabaf9d 14537 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
14538
14539 if (tp->inf == inf && priv != NULL)
dda83cd7 14540 {
7aabaf9d 14541 if (handle_len != priv->thread_handle.size ())
f6327dcb 14542 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
dda83cd7 14543 handle_len, priv->thread_handle.size ());
7aabaf9d 14544 if (memcmp (thread_handle, priv->thread_handle.data (),
dda83cd7 14545 handle_len) == 0)
f6327dcb
KB
14546 return tp;
14547 }
14548 }
14549
14550 return NULL;
14551}
14552
3d6c6204
KB
14553gdb::byte_vector
14554remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14555{
14556 remote_thread_info *priv = get_remote_thread_info (tp);
14557 return priv->thread_handle;
14558}
14559
57810aa7 14560bool
f6ac5f3d 14561remote_target::can_async_p ()
6426a772 14562{
fce6cd34
AB
14563 /* This flag should be checked in the common target.c code. */
14564 gdb_assert (target_async_permitted);
75c99385 14565
fce6cd34
AB
14566 /* We're async whenever the serial device can. */
14567 struct remote_state *rs = get_remote_state ();
5d93a237 14568 return serial_can_async_p (rs->remote_desc);
6426a772
JM
14569}
14570
57810aa7 14571bool
f6ac5f3d 14572remote_target::is_async_p ()
6426a772 14573{
23860348 14574 /* We're async whenever the serial device is. */
7054fa5b 14575 struct remote_state *rs = get_remote_state ();
5d93a237 14576 return serial_is_async_p (rs->remote_desc);
6426a772
JM
14577}
14578
2acceee2
JM
14579/* Pass the SERIAL event on and up to the client. One day this code
14580 will be able to delay notifying the client of an event until the
23860348 14581 point where an entire packet has been received. */
2acceee2 14582
2acceee2
JM
14583static serial_event_ftype remote_async_serial_handler;
14584
6426a772 14585static void
819cc324 14586remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14587{
2acceee2
JM
14588 /* Don't propogate error information up to the client. Instead let
14589 the client find out about the error by querying the target. */
b1a35af2 14590 inferior_event_handler (INF_REG_EVENT);
2acceee2
JM
14591}
14592
74531fed
PA
14593static void
14594remote_async_inferior_event_handler (gdb_client_data data)
14595{
6b36ddeb 14596 inferior_event_handler (INF_REG_EVENT);
74531fed
PA
14597}
14598
5b6d1e4f
PA
14599int
14600remote_target::async_wait_fd ()
14601{
14602 struct remote_state *rs = get_remote_state ();
14603 return rs->remote_desc->fd;
14604}
14605
f6ac5f3d 14606void
4a570176 14607remote_target::async (bool enable)
2acceee2 14608{
5d93a237
TT
14609 struct remote_state *rs = get_remote_state ();
14610
6a3753b3 14611 if (enable)
2acceee2 14612 {
88b496c3 14613 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14614
14615 /* If there are pending events in the stop reply queue tell the
14616 event loop to process them. */
953edf2b 14617 if (!rs->stop_reply_queue.empty ())
6b8edb51 14618 mark_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14619 /* For simplicity, below we clear the pending events token
14620 without remembering whether it is marked, so here we always
14621 mark it. If there's actually no pending notification to
14622 process, this ends up being a no-op (other than a spurious
14623 event-loop wakeup). */
14624 if (target_is_non_stop_p ())
14625 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14626 }
14627 else
b7d2e916
PA
14628 {
14629 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14630 /* If the core is disabling async, it doesn't want to be
14631 disturbed with target events. Clear all async event sources
14632 too. */
6b8edb51 14633 clear_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14634 if (target_is_non_stop_p ())
14635 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14636 }
6426a772
JM
14637}
14638
65706a29
PA
14639/* Implementation of the to_thread_events method. */
14640
f6ac5f3d
PA
14641void
14642remote_target::thread_events (int enable)
65706a29
PA
14643{
14644 struct remote_state *rs = get_remote_state ();
14645 size_t size = get_remote_packet_size ();
65706a29 14646
ff52c073 14647 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
65706a29
PA
14648 return;
14649
8d64371b 14650 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
65706a29 14651 putpkt (rs->buf);
8d64371b 14652 getpkt (&rs->buf, 0);
65706a29 14653
ff52c073 14654 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
65706a29
PA
14655 {
14656 case PACKET_OK:
8d64371b
TT
14657 if (strcmp (rs->buf.data (), "OK") != 0)
14658 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
65706a29
PA
14659 break;
14660 case PACKET_ERROR:
8d64371b 14661 warning (_("Remote failure reply: %s"), rs->buf.data ());
65706a29
PA
14662 break;
14663 case PACKET_UNKNOWN:
14664 break;
14665 }
14666}
14667
d471ea57 14668static void
981a3fb3 14669show_remote_cmd (const char *args, int from_tty)
d471ea57 14670{
37a105a1 14671 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14672 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14673 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14674 struct ui_out *uiout = current_uiout;
37a105a1 14675
2e783024 14676 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14677 for (; list != NULL; list = list->next)
14678 if (strcmp (list->name, "Z-packet") == 0)
14679 continue;
427c3a89
DJ
14680 else if (list->type == not_set_cmd)
14681 /* Alias commands are exactly like the original, except they
14682 don't have the normal type. */
14683 continue;
14684 else
37a105a1 14685 {
2e783024 14686 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14687
112e8700
SM
14688 uiout->field_string ("name", list->name);
14689 uiout->text (": ");
427c3a89 14690 if (list->type == show_cmd)
f5c4fcd9 14691 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14692 else
14693 cmd_func (list, NULL, from_tty);
37a105a1 14694 }
d471ea57 14695}
5a2468f5 14696
0f71a2f6 14697
23860348 14698/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
14699static void
14700remote_new_objfile (struct objfile *objfile)
14701{
06c7226e
SM
14702 /* The objfile change happened in that program space. */
14703 program_space *pspace = current_program_space;
5d93a237 14704
06c7226e
SM
14705 /* The affected program space is possibly shared by multiple inferiors.
14706 Consider sending a qSymbol packet for each of the inferiors using that
14707 program space. */
14708 for (inferior *inf : all_inferiors ())
14709 {
14710 if (inf->pspace != pspace)
14711 continue;
122373f7 14712
06c7226e
SM
14713 /* Check whether the inferior's process target is a remote target. */
14714 remote_target *remote = as_remote_target (inf->process_target ());
14715 if (remote == nullptr)
14716 continue;
14717
14718 /* When we are attaching or handling a fork child and the shared library
14719 subsystem reads the list of loaded libraries, we receive new objfile
14720 events in between each found library. The libraries are read in an
14721 undefined order, so if we gave the remote side a chance to look up
14722 symbols between each objfile, we might give it an inconsistent picture
14723 of the inferior. It could appear that a library A appears loaded but
14724 a library B does not, even though library A requires library B. That
14725 would present a state that couldn't normally exist in the inferior.
14726
14727 So, skip these events, we'll give the remote a chance to look up
14728 symbols once all the loaded libraries and their symbols are known to
14729 GDB. */
14730 if (inf->in_initial_library_scan)
14731 continue;
14732
14733 if (!remote->has_execution (inf))
14734 continue;
14735
14736 /* Need to switch to a specific thread, because remote_check_symbols will
287de656 14737 set the general thread using INFERIOR_PTID.
122373f7 14738
06c7226e
SM
14739 It's possible to have inferiors with no thread here, because we are
14740 called very early in the connection process, while the inferior is
14741 being set up, before threads are added. Just skip it, start_remote_1
14742 also calls remote_check_symbols when it's done setting things up. */
14743 thread_info *thread = any_thread_of_inferior (inf);
14744 if (thread != nullptr)
14745 {
14746 scoped_restore_current_thread restore_thread;
14747 switch_to_thread (thread);
14748 remote->remote_check_symbols ();
14749 }
14750 }
dc8acb97
MS
14751}
14752
00bf0b85
SS
14753/* Pull all the tracepoints defined on the target and create local
14754 data structures representing them. We don't want to create real
14755 tracepoints yet, we don't want to mess up the user's existing
14756 collection. */
14757
f6ac5f3d
PA
14758int
14759remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 14760{
00bf0b85
SS
14761 struct remote_state *rs = get_remote_state ();
14762 char *p;
d5551862 14763
00bf0b85
SS
14764 /* Ask for a first packet of tracepoint definition. */
14765 putpkt ("qTfP");
8d64371b
TT
14766 getpkt (&rs->buf, 0);
14767 p = rs->buf.data ();
00bf0b85 14768 while (*p && *p != 'l')
d5551862 14769 {
00bf0b85
SS
14770 parse_tracepoint_definition (p, utpp);
14771 /* Ask for another packet of tracepoint definition. */
14772 putpkt ("qTsP");
8d64371b
TT
14773 getpkt (&rs->buf, 0);
14774 p = rs->buf.data ();
d5551862 14775 }
00bf0b85 14776 return 0;
d5551862
SS
14777}
14778
f6ac5f3d
PA
14779int
14780remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 14781{
00bf0b85 14782 struct remote_state *rs = get_remote_state ();
d5551862 14783 char *p;
d5551862 14784
00bf0b85
SS
14785 /* Ask for a first packet of variable definition. */
14786 putpkt ("qTfV");
8d64371b
TT
14787 getpkt (&rs->buf, 0);
14788 p = rs->buf.data ();
00bf0b85 14789 while (*p && *p != 'l')
d5551862 14790 {
00bf0b85
SS
14791 parse_tsv_definition (p, utsvp);
14792 /* Ask for another packet of variable definition. */
14793 putpkt ("qTsV");
8d64371b
TT
14794 getpkt (&rs->buf, 0);
14795 p = rs->buf.data ();
d5551862 14796 }
00bf0b85 14797 return 0;
d5551862
SS
14798}
14799
c1e36e3e
PA
14800/* The "set/show range-stepping" show hook. */
14801
14802static void
14803show_range_stepping (struct ui_file *file, int from_tty,
14804 struct cmd_list_element *c,
14805 const char *value)
14806{
6cb06a8c
TT
14807 gdb_printf (file,
14808 _("Debugger's willingness to use range stepping "
14809 "is %s.\n"), value);
c1e36e3e
PA
14810}
14811
6b8edb51
PA
14812/* Return true if the vCont;r action is supported by the remote
14813 stub. */
14814
14815bool
14816remote_target::vcont_r_supported ()
14817{
ff52c073 14818 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
6b8edb51
PA
14819 && get_remote_state ()->supports_vCont.r);
14820}
14821
c1e36e3e
PA
14822/* The "set/show range-stepping" set hook. */
14823
14824static void
eb4c3f4a 14825set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
14826 struct cmd_list_element *c)
14827{
6b8edb51
PA
14828 /* When enabling, check whether range stepping is actually supported
14829 by the target, and warn if not. */
c1e36e3e
PA
14830 if (use_range_stepping)
14831 {
6b8edb51
PA
14832 remote_target *remote = get_current_remote_target ();
14833 if (remote == NULL
14834 || !remote->vcont_r_supported ())
14835 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
14836 }
14837}
14838
baf2b57f
SM
14839static void
14840show_remote_debug (struct ui_file *file, int from_tty,
14841 struct cmd_list_element *c, const char *value)
14842{
6cb06a8c
TT
14843 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14844 value);
baf2b57f
SM
14845}
14846
14847static void
14848show_remote_timeout (struct ui_file *file, int from_tty,
14849 struct cmd_list_element *c, const char *value)
14850{
6cb06a8c
TT
14851 gdb_printf (file,
14852 _("Timeout limit to wait for target to respond is %s.\n"),
14853 value);
baf2b57f
SM
14854}
14855
dbe692af
LM
14856/* Implement the "supports_memory_tagging" target_ops method. */
14857
14858bool
14859remote_target::supports_memory_tagging ()
14860{
ff52c073 14861 return m_features.remote_memory_tagging_p ();
2c2e7f87
LM
14862}
14863
14864/* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14865
14866static void
14867create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14868 size_t len, int type)
14869{
14870 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14871
14872 std::string request = string_printf ("qMemTags:%s,%s:%s",
14873 phex_nz (address, addr_size),
14874 phex_nz (len, sizeof (len)),
14875 phex_nz (type, sizeof (type)));
14876
14877 strcpy (packet.data (), request.c_str ());
14878}
14879
14880/* Parse the qMemTags packet reply into TAGS.
14881
14882 Return true if successful, false otherwise. */
14883
14884static bool
14885parse_fetch_memtags_reply (const gdb::char_vector &reply,
14886 gdb::byte_vector &tags)
14887{
14888 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14889 return false;
14890
14891 /* Copy the tag data. */
14892 tags = hex2bin (reply.data () + 1);
14893
14894 return true;
14895}
14896
14897/* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14898
14899static void
14900create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14901 size_t len, int type,
14902 const gdb::byte_vector &tags)
14903{
14904 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14905
14906 /* Put together the main packet, address and length. */
14907 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14908 phex_nz (address, addr_size),
14909 phex_nz (len, sizeof (len)),
14910 phex_nz (type, sizeof (type)));
14911 request += bin2hex (tags.data (), tags.size ());
14912
14913 /* Check if we have exceeded the maximum packet size. */
14914 if (packet.size () < request.length ())
14915 error (_("Contents too big for packet QMemTags."));
14916
14917 strcpy (packet.data (), request.c_str ());
dbe692af
LM
14918}
14919
14920/* Implement the "fetch_memtags" target_ops method. */
14921
14922bool
14923remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14924 gdb::byte_vector &tags, int type)
14925{
2c2e7f87 14926 /* Make sure the qMemTags packet is supported. */
ff52c073 14927 if (!m_features.remote_memory_tagging_p ())
2c2e7f87
LM
14928 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14929
14930 struct remote_state *rs = get_remote_state ();
14931
14932 create_fetch_memtags_request (rs->buf, address, len, type);
14933
14934 putpkt (rs->buf);
14935 getpkt (&rs->buf, 0);
14936
14937 return parse_fetch_memtags_reply (rs->buf, tags);
dbe692af
LM
14938}
14939
14940/* Implement the "store_memtags" target_ops method. */
14941
14942bool
14943remote_target::store_memtags (CORE_ADDR address, size_t len,
14944 const gdb::byte_vector &tags, int type)
14945{
2c2e7f87 14946 /* Make sure the QMemTags packet is supported. */
ff52c073 14947 if (!m_features.remote_memory_tagging_p ())
2c2e7f87
LM
14948 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14949
14950 struct remote_state *rs = get_remote_state ();
14951
14952 create_store_memtags_request (rs->buf, address, len, type, tags);
14953
14954 putpkt (rs->buf);
14955 getpkt (&rs->buf, 0);
14956
14957 /* Verify if the request was successful. */
14958 return packet_check_result (rs->buf.data ()) == PACKET_OK;
dbe692af
LM
14959}
14960
c39ebbf4
TV
14961/* Return true if remote target T is non-stop. */
14962
14963bool
14964remote_target_is_non_stop_p (remote_target *t)
14965{
14966 scoped_restore_current_thread restore_thread;
14967 switch_to_target_no_thread (t);
14968
14969 return target_is_non_stop_p ();
14970}
14971
754487e2
LM
14972#if GDB_SELF_TEST
14973
14974namespace selftests {
14975
14976static void
14977test_memory_tagging_functions ()
14978{
14979 remote_target remote;
14980
14981 struct packet_config *config
ff52c073 14982 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
754487e2
LM
14983
14984 scoped_restore restore_memtag_support_
14985 = make_scoped_restore (&config->support);
14986
14987 /* Test memory tagging packet support. */
14988 config->support = PACKET_SUPPORT_UNKNOWN;
14989 SELF_CHECK (remote.supports_memory_tagging () == false);
14990 config->support = PACKET_DISABLE;
14991 SELF_CHECK (remote.supports_memory_tagging () == false);
14992 config->support = PACKET_ENABLE;
14993 SELF_CHECK (remote.supports_memory_tagging () == true);
14994
14995 /* Setup testing. */
14996 gdb::char_vector packet;
14997 gdb::byte_vector tags, bv;
14998 std::string expected, reply;
14999 packet.resize (32000);
15000
15001 /* Test creating a qMemTags request. */
15002
15003 expected = "qMemTags:0,0:0";
15004 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15005 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15006
15007 expected = "qMemTags:deadbeef,10:1";
15008 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15009 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15010
15011 /* Test parsing a qMemTags reply. */
15012
15013 /* Error reply, tags vector unmodified. */
15014 reply = "E00";
15015 strcpy (packet.data (), reply.c_str ());
15016 tags.resize (0);
15017 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15018 SELF_CHECK (tags.size () == 0);
15019
15020 /* Valid reply, tags vector updated. */
15021 tags.resize (0);
15022 bv.resize (0);
15023
15024 for (int i = 0; i < 5; i++)
15025 bv.push_back (i);
15026
15027 reply = "m" + bin2hex (bv.data (), bv.size ());
15028 strcpy (packet.data (), reply.c_str ());
15029
15030 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15031 SELF_CHECK (tags.size () == 5);
15032
15033 for (int i = 0; i < 5; i++)
15034 SELF_CHECK (tags[i] == i);
15035
15036 /* Test creating a QMemTags request. */
15037
15038 /* Empty tag data. */
15039 tags.resize (0);
15040 expected = "QMemTags:0,0:0:";
15041 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15042 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15043 expected.length ()) == 0);
15044
15045 /* Non-empty tag data. */
15046 tags.resize (0);
15047 for (int i = 0; i < 5; i++)
15048 tags.push_back (i);
15049 expected = "QMemTags:deadbeef,ff:1:0001020304";
15050 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15051 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15052 expected.length ()) == 0);
15053}
15054
15055} // namespace selftests
15056#endif /* GDB_SELF_TEST */
15057
6c265988 15058void _initialize_remote ();
c906108c 15059void
6c265988 15060_initialize_remote ()
c906108c 15061{
d9f719f1
PA
15062 add_target (remote_target_info, remote_target::open);
15063 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 15064
dc8acb97 15065 /* Hook into new objfile notification. */
c90e7d63 15066 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
dc8acb97 15067
c906108c
SS
15068#if 0
15069 init_remote_threadtests ();
15070#endif
15071
23860348 15072 /* set/show remote ... */
d471ea57 15073
0743fc83 15074 add_basic_prefix_cmd ("remote", class_maintenance, _("\
590042fc 15075Remote protocol specific variables.\n\
5a2468f5 15076Configure various remote-protocol specific variables such as\n\
590042fc 15077the packets being used."),
2f822da5 15078 &remote_set_cmdlist,
0743fc83 15079 0 /* allow-unknown */, &setlist);
1bedd215 15080 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
590042fc 15081Remote protocol specific variables.\n\
5a2468f5 15082Configure various remote-protocol specific variables such as\n\
590042fc 15083the packets being used."),
2f822da5 15084 &remote_show_cmdlist,
23860348 15085 0 /* allow-unknown */, &showlist);
5a2468f5 15086
1a966eab
AC
15087 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15088Compare section data on target to the exec file.\n\
95cf3b38
DT
15089Argument is a single section name (default: all loaded sections).\n\
15090To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
15091 &cmdlist);
15092
e5b176f2 15093 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
1a966eab 15094Send an arbitrary packet to a remote target.\n\
c906108c
SS
15095 maintenance packet TEXT\n\
15096If GDB is talking to an inferior via the GDB serial protocol, then\n\
15097this command sends the string TEXT to the inferior, and displays the\n\
15098response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 15099terminating `#' character and checksum."),
c906108c
SS
15100 &maintenancelist);
15101
9f260536
SM
15102 set_show_commands remotebreak_cmds
15103 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7915a72c
AC
15104Set whether to send break if interrupted."), _("\
15105Show whether to send break if interrupted."), _("\
15106If set, a break, instead of a cntrl-c, is sent to the remote target."),
9f260536
SM
15107 set_remotebreak, show_remotebreak,
15108 &setlist, &showlist);
15109 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15110 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
9a7071a8
JB
15111
15112 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
15113 interrupt_sequence_modes, &interrupt_sequence_mode,
15114 _("\
9a7071a8
JB
15115Set interrupt sequence to remote target."), _("\
15116Show interrupt sequence to remote target."), _("\
15117Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15118 NULL, show_interrupt_sequence,
15119 &remote_set_cmdlist,
15120 &remote_show_cmdlist);
15121
15122 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15123 &interrupt_on_connect, _("\
590042fc
PW
15124Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15125Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
9a7071a8
JB
15126If set, interrupt sequence is sent to remote target."),
15127 NULL, NULL,
15128 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 15129
23860348 15130 /* Install commands for configuring memory read/write packets. */
11cf8741 15131
1a966eab
AC
15132 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15133Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 15134 &setlist);
1a966eab
AC
15135 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15136Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
15137 &showlist);
15138 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
15139 set_memory_write_packet_size, _("\
15140Set the maximum number of bytes per memory-write packet.\n\
15141Specify the number of bytes in a packet or 0 (zero) for the\n\
15142default packet size. The actual limit is further reduced\n\
fe4c3ca0
CS
15143dependent on the target. Specify \"fixed\" to disable the\n\
15144further restriction and \"limit\" to enable that restriction."),
11cf8741
JM
15145 &remote_set_cmdlist);
15146 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
15147 set_memory_read_packet_size, _("\
15148Set the maximum number of bytes per memory-read packet.\n\
15149Specify the number of bytes in a packet or 0 (zero) for the\n\
15150default packet size. The actual limit is further reduced\n\
fe4c3ca0
CS
15151dependent on the target. Specify \"fixed\" to disable the\n\
15152further restriction and \"limit\" to enable that restriction."),
11cf8741
JM
15153 &remote_set_cmdlist);
15154 add_cmd ("memory-write-packet-size", no_class,
15155 show_memory_write_packet_size,
1a966eab 15156 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
15157 &remote_show_cmdlist);
15158 add_cmd ("memory-read-packet-size", no_class,
15159 show_memory_read_packet_size,
1a966eab 15160 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 15161 &remote_show_cmdlist);
c906108c 15162
055303e2 15163 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
15164 &remote_hw_watchpoint_limit, _("\
15165Set the maximum number of target hardware watchpoints."), _("\
15166Show the maximum number of target hardware watchpoints."), _("\
055303e2
AB
15167Specify \"unlimited\" for unlimited hardware watchpoints."),
15168 NULL, show_hardware_watchpoint_limit,
15169 &remote_set_cmdlist,
15170 &remote_show_cmdlist);
15171 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15172 no_class,
480a3f21
PW
15173 &remote_hw_watchpoint_length_limit, _("\
15174Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15175Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
055303e2
AB
15176Specify \"unlimited\" to allow watchpoints of unlimited size."),
15177 NULL, show_hardware_watchpoint_length_limit,
480a3f21 15178 &remote_set_cmdlist, &remote_show_cmdlist);
055303e2 15179 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
15180 &remote_hw_breakpoint_limit, _("\
15181Set the maximum number of target hardware breakpoints."), _("\
15182Show the maximum number of target hardware breakpoints."), _("\
055303e2
AB
15183Specify \"unlimited\" for unlimited hardware breakpoints."),
15184 NULL, show_hardware_breakpoint_limit,
b3f42336 15185 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 15186
1b493192
PA
15187 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15188 &remote_address_size, _("\
4d28ad1e
AC
15189Set the maximum size of the address (in bits) in a memory packet."), _("\
15190Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
15191 NULL,
15192 NULL, /* FIXME: i18n: */
15193 &setlist, &showlist);
c906108c 15194
ca4f7f8b
PA
15195 init_all_packet_configs ();
15196
ff52c073 15197 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
0f71a2f6 15198
ff52c073 15199 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
506fb367 15200
ff52c073
CS
15201 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15202 0);
89be2091 15203
ff52c073
CS
15204 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15205 "catch-syscalls", 0);
82075af2 15206
ff52c073
CS
15207 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15208 "program-signals", 0);
9b224c5e 15209
ff52c073
CS
15210 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15211 "set-working-dir", 0);
bc3b087d 15212
ff52c073
CS
15213 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15214 "startup-with-shell", 0);
aefd8b33 15215
ff52c073
CS
15216 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15217 "environment-hex-encoded", 0);
0a2dde4a 15218
ff52c073
CS
15219 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15220 "environment-reset", 0);
0a2dde4a 15221
ff52c073
CS
15222 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15223 "environment-unset", 0);
0a2dde4a 15224
ff52c073 15225 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
dc8acb97 15226
ff52c073 15227 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
d471ea57 15228
ff52c073 15229 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
b96ec7ac 15230
ff52c073 15231 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
d471ea57 15232
ff52c073 15233 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
d471ea57 15234
ff52c073 15235 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
d471ea57 15236
ff52c073 15237 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
d471ea57 15238
ff52c073 15239 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
d471ea57 15240
ff52c073
CS
15241 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15242 "read-aux-vector", 0);
802188a7 15243
ff52c073
CS
15244 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15245 "pid-to-exec-file", 0);
c78fa86a 15246
ff52c073 15247 add_packet_config_cmd (PACKET_qXfer_features,
23181151
DJ
15248 "qXfer:features:read", "target-features", 0);
15249
ff52c073
CS
15250 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15251 "library-info", 0);
cfa9d6d9 15252
ff52c073 15253 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
2268b414
JK
15254 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15255
ff52c073
CS
15256 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15257 "memory-map", 0);
fd79ecee 15258
ff52c073 15259 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
07e059b5 15260
ff52c073
CS
15261 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15262 0);
dc146f7c 15263
ff52c073
CS
15264 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15265 "read-siginfo-object", 0);
4aa995e1 15266
ff52c073
CS
15267 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15268 "write-siginfo-object", 0);
4aa995e1 15269
ff52c073
CS
15270 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15271 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 15272
ff52c073
CS
15273 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15274 "unwind-info-block", 0);
169081d0 15275
ff52c073
CS
15276 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15277 "get-thread-local-storage-address", 0);
38691318 15278
ff52c073
CS
15279 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15280 "get-thread-information-block-address", 0);
711e434b 15281
ff52c073 15282 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
40ab02ce 15283
ff52c073 15284 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
40ab02ce 15285
ff52c073
CS
15286 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15287 0);
be2a5f71 15288
ff52c073
CS
15289 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15290 "search-memory", 0);
08388c79 15291
ff52c073 15292 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
bd3eecc3 15293
ff52c073 15294 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15a201c8 15295
ff52c073 15296 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
a6b151f1 15297
ff52c073 15298 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
a6b151f1 15299
ff52c073
CS
15300 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15301 0);
a6b151f1 15302
ff52c073 15303 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
a6b151f1 15304
ff52c073
CS
15305 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15306 0);
a6b151f1 15307
ff52c073
CS
15308 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15309 "hostio-readlink", 0);
b9e7b9c3 15310
ff52c073 15311 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
0a93529c 15312
ff52c073 15313 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
2d717e4f 15314
ff52c073 15315 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
2d717e4f 15316
ff52c073 15317 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
a6f3e723 15318
ff52c073 15319 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
82f73884 15320
ff52c073 15321 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
0b16c5cf 15322
ff52c073
CS
15323 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15324 "ConditionalTracepoints", "conditional-tracepoints",
15325 0);
3788aec7 15326
ff52c073
CS
15327 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15328 "ConditionalBreakpoints", "conditional-breakpoints",
15329 0);
3788aec7 15330
ff52c073 15331 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
d3ce09f5
SS
15332 "breakpoint-commands", 0);
15333
ff52c073
CS
15334 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15335 "fast-tracepoints", 0);
782b2b07 15336
ff52c073
CS
15337 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15338 "TracepointSource", 0);
409873ef 15339
ff52c073 15340 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
d914c394 15341
ff52c073
CS
15342 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15343 "static-tracepoints", 0);
0fb4aa4b 15344
ff52c073
CS
15345 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15346 "install-in-trace", 0);
1e4d1764 15347
ff52c073 15348 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
dda83cd7 15349 "qXfer:statictrace:read", "read-sdata-object", 0);
0fb4aa4b 15350
ff52c073
CS
15351 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15352 "read-fdpic-loadmap", 0);
78d85199 15353
ff52c073
CS
15354 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15355 "disable-randomization", 0);
03583c20 15356
ff52c073 15357 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
d1feda86 15358
ff52c073
CS
15359 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15360 "trace-buffer-size", 0);
f6f899bf 15361
ff52c073
CS
15362 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15363 0);
9accd112 15364
ff52c073
CS
15365 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15366 0);
b20a6524 15367
ff52c073
CS
15368 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15369 0);
9accd112 15370
ff52c073 15371 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
9accd112 15372
ff52c073
CS
15373 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15374 "read-btrace-conf", 0);
f4abbc16 15375
ff52c073
CS
15376 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15377 "btrace-conf-bts-size", 0);
d33501a5 15378
ff52c073
CS
15379 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15380 "multiprocess-feature", 0);
73b8c1fd 15381
ff52c073
CS
15382 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15383 "swbreak-feature", 0);
f7e6eed5 15384
ff52c073
CS
15385 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15386 "hwbreak-feature", 0);
f7e6eed5 15387
ff52c073
CS
15388 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15389 "fork-event-feature", 0);
89245bc0 15390
ff52c073
CS
15391 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15392 "vfork-event-feature", 0);
89245bc0 15393
ff52c073
CS
15394 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15395 "btrace-conf-pt-size", 0);
b20a6524 15396
ff52c073
CS
15397 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15398 "verbose-resume-supported", 0);
750ce8d1 15399
ff52c073
CS
15400 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15401 "exec-event-feature", 0);
94585166 15402
ff52c073 15403 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
de979965 15404
ff52c073
CS
15405 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15406 0);
65706a29 15407
ff52c073
CS
15408 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15409 "no-resumed-stop-reply", 0);
f2faf941 15410
ff52c073 15411 add_packet_config_cmd (PACKET_memory_tagging_feature,
2c2e7f87
LM
15412 "memory-tagging-feature", "memory-tagging-feature", 0);
15413
0b736949
DB
15414 /* Assert that we've registered "set remote foo-packet" commands
15415 for all packet configs. */
ca4f7f8b
PA
15416 {
15417 int i;
15418
15419 for (i = 0; i < PACKET_MAX; i++)
15420 {
15421 /* Ideally all configs would have a command associated. Some
15422 still don't though. */
15423 int excepted;
15424
15425 switch (i)
15426 {
15427 case PACKET_QNonStop:
ca4f7f8b
PA
15428 case PACKET_EnableDisableTracepoints_feature:
15429 case PACKET_tracenz_feature:
15430 case PACKET_DisconnectedTracing_feature:
15431 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
15432 case PACKET_qCRC:
15433 /* Additions to this list need to be well justified:
15434 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
15435 excepted = 1;
15436 break;
15437 default:
15438 excepted = 0;
15439 break;
15440 }
15441
15442 /* This catches both forgetting to add a config command, and
15443 forgetting to remove a packet from the exception list. */
ff52c073 15444 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
ca4f7f8b
PA
15445 }
15446 }
15447
37a105a1
DJ
15448 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15449 Z sub-packet has its own set and show commands, but users may
15450 have sets to this variable in their .gdbinit files (or in their
15451 documentation). */
e9e68a56 15452 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c 15453 &remote_Z_packet_detect, _("\
590042fc
PW
15454Set use of remote protocol `Z' packets."), _("\
15455Show use of remote protocol `Z' packets."), _("\
3b64bf98 15456When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 15457packets."),
e9e68a56 15458 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
15459 show_remote_protocol_Z_packet_cmd,
15460 /* FIXME: i18n: Use of remote protocol
15461 `Z' packets is %s. */
e9e68a56 15462 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 15463
0743fc83 15464 add_basic_prefix_cmd ("remote", class_files, _("\
590042fc 15465Manipulate files on the remote system.\n\
a6b151f1 15466Transfer files to and from the remote target system."),
2f822da5 15467 &remote_cmdlist,
0743fc83 15468 0 /* allow-unknown */, &cmdlist);
a6b151f1
DJ
15469
15470 add_cmd ("put", class_files, remote_put_command,
15471 _("Copy a local file to the remote system."),
15472 &remote_cmdlist);
15473
15474 add_cmd ("get", class_files, remote_get_command,
15475 _("Copy a remote file to the local system."),
15476 &remote_cmdlist);
15477
15478 add_cmd ("delete", class_files, remote_delete_command,
15479 _("Delete a remote file."),
15480 &remote_cmdlist);
15481
2d717e4f 15482 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 15483 &remote_exec_file_var, _("\
590042fc
PW
15484Set the remote pathname for \"run\"."), _("\
15485Show the remote pathname for \"run\"."), NULL,
94585166
DB
15486 set_remote_exec_file,
15487 show_remote_exec_file,
15488 &remote_set_cmdlist,
15489 &remote_show_cmdlist);
2d717e4f 15490
c1e36e3e
PA
15491 add_setshow_boolean_cmd ("range-stepping", class_run,
15492 &use_range_stepping, _("\
15493Enable or disable range stepping."), _("\
15494Show whether target-assisted range stepping is enabled."), _("\
15495If on, and the target supports it, when stepping a source line, GDB\n\
15496tells the target to step the corresponding range of addresses itself instead\n\
15497of issuing multiple single-steps. This speeds up source level\n\
15498stepping. If off, GDB always issues single-steps, even if range\n\
15499stepping is supported by the target. The default is on."),
15500 set_range_stepping,
15501 show_range_stepping,
15502 &setlist,
15503 &showlist);
15504
ed2b7c17
TT
15505 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15506Set watchdog timer."), _("\
15507Show watchdog timer."), _("\
15508When non-zero, this timeout is used instead of waiting forever for a target\n\
15509to finish a low-level step or continue operation. If the specified amount\n\
15510of time passes without a response from the target, an error occurs."),
15511 NULL,
15512 show_watchdog,
15513 &setlist, &showlist);
15514
6cc8564b
LM
15515 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15516 &remote_packet_max_chars, _("\
15517Set the maximum number of characters to display for each remote packet."), _("\
15518Show the maximum number of characters to display for each remote packet."), _("\
15519Specify \"unlimited\" to display all the characters."),
15520 NULL, show_remote_packet_max_chars,
15521 &setdebuglist, &showdebuglist);
15522
02349803
SM
15523 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15524 _("Set debugging of remote protocol."),
15525 _("Show debugging of remote protocol."),
15526 _("\
baf2b57f
SM
15527When enabled, each packet sent or received with the remote target\n\
15528is displayed."),
02349803
SM
15529 NULL,
15530 show_remote_debug,
15531 &setdebuglist, &showdebuglist);
baf2b57f
SM
15532
15533 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15534 &remote_timeout, _("\
15535Set timeout limit to wait for target to respond."), _("\
15536Show timeout limit to wait for target to respond."), _("\
15537This value is used to set the time limit for gdb to wait for a response\n\
15538from the target."),
15539 NULL,
15540 show_remote_timeout,
15541 &setlist, &showlist);
15542
449092f6 15543 /* Eventually initialize fileio. See fileio.c */
3f4d92eb 15544 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
754487e2
LM
15545
15546#if GDB_SELF_TEST
15547 selftests::register_test ("remote_memory_tagging",
15548 selftests::test_memory_tagging_functions);
15549#endif
c906108c 15550}