]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
gdb: remove target_section_table typedef
[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. */
99d9c3b9 372 /* long size in bytes; == register_size (arch, regnum);
3c69da40 373 at present. */
99d9c3b9 374 /* char *name; == gdbarch_register_name (arch, regnum);
3c69da40
PA
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
92b98b37
SM
416 void create_async_event_handler ()
417 {
418 gdb_assert (m_async_event_handler_token == nullptr);
419 m_async_event_handler_token
420 = ::create_async_event_handler ([] (gdb_client_data data)
421 {
422 inferior_event_handler (INF_REG_EVENT);
423 },
424 nullptr, "remote");
425 }
426
427 void mark_async_event_handler ()
635b2dd9
SM
428 {
429 gdb_assert (this->is_async_p ());
430 ::mark_async_event_handler (m_async_event_handler_token);
431 }
92b98b37
SM
432
433 void clear_async_event_handler ()
434 { ::clear_async_event_handler (m_async_event_handler_token); }
435
436 bool async_event_handler_marked () const
437 { return ::async_event_handler_marked (m_async_event_handler_token); }
438
439 void delete_async_event_handler ()
440 {
441 if (m_async_event_handler_token != nullptr)
442 ::delete_async_event_handler (&m_async_event_handler_token);
443 }
444
e84ffe7b
SM
445 bool is_async_p () const
446 {
447 /* We're async whenever the serial device is. */
448 gdb_assert (this->remote_desc != nullptr);
449 return serial_is_async_p (this->remote_desc);
450 }
451
452 bool can_async_p () const
453 {
454 /* We can async whenever the serial device can. */
455 gdb_assert (this->remote_desc != nullptr);
456 return serial_can_async_p (this->remote_desc);
457 }
458
3c69da40
PA
459public: /* data */
460
461 /* A buffer to use for incoming packets, and its current size. The
462 buffer is grown dynamically for larger incoming packets.
463 Outgoing packets may also be constructed in this buffer.
8d64371b 464 The size of the buffer is always at least REMOTE_PACKET_SIZE;
3c69da40
PA
465 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
466 packets. */
8d64371b 467 gdb::char_vector buf;
3c69da40
PA
468
469 /* True if we're going through initial connection setup (finding out
470 about the remote side's threads, relocating symbols, etc.). */
471 bool starting_up = false;
472
473 /* If we negotiated packet size explicitly (and thus can bypass
474 heuristics for the largest packet size that will not overflow
475 a buffer in the stub), this will be set to that packet size.
476 Otherwise zero, meaning to use the guessed size. */
477 long explicit_packet_size = 0;
478
3c69da40
PA
479 /* True, if in no ack mode. That is, neither GDB nor the stub will
480 expect acks from each other. The connection is assumed to be
481 reliable. */
482 bool noack_mode = false;
483
484 /* True if we're connected in extended remote mode. */
485 bool extended = false;
486
487 /* True if we resumed the target and we're waiting for the target to
488 stop. In the mean time, we can't start another command/query.
489 The remote server wouldn't be ready to process it, so we'd
490 timeout waiting for a reply that would never come and eventually
491 we'd close the connection. This can happen in asynchronous mode
492 because we allow GDB commands while the target is running. */
493 bool waiting_for_stop_reply = false;
494
495 /* The status of the stub support for the various vCont actions. */
496 vCont_action_support supports_vCont;
497
498 /* True if the user has pressed Ctrl-C, but the target hasn't
499 responded to that. */
500 bool ctrlc_pending_p = false;
501
502 /* True if we saw a Ctrl-C while reading or writing from/to the
503 remote descriptor. At that point it is not safe to send a remote
504 interrupt packet, so we instead remember we saw the Ctrl-C and
505 process it once we're done with sending/receiving the current
506 packet, which should be shortly. If however that takes too long,
507 and the user presses Ctrl-C again, we offer to disconnect. */
508 bool got_ctrlc_during_io = false;
509
510 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
511 remote_open knows that we don't have a file open when the program
512 starts. */
513 struct serial *remote_desc = nullptr;
514
515 /* These are the threads which we last sent to the remote system. The
516 TID member will be -1 for all or -2 for not sent yet. */
517 ptid_t general_thread = null_ptid;
518 ptid_t continue_thread = null_ptid;
519
520 /* This is the traceframe which we last selected on the remote system.
521 It will be -1 if no traceframe is selected. */
522 int remote_traceframe_number = -1;
523
524 char *last_pass_packet = nullptr;
525
526 /* The last QProgramSignals packet sent to the target. We bypass
527 sending a new program signals list down to the target if the new
528 packet is exactly the same as the last we sent. IOW, we only let
529 the target know about program signals list changes. */
530 char *last_program_signals_packet = nullptr;
531
532 gdb_signal last_sent_signal = GDB_SIGNAL_0;
533
534 bool last_sent_step = false;
535
536 /* The execution direction of the last resume we got. */
537 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
538
539 char *finished_object = nullptr;
540 char *finished_annex = nullptr;
541 ULONGEST finished_offset = 0;
542
543 /* Should we try the 'ThreadInfo' query packet?
544
545 This variable (NOT available to the user: auto-detect only!)
546 determines whether GDB will use the new, simpler "ThreadInfo"
547 query or the older, more complex syntax for thread queries.
548 This is an auto-detect variable (set to true at each connect,
549 and set to false when the target fails to recognize it). */
550 bool use_threadinfo_query = false;
551 bool use_threadextra_query = false;
552
553 threadref echo_nextthread {};
554 threadref nextthread {};
555 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
556
557 /* The state of remote notification. */
558 struct remote_notif_state *notif_state = nullptr;
559
560 /* The branch trace configuration. */
561 struct btrace_config btrace_config {};
562
563 /* The argument to the last "vFile:setfs:" packet we sent, used
564 to avoid sending repeated unnecessary "vFile:setfs:" packets.
565 Initialized to -1 to indicate that no "vFile:setfs:" packet
566 has yet been sent. */
567 int fs_pid = -1;
568
569 /* A readahead cache for vFile:pread. Often, reading a binary
570 involves a sequence of small reads. E.g., when parsing an ELF
571 file. A readahead cache helps mostly the case of remote
572 debugging on a connection with higher latency, due to the
573 request/reply nature of the RSP. We only cache data for a single
574 file descriptor at a time. */
575 struct readahead_cache readahead_cache;
576
577 /* The list of already fetched and acknowledged stop events. This
578 queue is used for notification Stop, and other notifications
579 don't need queue for their events, because the notification
580 events of Stop can't be consumed immediately, so that events
581 should be queued first, and be consumed by remote_wait_{ns,as}
582 one per time. Other notifications can consume their events
583 immediately, so queue is not needed for them. */
953edf2b 584 std::vector<stop_reply_up> stop_reply_queue;
3c69da40 585
3c69da40
PA
586 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
587 ``forever'' still use the normal timeout mechanism. This is
588 currently used by the ASYNC code to guarentee that target reads
589 during the initial connect always time-out. Once getpkt has been
590 modified to return a timeout indication and, in turn
591 remote_wait()/wait_for_inferior() have gained a timeout parameter
592 this can go away. */
8756b726 593 bool wait_forever_enabled_p = true;
3c69da40
PA
594
595private:
92b98b37
SM
596 /* Asynchronous signal handle registered as event loop source for
597 when we have pending events ready to be passed to the core. */
598 async_event_handler *m_async_event_handler_token = nullptr;
599
3c69da40
PA
600 /* Mapping of remote protocol data for each gdbarch. Usually there
601 is only one entry here, though we may see more with stubs that
602 support multi-process. */
603 std::unordered_map<struct gdbarch *, remote_arch_state>
604 m_arch_states;
605};
6b8edb51 606
d9f719f1
PA
607static const target_info remote_target_info = {
608 "remote",
ae9adb36 609 N_("Remote target using gdb-specific protocol"),
d9f719f1
PA
610 remote_doc
611};
612
ff52c073
CS
613/* Description of a remote packet. */
614
615struct packet_description
616{
617 /* Name of the packet used for gdb output. */
618 const char *name;
619
620 /* Title of the packet, used by the set/show remote name-packet
621 commands to identify the individual packages and gdb output. */
622 const char *title;
623};
624
625/* Configuration of a remote packet. */
626
627struct packet_config
628{
629 /* If auto, GDB auto-detects support for this packet or feature,
630 either through qSupported, or by trying the packet and looking
631 at the response. If true, GDB assumes the target supports this
632 packet. If false, the packet is disabled. Configs that don't
633 have an associated command always have this set to auto. */
634 enum auto_boolean detect;
635
636 /* Does the target support this packet? */
637 enum packet_support support;
638};
639
fe4c3ca0
CS
640/* User configurable variables for the number of characters in a
641 memory read/write packet. MIN (rsa->remote_packet_size,
642 rsa->sizeof_g_packet) is the default. Some targets need smaller
643 values (fifo overruns, et.al.) and some users need larger values
644 (speed up transfers). The variables ``preferred_*'' (the user
645 request), ``current_*'' (what was actually set) and ``forced_*''
646 (Positive - a soft limit, negative - a hard limit). */
647
648struct memory_packet_config
649{
650 const char *name;
651 long size;
652 int fixed_p;
653};
654
655/* These global variables contain the default configuration for every new
656 remote_feature object. */
657static memory_packet_config memory_read_packet_config =
658{
659 "memory-read-packet-size",
660};
661static memory_packet_config memory_write_packet_config =
662{
663 "memory-write-packet-size",
664};
665
ff52c073
CS
666/* This global array contains packet descriptions (name and title). */
667static packet_description packets_descriptions[PACKET_MAX];
668/* This global array contains the default configuration for every new
669 per-remote target array. */
670static packet_config remote_protocol_packets[PACKET_MAX];
671
672/* Description of a remote target's features. It stores the configuration
673 and provides functions to determine supported features of the target. */
674
675struct remote_features
676{
677 remote_features ()
678 {
fe4c3ca0
CS
679 m_memory_read_packet_config = memory_read_packet_config;
680 m_memory_write_packet_config = memory_write_packet_config;
681
ff52c073
CS
682 std::copy (std::begin (remote_protocol_packets),
683 std::end (remote_protocol_packets),
684 std::begin (m_protocol_packets));
685 }
686 ~remote_features () = default;
687
688 DISABLE_COPY_AND_ASSIGN (remote_features);
689
690 /* Returns whether a given packet defined by its enum value is supported. */
691 enum packet_support packet_support (int) const;
692
693 /* Returns the packet's corresponding "set remote foo-packet" command
694 state. See struct packet_config for more details. */
695 enum auto_boolean packet_set_cmd_state (int packet) const
696 { return m_protocol_packets[packet].detect; }
697
698 /* Returns true if the multi-process extensions are in effect. */
699 int remote_multi_process_p () const
700 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
701
702 /* Returns true if fork events are supported. */
703 int remote_fork_event_p () const
704 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
705
706 /* Returns true if vfork events are supported. */
707 int remote_vfork_event_p () const
708 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
709
710 /* Returns true if exec events are supported. */
711 int remote_exec_event_p () const
712 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
713
714 /* Returns true if memory tagging is supported, false otherwise. */
715 bool remote_memory_tagging_p () const
716 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
717
718 /* Reset all packets back to "unknown support". Called when opening a
719 new connection to a remote target. */
720 void reset_all_packet_configs_support ();
721
722/* Check result value in BUF for packet WHICH_PACKET and update the packet's
723 support configuration accordingly. */
724 packet_result packet_ok (const char *buf, const int which_packet);
725 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
726
fe4c3ca0
CS
727 /* Configuration of a remote target's memory read packet. */
728 memory_packet_config m_memory_read_packet_config;
729 /* Configuration of a remote target's memory write packet. */
730 memory_packet_config m_memory_write_packet_config;
731
ff52c073
CS
732 /* The per-remote target array which stores a remote's packet
733 configurations. */
734 packet_config m_protocol_packets[PACKET_MAX];
735};
736
3b3dac9b 737class remote_target : public process_stratum_target
f6ac5f3d
PA
738{
739public:
3b3dac9b 740 remote_target () = default;
6b8edb51 741 ~remote_target () override;
f6ac5f3d 742
d9f719f1
PA
743 const target_info &info () const override
744 { return remote_target_info; }
f6ac5f3d 745
121b3efd
PA
746 const char *connection_string () override;
747
f6ac5f3d
PA
748 thread_control_capabilities get_thread_control_capabilities () override
749 { return tc_schedlock; }
750
d9f719f1
PA
751 /* Open a remote connection. */
752 static void open (const char *, int);
753
f6ac5f3d
PA
754 void close () override;
755
756 void detach (inferior *, int) override;
757 void disconnect (const char *, int) override;
758
1192f124 759 void commit_resumed () override;
f6ac5f3d 760 void resume (ptid_t, int, enum gdb_signal) override;
b60cea74 761 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
b4b1a226 762 bool has_pending_events () override;
f6ac5f3d
PA
763
764 void fetch_registers (struct regcache *, int) override;
765 void store_registers (struct regcache *, int) override;
766 void prepare_to_store (struct regcache *) override;
767
f6ac5f3d
PA
768 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
769
770 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
771 enum remove_bp_reason) override;
772
773
57810aa7
PA
774 bool stopped_by_sw_breakpoint () override;
775 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 776
57810aa7 777 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 778
57810aa7 779 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 780
57810aa7 781 bool stopped_by_watchpoint () override;
f6ac5f3d 782
57810aa7 783 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 784
57810aa7 785 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
786
787 int can_use_hw_breakpoint (enum bptype, int, int) override;
788
789 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
790
791 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
792
793 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
794
795 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
796 struct expression *) override;
797
798 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
799 struct expression *) override;
800
801 void kill () override;
802
803 void load (const char *, int) override;
804
805 void mourn_inferior () override;
806
adc6a863 807 void pass_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d
PA
808
809 int set_syscall_catchpoint (int, bool, int,
810 gdb::array_view<const int>) override;
811
adc6a863 812 void program_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d 813
57810aa7 814 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
815
816 const char *thread_name (struct thread_info *) override;
817
818 void update_thread_list () override;
819
a068643d 820 std::string pid_to_str (ptid_t) override;
f6ac5f3d
PA
821
822 const char *extra_thread_info (struct thread_info *) override;
823
c80e29db 824 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
f6ac5f3d
PA
825
826 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
827 int handle_len,
828 inferior *inf) override;
829
1f08d324
TV
830 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
831 override;
3d6c6204 832
f6ac5f3d
PA
833 void stop (ptid_t) override;
834
835 void interrupt () override;
836
837 void pass_ctrlc () override;
838
839 enum target_xfer_status xfer_partial (enum target_object object,
840 const char *annex,
841 gdb_byte *readbuf,
842 const gdb_byte *writebuf,
843 ULONGEST offset, ULONGEST len,
844 ULONGEST *xfered_len) override;
845
846 ULONGEST get_memory_xfer_limit () override;
847
848 void rcmd (const char *command, struct ui_file *output) override;
849
0e90c441 850 const char *pid_to_exec_file (int pid) override;
f6ac5f3d
PA
851
852 void log_command (const char *cmd) override
853 {
854 serial_log_command (this, cmd);
855 }
856
857 CORE_ADDR get_thread_local_address (ptid_t ptid,
858 CORE_ADDR load_module_addr,
859 CORE_ADDR offset) override;
860
57810aa7 861 bool can_execute_reverse () override;
f6ac5f3d
PA
862
863 std::vector<mem_region> memory_map () override;
864
865 void flash_erase (ULONGEST address, LONGEST length) override;
866
867 void flash_done () override;
868
869 const struct target_desc *read_description () override;
870
871 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
872 const gdb_byte *pattern, ULONGEST pattern_len,
873 CORE_ADDR *found_addrp) override;
874
57810aa7 875 bool can_async_p () override;
f6ac5f3d 876
57810aa7 877 bool is_async_p () override;
f6ac5f3d 878
4a570176 879 void async (bool) override;
f6ac5f3d 880
5b6d1e4f
PA
881 int async_wait_fd () override;
882
f6ac5f3d
PA
883 void thread_events (int) override;
884
885 int can_do_single_step () override;
886
887 void terminal_inferior () override;
888
889 void terminal_ours () override;
890
57810aa7 891 bool supports_non_stop () override;
f6ac5f3d 892
57810aa7 893 bool supports_multi_process () override;
f6ac5f3d 894
57810aa7 895 bool supports_disable_randomization () override;
f6ac5f3d 896
57810aa7 897 bool filesystem_is_local () override;
f6ac5f3d
PA
898
899
900 int fileio_open (struct inferior *inf, const char *filename,
901 int flags, int mode, int warn_if_slow,
b872057a 902 fileio_error *target_errno) override;
f6ac5f3d
PA
903
904 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 905 ULONGEST offset, fileio_error *target_errno) override;
f6ac5f3d
PA
906
907 int fileio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 908 ULONGEST offset, fileio_error *target_errno) override;
f6ac5f3d 909
b872057a 910 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
f6ac5f3d 911
b872057a 912 int fileio_close (int fd, fileio_error *target_errno) override;
f6ac5f3d
PA
913
914 int fileio_unlink (struct inferior *inf,
915 const char *filename,
b872057a 916 fileio_error *target_errno) override;
f6ac5f3d
PA
917
918 gdb::optional<std::string>
919 fileio_readlink (struct inferior *inf,
920 const char *filename,
b872057a 921 fileio_error *target_errno) override;
f6ac5f3d 922
57810aa7 923 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 924
57810aa7 925 bool supports_string_tracing () override;
f6ac5f3d 926
ff52c073
CS
927 int remote_supports_cond_tracepoints ();
928
57810aa7 929 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 930
ff52c073
CS
931 int remote_supports_fast_tracepoints ();
932
933 int remote_supports_static_tracepoints ();
934
935 int remote_supports_install_in_trace ();
936
57810aa7 937 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
938
939 void trace_init () override;
940
941 void download_tracepoint (struct bp_location *location) override;
942
57810aa7 943 bool can_download_tracepoint () override;
f6ac5f3d
PA
944
945 void download_trace_state_variable (const trace_state_variable &tsv) override;
946
947 void enable_tracepoint (struct bp_location *location) override;
948
949 void disable_tracepoint (struct bp_location *location) override;
950
951 void trace_set_readonly_regions () override;
952
953 void trace_start () override;
954
955 int get_trace_status (struct trace_status *ts) override;
956
01bccc56 957 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
f6ac5f3d
PA
958 override;
959
960 void trace_stop () override;
961
962 int trace_find (enum trace_find_type type, int num,
963 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
964
57810aa7 965 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
966
967 int save_trace_data (const char *filename) override;
968
969 int upload_tracepoints (struct uploaded_tp **utpp) override;
970
971 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
972
973 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
974
975 int get_min_fast_tracepoint_insn_len () override;
976
977 void set_disconnected_tracing (int val) override;
978
979 void set_circular_trace_buffer (int val) override;
980
981 void set_trace_buffer_size (LONGEST val) override;
982
57810aa7
PA
983 bool set_trace_notes (const char *user, const char *notes,
984 const char *stopnotes) override;
f6ac5f3d
PA
985
986 int core_of_thread (ptid_t ptid) override;
987
988 int verify_memory (const gdb_byte *data,
989 CORE_ADDR memaddr, ULONGEST size) override;
990
991
57810aa7 992 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
993
994 void set_permissions () override;
995
996 bool static_tracepoint_marker_at (CORE_ADDR,
997 struct static_tracepoint_marker *marker)
998 override;
999
1000 std::vector<static_tracepoint_marker>
1001 static_tracepoint_markers_by_strid (const char *id) override;
1002
1003 traceframe_info_up traceframe_info () override;
1004
57810aa7
PA
1005 bool use_agent (bool use) override;
1006 bool can_use_agent () override;
f6ac5f3d 1007
696c0d5e
MM
1008 struct btrace_target_info *
1009 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
f6ac5f3d
PA
1010
1011 void disable_btrace (struct btrace_target_info *tinfo) override;
1012
1013 void teardown_btrace (struct btrace_target_info *tinfo) override;
1014
1015 enum btrace_error read_btrace (struct btrace_data *data,
1016 struct btrace_target_info *btinfo,
1017 enum btrace_read_type type) override;
1018
1019 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 1020 bool augmented_libraries_svr4_read () override;
82d1f134 1021 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
294c36eb 1022 void follow_exec (inferior *, ptid_t, const char *) override;
f6ac5f3d
PA
1023 int insert_fork_catchpoint (int) override;
1024 int remove_fork_catchpoint (int) override;
1025 int insert_vfork_catchpoint (int) override;
1026 int remove_vfork_catchpoint (int) override;
1027 int insert_exec_catchpoint (int) override;
1028 int remove_exec_catchpoint (int) override;
1029 enum exec_direction_kind execution_direction () override;
1030
dbe692af
LM
1031 bool supports_memory_tagging () override;
1032
1033 bool fetch_memtags (CORE_ADDR address, size_t len,
1034 gdb::byte_vector &tags, int type) override;
1035
1036 bool store_memtags (CORE_ADDR address, size_t len,
1037 const gdb::byte_vector &tags, int type) override;
1038
6b8edb51
PA
1039public: /* Remote specific methods. */
1040
1041 void remote_download_command_source (int num, ULONGEST addr,
1042 struct command_line *cmds);
1043
1044 void remote_file_put (const char *local_file, const char *remote_file,
1045 int from_tty);
1046 void remote_file_get (const char *remote_file, const char *local_file,
1047 int from_tty);
1048 void remote_file_delete (const char *remote_file, int from_tty);
1049
1050 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 1051 ULONGEST offset, fileio_error *remote_errno);
6b8edb51 1052 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 1053 ULONGEST offset, fileio_error *remote_errno);
6b8edb51 1054 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
b872057a 1055 ULONGEST offset, fileio_error *remote_errno);
6b8edb51
PA
1056
1057 int remote_hostio_send_command (int command_bytes, int which_packet,
b872057a 1058 fileio_error *remote_errno, const char **attachment,
6b8edb51
PA
1059 int *attachment_len);
1060 int remote_hostio_set_filesystem (struct inferior *inf,
b872057a 1061 fileio_error *remote_errno);
6b8edb51
PA
1062 /* We should get rid of this and use fileio_open directly. */
1063 int remote_hostio_open (struct inferior *inf, const char *filename,
1064 int flags, int mode, int warn_if_slow,
b872057a
SM
1065 fileio_error *remote_errno);
1066 int remote_hostio_close (int fd, fileio_error *remote_errno);
6b8edb51
PA
1067
1068 int remote_hostio_unlink (inferior *inf, const char *filename,
b872057a 1069 fileio_error *remote_errno);
6b8edb51
PA
1070
1071 struct remote_state *get_remote_state ();
1072
1073 long get_remote_packet_size (void);
1074 long get_memory_packet_size (struct memory_packet_config *config);
1075
1076 long get_memory_write_packet_size ();
1077 long get_memory_read_packet_size ();
1078
1079 char *append_pending_thread_resumptions (char *p, char *endp,
1080 ptid_t ptid);
d9f719f1 1081 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d 1082 void start_remote (int from_tty, int extended_p);
00431a78 1083 void remote_detach_1 (struct inferior *inf, int from_tty);
6b8edb51
PA
1084
1085 char *append_resumption (char *p, char *endp,
1086 ptid_t ptid, int step, gdb_signal siggnal);
d51926f0 1087 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
6b8edb51
PA
1088 gdb_signal siggnal);
1089
64d38fdd 1090 thread_info *add_current_inferior_and_thread (const char *wait_status);
6b8edb51
PA
1091
1092 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
b60cea74 1093 target_wait_flags options);
6b8edb51 1094 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
b60cea74 1095 target_wait_flags options);
6b8edb51
PA
1096
1097 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1098 target_waitstatus *status);
1099
8f66807b 1100 ptid_t select_thread_for_ambiguous_stop_reply
c272a98c 1101 (const struct target_waitstatus &status);
8f66807b 1102
8a82de58 1103 void remote_notice_new_inferior (ptid_t currthread, bool executing);
6b8edb51 1104
1edb66d8 1105 void print_one_stopped_thread (thread_info *thread);
6b8edb51
PA
1106 void process_initial_stop_replies (int from_tty);
1107
b622494e
AB
1108 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1109 bool silent_p);
6b8edb51
PA
1110
1111 void btrace_sync_conf (const btrace_config *conf);
1112
1113 void remote_btrace_maybe_reopen ();
1114
1115 void remove_new_fork_children (threads_listing_context *context);
28561a65 1116 void kill_new_fork_children (inferior *inf);
6b8edb51
PA
1117 void discard_pending_stop_replies (struct inferior *inf);
1118 int stop_reply_queue_length ();
1119
1120 void check_pending_events_prevent_wildcard_vcont
2f63ec5c 1121 (bool *may_global_wildcard_vcont);
6b8edb51
PA
1122
1123 void discard_pending_stop_replies_in_queue ();
1124 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1125 struct stop_reply *queued_stop_reply (ptid_t ptid);
1126 int peek_stop_reply (ptid_t ptid);
bb277751 1127 void remote_parse_stop_reply (const char *buf, stop_reply *event);
6b8edb51
PA
1128
1129 void remote_stop_ns (ptid_t ptid);
1130 void remote_interrupt_as ();
1131 void remote_interrupt_ns ();
1132
1133 char *remote_get_noisy_reply ();
1134 int remote_query_attached (int pid);
9ab8741a 1135 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51
PA
1136 int try_open_exec);
1137
1138 ptid_t remote_current_thread (ptid_t oldpid);
e3b2741b 1139 ptid_t get_current_thread (const char *wait_status);
6b8edb51
PA
1140
1141 void set_thread (ptid_t ptid, int gen);
1142 void set_general_thread (ptid_t ptid);
1143 void set_continue_thread (ptid_t ptid);
1144 void set_general_process ();
1145
1146 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1147
cecb1912 1148 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
6b8edb51
PA
1149 gdb_ext_thread_info *info);
1150 int remote_get_threadinfo (threadref *threadid, int fieldset,
1151 gdb_ext_thread_info *info);
1152
cecb1912 1153 int parse_threadlist_response (const char *pkt, int result_limit,
6b8edb51
PA
1154 threadref *original_echo,
1155 threadref *resultlist,
1156 int *doneflag);
1157 int remote_get_threadlist (int startflag, threadref *nextthread,
1158 int result_limit, int *done, int *result_count,
1159 threadref *threadlist);
1160
1161 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1162 void *context, int looplimit);
1163
1164 int remote_get_threads_with_ql (threads_listing_context *context);
1165 int remote_get_threads_with_qxfer (threads_listing_context *context);
1166 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1167
1168 void extended_remote_restart ();
1169
1170 void get_offsets ();
1171
1172 void remote_check_symbols ();
1173
1174 void remote_supported_packet (const struct protocol_feature *feature,
1175 enum packet_support support,
1176 const char *argument);
1177
1178 void remote_query_supported ();
1179
1180 void remote_packet_size (const protocol_feature *feature,
1181 packet_support support, const char *value);
1182
1183 void remote_serial_quit_handler ();
1184
1185 void remote_detach_pid (int pid);
1186
1187 void remote_vcont_probe ();
1188
1189 void remote_resume_with_hc (ptid_t ptid, int step,
1190 gdb_signal siggnal);
1191
1192 void send_interrupt_sequence ();
1193 void interrupt_query ();
1194
42938c1a 1195 void remote_notif_get_pending_events (const notif_client *nc);
6b8edb51
PA
1196
1197 int fetch_register_using_p (struct regcache *regcache,
1198 packet_reg *reg);
1199 int send_g_packet ();
1200 void process_g_packet (struct regcache *regcache);
1201 void fetch_registers_using_g (struct regcache *regcache);
1202 int store_register_using_P (const struct regcache *regcache,
1203 packet_reg *reg);
1204 void store_registers_using_G (const struct regcache *regcache);
1205
1206 void set_remote_traceframe ();
1207
1208 void check_binary_download (CORE_ADDR addr);
1209
1210 target_xfer_status remote_write_bytes_aux (const char *header,
1211 CORE_ADDR memaddr,
1212 const gdb_byte *myaddr,
1213 ULONGEST len_units,
1214 int unit_size,
1215 ULONGEST *xfered_len_units,
1216 char packet_format,
1217 int use_length);
1218
1219 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1220 const gdb_byte *myaddr, ULONGEST len,
1221 int unit_size, ULONGEST *xfered_len);
1222
1223 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1224 ULONGEST len_units,
1225 int unit_size, ULONGEST *xfered_len_units);
1226
1227 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1228 ULONGEST memaddr,
1229 ULONGEST len,
1230 int unit_size,
1231 ULONGEST *xfered_len);
1232
1233 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1234 gdb_byte *myaddr, ULONGEST len,
1235 int unit_size,
1236 ULONGEST *xfered_len);
1237
1238 packet_result remote_send_printf (const char *format, ...)
1239 ATTRIBUTE_PRINTF (2, 3);
1240
1241 target_xfer_status remote_flash_write (ULONGEST address,
1242 ULONGEST length, ULONGEST *xfered_len,
1243 const gdb_byte *data);
1244
1245 int readchar (int timeout);
1246
1247 void remote_serial_write (const char *str, int len);
1248
1249 int putpkt (const char *buf);
1250 int putpkt_binary (const char *buf, int cnt);
1251
8d64371b
TT
1252 int putpkt (const gdb::char_vector &buf)
1253 {
1254 return putpkt (buf.data ());
1255 }
1256
6b8edb51 1257 void skip_frame ();
8d64371b 1258 long read_frame (gdb::char_vector *buf_p);
aa7b36b8
TT
1259 int getpkt (gdb::char_vector *buf, bool forever = false,
1260 bool *is_notif = nullptr);
6b8edb51
PA
1261 int remote_vkill (int pid);
1262 void remote_kill_k ();
1263
1264 void extended_remote_disable_randomization (int val);
1265 int extended_remote_run (const std::string &args);
1266
1267 void send_environment_packet (const char *action,
1268 const char *packet,
1269 const char *value);
1270
1271 void extended_remote_environment_support ();
3c69da40 1272 void extended_remote_set_inferior_cwd ();
80152258 1273
3c69da40
PA
1274 target_xfer_status remote_write_qxfer (const char *object_name,
1275 const char *annex,
1276 const gdb_byte *writebuf,
1277 ULONGEST offset, LONGEST len,
1278 ULONGEST *xfered_len,
ff52c073 1279 const unsigned int which_packet);
43c3a0e4 1280
3c69da40
PA
1281 target_xfer_status remote_read_qxfer (const char *object_name,
1282 const char *annex,
1283 gdb_byte *readbuf, ULONGEST offset,
1284 LONGEST len,
1285 ULONGEST *xfered_len,
ff52c073 1286 const unsigned int which_packet);
43c3a0e4 1287
3c69da40 1288 void push_stop_reply (struct stop_reply *new_event);
43c3a0e4 1289
3c69da40 1290 bool vcont_r_supported ();
43c3a0e4 1291
ff52c073
CS
1292 remote_features m_features;
1293
288712bb
AB
1294private:
1295
1296 bool start_remote_1 (int from_tty, int extended_p);
43c3a0e4 1297
3c69da40
PA
1298 /* The remote state. Don't reference this directly. Use the
1299 get_remote_state method instead. */
1300 remote_state m_remote_state;
43c3a0e4
PA
1301};
1302
3c69da40
PA
1303static const target_info extended_remote_target_info = {
1304 "extended-remote",
ae9adb36 1305 N_("Extended remote target using gdb-specific protocol"),
3c69da40
PA
1306 remote_doc
1307};
ea9c271d 1308
3c69da40
PA
1309/* Set up the extended remote target by extending the standard remote
1310 target and adding to it. */
1311
1312class extended_remote_target final : public remote_target
ea9c271d 1313{
9d6eea31 1314public:
3c69da40
PA
1315 const target_info &info () const override
1316 { return extended_remote_target_info; }
9d6eea31 1317
3c69da40
PA
1318 /* Open an extended-remote connection. */
1319 static void open (const char *, int);
de44f5a7 1320
3c69da40
PA
1321 bool can_create_inferior () override { return true; }
1322 void create_inferior (const char *, const std::string &,
1323 char **, int) override;
9d6eea31 1324
3c69da40 1325 void detach (inferior *, int) override;
9d6eea31 1326
3c69da40
PA
1327 bool can_attach () override { return true; }
1328 void attach (const char *, int) override;
be2a5f71 1329
3c69da40
PA
1330 void post_attach (int) override;
1331 bool supports_disable_randomization () override;
1332};
1e51243a 1333
a4543480
SM
1334struct stop_reply : public notif_event
1335{
1336 ~stop_reply ();
1337
1338 /* The identifier of the thread about this event */
1339 ptid_t ptid;
1340
1341 /* The remote state this event is associated with. When the remote
1342 connection, represented by a remote_state object, is closed,
1343 all the associated stop_reply events should be released. */
1344 struct remote_state *rs;
1345
1346 struct target_waitstatus ws;
1347
1348 /* The architecture associated with the expedited registers. */
1349 gdbarch *arch;
1350
1351 /* Expedited registers. This makes remote debugging a bit more
1352 efficient for those targets that provide critical registers as
1353 part of their normal status mechanism (as another roundtrip to
1354 fetch them is avoided). */
1355 std::vector<cached_reg_t> regcache;
1356
1357 enum target_stop_reason stop_reason;
1358
1359 CORE_ADDR watch_data_address;
1360
1361 int core;
1362};
1363
06c7226e
SM
1364/* Return TARGET as a remote_target if it is one, else nullptr. */
1365
1366static remote_target *
1367as_remote_target (process_stratum_target *target)
1368{
1369 return dynamic_cast<remote_target *> (target);
1370}
1371
24b2de7b
AB
1372/* See remote.h. */
1373
1374bool
1375is_remote_target (process_stratum_target *target)
1376{
06c7226e 1377 return as_remote_target (target) != nullptr;
24b2de7b
AB
1378}
1379
3c69da40 1380/* Per-program-space data key. */
08b8a139 1381static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
7b4a314f 1382 remote_pspace_data;
2d717e4f 1383
3c69da40
PA
1384/* The variable registered as the control variable used by the
1385 remote exec-file commands. While the remote exec-file setting is
7a78108a 1386 per-program-space, the set/show machinery uses this as the
3c69da40 1387 location of the remote exec-file value. */
e0700ba4 1388static std::string remote_exec_file_var;
a6f3e723 1389
3c69da40
PA
1390/* The size to align memory write packets, when practical. The protocol
1391 does not guarantee any alignment, and gdb will generate short
1392 writes and unaligned writes, but even as a best-effort attempt this
1393 can improve bulk transfers. For instance, if a write is misaligned
1394 relative to the target's data bus, the stub may need to make an extra
1395 round trip fetching data from the target. This doesn't make a
1396 huge difference, but it's easy to do, so we try to be helpful.
82f73884 1397
3c69da40
PA
1398 The alignment chosen is arbitrary; usually data bus width is
1399 important here, not the possibly larger cache line size. */
1400enum { REMOTE_ALIGN_WRITES = 16 };
82f73884 1401
3c69da40 1402/* Prototypes for local functions. */
74531fed 1403
3c69da40 1404static int hexnumlen (ULONGEST num);
782b2b07 1405
3c69da40 1406static int stubhex (int ch);
5d93a237 1407
3c69da40 1408static int hexnumstr (char *, ULONGEST);
048094ac 1409
3c69da40 1410static int hexnumnstr (char *, ULONGEST, int);
47f8a51d 1411
3c69da40 1412static CORE_ADDR remote_address_masked (CORE_ADDR);
262e1174 1413
cecb1912 1414static int stub_unpack_int (const char *buff, int fieldlength);
5e4a05c4 1415
ff52c073
CS
1416static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1417 cmd_list_element *c);
1418
1419static void show_packet_config_cmd (ui_file *file,
1420 const unsigned int which_packet,
1421 remote_target *remote);
b73be471 1422
3c69da40
PA
1423static void show_remote_protocol_packet_cmd (struct ui_file *file,
1424 int from_tty,
1425 struct cmd_list_element *c,
1426 const char *value);
8e88304f 1427
3c69da40 1428static ptid_t read_ptid (const char *buf, const char **obuf);
3a00c802 1429
eefce37f 1430static bool remote_read_description_p (struct target_ops *target);
88b496c3 1431
05be00a8 1432static void remote_console_output (const char *msg);
5965e028 1433
3c69da40 1434static void remote_btrace_reset (remote_state *rs);
f4abbc16 1435
5b6d1e4f 1436static void remote_unpush_and_throw (remote_target *target);
15a201c8 1437
3c69da40 1438/* For "remote". */
80152258 1439
3c69da40 1440static struct cmd_list_element *remote_cmdlist;
9d6eea31 1441
3c69da40 1442/* For "set remote" and "show remote". */
6b8edb51 1443
3c69da40
PA
1444static struct cmd_list_element *remote_set_cmdlist;
1445static struct cmd_list_element *remote_show_cmdlist;
6b8edb51 1446
3c69da40 1447/* Controls whether GDB is willing to use range stepping. */
6b8edb51 1448
491144b5 1449static bool use_range_stepping = true;
3c69da40 1450
c9d22089
SM
1451/* From the remote target's point of view, each thread is in one of these three
1452 states. */
1453enum class resume_state
1454{
1455 /* Not resumed - we haven't been asked to resume this thread. */
1456 NOT_RESUMED,
1457
1458 /* We have been asked to resume this thread, but haven't sent a vCont action
1459 for it yet. We'll need to consider it next time commit_resume is
1460 called. */
1461 RESUMED_PENDING_VCONT,
1462
1463 /* We have been asked to resume this thread, and we have sent a vCont action
1464 for it. */
1465 RESUMED,
1466};
1467
1468/* Information about a thread's pending vCont-resume. Used when a thread is in
1469 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1470 stores this information which is then picked up by
1471 remote_target::commit_resume to know which is the proper action for this
1472 thread to include in the vCont packet. */
1473struct resumed_pending_vcont_info
1474{
1475 /* True if the last resume call for this thread was a step request, false
1476 if a continue request. */
1477 bool step;
1478
1479 /* The signal specified in the last resume call for this thread. */
1480 gdb_signal sig;
1481};
1482
7aabaf9d
SM
1483/* Private data that we'll store in (struct thread_info)->priv. */
1484struct remote_thread_info : public private_thread_info
dc146f7c 1485{
7aabaf9d
SM
1486 std::string extra;
1487 std::string name;
1488 int core = -1;
799a2abe 1489
f6327dcb
KB
1490 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1491 sequence of bytes. */
7aabaf9d 1492 gdb::byte_vector thread_handle;
f6327dcb 1493
799a2abe 1494 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1495 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1496
1497 /* This is set to the data address of the access causing the target
1498 to stop for a watchpoint. */
7aabaf9d 1499 CORE_ADDR watch_data_address = 0;
85ad3aaf 1500
c9d22089 1501 /* Get the thread's resume state. */
a6c11cbb 1502 enum resume_state get_resume_state () const
c9d22089
SM
1503 {
1504 return m_resume_state;
1505 }
1506
1507 /* Put the thread in the NOT_RESUMED state. */
1508 void set_not_resumed ()
1509 {
1510 m_resume_state = resume_state::NOT_RESUMED;
1511 }
85ad3aaf 1512
c9d22089
SM
1513 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1514 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1515 {
1516 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1517 m_resumed_pending_vcont_info.step = step;
1518 m_resumed_pending_vcont_info.sig = sig;
1519 }
85ad3aaf 1520
c9d22089 1521 /* Get the information this thread's pending vCont-resumption.
85ad3aaf 1522
c9d22089
SM
1523 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1524 state. */
1525 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1526 {
1527 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1528
1529 return m_resumed_pending_vcont_info;
1530 }
1531
1532 /* Put the thread in the VCONT_RESUMED state. */
1533 void set_resumed ()
1534 {
1535 m_resume_state = resume_state::RESUMED;
1536 }
1537
1538private:
1539 /* Resume state for this thread. This is used to implement vCont action
1540 coalescing (only when the target operates in non-stop mode).
1541
1542 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1543 which notes that this thread must be considered in the next commit_resume
1544 call.
1545
1546 remote_target::commit_resume sends a vCont packet with actions for the
1547 threads in the RESUMED_PENDING_VCONT state and moves them to the
1548 VCONT_RESUMED state.
1549
1550 When reporting a stop to the core for a thread, that thread is moved back
1551 to the NOT_RESUMED state. */
1552 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1553
1554 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1555 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
dc146f7c
VP
1556};
1557
de44f5a7 1558remote_state::remote_state ()
8d64371b 1559 : buf (400)
de44f5a7 1560{
de44f5a7
PA
1561}
1562
1563remote_state::~remote_state ()
1564{
1565 xfree (this->last_pass_packet);
1566 xfree (this->last_program_signals_packet);
de44f5a7
PA
1567 xfree (this->finished_object);
1568 xfree (this->finished_annex);
cf792862
TT
1569}
1570
35b1e5cc
SS
1571/* Utility: generate error from an incoming stub packet. */
1572static void
1573trace_error (char *buf)
1574{
1575 if (*buf++ != 'E')
1576 return; /* not an error msg */
1577 switch (*buf)
1578 {
1579 case '1': /* malformed packet error */
1580 if (*++buf == '0') /* general case: */
1581 error (_("remote.c: error in outgoing packet."));
1582 else
1583 error (_("remote.c: error in outgoing packet at field #%ld."),
1584 strtol (buf, NULL, 16));
35b1e5cc
SS
1585 default:
1586 error (_("Target returns error code '%s'."), buf);
1587 }
1588}
1589
1590/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1591
6b8edb51
PA
1592char *
1593remote_target::remote_get_noisy_reply ()
35b1e5cc 1594{
b6bb3468
PA
1595 struct remote_state *rs = get_remote_state ();
1596
35b1e5cc
SS
1597 do /* Loop on reply from remote stub. */
1598 {
1599 char *buf;
a744cf53 1600
0df8b418 1601 QUIT; /* Allow user to bail out with ^C. */
aa7b36b8 1602 getpkt (&rs->buf);
8d64371b 1603 buf = rs->buf.data ();
ad91cd99 1604 if (buf[0] == 'E')
35b1e5cc 1605 trace_error (buf);
61012eef 1606 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1607 {
1608 ULONGEST ul;
1609 CORE_ADDR from, to, org_to;
256642e8 1610 const char *p, *pp;
dde08ee1 1611 int adjusted_size = 0;
7556d4a4 1612 int relocated = 0;
dde08ee1
PA
1613
1614 p = buf + strlen ("qRelocInsn:");
1615 pp = unpack_varlen_hex (p, &ul);
1616 if (*pp != ';')
cb91c06a 1617 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1618 from = ul;
1619
1620 p = pp + 1;
a9cbf802 1621 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1622 to = ul;
1623
1624 org_to = to;
1625
a70b8144 1626 try
dde08ee1 1627 {
99d9c3b9
SM
1628 gdbarch_relocate_instruction (current_inferior ()->arch (),
1629 &to, from);
7556d4a4 1630 relocated = 1;
dde08ee1 1631 }
230d2906 1632 catch (const gdb_exception &ex)
7556d4a4
PA
1633 {
1634 if (ex.error == MEMORY_ERROR)
1635 {
1636 /* Propagate memory errors silently back to the
1637 target. The stub may have limited the range of
1638 addresses we can write to, for example. */
1639 }
1640 else
1641 {
1642 /* Something unexpectedly bad happened. Be verbose
1643 so we can tell what, and propagate the error back
1644 to the stub, so it doesn't get stuck waiting for
1645 a response. */
1646 exception_fprintf (gdb_stderr, ex,
1647 _("warning: relocating instruction: "));
1648 }
1649 putpkt ("E01");
1650 }
1651
1652 if (relocated)
dde08ee1
PA
1653 {
1654 adjusted_size = to - org_to;
1655
8d64371b 1656 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1657 putpkt (buf);
1658 }
dde08ee1 1659 }
ad91cd99 1660 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
1661 remote_console_output (buf + 1); /* 'O' message from stub */
1662 else
0df8b418 1663 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1664 }
1665 while (1);
1666}
3c3bea1c 1667
9d6eea31
PA
1668struct remote_arch_state *
1669remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1670{
43c3a0e4
PA
1671 remote_arch_state *rsa;
1672
1673 auto it = this->m_arch_states.find (gdbarch);
1674 if (it == this->m_arch_states.end ())
9d6eea31 1675 {
43c3a0e4
PA
1676 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1677 std::forward_as_tuple (gdbarch),
1678 std::forward_as_tuple (gdbarch));
1679 rsa = &p.first->second;
9d6eea31
PA
1680
1681 /* Make sure that the packet buffer is plenty big enough for
1682 this architecture. */
8d64371b
TT
1683 if (this->buf.size () < rsa->remote_packet_size)
1684 this->buf.resize (2 * rsa->remote_packet_size);
9d6eea31 1685 }
43c3a0e4
PA
1686 else
1687 rsa = &it->second;
1688
1689 return rsa;
d01949b6
AC
1690}
1691
0b83947e
DJ
1692/* Fetch the global remote target state. */
1693
6b8edb51
PA
1694remote_state *
1695remote_target::get_remote_state ()
0b83947e
DJ
1696{
1697 /* Make sure that the remote architecture state has been
1698 initialized, because doing so might reallocate rs->buf. Any
1699 function which calls getpkt also needs to be mindful of changes
1700 to rs->buf, but this call limits the number of places which run
1701 into trouble. */
99d9c3b9 1702 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
0b83947e 1703
3c69da40 1704 return &m_remote_state;
0b83947e
DJ
1705}
1706
94585166
DB
1707/* Fetch the remote exec-file from the current program space. */
1708
1709static const char *
1710get_remote_exec_file (void)
1711{
1712 char *remote_exec_file;
1713
7b4a314f 1714 remote_exec_file = remote_pspace_data.get (current_program_space);
94585166
DB
1715 if (remote_exec_file == NULL)
1716 return "";
1717
1718 return remote_exec_file;
1719}
1720
1721/* Set the remote exec file for PSPACE. */
1722
1723static void
1724set_pspace_remote_exec_file (struct program_space *pspace,
7b4a314f 1725 const char *remote_exec_file)
94585166 1726{
7b4a314f 1727 char *old_file = remote_pspace_data.get (pspace);
94585166
DB
1728
1729 xfree (old_file);
7b4a314f 1730 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
94585166
DB
1731}
1732
1733/* The "set/show remote exec-file" set command hook. */
1734
1735static void
eb4c3f4a 1736set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1737 struct cmd_list_element *c)
1738{
e0700ba4
SM
1739 set_pspace_remote_exec_file (current_program_space,
1740 remote_exec_file_var.c_str ());
94585166
DB
1741}
1742
1743/* The "set/show remote exec-file" show command hook. */
1744
1745static void
1746show_remote_exec_file (struct ui_file *file, int from_tty,
1747 struct cmd_list_element *cmd, const char *value)
1748{
6cb06a8c 1749 gdb_printf (file, "%s\n", get_remote_exec_file ());
94585166
DB
1750}
1751
c21236dc
PA
1752static int
1753map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1754{
74ca34ce 1755 int regnum, num_remote_regs, offset;
74ca34ce 1756 struct packet_reg **remote_regs;
ea9c271d 1757
4a22f64d 1758 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1759 {
c21236dc 1760 struct packet_reg *r = &regs[regnum];
baef701f 1761
4a22f64d 1762 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1763 /* Do not try to fetch zero-sized (placeholder) registers. */
1764 r->pnum = -1;
1765 else
1766 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1767
b323314b 1768 r->regnum = regnum;
74ca34ce
DJ
1769 }
1770
1771 /* Define the g/G packet format as the contents of each register
1772 with a remote protocol number, in order of ascending protocol
1773 number. */
1774
224c3ddb 1775 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1776 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1777 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1778 regnum++)
c21236dc
PA
1779 if (regs[regnum].pnum != -1)
1780 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1781
39ef2f62
CB
1782 std::sort (remote_regs, remote_regs + num_remote_regs,
1783 [] (const packet_reg *a, const packet_reg *b)
1784 { return a->pnum < b->pnum; });
74ca34ce
DJ
1785
1786 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1787 {
1788 remote_regs[regnum]->in_g_packet = 1;
1789 remote_regs[regnum]->offset = offset;
4a22f64d 1790 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1791 }
1792
c21236dc
PA
1793 return offset;
1794}
1795
1796/* Given the architecture described by GDBARCH, return the remote
1797 protocol register's number and the register's offset in the g/G
1798 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1799 If the target does not have a mapping for REGNUM, return false,
1800 otherwise, return true. */
1801
1802int
1803remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1804 int *pnum, int *poffset)
1805{
c21236dc
PA
1806 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1807
b80406ac 1808 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1809
b80406ac 1810 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1811
1812 *pnum = regs[regnum].pnum;
1813 *poffset = regs[regnum].offset;
1814
c21236dc
PA
1815 return *pnum != -1;
1816}
1817
9d6eea31 1818remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1819{
c21236dc
PA
1820 /* Use the architecture to build a regnum<->pnum table, which will be
1821 1:1 unless a feature set specifies otherwise. */
9d6eea31 1822 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1823
74ca34ce
DJ
1824 /* Record the maximum possible size of the g packet - it may turn out
1825 to be smaller. */
9d6eea31
PA
1826 this->sizeof_g_packet
1827 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1828
0df8b418 1829 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1830 remote stubs have a hardwired buffer size of 400 bytes
1831 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1832 as the maximum packet-size to ensure that the packet and an extra
1833 NUL character can always fit in the buffer. This stops GDB
1834 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1835 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1836 this->remote_packet_size = 400 - 1;
d01949b6 1837
ea9c271d 1838 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1839 this->actual_register_packet_size = 0;
ea9c271d
DJ
1840
1841 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1842 default, adjust the size accordingly. Remember that each byte is
1843 encoded as two characters. 32 is the overhead for the packet
1844 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1845 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1846 little. */
9d6eea31
PA
1847 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1848 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1849}
1850
6b8edb51
PA
1851/* Get a pointer to the current remote target. If not connected to a
1852 remote target, return NULL. */
1853
1854static remote_target *
1855get_current_remote_target ()
1856{
5b6d1e4f 1857 target_ops *proc_target = current_inferior ()->process_target ();
6b8edb51
PA
1858 return dynamic_cast<remote_target *> (proc_target);
1859}
1860
ea9c271d
DJ
1861/* Return the current allowed size of a remote packet. This is
1862 inferred from the current architecture, and should be used to
1863 limit the length of outgoing packets. */
6b8edb51
PA
1864long
1865remote_target::get_remote_packet_size ()
ea9c271d 1866{
be2a5f71 1867 struct remote_state *rs = get_remote_state ();
99d9c3b9
SM
1868 remote_arch_state *rsa
1869 = rs->get_remote_arch_state (current_inferior ()->arch ());
ea9c271d 1870
be2a5f71
DJ
1871 if (rs->explicit_packet_size)
1872 return rs->explicit_packet_size;
1873
ea9c271d 1874 return rsa->remote_packet_size;
d01949b6
AC
1875}
1876
ad10f812 1877static struct packet_reg *
5cd63fda
PA
1878packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1879 long regnum)
ad10f812 1880{
5cd63fda 1881 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1882 return NULL;
1883 else
ad10f812 1884 {
ea9c271d 1885 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1886
b323314b
AC
1887 gdb_assert (r->regnum == regnum);
1888 return r;
ad10f812 1889 }
ad10f812
AC
1890}
1891
1892static struct packet_reg *
5cd63fda
PA
1893packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1894 LONGEST pnum)
ad10f812 1895{
b323314b 1896 int i;
a744cf53 1897
5cd63fda 1898 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1899 {
ea9c271d 1900 struct packet_reg *r = &rsa->regs[i];
a744cf53 1901
b323314b
AC
1902 if (r->pnum == pnum)
1903 return r;
ad10f812
AC
1904 }
1905 return NULL;
d01949b6
AC
1906}
1907
9a7071a8
JB
1908/* Allow the user to specify what sequence to send to the remote
1909 when he requests a program interruption: Although ^C is usually
1910 what remote systems expect (this is the default, here), it is
1911 sometimes preferable to send a break. On other systems such
1912 as the Linux kernel, a break followed by g, which is Magic SysRq g
1913 is required in order to interrupt the execution. */
1914const char interrupt_sequence_control_c[] = "Ctrl-C";
1915const char interrupt_sequence_break[] = "BREAK";
1916const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1917static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1918 {
1919 interrupt_sequence_control_c,
1920 interrupt_sequence_break,
1921 interrupt_sequence_break_g,
1922 NULL
1923 };
1924static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1925
1926static void
1927show_interrupt_sequence (struct ui_file *file, int from_tty,
1928 struct cmd_list_element *c,
1929 const char *value)
1930{
1931 if (interrupt_sequence_mode == interrupt_sequence_control_c)
6cb06a8c
TT
1932 gdb_printf (file,
1933 _("Send the ASCII ETX character (Ctrl-c) "
1934 "to the remote target to interrupt the "
1935 "execution of the program.\n"));
9a7071a8 1936 else if (interrupt_sequence_mode == interrupt_sequence_break)
6cb06a8c
TT
1937 gdb_printf (file,
1938 _("send a break signal to the remote target "
1939 "to interrupt the execution of the program.\n"));
9a7071a8 1940 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
6cb06a8c
TT
1941 gdb_printf (file,
1942 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1943 "the remote target to interrupt the execution "
1944 "of Linux kernel.\n"));
9a7071a8 1945 else
f34652de 1946 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
9a7071a8
JB
1947 interrupt_sequence_mode);
1948}
6426a772 1949
9a7071a8
JB
1950/* This boolean variable specifies whether interrupt_sequence is sent
1951 to the remote target when gdb connects to it.
1952 This is mostly needed when you debug the Linux kernel: The Linux kernel
1953 expects BREAK g which is Magic SysRq g for connecting gdb. */
491144b5 1954static bool interrupt_on_connect = false;
c906108c 1955
9a7071a8
JB
1956/* This variable is used to implement the "set/show remotebreak" commands.
1957 Since these commands are now deprecated in favor of "set/show remote
1958 interrupt-sequence", it no longer has any effect on the code. */
491144b5 1959static bool remote_break;
c906108c 1960
9a7071a8 1961static void
eb4c3f4a 1962set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1963{
1964 if (remote_break)
1965 interrupt_sequence_mode = interrupt_sequence_break;
1966 else
1967 interrupt_sequence_mode = interrupt_sequence_control_c;
1968}
1969
1970static void
1971show_remotebreak (struct ui_file *file, int from_tty,
1972 struct cmd_list_element *c,
1973 const char *value)
1974{
1975}
1976
c906108c
SS
1977/* This variable sets the number of bits in an address that are to be
1978 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1979 leading zeros, the entire address would be sent. This variable
c906108c
SS
1980 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1981 initial implementation of remote.c restricted the address sent in
1982 memory packets to ``host::sizeof long'' bytes - (typically 32
1983 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1984 address was never sent. Since fixing this bug may cause a break in
85102364 1985 some remote targets this variable is principally provided to
23860348 1986 facilitate backward compatibility. */
c906108c 1987
883b9c6c 1988static unsigned int remote_address_size;
c906108c 1989
11cf8741 1990\f
cc0be08f
PA
1991/* The default max memory-write-packet-size, when the setting is
1992 "fixed". The 16k is historical. (It came from older GDB's using
1993 alloca for buffers and the knowledge (folklore?) that some hosts
1994 don't cope very well with large alloca calls.) */
1995#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
1996
1997/* The minimum remote packet size for memory transfers. Ensures we
1998 can write at least one byte. */
1999#define MIN_MEMORY_PACKET_SIZE 20
2000
cc0be08f
PA
2001/* Get the memory packet size, assuming it is fixed. */
2002
2003static long
2004get_fixed_memory_packet_size (struct memory_packet_config *config)
2005{
2006 gdb_assert (config->fixed_p);
2007
2008 if (config->size <= 0)
2009 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2010 else
2011 return config->size;
2012}
2013
11cf8741
JM
2014/* Compute the current size of a read/write packet. Since this makes
2015 use of ``actual_register_packet_size'' the computation is dynamic. */
2016
6b8edb51
PA
2017long
2018remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 2019{
d01949b6 2020 struct remote_state *rs = get_remote_state ();
99d9c3b9
SM
2021 remote_arch_state *rsa
2022 = rs->get_remote_arch_state (current_inferior ()->arch ());
ea9c271d 2023
11cf8741
JM
2024 long what_they_get;
2025 if (config->fixed_p)
cc0be08f 2026 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
2027 else
2028 {
ea9c271d 2029 what_they_get = get_remote_packet_size ();
23860348 2030 /* Limit the packet to the size specified by the user. */
11cf8741
JM
2031 if (config->size > 0
2032 && what_they_get > config->size)
2033 what_they_get = config->size;
be2a5f71
DJ
2034
2035 /* Limit it to the size of the targets ``g'' response unless we have
2036 permission from the stub to use a larger packet size. */
2037 if (rs->explicit_packet_size == 0
2038 && rsa->actual_register_packet_size > 0
2039 && what_they_get > rsa->actual_register_packet_size)
2040 what_they_get = rsa->actual_register_packet_size;
11cf8741 2041 }
a5c0808e
PA
2042 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2043 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
2044
2045 /* Make sure there is room in the global buffer for this packet
2046 (including its trailing NUL byte). */
8d64371b
TT
2047 if (rs->buf.size () < what_they_get + 1)
2048 rs->buf.resize (2 * what_they_get);
6d820c5c 2049
11cf8741
JM
2050 return what_they_get;
2051}
2052
0df8b418 2053/* Update the size of a read/write packet. If they user wants
23860348 2054 something really big then do a sanity check. */
11cf8741
JM
2055
2056static void
fe4c3ca0
CS
2057set_memory_packet_size (const char *args, struct memory_packet_config *config,
2058 bool target_connected)
11cf8741
JM
2059{
2060 int fixed_p = config->fixed_p;
2061 long size = config->size;
a744cf53 2062
11cf8741 2063 if (args == NULL)
fe4c3ca0 2064 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
11cf8741
JM
2065 else if (strcmp (args, "hard") == 0
2066 || strcmp (args, "fixed") == 0)
2067 fixed_p = 1;
2068 else if (strcmp (args, "soft") == 0
2069 || strcmp (args, "limit") == 0)
2070 fixed_p = 0;
2071 else
2072 {
2073 char *end;
a744cf53 2074
11cf8741
JM
2075 size = strtoul (args, &end, 0);
2076 if (args == end)
8a3fe4f8 2077 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
2078
2079 /* Instead of explicitly capping the size of a packet to or
2080 disallowing it, the user is allowed to set the size to
2081 something arbitrarily large. */
11cf8741 2082 }
a5c0808e 2083
23860348 2084 /* Extra checks? */
11cf8741
JM
2085 if (fixed_p && !config->fixed_p)
2086 {
cc0be08f
PA
2087 /* So that the query shows the correct value. */
2088 long query_size = (size <= 0
2089 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2090 : size);
2091
fe4c3ca0
CS
2092 if (target_connected
2093 && !query (_("The target may not be able to correctly handle a %s\n"
2094 "of %ld bytes. Change the packet size? "),
2095 config->name, query_size))
2096 error (_("Packet size not changed."));
2097 else if (!target_connected
2098 && !query (_("Future remote targets may not be able to "
2099 "correctly handle a %s\nof %ld bytes. Change the "
2100 "packet size for future remote targets? "),
2101 config->name, query_size))
8a3fe4f8 2102 error (_("Packet size not changed."));
11cf8741 2103 }
23860348 2104 /* Update the config. */
11cf8741
JM
2105 config->fixed_p = fixed_p;
2106 config->size = size;
fe4c3ca0
CS
2107
2108 const char *target_type = get_target_type_name (target_connected);
2109 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2110 args);
2111
11cf8741
JM
2112}
2113
fe4c3ca0
CS
2114/* Show the memory-read or write-packet size configuration CONFIG of the
2115 target REMOTE. If REMOTE is nullptr, the default configuration for future
2116 remote targets should be passed in CONFIG. */
2117
11cf8741 2118static void
fe4c3ca0 2119show_memory_packet_size (memory_packet_config *config, remote_target *remote)
11cf8741 2120{
fe4c3ca0
CS
2121 const char *target_type = get_target_type_name (remote != nullptr);
2122
cc0be08f 2123 if (config->size == 0)
fe4c3ca0 2124 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
cc0be08f 2125 else
fe4c3ca0
CS
2126 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2127 config->size);
2128
11cf8741 2129 if (config->fixed_p)
6cb06a8c
TT
2130 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2131 get_fixed_memory_packet_size (config));
11cf8741 2132 else
cc0be08f 2133 {
fe4c3ca0 2134 if (remote != nullptr)
6cb06a8c
TT
2135 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2136 remote->get_memory_packet_size (config));
cc0be08f 2137 else
0426ad51
TT
2138 gdb_puts ("The actual limit will be further reduced "
2139 "dependent on the target.\n");
cc0be08f 2140 }
11cf8741
JM
2141}
2142
fe4c3ca0
CS
2143/* Configure the memory-write-packet size of the currently selected target. If
2144 no target is available, the default configuration for future remote targets
2145 is configured. */
11cf8741
JM
2146
2147static void
ac88e2de 2148set_memory_write_packet_size (const char *args, int from_tty)
11cf8741 2149{
fe4c3ca0
CS
2150 remote_target *remote = get_current_remote_target ();
2151 if (remote != nullptr)
2152 {
2153 set_memory_packet_size
2154 (args, &remote->m_features.m_memory_write_packet_config, true);
2155 }
2156 else
2157 {
2158 memory_packet_config* config = &memory_write_packet_config;
2159 set_memory_packet_size (args, config, false);
2160 }
11cf8741
JM
2161}
2162
fe4c3ca0
CS
2163/* Display the memory-write-packet size of the currently selected target. If
2164 no target is available, the default configuration for future remote targets
2165 is shown. */
2166
11cf8741 2167static void
ac88e2de 2168show_memory_write_packet_size (const char *args, int from_tty)
11cf8741 2169{
fe4c3ca0
CS
2170 remote_target *remote = get_current_remote_target ();
2171 if (remote != nullptr)
2172 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2173 remote);
2174 else
2175 show_memory_packet_size (&memory_write_packet_config, nullptr);
11cf8741
JM
2176}
2177
055303e2
AB
2178/* Show the number of hardware watchpoints that can be used. */
2179
2180static void
2181show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2182 struct cmd_list_element *c,
2183 const char *value)
2184{
6cb06a8c
TT
2185 gdb_printf (file, _("The maximum number of target hardware "
2186 "watchpoints is %s.\n"), value);
055303e2
AB
2187}
2188
2189/* Show the length limit (in bytes) for hardware watchpoints. */
2190
2191static void
2192show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2193 struct cmd_list_element *c,
2194 const char *value)
2195{
6cb06a8c
TT
2196 gdb_printf (file, _("The maximum length (in bytes) of a target "
2197 "hardware watchpoint is %s.\n"), value);
055303e2
AB
2198}
2199
2200/* Show the number of hardware breakpoints that can be used. */
2201
2202static void
2203show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2204 struct cmd_list_element *c,
2205 const char *value)
2206{
6cb06a8c
TT
2207 gdb_printf (file, _("The maximum number of target hardware "
2208 "breakpoints is %s.\n"), value);
055303e2
AB
2209}
2210
6cc8564b
LM
2211/* Controls the maximum number of characters to display in the debug output
2212 for each remote packet. The remaining characters are omitted. */
2213
2214static int remote_packet_max_chars = 512;
2215
2216/* Show the maximum number of characters to display for each remote packet
2217 when remote debugging is enabled. */
2218
2219static void
2220show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2221 struct cmd_list_element *c,
2222 const char *value)
2223{
6cb06a8c
TT
2224 gdb_printf (file, _("Number of remote packet characters to "
2225 "display is %s.\n"), value);
6cc8564b
LM
2226}
2227
6b8edb51
PA
2228long
2229remote_target::get_memory_write_packet_size ()
11cf8741 2230{
fe4c3ca0 2231 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
11cf8741
JM
2232}
2233
fe4c3ca0
CS
2234/* Configure the memory-read-packet size of the currently selected target. If
2235 no target is available, the default configuration for future remote targets
2236 is adapted. */
11cf8741
JM
2237
2238static void
ac88e2de 2239set_memory_read_packet_size (const char *args, int from_tty)
11cf8741 2240{
fe4c3ca0
CS
2241 remote_target *remote = get_current_remote_target ();
2242 if (remote != nullptr)
2243 set_memory_packet_size
2244 (args, &remote->m_features.m_memory_read_packet_config, true);
2245 else
2246 {
2247 memory_packet_config* config = &memory_read_packet_config;
2248 set_memory_packet_size (args, config, false);
2249 }
2250
11cf8741
JM
2251}
2252
fe4c3ca0
CS
2253/* Display the memory-read-packet size of the currently selected target. If
2254 no target is available, the default configuration for future remote targets
2255 is shown. */
2256
11cf8741 2257static void
ac88e2de 2258show_memory_read_packet_size (const char *args, int from_tty)
11cf8741 2259{
fe4c3ca0
CS
2260 remote_target *remote = get_current_remote_target ();
2261 if (remote != nullptr)
2262 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2263 remote);
2264 else
2265 show_memory_packet_size (&memory_read_packet_config, nullptr);
11cf8741
JM
2266}
2267
6b8edb51
PA
2268long
2269remote_target::get_memory_read_packet_size ()
11cf8741 2270{
fe4c3ca0 2271 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
a744cf53 2272
11cf8741
JM
2273 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2274 extra buffer size argument before the memory read size can be
ea9c271d
DJ
2275 increased beyond this. */
2276 if (size > get_remote_packet_size ())
2277 size = get_remote_packet_size ();
11cf8741
JM
2278 return size;
2279}
2280
ff52c073 2281static enum packet_support packet_config_support (const packet_config *config);
5a2468f5 2282
4082afcc 2283
ff52c073
CS
2284static void
2285set_remote_protocol_packet_cmd (const char *args, int from_tty,
2286 cmd_list_element *c)
2287{
2288 remote_target *remote = get_current_remote_target ();
2289 gdb_assert (c->var.has_value ());
4082afcc 2290
ff52c073
CS
2291 auto *default_config = static_cast<packet_config *> (c->context ());
2292 const int packet_idx = std::distance (remote_protocol_packets,
2293 default_config);
fcef6471 2294
ff52c073
CS
2295 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2296 {
2297 const char *name = packets_descriptions[packet_idx].name;
2298 const auto_boolean value = c->var->get<auto_boolean> ();
2299 const char *support = get_packet_support_name (value);
2300 const char *target_type = get_target_type_name (remote != nullptr);
5a2468f5 2301
ff52c073
CS
2302 if (remote != nullptr)
2303 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2304 else
2305 remote_protocol_packets[packet_idx].detect = value;
2306
2307 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2308 target_type, support);
2309 return;
2310 }
2311
2312 internal_error (_("Could not find config for %s"), c->name);
2313}
5a2468f5
JM
2314
2315static void
ff52c073
CS
2316show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2317 remote_target *remote)
5a2468f5 2318{
a121b7c1 2319 const char *support = "internal-error";
ff52c073
CS
2320 const char *target_type = get_target_type_name (remote != nullptr);
2321
2322 packet_config *config;
2323 if (remote != nullptr)
2324 config = &remote->m_features.m_protocol_packets[which_packet];
2325 else
2326 config = &remote_protocol_packets[which_packet];
a744cf53 2327
4082afcc 2328 switch (packet_config_support (config))
5a2468f5
JM
2329 {
2330 case PACKET_ENABLE:
2331 support = "enabled";
2332 break;
2333 case PACKET_DISABLE:
2334 support = "disabled";
2335 break;
2336 case PACKET_SUPPORT_UNKNOWN:
2337 support = "unknown";
2338 break;
2339 }
2340 switch (config->detect)
2341 {
7f19b9a2 2342 case AUTO_BOOLEAN_AUTO:
6cb06a8c 2343 gdb_printf (file,
ff52c073
CS
2344 _("Support for the '%s' packet %s is \"auto\", "
2345 "currently %s.\n"),
2346 packets_descriptions[which_packet].name, target_type,
2347 support);
5a2468f5 2348 break;
7f19b9a2
AC
2349 case AUTO_BOOLEAN_TRUE:
2350 case AUTO_BOOLEAN_FALSE:
6cb06a8c 2351 gdb_printf (file,
ff52c073
CS
2352 _("Support for the '%s' packet %s is \"%s\".\n"),
2353 packets_descriptions[which_packet].name, target_type,
2354 get_packet_support_name (config->detect));
8e248173 2355 break;
5a2468f5
JM
2356 }
2357}
2358
2359static void
ff52c073 2360add_packet_config_cmd (const unsigned int which_packet, const char *name,
bb572ddd 2361 const char *title, int legacy)
d471ea57 2362{
ff52c073
CS
2363 packets_descriptions[which_packet].name = name;
2364 packets_descriptions[which_packet].title = title;
2365
2366 packet_config *config = &remote_protocol_packets[which_packet];
2367
8579fd13
AB
2368 gdb::unique_xmalloc_ptr<char> set_doc
2369 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2370 name, title);
2371 gdb::unique_xmalloc_ptr<char> show_doc
2372 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2373 name, title);
d471ea57 2374 /* set/show TITLE-packet {auto,on,off} */
8579fd13 2375 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
5e84b7ee 2376 set_show_commands cmds
8579fd13
AB
2377 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2378 &config->detect, set_doc.get (),
2379 show_doc.get (), NULL, /* help_doc */
ff52c073 2380 set_remote_protocol_packet_cmd,
5e84b7ee
SM
2381 show_remote_protocol_packet_cmd,
2382 &remote_set_cmdlist, &remote_show_cmdlist);
ff52c073
CS
2383 cmds.show->set_context (config);
2384 cmds.set->set_context (config);
5e84b7ee 2385
23860348 2386 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
2387 if (legacy)
2388 {
5f21c7aa
AB
2389 /* It's not clear who should take ownership of the LEGACY_NAME string
2390 created below, so, for now, place the string into a static vector
2391 which ensures the strings is released when GDB exits. */
2392 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2393 gdb::unique_xmalloc_ptr<char> legacy_name
8579fd13
AB
2394 = xstrprintf ("%s-packet", name);
2395 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
bb572ddd 2396 &remote_set_cmdlist);
8579fd13 2397 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
bb572ddd 2398 &remote_show_cmdlist);
5f21c7aa 2399 legacy_names.emplace_back (std::move (legacy_name));
d471ea57 2400 }
5a2468f5
JM
2401}
2402
d471ea57 2403static enum packet_result
a76d924d 2404packet_check_result (const char *buf)
5a2468f5 2405{
d471ea57 2406 if (buf[0] != '\0')
5a2468f5 2407 {
d471ea57 2408 /* The stub recognized the packet request. Check that the
23860348 2409 operation succeeded. */
a76d924d
DJ
2410 if (buf[0] == 'E'
2411 && isxdigit (buf[1]) && isxdigit (buf[2])
2412 && buf[3] == '\0')
85102364 2413 /* "Enn" - definitely an error. */
a76d924d
DJ
2414 return PACKET_ERROR;
2415
2416 /* Always treat "E." as an error. This will be used for
2417 more verbose error messages, such as E.memtypes. */
2418 if (buf[0] == 'E' && buf[1] == '.')
2419 return PACKET_ERROR;
2420
2421 /* The packet may or may not be OK. Just assume it is. */
2422 return PACKET_OK;
2423 }
2424 else
2425 /* The stub does not support the packet. */
2426 return PACKET_UNKNOWN;
2427}
2428
8d64371b
TT
2429static enum packet_result
2430packet_check_result (const gdb::char_vector &buf)
2431{
2432 return packet_check_result (buf.data ());
2433}
2434
ff52c073
CS
2435packet_result
2436remote_features::packet_ok (const char *buf, const int which_packet)
a76d924d 2437{
ff52c073
CS
2438 packet_config *config = &m_protocol_packets[which_packet];
2439 packet_description *descr = &packets_descriptions[which_packet];
2440
a76d924d
DJ
2441 enum packet_result result;
2442
4082afcc
PA
2443 if (config->detect != AUTO_BOOLEAN_TRUE
2444 && config->support == PACKET_DISABLE)
f34652de 2445 internal_error (_("packet_ok: attempt to use a disabled packet"));
4082afcc 2446
a76d924d
DJ
2447 result = packet_check_result (buf);
2448 switch (result)
2449 {
2450 case PACKET_OK:
2451 case PACKET_ERROR:
2452 /* The stub recognized the packet request. */
4082afcc 2453 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 2454 {
2189c312 2455 remote_debug_printf ("Packet %s (%s) is supported",
ff52c073 2456 descr->name, descr->title);
d471ea57 2457 config->support = PACKET_ENABLE;
d471ea57 2458 }
a76d924d
DJ
2459 break;
2460 case PACKET_UNKNOWN:
23860348 2461 /* The stub does not support the packet. */
4082afcc
PA
2462 if (config->detect == AUTO_BOOLEAN_AUTO
2463 && config->support == PACKET_ENABLE)
d471ea57 2464 {
4082afcc
PA
2465 /* If the stub previously indicated that the packet was
2466 supported then there is a protocol error. */
2467 error (_("Protocol error: %s (%s) conflicting enabled responses."),
ff52c073 2468 descr->name, descr->title);
4082afcc
PA
2469 }
2470 else if (config->detect == AUTO_BOOLEAN_TRUE)
2471 {
2472 /* The user set it wrong. */
2473 error (_("Enabled packet %s (%s) not recognized by stub"),
ff52c073 2474 descr->name, descr->title);
d471ea57 2475 }
4082afcc 2476
ff52c073
CS
2477 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2478 descr->title);
4082afcc 2479 config->support = PACKET_DISABLE;
a76d924d 2480 break;
5a2468f5 2481 }
a76d924d
DJ
2482
2483 return result;
5a2468f5
JM
2484}
2485
ff52c073
CS
2486packet_result
2487remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
f7e6eed5 2488{
ff52c073 2489 return packet_ok (buf.data (), which_packet);
f7e6eed5
PA
2490}
2491
4082afcc
PA
2492/* Returns whether a given packet or feature is supported. This takes
2493 into account the state of the corresponding "set remote foo-packet"
2494 command, which may be used to bypass auto-detection. */
dc8acb97 2495
4082afcc 2496static enum packet_support
ff52c073 2497packet_config_support (const packet_config *config)
4082afcc
PA
2498{
2499 switch (config->detect)
444abaca 2500 {
4082afcc
PA
2501 case AUTO_BOOLEAN_TRUE:
2502 return PACKET_ENABLE;
2503 case AUTO_BOOLEAN_FALSE:
2504 return PACKET_DISABLE;
2505 case AUTO_BOOLEAN_AUTO:
2506 return config->support;
2507 default:
557b4d76 2508 gdb_assert_not_reached ("bad switch");
444abaca 2509 }
4082afcc
PA
2510}
2511
ff52c073
CS
2512packet_support
2513remote_features::packet_support (int packet) const
4082afcc 2514{
ff52c073 2515 const packet_config *config = &m_protocol_packets[packet];
4082afcc 2516 return packet_config_support (config);
dc8acb97
MS
2517}
2518
5a2468f5 2519static void
444abaca
DJ
2520show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2521 struct cmd_list_element *c,
2522 const char *value)
5a2468f5 2523{
ff52c073 2524 remote_target *remote = get_current_remote_target ();
1d7fe7f0 2525 gdb_assert (c->var.has_value ());
5a2468f5 2526
ff52c073
CS
2527 auto *default_config = static_cast<packet_config *> (c->context ());
2528 const int packet_idx = std::distance (remote_protocol_packets,
2529 default_config);
2530
2531 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
444abaca 2532 {
ff52c073
CS
2533 show_packet_config_cmd (file, packet_idx, remote);
2534 return;
444abaca 2535 }
ff52c073 2536 internal_error (_("Could not find config for %s"), c->name);
5a2468f5
JM
2537}
2538
d471ea57
AC
2539/* Should we try one of the 'Z' requests? */
2540
2541enum Z_packet_type
2542{
2543 Z_PACKET_SOFTWARE_BP,
2544 Z_PACKET_HARDWARE_BP,
2545 Z_PACKET_WRITE_WP,
2546 Z_PACKET_READ_WP,
2547 Z_PACKET_ACCESS_WP,
2548 NR_Z_PACKET_TYPES
2549};
96baa820 2550
d471ea57 2551/* For compatibility with older distributions. Provide a ``set remote
23860348 2552 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2553
7f19b9a2 2554static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2555
2556static void
eb4c3f4a 2557set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2558 struct cmd_list_element *c)
96baa820 2559{
ff52c073 2560 remote_target *remote = get_current_remote_target ();
d471ea57 2561 int i;
a744cf53 2562
d471ea57 2563 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
ff52c073
CS
2564 {
2565 if (remote != nullptr)
2566 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2567 = remote_Z_packet_detect;
2568 else
2569 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2570 }
2571
2572 const char *support = get_packet_support_name (remote_Z_packet_detect);
2573 const char *target_type = get_target_type_name (remote != nullptr);
2574 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2575 support);
2576
96baa820
JM
2577}
2578
2579static void
08546159
AC
2580show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2581 struct cmd_list_element *c,
2582 const char *value)
96baa820 2583{
ff52c073 2584 remote_target *remote = get_current_remote_target ();
d471ea57 2585 int i;
a744cf53 2586
d471ea57 2587 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
ff52c073 2588 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2c2e7f87
LM
2589}
2590
cbb8991c
DB
2591/* Insert fork catchpoint target routine. If fork events are enabled
2592 then return success, nothing more to do. */
2593
f6ac5f3d
PA
2594int
2595remote_target::insert_fork_catchpoint (int pid)
cbb8991c 2596{
ff52c073 2597 return !m_features.remote_fork_event_p ();
cbb8991c
DB
2598}
2599
2600/* Remove fork catchpoint target routine. Nothing to do, just
2601 return success. */
2602
f6ac5f3d
PA
2603int
2604remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2605{
2606 return 0;
2607}
2608
2609/* Insert vfork catchpoint target routine. If vfork events are enabled
2610 then return success, nothing more to do. */
2611
f6ac5f3d
PA
2612int
2613remote_target::insert_vfork_catchpoint (int pid)
cbb8991c 2614{
ff52c073 2615 return !m_features.remote_vfork_event_p ();
cbb8991c
DB
2616}
2617
2618/* Remove vfork catchpoint target routine. Nothing to do, just
2619 return success. */
2620
f6ac5f3d
PA
2621int
2622remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2623{
2624 return 0;
2625}
2626
d46addbb
DB
2627/* Insert exec catchpoint target routine. If exec events are
2628 enabled, just return success. */
2629
f6ac5f3d
PA
2630int
2631remote_target::insert_exec_catchpoint (int pid)
d46addbb 2632{
ff52c073 2633 return !m_features.remote_exec_event_p ();
d46addbb
DB
2634}
2635
2636/* Remove exec catchpoint target routine. Nothing to do, just
2637 return success. */
2638
f6ac5f3d
PA
2639int
2640remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2641{
2642 return 0;
2643}
2644
c906108c
SS
2645\f
2646
ffdd69cf
TT
2647/* Take advantage of the fact that the TID field is not used, to tag
2648 special ptids with it set to != 0. */
2649static const ptid_t magic_null_ptid (42000, -1, 1);
2650static const ptid_t not_sent_ptid (42000, -2, 1);
2651static const ptid_t any_thread_ptid (42000, 0, 1);
79d7f229 2652
0b16c5cf
PA
2653/* Find out if the stub attached to PID (and hence GDB should offer to
2654 detach instead of killing it when bailing out). */
2655
6b8edb51
PA
2656int
2657remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2658{
2659 struct remote_state *rs = get_remote_state ();
bba74b36 2660 size_t size = get_remote_packet_size ();
0b16c5cf 2661
ff52c073 2662 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2663 return 0;
2664
ff52c073 2665 if (m_features.remote_multi_process_p ())
8d64371b 2666 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
0b16c5cf 2667 else
8d64371b 2668 xsnprintf (rs->buf.data (), size, "qAttached");
0b16c5cf
PA
2669
2670 putpkt (rs->buf);
aa7b36b8 2671 getpkt (&rs->buf);
0b16c5cf 2672
ff52c073 2673 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
0b16c5cf
PA
2674 {
2675 case PACKET_OK:
8d64371b 2676 if (strcmp (rs->buf.data (), "1") == 0)
0b16c5cf
PA
2677 return 1;
2678 break;
2679 case PACKET_ERROR:
8d64371b 2680 warning (_("Remote failure reply: %s"), rs->buf.data ());
0b16c5cf
PA
2681 break;
2682 case PACKET_UNKNOWN:
2683 break;
2684 }
2685
2686 return 0;
2687}
2688
49c62f2e
PA
2689/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2690 has been invented by GDB, instead of reported by the target. Since
2691 we can be connected to a remote system before before knowing about
2692 any inferior, mark the target with execution when we find the first
2693 inferior. If ATTACHED is 1, then we had just attached to this
2694 inferior. If it is 0, then we just created this inferior. If it
2695 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2696 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2697 attempt to open this inferior's executable as the main executable
2698 if no main executable is open already. */
1941c569 2699
6b8edb51 2700inferior *
9ab8741a 2701remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51 2702 int try_open_exec)
1941c569 2703{
1941c569
PA
2704 struct inferior *inf;
2705
0b16c5cf
PA
2706 /* Check whether this process we're learning about is to be
2707 considered attached, or if is to be considered to have been
2708 spawned by the stub. */
2709 if (attached == -1)
2710 attached = remote_query_attached (pid);
2711
99d9c3b9 2712 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
6c95b8df
PA
2713 {
2714 /* If the target shares code across all inferiors, then every
2715 attach adds a new inferior. */
2716 inf = add_inferior (pid);
2717
2718 /* ... and every inferior is bound to the same program space.
2719 However, each inferior may still have its own address
2720 space. */
2721 inf->aspace = maybe_new_address_space ();
2722 inf->pspace = current_program_space;
2723 }
2724 else
2725 {
2726 /* In the traditional debugging scenario, there's a 1-1 match
2727 between program/address spaces. We simply bind the inferior
2728 to the program space's address space. */
2729 inf = current_inferior ();
78f2c40a
PA
2730
2731 /* However, if the current inferior is already bound to a
2732 process, find some other empty inferior. */
2733 if (inf->pid != 0)
2734 {
2735 inf = nullptr;
2736 for (inferior *it : all_inferiors ())
2737 if (it->pid == 0)
2738 {
2739 inf = it;
2740 break;
2741 }
2742 }
2743 if (inf == nullptr)
2744 {
2745 /* Since all inferiors were already bound to a process, add
2746 a new inferior. */
2747 inf = add_inferior_with_spaces ();
2748 }
2749 switch_to_inferior_no_thread (inf);
02980c56 2750 inf->push_target (this);
6c95b8df
PA
2751 inferior_appeared (inf, pid);
2752 }
1941c569 2753
0b16c5cf 2754 inf->attach_flag = attached;
49c62f2e 2755 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2756
1b6e6f5c
GB
2757 /* If no main executable is currently open then attempt to
2758 open the file that was executed to create this inferior. */
835205d0 2759 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2760 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2761
a2fedca9
PW
2762 /* Check for exec file mismatch, and let the user solve it. */
2763 validate_exec_file (1);
2764
1941c569
PA
2765 return inf;
2766}
2767
7aabaf9d 2768static remote_thread_info *get_remote_thread_info (thread_info *thread);
5b6d1e4f
PA
2769static remote_thread_info *get_remote_thread_info (remote_target *target,
2770 ptid_t ptid);
85ad3aaf 2771
1941c569 2772/* Add thread PTID to GDB's thread list. Tag it as executing/running
b622494e
AB
2773 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2774 remote_state::starting_up flag) is true then the new thread is added
2775 silently, otherwise the new thread will be announced to the user. */
1941c569 2776
00431a78 2777thread_info *
b622494e
AB
2778remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2779 bool silent_p)
c906108c 2780{
b7ea362b 2781 struct remote_state *rs = get_remote_state ();
85ad3aaf 2782 struct thread_info *thread;
b7ea362b
PA
2783
2784 /* GDB historically didn't pull threads in the initial connection
2785 setup. If the remote target doesn't even have a concept of
2786 threads (e.g., a bare-metal target), even if internally we
2787 consider that a single-threaded target, mentioning a new thread
2788 might be confusing to the user. Be silent then, preserving the
2789 age old behavior. */
b622494e 2790 if (rs->starting_up || silent_p)
5b6d1e4f 2791 thread = add_thread_silent (this, ptid);
b7ea362b 2792 else
5b6d1e4f 2793 thread = add_thread (this, ptid);
1941c569 2794
c9d22089
SM
2795 /* We start by assuming threads are resumed. That state then gets updated
2796 when we process a matching stop reply. */
2797 get_remote_thread_info (thread)->set_resumed ();
2798
5b6d1e4f
PA
2799 set_executing (this, ptid, executing);
2800 set_running (this, ptid, running);
00431a78
PA
2801
2802 return thread;
1941c569
PA
2803}
2804
2805/* Come here when we learn about a thread id from the remote target.
2806 It may be the first time we hear about such thread, so take the
2807 opportunity to add it to GDB's thread list. In case this is the
2808 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2809 GDB's inferior list as well. EXECUTING indicates whether the
2810 thread is (internally) executing or stopped. */
1941c569 2811
6b8edb51 2812void
8a82de58 2813remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
1941c569 2814{
0d5b594f
PA
2815 /* In non-stop mode, we assume new found threads are (externally)
2816 running until proven otherwise with a stop reply. In all-stop,
2817 we can only get here if all threads are stopped. */
8a82de58 2818 bool running = target_is_non_stop_p ();
0d5b594f 2819
c906108c
SS
2820 /* If this is a new thread, add it to GDB's thread list.
2821 If we leave it up to WFI to do this, bad things will happen. */
82f73884 2822
9213a6d7 2823 thread_info *tp = this->find_thread (currthread);
00431a78 2824 if (tp != NULL && tp->state == THREAD_EXITED)
82f73884
PA
2825 {
2826 /* We're seeing an event on a thread id we knew had exited.
2827 This has to be a new thread reusing the old id. Add it. */
b622494e 2828 remote_add_thread (currthread, running, executing, false);
82f73884
PA
2829 return;
2830 }
2831
5b6d1e4f 2832 if (!in_thread_list (this, currthread))
c0a2216e 2833 {
1941c569 2834 struct inferior *inf = NULL;
e99b03dc 2835 int pid = currthread.pid ();
1941c569 2836
0e998d96 2837 if (inferior_ptid.is_pid ()
e99b03dc 2838 && pid == inferior_ptid.pid ())
c0a2216e
PA
2839 {
2840 /* inferior_ptid has no thread member yet. This can happen
2841 with the vAttach -> remote_wait,"TAAthread:" path if the
2842 stub doesn't support qC. This is the first stop reported
2843 after an attach, so this is the main thread. Update the
2844 ptid in the thread list. */
5b6d1e4f
PA
2845 if (in_thread_list (this, ptid_t (pid)))
2846 thread_change_ptid (this, inferior_ptid, currthread);
bad34192
PA
2847 else
2848 {
0ac55310 2849 thread_info *thr
b622494e 2850 = remote_add_thread (currthread, running, executing, false);
0ac55310 2851 switch_to_thread (thr);
bad34192 2852 }
dc146f7c 2853 return;
c0a2216e 2854 }
82f73884 2855
d7e15655 2856 if (magic_null_ptid == inferior_ptid)
c0a2216e
PA
2857 {
2858 /* inferior_ptid is not set yet. This can happen with the
2859 vRun -> remote_wait,"TAAthread:" path if the stub
2860 doesn't support qC. This is the first stop reported
2861 after an attach, so this is the main thread. Update the
2862 ptid in the thread list. */
5b6d1e4f 2863 thread_change_ptid (this, inferior_ptid, currthread);
82f73884 2864 return;
c0a2216e 2865 }
82f73884 2866
29c87f7f
PA
2867 /* When connecting to a target remote, or to a target
2868 extended-remote which already was debugging an inferior, we
2869 may not know about it yet. Add it before adding its child
2870 thread, so notifications are emitted in a sensible order. */
5b6d1e4f 2871 if (find_inferior_pid (this, currthread.pid ()) == NULL)
49c62f2e 2872 {
ff52c073 2873 bool fake_pid_p = !m_features.remote_multi_process_p ();
49c62f2e
PA
2874
2875 inf = remote_add_inferior (fake_pid_p,
e99b03dc 2876 currthread.pid (), -1, 1);
49c62f2e 2877 }
29c87f7f 2878
82f73884 2879 /* This is really a new thread. Add it. */
00431a78 2880 thread_info *new_thr
b622494e 2881 = remote_add_thread (currthread, running, executing, false);
1941c569
PA
2882
2883 /* If we found a new inferior, let the common code do whatever
2884 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2885 breakpoints), unless we're just setting up an all-stop
2886 connection. */
1941c569 2887 if (inf != NULL)
b7ea362b
PA
2888 {
2889 struct remote_state *rs = get_remote_state ();
2890
6efcd9a8 2891 if (!rs->starting_up)
00431a78 2892 notice_new_inferior (new_thr, executing, 0);
b7ea362b 2893 }
c0a2216e 2894 }
c906108c
SS
2895}
2896
85ad3aaf 2897/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2898
7aabaf9d
SM
2899static remote_thread_info *
2900get_remote_thread_info (thread_info *thread)
dc146f7c 2901{
85ad3aaf 2902 gdb_assert (thread != NULL);
dc146f7c 2903
85ad3aaf 2904 if (thread->priv == NULL)
7aabaf9d 2905 thread->priv.reset (new remote_thread_info);
dc146f7c 2906
98ed24fb 2907 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2908}
2909
5b6d1e4f
PA
2910/* Return PTID's private thread data, creating it if necessary. */
2911
7aabaf9d 2912static remote_thread_info *
5b6d1e4f 2913get_remote_thread_info (remote_target *target, ptid_t ptid)
85ad3aaf 2914{
9213a6d7 2915 thread_info *thr = target->find_thread (ptid);
00431a78 2916 return get_remote_thread_info (thr);
dc146f7c
VP
2917}
2918
74531fed
PA
2919/* Call this function as a result of
2920 1) A halt indication (T packet) containing a thread id
2921 2) A direct query of currthread
0df8b418 2922 3) Successful execution of set thread */
74531fed
PA
2923
2924static void
47f8a51d 2925record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2926{
47f8a51d 2927 rs->general_thread = currthread;
74531fed
PA
2928}
2929
89be2091
DJ
2930/* If 'QPassSignals' is supported, tell the remote stub what signals
2931 it can simply pass through to the inferior without reporting. */
2932
f6ac5f3d 2933void
adc6a863 2934remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
89be2091 2935{
ff52c073 2936 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2937 {
2938 char *pass_packet, *p;
adc6a863 2939 int count = 0;
747dc59d 2940 struct remote_state *rs = get_remote_state ();
89be2091 2941
adc6a863
PA
2942 gdb_assert (pass_signals.size () < 256);
2943 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2944 {
2455069d 2945 if (pass_signals[i])
89be2091
DJ
2946 count++;
2947 }
224c3ddb 2948 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2949 strcpy (pass_packet, "QPassSignals:");
2950 p = pass_packet + strlen (pass_packet);
adc6a863 2951 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2952 {
2455069d 2953 if (pass_signals[i])
89be2091
DJ
2954 {
2955 if (i >= 16)
2956 *p++ = tohex (i >> 4);
2957 *p++ = tohex (i & 15);
2958 if (count)
2959 *p++ = ';';
2960 else
2961 break;
2962 count--;
2963 }
2964 }
2965 *p = 0;
747dc59d 2966 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2967 {
89be2091 2968 putpkt (pass_packet);
aa7b36b8 2969 getpkt (&rs->buf);
ff52c073 2970 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
84d53fa9 2971 xfree (rs->last_pass_packet);
747dc59d 2972 rs->last_pass_packet = pass_packet;
89be2091
DJ
2973 }
2974 else
2975 xfree (pass_packet);
2976 }
2977}
2978
82075af2
JS
2979/* If 'QCatchSyscalls' is supported, tell the remote stub
2980 to report syscalls to GDB. */
2981
f6ac5f3d
PA
2982int
2983remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2984 gdb::array_view<const int> syscall_counts)
82075af2 2985{
b80406ac 2986 const char *catch_packet;
82075af2
JS
2987 enum packet_result result;
2988 int n_sysno = 0;
2989
ff52c073 2990 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
82075af2
JS
2991 {
2992 /* Not supported. */
2993 return 1;
2994 }
2995
649a140c 2996 if (needed && any_count == 0)
82075af2 2997 {
649a140c
PA
2998 /* Count how many syscalls are to be caught. */
2999 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 3000 {
649a140c 3001 if (syscall_counts[i] != 0)
82075af2
JS
3002 n_sysno++;
3003 }
3004 }
3005
2189c312
SM
3006 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3007 pid, needed, any_count, n_sysno);
82075af2 3008
1b81856f 3009 std::string built_packet;
82075af2
JS
3010 if (needed)
3011 {
3012 /* Prepare a packet with the sysno list, assuming max 8+1
3013 characters for a sysno. If the resulting packet size is too
3014 big, fallback on the non-selective packet. */
3015 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
3016 built_packet.reserve (maxpktsz);
3017 built_packet = "QCatchSyscalls:1";
649a140c 3018 if (any_count == 0)
82075af2 3019 {
649a140c
PA
3020 /* Add in each syscall to be caught. */
3021 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 3022 {
649a140c
PA
3023 if (syscall_counts[i] != 0)
3024 string_appendf (built_packet, ";%zx", i);
82075af2
JS
3025 }
3026 }
1b81856f 3027 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
3028 {
3029 /* catch_packet too big. Fallback to less efficient
3030 non selective mode, with GDB doing the filtering. */
b80406ac 3031 catch_packet = "QCatchSyscalls:1";
82075af2 3032 }
b80406ac 3033 else
1b81856f 3034 catch_packet = built_packet.c_str ();
82075af2
JS
3035 }
3036 else
b80406ac 3037 catch_packet = "QCatchSyscalls:0";
82075af2 3038
b80406ac 3039 struct remote_state *rs = get_remote_state ();
82075af2 3040
b80406ac 3041 putpkt (catch_packet);
aa7b36b8 3042 getpkt (&rs->buf);
ff52c073 3043 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
b80406ac
TT
3044 if (result == PACKET_OK)
3045 return 0;
3046 else
3047 return -1;
82075af2
JS
3048}
3049
9b224c5e
PA
3050/* If 'QProgramSignals' is supported, tell the remote stub what
3051 signals it should pass through to the inferior when detaching. */
3052
f6ac5f3d 3053void
adc6a863 3054remote_target::program_signals (gdb::array_view<const unsigned char> signals)
9b224c5e 3055{
ff52c073 3056 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
3057 {
3058 char *packet, *p;
adc6a863 3059 int count = 0;
5e4a05c4 3060 struct remote_state *rs = get_remote_state ();
9b224c5e 3061
adc6a863
PA
3062 gdb_assert (signals.size () < 256);
3063 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
3064 {
3065 if (signals[i])
3066 count++;
3067 }
224c3ddb 3068 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
3069 strcpy (packet, "QProgramSignals:");
3070 p = packet + strlen (packet);
adc6a863 3071 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
3072 {
3073 if (signal_pass_state (i))
3074 {
3075 if (i >= 16)
3076 *p++ = tohex (i >> 4);
3077 *p++ = tohex (i & 15);
3078 if (count)
3079 *p++ = ';';
3080 else
3081 break;
3082 count--;
3083 }
3084 }
3085 *p = 0;
5e4a05c4
TT
3086 if (!rs->last_program_signals_packet
3087 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 3088 {
9b224c5e 3089 putpkt (packet);
aa7b36b8 3090 getpkt (&rs->buf);
ff52c073 3091 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
5e4a05c4
TT
3092 xfree (rs->last_program_signals_packet);
3093 rs->last_program_signals_packet = packet;
9b224c5e
PA
3094 }
3095 else
3096 xfree (packet);
3097 }
3098}
3099
79d7f229
PA
3100/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3101 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3102 thread. If GEN is set, set the general thread, if not, then set
3103 the step/continue thread. */
6b8edb51
PA
3104void
3105remote_target::set_thread (ptid_t ptid, int gen)
c906108c 3106{
d01949b6 3107 struct remote_state *rs = get_remote_state ();
47f8a51d 3108 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
8d64371b
TT
3109 char *buf = rs->buf.data ();
3110 char *endbuf = buf + get_remote_packet_size ();
c906108c 3111
d7e15655 3112 if (state == ptid)
c906108c
SS
3113 return;
3114
79d7f229
PA
3115 *buf++ = 'H';
3116 *buf++ = gen ? 'g' : 'c';
d7e15655 3117 if (ptid == magic_null_ptid)
79d7f229 3118 xsnprintf (buf, endbuf - buf, "0");
d7e15655 3119 else if (ptid == any_thread_ptid)
79d7f229 3120 xsnprintf (buf, endbuf - buf, "0");
d7e15655 3121 else if (ptid == minus_one_ptid)
79d7f229
PA
3122 xsnprintf (buf, endbuf - buf, "-1");
3123 else
82f73884 3124 write_ptid (buf, endbuf, ptid);
79d7f229 3125 putpkt (rs->buf);
aa7b36b8 3126 getpkt (&rs->buf);
c906108c 3127 if (gen)
47f8a51d 3128 rs->general_thread = ptid;
c906108c 3129 else
47f8a51d 3130 rs->continue_thread = ptid;
c906108c 3131}
79d7f229 3132
6b8edb51
PA
3133void
3134remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
3135{
3136 set_thread (ptid, 1);
3137}
3138
6b8edb51
PA
3139void
3140remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
3141{
3142 set_thread (ptid, 0);
3143}
3144
3c9c4b83
PA
3145/* Change the remote current process. Which thread within the process
3146 ends up selected isn't important, as long as it is the same process
3147 as what INFERIOR_PTID points to.
3148
3149 This comes from that fact that there is no explicit notion of
3150 "selected process" in the protocol. The selected process for
3151 general operations is the process the selected general thread
3152 belongs to. */
3153
6b8edb51
PA
3154void
3155remote_target::set_general_process ()
3c9c4b83 3156{
3c9c4b83 3157 /* If the remote can't handle multiple processes, don't bother. */
ff52c073 3158 if (!m_features.remote_multi_process_p ())
3c9c4b83
PA
3159 return;
3160
ff52c073
CS
3161 remote_state *rs = get_remote_state ();
3162
3c9c4b83
PA
3163 /* We only need to change the remote current thread if it's pointing
3164 at some other process. */
e99b03dc 3165 if (rs->general_thread.pid () != inferior_ptid.pid ())
3c9c4b83
PA
3166 set_general_thread (inferior_ptid);
3167}
3168
c906108c 3169\f
7d1a114c
PA
3170/* Return nonzero if this is the main thread that we made up ourselves
3171 to model non-threaded targets as single-threaded. */
c906108c
SS
3172
3173static int
f6ac5f3d 3174remote_thread_always_alive (ptid_t ptid)
c906108c 3175{
d7e15655 3176 if (ptid == magic_null_ptid)
c0a2216e
PA
3177 /* The main thread is always alive. */
3178 return 1;
3179
e38504b3 3180 if (ptid.pid () != 0 && ptid.lwp () == 0)
c0a2216e
PA
3181 /* The main thread is always alive. This can happen after a
3182 vAttach, if the remote side doesn't support
3183 multi-threading. */
3184 return 1;
3185
7d1a114c
PA
3186 return 0;
3187}
3188
3189/* Return nonzero if the thread PTID is still alive on the remote
3190 system. */
3191
57810aa7 3192bool
f6ac5f3d 3193remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
3194{
3195 struct remote_state *rs = get_remote_state ();
3196 char *p, *endp;
3197
3198 /* Check if this is a thread that we made up ourselves to model
3199 non-threaded targets as single-threaded. */
f6ac5f3d 3200 if (remote_thread_always_alive (ptid))
7d1a114c
PA
3201 return 1;
3202
8d64371b
TT
3203 p = rs->buf.data ();
3204 endp = p + get_remote_packet_size ();
82f73884
PA
3205
3206 *p++ = 'T';
3207 write_ptid (p, endp, ptid);
3208
2e9f7625 3209 putpkt (rs->buf);
aa7b36b8 3210 getpkt (&rs->buf);
2e9f7625 3211 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
3212}
3213
79efa585
SM
3214/* Return a pointer to a thread name if we know it and NULL otherwise.
3215 The thread_info object owns the memory for the name. */
3216
f6ac5f3d
PA
3217const char *
3218remote_target::thread_name (struct thread_info *info)
79efa585
SM
3219{
3220 if (info->priv != NULL)
a9334058
SM
3221 {
3222 const std::string &name = get_remote_thread_info (info)->name;
3223 return !name.empty () ? name.c_str () : NULL;
3224 }
79efa585
SM
3225
3226 return NULL;
3227}
3228
c906108c
SS
3229/* About these extended threadlist and threadinfo packets. They are
3230 variable length packets but, the fields within them are often fixed
30baf67b 3231 length. They are redundant enough to send over UDP as is the
c906108c
SS
3232 remote protocol in general. There is a matching unit test module
3233 in libstub. */
3234
23860348 3235/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 3236 libstub protocol encoding, and remote.c. It is not particularly
33b5899f 3237 changeable. */
cce74817
JM
3238
3239/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 3240 Plan to fix this. */
cce74817 3241
23860348 3242typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 3243
9d1f7ab2 3244/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 3245 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
3246
3247struct gdb_ext_thread_info
c5aa993b 3248 {
23860348 3249 threadref threadid; /* External form of thread reference. */
2bc416ba 3250 int active; /* Has state interesting to GDB?
23860348 3251 regs, stack. */
2bc416ba 3252 char display[256]; /* Brief state display, name,
cedea757 3253 blocked/suspended. */
23860348 3254 char shortname[32]; /* To be used to name threads. */
2bc416ba 3255 char more_display[256]; /* Long info, statistics, queue depth,
23860348 3256 whatever. */
c5aa993b 3257 };
cce74817
JM
3258
3259/* The volume of remote transfers can be limited by submitting
3260 a mask containing bits specifying the desired information.
3261 Use a union of these values as the 'selection' parameter to
0df8b418 3262 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
3263
3264#define TAG_THREADID 1
3265#define TAG_EXISTS 2
3266#define TAG_DISPLAY 4
3267#define TAG_THREADNAME 8
c5aa993b 3268#define TAG_MOREDISPLAY 16
cce74817 3269
23860348 3270#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 3271
cecb1912 3272static const char *unpack_nibble (const char *buf, int *val);
cce74817 3273
cecb1912 3274static const char *unpack_byte (const char *buf, int *value);
cce74817 3275
a14ed312 3276static char *pack_int (char *buf, int value);
cce74817 3277
cecb1912 3278static const char *unpack_int (const char *buf, int *value);
cce74817 3279
cecb1912 3280static const char *unpack_string (const char *src, char *dest, int length);
cce74817 3281
23860348 3282static char *pack_threadid (char *pkt, threadref *id);
cce74817 3283
cecb1912 3284static const char *unpack_threadid (const char *inbuf, threadref *id);
cce74817 3285
23860348 3286void int_to_threadref (threadref *id, int value);
cce74817 3287
23860348 3288static int threadref_to_int (threadref *ref);
cce74817 3289
23860348 3290static void copy_threadref (threadref *dest, threadref *src);
cce74817 3291
23860348 3292static int threadmatch (threadref *dest, threadref *src);
cce74817 3293
2bc416ba 3294static char *pack_threadinfo_request (char *pkt, int mode,
23860348 3295 threadref *id);
cce74817 3296
a14ed312
KB
3297static char *pack_threadlist_request (char *pkt, int startflag,
3298 int threadcount,
23860348 3299 threadref *nextthread);
cce74817 3300
23860348 3301static int remote_newthread_step (threadref *ref, void *context);
cce74817 3302
82f73884
PA
3303
3304/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3305 buffer we're allowed to write to. Returns
3306 BUF+CHARACTERS_WRITTEN. */
3307
6b8edb51
PA
3308char *
3309remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
3310{
3311 int pid, tid;
82f73884 3312
ff52c073 3313 if (m_features.remote_multi_process_p ())
82f73884 3314 {
e99b03dc 3315 pid = ptid.pid ();
82f73884
PA
3316 if (pid < 0)
3317 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3318 else
3319 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3320 }
e38504b3 3321 tid = ptid.lwp ();
82f73884
PA
3322 if (tid < 0)
3323 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3324 else
3325 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3326
3327 return buf;
3328}
3329
256642e8
PA
3330/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3331 last parsed char. Returns null_ptid if no thread id is found, and
3332 throws an error if the thread id has an invalid format. */
82f73884
PA
3333
3334static ptid_t
256642e8 3335read_ptid (const char *buf, const char **obuf)
82f73884 3336{
256642e8
PA
3337 const char *p = buf;
3338 const char *pp;
82f73884 3339 ULONGEST pid = 0, tid = 0;
82f73884
PA
3340
3341 if (*p == 'p')
3342 {
3343 /* Multi-process ptid. */
3344 pp = unpack_varlen_hex (p + 1, &pid);
3345 if (*pp != '.')
b37520b6 3346 error (_("invalid remote ptid: %s"), p);
82f73884
PA
3347
3348 p = pp;
3349 pp = unpack_varlen_hex (p + 1, &tid);
3350 if (obuf)
3351 *obuf = pp;
184ea2f7 3352 return ptid_t (pid, tid);
82f73884
PA
3353 }
3354
3355 /* No multi-process. Just a tid. */
3356 pp = unpack_varlen_hex (p, &tid);
3357
c9f35b34
KB
3358 /* Return null_ptid when no thread id is found. */
3359 if (p == pp)
3360 {
3361 if (obuf)
3362 *obuf = pp;
3363 return null_ptid;
3364 }
3365
2f761de2
TBA
3366 /* Since the stub is not sending a process id, default to what's
3367 current_inferior, unless it doesn't have a PID yet. If so,
ca19bf23
PA
3368 then since there's no way to know the pid of the reported
3369 threads, use the magic number. */
2f761de2
TBA
3370 inferior *inf = current_inferior ();
3371 if (inf->pid == 0)
e99b03dc 3372 pid = magic_null_ptid.pid ();
ca19bf23 3373 else
2f761de2 3374 pid = inf->pid;
82f73884
PA
3375
3376 if (obuf)
3377 *obuf = pp;
184ea2f7 3378 return ptid_t (pid, tid);
82f73884
PA
3379}
3380
c906108c 3381static int
fba45db2 3382stubhex (int ch)
c906108c
SS
3383{
3384 if (ch >= 'a' && ch <= 'f')
3385 return ch - 'a' + 10;
3386 if (ch >= '0' && ch <= '9')
3387 return ch - '0';
3388 if (ch >= 'A' && ch <= 'F')
3389 return ch - 'A' + 10;
3390 return -1;
3391}
3392
3393static int
cecb1912 3394stub_unpack_int (const char *buff, int fieldlength)
c906108c
SS
3395{
3396 int nibble;
3397 int retval = 0;
3398
3399 while (fieldlength)
3400 {
3401 nibble = stubhex (*buff++);
3402 retval |= nibble;
3403 fieldlength--;
3404 if (fieldlength)
3405 retval = retval << 4;
3406 }
3407 return retval;
3408}
3409
cecb1912
SM
3410static const char *
3411unpack_nibble (const char *buf, int *val)
c906108c 3412{
b7589f7d 3413 *val = fromhex (*buf++);
c906108c
SS
3414 return buf;
3415}
3416
cecb1912
SM
3417static const char *
3418unpack_byte (const char *buf, int *value)
c906108c
SS
3419{
3420 *value = stub_unpack_int (buf, 2);
3421 return buf + 2;
3422}
3423
3424static char *
fba45db2 3425pack_int (char *buf, int value)
c906108c
SS
3426{
3427 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3428 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3429 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3430 buf = pack_hex_byte (buf, (value & 0xff));
3431 return buf;
3432}
3433
cecb1912
SM
3434static const char *
3435unpack_int (const char *buf, int *value)
c906108c
SS
3436{
3437 *value = stub_unpack_int (buf, 8);
3438 return buf + 8;
3439}
3440
23860348 3441#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3442static char *pack_string (char *pkt, char *string);
c906108c
SS
3443
3444static char *
fba45db2 3445pack_string (char *pkt, char *string)
c906108c
SS
3446{
3447 char ch;
3448 int len;
3449
3450 len = strlen (string);
3451 if (len > 200)
23860348 3452 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3453 pkt = pack_hex_byte (pkt, len);
3454 while (len-- > 0)
3455 {
3456 ch = *string++;
3457 if ((ch == '\0') || (ch == '#'))
23860348 3458 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3459 *pkt++ = ch;
3460 }
3461 return pkt;
3462}
3463#endif /* 0 (unused) */
3464
cecb1912
SM
3465static const char *
3466unpack_string (const char *src, char *dest, int length)
c906108c
SS
3467{
3468 while (length--)
3469 *dest++ = *src++;
3470 *dest = '\0';
3471 return src;
3472}
3473
3474static char *
fba45db2 3475pack_threadid (char *pkt, threadref *id)
c906108c
SS
3476{
3477 char *limit;
3478 unsigned char *altid;
3479
3480 altid = (unsigned char *) id;
3481 limit = pkt + BUF_THREAD_ID_SIZE;
3482 while (pkt < limit)
3483 pkt = pack_hex_byte (pkt, *altid++);
3484 return pkt;
3485}
3486
3487
cecb1912
SM
3488static const char *
3489unpack_threadid (const char *inbuf, threadref *id)
c906108c
SS
3490{
3491 char *altref;
cecb1912 3492 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
c906108c
SS
3493 int x, y;
3494
3495 altref = (char *) id;
3496
3497 while (inbuf < limit)
3498 {
3499 x = stubhex (*inbuf++);
3500 y = stubhex (*inbuf++);
3501 *altref++ = (x << 4) | y;
3502 }
3503 return inbuf;
3504}
3505
3506/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3507 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3508 to use 64bit thread references internally. This is an adapter
3509 function. */
3510
3511void
fba45db2 3512int_to_threadref (threadref *id, int value)
c906108c
SS
3513{
3514 unsigned char *scan;
3515
3516 scan = (unsigned char *) id;
3517 {
3518 int i = 4;
3519 while (i--)
3520 *scan++ = 0;
3521 }
3522 *scan++ = (value >> 24) & 0xff;
3523 *scan++ = (value >> 16) & 0xff;
3524 *scan++ = (value >> 8) & 0xff;
3525 *scan++ = (value & 0xff);
3526}
3527
3528static int
fba45db2 3529threadref_to_int (threadref *ref)
c906108c
SS
3530{
3531 int i, value = 0;
3532 unsigned char *scan;
3533
cfd77fa1 3534 scan = *ref;
c906108c
SS
3535 scan += 4;
3536 i = 4;
3537 while (i-- > 0)
3538 value = (value << 8) | ((*scan++) & 0xff);
3539 return value;
3540}
3541
3542static void
fba45db2 3543copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3544{
3545 int i;
3546 unsigned char *csrc, *cdest;
3547
3548 csrc = (unsigned char *) src;
3549 cdest = (unsigned char *) dest;
3550 i = 8;
3551 while (i--)
3552 *cdest++ = *csrc++;
3553}
3554
3555static int
fba45db2 3556threadmatch (threadref *dest, threadref *src)
c906108c 3557{
23860348 3558 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3559#if 0
3560 unsigned char *srcp, *destp;
3561 int i, result;
3562 srcp = (char *) src;
3563 destp = (char *) dest;
3564
3565 result = 1;
3566 while (i-- > 0)
3567 result &= (*srcp++ == *destp++) ? 1 : 0;
3568 return result;
3569#endif
3570 return 1;
3571}
3572
3573/*
c5aa993b
JM
3574 threadid:1, # always request threadid
3575 context_exists:2,
3576 display:4,
3577 unique_name:8,
3578 more_display:16
3579 */
c906108c
SS
3580
3581/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3582
3583static char *
fba45db2 3584pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3585{
23860348
MS
3586 *pkt++ = 'q'; /* Info Query */
3587 *pkt++ = 'P'; /* process or thread info */
3588 pkt = pack_int (pkt, mode); /* mode */
c906108c 3589 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3590 *pkt = '\0'; /* terminate */
c906108c
SS
3591 return pkt;
3592}
3593
23860348 3594/* These values tag the fields in a thread info response packet. */
c906108c 3595/* Tagging the fields allows us to request specific fields and to
23860348 3596 add more fields as time goes by. */
c906108c 3597
23860348 3598#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3599#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3600 fetch registers and its stack? */
c5aa993b 3601#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3602#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3603#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3604 the process. */
c906108c 3605
6b8edb51 3606int
cecb1912 3607remote_target::remote_unpack_thread_info_response (const char *pkt,
6b8edb51
PA
3608 threadref *expectedref,
3609 gdb_ext_thread_info *info)
c906108c 3610{
d01949b6 3611 struct remote_state *rs = get_remote_state ();
c906108c 3612 int mask, length;
cfd77fa1 3613 int tag;
c906108c 3614 threadref ref;
cecb1912 3615 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
c906108c
SS
3616 int retval = 1;
3617
23860348 3618 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3619 info->active = 0;
3620 info->display[0] = '\0';
3621 info->shortname[0] = '\0';
3622 info->more_display[0] = '\0';
3623
23860348
MS
3624 /* Assume the characters indicating the packet type have been
3625 stripped. */
c906108c
SS
3626 pkt = unpack_int (pkt, &mask); /* arg mask */
3627 pkt = unpack_threadid (pkt, &ref);
3628
3629 if (mask == 0)
8a3fe4f8 3630 warning (_("Incomplete response to threadinfo request."));
c906108c 3631 if (!threadmatch (&ref, expectedref))
23860348 3632 { /* This is an answer to a different request. */
8a3fe4f8 3633 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3634 return 0;
3635 }
3636 copy_threadref (&info->threadid, &ref);
3637
405feb71 3638 /* Loop on tagged fields , try to bail if something goes wrong. */
c906108c 3639
23860348
MS
3640 /* Packets are terminated with nulls. */
3641 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3642 {
3643 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3644 pkt = unpack_byte (pkt, &length); /* length */
3645 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3646 {
8a3fe4f8 3647 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3648 retval = 0;
3649 break;
3650 }
3651 if (tag == TAG_THREADID)
3652 {
3653 if (length != 16)
3654 {
8a3fe4f8 3655 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3656 retval = 0;
3657 break;
3658 }
3659 pkt = unpack_threadid (pkt, &ref);
3660 mask = mask & ~TAG_THREADID;
3661 continue;
3662 }
3663 if (tag == TAG_EXISTS)
3664 {
3665 info->active = stub_unpack_int (pkt, length);
3666 pkt += length;
3667 mask = mask & ~(TAG_EXISTS);
3668 if (length > 8)
3669 {
8a3fe4f8 3670 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3671 retval = 0;
3672 break;
3673 }
3674 continue;
3675 }
3676 if (tag == TAG_THREADNAME)
3677 {
3678 pkt = unpack_string (pkt, &info->shortname[0], length);
3679 mask = mask & ~TAG_THREADNAME;
3680 continue;
3681 }
3682 if (tag == TAG_DISPLAY)
3683 {
3684 pkt = unpack_string (pkt, &info->display[0], length);
3685 mask = mask & ~TAG_DISPLAY;
3686 continue;
3687 }
3688 if (tag == TAG_MOREDISPLAY)
3689 {
3690 pkt = unpack_string (pkt, &info->more_display[0], length);
3691 mask = mask & ~TAG_MOREDISPLAY;
3692 continue;
3693 }
8a3fe4f8 3694 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3695 break; /* Not a tag we know about. */
c906108c
SS
3696 }
3697 return retval;
3698}
3699
6b8edb51
PA
3700int
3701remote_target::remote_get_threadinfo (threadref *threadid,
3702 int fieldset,
3703 gdb_ext_thread_info *info)
c906108c 3704{
d01949b6 3705 struct remote_state *rs = get_remote_state ();
c906108c 3706 int result;
c906108c 3707
8d64371b 3708 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
2e9f7625 3709 putpkt (rs->buf);
aa7b36b8 3710 getpkt (&rs->buf);
3084dd77
PA
3711
3712 if (rs->buf[0] == '\0')
3713 return 0;
3714
8d64371b 3715 result = remote_unpack_thread_info_response (&rs->buf[2],
23860348 3716 threadid, info);
c906108c
SS
3717 return result;
3718}
3719
c906108c
SS
3720/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3721
3722static char *
fba45db2
KB
3723pack_threadlist_request (char *pkt, int startflag, int threadcount,
3724 threadref *nextthread)
c906108c
SS
3725{
3726 *pkt++ = 'q'; /* info query packet */
3727 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3728 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3729 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3730 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3731 *pkt = '\0';
3732 return pkt;
3733}
3734
3735/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3736
6b8edb51 3737int
cecb1912 3738remote_target::parse_threadlist_response (const char *pkt, int result_limit,
6b8edb51
PA
3739 threadref *original_echo,
3740 threadref *resultlist,
3741 int *doneflag)
c906108c 3742{
d01949b6 3743 struct remote_state *rs = get_remote_state ();
c906108c
SS
3744 int count, resultcount, done;
3745
3746 resultcount = 0;
3747 /* Assume the 'q' and 'M chars have been stripped. */
cecb1912 3748 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
23860348 3749 /* done parse past here */
c906108c
SS
3750 pkt = unpack_byte (pkt, &count); /* count field */
3751 pkt = unpack_nibble (pkt, &done);
3752 /* The first threadid is the argument threadid. */
3753 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3754 while ((count-- > 0) && (pkt < limit))
3755 {
3756 pkt = unpack_threadid (pkt, resultlist++);
3757 if (resultcount++ >= result_limit)
3758 break;
3759 }
3760 if (doneflag)
3761 *doneflag = done;
3762 return resultcount;
3763}
3764
6dc54d91
PA
3765/* Fetch the next batch of threads from the remote. Returns -1 if the
3766 qL packet is not supported, 0 on error and 1 on success. */
3767
6b8edb51
PA
3768int
3769remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3770 int result_limit, int *done, int *result_count,
3771 threadref *threadlist)
c906108c 3772{
d01949b6 3773 struct remote_state *rs = get_remote_state ();
c906108c
SS
3774 int result = 1;
3775
405feb71 3776 /* Truncate result limit to be smaller than the packet size. */
3e43a32a
MS
3777 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3778 >= get_remote_packet_size ())
ea9c271d 3779 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3780
8d64371b
TT
3781 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3782 nextthread);
6d820c5c 3783 putpkt (rs->buf);
aa7b36b8 3784 getpkt (&rs->buf);
8d64371b 3785 if (rs->buf[0] == '\0')
6dc54d91
PA
3786 {
3787 /* Packet not supported. */
3788 return -1;
3789 }
3790
3791 *result_count =
8d64371b 3792 parse_threadlist_response (&rs->buf[2], result_limit,
6dc54d91 3793 &rs->echo_nextthread, threadlist, done);
c906108c 3794
0d031856 3795 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3796 {
23860348 3797 /* FIXME: This is a good reason to drop the packet. */
405feb71
TV
3798 /* Possibly, there is a duplicate response. */
3799 /* Possibilities :
dda83cd7
SM
3800 retransmit immediatly - race conditions
3801 retransmit after timeout - yes
3802 exit
3803 wait for packet, then exit
c906108c 3804 */
8a3fe4f8 3805 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3806 return 0; /* I choose simply exiting. */
c906108c
SS
3807 }
3808 if (*result_count <= 0)
3809 {
3810 if (*done != 1)
3811 {
8a3fe4f8 3812 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3813 result = 0;
3814 }
3815 return result; /* break; */
3816 }
3817 if (*result_count > result_limit)
3818 {
3819 *result_count = 0;
8a3fe4f8 3820 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3821 return 0;
3822 }
3823 return result;
3824}
3825
6dc54d91
PA
3826/* Fetch the list of remote threads, with the qL packet, and call
3827 STEPFUNCTION for each thread found. Stops iterating and returns 1
3828 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3829 STEPFUNCTION returns false. If the packet is not supported,
3830 returns -1. */
c906108c 3831
6b8edb51
PA
3832int
3833remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3834 void *context, int looplimit)
c906108c 3835{
0d031856 3836 struct remote_state *rs = get_remote_state ();
c906108c
SS
3837 int done, i, result_count;
3838 int startflag = 1;
3839 int result = 1;
3840 int loopcount = 0;
c906108c
SS
3841
3842 done = 0;
3843 while (!done)
3844 {
3845 if (loopcount++ > looplimit)
3846 {
3847 result = 0;
8a3fe4f8 3848 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3849 break;
3850 }
6dc54d91
PA
3851 result = remote_get_threadlist (startflag, &rs->nextthread,
3852 MAXTHREADLISTRESULTS,
3853 &done, &result_count,
3854 rs->resultthreadlist);
3855 if (result <= 0)
3856 break;
23860348 3857 /* Clear for later iterations. */
c906108c
SS
3858 startflag = 0;
3859 /* Setup to resume next batch of thread references, set nextthread. */
3860 if (result_count >= 1)
0d031856
TT
3861 copy_threadref (&rs->nextthread,
3862 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3863 i = 0;
3864 while (result_count--)
6dc54d91
PA
3865 {
3866 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3867 {
3868 result = 0;
3869 break;
3870 }
3871 }
c906108c
SS
3872 }
3873 return result;
3874}
3875
6dc54d91
PA
3876/* A thread found on the remote target. */
3877
21fe1c75 3878struct thread_item
6dc54d91 3879{
21fe1c75
SM
3880 explicit thread_item (ptid_t ptid_)
3881 : ptid (ptid_)
3882 {}
3883
3884 thread_item (thread_item &&other) = default;
3885 thread_item &operator= (thread_item &&other) = default;
3886
3887 DISABLE_COPY_AND_ASSIGN (thread_item);
3888
6dc54d91
PA
3889 /* The thread's PTID. */
3890 ptid_t ptid;
3891
21fe1c75
SM
3892 /* The thread's extra info. */
3893 std::string extra;
6dc54d91 3894
21fe1c75
SM
3895 /* The thread's name. */
3896 std::string name;
79efa585 3897
6dc54d91 3898 /* The core the thread was running on. -1 if not known. */
21fe1c75 3899 int core = -1;
f6327dcb
KB
3900
3901 /* The thread handle associated with the thread. */
21fe1c75 3902 gdb::byte_vector thread_handle;
21fe1c75 3903};
6dc54d91
PA
3904
3905/* Context passed around to the various methods listing remote
3906 threads. As new threads are found, they're added to the ITEMS
3907 vector. */
3908
3909struct threads_listing_context
3910{
21fe1c75
SM
3911 /* Return true if this object contains an entry for a thread with ptid
3912 PTID. */
6dc54d91 3913
21fe1c75
SM
3914 bool contains_thread (ptid_t ptid) const
3915 {
3916 auto match_ptid = [&] (const thread_item &item)
3917 {
3918 return item.ptid == ptid;
3919 };
80134cf5 3920
21fe1c75
SM
3921 auto it = std::find_if (this->items.begin (),
3922 this->items.end (),
3923 match_ptid);
80134cf5 3924
21fe1c75
SM
3925 return it != this->items.end ();
3926 }
80134cf5 3927
21fe1c75 3928 /* Remove the thread with ptid PTID. */
80134cf5 3929
21fe1c75
SM
3930 void remove_thread (ptid_t ptid)
3931 {
3932 auto match_ptid = [&] (const thread_item &item)
3933 {
dda83cd7 3934 return item.ptid == ptid;
21fe1c75 3935 };
cbb8991c 3936
21fe1c75
SM
3937 auto it = std::remove_if (this->items.begin (),
3938 this->items.end (),
3939 match_ptid);
cbb8991c 3940
21fe1c75
SM
3941 if (it != this->items.end ())
3942 this->items.erase (it);
3943 }
3944
3945 /* The threads found on the remote target. */
3946 std::vector<thread_item> items;
3947};
cbb8991c 3948
c906108c 3949static int
6dc54d91 3950remote_newthread_step (threadref *ref, void *data)
c906108c 3951{
19ba03f4
SM
3952 struct threads_listing_context *context
3953 = (struct threads_listing_context *) data;
21fe1c75
SM
3954 int pid = inferior_ptid.pid ();
3955 int lwp = threadref_to_int (ref);
3956 ptid_t ptid (pid, lwp);
6dc54d91 3957
21fe1c75 3958 context->items.emplace_back (ptid);
6dc54d91 3959
c906108c
SS
3960 return 1; /* continue iterator */
3961}
3962
3963#define CRAZY_MAX_THREADS 1000
3964
6b8edb51
PA
3965ptid_t
3966remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3967{
d01949b6 3968 struct remote_state *rs = get_remote_state ();
c906108c
SS
3969
3970 putpkt ("qC");
aa7b36b8 3971 getpkt (&rs->buf);
2e9f7625 3972 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3973 {
256642e8 3974 const char *obuf;
c9f35b34
KB
3975 ptid_t result;
3976
3977 result = read_ptid (&rs->buf[2], &obuf);
2189c312
SM
3978 if (*obuf != '\0')
3979 remote_debug_printf ("warning: garbage in qC reply");
c9f35b34
KB
3980
3981 return result;
3982 }
c906108c
SS
3983 else
3984 return oldpid;
3985}
3986
6dc54d91 3987/* List remote threads using the deprecated qL packet. */
cce74817 3988
6b8edb51
PA
3989int
3990remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3991{
6dc54d91
PA
3992 if (remote_threadlist_iterator (remote_newthread_step, context,
3993 CRAZY_MAX_THREADS) >= 0)
3994 return 1;
3995
3996 return 0;
c906108c
SS
3997}
3998
dc146f7c
VP
3999#if defined(HAVE_LIBEXPAT)
4000
dc146f7c
VP
4001static void
4002start_thread (struct gdb_xml_parser *parser,
4003 const struct gdb_xml_element *element,
4d0fdd9b
SM
4004 void *user_data,
4005 std::vector<gdb_xml_value> &attributes)
dc146f7c 4006{
19ba03f4
SM
4007 struct threads_listing_context *data
4008 = (struct threads_listing_context *) user_data;
3d2c1d41 4009 struct gdb_xml_value *attr;
dc146f7c 4010
4d0fdd9b 4011 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
4012 ptid_t ptid = read_ptid (id, NULL);
4013
4014 data->items.emplace_back (ptid);
4015 thread_item &item = data->items.back ();
dc146f7c 4016
3d2c1d41
PA
4017 attr = xml_find_attribute (attributes, "core");
4018 if (attr != NULL)
4d0fdd9b 4019 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 4020
79efa585 4021 attr = xml_find_attribute (attributes, "name");
21fe1c75 4022 if (attr != NULL)
4d0fdd9b 4023 item.name = (const char *) attr->value.get ();
79efa585 4024
f6327dcb
KB
4025 attr = xml_find_attribute (attributes, "handle");
4026 if (attr != NULL)
4d0fdd9b 4027 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
4028}
4029
4030static void
4031end_thread (struct gdb_xml_parser *parser,
4032 const struct gdb_xml_element *element,
4033 void *user_data, const char *body_text)
4034{
19ba03f4
SM
4035 struct threads_listing_context *data
4036 = (struct threads_listing_context *) user_data;
dc146f7c 4037
21fe1c75
SM
4038 if (body_text != NULL && *body_text != '\0')
4039 data->items.back ().extra = body_text;
dc146f7c
VP
4040}
4041
4042const struct gdb_xml_attribute thread_attributes[] = {
4043 { "id", GDB_XML_AF_NONE, NULL, NULL },
4044 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 4045 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 4046 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
4047 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4048};
4049
4050const struct gdb_xml_element thread_children[] = {
4051 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4052};
4053
4054const struct gdb_xml_element threads_children[] = {
4055 { "thread", thread_attributes, thread_children,
4056 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4057 start_thread, end_thread },
4058 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4059};
4060
4061const struct gdb_xml_element threads_elements[] = {
4062 { "threads", NULL, threads_children,
4063 GDB_XML_EF_NONE, NULL, NULL },
4064 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4065};
4066
4067#endif
4068
6dc54d91 4069/* List remote threads using qXfer:threads:read. */
9d1f7ab2 4070
6b8edb51
PA
4071int
4072remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 4073{
dc146f7c 4074#if defined(HAVE_LIBEXPAT)
ff52c073 4075 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 4076 {
9018be22 4077 gdb::optional<gdb::char_vector> xml
6b8edb51 4078 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 4079
9018be22 4080 if (xml && (*xml)[0] != '\0')
dc146f7c 4081 {
6dc54d91 4082 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 4083 threads_elements, xml->data (), context);
dc146f7c
VP
4084 }
4085
6dc54d91 4086 return 1;
dc146f7c
VP
4087 }
4088#endif
4089
6dc54d91
PA
4090 return 0;
4091}
4092
4093/* List remote threads using qfThreadInfo/qsThreadInfo. */
4094
6b8edb51
PA
4095int
4096remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
4097{
4098 struct remote_state *rs = get_remote_state ();
4099
b80fafe3 4100 if (rs->use_threadinfo_query)
9d1f7ab2 4101 {
256642e8 4102 const char *bufp;
6dc54d91 4103
9d1f7ab2 4104 putpkt ("qfThreadInfo");
aa7b36b8 4105 getpkt (&rs->buf);
8d64371b 4106 bufp = rs->buf.data ();
9d1f7ab2 4107 if (bufp[0] != '\0') /* q packet recognized */
802188a7 4108 {
9d1f7ab2
MS
4109 while (*bufp++ == 'm') /* reply contains one or more TID */
4110 {
4111 do
4112 {
21fe1c75
SM
4113 ptid_t ptid = read_ptid (bufp, &bufp);
4114 context->items.emplace_back (ptid);
9d1f7ab2
MS
4115 }
4116 while (*bufp++ == ','); /* comma-separated list */
4117 putpkt ("qsThreadInfo");
aa7b36b8 4118 getpkt (&rs->buf);
8d64371b 4119 bufp = rs->buf.data ();
9d1f7ab2 4120 }
6dc54d91
PA
4121 return 1;
4122 }
4123 else
4124 {
4125 /* Packet not recognized. */
4126 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
4127 }
4128 }
4129
6dc54d91
PA
4130 return 0;
4131}
4132
a05575d3
TBA
4133/* Return true if INF only has one non-exited thread. */
4134
4135static bool
4136has_single_non_exited_thread (inferior *inf)
4137{
4138 int count = 0;
4139 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4140 if (++count > 1)
4141 break;
4142 return count == 1;
4143}
4144
e8032dde 4145/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
4146 targets. */
4147
f6ac5f3d
PA
4148void
4149remote_target::update_thread_list ()
6dc54d91 4150{
6dc54d91 4151 struct threads_listing_context context;
ab970af1 4152 int got_list = 0;
e8032dde 4153
6dc54d91
PA
4154 /* We have a few different mechanisms to fetch the thread list. Try
4155 them all, starting with the most preferred one first, falling
4156 back to older methods. */
6b8edb51
PA
4157 if (remote_get_threads_with_qxfer (&context)
4158 || remote_get_threads_with_qthreadinfo (&context)
4159 || remote_get_threads_with_ql (&context))
6dc54d91 4160 {
ab970af1
PA
4161 got_list = 1;
4162
21fe1c75 4163 if (context.items.empty ()
f6ac5f3d 4164 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
4165 {
4166 /* Some targets don't really support threads, but still
4167 reply an (empty) thread list in response to the thread
4168 listing packets, instead of replying "packet not
4169 supported". Exit early so we don't delete the main
4170 thread. */
7d1a114c
PA
4171 return;
4172 }
4173
ab970af1
PA
4174 /* CONTEXT now holds the current thread list on the remote
4175 target end. Delete GDB-side threads no longer found on the
4176 target. */
08036331 4177 for (thread_info *tp : all_threads_safe ())
cbb8991c 4178 {
5b6d1e4f
PA
4179 if (tp->inf->process_target () != this)
4180 continue;
4181
21fe1c75 4182 if (!context.contains_thread (tp->ptid))
ab970af1 4183 {
a05575d3
TBA
4184 /* Do not remove the thread if it is the last thread in
4185 the inferior. This situation happens when we have a
4186 pending exit process status to process. Otherwise we
4187 may end up with a seemingly live inferior (i.e. pid
4188 != 0) that has no threads. */
4189 if (has_single_non_exited_thread (tp->inf))
4190 continue;
4191
ab970af1 4192 /* Not found. */
00431a78 4193 delete_thread (tp);
ab970af1 4194 }
cbb8991c
DB
4195 }
4196
4197 /* Remove any unreported fork child threads from CONTEXT so
4198 that we don't interfere with follow fork, which is where
4199 creation of such threads is handled. */
4200 remove_new_fork_children (&context);
74531fed 4201
ab970af1 4202 /* And now add threads we don't know about yet to our list. */
21fe1c75 4203 for (thread_item &item : context.items)
6dc54d91 4204 {
21fe1c75 4205 if (item.ptid != null_ptid)
6dc54d91 4206 {
6dc54d91 4207 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
4208 executing until proven otherwise with a stop reply.
4209 In all-stop, we can only get here if all threads are
6dc54d91 4210 stopped. */
8a82de58 4211 bool executing = target_is_non_stop_p ();
6dc54d91 4212
21fe1c75 4213 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 4214
9213a6d7 4215 thread_info *tp = this->find_thread (item.ptid);
00431a78 4216 remote_thread_info *info = get_remote_thread_info (tp);
21fe1c75 4217 info->core = item.core;
7aabaf9d
SM
4218 info->extra = std::move (item.extra);
4219 info->name = std::move (item.name);
4220 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
4221 }
4222 }
4223 }
4224
ab970af1
PA
4225 if (!got_list)
4226 {
4227 /* If no thread listing method is supported, then query whether
4228 each known thread is alive, one by one, with the T packet.
4229 If the target doesn't support threads at all, then this is a
4230 no-op. See remote_thread_alive. */
4231 prune_threads ();
4232 }
9d1f7ab2
MS
4233}
4234
802188a7 4235/*
9d1f7ab2
MS
4236 * Collect a descriptive string about the given thread.
4237 * The target may say anything it wants to about the thread
4238 * (typically info about its blocked / runnable state, name, etc.).
4239 * This string will appear in the info threads display.
802188a7 4240 *
9d1f7ab2
MS
4241 * Optional: targets are not required to implement this function.
4242 */
4243
f6ac5f3d
PA
4244const char *
4245remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 4246{
d01949b6 4247 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
4248 int set;
4249 threadref id;
4250 struct gdb_ext_thread_info threadinfo;
9d1f7ab2 4251
5d93a237 4252 if (rs->remote_desc == 0) /* paranoia */
f34652de 4253 internal_error (_("remote_threads_extra_info"));
9d1f7ab2 4254
d7e15655 4255 if (tp->ptid == magic_null_ptid
e38504b3 4256 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
60e569b9
PA
4257 /* This is the main thread which was added by GDB. The remote
4258 server doesn't know about it. */
4259 return NULL;
4260
c76a8ea3
PA
4261 std::string &extra = get_remote_thread_info (tp)->extra;
4262
4263 /* If already have cached info, use it. */
4264 if (!extra.empty ())
4265 return extra.c_str ();
4266
ff52c073 4267 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 4268 {
c76a8ea3
PA
4269 /* If we're using qXfer:threads:read, then the extra info is
4270 included in the XML. So if we didn't have anything cached,
4271 it's because there's really no extra info. */
4272 return NULL;
dc146f7c
VP
4273 }
4274
b80fafe3 4275 if (rs->use_threadextra_query)
9d1f7ab2 4276 {
8d64371b
TT
4277 char *b = rs->buf.data ();
4278 char *endb = b + get_remote_packet_size ();
82f73884
PA
4279
4280 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4281 b += strlen (b);
4282 write_ptid (b, endb, tp->ptid);
4283
2e9f7625 4284 putpkt (rs->buf);
aa7b36b8 4285 getpkt (&rs->buf);
2e9f7625 4286 if (rs->buf[0] != 0)
9d1f7ab2 4287 {
8d64371b
TT
4288 extra.resize (strlen (rs->buf.data ()) / 2);
4289 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
c76a8ea3 4290 return extra.c_str ();
9d1f7ab2 4291 }
0f71a2f6 4292 }
9d1f7ab2
MS
4293
4294 /* If the above query fails, fall back to the old method. */
b80fafe3 4295 rs->use_threadextra_query = 0;
9d1f7ab2
MS
4296 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4297 | TAG_MOREDISPLAY | TAG_DISPLAY;
e38504b3 4298 int_to_threadref (&id, tp->ptid.lwp ());
9d1f7ab2
MS
4299 if (remote_get_threadinfo (&id, set, &threadinfo))
4300 if (threadinfo.active)
0f71a2f6 4301 {
9d1f7ab2 4302 if (*threadinfo.shortname)
c76a8ea3 4303 string_appendf (extra, " Name: %s", threadinfo.shortname);
9d1f7ab2 4304 if (*threadinfo.display)
c76a8ea3
PA
4305 {
4306 if (!extra.empty ())
4307 extra += ',';
4308 string_appendf (extra, " State: %s", threadinfo.display);
4309 }
9d1f7ab2 4310 if (*threadinfo.more_display)
c5aa993b 4311 {
c76a8ea3
PA
4312 if (!extra.empty ())
4313 extra += ',';
4314 string_appendf (extra, " Priority: %s", threadinfo.more_display);
c5aa993b 4315 }
c76a8ea3 4316 return extra.c_str ();
0f71a2f6 4317 }
9d1f7ab2 4318 return NULL;
0f71a2f6 4319}
c906108c 4320\f
c5aa993b 4321
f6ac5f3d
PA
4322bool
4323remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4324 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
4325{
4326 struct remote_state *rs = get_remote_state ();
8d64371b 4327 char *p = rs->buf.data ();
0fb4aa4b 4328
bba74b36 4329 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
4330 p += strlen (p);
4331 p += hexnumstr (p, addr);
4332 putpkt (rs->buf);
aa7b36b8 4333 getpkt (&rs->buf);
8d64371b 4334 p = rs->buf.data ();
0fb4aa4b
PA
4335
4336 if (*p == 'E')
4337 error (_("Remote failure reply: %s"), p);
4338
4339 if (*p++ == 'm')
4340 {
256642e8 4341 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 4342 return true;
0fb4aa4b
PA
4343 }
4344
5d9310c4 4345 return false;
0fb4aa4b
PA
4346}
4347
f6ac5f3d
PA
4348std::vector<static_tracepoint_marker>
4349remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
4350{
4351 struct remote_state *rs = get_remote_state ();
5d9310c4 4352 std::vector<static_tracepoint_marker> markers;
256642e8 4353 const char *p;
5d9310c4 4354 static_tracepoint_marker marker;
0fb4aa4b
PA
4355
4356 /* Ask for a first packet of static tracepoint marker
4357 definition. */
4358 putpkt ("qTfSTM");
aa7b36b8 4359 getpkt (&rs->buf);
8d64371b 4360 p = rs->buf.data ();
0fb4aa4b
PA
4361 if (*p == 'E')
4362 error (_("Remote failure reply: %s"), p);
4363
0fb4aa4b
PA
4364 while (*p++ == 'm')
4365 {
0fb4aa4b
PA
4366 do
4367 {
5d9310c4 4368 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 4369
5d9310c4
SM
4370 if (strid == NULL || marker.str_id == strid)
4371 markers.push_back (std::move (marker));
0fb4aa4b
PA
4372 }
4373 while (*p++ == ','); /* comma-separated list */
4374 /* Ask for another packet of static tracepoint definition. */
4375 putpkt ("qTsSTM");
aa7b36b8 4376 getpkt (&rs->buf);
8d64371b 4377 p = rs->buf.data ();
0fb4aa4b
PA
4378 }
4379
0fb4aa4b
PA
4380 return markers;
4381}
4382
4383\f
10760264
JB
4384/* Implement the to_get_ada_task_ptid function for the remote targets. */
4385
f6ac5f3d 4386ptid_t
c80e29db 4387remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
10760264 4388{
184ea2f7 4389 return ptid_t (inferior_ptid.pid (), lwp);
10760264
JB
4390}
4391\f
4392
24b06219 4393/* Restart the remote side; this is an extended protocol operation. */
c906108c 4394
6b8edb51
PA
4395void
4396remote_target::extended_remote_restart ()
c906108c 4397{
d01949b6 4398 struct remote_state *rs = get_remote_state ();
c906108c
SS
4399
4400 /* Send the restart command; for reasons I don't understand the
4401 remote side really expects a number after the "R". */
8d64371b 4402 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
6d820c5c 4403 putpkt (rs->buf);
c906108c 4404
ad9a8f3f 4405 remote_fileio_reset ();
c906108c
SS
4406}
4407\f
4408/* Clean up connection to a remote debugger. */
4409
f6ac5f3d
PA
4410void
4411remote_target::close ()
c906108c 4412{
048094ac 4413 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4414 terminal_ours ();
ce5ce7ed 4415
6b8edb51
PA
4416 trace_reset_local_state ();
4417
4418 delete this;
4419}
4420
4421remote_target::~remote_target ()
4422{
4423 struct remote_state *rs = get_remote_state ();
4424
4425 /* Check for NULL because we may get here with a partially
4426 constructed target/connection. */
4427 if (rs->remote_desc == nullptr)
4428 return;
4429
4430 serial_close (rs->remote_desc);
4431
4432 /* We are destroying the remote target, so we should discard
f48ff2a7 4433 everything of this target. */
6b8edb51 4434 discard_pending_stop_replies_in_queue ();
74531fed 4435
92b98b37 4436 rs->delete_async_event_handler ();
722247f1 4437
97dfbadd 4438 delete rs->notif_state;
c906108c
SS
4439}
4440
23860348 4441/* Query the remote side for the text, data and bss offsets. */
c906108c 4442
6b8edb51
PA
4443void
4444remote_target::get_offsets ()
c906108c 4445{
d01949b6 4446 struct remote_state *rs = get_remote_state ();
2e9f7625 4447 char *buf;
085dd6e6 4448 char *ptr;
31d99776
DJ
4449 int lose, num_segments = 0, do_sections, do_segments;
4450 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
31d99776 4451
a42d7dd8 4452 if (current_program_space->symfile_object_file == NULL)
31d99776 4453 return;
c906108c
SS
4454
4455 putpkt ("qOffsets");
aa7b36b8 4456 getpkt (&rs->buf);
8d64371b 4457 buf = rs->buf.data ();
c906108c
SS
4458
4459 if (buf[0] == '\000')
4460 return; /* Return silently. Stub doesn't support
23860348 4461 this command. */
c906108c
SS
4462 if (buf[0] == 'E')
4463 {
8a3fe4f8 4464 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4465 return;
4466 }
4467
4468 /* Pick up each field in turn. This used to be done with scanf, but
4469 scanf will make trouble if CORE_ADDR size doesn't match
4470 conversion directives correctly. The following code will work
4471 with any size of CORE_ADDR. */
4472 text_addr = data_addr = bss_addr = 0;
4473 ptr = buf;
4474 lose = 0;
4475
61012eef 4476 if (startswith (ptr, "Text="))
c906108c
SS
4477 {
4478 ptr += 5;
4479 /* Don't use strtol, could lose on big values. */
4480 while (*ptr && *ptr != ';')
4481 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4482
61012eef 4483 if (startswith (ptr, ";Data="))
31d99776
DJ
4484 {
4485 ptr += 6;
4486 while (*ptr && *ptr != ';')
4487 data_addr = (data_addr << 4) + fromhex (*ptr++);
4488 }
4489 else
4490 lose = 1;
4491
61012eef 4492 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4493 {
4494 ptr += 5;
4495 while (*ptr && *ptr != ';')
4496 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4497
31d99776
DJ
4498 if (bss_addr != data_addr)
4499 warning (_("Target reported unsupported offsets: %s"), buf);
4500 }
4501 else
4502 lose = 1;
4503 }
61012eef 4504 else if (startswith (ptr, "TextSeg="))
c906108c 4505 {
31d99776
DJ
4506 ptr += 8;
4507 /* Don't use strtol, could lose on big values. */
c906108c 4508 while (*ptr && *ptr != ';')
31d99776
DJ
4509 text_addr = (text_addr << 4) + fromhex (*ptr++);
4510 num_segments = 1;
4511
61012eef 4512 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4513 {
4514 ptr += 9;
4515 while (*ptr && *ptr != ';')
4516 data_addr = (data_addr << 4) + fromhex (*ptr++);
4517 num_segments++;
4518 }
c906108c
SS
4519 }
4520 else
4521 lose = 1;
4522
4523 if (lose)
8a3fe4f8 4524 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4525 else if (*ptr != '\0')
4526 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4527
a42d7dd8
TT
4528 objfile *objf = current_program_space->symfile_object_file;
4529 section_offsets offs = objf->section_offsets;
c906108c 4530
98badbfd 4531 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
31d99776
DJ
4532 do_segments = (data != NULL);
4533 do_sections = num_segments == 0;
c906108c 4534
28c32713 4535 if (num_segments > 0)
31d99776 4536 {
31d99776
DJ
4537 segments[0] = text_addr;
4538 segments[1] = data_addr;
4539 }
28c32713
JB
4540 /* If we have two segments, we can still try to relocate everything
4541 by assuming that the .text and .data offsets apply to the whole
4542 text and data segments. Convert the offsets given in the packet
4543 to base addresses for symfile_map_offsets_to_segments. */
68b888ff 4544 else if (data != nullptr && data->segments.size () == 2)
28c32713 4545 {
68b888ff
SM
4546 segments[0] = data->segments[0].base + text_addr;
4547 segments[1] = data->segments[1].base + data_addr;
28c32713
JB
4548 num_segments = 2;
4549 }
8d385431
DJ
4550 /* If the object file has only one segment, assume that it is text
4551 rather than data; main programs with no writable data are rare,
4552 but programs with no code are useless. Of course the code might
4553 have ended up in the data segment... to detect that we would need
4554 the permissions here. */
68b888ff 4555 else if (data && data->segments.size () == 1)
8d385431 4556 {
68b888ff 4557 segments[0] = data->segments[0].base + text_addr;
8d385431
DJ
4558 num_segments = 1;
4559 }
28c32713
JB
4560 /* There's no way to relocate by segment. */
4561 else
4562 do_segments = 0;
31d99776
DJ
4563
4564 if (do_segments)
4565 {
98badbfd 4566 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
62982abd
SM
4567 data.get (), offs,
4568 num_segments, segments);
31d99776
DJ
4569
4570 if (ret == 0 && !do_sections)
3e43a32a
MS
4571 error (_("Can not handle qOffsets TextSeg "
4572 "response with this symbol file"));
31d99776
DJ
4573
4574 if (ret > 0)
4575 do_sections = 0;
4576 }
c906108c 4577
31d99776
DJ
4578 if (do_sections)
4579 {
a42d7dd8 4580 offs[SECT_OFF_TEXT (objf)] = text_addr;
31d99776 4581
3e43a32a
MS
4582 /* This is a temporary kludge to force data and bss to use the
4583 same offsets because that's what nlmconv does now. The real
4584 solution requires changes to the stub and remote.c that I
4585 don't have time to do right now. */
31d99776 4586
a42d7dd8
TT
4587 offs[SECT_OFF_DATA (objf)] = data_addr;
4588 offs[SECT_OFF_BSS (objf)] = data_addr;
31d99776 4589 }
c906108c 4590
a42d7dd8 4591 objfile_relocate (objf, offs);
c906108c
SS
4592}
4593
9a7071a8 4594/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4595
4596void
4597remote_target::send_interrupt_sequence ()
9a7071a8 4598{
5d93a237
TT
4599 struct remote_state *rs = get_remote_state ();
4600
9a7071a8 4601 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4602 remote_serial_write ("\x03", 1);
9a7071a8 4603 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4604 serial_send_break (rs->remote_desc);
9a7071a8
JB
4605 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4606 {
5d93a237 4607 serial_send_break (rs->remote_desc);
c33e31fd 4608 remote_serial_write ("g", 1);
9a7071a8
JB
4609 }
4610 else
f34652de 4611 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
9a7071a8
JB
4612 interrupt_sequence_mode);
4613}
4614
3405876a
PA
4615
4616/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4617 and extract the PTID. Returns NULL_PTID if not found. */
4618
4619static ptid_t
e3b2741b 4620stop_reply_extract_thread (const char *stop_reply)
3405876a
PA
4621{
4622 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4623 {
256642e8 4624 const char *p;
3405876a
PA
4625
4626 /* Txx r:val ; r:val (...) */
4627 p = &stop_reply[3];
4628
4629 /* Look for "register" named "thread". */
4630 while (*p != '\0')
4631 {
256642e8 4632 const char *p1;
3405876a
PA
4633
4634 p1 = strchr (p, ':');
4635 if (p1 == NULL)
4636 return null_ptid;
4637
4638 if (strncmp (p, "thread", p1 - p) == 0)
4639 return read_ptid (++p1, &p);
4640
4641 p1 = strchr (p, ';');
4642 if (p1 == NULL)
4643 return null_ptid;
4644 p1++;
4645
4646 p = p1;
4647 }
4648 }
4649
4650 return null_ptid;
4651}
4652
b7ea362b
PA
4653/* Determine the remote side's current thread. If we have a stop
4654 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4655 "thread" register we can extract the current thread from. If not,
4656 ask the remote which is the current thread with qC. The former
4657 method avoids a roundtrip. */
4658
6b8edb51 4659ptid_t
e3b2741b 4660remote_target::get_current_thread (const char *wait_status)
b7ea362b 4661{
6a49a997 4662 ptid_t ptid = null_ptid;
b7ea362b
PA
4663
4664 /* Note we don't use remote_parse_stop_reply as that makes use of
4665 the target architecture, which we haven't yet fully determined at
4666 this point. */
4667 if (wait_status != NULL)
4668 ptid = stop_reply_extract_thread (wait_status);
d7e15655 4669 if (ptid == null_ptid)
b7ea362b
PA
4670 ptid = remote_current_thread (inferior_ptid);
4671
4672 return ptid;
4673}
4674
49c62f2e
PA
4675/* Query the remote target for which is the current thread/process,
4676 add it to our tables, and update INFERIOR_PTID. The caller is
4677 responsible for setting the state such that the remote end is ready
3405876a
PA
4678 to return the current thread.
4679
4680 This function is called after handling the '?' or 'vRun' packets,
4681 whose response is a stop reply from which we can also try
4682 extracting the thread. If the target doesn't support the explicit
4683 qC query, we infer the current thread from that stop reply, passed
64d38fdd 4684 in in WAIT_STATUS, which may be NULL.
49c62f2e 4685
64d38fdd
JM
4686 The function returns pointer to the main thread of the inferior. */
4687
4688thread_info *
e3b2741b 4689remote_target::add_current_inferior_and_thread (const char *wait_status)
49c62f2e 4690{
9ab8741a 4691 bool fake_pid_p = false;
49c62f2e 4692
0ac55310 4693 switch_to_no_thread ();
49c62f2e 4694
0ac55310
PA
4695 /* Now, if we have thread information, update the current thread's
4696 ptid. */
87215ad1 4697 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4698
87215ad1 4699 if (curr_ptid != null_ptid)
49c62f2e 4700 {
ff52c073 4701 if (!m_features.remote_multi_process_p ())
9ab8741a 4702 fake_pid_p = true;
49c62f2e
PA
4703 }
4704 else
4705 {
4706 /* Without this, some commands which require an active target
4707 (such as kill) won't work. This variable serves (at least)
4708 double duty as both the pid of the target process (if it has
4709 such), and as a flag indicating that a target is active. */
87215ad1 4710 curr_ptid = magic_null_ptid;
9ab8741a 4711 fake_pid_p = true;
49c62f2e
PA
4712 }
4713
e99b03dc 4714 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
49c62f2e 4715
87215ad1
SDJ
4716 /* Add the main thread and switch to it. Don't try reading
4717 registers yet, since we haven't fetched the target description
4718 yet. */
5b6d1e4f 4719 thread_info *tp = add_thread_silent (this, curr_ptid);
87215ad1 4720 switch_to_thread_no_regs (tp);
64d38fdd
JM
4721
4722 return tp;
49c62f2e
PA
4723}
4724
6efcd9a8
PA
4725/* Print info about a thread that was found already stopped on
4726 connection. */
4727
1edb66d8
SM
4728void
4729remote_target::print_one_stopped_thread (thread_info *thread)
6efcd9a8 4730{
1edb66d8
SM
4731 target_waitstatus ws;
4732
4733 /* If there is a pending waitstatus, use it. If there isn't it's because
4734 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4735 and process_initial_stop_replies decided it wasn't interesting to save
4736 and report to the core. */
4737 if (thread->has_pending_waitstatus ())
4738 {
4739 ws = thread->pending_waitstatus ();
4740 thread->clear_pending_waitstatus ();
4741 }
4742 else
4743 {
183be222 4744 ws.set_stopped (GDB_SIGNAL_0);
1edb66d8 4745 }
6efcd9a8 4746
00431a78 4747 switch_to_thread (thread);
1edb66d8 4748 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
6efcd9a8
PA
4749 set_current_sal_from_frame (get_current_frame ());
4750
1edb66d8
SM
4751 /* For "info program". */
4752 set_last_target_status (this, thread->ptid, ws);
6efcd9a8 4753
183be222 4754 if (ws.kind () == TARGET_WAITKIND_STOPPED)
6efcd9a8 4755 {
183be222 4756 enum gdb_signal sig = ws.sig ();
6efcd9a8
PA
4757
4758 if (signal_print_state (sig))
3f75a984 4759 notify_signal_received (sig);
6efcd9a8 4760 }
87829267
SM
4761
4762 notify_normal_stop (nullptr, 1);
6efcd9a8
PA
4763}
4764
221e1a37
PA
4765/* Process all initial stop replies the remote side sent in response
4766 to the ? packet. These indicate threads that were already stopped
4767 on initial connection. We mark these threads as stopped and print
4768 their current frame before giving the user the prompt. */
4769
6b8edb51
PA
4770void
4771remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4772{
4773 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4774 struct thread_info *selected = NULL;
4775 struct thread_info *lowest_stopped = NULL;
4776 struct thread_info *first = NULL;
221e1a37 4777
1edb66d8
SM
4778 /* This is only used when the target is non-stop. */
4779 gdb_assert (target_is_non_stop_p ());
4780
221e1a37
PA
4781 /* Consume the initial pending events. */
4782 while (pending_stop_replies-- > 0)
4783 {
4784 ptid_t waiton_ptid = minus_one_ptid;
4785 ptid_t event_ptid;
4786 struct target_waitstatus ws;
4787 int ignore_event = 0;
4788
221e1a37
PA
4789 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4790 if (remote_debug)
c272a98c 4791 print_target_wait_results (waiton_ptid, event_ptid, ws);
221e1a37 4792
183be222 4793 switch (ws.kind ())
221e1a37
PA
4794 {
4795 case TARGET_WAITKIND_IGNORE:
4796 case TARGET_WAITKIND_NO_RESUMED:
4797 case TARGET_WAITKIND_SIGNALLED:
4798 case TARGET_WAITKIND_EXITED:
4799 /* We shouldn't see these, but if we do, just ignore. */
2189c312 4800 remote_debug_printf ("event ignored");
221e1a37
PA
4801 ignore_event = 1;
4802 break;
4803
221e1a37
PA
4804 default:
4805 break;
4806 }
4807
4808 if (ignore_event)
4809 continue;
4810
9213a6d7 4811 thread_info *evthread = this->find_thread (event_ptid);
221e1a37 4812
183be222 4813 if (ws.kind () == TARGET_WAITKIND_STOPPED)
221e1a37 4814 {
183be222 4815 enum gdb_signal sig = ws.sig ();
221e1a37
PA
4816
4817 /* Stubs traditionally report SIGTRAP as initial signal,
4818 instead of signal 0. Suppress it. */
4819 if (sig == GDB_SIGNAL_TRAP)
4820 sig = GDB_SIGNAL_0;
1edb66d8 4821 evthread->set_stop_signal (sig);
183be222 4822 ws.set_stopped (sig);
6efcd9a8 4823 }
221e1a37 4824
183be222
SM
4825 if (ws.kind () != TARGET_WAITKIND_STOPPED
4826 || ws.sig () != GDB_SIGNAL_0)
1edb66d8 4827 evthread->set_pending_waitstatus (ws);
6efcd9a8 4828
719546c4
SM
4829 set_executing (this, event_ptid, false);
4830 set_running (this, event_ptid, false);
c9d22089 4831 get_remote_thread_info (evthread)->set_not_resumed ();
6efcd9a8
PA
4832 }
4833
4834 /* "Notice" the new inferiors before anything related to
4835 registers/memory. */
5b6d1e4f 4836 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4837 {
30220b46 4838 inf->needs_setup = true;
6efcd9a8
PA
4839
4840 if (non_stop)
4841 {
08036331 4842 thread_info *thread = any_live_thread_of_inferior (inf);
00431a78 4843 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
6efcd9a8
PA
4844 from_tty);
4845 }
4846 }
4847
4848 /* If all-stop on top of non-stop, pause all threads. Note this
4849 records the threads' stop pc, so must be done after "noticing"
4850 the inferiors. */
4851 if (!non_stop)
4852 {
abe8cab7
SM
4853 {
4854 /* At this point, the remote target is not async. It needs to be for
4855 the poll in stop_all_threads to consider events from it, so enable
4856 it temporarily. */
4857 gdb_assert (!this->is_async_p ());
4a570176
TT
4858 SCOPE_EXIT { target_async (false); };
4859 target_async (true);
4f5539f0 4860 stop_all_threads ("remote connect in all-stop");
abe8cab7 4861 }
6efcd9a8
PA
4862
4863 /* If all threads of an inferior were already stopped, we
4864 haven't setup the inferior yet. */
5b6d1e4f 4865 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4866 {
6efcd9a8
PA
4867 if (inf->needs_setup)
4868 {
08036331 4869 thread_info *thread = any_live_thread_of_inferior (inf);
6efcd9a8
PA
4870 switch_to_thread_no_regs (thread);
4871 setup_inferior (0);
4872 }
4873 }
221e1a37 4874 }
6efcd9a8
PA
4875
4876 /* Now go over all threads that are stopped, and print their current
4877 frame. If all-stop, then if there's a signalled thread, pick
4878 that as current. */
5b6d1e4f 4879 for (thread_info *thread : all_non_exited_threads (this))
6efcd9a8 4880 {
6efcd9a8
PA
4881 if (first == NULL)
4882 first = thread;
4883
4884 if (!non_stop)
00431a78 4885 thread->set_running (false);
6efcd9a8
PA
4886 else if (thread->state != THREAD_STOPPED)
4887 continue;
4888
1edb66d8 4889 if (selected == nullptr && thread->has_pending_waitstatus ())
6efcd9a8
PA
4890 selected = thread;
4891
5d5658a1
PA
4892 if (lowest_stopped == NULL
4893 || thread->inf->num < lowest_stopped->inf->num
4894 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4895 lowest_stopped = thread;
4896
4897 if (non_stop)
4898 print_one_stopped_thread (thread);
4899 }
4900
4901 /* In all-stop, we only print the status of one thread, and leave
4902 others with their status pending. */
4903 if (!non_stop)
4904 {
08036331 4905 thread_info *thread = selected;
6efcd9a8
PA
4906 if (thread == NULL)
4907 thread = lowest_stopped;
4908 if (thread == NULL)
4909 thread = first;
4910
4911 print_one_stopped_thread (thread);
4912 }
221e1a37
PA
4913}
4914
45664f16 4915/* Mark a remote_target as starting (by setting the starting_up flag within
7a34f66b
AB
4916 its remote_state) for the lifetime of this object. The reference count
4917 on the remote target is temporarily incremented, to prevent the target
4918 being deleted under our feet. */
4919
4920struct scoped_mark_target_starting
4921{
4922 /* Constructor, TARGET is the target to be marked as starting, its
4923 reference count will be incremented. */
4924 scoped_mark_target_starting (remote_target *target)
45664f16
AB
4925 : m_remote_target (remote_target_ref::new_reference (target)),
4926 m_restore_starting_up (set_starting_up_flag (target))
4927 { /* Nothing. */ }
4928
4929private:
7a34f66b 4930
45664f16
AB
4931 /* Helper function, set the starting_up flag on TARGET and return an
4932 object which, when it goes out of scope, will restore the previous
4933 value of the starting_up flag. */
4934 static scoped_restore_tmpl<bool>
4935 set_starting_up_flag (remote_target *target)
7a34f66b 4936 {
45664f16
AB
4937 remote_state *rs = target->get_remote_state ();
4938 gdb_assert (!rs->starting_up);
4939 return make_scoped_restore (&rs->starting_up, true);
7a34f66b
AB
4940 }
4941
45664f16
AB
4942 /* A gdb::ref_ptr pointer to a remote_target. */
4943 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4944
4945 /* A reference to the target on which we are operating. */
4946 remote_target_ref m_remote_target;
7a34f66b 4947
45664f16
AB
4948 /* An object which restores the previous value of the starting_up flag
4949 when it goes out of scope. */
4950 scoped_restore_tmpl<bool> m_restore_starting_up;
7a34f66b
AB
4951};
4952
288712bb
AB
4953/* Helper for remote_target::start_remote, start the remote connection and
4954 sync state. Return true if everything goes OK, otherwise, return false.
4955 This function exists so that the scoped_restore created within it will
4956 expire before we return to remote_target::start_remote. */
048094ac 4957
288712bb
AB
4958bool
4959remote_target::start_remote_1 (int from_tty, int extended_p)
c906108c 4960{
2189c312
SM
4961 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4962
c8d104ad 4963 struct remote_state *rs = get_remote_state ();
8621d6a9 4964
048094ac
PA
4965 /* Signal other parts that we're going through the initial setup,
4966 and so things may not be stable yet. E.g., we don't try to
4967 install tracepoints until we've relocated symbols. Also, a
4968 Ctrl-C before we're connected and synced up can't interrupt the
4969 target. Instead, it offers to drop the (potentially wedged)
4970 connection. */
7a34f66b 4971 scoped_mark_target_starting target_is_starting (this);
048094ac 4972
522002f9 4973 QUIT;
c906108c 4974
9a7071a8
JB
4975 if (interrupt_on_connect)
4976 send_interrupt_sequence ();
4977
57e12211 4978 /* Ack any packet which the remote side has already sent. */
048094ac 4979 remote_serial_write ("+", 1);
1e51243a 4980
c8d104ad
PA
4981 /* The first packet we send to the target is the optional "supported
4982 packets" request. If the target can answer this, it will tell us
4983 which later probes to skip. */
4984 remote_query_supported ();
4985
34f0de5a
CS
4986 /* Check vCont support and set the remote state's vCont_action_support
4987 attribute. */
4988 remote_vcont_probe ();
4989
d914c394 4990 /* If the stub wants to get a QAllow, compose one and send it. */
ff52c073 4991 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4992 set_permissions ();
d914c394 4993
57809e5e
JK
4994 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4995 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4996 as a reply to known packet. For packet "vFile:setfs:" it is an
4997 invalid reply and GDB would return error in
4998 remote_hostio_set_filesystem, making remote files access impossible.
4999 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5000 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5001 {
5002 const char v_mustreplyempty[] = "vMustReplyEmpty";
5003
5004 putpkt (v_mustreplyempty);
aa7b36b8 5005 getpkt (&rs->buf);
8d64371b 5006 if (strcmp (rs->buf.data (), "OK") == 0)
ff52c073
CS
5007 {
5008 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5009 = PACKET_DISABLE;
5010 }
8d64371b 5011 else if (strcmp (rs->buf.data (), "") != 0)
57809e5e 5012 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
8d64371b 5013 rs->buf.data ());
57809e5e
JK
5014 }
5015
c8d104ad
PA
5016 /* Next, we possibly activate noack mode.
5017
5018 If the QStartNoAckMode packet configuration is set to AUTO,
5019 enable noack mode if the stub reported a wish for it with
5020 qSupported.
5021
5022 If set to TRUE, then enable noack mode even if the stub didn't
5023 report it in qSupported. If the stub doesn't reply OK, the
5024 session ends with an error.
5025
5026 If FALSE, then don't activate noack mode, regardless of what the
5027 stub claimed should be the default with qSupported. */
5028
ff52c073 5029 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
c8d104ad
PA
5030 {
5031 putpkt ("QStartNoAckMode");
aa7b36b8 5032 getpkt (&rs->buf);
ff52c073 5033 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
c8d104ad
PA
5034 rs->noack_mode = 1;
5035 }
5036
04bd08de 5037 if (extended_p)
5fe04517
PA
5038 {
5039 /* Tell the remote that we are using the extended protocol. */
5040 putpkt ("!");
aa7b36b8 5041 getpkt (&rs->buf);
5fe04517
PA
5042 }
5043
9b224c5e
PA
5044 /* Let the target know which signals it is allowed to pass down to
5045 the program. */
5046 update_signals_program_target ();
5047
d962ef82
DJ
5048 /* Next, if the target can specify a description, read it. We do
5049 this before anything involving memory or registers. */
5050 target_find_description ();
5051
6c95b8df
PA
5052 /* Next, now that we know something about the target, update the
5053 address spaces in the program spaces. */
5054 update_address_spaces ();
5055
50c71eaf
PA
5056 /* On OSs where the list of libraries is global to all
5057 processes, we fetch them early. */
99d9c3b9 5058 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
e696b3ad 5059 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 5060
6efcd9a8 5061 if (target_is_non_stop_p ())
74531fed 5062 {
ff52c073 5063 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
5064 error (_("Non-stop mode requested, but remote "
5065 "does not support non-stop"));
74531fed
PA
5066
5067 putpkt ("QNonStop:1");
aa7b36b8 5068 getpkt (&rs->buf);
74531fed 5069
8d64371b
TT
5070 if (strcmp (rs->buf.data (), "OK") != 0)
5071 error (_("Remote refused setting non-stop mode with: %s"),
5072 rs->buf.data ());
74531fed
PA
5073
5074 /* Find about threads and processes the stub is already
5075 controlling. We default to adding them in the running state.
5076 The '?' query below will then tell us about which threads are
5077 stopped. */
f6ac5f3d 5078 this->update_thread_list ();
74531fed 5079 }
ff52c073 5080 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
5081 {
5082 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 5083 Request it explicitly. */
74531fed 5084 putpkt ("QNonStop:0");
aa7b36b8 5085 getpkt (&rs->buf);
74531fed 5086
8d64371b
TT
5087 if (strcmp (rs->buf.data (), "OK") != 0)
5088 error (_("Remote refused setting all-stop mode with: %s"),
5089 rs->buf.data ());
74531fed
PA
5090 }
5091
a0743c90
YQ
5092 /* Upload TSVs regardless of whether the target is running or not. The
5093 remote stub, such as GDBserver, may have some predefined or builtin
5094 TSVs, even if the target is not running. */
f6ac5f3d 5095 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
5096 {
5097 struct uploaded_tsv *uploaded_tsvs = NULL;
5098
f6ac5f3d 5099 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
5100 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5101 }
5102
2d717e4f
DJ
5103 /* Check whether the target is running now. */
5104 putpkt ("?");
aa7b36b8 5105 getpkt (&rs->buf);
2d717e4f 5106
6efcd9a8 5107 if (!target_is_non_stop_p ())
2d717e4f 5108 {
b5c8f22d
SM
5109 char *wait_status = NULL;
5110
74531fed 5111 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 5112 {
04bd08de 5113 if (!extended_p)
74531fed 5114 error (_("The target is not running (try extended-remote?)"));
288712bb 5115 return false;
2d717e4f
DJ
5116 }
5117 else
74531fed 5118 {
74531fed 5119 /* Save the reply for later. */
8d64371b
TT
5120 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5121 strcpy (wait_status, rs->buf.data ());
74531fed
PA
5122 }
5123
b7ea362b 5124 /* Fetch thread list. */
e8032dde 5125 target_update_thread_list ();
b7ea362b 5126
74531fed
PA
5127 /* Let the stub know that we want it to return the thread. */
5128 set_continue_thread (minus_one_ptid);
5129
5b6d1e4f 5130 if (thread_count (this) == 0)
b7ea362b
PA
5131 {
5132 /* Target has no concept of threads at all. GDB treats
5133 non-threaded target as single-threaded; add a main
5134 thread. */
64d38fdd
JM
5135 thread_info *tp = add_current_inferior_and_thread (wait_status);
5136 get_remote_thread_info (tp)->set_resumed ();
b7ea362b
PA
5137 }
5138 else
5139 {
5140 /* We have thread information; select the thread the target
5141 says should be current. If we're reconnecting to a
5142 multi-threaded program, this will ideally be the thread
5143 that last reported an event before GDB disconnected. */
75c6c844
PA
5144 ptid_t curr_thread = get_current_thread (wait_status);
5145 if (curr_thread == null_ptid)
b7ea362b
PA
5146 {
5147 /* Odd... The target was able to list threads, but not
5148 tell us which thread was current (no "thread"
5149 register in T stop reply?). Just pick the first
5150 thread in the thread list then. */
2189c312
SM
5151
5152 remote_debug_printf ("warning: couldn't determine remote "
5153 "current thread; picking first in list.");
c9f35b34 5154
5b6d1e4f
PA
5155 for (thread_info *tp : all_non_exited_threads (this,
5156 minus_one_ptid))
75c6c844
PA
5157 {
5158 switch_to_thread (tp);
5159 break;
5160 }
b7ea362b 5161 }
75c6c844 5162 else
9213a6d7 5163 switch_to_thread (this->find_thread (curr_thread));
b7ea362b 5164 }
74531fed 5165
6e586cc5
YQ
5166 /* init_wait_for_inferior should be called before get_offsets in order
5167 to manage `inserted' flag in bp loc in a correct state.
5168 breakpoint_init_inferior, called from init_wait_for_inferior, set
5169 `inserted' flag to 0, while before breakpoint_re_set, called from
5170 start_remote, set `inserted' flag to 1. In the initialization of
5171 inferior, breakpoint_init_inferior should be called first, and then
5172 breakpoint_re_set can be called. If this order is broken, state of
5173 `inserted' flag is wrong, and cause some problems on breakpoint
5174 manipulation. */
5175 init_wait_for_inferior ();
5176
74531fed
PA
5177 get_offsets (); /* Get text, data & bss offsets. */
5178
d962ef82
DJ
5179 /* If we could not find a description using qXfer, and we know
5180 how to do it some other way, try again. This is not
5181 supported for non-stop; it could be, but it is tricky if
5182 there are no stopped threads when we connect. */
f6ac5f3d 5183 if (remote_read_description_p (this)
99d9c3b9 5184 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
d962ef82
DJ
5185 {
5186 target_clear_description ();
5187 target_find_description ();
5188 }
5189
74531fed
PA
5190 /* Use the previously fetched status. */
5191 gdb_assert (wait_status != NULL);
4f626cad
AB
5192 struct notif_event *reply
5193 = remote_notif_parse (this, &notif_client_stop, wait_status);
5194 push_stop_reply ((struct stop_reply *) reply);
74531fed 5195
f6ac5f3d 5196 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
5197 }
5198 else
5199 {
68c97600
PA
5200 /* Clear WFI global state. Do this before finding about new
5201 threads and inferiors, and setting the current inferior.
5202 Otherwise we would clear the proceed status of the current
5203 inferior when we want its stop_soon state to be preserved
5204 (see notice_new_inferior). */
5205 init_wait_for_inferior ();
5206
74531fed
PA
5207 /* In non-stop, we will either get an "OK", meaning that there
5208 are no stopped threads at this time; or, a regular stop
5209 reply. In the latter case, there may be more than one thread
5210 stopped --- we pull them all out using the vStopped
5211 mechanism. */
8d64371b 5212 if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 5213 {
42938c1a 5214 const notif_client *notif = &notif_client_stop;
2d717e4f 5215
722247f1
YQ
5216 /* remote_notif_get_pending_replies acks this one, and gets
5217 the rest out. */
f48ff2a7 5218 rs->notif_state->pending_event[notif_client_stop.id]
8d64371b 5219 = remote_notif_parse (this, notif, rs->buf.data ());
722247f1 5220 remote_notif_get_pending_events (notif);
74531fed 5221 }
2d717e4f 5222
5b6d1e4f 5223 if (thread_count (this) == 0)
74531fed 5224 {
04bd08de 5225 if (!extended_p)
74531fed 5226 error (_("The target is not running (try extended-remote?)"));
288712bb 5227 return false;
c35b1492 5228 }
74531fed 5229
2455069d 5230 /* Report all signals during attach/startup. */
adc6a863 5231 pass_signals ({});
221e1a37
PA
5232
5233 /* If there are already stopped threads, mark them stopped and
5234 report their stops before giving the prompt to the user. */
6efcd9a8 5235 process_initial_stop_replies (from_tty);
221e1a37
PA
5236
5237 if (target_can_async_p ())
4a570176 5238 target_async (true);
74531fed 5239 }
c8d104ad 5240
901e4e8d
SM
5241 /* Give the target a chance to look up symbols. */
5242 for (inferior *inf : all_inferiors (this))
c8d104ad 5243 {
901e4e8d
SM
5244 /* The inferiors that exist at this point were created from what
5245 was found already running on the remote side, so we know they
5246 have execution. */
5247 gdb_assert (this->has_execution (inf));
5248
a42d7dd8 5249 /* No use without a symbol-file. */
901e4e8d
SM
5250 if (inf->pspace->symfile_object_file == nullptr)
5251 continue;
5252
5253 /* Need to switch to a specific thread, because remote_check_symbols
287de656 5254 uses INFERIOR_PTID to set the general thread. */
901e4e8d
SM
5255 scoped_restore_current_thread restore_thread;
5256 thread_info *thread = any_thread_of_inferior (inf);
5257 switch_to_thread (thread);
5258 this->remote_check_symbols ();
c8d104ad 5259 }
50c71eaf 5260
d5551862
SS
5261 /* Possibly the target has been engaged in a trace run started
5262 previously; find out where things are at. */
f6ac5f3d 5263 if (get_trace_status (current_trace_status ()) != -1)
d5551862 5264 {
00bf0b85 5265 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 5266
00bf0b85 5267 if (current_trace_status ()->running)
6cb06a8c 5268 gdb_printf (_("Trace is already running on the target.\n"));
00bf0b85 5269
f6ac5f3d 5270 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
5271
5272 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
5273 }
5274
c0272db5
TW
5275 /* Possibly the target has been engaged in a btrace record started
5276 previously; find out where things are at. */
5277 remote_btrace_maybe_reopen ();
5278
288712bb
AB
5279 return true;
5280}
5281
5282/* Start the remote connection and sync state. */
1e51243a 5283
288712bb
AB
5284void
5285remote_target::start_remote (int from_tty, int extended_p)
5286{
5287 if (start_remote_1 (from_tty, extended_p)
5288 && breakpoints_should_be_inserted_now ())
50c71eaf 5289 insert_breakpoints ();
c906108c
SS
5290}
5291
121b3efd
PA
5292const char *
5293remote_target::connection_string ()
5294{
5295 remote_state *rs = get_remote_state ();
5296
5297 if (rs->remote_desc->name != NULL)
5298 return rs->remote_desc->name;
5299 else
5300 return NULL;
5301}
5302
c906108c
SS
5303/* Open a connection to a remote debugger.
5304 NAME is the filename used for communication. */
5305
f6ac5f3d
PA
5306void
5307remote_target::open (const char *name, int from_tty)
c906108c 5308{
f6ac5f3d 5309 open_1 (name, from_tty, 0);
43ff13b4
JM
5310}
5311
c906108c
SS
5312/* Open a connection to a remote debugger using the extended
5313 remote gdb protocol. NAME is the filename used for communication. */
5314
f6ac5f3d
PA
5315void
5316extended_remote_target::open (const char *name, int from_tty)
c906108c 5317{
f6ac5f3d 5318 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
5319}
5320
ff52c073
CS
5321void
5322remote_features::reset_all_packet_configs_support ()
d471ea57
AC
5323{
5324 int i;
a744cf53 5325
444abaca 5326 for (i = 0; i < PACKET_MAX; i++)
ff52c073 5327 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
5328}
5329
ca4f7f8b
PA
5330/* Initialize all packet configs. */
5331
5332static void
5333init_all_packet_configs (void)
5334{
5335 int i;
5336
5337 for (i = 0; i < PACKET_MAX; i++)
5338 {
5339 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5340 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5341 }
5342}
5343
23860348 5344/* Symbol look-up. */
dc8acb97 5345
6b8edb51
PA
5346void
5347remote_target::remote_check_symbols ()
dc8acb97 5348{
8d64371b 5349 char *tmp;
dc8acb97
MS
5350 int end;
5351
06c7226e
SM
5352 /* It doesn't make sense to send a qSymbol packet for an inferior that
5353 doesn't have execution, because the remote side doesn't know about
5354 inferiors without execution. */
5355 gdb_assert (target_has_execution ());
63154eca 5356
ff52c073 5357 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
5358 return;
5359
63154eca
PA
5360 /* Make sure the remote is pointing at the right process. Note
5361 there's no way to select "no process". */
3c9c4b83
PA
5362 set_general_process ();
5363
6d820c5c
DJ
5364 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5365 because we need both at the same time. */
66644cd3 5366 gdb::char_vector msg (get_remote_packet_size ());
8d64371b 5367 gdb::char_vector reply (get_remote_packet_size ());
6d820c5c 5368
23860348 5369 /* Invite target to request symbol lookups. */
dc8acb97
MS
5370
5371 putpkt ("qSymbol::");
aa7b36b8 5372 getpkt (&reply);
ff52c073 5373 m_features.packet_ok (reply, PACKET_qSymbol);
dc8acb97 5374
8d64371b 5375 while (startswith (reply.data (), "qSymbol:"))
dc8acb97 5376 {
77e371c0
TT
5377 struct bound_minimal_symbol sym;
5378
dc8acb97 5379 tmp = &reply[8];
66644cd3
AB
5380 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5381 strlen (tmp) / 2);
dc8acb97 5382 msg[end] = '\0';
66644cd3 5383 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
3b7344d5 5384 if (sym.minsym == NULL)
66644cd3
AB
5385 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5386 &reply[8]);
dc8acb97 5387 else
2bbe3cc1 5388 {
99d9c3b9 5389 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
4aeddc50 5390 CORE_ADDR sym_addr = sym.value_address ();
2bbe3cc1
DJ
5391
5392 /* If this is a function address, return the start of code
5393 instead of any data function descriptor. */
328d42d8 5394 sym_addr = gdbarch_convert_from_func_ptr_addr
99d9c3b9
SM
5395 (current_inferior ()->arch (), sym_addr,
5396 current_inferior ()->top_target ());
2bbe3cc1 5397
66644cd3 5398 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 5399 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1 5400 }
66644cd3
AB
5401
5402 putpkt (msg.data ());
aa7b36b8 5403 getpkt (&reply);
dc8acb97
MS
5404 }
5405}
5406
9db8d71f 5407static struct serial *
baa336ce 5408remote_serial_open (const char *name)
9db8d71f
DJ
5409{
5410 static int udp_warning = 0;
5411
5412 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5413 of in ser-tcp.c, because it is the remote protocol assuming that the
5414 serial connection is reliable and not the serial connection promising
5415 to be. */
61012eef 5416 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 5417 {
3e43a32a
MS
5418 warning (_("The remote protocol may be unreliable over UDP.\n"
5419 "Some events may be lost, rendering further debugging "
5420 "impossible."));
9db8d71f
DJ
5421 udp_warning = 1;
5422 }
5423
5424 return serial_open (name);
5425}
5426
d914c394
SS
5427/* Inform the target of our permission settings. The permission flags
5428 work without this, but if the target knows the settings, it can do
5429 a couple things. First, it can add its own check, to catch cases
5430 that somehow manage to get by the permissions checks in target
5431 methods. Second, if the target is wired to disallow particular
5432 settings (for instance, a system in the field that is not set up to
5433 be able to stop at a breakpoint), it can object to any unavailable
5434 permissions. */
5435
5436void
f6ac5f3d 5437remote_target::set_permissions ()
d914c394
SS
5438{
5439 struct remote_state *rs = get_remote_state ();
5440
8d64371b 5441 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
bba74b36
YQ
5442 "WriteReg:%x;WriteMem:%x;"
5443 "InsertBreak:%x;InsertTrace:%x;"
5444 "InsertFastTrace:%x;Stop:%x",
5445 may_write_registers, may_write_memory,
5446 may_insert_breakpoints, may_insert_tracepoints,
5447 may_insert_fast_tracepoints, may_stop);
d914c394 5448 putpkt (rs->buf);
aa7b36b8 5449 getpkt (&rs->buf);
d914c394
SS
5450
5451 /* If the target didn't like the packet, warn the user. Do not try
5452 to undo the user's settings, that would just be maddening. */
8d64371b
TT
5453 if (strcmp (rs->buf.data (), "OK") != 0)
5454 warning (_("Remote refused setting permissions with: %s"),
5455 rs->buf.data ());
d914c394
SS
5456}
5457
be2a5f71
DJ
5458/* This type describes each known response to the qSupported
5459 packet. */
5460struct protocol_feature
5461{
5462 /* The name of this protocol feature. */
5463 const char *name;
5464
5465 /* The default for this protocol feature. */
5466 enum packet_support default_support;
5467
5468 /* The function to call when this feature is reported, or after
5469 qSupported processing if the feature is not supported.
5470 The first argument points to this structure. The second
5471 argument indicates whether the packet requested support be
5472 enabled, disabled, or probed (or the default, if this function
5473 is being called at the end of processing and this feature was
5474 not reported). The third argument may be NULL; if not NULL, it
5475 is a NUL-terminated string taken from the packet following
5476 this feature's name and an equals sign. */
6b8edb51
PA
5477 void (*func) (remote_target *remote, const struct protocol_feature *,
5478 enum packet_support, const char *);
be2a5f71
DJ
5479
5480 /* The corresponding packet for this feature. Only used if
5481 FUNC is remote_supported_packet. */
5482 int packet;
5483};
5484
be2a5f71 5485static void
6b8edb51
PA
5486remote_supported_packet (remote_target *remote,
5487 const struct protocol_feature *feature,
be2a5f71
DJ
5488 enum packet_support support,
5489 const char *argument)
5490{
5491 if (argument)
5492 {
5493 warning (_("Remote qSupported response supplied an unexpected value for"
5494 " \"%s\"."), feature->name);
5495 return;
5496 }
5497
ff52c073 5498 remote->m_features.m_protocol_packets[feature->packet].support = support;
be2a5f71 5499}
be2a5f71 5500
6b8edb51
PA
5501void
5502remote_target::remote_packet_size (const protocol_feature *feature,
5503 enum packet_support support, const char *value)
be2a5f71
DJ
5504{
5505 struct remote_state *rs = get_remote_state ();
5506
5507 int packet_size;
5508 char *value_end;
5509
5510 if (support != PACKET_ENABLE)
5511 return;
5512
5513 if (value == NULL || *value == '\0')
5514 {
5515 warning (_("Remote target reported \"%s\" without a size."),
5516 feature->name);
5517 return;
5518 }
5519
5520 errno = 0;
5521 packet_size = strtol (value, &value_end, 16);
5522 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5523 {
5524 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5525 feature->name, value);
5526 return;
5527 }
5528
be2a5f71
DJ
5529 /* Record the new maximum packet size. */
5530 rs->explicit_packet_size = packet_size;
5531}
5532
cb8c24b6 5533static void
6b8edb51
PA
5534remote_packet_size (remote_target *remote, const protocol_feature *feature,
5535 enum packet_support support, const char *value)
5536{
5537 remote->remote_packet_size (feature, support, value);
5538}
5539
dc473cfb 5540static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5541 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5542 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5543 PACKET_qXfer_auxv },
c78fa86a
GB
5544 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5545 PACKET_qXfer_exec_file },
23181151
DJ
5546 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5547 PACKET_qXfer_features },
cfa9d6d9
DJ
5548 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5549 PACKET_qXfer_libraries },
2268b414
JK
5550 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5551 PACKET_qXfer_libraries_svr4 },
ced63ec0 5552 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5553 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5554 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5555 PACKET_qXfer_memory_map },
07e059b5
VP
5556 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5557 PACKET_qXfer_osdata },
dc146f7c
VP
5558 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5559 PACKET_qXfer_threads },
b3b9301e
PA
5560 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5561 PACKET_qXfer_traceframe_info },
89be2091
DJ
5562 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5563 PACKET_QPassSignals },
82075af2
JS
5564 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5565 PACKET_QCatchSyscalls },
9b224c5e
PA
5566 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5567 PACKET_QProgramSignals },
bc3b087d
SDJ
5568 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5569 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5570 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5571 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5572 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5573 PACKET_QEnvironmentHexEncoded },
5574 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5575 PACKET_QEnvironmentReset },
5576 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5577 PACKET_QEnvironmentUnset },
a6f3e723
SL
5578 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5579 PACKET_QStartNoAckMode },
4082afcc
PA
5580 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5581 PACKET_multiprocess_feature },
5582 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5583 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5584 PACKET_qXfer_siginfo_read },
5585 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5586 PACKET_qXfer_siginfo_write },
4082afcc 5587 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5588 PACKET_ConditionalTracepoints },
4082afcc 5589 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5590 PACKET_ConditionalBreakpoints },
4082afcc 5591 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5592 PACKET_BreakpointCommands },
4082afcc 5593 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5594 PACKET_FastTracepoints },
4082afcc 5595 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5596 PACKET_StaticTracepoints },
4082afcc 5597 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5598 PACKET_InstallInTrace},
4082afcc
PA
5599 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5600 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5601 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5602 PACKET_bc },
5603 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5604 PACKET_bs },
409873ef
SS
5605 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5606 PACKET_TracepointSource },
d914c394
SS
5607 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5608 PACKET_QAllow },
4082afcc
PA
5609 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5610 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5611 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5612 PACKET_qXfer_fdpic },
169081d0
TG
5613 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5614 PACKET_qXfer_uib },
03583c20
UW
5615 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5616 PACKET_QDisableRandomization },
d1feda86 5617 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5618 { "QTBuffer:size", PACKET_DISABLE,
5619 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5620 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5621 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5622 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5623 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5624 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5625 PACKET_qXfer_btrace },
5626 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5627 PACKET_qXfer_btrace_conf },
5628 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5629 PACKET_Qbtrace_conf_bts_size },
5630 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5631 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5632 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5633 PACKET_fork_event_feature },
5634 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5635 PACKET_vfork_event_feature },
94585166
DB
5636 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5637 PACKET_exec_event_feature },
b20a6524 5638 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5639 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5640 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5641 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5642 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
2c2e7f87
LM
5643 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5644 PACKET_memory_tagging_feature },
be2a5f71
DJ
5645};
5646
c8d5aac9
L
5647static char *remote_support_xml;
5648
5649/* Register string appended to "xmlRegisters=" in qSupported query. */
5650
5651void
6e39997a 5652register_remote_support_xml (const char *xml)
c8d5aac9
L
5653{
5654#if defined(HAVE_LIBEXPAT)
5655 if (remote_support_xml == NULL)
c4f7c687 5656 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5657 else
5658 {
5659 char *copy = xstrdup (remote_support_xml + 13);
ca3a04f6
CB
5660 char *saveptr;
5661 char *p = strtok_r (copy, ",", &saveptr);
c8d5aac9
L
5662
5663 do
5664 {
5665 if (strcmp (p, xml) == 0)
5666 {
5667 /* already there */
5668 xfree (copy);
5669 return;
5670 }
5671 }
ca3a04f6 5672 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
c8d5aac9
L
5673 xfree (copy);
5674
94b0dee1
PA
5675 remote_support_xml = reconcat (remote_support_xml,
5676 remote_support_xml, ",", xml,
5677 (char *) NULL);
c8d5aac9
L
5678 }
5679#endif
5680}
5681
69b6ecb0
TT
5682static void
5683remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5684{
69b6ecb0
TT
5685 if (!msg->empty ())
5686 msg->append (";");
5687 msg->append (append);
c8d5aac9
L
5688}
5689
6b8edb51
PA
5690void
5691remote_target::remote_query_supported ()
be2a5f71
DJ
5692{
5693 struct remote_state *rs = get_remote_state ();
5694 char *next;
5695 int i;
5696 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5697
5698 /* The packet support flags are handled differently for this packet
5699 than for most others. We treat an error, a disabled packet, and
5700 an empty response identically: any features which must be reported
5701 to be used will be automatically disabled. An empty buffer
5702 accomplishes this, since that is also the representation for a list
5703 containing no features. */
5704
5705 rs->buf[0] = 0;
ff52c073 5706 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5707 {
69b6ecb0 5708 std::string q;
c8d5aac9 5709
ff52c073
CS
5710 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5711 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5712 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5713
ff52c073
CS
5714 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5715 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5716 remote_query_supported_append (&q, "swbreak+");
ff52c073
CS
5717
5718 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5719 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5720 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5721
69b6ecb0 5722 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5723
ff52c073 5724 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
8020350c 5725 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5726 remote_query_supported_append (&q, "fork-events+");
ff52c073
CS
5727
5728 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
8020350c 5729 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5730 remote_query_supported_append (&q, "vfork-events+");
ff52c073
CS
5731
5732 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
8020350c 5733 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5734 remote_query_supported_append (&q, "exec-events+");
89245bc0 5735
ff52c073
CS
5736 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5737 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5738 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5739
ff52c073
CS
5740 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5741 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5742 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5743
ff52c073
CS
5744 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5745 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5746 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5747
ff52c073 5748 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
2c2e7f87
LM
5749 != AUTO_BOOLEAN_FALSE)
5750 remote_query_supported_append (&q, "memory-tagging+");
5751
b35d5edb
PA
5752 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5753 the qSupported:xmlRegisters=i386 handling. */
7cc244de 5754 if (remote_support_xml != NULL
ff52c073
CS
5755 && (m_features.packet_support (PACKET_qXfer_features)
5756 != PACKET_DISABLE))
69b6ecb0 5757 remote_query_supported_append (&q, remote_support_xml);
82f73884 5758
69b6ecb0
TT
5759 q = "qSupported:" + q;
5760 putpkt (q.c_str ());
94b0dee1 5761
aa7b36b8 5762 getpkt (&rs->buf);
be2a5f71 5763
33b5899f 5764 /* If an error occurred, warn, but do not return - just reset the
be2a5f71 5765 buffer to empty and go on to disable features. */
ff52c073 5766 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
be2a5f71 5767 {
8d64371b 5768 warning (_("Remote failure reply: %s"), rs->buf.data ());
be2a5f71
DJ
5769 rs->buf[0] = 0;
5770 }
5771 }
5772
5773 memset (seen, 0, sizeof (seen));
5774
8d64371b 5775 next = rs->buf.data ();
be2a5f71
DJ
5776 while (*next)
5777 {
5778 enum packet_support is_supported;
5779 char *p, *end, *name_end, *value;
5780
5781 /* First separate out this item from the rest of the packet. If
5782 there's another item after this, we overwrite the separator
5783 (terminated strings are much easier to work with). */
5784 p = next;
5785 end = strchr (p, ';');
5786 if (end == NULL)
5787 {
5788 end = p + strlen (p);
5789 next = end;
5790 }
5791 else
5792 {
89be2091
DJ
5793 *end = '\0';
5794 next = end + 1;
5795
be2a5f71
DJ
5796 if (end == p)
5797 {
5798 warning (_("empty item in \"qSupported\" response"));
5799 continue;
5800 }
be2a5f71
DJ
5801 }
5802
5803 name_end = strchr (p, '=');
5804 if (name_end)
5805 {
5806 /* This is a name=value entry. */
5807 is_supported = PACKET_ENABLE;
5808 value = name_end + 1;
5809 *name_end = '\0';
5810 }
5811 else
5812 {
5813 value = NULL;
5814 switch (end[-1])
5815 {
5816 case '+':
5817 is_supported = PACKET_ENABLE;
5818 break;
5819
5820 case '-':
5821 is_supported = PACKET_DISABLE;
5822 break;
5823
5824 case '?':
5825 is_supported = PACKET_SUPPORT_UNKNOWN;
5826 break;
5827
5828 default:
3e43a32a
MS
5829 warning (_("unrecognized item \"%s\" "
5830 "in \"qSupported\" response"), p);
be2a5f71
DJ
5831 continue;
5832 }
5833 end[-1] = '\0';
5834 }
5835
5836 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5837 if (strcmp (remote_protocol_features[i].name, p) == 0)
5838 {
5839 const struct protocol_feature *feature;
5840
5841 seen[i] = 1;
5842 feature = &remote_protocol_features[i];
6b8edb51 5843 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5844 break;
5845 }
5846 }
5847
5848 /* If we increased the packet size, make sure to increase the global
5849 buffer size also. We delay this until after parsing the entire
5850 qSupported packet, because this is the same buffer we were
5851 parsing. */
8d64371b
TT
5852 if (rs->buf.size () < rs->explicit_packet_size)
5853 rs->buf.resize (rs->explicit_packet_size);
be2a5f71
DJ
5854
5855 /* Handle the defaults for unmentioned features. */
5856 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5857 if (!seen[i])
5858 {
5859 const struct protocol_feature *feature;
5860
5861 feature = &remote_protocol_features[i];
6b8edb51 5862 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5863 }
5864}
5865
048094ac
PA
5866/* Serial QUIT handler for the remote serial descriptor.
5867
5868 Defers handling a Ctrl-C until we're done with the current
5869 command/response packet sequence, unless:
5870
5871 - We're setting up the connection. Don't send a remote interrupt
5872 request, as we're not fully synced yet. Quit immediately
5873 instead.
5874
5875 - The target has been resumed in the foreground
223ffa71 5876 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5877 packet, and we're blocked waiting for the stop reply, thus a
5878 Ctrl-C should be immediately sent to the target.
5879
5880 - We get a second Ctrl-C while still within the same serial read or
5881 write. In that case the serial is seemingly wedged --- offer to
5882 quit/disconnect.
5883
5884 - We see a second Ctrl-C without target response, after having
5885 previously interrupted the target. In that case the target/stub
5886 is probably wedged --- offer to quit/disconnect.
5887*/
5888
6b8edb51
PA
5889void
5890remote_target::remote_serial_quit_handler ()
048094ac
PA
5891{
5892 struct remote_state *rs = get_remote_state ();
5893
5894 if (check_quit_flag ())
5895 {
5896 /* If we're starting up, we're not fully synced yet. Quit
5897 immediately. */
5898 if (rs->starting_up)
5899 quit ();
5900 else if (rs->got_ctrlc_during_io)
5901 {
5902 if (query (_("The target is not responding to GDB commands.\n"
5903 "Stop debugging it? ")))
5b6d1e4f 5904 remote_unpush_and_throw (this);
048094ac
PA
5905 }
5906 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5907 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5908 interrupt_query ();
5909 /* All-stop protocol, and blocked waiting for stop reply. Send
5910 an interrupt request. */
223ffa71 5911 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5912 target_interrupt ();
048094ac
PA
5913 else
5914 rs->got_ctrlc_during_io = 1;
5915 }
5916}
5917
6b8edb51
PA
5918/* The remote_target that is current while the quit handler is
5919 overridden with remote_serial_quit_handler. */
5920static remote_target *curr_quit_handler_target;
5921
5922static void
5923remote_serial_quit_handler ()
5924{
5925 curr_quit_handler_target->remote_serial_quit_handler ();
5926}
5927
5b6d1e4f
PA
5928/* Remove the remote target from the target stack of each inferior
5929 that is using it. Upper targets depend on it so remove them
5930 first. */
78a095c3
JK
5931
5932static void
5b6d1e4f 5933remote_unpush_target (remote_target *target)
78a095c3 5934{
5b6d1e4f
PA
5935 /* We have to unpush the target from all inferiors, even those that
5936 aren't running. */
5937 scoped_restore_current_inferior restore_current_inferior;
5938
5939 for (inferior *inf : all_inferiors (target))
5940 {
5941 switch_to_inferior_no_thread (inf);
c8181f70 5942 inf->pop_all_targets_at_and_above (process_stratum);
5b6d1e4f
PA
5943 generic_mourn_inferior ();
5944 }
d7cb0ef3
PA
5945
5946 /* Don't rely on target_close doing this when the target is popped
5947 from the last remote inferior above, because something may be
5948 holding a reference to the target higher up on the stack, meaning
5949 target_close won't be called yet. We lost the connection to the
5950 target, so clear these now, otherwise we may later throw
5951 TARGET_CLOSE_ERROR while trying to tell the remote target to
5952 close the file. */
5953 fileio_handles_invalidate_target (target);
78a095c3 5954}
be2a5f71 5955
048094ac 5956static void
5b6d1e4f 5957remote_unpush_and_throw (remote_target *target)
048094ac 5958{
5b6d1e4f 5959 remote_unpush_target (target);
048094ac
PA
5960 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5961}
5962
f6ac5f3d
PA
5963void
5964remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5965{
6b8edb51 5966 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5967
c906108c 5968 if (name == 0)
8a3fe4f8 5969 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5970 "serial device is attached to the remote system\n"
8a3fe4f8 5971 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5972
2d717e4f 5973 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5974 Ask this question first, before target_preopen has a chance to kill
5975 anything. */
55f6301a 5976 if (curr_remote != NULL && !target_has_execution ())
2d717e4f 5977 {
78a095c3
JK
5978 if (from_tty
5979 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5980 error (_("Still connected."));
5981 }
5982
78a095c3 5983 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5984 target_preopen (from_tty);
5985
ad9a8f3f 5986 remote_fileio_reset ();
1dd41f16 5987 reopen_exec_file ();
9dec38d3 5988 reread_symbols (from_tty);
1dd41f16 5989
6b8edb51
PA
5990 remote_target *remote
5991 = (extended_p ? new extended_remote_target () : new remote_target ());
5992 target_ops_up target_holder (remote);
5993
5994 remote_state *rs = remote->get_remote_state ();
5995
5996 /* See FIXME above. */
5997 if (!target_async_permitted)
8756b726 5998 rs->wait_forever_enabled_p = true;
6b8edb51 5999
5d93a237
TT
6000 rs->remote_desc = remote_serial_open (name);
6001 if (!rs->remote_desc)
c906108c
SS
6002 perror_with_name (name);
6003
6004 if (baud_rate != -1)
6005 {
5d93a237 6006 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 6007 {
9b74d5d3
KB
6008 /* The requested speed could not be set. Error out to
6009 top level after closing remote_desc. Take care to
6010 set remote_desc to NULL to avoid closing remote_desc
6011 more than once. */
5d93a237
TT
6012 serial_close (rs->remote_desc);
6013 rs->remote_desc = NULL;
c906108c
SS
6014 perror_with_name (name);
6015 }
6016 }
6017
236af5e3 6018 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 6019 serial_raw (rs->remote_desc);
c906108c
SS
6020
6021 /* If there is something sitting in the buffer we might take it as a
6022 response to a command, which would be bad. */
5d93a237 6023 serial_flush_input (rs->remote_desc);
c906108c
SS
6024
6025 if (from_tty)
6026 {
0426ad51
TT
6027 gdb_puts ("Remote debugging using ");
6028 gdb_puts (name);
6029 gdb_puts ("\n");
c906108c 6030 }
d9f719f1 6031
6b8edb51 6032 /* Switch to using the remote target now. */
02980c56 6033 current_inferior ()->push_target (std::move (target_holder));
c906108c 6034
74531fed 6035 /* Register extra event sources in the event loop. */
92b98b37
SM
6036 rs->create_async_event_handler ();
6037
6b8edb51 6038 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 6039
be2a5f71
DJ
6040 /* Reset the target state; these things will be queried either by
6041 remote_query_supported or as they are needed. */
ff52c073 6042 remote->m_features.reset_all_packet_configs_support ();
be2a5f71 6043 rs->explicit_packet_size = 0;
a6f3e723 6044 rs->noack_mode = 0;
82f73884 6045 rs->extended = extended_p;
e24a49d8 6046 rs->waiting_for_stop_reply = 0;
3a29589a 6047 rs->ctrlc_pending_p = 0;
048094ac 6048 rs->got_ctrlc_during_io = 0;
802188a7 6049
47f8a51d
TT
6050 rs->general_thread = not_sent_ptid;
6051 rs->continue_thread = not_sent_ptid;
262e1174 6052 rs->remote_traceframe_number = -1;
c906108c 6053
3a00c802
PA
6054 rs->last_resume_exec_dir = EXEC_FORWARD;
6055
9d1f7ab2 6056 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
6057 rs->use_threadinfo_query = 1;
6058 rs->use_threadextra_query = 1;
9d1f7ab2 6059
dd194f6b 6060 rs->readahead_cache.invalidate ();
80152258 6061
c6ebd6cf 6062 if (target_async_permitted)
92d1e331 6063 {
92d1e331
DJ
6064 /* FIXME: cagney/1999-09-23: During the initial connection it is
6065 assumed that the target is already ready and able to respond to
0df8b418 6066 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 6067 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 6068 around this. Eventually a mechanism that allows
92d1e331 6069 wait_for_inferior() to expect/get timeouts will be
23860348 6070 implemented. */
8756b726 6071 rs->wait_forever_enabled_p = false;
92d1e331
DJ
6072 }
6073
23860348 6074 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 6075 no_shared_libraries (NULL, 0);
f78f6cf1 6076
36918e70 6077 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
6078 target (we'd otherwise be in an inconsistent state) and then
6079 propogate the error on up the exception chain. This ensures that
6080 the caller doesn't stumble along blindly assuming that the
6081 function succeeded. The CLI doesn't have this problem but other
6082 UI's, such as MI do.
36918e70
AC
6083
6084 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6085 this function should return an error indication letting the
ce2826aa 6086 caller restore the previous state. Unfortunately the command
36918e70
AC
6087 ``target remote'' is directly wired to this function making that
6088 impossible. On a positive note, the CLI side of this problem has
6089 been fixed - the function set_cmd_context() makes it possible for
6090 all the ``target ....'' commands to share a common callback
6091 function. See cli-dump.c. */
109c3e39 6092 {
2d717e4f 6093
a70b8144 6094 try
04bd08de 6095 {
6b8edb51 6096 remote->start_remote (from_tty, extended_p);
04bd08de 6097 }
230d2906 6098 catch (const gdb_exception &ex)
109c3e39 6099 {
c8d104ad
PA
6100 /* Pop the partially set up target - unless something else did
6101 already before throwing the exception. */
6b8edb51 6102 if (ex.error != TARGET_CLOSE_ERROR)
5b6d1e4f 6103 remote_unpush_target (remote);
eedc3f4f 6104 throw;
109c3e39
AC
6105 }
6106 }
c906108c 6107
6b8edb51 6108 remote_btrace_reset (rs);
f4abbc16 6109
c6ebd6cf 6110 if (target_async_permitted)
8756b726 6111 rs->wait_forever_enabled_p = true;
43ff13b4
JM
6112}
6113
28561a65 6114/* Determine if WS represents a fork status. */
a4543480 6115
28561a65
SM
6116static bool
6117is_fork_status (target_waitkind kind)
a4543480 6118{
28561a65
SM
6119 return (kind == TARGET_WAITKIND_FORKED
6120 || kind == TARGET_WAITKIND_VFORKED);
a4543480
SM
6121}
6122
28561a65
SM
6123/* Return THREAD's pending status if it is a pending fork parent, else
6124 return nullptr. */
a4543480 6125
28561a65 6126static const target_waitstatus *
a4543480
SM
6127thread_pending_fork_status (struct thread_info *thread)
6128{
28561a65
SM
6129 const target_waitstatus &ws
6130 = (thread->has_pending_waitstatus ()
6131 ? thread->pending_waitstatus ()
6132 : thread->pending_follow);
a4543480 6133
28561a65
SM
6134 if (!is_fork_status (ws.kind ()))
6135 return nullptr;
a4543480 6136
28561a65 6137 return &ws;
a4543480
SM
6138}
6139
de0d863e
DB
6140/* Detach the specified process. */
6141
6b8edb51
PA
6142void
6143remote_target::remote_detach_pid (int pid)
de0d863e
DB
6144{
6145 struct remote_state *rs = get_remote_state ();
6146
4c7333b3
PA
6147 /* This should not be necessary, but the handling for D;PID in
6148 GDBserver versions prior to 8.2 incorrectly assumes that the
6149 selected process points to the same process we're detaching,
6150 leading to misbehavior (and possibly GDBserver crashing) when it
6151 does not. Since it's easy and cheap, work around it by forcing
6152 GDBserver to select GDB's current process. */
6153 set_general_process ();
6154
ff52c073 6155 if (m_features.remote_multi_process_p ())
8d64371b 6156 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
de0d863e 6157 else
8d64371b 6158 strcpy (rs->buf.data (), "D");
de0d863e
DB
6159
6160 putpkt (rs->buf);
aa7b36b8 6161 getpkt (&rs->buf);
de0d863e
DB
6162
6163 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6164 ;
6165 else if (rs->buf[0] == '\0')
6166 error (_("Remote doesn't know how to detach"));
6167 else
6168 error (_("Can't detach process."));
6169}
6170
6171/* This detaches a program to which we previously attached, using
6172 inferior_ptid to identify the process. After this is done, GDB
6173 can be used to debug some other program. We better not have left
6174 any breakpoints in the target program or it'll die when it hits
6175 one. */
c906108c 6176
6b8edb51 6177void
00431a78 6178remote_target::remote_detach_1 (inferior *inf, int from_tty)
c906108c 6179{
e99b03dc 6180 int pid = inferior_ptid.pid ();
d01949b6 6181 struct remote_state *rs = get_remote_state ();
de0d863e 6182 int is_fork_parent;
c906108c 6183
55f6301a 6184 if (!target_has_execution ())
2d717e4f
DJ
6185 error (_("No process to detach from."));
6186
0f48b757 6187 target_announce_detach (from_tty);
7cee1e54 6188
99d9c3b9 6189 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
e87f0fe8
PA
6190 {
6191 /* If we're in breakpoints-always-inserted mode, or the inferior
6192 is running, we have to remove breakpoints before detaching.
6193 We don't do this in common code instead because not all
6194 targets support removing breakpoints while the target is
6195 running. The remote target / gdbserver does, though. */
6196 remove_breakpoints_inf (current_inferior ());
6197 }
6198
c906108c 6199 /* Tell the remote target to detach. */
de0d863e 6200 remote_detach_pid (pid);
82f73884 6201
8020350c 6202 /* Exit only if this is the only active inferior. */
5b6d1e4f 6203 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
0426ad51 6204 gdb_puts (_("Ending remote debugging.\n"));
82f73884 6205
df5ad102
SM
6206 /* See if any thread of the inferior we are detaching has a pending fork
6207 status. In that case, we must detach from the child resulting from
6208 that fork. */
6209 for (thread_info *thread : inf->non_exited_threads ())
6210 {
6211 const target_waitstatus *ws = thread_pending_fork_status (thread);
6212
6213 if (ws == nullptr)
6214 continue;
6215
6216 remote_detach_pid (ws->child_ptid ().pid ());
6217 }
6218
6219 /* Check also for any pending fork events in the stop reply queue. */
6220 remote_notif_get_pending_events (&notif_client_stop);
6221 for (stop_reply_up &reply : rs->stop_reply_queue)
6222 {
6223 if (reply->ptid.pid () != pid)
6224 continue;
6225
6226 if (!is_fork_status (reply->ws.kind ()))
6227 continue;
6228
6229 remote_detach_pid (reply->ws.child_ptid ().pid ());
6230 }
6231
9213a6d7 6232 thread_info *tp = this->find_thread (inferior_ptid);
00431a78 6233
de0d863e
DB
6234 /* Check to see if we are detaching a fork parent. Note that if we
6235 are detaching a fork child, tp == NULL. */
6236 is_fork_parent = (tp != NULL
183be222 6237 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
de0d863e
DB
6238
6239 /* If doing detach-on-fork, we don't mourn, because that will delete
6240 breakpoints that should be available for the followed inferior. */
6241 if (!is_fork_parent)
f67c0c91 6242 {
249b5733
PA
6243 /* Save the pid as a string before mourning, since that will
6244 unpush the remote target, and we need the string after. */
f2907e49 6245 std::string infpid = target_pid_to_str (ptid_t (pid));
f67c0c91
SDJ
6246
6247 target_mourn_inferior (inferior_ptid);
6248 if (print_inferior_events)
6cb06a8c
TT
6249 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6250 inf->num, infpid.c_str ());
f67c0c91 6251 }
de0d863e
DB
6252 else
6253 {
0ac55310 6254 switch_to_no_thread ();
00431a78 6255 detach_inferior (current_inferior ());
de0d863e 6256 }
2d717e4f
DJ
6257}
6258
f6ac5f3d
PA
6259void
6260remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6261{
00431a78 6262 remote_detach_1 (inf, from_tty);
2d717e4f
DJ
6263}
6264
f6ac5f3d
PA
6265void
6266extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6267{
00431a78 6268 remote_detach_1 (inf, from_tty);
de0d863e
DB
6269}
6270
6271/* Target follow-fork function for remote targets. On entry, and
6272 at return, the current inferior is the fork parent.
6273
6274 Note that although this is currently only used for extended-remote,
6275 it is named remote_follow_fork in anticipation of using it for the
6276 remote target as well. */
6277
e97007b6 6278void
82d1f134
SM
6279remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6280 target_waitkind fork_kind, bool follow_child,
6281 bool detach_fork)
de0d863e 6282{
82d1f134
SM
6283 process_stratum_target::follow_fork (child_inf, child_ptid,
6284 fork_kind, follow_child, detach_fork);
6285
ff52c073
CS
6286 if ((fork_kind == TARGET_WAITKIND_FORKED
6287 && m_features.remote_fork_event_p ())
6288 || (fork_kind == TARGET_WAITKIND_VFORKED
6289 && m_features.remote_vfork_event_p ()))
de0d863e
DB
6290 {
6291 /* When following the parent and detaching the child, we detach
6292 the child here. For the case of following the child and
6293 detaching the parent, the detach is done in the target-
6294 independent follow fork code in infrun.c. We can't use
6295 target_detach when detaching an unfollowed child because
6296 the client side doesn't know anything about the child. */
6297 if (detach_fork && !follow_child)
6298 {
6299 /* Detach the fork child. */
3a849a34 6300 remote_detach_pid (child_ptid.pid ());
de0d863e
DB
6301 }
6302 }
c906108c
SS
6303}
6304
94585166 6305/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
294c36eb 6306 in the program space of the new inferior. */
94585166 6307
f6ac5f3d 6308void
294c36eb
SM
6309remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6310 const char *execd_pathname)
94585166 6311{
294c36eb
SM
6312 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6313
94585166
DB
6314 /* We know that this is a target file name, so if it has the "target:"
6315 prefix we strip it off before saving it in the program space. */
6316 if (is_target_filename (execd_pathname))
6317 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6318
294c36eb 6319 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
94585166
DB
6320}
6321
6ad8ae5c
DJ
6322/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6323
f6ac5f3d
PA
6324void
6325remote_target::disconnect (const char *args, int from_tty)
43ff13b4 6326{
43ff13b4 6327 if (args)
2d717e4f 6328 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 6329
8020350c 6330 /* Make sure we unpush even the extended remote targets. Calling
5b6d1e4f
PA
6331 target_mourn_inferior won't unpush, and
6332 remote_target::mourn_inferior won't unpush if there is more than
6333 one inferior left. */
6334 remote_unpush_target (this);
2d717e4f 6335
43ff13b4 6336 if (from_tty)
0426ad51 6337 gdb_puts ("Ending remote debugging.\n");
43ff13b4
JM
6338}
6339
2d717e4f
DJ
6340/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6341 be chatty about it. */
6342
f6ac5f3d
PA
6343void
6344extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
6345{
6346 struct remote_state *rs = get_remote_state ();
be86555c 6347 int pid;
96ef3384 6348 char *wait_status = NULL;
2d717e4f 6349
74164c56 6350 pid = parse_pid_to_attach (args);
2d717e4f 6351
74164c56
JK
6352 /* Remote PID can be freely equal to getpid, do not check it here the same
6353 way as in other targets. */
2d717e4f 6354
ff52c073 6355 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
6356 error (_("This target does not support attaching to a process"));
6357
bc521517 6358 target_announce_attach (from_tty, pid);
7cee1e54 6359
8d64371b 6360 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f 6361 putpkt (rs->buf);
aa7b36b8 6362 getpkt (&rs->buf);
2d717e4f 6363
ff52c073 6364 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
2d717e4f 6365 {
4082afcc 6366 case PACKET_OK:
6efcd9a8 6367 if (!target_is_non_stop_p ())
74531fed
PA
6368 {
6369 /* Save the reply for later. */
8d64371b
TT
6370 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6371 strcpy (wait_status, rs->buf.data ());
74531fed 6372 }
8d64371b 6373 else if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 6374 error (_("Attaching to %s failed with: %s"),
a068643d 6375 target_pid_to_str (ptid_t (pid)).c_str (),
8d64371b 6376 rs->buf.data ());
4082afcc
PA
6377 break;
6378 case PACKET_UNKNOWN:
6379 error (_("This target does not support attaching to a process"));
6380 default:
50fa3001
SDJ
6381 error (_("Attaching to %s failed"),
6382 target_pid_to_str (ptid_t (pid)).c_str ());
2d717e4f 6383 }
2d717e4f 6384
0ac55310 6385 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
bad34192 6386
f2907e49 6387 inferior_ptid = ptid_t (pid);
79d7f229 6388
6efcd9a8 6389 if (target_is_non_stop_p ())
bad34192 6390 {
bad34192 6391 /* Get list of threads. */
f6ac5f3d 6392 update_thread_list ();
82f73884 6393
0ac55310
PA
6394 thread_info *thread = first_thread_of_inferior (current_inferior ());
6395 if (thread != nullptr)
6396 switch_to_thread (thread);
bad34192
PA
6397
6398 /* Invalidate our notion of the remote current thread. */
47f8a51d 6399 record_currthread (rs, minus_one_ptid);
bad34192 6400 }
74531fed 6401 else
bad34192 6402 {
0ac55310
PA
6403 /* Now, if we have thread information, update the main thread's
6404 ptid. */
6405 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
bad34192 6406
b622494e
AB
6407 /* Add the main thread to the thread list. We add the thread
6408 silently in this case (the final true parameter). */
6409 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
0ac55310
PA
6410
6411 switch_to_thread (thr);
bad34192 6412 }
c0a2216e 6413
96ef3384
UW
6414 /* Next, if the target can specify a description, read it. We do
6415 this before anything involving memory or registers. */
6416 target_find_description ();
6417
6efcd9a8 6418 if (!target_is_non_stop_p ())
74531fed
PA
6419 {
6420 /* Use the previously fetched status. */
6421 gdb_assert (wait_status != NULL);
6422
4f626cad
AB
6423 struct notif_event *reply
6424 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 6425
4f626cad 6426 push_stop_reply ((struct stop_reply *) reply);
74531fed
PA
6427 }
6428 else
621cc310
PA
6429 {
6430 gdb_assert (wait_status == NULL);
6431
6432 gdb_assert (target_can_async_p ());
621cc310 6433 }
2d717e4f
DJ
6434}
6435
b9c1d481
AS
6436/* Implementation of the to_post_attach method. */
6437
f6ac5f3d
PA
6438void
6439extended_remote_target::post_attach (int pid)
b9c1d481 6440{
6efcd9a8
PA
6441 /* Get text, data & bss offsets. */
6442 get_offsets ();
6443
b9c1d481
AS
6444 /* In certain cases GDB might not have had the chance to start
6445 symbol lookup up until now. This could happen if the debugged
6446 binary is not using shared libraries, the vsyscall page is not
6447 present (on Linux) and the binary itself hadn't changed since the
6448 debugging process was started. */
a42d7dd8 6449 if (current_program_space->symfile_object_file != NULL)
b9c1d481
AS
6450 remote_check_symbols();
6451}
6452
c906108c 6453\f
506fb367
DJ
6454/* Check for the availability of vCont. This function should also check
6455 the response. */
c906108c 6456
6b8edb51
PA
6457void
6458remote_target::remote_vcont_probe ()
c906108c 6459{
6b8edb51 6460 remote_state *rs = get_remote_state ();
2e9f7625 6461 char *buf;
6d820c5c 6462
8d64371b 6463 strcpy (rs->buf.data (), "vCont?");
2e9f7625 6464 putpkt (rs->buf);
aa7b36b8 6465 getpkt (&rs->buf);
8d64371b 6466 buf = rs->buf.data ();
c906108c 6467
506fb367 6468 /* Make sure that the features we assume are supported. */
61012eef 6469 if (startswith (buf, "vCont"))
506fb367
DJ
6470 {
6471 char *p = &buf[5];
750ce8d1 6472 int support_c, support_C;
506fb367 6473
750ce8d1
YQ
6474 rs->supports_vCont.s = 0;
6475 rs->supports_vCont.S = 0;
506fb367
DJ
6476 support_c = 0;
6477 support_C = 0;
d458bd84 6478 rs->supports_vCont.t = 0;
c1e36e3e 6479 rs->supports_vCont.r = 0;
506fb367
DJ
6480 while (p && *p == ';')
6481 {
6482 p++;
6483 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6484 rs->supports_vCont.s = 1;
506fb367 6485 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6486 rs->supports_vCont.S = 1;
506fb367
DJ
6487 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6488 support_c = 1;
6489 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6490 support_C = 1;
74531fed 6491 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 6492 rs->supports_vCont.t = 1;
c1e36e3e
PA
6493 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6494 rs->supports_vCont.r = 1;
506fb367
DJ
6495
6496 p = strchr (p, ';');
6497 }
c906108c 6498
750ce8d1
YQ
6499 /* If c, and C are not all supported, we can't use vCont. Clearing
6500 BUF will make packet_ok disable the packet. */
6501 if (!support_c || !support_C)
506fb367
DJ
6502 buf[0] = 0;
6503 }
c906108c 6504
ff52c073 6505 m_features.packet_ok (rs->buf, PACKET_vCont);
506fb367 6506}
c906108c 6507
0d8f58ca
PA
6508/* Helper function for building "vCont" resumptions. Write a
6509 resumption to P. ENDP points to one-passed-the-end of the buffer
6510 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6511 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6512 resumed thread should be single-stepped and/or signalled. If PTID
6513 equals minus_one_ptid, then all threads are resumed; if PTID
d51926f0
PA
6514 represents a process, then all threads of the process are
6515 resumed. */
0d8f58ca 6516
6b8edb51
PA
6517char *
6518remote_target::append_resumption (char *p, char *endp,
6519 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
6520{
6521 struct remote_state *rs = get_remote_state ();
6522
a493e3e2 6523 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 6524 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
6525 else if (step
6526 /* GDB is willing to range step. */
6527 && use_range_stepping
6528 /* Target supports range stepping. */
6529 && rs->supports_vCont.r
6530 /* We don't currently support range stepping multiple
6531 threads with a wildcard (though the protocol allows it,
6532 so stubs shouldn't make an active effort to forbid
6533 it). */
ff52c073 6534 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
c1e36e3e
PA
6535 {
6536 struct thread_info *tp;
6537
d7e15655 6538 if (ptid == minus_one_ptid)
c1e36e3e
PA
6539 {
6540 /* If we don't know about the target thread's tid, then
6541 we're resuming magic_null_ptid (see caller). */
9213a6d7 6542 tp = this->find_thread (magic_null_ptid);
c1e36e3e
PA
6543 }
6544 else
9213a6d7 6545 tp = this->find_thread (ptid);
c1e36e3e
PA
6546 gdb_assert (tp != NULL);
6547
6548 if (tp->control.may_range_step)
6549 {
99d9c3b9 6550 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
c1e36e3e
PA
6551
6552 p += xsnprintf (p, endp - p, ";r%s,%s",
6553 phex_nz (tp->control.step_range_start,
6554 addr_size),
6555 phex_nz (tp->control.step_range_end,
6556 addr_size));
6557 }
6558 else
6559 p += xsnprintf (p, endp - p, ";s");
6560 }
0d8f58ca
PA
6561 else if (step)
6562 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6563 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6564 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6565 else
6566 p += xsnprintf (p, endp - p, ";c");
6567
ff52c073 6568 if (m_features.remote_multi_process_p () && ptid.is_pid ())
0d8f58ca
PA
6569 {
6570 ptid_t nptid;
6571
6572 /* All (-1) threads of process. */
184ea2f7 6573 nptid = ptid_t (ptid.pid (), -1);
0d8f58ca
PA
6574
6575 p += xsnprintf (p, endp - p, ":");
6576 p = write_ptid (p, endp, nptid);
6577 }
d7e15655 6578 else if (ptid != minus_one_ptid)
0d8f58ca
PA
6579 {
6580 p += xsnprintf (p, endp - p, ":");
6581 p = write_ptid (p, endp, ptid);
6582 }
6583
6584 return p;
6585}
6586
799a2abe
PA
6587/* Clear the thread's private info on resume. */
6588
6589static void
6590resume_clear_thread_private_info (struct thread_info *thread)
6591{
6592 if (thread->priv != NULL)
6593 {
7aabaf9d
SM
6594 remote_thread_info *priv = get_remote_thread_info (thread);
6595
6596 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6597 priv->watch_data_address = 0;
799a2abe
PA
6598 }
6599}
6600
e5ef252a
PA
6601/* Append a vCont continue-with-signal action for threads that have a
6602 non-zero stop signal. */
6603
6b8edb51
PA
6604char *
6605remote_target::append_pending_thread_resumptions (char *p, char *endp,
6606 ptid_t ptid)
e5ef252a 6607{
5b6d1e4f 6608 for (thread_info *thread : all_non_exited_threads (this, ptid))
08036331 6609 if (inferior_ptid != thread->ptid
1edb66d8 6610 && thread->stop_signal () != GDB_SIGNAL_0)
e5ef252a
PA
6611 {
6612 p = append_resumption (p, endp, thread->ptid,
1edb66d8
SM
6613 0, thread->stop_signal ());
6614 thread->set_stop_signal (GDB_SIGNAL_0);
799a2abe 6615 resume_clear_thread_private_info (thread);
e5ef252a
PA
6616 }
6617
6618 return p;
6619}
6620
7b68ffbb
PA
6621/* Set the target running, using the packets that use Hc
6622 (c/s/C/S). */
6623
6b8edb51
PA
6624void
6625remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6626 gdb_signal siggnal)
7b68ffbb
PA
6627{
6628 struct remote_state *rs = get_remote_state ();
7b68ffbb
PA
6629 char *buf;
6630
6631 rs->last_sent_signal = siggnal;
6632 rs->last_sent_step = step;
6633
6634 /* The c/s/C/S resume packets use Hc, so set the continue
6635 thread. */
d7e15655 6636 if (ptid == minus_one_ptid)
7b68ffbb
PA
6637 set_continue_thread (any_thread_ptid);
6638 else
6639 set_continue_thread (ptid);
6640
5b6d1e4f 6641 for (thread_info *thread : all_non_exited_threads (this))
7b68ffbb
PA
6642 resume_clear_thread_private_info (thread);
6643
8d64371b 6644 buf = rs->buf.data ();
6b8edb51 6645 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6646 {
6647 /* We don't pass signals to the target in reverse exec mode. */
6648 if (info_verbose && siggnal != GDB_SIGNAL_0)
6649 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6650 siggnal);
6651
ff52c073 6652 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
7b68ffbb 6653 error (_("Remote reverse-step not supported."));
ff52c073 6654 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
7b68ffbb
PA
6655 error (_("Remote reverse-continue not supported."));
6656
6657 strcpy (buf, step ? "bs" : "bc");
6658 }
6659 else if (siggnal != GDB_SIGNAL_0)
6660 {
6661 buf[0] = step ? 'S' : 'C';
6662 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6663 buf[2] = tohex (((int) siggnal) & 0xf);
6664 buf[3] = '\0';
6665 }
6666 else
6667 strcpy (buf, step ? "s" : "c");
6668
6669 putpkt (buf);
6670}
6671
d51926f0
PA
6672/* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6673 STEP, and SIGGNAL have the same meaning as in target_resume. This
6674 function returns non-zero iff it resumes the inferior.
44eaed12 6675
7b68ffbb
PA
6676 This function issues a strict subset of all possible vCont commands
6677 at the moment. */
44eaed12 6678
6b8edb51 6679int
d51926f0 6680remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6b8edb51 6681 enum gdb_signal siggnal)
506fb367
DJ
6682{
6683 struct remote_state *rs = get_remote_state ();
82f73884
PA
6684 char *p;
6685 char *endp;
44eaed12 6686
7b68ffbb 6687 /* No reverse execution actions defined for vCont. */
6b8edb51 6688 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6689 return 0;
6690
ff52c073 6691 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6692 return 0;
44eaed12 6693
8d64371b
TT
6694 p = rs->buf.data ();
6695 endp = p + get_remote_packet_size ();
82f73884 6696
506fb367
DJ
6697 /* If we could generate a wider range of packets, we'd have to worry
6698 about overflowing BUF. Should there be a generic
6699 "multi-part-packet" packet? */
6700
0d8f58ca
PA
6701 p += xsnprintf (p, endp - p, "vCont");
6702
d51926f0 6703 if (scope_ptid == magic_null_ptid)
c906108c 6704 {
79d7f229
PA
6705 /* MAGIC_NULL_PTID means that we don't have any active threads,
6706 so we don't have any TID numbers the inferior will
6707 understand. Make sure to only send forms that do not specify
6708 a TID. */
a9cbf802 6709 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6710 }
d51926f0 6711 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
506fb367 6712 {
0d8f58ca
PA
6713 /* Resume all threads (of all processes, or of a single
6714 process), with preference for INFERIOR_PTID. This assumes
6715 inferior_ptid belongs to the set of all threads we are about
6716 to resume. */
a493e3e2 6717 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6718 {
0d8f58ca
PA
6719 /* Step inferior_ptid, with or without signal. */
6720 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6721 }
0d8f58ca 6722
e5ef252a
PA
6723 /* Also pass down any pending signaled resumption for other
6724 threads not the current. */
d51926f0 6725 p = append_pending_thread_resumptions (p, endp, scope_ptid);
e5ef252a 6726
0d8f58ca 6727 /* And continue others without a signal. */
d51926f0 6728 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6729 }
6730 else
506fb367 6731 {
d51926f0
PA
6732 /* Scheduler locking; resume only SCOPE_PTID. */
6733 append_resumption (p, endp, scope_ptid, step, siggnal);
506fb367 6734 }
c906108c 6735
8d64371b 6736 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
82f73884 6737 putpkt (rs->buf);
506fb367 6738
6efcd9a8 6739 if (target_is_non_stop_p ())
74531fed
PA
6740 {
6741 /* In non-stop, the stub replies to vCont with "OK". The stop
6742 reply will be reported asynchronously by means of a `%Stop'
6743 notification. */
aa7b36b8 6744 getpkt (&rs->buf);
8d64371b
TT
6745 if (strcmp (rs->buf.data (), "OK") != 0)
6746 error (_("Unexpected vCont reply in non-stop mode: %s"),
6747 rs->buf.data ());
74531fed
PA
6748 }
6749
506fb367 6750 return 1;
c906108c 6751}
43ff13b4 6752
506fb367
DJ
6753/* Tell the remote machine to resume. */
6754
f6ac5f3d 6755void
d51926f0 6756remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
43ff13b4 6757{
d01949b6 6758 struct remote_state *rs = get_remote_state ();
43ff13b4 6759
85ad3aaf
PA
6760 /* When connected in non-stop mode, the core resumes threads
6761 individually. Resuming remote threads directly in target_resume
6762 would thus result in sending one packet per thread. Instead, to
6763 minimize roundtrip latency, here we just store the resume
c9d22089
SM
6764 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6765 resumption will be done in remote_target::commit_resume, where we'll be
6766 able to do vCont action coalescing. */
f6ac5f3d 6767 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6768 {
d51926f0
PA
6769 remote_thread_info *remote_thr
6770 = get_remote_thread_info (inferior_thread ());
7aabaf9d 6771
c9d22089 6772 /* We don't expect the core to ask to resume an already resumed (from
287de656 6773 its point of view) thread. */
a6c11cbb 6774 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
c9d22089
SM
6775
6776 remote_thr->set_resumed_pending_vcont (step, siggnal);
d51926f0
PA
6777
6778 /* There's actually nothing that says that the core can't
6779 request a wildcard resume in non-stop mode, though. It's
6780 just that we know it doesn't currently, so we don't bother
6781 with it. */
6782 gdb_assert (scope_ptid == inferior_ptid);
85ad3aaf
PA
6783 return;
6784 }
6785
722247f1
YQ
6786 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6787 (explained in remote-notif.c:handle_notification) so
6788 remote_notif_process is not called. We need find a place where
6789 it is safe to start a 'vNotif' sequence. It is good to do it
6790 before resuming inferior, because inferior was stopped and no RSP
6791 traffic at that moment. */
6efcd9a8 6792 if (!target_is_non_stop_p ())
5965e028 6793 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6794
f6ac5f3d 6795 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6796
7b68ffbb 6797 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
d51926f0
PA
6798 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6799 remote_resume_with_hc (scope_ptid, step, siggnal);
43ff13b4 6800
c9d22089 6801 /* Update resumed state tracked by the remote target. */
d51926f0 6802 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
c9d22089
SM
6803 get_remote_thread_info (tp)->set_resumed ();
6804
e24a49d8
PA
6805 /* We've just told the target to resume. The remote server will
6806 wait for the inferior to stop, and then send a stop reply. In
6807 the mean time, we can't start another command/query ourselves
74531fed
PA
6808 because the stub wouldn't be ready to process it. This applies
6809 only to the base all-stop protocol, however. In non-stop (which
6810 only supports vCont), the stub replies with an "OK", and is
6811 immediate able to process further serial input. */
6efcd9a8 6812 if (!target_is_non_stop_p ())
74531fed 6813 rs->waiting_for_stop_reply = 1;
43ff13b4 6814}
85ad3aaf 6815
85ad3aaf
PA
6816/* Private per-inferior info for target remote processes. */
6817
089354bb 6818struct remote_inferior : public private_inferior
85ad3aaf
PA
6819{
6820 /* Whether we can send a wildcard vCont for this process. */
089354bb 6821 bool may_wildcard_vcont = true;
85ad3aaf
PA
6822};
6823
089354bb
SM
6824/* Get the remote private inferior data associated to INF. */
6825
6826static remote_inferior *
6827get_remote_inferior (inferior *inf)
6828{
6829 if (inf->priv == NULL)
6830 inf->priv.reset (new remote_inferior);
6831
98ed24fb 6832 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
089354bb
SM
6833}
6834
f5db4863 6835/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6836 outgoing packet buffer. This is used to send multiple vCont
6837 packets if we have more actions than would fit a single packet. */
6838
f5db4863 6839class vcont_builder
85ad3aaf 6840{
f5db4863 6841public:
6b8edb51
PA
6842 explicit vcont_builder (remote_target *remote)
6843 : m_remote (remote)
f5db4863
PA
6844 {
6845 restart ();
6846 }
6847
6848 void flush ();
6849 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6850
6851private:
6852 void restart ();
6853
6b8edb51
PA
6854 /* The remote target. */
6855 remote_target *m_remote;
6856
85ad3aaf
PA
6857 /* Pointer to the first action. P points here if no action has been
6858 appended yet. */
f5db4863 6859 char *m_first_action;
85ad3aaf
PA
6860
6861 /* Where the next action will be appended. */
f5db4863 6862 char *m_p;
85ad3aaf
PA
6863
6864 /* The end of the buffer. Must never write past this. */
f5db4863 6865 char *m_endp;
85ad3aaf
PA
6866};
6867
6868/* Prepare the outgoing buffer for a new vCont packet. */
6869
f5db4863
PA
6870void
6871vcont_builder::restart ()
85ad3aaf 6872{
6b8edb51 6873 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6874
8d64371b
TT
6875 m_p = rs->buf.data ();
6876 m_endp = m_p + m_remote->get_remote_packet_size ();
f5db4863
PA
6877 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6878 m_first_action = m_p;
85ad3aaf
PA
6879}
6880
6881/* If the vCont packet being built has any action, send it to the
6882 remote end. */
6883
f5db4863
PA
6884void
6885vcont_builder::flush ()
85ad3aaf
PA
6886{
6887 struct remote_state *rs;
6888
f5db4863 6889 if (m_p == m_first_action)
85ad3aaf
PA
6890 return;
6891
6b8edb51
PA
6892 rs = m_remote->get_remote_state ();
6893 m_remote->putpkt (rs->buf);
aa7b36b8 6894 m_remote->getpkt (&rs->buf);
8d64371b
TT
6895 if (strcmp (rs->buf.data (), "OK") != 0)
6896 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
85ad3aaf
PA
6897}
6898
6899/* The largest action is range-stepping, with its two addresses. This
6900 is more than sufficient. If a new, bigger action is created, it'll
6901 quickly trigger a failed assertion in append_resumption (and we'll
6902 just bump this). */
6903#define MAX_ACTION_SIZE 200
6904
6905/* Append a new vCont action in the outgoing packet being built. If
6906 the action doesn't fit the packet along with previous actions, push
6907 what we've got so far to the remote end and start over a new vCont
6908 packet (with the new action). */
6909
f5db4863
PA
6910void
6911vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6912{
6913 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6914
6b8edb51
PA
6915 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6916 ptid, step, siggnal);
85ad3aaf
PA
6917
6918 /* Check whether this new action would fit in the vCont packet along
6919 with previous actions. If not, send what we've got so far and
6920 start a new vCont packet. */
f5db4863
PA
6921 size_t rsize = endp - buf;
6922 if (rsize > m_endp - m_p)
85ad3aaf 6923 {
f5db4863
PA
6924 flush ();
6925 restart ();
85ad3aaf
PA
6926
6927 /* Should now fit. */
f5db4863 6928 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6929 }
6930
f5db4863
PA
6931 memcpy (m_p, buf, rsize);
6932 m_p += rsize;
6933 *m_p = '\0';
85ad3aaf
PA
6934}
6935
6936/* to_commit_resume implementation. */
6937
f6ac5f3d 6938void
1192f124 6939remote_target::commit_resumed ()
85ad3aaf 6940{
85ad3aaf
PA
6941 /* If connected in all-stop mode, we'd send the remote resume
6942 request directly from remote_resume. Likewise if
6943 reverse-debugging, as there are no defined vCont actions for
6944 reverse execution. */
f6ac5f3d 6945 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6946 return;
6947
6948 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6949 instead of resuming all threads of each process individually.
6950 However, if any thread of a process must remain halted, we can't
6951 send wildcard resumes and must send one action per thread.
6952
6953 Care must be taken to not resume threads/processes the server
6954 side already told us are stopped, but the core doesn't know about
6955 yet, because the events are still in the vStopped notification
6956 queue. For example:
6957
6958 #1 => vCont s:p1.1;c
6959 #2 <= OK
6960 #3 <= %Stopped T05 p1.1
6961 #4 => vStopped
6962 #5 <= T05 p1.2
6963 #6 => vStopped
6964 #7 <= OK
6965 #8 (infrun handles the stop for p1.1 and continues stepping)
6966 #9 => vCont s:p1.1;c
6967
6968 The last vCont above would resume thread p1.2 by mistake, because
6969 the server has no idea that the event for p1.2 had not been
6970 handled yet.
6971
6972 The server side must similarly ignore resume actions for the
6973 thread that has a pending %Stopped notification (and any other
6974 threads with events pending), until GDB acks the notification
6975 with vStopped. Otherwise, e.g., the following case is
6976 mishandled:
6977
6978 #1 => g (or any other packet)
6979 #2 <= [registers]
6980 #3 <= %Stopped T05 p1.2
6981 #4 => vCont s:p1.1;c
6982 #5 <= OK
6983
6984 Above, the server must not resume thread p1.2. GDB can't know
6985 that p1.2 stopped until it acks the %Stopped notification, and
6986 since from GDB's perspective all threads should be running, it
6987 sends a "c" action.
6988
6989 Finally, special care must also be given to handling fork/vfork
6990 events. A (v)fork event actually tells us that two processes
6991 stopped -- the parent and the child. Until we follow the fork,
6992 we must not resume the child. Therefore, if we have a pending
6993 fork follow, we must not send a global wildcard resume action
6994 (vCont;c). We can still send process-wide wildcards though. */
6995
6996 /* Start by assuming a global wildcard (vCont;c) is possible. */
2f63ec5c 6997 bool may_global_wildcard_vcont = true;
85ad3aaf
PA
6998
6999 /* And assume every process is individually wildcard-able too. */
5b6d1e4f 7000 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 7001 {
089354bb
SM
7002 remote_inferior *priv = get_remote_inferior (inf);
7003
7004 priv->may_wildcard_vcont = true;
85ad3aaf
PA
7005 }
7006
7007 /* Check for any pending events (not reported or processed yet) and
7008 disable process and global wildcard resumes appropriately. */
7009 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7010
1192f124
SM
7011 bool any_pending_vcont_resume = false;
7012
5b6d1e4f 7013 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 7014 {
c9d22089
SM
7015 remote_thread_info *priv = get_remote_thread_info (tp);
7016
85ad3aaf
PA
7017 /* If a thread of a process is not meant to be resumed, then we
7018 can't wildcard that process. */
a6c11cbb 7019 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
85ad3aaf 7020 {
089354bb 7021 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
7022
7023 /* And if we can't wildcard a process, we can't wildcard
7024 everything either. */
2f63ec5c 7025 may_global_wildcard_vcont = false;
85ad3aaf
PA
7026 continue;
7027 }
7028
1192f124
SM
7029 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7030 any_pending_vcont_resume = true;
7031
85ad3aaf
PA
7032 /* If a thread is the parent of an unfollowed fork, then we
7033 can't do a global wildcard, as that would resume the fork
7034 child. */
28561a65 7035 if (thread_pending_fork_status (tp) != nullptr)
2f63ec5c 7036 may_global_wildcard_vcont = false;
85ad3aaf
PA
7037 }
7038
1192f124
SM
7039 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7040 do. */
7041 if (!any_pending_vcont_resume)
7042 return;
7043
85ad3aaf
PA
7044 /* Now let's build the vCont packet(s). Actions must be appended
7045 from narrower to wider scopes (thread -> process -> global). If
7046 we end up with too many actions for a single packet vcont_builder
7047 flushes the current vCont packet to the remote side and starts a
7048 new one. */
6b8edb51 7049 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
7050
7051 /* Threads first. */
5b6d1e4f 7052 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 7053 {
7aabaf9d 7054 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf 7055
c9d22089
SM
7056 /* If the thread was previously vCont-resumed, no need to send a specific
7057 action for it. If we didn't receive a resume request for it, don't
7058 send an action for it either. */
a6c11cbb 7059 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
85ad3aaf
PA
7060 continue;
7061
7062 gdb_assert (!thread_is_in_step_over_chain (tp));
7063
1192f124 7064 /* We should never be commit-resuming a thread that has a stop reply.
287de656 7065 Otherwise, we would end up reporting a stop event for a thread while
1192f124
SM
7066 it is running on the remote target. */
7067 remote_state *rs = get_remote_state ();
7068 for (const auto &stop_reply : rs->stop_reply_queue)
7069 gdb_assert (stop_reply->ptid != tp->ptid);
7070
c9d22089
SM
7071 const resumed_pending_vcont_info &info
7072 = remote_thr->resumed_pending_vcont_info ();
85ad3aaf 7073
c9d22089 7074 /* Check if we need to send a specific action for this thread. If not,
287de656 7075 it will be included in a wildcard resume instead. */
c9d22089
SM
7076 if (info.step || info.sig != GDB_SIGNAL_0
7077 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7078 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7079
7080 remote_thr->set_resumed ();
85ad3aaf
PA
7081 }
7082
7083 /* Now check whether we can send any process-wide wildcard. This is
7084 to avoid sending a global wildcard in the case nothing is
7085 supposed to be resumed. */
2f63ec5c 7086 bool any_process_wildcard = false;
85ad3aaf 7087
5b6d1e4f 7088 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 7089 {
089354bb 7090 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 7091 {
2f63ec5c 7092 any_process_wildcard = true;
85ad3aaf
PA
7093 break;
7094 }
7095 }
7096
7097 if (any_process_wildcard)
7098 {
7099 /* If all processes are wildcard-able, then send a single "c"
7100 action, otherwise, send an "all (-1) threads of process"
7101 continue action for each running process, if any. */
7102 if (may_global_wildcard_vcont)
7103 {
f5db4863
PA
7104 vcont_builder.push_action (minus_one_ptid,
7105 false, GDB_SIGNAL_0);
85ad3aaf
PA
7106 }
7107 else
7108 {
5b6d1e4f 7109 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 7110 {
089354bb 7111 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 7112 {
f2907e49 7113 vcont_builder.push_action (ptid_t (inf->pid),
f5db4863 7114 false, GDB_SIGNAL_0);
85ad3aaf
PA
7115 }
7116 }
7117 }
7118 }
7119
f5db4863 7120 vcont_builder.flush ();
85ad3aaf
PA
7121}
7122
b4b1a226
SM
7123/* Implementation of target_has_pending_events. */
7124
7125bool
7126remote_target::has_pending_events ()
7127{
7128 if (target_can_async_p ())
7129 {
7130 remote_state *rs = get_remote_state ();
7131
92b98b37 7132 if (rs->async_event_handler_marked ())
b4b1a226
SM
7133 return true;
7134
7135 /* Note that BUFCNT can be negative, indicating sticky
7136 error. */
7137 if (rs->remote_desc->bufcnt != 0)
7138 return true;
7139 }
7140 return false;
7141}
7142
c906108c 7143\f
43ff13b4 7144
74531fed
PA
7145/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7146 thread, all threads of a remote process, or all threads of all
7147 processes. */
7148
6b8edb51
PA
7149void
7150remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
7151{
7152 struct remote_state *rs = get_remote_state ();
8d64371b
TT
7153 char *p = rs->buf.data ();
7154 char *endp = p + get_remote_packet_size ();
74531fed 7155
1192f124
SM
7156 /* If any thread that needs to stop was resumed but pending a vCont
7157 resume, generate a phony stop_reply. However, first check
7158 whether the thread wasn't resumed with a signal. Generating a
7159 phony stop in that case would result in losing the signal. */
7160 bool needs_commit = false;
7161 for (thread_info *tp : all_non_exited_threads (this, ptid))
7162 {
7163 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7164
7165 if (remote_thr->get_resume_state ()
7166 == resume_state::RESUMED_PENDING_VCONT)
7167 {
7168 const resumed_pending_vcont_info &info
7169 = remote_thr->resumed_pending_vcont_info ();
7170 if (info.sig != GDB_SIGNAL_0)
7171 {
7172 /* This signal must be forwarded to the inferior. We
7173 could commit-resume just this thread, but its simpler
7174 to just commit-resume everything. */
7175 needs_commit = true;
7176 break;
7177 }
7178 }
7179 }
7180
7181 if (needs_commit)
7182 commit_resumed ();
7183 else
7184 for (thread_info *tp : all_non_exited_threads (this, ptid))
7185 {
7186 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7187
7188 if (remote_thr->get_resume_state ()
7189 == resume_state::RESUMED_PENDING_VCONT)
7190 {
7191 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
96bbe3ef
TT
7192 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7193 tp->ptid.lwp (),
7194 pulongest (tp->ptid.tid ()));
1192f124
SM
7195
7196 /* Check that the thread wasn't resumed with a signal.
7197 Generating a phony stop would result in losing the
7198 signal. */
7199 const resumed_pending_vcont_info &info
7200 = remote_thr->resumed_pending_vcont_info ();
7201 gdb_assert (info.sig == GDB_SIGNAL_0);
7202
7203 stop_reply *sr = new stop_reply ();
7204 sr->ptid = tp->ptid;
7205 sr->rs = rs;
183be222 7206 sr->ws.set_stopped (GDB_SIGNAL_0);
27b1f19f 7207 sr->arch = tp->inf->arch ();
1192f124
SM
7208 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7209 sr->watch_data_address = 0;
7210 sr->core = 0;
7211 this->push_stop_reply (sr);
7212
7213 /* Pretend that this thread was actually resumed on the
7214 remote target, then stopped. If we leave it in the
7215 RESUMED_PENDING_VCONT state and the commit_resumed
7216 method is called while the stop reply is still in the
7217 queue, we'll end up reporting a stop event to the core
7218 for that thread while it is running on the remote
7219 target... that would be bad. */
7220 remote_thr->set_resumed ();
7221 }
7222 }
7223
d458bd84 7224 if (!rs->supports_vCont.t)
74531fed
PA
7225 error (_("Remote server does not support stopping threads"));
7226
d7e15655 7227 if (ptid == minus_one_ptid
ff52c073 7228 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
74531fed
PA
7229 p += xsnprintf (p, endp - p, "vCont;t");
7230 else
7231 {
7232 ptid_t nptid;
7233
74531fed
PA
7234 p += xsnprintf (p, endp - p, "vCont;t:");
7235
0e998d96 7236 if (ptid.is_pid ())
74531fed 7237 /* All (-1) threads of process. */
184ea2f7 7238 nptid = ptid_t (ptid.pid (), -1);
74531fed
PA
7239 else
7240 {
7241 /* Small optimization: if we already have a stop reply for
7242 this thread, no use in telling the stub we want this
7243 stopped. */
7244 if (peek_stop_reply (ptid))
7245 return;
7246
7247 nptid = ptid;
7248 }
7249
a9cbf802 7250 write_ptid (p, endp, nptid);
74531fed
PA
7251 }
7252
7253 /* In non-stop, we get an immediate OK reply. The stop reply will
7254 come in asynchronously by notification. */
7255 putpkt (rs->buf);
aa7b36b8 7256 getpkt (&rs->buf);
8d64371b 7257 if (strcmp (rs->buf.data (), "OK") != 0)
a068643d 7258 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
8d64371b 7259 rs->buf.data ());
74531fed
PA
7260}
7261
bfedc46a
PA
7262/* All-stop version of target_interrupt. Sends a break or a ^C to
7263 interrupt the remote target. It is undefined which thread of which
7264 process reports the interrupt. */
74531fed 7265
6b8edb51
PA
7266void
7267remote_target::remote_interrupt_as ()
74531fed
PA
7268{
7269 struct remote_state *rs = get_remote_state ();
7270
3a29589a
DJ
7271 rs->ctrlc_pending_p = 1;
7272
74531fed 7273 /* If the inferior is stopped already, but the core didn't know
4f626cad 7274 about it yet, just ignore the request. The pending stop events
74531fed 7275 will be collected in remote_wait. */
4f626cad 7276 if (stop_reply_queue_length () > 0)
74531fed
PA
7277 return;
7278
9a7071a8
JB
7279 /* Send interrupt_sequence to remote target. */
7280 send_interrupt_sequence ();
74531fed
PA
7281}
7282
de979965
PA
7283/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7284 the remote target. It is undefined which thread of which process
e42de8c7
PA
7285 reports the interrupt. Throws an error if the packet is not
7286 supported by the server. */
de979965 7287
6b8edb51
PA
7288void
7289remote_target::remote_interrupt_ns ()
de979965
PA
7290{
7291 struct remote_state *rs = get_remote_state ();
8d64371b
TT
7292 char *p = rs->buf.data ();
7293 char *endp = p + get_remote_packet_size ();
de979965
PA
7294
7295 xsnprintf (p, endp - p, "vCtrlC");
7296
7297 /* In non-stop, we get an immediate OK reply. The stop reply will
7298 come in asynchronously by notification. */
7299 putpkt (rs->buf);
aa7b36b8 7300 getpkt (&rs->buf);
de979965 7301
ff52c073 7302 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
de979965
PA
7303 {
7304 case PACKET_OK:
7305 break;
7306 case PACKET_UNKNOWN:
e42de8c7 7307 error (_("No support for interrupting the remote target."));
de979965 7308 case PACKET_ERROR:
8d64371b 7309 error (_("Interrupting target failed: %s"), rs->buf.data ());
de979965 7310 }
de979965
PA
7311}
7312
bfedc46a 7313/* Implement the to_stop function for the remote targets. */
74531fed 7314
f6ac5f3d
PA
7315void
7316remote_target::stop (ptid_t ptid)
c906108c 7317{
2189c312 7318 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
c906108c 7319
6efcd9a8 7320 if (target_is_non_stop_p ())
74531fed 7321 remote_stop_ns (ptid);
c906108c 7322 else
bfedc46a
PA
7323 {
7324 /* We don't currently have a way to transparently pause the
7325 remote target in all-stop mode. Interrupt it instead. */
de979965 7326 remote_interrupt_as ();
bfedc46a
PA
7327 }
7328}
7329
7330/* Implement the to_interrupt function for the remote targets. */
7331
f6ac5f3d
PA
7332void
7333remote_target::interrupt ()
bfedc46a 7334{
2189c312 7335 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
bfedc46a 7336
e42de8c7
PA
7337 if (target_is_non_stop_p ())
7338 remote_interrupt_ns ();
bfedc46a 7339 else
e42de8c7 7340 remote_interrupt_as ();
c906108c
SS
7341}
7342
93692b58
PA
7343/* Implement the to_pass_ctrlc function for the remote targets. */
7344
f6ac5f3d
PA
7345void
7346remote_target::pass_ctrlc ()
93692b58 7347{
2189c312 7348 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
93692b58 7349
2189c312 7350 struct remote_state *rs = get_remote_state ();
93692b58
PA
7351
7352 /* If we're starting up, we're not fully synced yet. Quit
7353 immediately. */
7354 if (rs->starting_up)
7355 quit ();
7356 /* If ^C has already been sent once, offer to disconnect. */
7357 else if (rs->ctrlc_pending_p)
7358 interrupt_query ();
7359 else
e671cd59 7360 target_interrupt ();
93692b58
PA
7361}
7362
c906108c
SS
7363/* Ask the user what to do when an interrupt is received. */
7364
6b8edb51
PA
7365void
7366remote_target::interrupt_query ()
c906108c 7367{
abc56d60 7368 struct remote_state *rs = get_remote_state ();
c906108c 7369
abc56d60 7370 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 7371 {
abc56d60
PA
7372 if (query (_("The target is not responding to interrupt requests.\n"
7373 "Stop debugging it? ")))
74531fed 7374 {
5b6d1e4f 7375 remote_unpush_target (this);
abc56d60 7376 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
7377 }
7378 }
abc56d60
PA
7379 else
7380 {
7381 if (query (_("Interrupted while waiting for the program.\n"
7382 "Give up waiting? ")))
7383 quit ();
7384 }
c906108c
SS
7385}
7386
6426a772
JM
7387/* Enable/disable target terminal ownership. Most targets can use
7388 terminal groups to control terminal ownership. Remote targets are
7389 different in that explicit transfer of ownership to/from GDB/target
23860348 7390 is required. */
6426a772 7391
f6ac5f3d
PA
7392void
7393remote_target::terminal_inferior ()
6426a772 7394{
6426a772
JM
7395 /* NOTE: At this point we could also register our selves as the
7396 recipient of all input. Any characters typed could then be
23860348 7397 passed on down to the target. */
6426a772
JM
7398}
7399
f6ac5f3d
PA
7400void
7401remote_target::terminal_ours ()
6426a772 7402{
6426a772
JM
7403}
7404
176a6961 7405static void
05be00a8 7406remote_console_output (const char *msg)
c906108c 7407{
05be00a8 7408 const char *p;
c906108c 7409
c5aa993b 7410 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
7411 {
7412 char tb[2];
7413 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 7414
c906108c
SS
7415 tb[0] = c;
7416 tb[1] = 0;
da5bd37e 7417 gdb_stdtarg->puts (tb);
c906108c 7418 }
da5bd37e 7419 gdb_stdtarg->flush ();
00db5b94 7420}
74531fed 7421
221e1a37
PA
7422/* Return the length of the stop reply queue. */
7423
6b8edb51
PA
7424int
7425remote_target::stop_reply_queue_length ()
221e1a37 7426{
6b8edb51 7427 remote_state *rs = get_remote_state ();
953edf2b 7428 return rs->stop_reply_queue.size ();
221e1a37
PA
7429}
7430
cb8c24b6 7431static void
6b8edb51 7432remote_notif_stop_parse (remote_target *remote,
42938c1a 7433 const notif_client *self, const char *buf,
722247f1
YQ
7434 struct notif_event *event)
7435{
6b8edb51 7436 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
7437}
7438
7439static void
6b8edb51 7440remote_notif_stop_ack (remote_target *remote,
42938c1a 7441 const notif_client *self, const char *buf,
722247f1
YQ
7442 struct notif_event *event)
7443{
7444 struct stop_reply *stop_reply = (struct stop_reply *) event;
7445
7446 /* acknowledge */
6b8edb51 7447 putpkt (remote, self->ack_command);
722247f1 7448
b0083dd7
PA
7449 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7450 the notification. It was left in the queue because we need to
7451 acknowledge it and pull the rest of the notifications out. */
183be222 7452 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
b0083dd7 7453 remote->push_stop_reply (stop_reply);
722247f1
YQ
7454}
7455
7456static int
6b8edb51 7457remote_notif_stop_can_get_pending_events (remote_target *remote,
42938c1a 7458 const notif_client *self)
722247f1
YQ
7459{
7460 /* We can't get pending events in remote_notif_process for
7461 notification stop, and we have to do this in remote_wait_ns
7462 instead. If we fetch all queued events from stub, remote stub
7463 may exit and we have no chance to process them back in
7464 remote_wait_ns. */
6b8edb51 7465 remote_state *rs = remote->get_remote_state ();
92b98b37 7466 rs->mark_async_event_handler ();
722247f1
YQ
7467 return 0;
7468}
7469
32603266 7470stop_reply::~stop_reply ()
722247f1 7471{
32603266
TT
7472 for (cached_reg_t &reg : regcache)
7473 xfree (reg.data);
722247f1
YQ
7474}
7475
32603266
TT
7476static notif_event_up
7477remote_notif_stop_alloc_reply ()
722247f1 7478{
32603266 7479 return notif_event_up (new struct stop_reply ());
722247f1
YQ
7480}
7481
7482/* A client of notification Stop. */
7483
42938c1a 7484const notif_client notif_client_stop =
722247f1
YQ
7485{
7486 "Stop",
7487 "vStopped",
7488 remote_notif_stop_parse,
7489 remote_notif_stop_ack,
7490 remote_notif_stop_can_get_pending_events,
7491 remote_notif_stop_alloc_reply,
f48ff2a7 7492 REMOTE_NOTIF_STOP,
722247f1
YQ
7493};
7494
cbb8991c
DB
7495/* If CONTEXT contains any fork child threads that have not been
7496 reported yet, remove them from the CONTEXT list. If such a
7497 thread exists it is because we are stopped at a fork catchpoint
7498 and have not yet called follow_fork, which will set up the
7499 host-side data structures for the new process. */
7500
6b8edb51
PA
7501void
7502remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c 7503{
42938c1a 7504 const notif_client *notif = &notif_client_stop;
cbb8991c
DB
7505
7506 /* For any threads stopped at a fork event, remove the corresponding
7507 fork child threads from the CONTEXT list. */
5b6d1e4f 7508 for (thread_info *thread : all_non_exited_threads (this))
cbb8991c 7509 {
28561a65
SM
7510 const target_waitstatus *ws = thread_pending_fork_status (thread);
7511
7512 if (ws == nullptr)
7513 continue;
cbb8991c 7514
28561a65 7515 context->remove_thread (ws->child_ptid ());
cbb8991c
DB
7516 }
7517
7518 /* Check for any pending fork events (not reported or processed yet)
7519 in process PID and remove those fork child threads from the
7520 CONTEXT list as well. */
7521 remote_notif_get_pending_events (notif);
953edf2b 7522 for (auto &event : get_remote_state ()->stop_reply_queue)
183be222 7523 if (event->ws.kind () == TARGET_WAITKIND_FORKED
3890f02a 7524 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
183be222 7525 context->remove_thread (event->ws.child_ptid ());
3890f02a
SM
7526 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7527 context->remove_thread (event->ptid);
85ad3aaf
PA
7528}
7529
2f63ec5c
AB
7530/* Check whether any event pending in the vStopped queue would prevent a
7531 global or process wildcard vCont action. Set *may_global_wildcard to
7532 false if we can't do a global wildcard (vCont;c), and clear the event
7533 inferior's may_wildcard_vcont flag if we can't do a process-wide
7534 wildcard resume (vCont;c:pPID.-1). */
85ad3aaf 7535
6b8edb51
PA
7536void
7537remote_target::check_pending_events_prevent_wildcard_vcont
2f63ec5c 7538 (bool *may_global_wildcard)
85ad3aaf 7539{
42938c1a 7540 const notif_client *notif = &notif_client_stop;
85ad3aaf
PA
7541
7542 remote_notif_get_pending_events (notif);
953edf2b
TT
7543 for (auto &event : get_remote_state ()->stop_reply_queue)
7544 {
183be222
SM
7545 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7546 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
953edf2b 7547 continue;
85ad3aaf 7548
183be222
SM
7549 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7550 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
2f63ec5c 7551 *may_global_wildcard = false;
722247f1 7552
953edf2b
TT
7553 /* This may be the first time we heard about this process.
7554 Regardless, we must not do a global wildcard resume, otherwise
7555 we'd resume this process too. */
2f63ec5c 7556 *may_global_wildcard = false;
323fd5b9
PA
7557 if (event->ptid != null_ptid)
7558 {
7559 inferior *inf = find_inferior_ptid (this, event->ptid);
7560 if (inf != NULL)
7561 get_remote_inferior (inf)->may_wildcard_vcont = false;
7562 }
722247f1 7563 }
722247f1
YQ
7564}
7565
f48ff2a7 7566/* Discard all pending stop replies of inferior INF. */
c906108c 7567
6b8edb51
PA
7568void
7569remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7570{
f48ff2a7
YQ
7571 struct stop_reply *reply;
7572 struct remote_state *rs = get_remote_state ();
7573 struct remote_notif_state *rns = rs->notif_state;
7574
7575 /* This function can be notified when an inferior exists. When the
7576 target is not remote, the notification state is NULL. */
7577 if (rs->remote_desc == NULL)
7578 return;
7579
7580 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7581
74531fed 7582 /* Discard the in-flight notification. */
e99b03dc 7583 if (reply != NULL && reply->ptid.pid () == inf->pid)
74531fed 7584 {
b0083dd7
PA
7585 /* Leave the notification pending, since the server expects that
7586 we acknowledge it with vStopped. But clear its contents, so
7587 that later on when we acknowledge it, we also discard it. */
df5ad102
SM
7588 remote_debug_printf
7589 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7590 reply->ptid.to_string().c_str(),
7591 reply->ws.to_string ().c_str ());
183be222 7592 reply->ws.set_ignore ();
74531fed 7593 }
c906108c 7594
74531fed
PA
7595 /* Discard the stop replies we have already pulled with
7596 vStopped. */
953edf2b
TT
7597 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7598 rs->stop_reply_queue.end (),
7599 [=] (const stop_reply_up &event)
7600 {
7601 return event->ptid.pid () == inf->pid;
7602 });
df5ad102
SM
7603 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7604 remote_debug_printf
7605 ("discarding queued stop reply: ptid: %s, ws: %s\n",
1720b64f
AB
7606 (*it)->ptid.to_string().c_str(),
7607 (*it)->ws.to_string ().c_str ());
953edf2b 7608 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
bcc75809
YQ
7609}
7610
7611/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7612
6b8edb51
PA
7613void
7614remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7615{
6b8edb51 7616 remote_state *rs = get_remote_state ();
f48ff2a7 7617
f48ff2a7
YQ
7618 /* Discard the stop replies we have already pulled with
7619 vStopped. */
953edf2b
TT
7620 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7621 rs->stop_reply_queue.end (),
7622 [=] (const stop_reply_up &event)
7623 {
7624 return event->rs == rs;
7625 });
7626 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
74531fed 7627}
43ff13b4 7628
722247f1
YQ
7629/* Remove the first reply in 'stop_reply_queue' which matches
7630 PTID. */
2e9f7625 7631
6b8edb51
PA
7632struct stop_reply *
7633remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7634{
953edf2b 7635 remote_state *rs = get_remote_state ();
722247f1 7636
953edf2b
TT
7637 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7638 rs->stop_reply_queue.end (),
7639 [=] (const stop_reply_up &event)
7640 {
7641 return event->ptid.matches (ptid);
7642 });
7643 struct stop_reply *result;
7644 if (iter == rs->stop_reply_queue.end ())
7645 result = nullptr;
7646 else
7647 {
7648 result = iter->release ();
7649 rs->stop_reply_queue.erase (iter);
7650 }
722247f1 7651
722247f1 7652 if (notif_debug)
6cb06a8c
TT
7653 gdb_printf (gdb_stdlog,
7654 "notif: discard queued event: 'Stop' in %s\n",
7655 ptid.to_string ().c_str ());
a744cf53 7656
953edf2b 7657 return result;
74531fed 7658}
75c99385 7659
74531fed
PA
7660/* Look for a queued stop reply belonging to PTID. If one is found,
7661 remove it from the queue, and return it. Returns NULL if none is
7662 found. If there are still queued events left to process, tell the
7663 event loop to get back to target_wait soon. */
e24a49d8 7664
6b8edb51
PA
7665struct stop_reply *
7666remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7667{
953edf2b 7668 remote_state *rs = get_remote_state ();
722247f1 7669 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7670
4f626cad 7671 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
6b8edb51 7672 {
6b8edb51 7673 /* There's still at least an event left. */
92b98b37 7674 rs->mark_async_event_handler ();
6b8edb51 7675 }
74531fed 7676
722247f1 7677 return r;
74531fed
PA
7678}
7679
7680/* Push a fully parsed stop reply in the stop reply queue. Since we
7681 know that we now have at least one queued event left to pass to the
7682 core side, tell the event loop to get back to target_wait soon. */
7683
6b8edb51
PA
7684void
7685remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7686{
6b8edb51 7687 remote_state *rs = get_remote_state ();
953edf2b 7688 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
74531fed 7689
722247f1 7690 if (notif_debug)
6cb06a8c
TT
7691 gdb_printf (gdb_stdlog,
7692 "notif: push 'Stop' %s to queue %d\n",
7693 new_event->ptid.to_string ().c_str (),
7694 int (rs->stop_reply_queue.size ()));
74531fed 7695
4f626cad
AB
7696 /* Mark the pending event queue only if async mode is currently enabled.
7697 If async mode is not currently enabled, then, if it later becomes
7698 enabled, and there are events in this queue, we will mark the event
7699 token at that point, see remote_target::async. */
7700 if (target_is_async_p ())
92b98b37 7701 rs->mark_async_event_handler ();
74531fed
PA
7702}
7703
7704/* Returns true if we have a stop reply for PTID. */
7705
6b8edb51
PA
7706int
7707remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7708{
6b8edb51 7709 remote_state *rs = get_remote_state ();
953edf2b
TT
7710 for (auto &event : rs->stop_reply_queue)
7711 if (ptid == event->ptid
183be222 7712 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
953edf2b
TT
7713 return 1;
7714 return 0;
74531fed
PA
7715}
7716
26d56a93
SL
7717/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7718 starting with P and ending with PEND matches PREFIX. */
7719
7720static int
7721strprefix (const char *p, const char *pend, const char *prefix)
7722{
7723 for ( ; p < pend; p++, prefix++)
7724 if (*p != *prefix)
7725 return 0;
7726 return *prefix == '\0';
7727}
7728
74531fed
PA
7729/* Parse the stop reply in BUF. Either the function succeeds, and the
7730 result is stored in EVENT, or throws an error. */
7731
6b8edb51 7732void
bb277751 7733remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
74531fed 7734{
5cd63fda 7735 remote_arch_state *rsa = NULL;
74531fed 7736 ULONGEST addr;
256642e8 7737 const char *p;
94585166 7738 int skipregs = 0;
74531fed
PA
7739
7740 event->ptid = null_ptid;
bcc75809 7741 event->rs = get_remote_state ();
183be222 7742 event->ws.set_ignore ();
f7e6eed5 7743 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
32603266 7744 event->regcache.clear ();
dc146f7c 7745 event->core = -1;
74531fed
PA
7746
7747 switch (buf[0])
7748 {
7749 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7750 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7751 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7752 ss = signal number
7753 n... = register number
7754 r... = register contents
7755 */
7756
7757 p = &buf[3]; /* after Txx */
7758 while (*p)
7759 {
256642e8 7760 const char *p1;
cea39f65 7761 int fieldsize;
43ff13b4 7762
1f10ba14
PA
7763 p1 = strchr (p, ':');
7764 if (p1 == NULL)
7765 error (_("Malformed packet(a) (missing colon): %s\n\
7766Packet: '%s'\n"),
7767 p, buf);
7768 if (p == p1)
7769 error (_("Malformed packet(a) (missing register number): %s\n\
7770Packet: '%s'\n"),
7771 p, buf);
3c3bea1c 7772
1f10ba14
PA
7773 /* Some "registers" are actually extended stop information.
7774 Note if you're adding a new entry here: GDB 7.9 and
7775 earlier assume that all register "numbers" that start
7776 with an hex digit are real register numbers. Make sure
7777 the server only sends such a packet if it knows the
7778 client understands it. */
c8e38a49 7779
26d56a93 7780 if (strprefix (p, p1, "thread"))
1f10ba14 7781 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7782 else if (strprefix (p, p1, "syscall_entry"))
7783 {
7784 ULONGEST sysno;
7785
82075af2 7786 p = unpack_varlen_hex (++p1, &sysno);
183be222 7787 event->ws.set_syscall_entry ((int) sysno);
82075af2
JS
7788 }
7789 else if (strprefix (p, p1, "syscall_return"))
7790 {
7791 ULONGEST sysno;
7792
82075af2 7793 p = unpack_varlen_hex (++p1, &sysno);
183be222 7794 event->ws.set_syscall_return ((int) sysno);
82075af2 7795 }
26d56a93
SL
7796 else if (strprefix (p, p1, "watch")
7797 || strprefix (p, p1, "rwatch")
7798 || strprefix (p, p1, "awatch"))
cea39f65 7799 {
f7e6eed5 7800 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7801 p = unpack_varlen_hex (++p1, &addr);
7802 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7803 }
26d56a93 7804 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7805 {
7806 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7807
7808 /* Make sure the stub doesn't forget to indicate support
7809 with qSupported. */
ff52c073
CS
7810 if (m_features.packet_support (PACKET_swbreak_feature)
7811 != PACKET_ENABLE)
f7e6eed5
PA
7812 error (_("Unexpected swbreak stop reason"));
7813
7814 /* The value part is documented as "must be empty",
7815 though we ignore it, in case we ever decide to make
7816 use of it in a backward compatible way. */
8424cc97 7817 p = strchrnul (p1 + 1, ';');
f7e6eed5 7818 }
26d56a93 7819 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7820 {
7821 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7822
7823 /* Make sure the stub doesn't forget to indicate support
7824 with qSupported. */
ff52c073
CS
7825 if (m_features.packet_support (PACKET_hwbreak_feature)
7826 != PACKET_ENABLE)
f7e6eed5
PA
7827 error (_("Unexpected hwbreak stop reason"));
7828
7829 /* See above. */
8424cc97 7830 p = strchrnul (p1 + 1, ';');
f7e6eed5 7831 }
26d56a93 7832 else if (strprefix (p, p1, "library"))
cea39f65 7833 {
183be222 7834 event->ws.set_loaded ();
8424cc97 7835 p = strchrnul (p1 + 1, ';');
1f10ba14 7836 }
26d56a93 7837 else if (strprefix (p, p1, "replaylog"))
1f10ba14 7838 {
183be222 7839 event->ws.set_no_history ();
1f10ba14
PA
7840 /* p1 will indicate "begin" or "end", but it makes
7841 no difference for now, so ignore it. */
8424cc97 7842 p = strchrnul (p1 + 1, ';');
1f10ba14 7843 }
26d56a93 7844 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7845 {
7846 ULONGEST c;
a744cf53 7847
1f10ba14
PA
7848 p = unpack_varlen_hex (++p1, &c);
7849 event->core = c;
cea39f65 7850 }
26d56a93 7851 else if (strprefix (p, p1, "fork"))
183be222 7852 event->ws.set_forked (read_ptid (++p1, &p));
26d56a93 7853 else if (strprefix (p, p1, "vfork"))
183be222 7854 event->ws.set_vforked (read_ptid (++p1, &p));
26d56a93 7855 else if (strprefix (p, p1, "vforkdone"))
c269dbdb 7856 {
183be222 7857 event->ws.set_vfork_done ();
8424cc97 7858 p = strchrnul (p1 + 1, ';');
c269dbdb 7859 }
6ab24463 7860 else if (strprefix (p, p1, "exec"))
94585166
DB
7861 {
7862 ULONGEST ignored;
94585166
DB
7863 int pathlen;
7864
7865 /* Determine the length of the execd pathname. */
7866 p = unpack_varlen_hex (++p1, &ignored);
7867 pathlen = (p - p1) / 2;
7868
7869 /* Save the pathname for event reporting and for
7870 the next run command. */
183be222 7871 gdb::unique_xmalloc_ptr<char> pathname
c6321f19
TT
7872 ((char *) xmalloc (pathlen + 1));
7873 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
183be222 7874 pathname.get ()[pathlen] = '\0';
94585166
DB
7875
7876 /* This is freed during event handling. */
183be222 7877 event->ws.set_execd (std::move (pathname));
94585166
DB
7878
7879 /* Skip the registers included in this packet, since
7880 they may be for an architecture different from the
7881 one used by the original program. */
7882 skipregs = 1;
7883 }
65706a29
PA
7884 else if (strprefix (p, p1, "create"))
7885 {
183be222 7886 event->ws.set_thread_created ();
8424cc97 7887 p = strchrnul (p1 + 1, ';');
65706a29 7888 }
cea39f65
MS
7889 else
7890 {
1f10ba14 7891 ULONGEST pnum;
256642e8 7892 const char *p_temp;
1f10ba14 7893
94585166
DB
7894 if (skipregs)
7895 {
8424cc97 7896 p = strchrnul (p1 + 1, ';');
94585166
DB
7897 p++;
7898 continue;
7899 }
7900
1f10ba14
PA
7901 /* Maybe a real ``P'' register number. */
7902 p_temp = unpack_varlen_hex (p, &pnum);
7903 /* If the first invalid character is the colon, we got a
7904 register number. Otherwise, it's an unknown stop
7905 reason. */
7906 if (p_temp == p1)
7907 {
5cd63fda
PA
7908 /* If we haven't parsed the event's thread yet, find
7909 it now, in order to find the architecture of the
7910 reported expedited registers. */
7911 if (event->ptid == null_ptid)
7912 {
24ed6739
AB
7913 /* If there is no thread-id information then leave
7914 the event->ptid as null_ptid. Later in
7915 process_stop_reply we will pick a suitable
7916 thread. */
5cd63fda
PA
7917 const char *thr = strstr (p1 + 1, ";thread:");
7918 if (thr != NULL)
7919 event->ptid = read_ptid (thr + strlen (";thread:"),
7920 NULL);
5cd63fda
PA
7921 }
7922
7923 if (rsa == NULL)
7924 {
5b6d1e4f
PA
7925 inferior *inf
7926 = (event->ptid == null_ptid
7927 ? NULL
7928 : find_inferior_ptid (this, event->ptid));
5cd63fda
PA
7929 /* If this is the first time we learn anything
7930 about this process, skip the registers
7931 included in this packet, since we don't yet
7932 know which architecture to use to parse them.
7933 We'll determine the architecture later when
7934 we process the stop reply and retrieve the
7935 target description, via
7936 remote_notice_new_inferior ->
7937 post_create_inferior. */
7938 if (inf == NULL)
7939 {
7940 p = strchrnul (p1 + 1, ';');
7941 p++;
7942 continue;
7943 }
7944
27b1f19f 7945 event->arch = inf->arch ();
9d6eea31 7946 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7947 }
7948
7949 packet_reg *reg
7950 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7951 cached_reg_t cached_reg;
43ff13b4 7952
1f10ba14
PA
7953 if (reg == NULL)
7954 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7955Packet: '%s'\n"),
1f10ba14 7956 hex_string (pnum), p, buf);
c8e38a49 7957
1f10ba14 7958 cached_reg.num = reg->regnum;
d1dff226 7959 cached_reg.data = (gdb_byte *)
5cd63fda 7960 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7961
1f10ba14
PA
7962 p = p1 + 1;
7963 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7964 register_size (event->arch, reg->regnum));
1f10ba14 7965 p += 2 * fieldsize;
5cd63fda 7966 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7967 warning (_("Remote reply is too short: %s"), buf);
74531fed 7968
32603266 7969 event->regcache.push_back (cached_reg);
1f10ba14
PA
7970 }
7971 else
7972 {
7973 /* Not a number. Silently skip unknown optional
7974 info. */
8424cc97 7975 p = strchrnul (p1 + 1, ';');
1f10ba14 7976 }
cea39f65 7977 }
c8e38a49 7978
cea39f65
MS
7979 if (*p != ';')
7980 error (_("Remote register badly formatted: %s\nhere: %s"),
7981 buf, p);
7982 ++p;
7983 }
5b5596ff 7984
183be222 7985 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
5b5596ff
PA
7986 break;
7987
c8e38a49
PA
7988 /* fall through */
7989 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7990 {
7991 int sig;
7992
3a09da41
PA
7993 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7994 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
183be222 7995 event->ws.set_stopped ((enum gdb_signal) sig);
3a09da41 7996 else
183be222 7997 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
3a09da41 7998 }
c8e38a49 7999 break;
65706a29
PA
8000 case 'w': /* Thread exited. */
8001 {
65706a29
PA
8002 ULONGEST value;
8003
65706a29 8004 p = unpack_varlen_hex (&buf[1], &value);
183be222 8005 event->ws.set_thread_exited (value);
65706a29
PA
8006 if (*p != ';')
8007 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 8008 event->ptid = read_ptid (++p, NULL);
65706a29
PA
8009 break;
8010 }
c8e38a49
PA
8011 case 'W': /* Target exited. */
8012 case 'X':
8013 {
c8e38a49 8014 ULONGEST value;
82f73884 8015
c8e38a49
PA
8016 /* GDB used to accept only 2 hex chars here. Stubs should
8017 only send more if they detect GDB supports multi-process
8018 support. */
8019 p = unpack_varlen_hex (&buf[1], &value);
82f73884 8020
c8e38a49
PA
8021 if (buf[0] == 'W')
8022 {
8023 /* The remote process exited. */
183be222 8024 event->ws.set_exited (value);
c8e38a49
PA
8025 }
8026 else
8027 {
8028 /* The remote process exited with a signal. */
3a09da41 8029 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
183be222 8030 event->ws.set_signalled ((enum gdb_signal) value);
3a09da41 8031 else
183be222 8032 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
c8e38a49 8033 }
82f73884 8034
e7af6c70
TBA
8035 /* If no process is specified, return null_ptid, and let the
8036 caller figure out the right process to use. */
8037 int pid = 0;
c8e38a49
PA
8038 if (*p == '\0')
8039 ;
8040 else if (*p == ';')
8041 {
8042 p++;
8043
0b24eb2d 8044 if (*p == '\0')
82f73884 8045 ;
61012eef 8046 else if (startswith (p, "process:"))
82f73884 8047 {
c8e38a49 8048 ULONGEST upid;
a744cf53 8049
c8e38a49
PA
8050 p += sizeof ("process:") - 1;
8051 unpack_varlen_hex (p, &upid);
8052 pid = upid;
82f73884
PA
8053 }
8054 else
8055 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 8056 }
c8e38a49
PA
8057 else
8058 error (_("unknown stop reply packet: %s"), buf);
f2907e49 8059 event->ptid = ptid_t (pid);
74531fed
PA
8060 }
8061 break;
f2faf941 8062 case 'N':
183be222 8063 event->ws.set_no_resumed ();
f2faf941
PA
8064 event->ptid = minus_one_ptid;
8065 break;
74531fed 8066 }
74531fed
PA
8067}
8068
722247f1
YQ
8069/* When the stub wants to tell GDB about a new notification reply, it
8070 sends a notification (%Stop, for example). Those can come it at
8071 any time, hence, we have to make sure that any pending
8072 putpkt/getpkt sequence we're making is finished, before querying
8073 the stub for more events with the corresponding ack command
8074 (vStopped, for example). E.g., if we started a vStopped sequence
8075 immediately upon receiving the notification, something like this
8076 could happen:
74531fed
PA
8077
8078 1.1) --> Hg 1
8079 1.2) <-- OK
8080 1.3) --> g
8081 1.4) <-- %Stop
8082 1.5) --> vStopped
8083 1.6) <-- (registers reply to step #1.3)
8084
8085 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8086 query.
8087
796cb314 8088 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
8089 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8090 doing whatever we were doing:
8091
8092 2.1) --> Hg 1
8093 2.2) <-- OK
8094 2.3) --> g
8095 2.4) <-- %Stop
8096 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8097 2.5) <-- (registers reply to step #2.3)
8098
85102364 8099 Eventually after step #2.5, we return to the event loop, which
74531fed
PA
8100 notices there's an event on the
8101 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8102 associated callback --- the function below. At this point, we're
8103 always safe to start a vStopped sequence. :
8104
8105 2.6) --> vStopped
8106 2.7) <-- T05 thread:2
8107 2.8) --> vStopped
8108 2.9) --> OK
8109*/
8110
722247f1 8111void
42938c1a 8112remote_target::remote_notif_get_pending_events (const notif_client *nc)
74531fed
PA
8113{
8114 struct remote_state *rs = get_remote_state ();
74531fed 8115
f48ff2a7 8116 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 8117 {
722247f1 8118 if (notif_debug)
6cb06a8c
TT
8119 gdb_printf (gdb_stdlog,
8120 "notif: process: '%s' ack pending event\n",
8121 nc->name);
74531fed 8122
722247f1 8123 /* acknowledge */
8d64371b
TT
8124 nc->ack (this, nc, rs->buf.data (),
8125 rs->notif_state->pending_event[nc->id]);
f48ff2a7 8126 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
8127
8128 while (1)
8129 {
aa7b36b8 8130 getpkt (&rs->buf);
8d64371b 8131 if (strcmp (rs->buf.data (), "OK") == 0)
74531fed
PA
8132 break;
8133 else
8d64371b 8134 remote_notif_ack (this, nc, rs->buf.data ());
74531fed
PA
8135 }
8136 }
722247f1
YQ
8137 else
8138 {
8139 if (notif_debug)
6cb06a8c
TT
8140 gdb_printf (gdb_stdlog,
8141 "notif: process: '%s' no pending reply\n",
8142 nc->name);
722247f1 8143 }
74531fed
PA
8144}
8145
6b8edb51
PA
8146/* Wrapper around remote_target::remote_notif_get_pending_events to
8147 avoid having to export the whole remote_target class. */
8148
8149void
42938c1a 8150remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
6b8edb51
PA
8151{
8152 remote->remote_notif_get_pending_events (nc);
8153}
8154
8f66807b
AB
8155/* Called from process_stop_reply when the stop packet we are responding
8156 to didn't include a process-id or thread-id. STATUS is the stop event
8157 we are responding to.
8158
8159 It is the task of this function to select a suitable thread (or process)
8160 and return its ptid, this is the thread (or process) we will assume the
8161 stop event came from.
8162
8163 In some cases there isn't really any choice about which thread (or
8164 process) is selected, a basic remote with a single process containing a
8165 single thread might choose not to send any process-id or thread-id in
8166 its stop packets, this function will select and return the one and only
8167 thread.
8168
8169 However, if a target supports multiple threads (or processes) and still
8170 doesn't include a thread-id (or process-id) in its stop packet then
8171 first, this is a badly behaving target, and second, we're going to have
8172 to select a thread (or process) at random and use that. This function
8173 will print a warning to the user if it detects that there is the
8174 possibility that GDB is guessing which thread (or process) to
8175 report.
8176
8177 Note that this is called before GDB fetches the updated thread list from the
8178 target. So it's possible for the stop reply to be ambiguous and for GDB to
8179 not realize it. For example, if there's initially one thread, the target
8180 spawns a second thread, and then sends a stop reply without an id that
8181 concerns the first thread. GDB will assume the stop reply is about the
8182 first thread - the only thread it knows about - without printing a warning.
8183 Anyway, if the remote meant for the stop reply to be about the second thread,
8184 then it would be really broken, because GDB doesn't know about that thread
8185 yet. */
74531fed 8186
6b8edb51 8187ptid_t
8f66807b 8188remote_target::select_thread_for_ambiguous_stop_reply
c272a98c 8189 (const target_waitstatus &status)
74531fed 8190{
4351271e
AB
8191 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8192
8f66807b
AB
8193 /* Some stop events apply to all threads in an inferior, while others
8194 only apply to a single thread. */
8195 bool process_wide_stop
c272a98c
SM
8196 = (status.kind () == TARGET_WAITKIND_EXITED
8197 || status.kind () == TARGET_WAITKIND_SIGNALLED);
74531fed 8198
4351271e
AB
8199 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8200
8f66807b
AB
8201 thread_info *first_resumed_thread = nullptr;
8202 bool ambiguous = false;
74531fed 8203
8f66807b
AB
8204 /* Consider all non-exited threads of the target, find the first resumed
8205 one. */
8206 for (thread_info *thr : all_non_exited_threads (this))
24ed6739 8207 {
8f66807b 8208 remote_thread_info *remote_thr = get_remote_thread_info (thr);
cada5fc9 8209
a6c11cbb 8210 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8f66807b 8211 continue;
24ed6739 8212
8f66807b
AB
8213 if (first_resumed_thread == nullptr)
8214 first_resumed_thread = thr;
8215 else if (!process_wide_stop
8216 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8217 ambiguous = true;
8218 }
8219
b622494e
AB
8220 gdb_assert (first_resumed_thread != nullptr);
8221
4351271e
AB
8222 remote_debug_printf ("first resumed thread is %s",
8223 pid_to_str (first_resumed_thread->ptid).c_str ());
8224 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8225
8f66807b
AB
8226 /* Warn if the remote target is sending ambiguous stop replies. */
8227 if (ambiguous)
8228 {
8229 static bool warned = false;
8230
8231 if (!warned)
8232 {
8233 /* If you are seeing this warning then the remote target has
8234 stopped without specifying a thread-id, but the target
8235 does have multiple threads (or inferiors), and so GDB is
8236 having to guess which thread stopped.
8237
8238 Examples of what might cause this are the target sending
8239 and 'S' stop packet, or a 'T' stop packet and not
8240 including a thread-id.
8241
8242 Additionally, the target might send a 'W' or 'X packet
8243 without including a process-id, when the target has
8244 multiple running inferiors. */
8245 if (process_wide_stop)
8246 warning (_("multi-inferior target stopped without "
8247 "sending a process-id, using first "
8248 "non-exited inferior"));
cada5fc9 8249 else
8f66807b
AB
8250 warning (_("multi-threaded target stopped without "
8251 "sending a thread-id, using first "
8252 "non-exited thread"));
8253 warned = true;
24ed6739 8254 }
24ed6739 8255 }
74531fed 8256
8f66807b
AB
8257 /* If this is a stop for all threads then don't use a particular threads
8258 ptid, instead create a new ptid where only the pid field is set. */
8259 if (process_wide_stop)
8260 return ptid_t (first_resumed_thread->ptid.pid ());
8261 else
8262 return first_resumed_thread->ptid;
8263}
8264
8265/* Called when it is decided that STOP_REPLY holds the info of the
8266 event that is to be returned to the core. This function always
8267 destroys STOP_REPLY. */
8268
8269ptid_t
8270remote_target::process_stop_reply (struct stop_reply *stop_reply,
8271 struct target_waitstatus *status)
8272{
8273 *status = stop_reply->ws;
8274 ptid_t ptid = stop_reply->ptid;
8275
8276 /* If no thread/process was reported by the stub then select a suitable
8277 thread/process. */
8278 if (ptid == null_ptid)
c272a98c 8279 ptid = select_thread_for_ambiguous_stop_reply (*status);
8f66807b
AB
8280 gdb_assert (ptid != null_ptid);
8281
183be222
SM
8282 if (status->kind () != TARGET_WAITKIND_EXITED
8283 && status->kind () != TARGET_WAITKIND_SIGNALLED
8284 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
74531fed 8285 {
5f3563ea 8286 /* Expedited registers. */
32603266 8287 if (!stop_reply->regcache.empty ())
5f3563ea 8288 {
217f1f79 8289 struct regcache *regcache
5b6d1e4f 8290 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
5f3563ea 8291
32603266
TT
8292 for (cached_reg_t &reg : stop_reply->regcache)
8293 {
8294 regcache->raw_supply (reg.num, reg.data);
8295 xfree (reg.data);
8296 }
d1dff226 8297
32603266 8298 stop_reply->regcache.clear ();
5f3563ea 8299 }
74531fed 8300
8a82de58 8301 remote_notice_new_inferior (ptid, false);
5b6d1e4f 8302 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
799a2abe
PA
8303 remote_thr->core = stop_reply->core;
8304 remote_thr->stop_reason = stop_reply->stop_reason;
8305 remote_thr->watch_data_address = stop_reply->watch_data_address;
c9d22089
SM
8306
8307 if (target_is_non_stop_p ())
8308 {
8309 /* If the target works in non-stop mode, a stop-reply indicates that
8310 only this thread stopped. */
8311 remote_thr->set_not_resumed ();
8312 }
8313 else
8314 {
8315 /* If the target works in all-stop mode, a stop-reply indicates that
8316 all the target's threads stopped. */
8317 for (thread_info *tp : all_non_exited_threads (this))
8318 get_remote_thread_info (tp)->set_not_resumed ();
8319 }
74531fed
PA
8320 }
8321
32603266 8322 delete stop_reply;
74531fed
PA
8323 return ptid;
8324}
8325
8326/* The non-stop mode version of target_wait. */
8327
6b8edb51 8328ptid_t
b60cea74
TT
8329remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8330 target_wait_flags options)
74531fed
PA
8331{
8332 struct remote_state *rs = get_remote_state ();
74531fed
PA
8333 struct stop_reply *stop_reply;
8334 int ret;
8756b726 8335 bool is_notif = false;
74531fed
PA
8336
8337 /* If in non-stop mode, get out of getpkt even if a
8338 notification is received. */
8339
a60f93c7 8340 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
74531fed
PA
8341 while (1)
8342 {
fee9eda9 8343 if (ret != -1 && !is_notif)
74531fed
PA
8344 switch (rs->buf[0])
8345 {
8346 case 'E': /* Error of some sort. */
8347 /* We're out of sync with the target now. Did it continue
8348 or not? We can't tell which thread it was in non-stop,
8349 so just ignore this. */
8d64371b 8350 warning (_("Remote failure reply: %s"), rs->buf.data ());
74531fed
PA
8351 break;
8352 case 'O': /* Console output. */
8d64371b 8353 remote_console_output (&rs->buf[1]);
74531fed
PA
8354 break;
8355 default:
8d64371b 8356 warning (_("Invalid remote reply: %s"), rs->buf.data ());
74531fed
PA
8357 break;
8358 }
8359
8360 /* Acknowledge a pending stop reply that may have arrived in the
8361 mean time. */
f48ff2a7 8362 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 8363 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
8364
8365 /* If indeed we noticed a stop reply, we're done. */
8366 stop_reply = queued_stop_reply (ptid);
8367 if (stop_reply != NULL)
8368 return process_stop_reply (stop_reply, status);
8369
47608cb1 8370 /* Still no event. If we're just polling for an event, then
74531fed 8371 return to the event loop. */
47608cb1 8372 if (options & TARGET_WNOHANG)
74531fed 8373 {
183be222 8374 status->set_ignore ();
74531fed
PA
8375 return minus_one_ptid;
8376 }
8377
47608cb1 8378 /* Otherwise do a blocking wait. */
a60f93c7 8379 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
74531fed
PA
8380 }
8381}
8382
31ba933e
PA
8383/* Return the first resumed thread. */
8384
8385static ptid_t
5b6d1e4f 8386first_remote_resumed_thread (remote_target *target)
31ba933e 8387{
5b6d1e4f 8388 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
7846f3aa 8389 if (tp->resumed ())
31ba933e
PA
8390 return tp->ptid;
8391 return null_ptid;
8392}
8393
74531fed
PA
8394/* Wait until the remote machine stops, then return, storing status in
8395 STATUS just as `wait' would. */
8396
6b8edb51 8397ptid_t
b60cea74
TT
8398remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8399 target_wait_flags options)
74531fed
PA
8400{
8401 struct remote_state *rs = get_remote_state ();
74531fed 8402 ptid_t event_ptid = null_ptid;
cea39f65 8403 char *buf;
74531fed
PA
8404 struct stop_reply *stop_reply;
8405
47608cb1
PA
8406 again:
8407
183be222 8408 status->set_ignore ();
74531fed
PA
8409
8410 stop_reply = queued_stop_reply (ptid);
8411 if (stop_reply != NULL)
4f626cad
AB
8412 {
8413 /* None of the paths that push a stop reply onto the queue should
8414 have set the waiting_for_stop_reply flag. */
8415 gdb_assert (!rs->waiting_for_stop_reply);
8416 event_ptid = process_stop_reply (stop_reply, status);
8417 }
74531fed
PA
8418 else
8419 {
8756b726
TT
8420 bool forever = ((options & TARGET_WNOHANG) == 0
8421 && rs->wait_forever_enabled_p);
567420d1
PA
8422
8423 if (!rs->waiting_for_stop_reply)
8424 {
183be222 8425 status->set_no_resumed ();
567420d1
PA
8426 return minus_one_ptid;
8427 }
74531fed 8428
74531fed
PA
8429 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8430 _never_ wait for ever -> test on target_is_async_p().
8431 However, before we do that we need to ensure that the caller
8432 knows how to take the target into/out of async mode. */
8756b726 8433 bool is_notif;
a60f93c7 8434 int ret = getpkt (&rs->buf, forever, &is_notif);
722247f1
YQ
8435
8436 /* GDB gets a notification. Return to core as this event is
8437 not interesting. */
8438 if (ret != -1 && is_notif)
8439 return minus_one_ptid;
567420d1
PA
8440
8441 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8442 return minus_one_ptid;
74531fed 8443
4f626cad 8444 buf = rs->buf.data ();
74531fed 8445
4f626cad
AB
8446 /* Assume that the target has acknowledged Ctrl-C unless we receive
8447 an 'F' or 'O' packet. */
8448 if (buf[0] != 'F' && buf[0] != 'O')
8449 rs->ctrlc_pending_p = 0;
3a29589a 8450
4f626cad
AB
8451 switch (buf[0])
8452 {
8453 case 'E': /* Error of some sort. */
8454 /* We're out of sync with the target now. Did it continue or
8455 not? Not is more likely, so report a stop. */
8456 rs->waiting_for_stop_reply = 0;
29090fb6 8457
4f626cad
AB
8458 warning (_("Remote failure reply: %s"), buf);
8459 status->set_stopped (GDB_SIGNAL_0);
8460 break;
8461 case 'F': /* File-I/O request. */
8462 /* GDB may access the inferior memory while handling the File-I/O
8463 request, but we don't want GDB accessing memory while waiting
8464 for a stop reply. See the comments in putpkt_binary. Set
8465 waiting_for_stop_reply to 0 temporarily. */
8466 rs->waiting_for_stop_reply = 0;
8467 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8468 rs->ctrlc_pending_p = 0;
8469 /* GDB handled the File-I/O request, and the target is running
8470 again. Keep waiting for events. */
8471 rs->waiting_for_stop_reply = 1;
8472 break;
8473 case 'N': case 'T': case 'S': case 'X': case 'W':
8474 {
8475 /* There is a stop reply to handle. */
8476 rs->waiting_for_stop_reply = 0;
29090fb6 8477
4f626cad
AB
8478 stop_reply
8479 = (struct stop_reply *) remote_notif_parse (this,
8480 &notif_client_stop,
8481 rs->buf.data ());
74531fed 8482
4f626cad
AB
8483 event_ptid = process_stop_reply (stop_reply, status);
8484 break;
8485 }
8486 case 'O': /* Console output. */
8487 remote_console_output (buf + 1);
8488 break;
8489 case '\0':
8490 if (rs->last_sent_signal != GDB_SIGNAL_0)
8491 {
8492 /* Zero length reply means that we tried 'S' or 'C' and the
8493 remote system doesn't support it. */
8494 target_terminal::ours_for_output ();
6cb06a8c 8495 gdb_printf
4f626cad
AB
8496 ("Can't send signals to this remote system. %s not sent.\n",
8497 gdb_signal_to_name (rs->last_sent_signal));
8498 rs->last_sent_signal = GDB_SIGNAL_0;
8499 target_terminal::inferior ();
8500
8501 strcpy (buf, rs->last_sent_step ? "s" : "c");
8502 putpkt (buf);
8503 break;
8504 }
8505 /* fallthrough */
8506 default:
8507 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 8508 break;
43ff13b4
JM
8509 }
8510 }
c8e38a49 8511
183be222 8512 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
f2faf941 8513 return minus_one_ptid;
183be222 8514 else if (status->kind () == TARGET_WAITKIND_IGNORE)
47608cb1
PA
8515 {
8516 /* Nothing interesting happened. If we're doing a non-blocking
8517 poll, we're done. Otherwise, go back to waiting. */
8518 if (options & TARGET_WNOHANG)
8519 return minus_one_ptid;
8520 else
8521 goto again;
8522 }
183be222
SM
8523 else if (status->kind () != TARGET_WAITKIND_EXITED
8524 && status->kind () != TARGET_WAITKIND_SIGNALLED)
82f73884 8525 {
d7e15655 8526 if (event_ptid != null_ptid)
47f8a51d 8527 record_currthread (rs, event_ptid);
82f73884 8528 else
5b6d1e4f 8529 event_ptid = first_remote_resumed_thread (this);
43ff13b4 8530 }
74531fed 8531 else
e7af6c70
TBA
8532 {
8533 /* A process exit. Invalidate our notion of current thread. */
8534 record_currthread (rs, minus_one_ptid);
8535 /* It's possible that the packet did not include a pid. */
8536 if (event_ptid == null_ptid)
5b6d1e4f 8537 event_ptid = first_remote_resumed_thread (this);
e7af6c70
TBA
8538 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8539 if (event_ptid == null_ptid)
8540 event_ptid = magic_null_ptid;
8541 }
79d7f229 8542
82f73884 8543 return event_ptid;
43ff13b4
JM
8544}
8545
74531fed
PA
8546/* Wait until the remote machine stops, then return, storing status in
8547 STATUS just as `wait' would. */
8548
f6ac5f3d 8549ptid_t
b60cea74
TT
8550remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8551 target_wait_flags options)
c8e38a49 8552{
2189c312
SM
8553 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8554
baa8575b
SM
8555 remote_state *rs = get_remote_state ();
8556
8557 /* Start by clearing the flag that asks for our wait method to be called,
8d34471f
AB
8558 we'll mark it again at the end if needed. If the target is not in
8559 async mode then the async token should not be marked. */
baa8575b 8560 if (target_is_async_p ())
92b98b37 8561 rs->clear_async_event_handler ();
8d34471f 8562 else
92b98b37 8563 gdb_assert (!rs->async_event_handler_marked ());
baa8575b 8564
c8e38a49
PA
8565 ptid_t event_ptid;
8566
6efcd9a8 8567 if (target_is_non_stop_p ())
6b8edb51 8568 event_ptid = wait_ns (ptid, status, options);
74531fed 8569 else
6b8edb51 8570 event_ptid = wait_as (ptid, status, options);
c8e38a49 8571
d9d41e78 8572 if (target_is_async_p ())
c8e38a49 8573 {
baa8575b
SM
8574 /* If there are events left in the queue, or unacknowledged
8575 notifications, then tell the event loop to call us again. */
8576 if (!rs->stop_reply_queue.empty ()
8577 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
92b98b37 8578 rs->mark_async_event_handler ();
c8e38a49 8579 }
c8e38a49
PA
8580
8581 return event_ptid;
8582}
8583
74ca34ce 8584/* Fetch a single register using a 'p' packet. */
c906108c 8585
6b8edb51
PA
8586int
8587remote_target::fetch_register_using_p (struct regcache *regcache,
8588 packet_reg *reg)
b96ec7ac 8589{
ac7936df 8590 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 8591 struct remote_state *rs = get_remote_state ();
2e9f7625 8592 char *buf, *p;
9890e433 8593 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
8594 int i;
8595
ff52c073 8596 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
8597 return 0;
8598
8599 if (reg->pnum == -1)
8600 return 0;
8601
8d64371b 8602 p = rs->buf.data ();
fcad0fa4 8603 *p++ = 'p';
74ca34ce 8604 p += hexnumstr (p, reg->pnum);
fcad0fa4 8605 *p++ = '\0';
1f4437a4 8606 putpkt (rs->buf);
aa7b36b8 8607 getpkt (&rs->buf);
3f9a994c 8608
8d64371b 8609 buf = rs->buf.data ();
2e9f7625 8610
ff52c073 8611 switch (m_features.packet_ok (rs->buf, PACKET_p))
74ca34ce
DJ
8612 {
8613 case PACKET_OK:
8614 break;
8615 case PACKET_UNKNOWN:
8616 return 0;
8617 case PACKET_ERROR:
27a9c0bf 8618 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7a78108a 8619 gdbarch_register_name (regcache->arch (), reg->regnum),
27a9c0bf 8620 buf);
74ca34ce 8621 }
3f9a994c
JB
8622
8623 /* If this register is unfetchable, tell the regcache. */
8624 if (buf[0] == 'x')
8480adf2 8625 {
73e1c03f 8626 regcache->raw_supply (reg->regnum, NULL);
8480adf2 8627 return 1;
b96ec7ac 8628 }
b96ec7ac 8629
3f9a994c
JB
8630 /* Otherwise, parse and supply the value. */
8631 p = buf;
8632 i = 0;
8633 while (p[0] != 0)
8634 {
8635 if (p[1] == 0)
74ca34ce 8636 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
8637
8638 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8639 p += 2;
8640 }
73e1c03f 8641 regcache->raw_supply (reg->regnum, regp);
3f9a994c 8642 return 1;
b96ec7ac
AC
8643}
8644
74ca34ce
DJ
8645/* Fetch the registers included in the target's 'g' packet. */
8646
6b8edb51
PA
8647int
8648remote_target::send_g_packet ()
c906108c 8649{
d01949b6 8650 struct remote_state *rs = get_remote_state ();
cea39f65 8651 int buf_len;
c906108c 8652
8d64371b 8653 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
b75abf5b 8654 putpkt (rs->buf);
aa7b36b8 8655 getpkt (&rs->buf);
b75abf5b
AK
8656 if (packet_check_result (rs->buf) == PACKET_ERROR)
8657 error (_("Could not read registers; remote failure reply '%s'"),
dda83cd7 8658 rs->buf.data ());
c906108c 8659
29709017
DJ
8660 /* We can get out of synch in various cases. If the first character
8661 in the buffer is not a hex character, assume that has happened
8662 and try to fetch another packet to read. */
8663 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8664 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8665 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8666 && rs->buf[0] != 'x') /* New: unavailable register value. */
8667 {
2189c312 8668 remote_debug_printf ("Bad register packet; fetching a new packet");
aa7b36b8 8669 getpkt (&rs->buf);
29709017
DJ
8670 }
8671
8d64371b 8672 buf_len = strlen (rs->buf.data ());
74ca34ce
DJ
8673
8674 /* Sanity check the received packet. */
8675 if (buf_len % 2 != 0)
8d64371b 8676 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
29709017
DJ
8677
8678 return buf_len / 2;
8679}
8680
6b8edb51
PA
8681void
8682remote_target::process_g_packet (struct regcache *regcache)
29709017 8683{
ac7936df 8684 struct gdbarch *gdbarch = regcache->arch ();
29709017 8685 struct remote_state *rs = get_remote_state ();
9d6eea31 8686 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8687 int i, buf_len;
8688 char *p;
8689 char *regs;
8690
8d64371b 8691 buf_len = strlen (rs->buf.data ());
29709017
DJ
8692
8693 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8694 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827 8695 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8d64371b
TT
8696 "bytes): %s"),
8697 rsa->sizeof_g_packet, buf_len / 2,
8698 rs->buf.data ());
74ca34ce
DJ
8699
8700 /* Save the size of the packet sent to us by the target. It is used
8701 as a heuristic when determining the max size of packets that the
8702 target can safely receive. */
8703 if (rsa->actual_register_packet_size == 0)
8704 rsa->actual_register_packet_size = buf_len;
8705
8706 /* If this is smaller than we guessed the 'g' packet would be,
8707 update our records. A 'g' reply that doesn't include a register's
8708 value implies either that the register is not available, or that
8709 the 'p' packet must be used. */
8710 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8711 {
9dc193c3 8712 long sizeof_g_packet = buf_len / 2;
74ca34ce 8713
4a22f64d 8714 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8715 {
9dc193c3
LF
8716 long offset = rsa->regs[i].offset;
8717 long reg_size = register_size (gdbarch, i);
8718
74ca34ce
DJ
8719 if (rsa->regs[i].pnum == -1)
8720 continue;
8721
9dc193c3 8722 if (offset >= sizeof_g_packet)
74ca34ce 8723 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8724 else if (offset + reg_size > sizeof_g_packet)
8725 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8726 else
74ca34ce 8727 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8728 }
9dc193c3
LF
8729
8730 /* Looks valid enough, we can assume this is the correct length
dda83cd7
SM
8731 for a 'g' packet. It's important not to adjust
8732 rsa->sizeof_g_packet if we have truncated registers otherwise
8733 this "if" won't be run the next time the method is called
8734 with a packet of the same size and one of the internal errors
8735 below will trigger instead. */
9dc193c3 8736 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8737 }
b323314b 8738
224c3ddb 8739 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8740
8741 /* Unimplemented registers read as all bits zero. */
ea9c271d 8742 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8743
c906108c
SS
8744 /* Reply describes registers byte by byte, each byte encoded as two
8745 hex characters. Suck them all up, then supply them to the
8746 register cacheing/storage mechanism. */
8747
8d64371b 8748 p = rs->buf.data ();
ea9c271d 8749 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8750 {
74ca34ce
DJ
8751 if (p[0] == 0 || p[1] == 0)
8752 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
f34652de 8753 internal_error (_("unexpected end of 'g' packet reply"));
74ca34ce 8754
c906108c 8755 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8756 regs[i] = 0; /* 'x' */
c906108c
SS
8757 else
8758 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8759 p += 2;
8760 }
8761
a744cf53
MS
8762 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8763 {
8764 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8765 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8766
8767 if (r->in_g_packet)
8768 {
8d64371b 8769 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
a744cf53 8770 /* This shouldn't happen - we adjusted in_g_packet above. */
f34652de 8771 internal_error (_("unexpected end of 'g' packet reply"));
a744cf53
MS
8772 else if (rs->buf[r->offset * 2] == 'x')
8773 {
8d64371b 8774 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
a744cf53
MS
8775 /* The register isn't available, mark it as such (at
8776 the same time setting the value to zero). */
73e1c03f 8777 regcache->raw_supply (r->regnum, NULL);
a744cf53
MS
8778 }
8779 else
73e1c03f 8780 regcache->raw_supply (r->regnum, regs + r->offset);
a744cf53
MS
8781 }
8782 }
c906108c
SS
8783}
8784
6b8edb51
PA
8785void
8786remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8787{
8788 send_g_packet ();
56be3814 8789 process_g_packet (regcache);
29709017
DJ
8790}
8791
e6e4e701
PA
8792/* Make the remote selected traceframe match GDB's selected
8793 traceframe. */
8794
6b8edb51
PA
8795void
8796remote_target::set_remote_traceframe ()
e6e4e701
PA
8797{
8798 int newnum;
262e1174 8799 struct remote_state *rs = get_remote_state ();
e6e4e701 8800
262e1174 8801 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8802 return;
8803
8804 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8805 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8806
8807 newnum = target_trace_find (tfind_number,
8808 get_traceframe_number (), 0, 0, NULL);
8809
8810 /* Should not happen. If it does, all bets are off. */
8811 if (newnum != get_traceframe_number ())
8812 warning (_("could not set remote traceframe"));
8813}
8814
f6ac5f3d
PA
8815void
8816remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8817{
ac7936df 8818 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8819 struct remote_state *rs = get_remote_state ();
8820 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8821 int i;
8822
e6e4e701 8823 set_remote_traceframe ();
222312d3 8824 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8825
8826 if (regnum >= 0)
8827 {
5cd63fda 8828 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8829
74ca34ce
DJ
8830 gdb_assert (reg != NULL);
8831
8832 /* If this register might be in the 'g' packet, try that first -
8833 we are likely to read more than one register. If this is the
8834 first 'g' packet, we might be overly optimistic about its
8835 contents, so fall back to 'p'. */
8836 if (reg->in_g_packet)
8837 {
56be3814 8838 fetch_registers_using_g (regcache);
74ca34ce
DJ
8839 if (reg->in_g_packet)
8840 return;
8841 }
8842
56be3814 8843 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8844 return;
8845
8846 /* This register is not available. */
73e1c03f 8847 regcache->raw_supply (reg->regnum, NULL);
74ca34ce
DJ
8848
8849 return;
8850 }
8851
56be3814 8852 fetch_registers_using_g (regcache);
74ca34ce 8853
5cd63fda 8854 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8855 if (!rsa->regs[i].in_g_packet)
56be3814 8856 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8857 {
8858 /* This register is not available. */
73e1c03f 8859 regcache->raw_supply (i, NULL);
74ca34ce
DJ
8860 }
8861}
8862
c906108c
SS
8863/* Prepare to store registers. Since we may send them all (using a
8864 'G' request), we have to read out the ones we don't want to change
8865 first. */
8866
f6ac5f3d
PA
8867void
8868remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8869{
9d6eea31
PA
8870 struct remote_state *rs = get_remote_state ();
8871 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8872 int i;
cf0e1e0d 8873
c906108c 8874 /* Make sure the entire registers array is valid. */
ff52c073 8875 switch (m_features.packet_support (PACKET_P))
5a2468f5
JM
8876 {
8877 case PACKET_DISABLE:
8878 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8879 /* Make sure all the necessary registers are cached. */
ac7936df 8880 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8881 if (rsa->regs[i].in_g_packet)
0b47d985 8882 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
8883 break;
8884 case PACKET_ENABLE:
8885 break;
8886 }
8887}
8888
ad10f812 8889/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8890 packet was not recognized. */
5a2468f5 8891
6b8edb51
PA
8892int
8893remote_target::store_register_using_P (const struct regcache *regcache,
8894 packet_reg *reg)
5a2468f5 8895{
ac7936df 8896 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8897 struct remote_state *rs = get_remote_state ();
5a2468f5 8898 /* Try storing a single register. */
8d64371b 8899 char *buf = rs->buf.data ();
9890e433 8900 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8901 char *p;
5a2468f5 8902
ff52c073 8903 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8904 return 0;
8905
8906 if (reg->pnum == -1)
8907 return 0;
8908
ea9c271d 8909 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8910 p = buf + strlen (buf);
34a79281 8911 regcache->raw_collect (reg->regnum, regp);
4a22f64d 8912 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4 8913 putpkt (rs->buf);
aa7b36b8 8914 getpkt (&rs->buf);
5a2468f5 8915
ff52c073 8916 switch (m_features.packet_ok (rs->buf, PACKET_P))
74ca34ce
DJ
8917 {
8918 case PACKET_OK:
8919 return 1;
8920 case PACKET_ERROR:
27a9c0bf 8921 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8d64371b 8922 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
74ca34ce
DJ
8923 case PACKET_UNKNOWN:
8924 return 0;
8925 default:
f34652de 8926 internal_error (_("Bad result from packet_ok"));
74ca34ce 8927 }
c906108c
SS
8928}
8929
23860348
MS
8930/* Store register REGNUM, or all registers if REGNUM == -1, from the
8931 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8932
6b8edb51
PA
8933void
8934remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8935{
d01949b6 8936 struct remote_state *rs = get_remote_state ();
9d6eea31 8937 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8938 gdb_byte *regs;
c906108c
SS
8939 char *p;
8940
193cb69f
AC
8941 /* Extract all the registers in the regcache copying them into a
8942 local buffer. */
8943 {
b323314b 8944 int i;
a744cf53 8945
224c3ddb 8946 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8947 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8948 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8949 {
ea9c271d 8950 struct packet_reg *r = &rsa->regs[i];
a744cf53 8951
b323314b 8952 if (r->in_g_packet)
34a79281 8953 regcache->raw_collect (r->regnum, regs + r->offset);
193cb69f
AC
8954 }
8955 }
c906108c
SS
8956
8957 /* Command describes registers byte by byte,
8958 each byte encoded as two hex characters. */
8d64371b 8959 p = rs->buf.data ();
193cb69f 8960 *p++ = 'G';
74ca34ce 8961 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4 8962 putpkt (rs->buf);
aa7b36b8 8963 getpkt (&rs->buf);
1f4437a4 8964 if (packet_check_result (rs->buf) == PACKET_ERROR)
7a78108a 8965 error (_("Could not write registers; remote failure reply '%s'"),
8d64371b 8966 rs->buf.data ());
c906108c 8967}
74ca34ce
DJ
8968
8969/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8970 of the register cache buffer. FIXME: ignores errors. */
8971
f6ac5f3d
PA
8972void
8973remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8974{
5cd63fda 8975 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8976 struct remote_state *rs = get_remote_state ();
8977 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8978 int i;
8979
e6e4e701 8980 set_remote_traceframe ();
222312d3 8981 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8982
8983 if (regnum >= 0)
8984 {
5cd63fda 8985 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8986
74ca34ce
DJ
8987 gdb_assert (reg != NULL);
8988
8989 /* Always prefer to store registers using the 'P' packet if
8990 possible; we often change only a small number of registers.
8991 Sometimes we change a larger number; we'd need help from a
8992 higher layer to know to use 'G'. */
56be3814 8993 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8994 return;
8995
8996 /* For now, don't complain if we have no way to write the
8997 register. GDB loses track of unavailable registers too
8998 easily. Some day, this may be an error. We don't have
0df8b418 8999 any way to read the register, either... */
74ca34ce
DJ
9000 if (!reg->in_g_packet)
9001 return;
9002
56be3814 9003 store_registers_using_G (regcache);
74ca34ce
DJ
9004 return;
9005 }
9006
56be3814 9007 store_registers_using_G (regcache);
74ca34ce 9008
5cd63fda 9009 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 9010 if (!rsa->regs[i].in_g_packet)
56be3814 9011 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
9012 /* See above for why we do not issue an error here. */
9013 continue;
9014}
c906108c
SS
9015\f
9016
9017/* Return the number of hex digits in num. */
9018
9019static int
fba45db2 9020hexnumlen (ULONGEST num)
c906108c
SS
9021{
9022 int i;
9023
9024 for (i = 0; num != 0; i++)
9025 num >>= 4;
9026
325fac50 9027 return std::max (i, 1);
c906108c
SS
9028}
9029
2df3850c 9030/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
9031
9032static int
fba45db2 9033hexnumstr (char *buf, ULONGEST num)
c906108c 9034{
c906108c 9035 int len = hexnumlen (num);
a744cf53 9036
2df3850c
JM
9037 return hexnumnstr (buf, num, len);
9038}
9039
c906108c 9040
2df3850c 9041/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 9042
2df3850c 9043static int
fba45db2 9044hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
9045{
9046 int i;
9047
9048 buf[width] = '\0';
9049
9050 for (i = width - 1; i >= 0; i--)
c906108c 9051 {
c5aa993b 9052 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
9053 num >>= 4;
9054 }
9055
2df3850c 9056 return width;
c906108c
SS
9057}
9058
23860348 9059/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
9060
9061static CORE_ADDR
fba45db2 9062remote_address_masked (CORE_ADDR addr)
c906108c 9063{
883b9c6c 9064 unsigned int address_size = remote_address_size;
a744cf53 9065
911c95a5
UW
9066 /* If "remoteaddresssize" was not set, default to target address size. */
9067 if (!address_size)
99d9c3b9 9068 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
911c95a5
UW
9069
9070 if (address_size > 0
9071 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
9072 {
9073 /* Only create a mask when that mask can safely be constructed
dda83cd7 9074 in a ULONGEST variable. */
c906108c 9075 ULONGEST mask = 1;
a744cf53 9076
911c95a5 9077 mask = (mask << address_size) - 1;
c906108c
SS
9078 addr &= mask;
9079 }
9080 return addr;
9081}
9082
9083/* Determine whether the remote target supports binary downloading.
9084 This is accomplished by sending a no-op memory write of zero length
9085 to the target at the specified address. It does not suffice to send
23860348
MS
9086 the whole packet, since many stubs strip the eighth bit and
9087 subsequently compute a wrong checksum, which causes real havoc with
9088 remote_write_bytes.
7a292a7a 9089
96baa820 9090 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 9091 clean. In cases like this, the user should clear "remote
23860348 9092 X-packet". */
96baa820 9093
6b8edb51
PA
9094void
9095remote_target::check_binary_download (CORE_ADDR addr)
c906108c 9096{
d01949b6 9097 struct remote_state *rs = get_remote_state ();
24b06219 9098
ff52c073 9099 switch (m_features.packet_support (PACKET_X))
c906108c 9100 {
96baa820
JM
9101 case PACKET_DISABLE:
9102 break;
9103 case PACKET_ENABLE:
9104 break;
9105 case PACKET_SUPPORT_UNKNOWN:
9106 {
96baa820 9107 char *p;
802188a7 9108
8d64371b 9109 p = rs->buf.data ();
96baa820
JM
9110 *p++ = 'X';
9111 p += hexnumstr (p, (ULONGEST) addr);
9112 *p++ = ',';
9113 p += hexnumstr (p, (ULONGEST) 0);
9114 *p++ = ':';
9115 *p = '\0';
802188a7 9116
8d64371b 9117 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
aa7b36b8 9118 getpkt (&rs->buf);
c906108c 9119
2e9f7625 9120 if (rs->buf[0] == '\0')
96baa820 9121 {
2189c312 9122 remote_debug_printf ("binary downloading NOT supported by target");
ff52c073 9123 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
9124 }
9125 else
9126 {
2189c312 9127 remote_debug_printf ("binary downloading supported by target");
ff52c073 9128 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
9129 }
9130 break;
9131 }
c906108c
SS
9132 }
9133}
9134
124e13d9
SM
9135/* Helper function to resize the payload in order to try to get a good
9136 alignment. We try to write an amount of data such that the next write will
9137 start on an address aligned on REMOTE_ALIGN_WRITES. */
9138
9139static int
9140align_for_efficient_write (int todo, CORE_ADDR memaddr)
9141{
9142 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9143}
9144
c906108c
SS
9145/* Write memory data directly to the remote machine.
9146 This does not inform the data cache; the data cache uses this.
a76d924d 9147 HEADER is the starting part of the packet.
c906108c
SS
9148 MEMADDR is the address in the remote memory space.
9149 MYADDR is the address of the buffer in our space.
124e13d9
SM
9150 LEN_UNITS is the number of addressable units to write.
9151 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
9152 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9153 should send data as binary ('X'), or hex-encoded ('M').
9154
9155 The function creates packet of the form
9156 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9157
124e13d9 9158 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
9159
9160 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9161 are omitted.
9162
9b409511 9163 Return the transferred status, error or OK (an
124e13d9
SM
9164 'enum target_xfer_status' value). Save the number of addressable units
9165 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9166
9167 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9168 exchange between gdb and the stub could look like (?? in place of the
9169 checksum):
9170
9171 -> $m1000,4#??
9172 <- aaaabbbbccccdddd
9173
9174 -> $M1000,3:eeeeffffeeee#??
9175 <- OK
9176
9177 -> $m1000,4#??
9178 <- eeeeffffeeeedddd */
c906108c 9179
6b8edb51
PA
9180target_xfer_status
9181remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9182 const gdb_byte *myaddr,
9183 ULONGEST len_units,
9184 int unit_size,
9185 ULONGEST *xfered_len_units,
9186 char packet_format, int use_length)
c906108c 9187{
6d820c5c 9188 struct remote_state *rs = get_remote_state ();
cfd77fa1 9189 char *p;
a76d924d
DJ
9190 char *plen = NULL;
9191 int plenlen = 0;
124e13d9
SM
9192 int todo_units;
9193 int units_written;
9194 int payload_capacity_bytes;
9195 int payload_length_bytes;
a76d924d
DJ
9196
9197 if (packet_format != 'X' && packet_format != 'M')
f34652de 9198 internal_error (_("remote_write_bytes_aux: bad packet format"));
c906108c 9199
124e13d9 9200 if (len_units == 0)
9b409511 9201 return TARGET_XFER_EOF;
b2182ed2 9202
124e13d9 9203 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 9204
6d820c5c
DJ
9205 /* The packet buffer will be large enough for the payload;
9206 get_memory_packet_size ensures this. */
a76d924d 9207 rs->buf[0] = '\0';
c906108c 9208
a257b5bb 9209 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
9210 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9211
124e13d9 9212 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 9213 if (!use_length)
0df8b418 9214 /* The comma won't be used. */
124e13d9
SM
9215 payload_capacity_bytes += 1;
9216 payload_capacity_bytes -= strlen (header);
9217 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 9218
a76d924d 9219 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 9220
8d64371b
TT
9221 strcat (rs->buf.data (), header);
9222 p = rs->buf.data () + strlen (header);
a76d924d
DJ
9223
9224 /* Compute a best guess of the number of bytes actually transfered. */
9225 if (packet_format == 'X')
c906108c 9226 {
23860348 9227 /* Best guess at number of bytes that will fit. */
325fac50
PA
9228 todo_units = std::min (len_units,
9229 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 9230 if (use_length)
124e13d9 9231 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 9232 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
9233 }
9234 else
9235 {
124e13d9 9236 /* Number of bytes that will fit. */
325fac50
PA
9237 todo_units
9238 = std::min (len_units,
9239 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 9240 if (use_length)
124e13d9 9241 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
9242 todo_units = std::min (todo_units,
9243 (payload_capacity_bytes / unit_size) / 2);
917317f4 9244 }
a76d924d 9245
124e13d9 9246 if (todo_units <= 0)
f34652de 9247 internal_error (_("minimum packet size too small to write data"));
802188a7 9248
6765f3e5
DJ
9249 /* If we already need another packet, then try to align the end
9250 of this packet to a useful boundary. */
124e13d9
SM
9251 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9252 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 9253
a257b5bb 9254 /* Append "<memaddr>". */
917317f4
JM
9255 memaddr = remote_address_masked (memaddr);
9256 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 9257
a76d924d
DJ
9258 if (use_length)
9259 {
9260 /* Append ",". */
9261 *p++ = ',';
802188a7 9262
124e13d9 9263 /* Append the length and retain its location and size. It may need to be
dda83cd7 9264 adjusted once the packet body has been created. */
a76d924d 9265 plen = p;
124e13d9 9266 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
9267 p += plenlen;
9268 }
a257b5bb
AC
9269
9270 /* Append ":". */
917317f4
JM
9271 *p++ = ':';
9272 *p = '\0';
802188a7 9273
a257b5bb 9274 /* Append the packet body. */
a76d924d 9275 if (packet_format == 'X')
917317f4 9276 {
917317f4
JM
9277 /* Binary mode. Send target system values byte by byte, in
9278 increasing byte addresses. Only escape certain critical
9279 characters. */
124e13d9
SM
9280 payload_length_bytes =
9281 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9282 &units_written, payload_capacity_bytes);
6765f3e5 9283
124e13d9 9284 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
9285 a second try to keep the end of the packet aligned. Don't do
9286 this if the packet is tiny. */
124e13d9 9287 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 9288 {
124e13d9
SM
9289 int new_todo_units;
9290
9291 new_todo_units = align_for_efficient_write (units_written, memaddr);
9292
9293 if (new_todo_units != units_written)
9294 payload_length_bytes =
9295 remote_escape_output (myaddr, new_todo_units, unit_size,
9296 (gdb_byte *) p, &units_written,
9297 payload_capacity_bytes);
6765f3e5
DJ
9298 }
9299
124e13d9
SM
9300 p += payload_length_bytes;
9301 if (use_length && units_written < todo_units)
c906108c 9302 {
802188a7 9303 /* Escape chars have filled up the buffer prematurely,
124e13d9 9304 and we have actually sent fewer units than planned.
917317f4
JM
9305 Fix-up the length field of the packet. Use the same
9306 number of characters as before. */
124e13d9
SM
9307 plen += hexnumnstr (plen, (ULONGEST) units_written,
9308 plenlen);
917317f4 9309 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 9310 }
a76d924d
DJ
9311 }
9312 else
9313 {
917317f4
JM
9314 /* Normal mode: Send target system values byte by byte, in
9315 increasing byte addresses. Each byte is encoded as a two hex
9316 value. */
124e13d9
SM
9317 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9318 units_written = todo_units;
c906108c 9319 }
802188a7 9320
8d64371b 9321 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
aa7b36b8 9322 getpkt (&rs->buf);
802188a7 9323
2e9f7625 9324 if (rs->buf[0] == 'E')
00d84524 9325 return TARGET_XFER_E_IO;
802188a7 9326
124e13d9
SM
9327 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9328 send fewer units than we'd planned. */
9329 *xfered_len_units = (ULONGEST) units_written;
92ffd475 9330 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
9331}
9332
a76d924d
DJ
9333/* Write memory data directly to the remote machine.
9334 This does not inform the data cache; the data cache uses this.
9335 MEMADDR is the address in the remote memory space.
9336 MYADDR is the address of the buffer in our space.
9337 LEN is the number of bytes.
9338
9b409511
YQ
9339 Return the transferred status, error or OK (an
9340 'enum target_xfer_status' value). Save the number of bytes
9341 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 9342
6b8edb51
PA
9343target_xfer_status
9344remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9345 ULONGEST len, int unit_size,
9346 ULONGEST *xfered_len)
a76d924d 9347{
a121b7c1 9348 const char *packet_format = NULL;
a76d924d
DJ
9349
9350 /* Check whether the target supports binary download. */
9351 check_binary_download (memaddr);
9352
ff52c073 9353 switch (m_features.packet_support (PACKET_X))
a76d924d
DJ
9354 {
9355 case PACKET_ENABLE:
9356 packet_format = "X";
9357 break;
9358 case PACKET_DISABLE:
9359 packet_format = "M";
9360 break;
9361 case PACKET_SUPPORT_UNKNOWN:
f34652de 9362 internal_error (_("remote_write_bytes: bad internal state"));
a76d924d 9363 default:
f34652de 9364 internal_error (_("bad switch"));
a76d924d
DJ
9365 }
9366
9367 return remote_write_bytes_aux (packet_format,
124e13d9 9368 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 9369 packet_format[0], 1);
a76d924d
DJ
9370}
9371
9217e74e
YQ
9372/* Read memory data directly from the remote machine.
9373 This does not use the data cache; the data cache uses this.
9374 MEMADDR is the address in the remote memory space.
9375 MYADDR is the address of the buffer in our space.
124e13d9
SM
9376 LEN_UNITS is the number of addressable memory units to read..
9377 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
9378
9379 Return the transferred status, error or OK (an
9380 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
9381 transferred in *XFERED_LEN_UNITS.
9382
9383 See the comment of remote_write_bytes_aux for an example of
9384 memory read/write exchange between gdb and the stub. */
9217e74e 9385
6b8edb51
PA
9386target_xfer_status
9387remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9388 ULONGEST len_units,
9389 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
9390{
9391 struct remote_state *rs = get_remote_state ();
124e13d9 9392 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 9393 char *p;
124e13d9
SM
9394 int todo_units;
9395 int decoded_bytes;
9217e74e 9396
124e13d9 9397 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
9398 /* The packet buffer will be large enough for the payload;
9399 get_memory_packet_size ensures this. */
9400
124e13d9 9401 /* Number of units that will fit. */
325fac50
PA
9402 todo_units = std::min (len_units,
9403 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
9404
9405 /* Construct "m"<memaddr>","<len>". */
9406 memaddr = remote_address_masked (memaddr);
8d64371b 9407 p = rs->buf.data ();
9217e74e
YQ
9408 *p++ = 'm';
9409 p += hexnumstr (p, (ULONGEST) memaddr);
9410 *p++ = ',';
124e13d9 9411 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
9412 *p = '\0';
9413 putpkt (rs->buf);
aa7b36b8 9414 getpkt (&rs->buf);
9217e74e
YQ
9415 if (rs->buf[0] == 'E'
9416 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9417 && rs->buf[3] == '\0')
9418 return TARGET_XFER_E_IO;
9419 /* Reply describes memory byte by byte, each byte encoded as two hex
9420 characters. */
8d64371b 9421 p = rs->buf.data ();
124e13d9 9422 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 9423 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 9424 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 9425 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
9426}
9427
b55fbac4
YQ
9428/* Using the set of read-only target sections of remote, read live
9429 read-only memory.
8acf9577
YQ
9430
9431 For interface/parameters/return description see target.h,
9432 to_xfer_partial. */
9433
6b8edb51
PA
9434target_xfer_status
9435remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9436 ULONGEST memaddr,
9437 ULONGEST len,
9438 int unit_size,
9439 ULONGEST *xfered_len)
8acf9577 9440{
19cf757a 9441 const struct target_section *secp;
8acf9577 9442
6b8edb51 9443 secp = target_section_by_addr (this, memaddr);
8acf9577 9444 if (secp != NULL
fd361982 9445 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
8acf9577 9446 {
8acf9577
YQ
9447 ULONGEST memend = memaddr + len;
9448
25b5a04e
SM
9449 const std::vector<target_section> *table
9450 = target_get_section_table (this);
19cf757a 9451 for (const target_section &p : *table)
8acf9577 9452 {
bb2a6777 9453 if (memaddr >= p.addr)
8acf9577 9454 {
bb2a6777 9455 if (memend <= p.endaddr)
8acf9577
YQ
9456 {
9457 /* Entire transfer is within this section. */
124e13d9 9458 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9459 xfered_len);
8acf9577 9460 }
bb2a6777 9461 else if (memaddr >= p.endaddr)
8acf9577
YQ
9462 {
9463 /* This section ends before the transfer starts. */
9464 continue;
9465 }
9466 else
9467 {
9468 /* This section overlaps the transfer. Just do half. */
bb2a6777 9469 len = p.endaddr - memaddr;
124e13d9 9470 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9471 xfered_len);
8acf9577
YQ
9472 }
9473 }
9474 }
9475 }
9476
9477 return TARGET_XFER_EOF;
9478}
9479
9217e74e
YQ
9480/* Similar to remote_read_bytes_1, but it reads from the remote stub
9481 first if the requested memory is unavailable in traceframe.
9482 Otherwise, fall back to remote_read_bytes_1. */
c906108c 9483
6b8edb51
PA
9484target_xfer_status
9485remote_target::remote_read_bytes (CORE_ADDR memaddr,
9486 gdb_byte *myaddr, ULONGEST len, int unit_size,
9487 ULONGEST *xfered_len)
c906108c 9488{
6b6aa828 9489 if (len == 0)
96c4f946 9490 return TARGET_XFER_EOF;
b2182ed2 9491
8acf9577
YQ
9492 if (get_traceframe_number () != -1)
9493 {
a79b1bc6 9494 std::vector<mem_range> available;
8acf9577
YQ
9495
9496 /* If we fail to get the set of available memory, then the
9497 target does not support querying traceframe info, and so we
9498 attempt reading from the traceframe anyway (assuming the
9499 target implements the old QTro packet then). */
9500 if (traceframe_available_memory (&available, memaddr, len))
9501 {
a79b1bc6 9502 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
9503 {
9504 enum target_xfer_status res;
9505
9506 /* Don't read into the traceframe's available
9507 memory. */
a79b1bc6 9508 if (!available.empty ())
8acf9577
YQ
9509 {
9510 LONGEST oldlen = len;
9511
a79b1bc6 9512 len = available[0].start - memaddr;
8acf9577
YQ
9513 gdb_assert (len <= oldlen);
9514 }
9515
8acf9577 9516 /* This goes through the topmost target again. */
6b8edb51 9517 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 9518 len, unit_size, xfered_len);
8acf9577
YQ
9519 if (res == TARGET_XFER_OK)
9520 return TARGET_XFER_OK;
9521 else
9522 {
9523 /* No use trying further, we know some memory starting
9524 at MEMADDR isn't available. */
9525 *xfered_len = len;
92ffd475
PC
9526 return (*xfered_len != 0) ?
9527 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
9528 }
9529 }
9530
9531 /* Don't try to read more than how much is available, in
9532 case the target implements the deprecated QTro packet to
9533 cater for older GDBs (the target's knowledge of read-only
9534 sections may be outdated by now). */
a79b1bc6 9535 len = available[0].length;
8acf9577
YQ
9536 }
9537 }
9538
124e13d9 9539 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 9540}
74531fed 9541
c906108c 9542\f
c906108c 9543
a76d924d
DJ
9544/* Sends a packet with content determined by the printf format string
9545 FORMAT and the remaining arguments, then gets the reply. Returns
9546 whether the packet was a success, a failure, or unknown. */
9547
6b8edb51
PA
9548packet_result
9549remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
9550{
9551 struct remote_state *rs = get_remote_state ();
9552 int max_size = get_remote_packet_size ();
a76d924d 9553 va_list ap;
a744cf53 9554
a76d924d
DJ
9555 va_start (ap, format);
9556
9557 rs->buf[0] = '\0';
8d64371b 9558 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
33b031ce
GB
9559
9560 va_end (ap);
9561
9562 if (size >= max_size)
f34652de 9563 internal_error (_("Too long remote packet."));
a76d924d
DJ
9564
9565 if (putpkt (rs->buf) < 0)
9566 error (_("Communication problem with target."));
9567
9568 rs->buf[0] = '\0';
aa7b36b8 9569 getpkt (&rs->buf);
a76d924d
DJ
9570
9571 return packet_check_result (rs->buf);
9572}
9573
a76d924d
DJ
9574/* Flash writing can take quite some time. We'll set
9575 effectively infinite timeout for flash operations.
9576 In future, we'll need to decide on a better approach. */
9577static const int remote_flash_timeout = 1000;
9578
f6ac5f3d
PA
9579void
9580remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 9581{
99d9c3b9 9582 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
a76d924d 9583 enum packet_result ret;
2ec845e7
TT
9584 scoped_restore restore_timeout
9585 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
9586
9587 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 9588 phex (address, addr_size),
a76d924d
DJ
9589 phex (length, 4));
9590 switch (ret)
9591 {
9592 case PACKET_UNKNOWN:
9593 error (_("Remote target does not support flash erase"));
9594 case PACKET_ERROR:
9595 error (_("Error erasing flash with vFlashErase packet"));
9596 default:
9597 break;
9598 }
a76d924d
DJ
9599}
9600
6b8edb51
PA
9601target_xfer_status
9602remote_target::remote_flash_write (ULONGEST address,
9603 ULONGEST length, ULONGEST *xfered_len,
9604 const gdb_byte *data)
a76d924d 9605{
2ec845e7
TT
9606 scoped_restore restore_timeout
9607 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9608 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9609 xfered_len,'X', 0);
a76d924d
DJ
9610}
9611
f6ac5f3d
PA
9612void
9613remote_target::flash_done ()
a76d924d 9614{
a76d924d 9615 int ret;
a76d924d 9616
2ec845e7
TT
9617 scoped_restore restore_timeout
9618 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9619
a76d924d 9620 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
9621
9622 switch (ret)
9623 {
9624 case PACKET_UNKNOWN:
9625 error (_("Remote target does not support vFlashDone"));
9626 case PACKET_ERROR:
9627 error (_("Error finishing flash operation"));
9628 default:
9629 break;
9630 }
9631}
9632
c906108c
SS
9633\f
9634/* Stuff for dealing with the packets which are part of this protocol.
9635 See comment at top of file for details. */
9636
1927e618
PA
9637/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9638 error to higher layers. Called when a serial error is detected.
9639 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
9640 the system error message for errno at function entry and final dot
9641 for output compatibility with throw_perror_with_name. */
1927e618
PA
9642
9643static void
5b6d1e4f 9644unpush_and_perror (remote_target *target, const char *string)
1927e618 9645{
d6cb50a2 9646 int saved_errno = errno;
1927e618 9647
5b6d1e4f 9648 remote_unpush_target (target);
d6cb50a2
JK
9649 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9650 safe_strerror (saved_errno));
1927e618
PA
9651}
9652
048094ac
PA
9653/* Read a single character from the remote end. The current quit
9654 handler is overridden to avoid quitting in the middle of packet
9655 sequence, as that would break communication with the remote server.
9656 See remote_serial_quit_handler for more detail. */
c906108c 9657
6b8edb51
PA
9658int
9659remote_target::readchar (int timeout)
c906108c
SS
9660{
9661 int ch;
5d93a237 9662 struct remote_state *rs = get_remote_state ();
048094ac 9663
2ec845e7 9664 {
6b8edb51
PA
9665 scoped_restore restore_quit_target
9666 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9667 scoped_restore restore_quit
6b8edb51 9668 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9669
2ec845e7 9670 rs->got_ctrlc_during_io = 0;
c906108c 9671
2ec845e7 9672 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9673
2ec845e7
TT
9674 if (rs->got_ctrlc_during_io)
9675 set_quit_flag ();
9676 }
048094ac 9677
2acceee2 9678 if (ch >= 0)
0876f84a 9679 return ch;
2acceee2
JM
9680
9681 switch ((enum serial_rc) ch)
c906108c
SS
9682 {
9683 case SERIAL_EOF:
5b6d1e4f 9684 remote_unpush_target (this);
598d3636 9685 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9686 /* no return */
c906108c 9687 case SERIAL_ERROR:
5b6d1e4f 9688 unpush_and_perror (this, _("Remote communication error. "
c8f6fc92 9689 "Target disconnected"));
2acceee2 9690 /* no return */
c906108c 9691 case SERIAL_TIMEOUT:
2acceee2 9692 break;
c906108c 9693 }
2acceee2 9694 return ch;
c906108c
SS
9695}
9696
c33e31fd 9697/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9698 writing fails. The current quit handler is overridden to avoid
9699 quitting in the middle of packet sequence, as that would break
9700 communication with the remote server. See
9701 remote_serial_quit_handler for more detail. */
c33e31fd 9702
6b8edb51
PA
9703void
9704remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9705{
5d93a237 9706 struct remote_state *rs = get_remote_state ();
048094ac 9707
6b8edb51
PA
9708 scoped_restore restore_quit_target
9709 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9710 scoped_restore restore_quit
6b8edb51 9711 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9712
9713 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9714
9715 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9716 {
5b6d1e4f 9717 unpush_and_perror (this, _("Remote communication error. "
c8f6fc92 9718 "Target disconnected"));
c33e31fd 9719 }
048094ac
PA
9720
9721 if (rs->got_ctrlc_during_io)
9722 set_quit_flag ();
c33e31fd
PA
9723}
9724
b3ced9ba
PA
9725/* Return a string representing an escaped version of BUF, of len N.
9726 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9727
b3ced9ba 9728static std::string
6e5abd65
PA
9729escape_buffer (const char *buf, int n)
9730{
d7e74731 9731 string_file stb;
6e5abd65 9732
d7e74731 9733 stb.putstrn (buf, n, '\\');
5d10a204 9734 return stb.release ();
6e5abd65
PA
9735}
9736
c906108c 9737int
6b8edb51 9738remote_target::putpkt (const char *buf)
c906108c
SS
9739{
9740 return putpkt_binary (buf, strlen (buf));
9741}
9742
6b8edb51
PA
9743/* Wrapper around remote_target::putpkt to avoid exporting
9744 remote_target. */
9745
9746int
9747putpkt (remote_target *remote, const char *buf)
9748{
9749 return remote->putpkt (buf);
9750}
9751
c906108c 9752/* Send a packet to the remote machine, with error checking. The data
23860348 9753 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9754 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9755 and for a possible /0 if we are debugging (remote_debug) and want
9756 to print the sent packet as a string. */
c906108c 9757
6b8edb51
PA
9758int
9759remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9760{
2d717e4f 9761 struct remote_state *rs = get_remote_state ();
c906108c
SS
9762 int i;
9763 unsigned char csum = 0;
b80406ac
TT
9764 gdb::def_vector<char> data (cnt + 6);
9765 char *buf2 = data.data ();
085dd6e6 9766
c906108c
SS
9767 int ch;
9768 int tcount = 0;
9769 char *p;
9770
e24a49d8
PA
9771 /* Catch cases like trying to read memory or listing threads while
9772 we're waiting for a stop reply. The remote server wouldn't be
9773 ready to handle this request, so we'd hang and timeout. We don't
9774 have to worry about this in synchronous mode, because in that
9775 case it's not possible to issue a command while the target is
74531fed
PA
9776 running. This is not a problem in non-stop mode, because in that
9777 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9778 if (!target_is_non_stop_p ()
9779 && target_is_async_p ()
9780 && rs->waiting_for_stop_reply)
9597b22a
DE
9781 {
9782 error (_("Cannot execute this command while the target is running.\n"
9783 "Use the \"interrupt\" command to stop the target\n"
9784 "and then try again."));
9785 }
e24a49d8 9786
c906108c
SS
9787 /* Copy the packet into buffer BUF2, encapsulating it
9788 and giving it a checksum. */
9789
c906108c
SS
9790 p = buf2;
9791 *p++ = '$';
9792
9793 for (i = 0; i < cnt; i++)
9794 {
9795 csum += buf[i];
9796 *p++ = buf[i];
9797 }
9798 *p++ = '#';
9799 *p++ = tohex ((csum >> 4) & 0xf);
9800 *p++ = tohex (csum & 0xf);
9801
9802 /* Send it over and over until we get a positive ack. */
9803
9804 while (1)
9805 {
c906108c
SS
9806 if (remote_debug)
9807 {
9808 *p = '\0';
b3ced9ba 9809
6f8976bf 9810 int len = (int) (p - buf2);
6cc8564b
LM
9811 int max_chars;
9812
9813 if (remote_packet_max_chars < 0)
9814 max_chars = len;
9815 else
9816 max_chars = remote_packet_max_chars;
6f8976bf
YQ
9817
9818 std::string str
6cc8564b 9819 = escape_buffer (buf2, std::min (len, max_chars));
6f8976bf 9820
6cc8564b 9821 if (len > max_chars)
2189c312
SM
9822 remote_debug_printf_nofunc
9823 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9824 len - max_chars);
9825 else
9826 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
c906108c 9827 }
c33e31fd 9828 remote_serial_write (buf2, p - buf2);
c906108c 9829
a6f3e723
SL
9830 /* If this is a no acks version of the remote protocol, send the
9831 packet and move on. */
9832 if (rs->noack_mode)
dda83cd7 9833 break;
a6f3e723 9834
74531fed
PA
9835 /* Read until either a timeout occurs (-2) or '+' is read.
9836 Handle any notification that arrives in the mean time. */
c906108c
SS
9837 while (1)
9838 {
9839 ch = readchar (remote_timeout);
9840
c906108c
SS
9841 switch (ch)
9842 {
9843 case '+':
2189c312 9844 remote_debug_printf_nofunc ("Received Ack");
c906108c 9845 return 1;
1216fa2c 9846 case '-':
2189c312 9847 remote_debug_printf_nofunc ("Received Nak");
a17d146e 9848 /* FALLTHROUGH */
c906108c 9849 case SERIAL_TIMEOUT:
c5aa993b 9850 tcount++;
c906108c 9851 if (tcount > 3)
b80406ac 9852 return 0;
23860348 9853 break; /* Retransmit buffer. */
c906108c
SS
9854 case '$':
9855 {
2189c312 9856 remote_debug_printf ("Packet instead of Ack, ignoring it");
d6f7abdf
AC
9857 /* It's probably an old response sent because an ACK
9858 was lost. Gobble up the packet and ack it so it
9859 doesn't get retransmitted when we resend this
9860 packet. */
6d820c5c 9861 skip_frame ();
c33e31fd 9862 remote_serial_write ("+", 1);
23860348 9863 continue; /* Now, go look for +. */
c906108c 9864 }
74531fed
PA
9865
9866 case '%':
9867 {
9868 int val;
9869
9870 /* If we got a notification, handle it, and go back to looking
9871 for an ack. */
9872 /* We've found the start of a notification. Now
9873 collect the data. */
8d64371b 9874 val = read_frame (&rs->buf);
74531fed
PA
9875 if (val >= 0)
9876 {
2189c312
SM
9877 remote_debug_printf_nofunc
9878 (" Notification received: %s",
9879 escape_buffer (rs->buf.data (), val).c_str ());
6e5abd65 9880
8d64371b 9881 handle_notification (rs->notif_state, rs->buf.data ());
74531fed
PA
9882 /* We're in sync now, rewait for the ack. */
9883 tcount = 0;
9884 }
9885 else
2189c312
SM
9886 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9887 rs->buf.data ());
74531fed
PA
9888 continue;
9889 }
9890 /* fall-through */
c906108c 9891 default:
2189c312
SM
9892 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9893 rs->buf.data ());
c906108c
SS
9894 continue;
9895 }
23860348 9896 break; /* Here to retransmit. */
c906108c
SS
9897 }
9898
9899#if 0
9900 /* This is wrong. If doing a long backtrace, the user should be
dda83cd7
SM
9901 able to get out next time we call QUIT, without anything as
9902 violent as interrupt_query. If we want to provide a way out of
9903 here without getting to the next QUIT, it should be based on
9904 hitting ^C twice as in remote_wait. */
c906108c
SS
9905 if (quit_flag)
9906 {
9907 quit_flag = 0;
9908 interrupt_query ();
9909 }
9910#endif
9911 }
a5c0808e 9912
a6f3e723 9913 return 0;
c906108c
SS
9914}
9915
6d820c5c
DJ
9916/* Come here after finding the start of a frame when we expected an
9917 ack. Do our best to discard the rest of this packet. */
9918
6b8edb51
PA
9919void
9920remote_target::skip_frame ()
6d820c5c
DJ
9921{
9922 int c;
9923
9924 while (1)
9925 {
9926 c = readchar (remote_timeout);
9927 switch (c)
9928 {
9929 case SERIAL_TIMEOUT:
9930 /* Nothing we can do. */
9931 return;
9932 case '#':
9933 /* Discard the two bytes of checksum and stop. */
9934 c = readchar (remote_timeout);
9935 if (c >= 0)
9936 c = readchar (remote_timeout);
9937
9938 return;
9939 case '*': /* Run length encoding. */
9940 /* Discard the repeat count. */
9941 c = readchar (remote_timeout);
9942 if (c < 0)
9943 return;
9944 break;
9945 default:
9946 /* A regular character. */
9947 break;
9948 }
9949 }
9950}
9951
c906108c 9952/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9953 into *BUF, verifying the checksum, length, and handling run-length
9954 compression. NUL terminate the buffer. If there is not enough room,
8d64371b 9955 expand *BUF.
c906108c 9956
c2d11a7d
JM
9957 Returns -1 on error, number of characters in buffer (ignoring the
9958 trailing NULL) on success. (could be extended to return one of the
23860348 9959 SERIAL status indications). */
c2d11a7d 9960
6b8edb51 9961long
8d64371b 9962remote_target::read_frame (gdb::char_vector *buf_p)
c906108c
SS
9963{
9964 unsigned char csum;
c2d11a7d 9965 long bc;
c906108c 9966 int c;
8d64371b 9967 char *buf = buf_p->data ();
a6f3e723 9968 struct remote_state *rs = get_remote_state ();
c906108c
SS
9969
9970 csum = 0;
c2d11a7d 9971 bc = 0;
c906108c
SS
9972
9973 while (1)
9974 {
9975 c = readchar (remote_timeout);
c906108c
SS
9976 switch (c)
9977 {
9978 case SERIAL_TIMEOUT:
2189c312 9979 remote_debug_printf ("Timeout in mid-packet, retrying");
c2d11a7d 9980 return -1;
2189c312 9981
c906108c 9982 case '$':
2189c312 9983 remote_debug_printf ("Saw new packet start in middle of old one");
23860348 9984 return -1; /* Start a new packet, count retries. */
2189c312 9985
c906108c
SS
9986 case '#':
9987 {
9988 unsigned char pktcsum;
e1b09194
AC
9989 int check_0 = 0;
9990 int check_1 = 0;
c906108c 9991
c2d11a7d 9992 buf[bc] = '\0';
c906108c 9993
e1b09194
AC
9994 check_0 = readchar (remote_timeout);
9995 if (check_0 >= 0)
9996 check_1 = readchar (remote_timeout);
802188a7 9997
e1b09194
AC
9998 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9999 {
2189c312 10000 remote_debug_printf ("Timeout in checksum, retrying");
e1b09194
AC
10001 return -1;
10002 }
10003 else if (check_0 < 0 || check_1 < 0)
40e3f985 10004 {
2189c312 10005 remote_debug_printf ("Communication error in checksum");
40e3f985
FN
10006 return -1;
10007 }
c906108c 10008
a6f3e723
SL
10009 /* Don't recompute the checksum; with no ack packets we
10010 don't have any way to indicate a packet retransmission
10011 is necessary. */
10012 if (rs->noack_mode)
10013 return bc;
10014
e1b09194 10015 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 10016 if (csum == pktcsum)
dda83cd7 10017 return bc;
c906108c 10018
2189c312
SM
10019 remote_debug_printf
10020 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10021 pktcsum, csum, escape_buffer (buf, bc).c_str ());
6e5abd65 10022
c2d11a7d 10023 /* Number of characters in buffer ignoring trailing
dda83cd7 10024 NULL. */
c2d11a7d 10025 return -1;
c906108c 10026 }
23860348 10027 case '*': /* Run length encoding. */
dda83cd7 10028 {
c2c6d25f 10029 int repeat;
c906108c 10030
24b21115 10031 csum += c;
b4501125
AC
10032 c = readchar (remote_timeout);
10033 csum += c;
23860348 10034 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 10035
23860348 10036 /* The character before ``*'' is repeated. */
c2d11a7d 10037
6d820c5c 10038 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 10039 {
8d64371b 10040 if (bc + repeat - 1 >= buf_p->size () - 1)
6d820c5c
DJ
10041 {
10042 /* Make some more room in the buffer. */
8d64371b
TT
10043 buf_p->resize (buf_p->size () + repeat);
10044 buf = buf_p->data ();
6d820c5c
DJ
10045 }
10046
c2d11a7d
JM
10047 memset (&buf[bc], buf[bc - 1], repeat);
10048 bc += repeat;
c2c6d25f
JM
10049 continue;
10050 }
10051
c2d11a7d 10052 buf[bc] = '\0';
6cb06a8c 10053 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 10054 return -1;
c2c6d25f 10055 }
c906108c 10056 default:
8d64371b 10057 if (bc >= buf_p->size () - 1)
c906108c 10058 {
6d820c5c 10059 /* Make some more room in the buffer. */
8d64371b
TT
10060 buf_p->resize (buf_p->size () * 2);
10061 buf = buf_p->data ();
c906108c
SS
10062 }
10063
6d820c5c
DJ
10064 buf[bc++] = c;
10065 csum += c;
10066 continue;
c906108c
SS
10067 }
10068 }
10069}
10070
ed2b7c17
TT
10071/* Set this to the maximum number of seconds to wait instead of waiting forever
10072 in target_wait(). If this timer times out, then it generates an error and
10073 the command is aborted. This replaces most of the need for timeouts in the
10074 GDB test suite, and makes it possible to distinguish between a hung target
10075 and one with slow communications. */
10076
10077static int watchdog = 0;
10078static void
10079show_watchdog (struct ui_file *file, int from_tty,
10080 struct cmd_list_element *c, const char *value)
10081{
6cb06a8c 10082 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
ed2b7c17
TT
10083}
10084
d9fcf2fb 10085/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
10086 store it in *BUF. Resize *BUF if necessary to hold the result. If
10087 FOREVER, wait forever rather than timing out; this is used (in
10088 synchronous mode) to wait for a target that is is executing user
8756b726 10089 code to stop. If FOREVER == false, this function is allowed to time
8d64371b 10090 out gracefully and return an indication of this to the caller.
ef6a9843
TT
10091 Otherwise return the number of bytes read. If IS_NOTIF is not
10092 NULL, then consider receiving a notification enough reason to
10093 return to the caller. In this case, *IS_NOTIF is an output boolean
10094 that indicates whether *BUF holds a notification or not (a regular
10095 packet). */
74531fed 10096
6b8edb51 10097int
a60f93c7 10098remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
c906108c 10099{
2d717e4f 10100 struct remote_state *rs = get_remote_state ();
c906108c
SS
10101 int c;
10102 int tries;
10103 int timeout;
df4b58fe 10104 int val = -1;
c906108c 10105
8d64371b 10106 strcpy (buf->data (), "timeout");
c906108c
SS
10107
10108 if (forever)
74531fed 10109 timeout = watchdog > 0 ? watchdog : -1;
ef6a9843 10110 else if (is_notif != nullptr)
74531fed
PA
10111 timeout = 0; /* There should already be a char in the buffer. If
10112 not, bail out. */
c906108c
SS
10113 else
10114 timeout = remote_timeout;
10115
10116#define MAX_TRIES 3
10117
74531fed
PA
10118 /* Process any number of notifications, and then return when
10119 we get a packet. */
10120 for (;;)
c906108c 10121 {
d9c43928 10122 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
10123 times. */
10124 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 10125 {
74531fed
PA
10126 /* This can loop forever if the remote side sends us
10127 characters continuously, but if it pauses, we'll get
10128 SERIAL_TIMEOUT from readchar because of timeout. Then
10129 we'll count that as a retry.
10130
10131 Note that even when forever is set, we will only wait
10132 forever prior to the start of a packet. After that, we
10133 expect characters to arrive at a brisk pace. They should
10134 show up within remote_timeout intervals. */
10135 do
10136 c = readchar (timeout);
10137 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
10138
10139 if (c == SERIAL_TIMEOUT)
10140 {
ef6a9843 10141 if (is_notif != nullptr)
74531fed
PA
10142 return -1; /* Don't complain, it's normal to not get
10143 anything in this case. */
10144
23860348 10145 if (forever) /* Watchdog went off? Kill the target. */
c906108c 10146 {
5b6d1e4f 10147 remote_unpush_target (this);
598d3636
JK
10148 throw_error (TARGET_CLOSE_ERROR,
10149 _("Watchdog timeout has expired. "
10150 "Target detached."));
c906108c 10151 }
2189c312
SM
10152
10153 remote_debug_printf ("Timed out.");
c906108c 10154 }
74531fed
PA
10155 else
10156 {
10157 /* We've found the start of a packet or notification.
10158 Now collect the data. */
8d64371b 10159 val = read_frame (buf);
74531fed
PA
10160 if (val >= 0)
10161 break;
10162 }
10163
c33e31fd 10164 remote_serial_write ("-", 1);
c906108c 10165 }
c906108c 10166
74531fed
PA
10167 if (tries > MAX_TRIES)
10168 {
10169 /* We have tried hard enough, and just can't receive the
10170 packet/notification. Give up. */
6cb06a8c 10171 gdb_printf (_("Ignoring packet error, continuing...\n"));
c906108c 10172
74531fed
PA
10173 /* Skip the ack char if we're in no-ack mode. */
10174 if (!rs->noack_mode)
c33e31fd 10175 remote_serial_write ("+", 1);
74531fed
PA
10176 return -1;
10177 }
c906108c 10178
74531fed
PA
10179 /* If we got an ordinary packet, return that to our caller. */
10180 if (c == '$')
c906108c
SS
10181 {
10182 if (remote_debug)
43e526b9 10183 {
6cc8564b
LM
10184 int max_chars;
10185
10186 if (remote_packet_max_chars < 0)
10187 max_chars = val;
10188 else
10189 max_chars = remote_packet_max_chars;
10190
6f8976bf 10191 std::string str
8d64371b 10192 = escape_buffer (buf->data (),
6cc8564b 10193 std::min (val, max_chars));
6f8976bf 10194
6cc8564b 10195 if (val > max_chars)
2189c312
SM
10196 remote_debug_printf_nofunc
10197 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10198 val - max_chars);
10199 else
10200 remote_debug_printf_nofunc ("Packet received: %s",
10201 str.c_str ());
43e526b9 10202 }
a6f3e723
SL
10203
10204 /* Skip the ack char if we're in no-ack mode. */
10205 if (!rs->noack_mode)
c33e31fd 10206 remote_serial_write ("+", 1);
fee9eda9 10207 if (is_notif != NULL)
8756b726 10208 *is_notif = false;
0876f84a 10209 return val;
c906108c
SS
10210 }
10211
74531fed
PA
10212 /* If we got a notification, handle it, and go back to looking
10213 for a packet. */
10214 else
10215 {
10216 gdb_assert (c == '%');
10217
2189c312
SM
10218 remote_debug_printf_nofunc
10219 (" Notification received: %s",
10220 escape_buffer (buf->data (), val).c_str ());
6e5abd65 10221
fee9eda9 10222 if (is_notif != NULL)
8756b726 10223 *is_notif = true;
c906108c 10224
8d64371b 10225 handle_notification (rs->notif_state, buf->data ());
c906108c 10226
74531fed 10227 /* Notifications require no acknowledgement. */
a6f3e723 10228
ef6a9843 10229 if (is_notif != nullptr)
fee9eda9 10230 return val;
74531fed
PA
10231 }
10232 }
10233}
10234
28561a65 10235/* Kill any new fork children of inferior INF that haven't been
cbb8991c
DB
10236 processed by follow_fork. */
10237
6b8edb51 10238void
28561a65 10239remote_target::kill_new_fork_children (inferior *inf)
cbb8991c 10240{
6b8edb51 10241 remote_state *rs = get_remote_state ();
42938c1a 10242 const notif_client *notif = &notif_client_stop;
cbb8991c 10243
28561a65
SM
10244 /* Kill the fork child threads of any threads in inferior INF that are stopped
10245 at a fork event. */
10246 for (thread_info *thread : inf->non_exited_threads ())
cbb8991c 10247 {
28561a65 10248 const target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c 10249
28561a65
SM
10250 if (ws == nullptr)
10251 continue;
cbb8991c 10252
28561a65
SM
10253 int child_pid = ws->child_ptid ().pid ();
10254 int res = remote_vkill (child_pid);
10255
10256 if (res != 0)
10257 error (_("Can't kill fork child process %d"), child_pid);
cbb8991c
DB
10258 }
10259
10260 /* Check for any pending fork events (not reported or processed yet)
28561a65 10261 in inferior INF and kill those fork child threads as well. */
cbb8991c 10262 remote_notif_get_pending_events (notif);
953edf2b 10263 for (auto &event : rs->stop_reply_queue)
28561a65
SM
10264 {
10265 if (event->ptid.pid () != inf->pid)
10266 continue;
953edf2b 10267
28561a65
SM
10268 if (!is_fork_status (event->ws.kind ()))
10269 continue;
10270
10271 int child_pid = event->ws.child_ptid ().pid ();
10272 int res = remote_vkill (child_pid);
10273
10274 if (res != 0)
10275 error (_("Can't kill fork child process %d"), child_pid);
10276 }
cbb8991c
DB
10277}
10278
c906108c 10279\f
8020350c
DB
10280/* Target hook to kill the current inferior. */
10281
f6ac5f3d
PA
10282void
10283remote_target::kill ()
43ff13b4 10284{
8020350c 10285 int res = -1;
28561a65 10286 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
0fdf84ca 10287
28561a65
SM
10288 gdb_assert (inf != nullptr);
10289
ff52c073 10290 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 10291 {
8020350c
DB
10292 /* If we're stopped while forking and we haven't followed yet,
10293 kill the child task. We need to do this before killing the
10294 parent task because if this is a vfork then the parent will
10295 be sleeping. */
28561a65 10296 kill_new_fork_children (inf);
8020350c 10297
28561a65 10298 res = remote_vkill (inf->pid);
8020350c 10299 if (res == 0)
0fdf84ca 10300 {
bc1e6c81 10301 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
10302 return;
10303 }
8020350c 10304 }
0fdf84ca 10305
8020350c
DB
10306 /* If we are in 'target remote' mode and we are killing the only
10307 inferior, then we will tell gdbserver to exit and unpush the
10308 target. */
ff52c073 10309 if (res == -1 && !m_features.remote_multi_process_p ()
5b6d1e4f 10310 && number_of_live_inferiors (this) == 1)
8020350c
DB
10311 {
10312 remote_kill_k ();
10313
10314 /* We've killed the remote end, we get to mourn it. If we are
10315 not in extended mode, mourning the inferior also unpushes
10316 remote_ops from the target stack, which closes the remote
10317 connection. */
bc1e6c81 10318 target_mourn_inferior (inferior_ptid);
8020350c
DB
10319
10320 return;
0fdf84ca 10321 }
43ff13b4 10322
8020350c 10323 error (_("Can't kill process"));
43ff13b4
JM
10324}
10325
8020350c
DB
10326/* Send a kill request to the target using the 'vKill' packet. */
10327
6b8edb51
PA
10328int
10329remote_target::remote_vkill (int pid)
82f73884 10330{
ff52c073 10331 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
10332 return -1;
10333
6b8edb51
PA
10334 remote_state *rs = get_remote_state ();
10335
82f73884 10336 /* Tell the remote target to detach. */
8d64371b 10337 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
82f73884 10338 putpkt (rs->buf);
aa7b36b8 10339 getpkt (&rs->buf);
82f73884 10340
ff52c073 10341 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
4082afcc
PA
10342 {
10343 case PACKET_OK:
10344 return 0;
10345 case PACKET_ERROR:
10346 return 1;
10347 case PACKET_UNKNOWN:
10348 return -1;
10349 default:
f34652de 10350 internal_error (_("Bad result from packet_ok"));
4082afcc 10351 }
82f73884
PA
10352}
10353
8020350c
DB
10354/* Send a kill request to the target using the 'k' packet. */
10355
6b8edb51
PA
10356void
10357remote_target::remote_kill_k ()
82f73884 10358{
8020350c
DB
10359 /* Catch errors so the user can quit from gdb even when we
10360 aren't on speaking terms with the remote system. */
a70b8144 10361 try
82f73884 10362 {
82f73884 10363 putpkt ("k");
82f73884 10364 }
230d2906 10365 catch (const gdb_exception_error &ex)
8020350c
DB
10366 {
10367 if (ex.error == TARGET_CLOSE_ERROR)
10368 {
10369 /* If we got an (EOF) error that caused the target
10370 to go away, then we're done, that's what we wanted.
10371 "k" is susceptible to cause a premature EOF, given
10372 that the remote server isn't actually required to
10373 reply to "k", and it can happen that it doesn't
10374 even get to reply ACK to the "k". */
10375 return;
10376 }
82f73884 10377
8020350c
DB
10378 /* Otherwise, something went wrong. We didn't actually kill
10379 the target. Just propagate the exception, and let the
10380 user or higher layers decide what to do. */
eedc3f4f 10381 throw;
8020350c 10382 }
82f73884
PA
10383}
10384
f6ac5f3d
PA
10385void
10386remote_target::mourn_inferior ()
c906108c 10387{
8020350c 10388 struct remote_state *rs = get_remote_state ();
ce5ce7ed 10389
9607784a
PA
10390 /* We're no longer interested in notification events of an inferior
10391 that exited or was killed/detached. */
10392 discard_pending_stop_replies (current_inferior ());
10393
8020350c 10394 /* In 'target remote' mode with one inferior, we close the connection. */
5b6d1e4f 10395 if (!rs->extended && number_of_live_inferiors (this) <= 1)
8020350c 10396 {
5b6d1e4f 10397 remote_unpush_target (this);
8020350c
DB
10398 return;
10399 }
c906108c 10400
e24a49d8
PA
10401 /* In case we got here due to an error, but we're going to stay
10402 connected. */
10403 rs->waiting_for_stop_reply = 0;
10404
dc1981d7
PA
10405 /* If the current general thread belonged to the process we just
10406 detached from or has exited, the remote side current general
10407 thread becomes undefined. Considering a case like this:
10408
10409 - We just got here due to a detach.
10410 - The process that we're detaching from happens to immediately
10411 report a global breakpoint being hit in non-stop mode, in the
10412 same thread we had selected before.
10413 - GDB attaches to this process again.
10414 - This event happens to be the next event we handle.
10415
10416 GDB would consider that the current general thread didn't need to
10417 be set on the stub side (with Hg), since for all it knew,
10418 GENERAL_THREAD hadn't changed.
10419
10420 Notice that although in all-stop mode, the remote server always
10421 sets the current thread to the thread reporting the stop event,
10422 that doesn't happen in non-stop mode; in non-stop, the stub *must
10423 not* change the current thread when reporting a breakpoint hit,
10424 due to the decoupling of event reporting and event handling.
10425
10426 To keep things simple, we always invalidate our notion of the
10427 current thread. */
47f8a51d 10428 record_currthread (rs, minus_one_ptid);
dc1981d7 10429
8020350c 10430 /* Call common code to mark the inferior as not running. */
48aa3c27 10431 generic_mourn_inferior ();
2d717e4f 10432}
c906108c 10433
57810aa7 10434bool
f6ac5f3d 10435extended_remote_target::supports_disable_randomization ()
03583c20 10436{
ff52c073
CS
10437 return (m_features.packet_support (PACKET_QDisableRandomization)
10438 == PACKET_ENABLE);
03583c20
UW
10439}
10440
6b8edb51
PA
10441void
10442remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
10443{
10444 struct remote_state *rs = get_remote_state ();
10445 char *reply;
10446
8d64371b
TT
10447 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10448 "QDisableRandomization:%x", val);
03583c20 10449 putpkt (rs->buf);
b6bb3468 10450 reply = remote_get_noisy_reply ();
03583c20
UW
10451 if (*reply == '\0')
10452 error (_("Target does not support QDisableRandomization."));
10453 if (strcmp (reply, "OK") != 0)
10454 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10455}
10456
6b8edb51
PA
10457int
10458remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
10459{
10460 struct remote_state *rs = get_remote_state ();
2d717e4f 10461 int len;
94585166 10462 const char *remote_exec_file = get_remote_exec_file ();
c906108c 10463
2d717e4f
DJ
10464 /* If the user has disabled vRun support, or we have detected that
10465 support is not available, do not try it. */
ff52c073 10466 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 10467 return -1;
424163ea 10468
8d64371b
TT
10469 strcpy (rs->buf.data (), "vRun;");
10470 len = strlen (rs->buf.data ());
c906108c 10471
2d717e4f
DJ
10472 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10473 error (_("Remote file name too long for run packet"));
8d64371b 10474 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
9f1b45b0 10475 strlen (remote_exec_file));
2d717e4f 10476
7c5ded6a 10477 if (!args.empty ())
2d717e4f 10478 {
2d717e4f 10479 int i;
2d717e4f 10480
773a1edc 10481 gdb_argv argv (args.c_str ());
2d717e4f
DJ
10482 for (i = 0; argv[i] != NULL; i++)
10483 {
10484 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10485 error (_("Argument list too long for run packet"));
10486 rs->buf[len++] = ';';
8d64371b 10487 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
9f1b45b0 10488 strlen (argv[i]));
2d717e4f 10489 }
2d717e4f
DJ
10490 }
10491
10492 rs->buf[len++] = '\0';
10493
10494 putpkt (rs->buf);
aa7b36b8 10495 getpkt (&rs->buf);
2d717e4f 10496
ff52c073 10497 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
2d717e4f 10498 {
4082afcc 10499 case PACKET_OK:
3405876a 10500 /* We have a wait response. All is well. */
2d717e4f 10501 return 0;
4082afcc
PA
10502 case PACKET_UNKNOWN:
10503 return -1;
10504 case PACKET_ERROR:
2d717e4f
DJ
10505 if (remote_exec_file[0] == '\0')
10506 error (_("Running the default executable on the remote target failed; "
10507 "try \"set remote exec-file\"?"));
10508 else
10509 error (_("Running \"%s\" on the remote target failed"),
10510 remote_exec_file);
4082afcc 10511 default:
557b4d76 10512 gdb_assert_not_reached ("bad switch");
2d717e4f 10513 }
c906108c
SS
10514}
10515
0a2dde4a
SDJ
10516/* Helper function to send set/unset environment packets. ACTION is
10517 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10518 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10519 sent. */
10520
6b8edb51
PA
10521void
10522remote_target::send_environment_packet (const char *action,
10523 const char *packet,
10524 const char *value)
0a2dde4a 10525{
6b8edb51
PA
10526 remote_state *rs = get_remote_state ();
10527
0a2dde4a
SDJ
10528 /* Convert the environment variable to an hex string, which
10529 is the best format to be transmitted over the wire. */
10530 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10531 strlen (value));
10532
8d64371b 10533 xsnprintf (rs->buf.data (), get_remote_packet_size (),
0a2dde4a
SDJ
10534 "%s:%s", packet, encoded_value.c_str ());
10535
10536 putpkt (rs->buf);
aa7b36b8 10537 getpkt (&rs->buf);
8d64371b 10538 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10539 warning (_("Unable to %s environment variable '%s' on remote."),
10540 action, value);
10541}
10542
10543/* Helper function to handle the QEnvironment* packets. */
10544
6b8edb51
PA
10545void
10546remote_target::extended_remote_environment_support ()
0a2dde4a 10547{
6b8edb51
PA
10548 remote_state *rs = get_remote_state ();
10549
ff52c073 10550 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
0a2dde4a
SDJ
10551 {
10552 putpkt ("QEnvironmentReset");
aa7b36b8 10553 getpkt (&rs->buf);
8d64371b 10554 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10555 warning (_("Unable to reset environment on remote."));
10556 }
10557
10558 gdb_environ *e = &current_inferior ()->environment;
10559
ff52c073
CS
10560 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10561 != PACKET_DISABLE)
10562 {
10563 for (const std::string &el : e->user_set_env ())
10564 send_environment_packet ("set", "QEnvironmentHexEncoded",
10565 el.c_str ());
10566 }
10567
0a2dde4a 10568
ff52c073 10569 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
0a2dde4a 10570 for (const std::string &el : e->user_unset_env ())
6b8edb51 10571 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10572}
10573
bc3b087d
SDJ
10574/* Helper function to set the current working directory for the
10575 inferior in the remote target. */
10576
6b8edb51
PA
10577void
10578remote_target::extended_remote_set_inferior_cwd ()
bc3b087d 10579{
ff52c073 10580 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
bc3b087d 10581 {
11bd012e 10582 const std::string &inferior_cwd = current_inferior ()->cwd ();
6b8edb51 10583 remote_state *rs = get_remote_state ();
bc3b087d 10584
11bd012e 10585 if (!inferior_cwd.empty ())
bc3b087d 10586 {
11bd012e
SM
10587 std::string hexpath
10588 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10589 inferior_cwd.size ());
bc3b087d 10590
8d64371b 10591 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10592 "QSetWorkingDir:%s", hexpath.c_str ());
10593 }
10594 else
10595 {
10596 /* An empty inferior_cwd means that the user wants us to
10597 reset the remote server's inferior's cwd. */
8d64371b 10598 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10599 "QSetWorkingDir:");
10600 }
10601
10602 putpkt (rs->buf);
aa7b36b8 10603 getpkt (&rs->buf);
ff52c073 10604 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
bc3b087d
SDJ
10605 error (_("\
10606Remote replied unexpectedly while setting the inferior's working\n\
10607directory: %s"),
8d64371b 10608 rs->buf.data ());
bc3b087d
SDJ
10609
10610 }
10611}
10612
2d717e4f
DJ
10613/* In the extended protocol we want to be able to do things like
10614 "run" and have them basically work as expected. So we need
10615 a special create_inferior function. We support changing the
10616 executable file and the command line arguments, but not the
10617 environment. */
10618
f6ac5f3d
PA
10619void
10620extended_remote_target::create_inferior (const char *exec_file,
10621 const std::string &args,
10622 char **env, int from_tty)
43ff13b4 10623{
3405876a
PA
10624 int run_worked;
10625 char *stop_reply;
10626 struct remote_state *rs = get_remote_state ();
94585166 10627 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10628
43ff13b4 10629 /* If running asynchronously, register the target file descriptor
23860348 10630 with the event loop. */
75c99385 10631 if (target_can_async_p ())
4a570176 10632 target_async (true);
43ff13b4 10633
03583c20 10634 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10635 if (supports_disable_randomization ())
03583c20
UW
10636 extended_remote_disable_randomization (disable_randomization);
10637
aefd8b33
SDJ
10638 /* If startup-with-shell is on, we inform gdbserver to start the
10639 remote inferior using a shell. */
ff52c073 10640 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
aefd8b33 10641 {
8d64371b 10642 xsnprintf (rs->buf.data (), get_remote_packet_size (),
aefd8b33
SDJ
10643 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10644 putpkt (rs->buf);
aa7b36b8 10645 getpkt (&rs->buf);
8d64371b 10646 if (strcmp (rs->buf.data (), "OK") != 0)
aefd8b33
SDJ
10647 error (_("\
10648Remote replied unexpectedly while setting startup-with-shell: %s"),
8d64371b 10649 rs->buf.data ());
aefd8b33
SDJ
10650 }
10651
6b8edb51 10652 extended_remote_environment_support ();
0a2dde4a 10653
6b8edb51 10654 extended_remote_set_inferior_cwd ();
bc3b087d 10655
43ff13b4 10656 /* Now restart the remote server. */
3405876a
PA
10657 run_worked = extended_remote_run (args) != -1;
10658 if (!run_worked)
2d717e4f
DJ
10659 {
10660 /* vRun was not supported. Fail if we need it to do what the
10661 user requested. */
10662 if (remote_exec_file[0])
10663 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10664 if (!args.empty ())
65e65158 10665 error (_("Remote target does not support \"set args\" or run ARGS"));
43ff13b4 10666
2d717e4f
DJ
10667 /* Fall back to "R". */
10668 extended_remote_restart ();
10669 }
424163ea 10670
3405876a 10671 /* vRun's success return is a stop reply. */
8d64371b 10672 stop_reply = run_worked ? rs->buf.data () : NULL;
3405876a 10673 add_current_inferior_and_thread (stop_reply);
c0a2216e 10674
2d717e4f
DJ
10675 /* Get updated offsets, if the stub uses qOffsets. */
10676 get_offsets ();
2d717e4f 10677}
c906108c 10678\f
c5aa993b 10679
b775012e
LM
10680/* Given a location's target info BP_TGT and the packet buffer BUF, output
10681 the list of conditions (in agent expression bytecode format), if any, the
10682 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10683 started from BUF and ended at BUF_END. */
b775012e
LM
10684
10685static int
10686remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10687 struct bp_target_info *bp_tgt, char *buf,
10688 char *buf_end)
b775012e 10689{
3cde5c42 10690 if (bp_tgt->conditions.empty ())
b775012e
LM
10691 return 0;
10692
10693 buf += strlen (buf);
bba74b36 10694 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10695 buf++;
10696
83621223 10697 /* Send conditions to the target. */
d538e36d 10698 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10699 {
6f96f485 10700 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
b775012e 10701 buf += strlen (buf);
6f96f485 10702 for (int i = 0; i < aexpr->buf.size (); ++i)
b775012e
LM
10703 buf = pack_hex_byte (buf, aexpr->buf[i]);
10704 *buf = '\0';
10705 }
b775012e
LM
10706 return 0;
10707}
10708
d3ce09f5
SS
10709static void
10710remote_add_target_side_commands (struct gdbarch *gdbarch,
10711 struct bp_target_info *bp_tgt, char *buf)
10712{
3cde5c42 10713 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10714 return;
10715
10716 buf += strlen (buf);
10717
10718 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10719 buf += strlen (buf);
10720
10721 /* Concatenate all the agent expressions that are commands into the
10722 cmds parameter. */
df97be55 10723 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5 10724 {
6f96f485 10725 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
d3ce09f5 10726 buf += strlen (buf);
6f96f485 10727 for (int i = 0; i < aexpr->buf.size (); ++i)
d3ce09f5
SS
10728 buf = pack_hex_byte (buf, aexpr->buf[i]);
10729 *buf = '\0';
10730 }
d3ce09f5
SS
10731}
10732
8181d85f
DJ
10733/* Insert a breakpoint. On targets that have software breakpoint
10734 support, we ask the remote target to do the work; on targets
10735 which don't, we insert a traditional memory breakpoint. */
c906108c 10736
f6ac5f3d
PA
10737int
10738remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10739 struct bp_target_info *bp_tgt)
c906108c 10740{
d471ea57
AC
10741 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10742 If it succeeds, then set the support to PACKET_ENABLE. If it
10743 fails, and the user has explicitly requested the Z support then
23860348 10744 report an error, otherwise, mark it disabled and go on. */
802188a7 10745
ff52c073 10746 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10747 {
0d5ed153 10748 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10749 struct remote_state *rs;
bba74b36 10750 char *p, *endbuf;
4fff2411 10751
28439a30
PA
10752 /* Make sure the remote is pointing at the right process, if
10753 necessary. */
99d9c3b9 10754 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
28439a30
PA
10755 set_general_process ();
10756
4fff2411 10757 rs = get_remote_state ();
8d64371b
TT
10758 p = rs->buf.data ();
10759 endbuf = p + get_remote_packet_size ();
802188a7 10760
96baa820
JM
10761 *(p++) = 'Z';
10762 *(p++) = '0';
10763 *(p++) = ',';
7c0f6dcc 10764 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10765 p += hexnumstr (p, addr);
579c6ad9 10766 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10767
f6ac5f3d 10768 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10769 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10770
f6ac5f3d 10771 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10772 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10773
6d820c5c 10774 putpkt (rs->buf);
aa7b36b8 10775 getpkt (&rs->buf);
96baa820 10776
ff52c073 10777 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
96baa820 10778 {
d471ea57
AC
10779 case PACKET_ERROR:
10780 return -1;
10781 case PACKET_OK:
10782 return 0;
10783 case PACKET_UNKNOWN:
10784 break;
96baa820
JM
10785 }
10786 }
c906108c 10787
0000e5cc
PA
10788 /* If this breakpoint has target-side commands but this stub doesn't
10789 support Z0 packets, throw error. */
3cde5c42 10790 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10791 throw_error (NOT_SUPPORTED_ERROR, _("\
10792Target doesn't support breakpoints that have target side commands."));
10793
f6ac5f3d 10794 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10795}
10796
f6ac5f3d
PA
10797int
10798remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10799 struct bp_target_info *bp_tgt,
10800 enum remove_bp_reason reason)
c906108c 10801{
8181d85f 10802 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10803 struct remote_state *rs = get_remote_state ();
96baa820 10804
ff52c073 10805 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10806 {
8d64371b
TT
10807 char *p = rs->buf.data ();
10808 char *endbuf = p + get_remote_packet_size ();
802188a7 10809
28439a30
PA
10810 /* Make sure the remote is pointing at the right process, if
10811 necessary. */
99d9c3b9 10812 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
28439a30
PA
10813 set_general_process ();
10814
96baa820
JM
10815 *(p++) = 'z';
10816 *(p++) = '0';
10817 *(p++) = ',';
10818
8181d85f
DJ
10819 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10820 p += hexnumstr (p, addr);
579c6ad9 10821 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10822
6d820c5c 10823 putpkt (rs->buf);
aa7b36b8 10824 getpkt (&rs->buf);
96baa820 10825
6d820c5c 10826 return (rs->buf[0] == 'E');
96baa820
JM
10827 }
10828
f6ac5f3d 10829 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10830}
10831
f486487f 10832static enum Z_packet_type
d471ea57
AC
10833watchpoint_to_Z_packet (int type)
10834{
10835 switch (type)
10836 {
10837 case hw_write:
bb858e6a 10838 return Z_PACKET_WRITE_WP;
d471ea57
AC
10839 break;
10840 case hw_read:
bb858e6a 10841 return Z_PACKET_READ_WP;
d471ea57
AC
10842 break;
10843 case hw_access:
bb858e6a 10844 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10845 break;
10846 default:
f34652de 10847 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10848 }
10849}
10850
f6ac5f3d
PA
10851int
10852remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10853 enum target_hw_bp_type type, struct expression *cond)
96baa820 10854{
d01949b6 10855 struct remote_state *rs = get_remote_state ();
8d64371b 10856 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10857 char *p;
d471ea57 10858 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10859
24a601dd
TV
10860 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10861 + to_underlying (packet))) == PACKET_DISABLE)
85d721b8 10862 return 1;
802188a7 10863
28439a30
PA
10864 /* Make sure the remote is pointing at the right process, if
10865 necessary. */
99d9c3b9 10866 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
28439a30
PA
10867 set_general_process ();
10868
8d64371b
TT
10869 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10870 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10871 addr = remote_address_masked (addr);
10872 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10873 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10874
6d820c5c 10875 putpkt (rs->buf);
aa7b36b8 10876 getpkt (&rs->buf);
96baa820 10877
24a601dd
TV
10878 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10879 + to_underlying (packet))))
d471ea57
AC
10880 {
10881 case PACKET_ERROR:
d471ea57 10882 return -1;
85d721b8
PA
10883 case PACKET_UNKNOWN:
10884 return 1;
d471ea57
AC
10885 case PACKET_OK:
10886 return 0;
10887 }
f34652de 10888 internal_error (_("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10889}
10890
57810aa7 10891bool
f6ac5f3d
PA
10892remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10893 CORE_ADDR start, int length)
283002cf
MR
10894{
10895 CORE_ADDR diff = remote_address_masked (addr - start);
10896
10897 return diff < length;
10898}
10899
d471ea57 10900
f6ac5f3d
PA
10901int
10902remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10903 enum target_hw_bp_type type, struct expression *cond)
96baa820 10904{
d01949b6 10905 struct remote_state *rs = get_remote_state ();
8d64371b 10906 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10907 char *p;
d471ea57
AC
10908 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10909
24a601dd
TV
10910 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10911 + to_underlying (packet))) == PACKET_DISABLE)
5cffb350 10912 return -1;
802188a7 10913
28439a30
PA
10914 /* Make sure the remote is pointing at the right process, if
10915 necessary. */
99d9c3b9 10916 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
28439a30
PA
10917 set_general_process ();
10918
8d64371b
TT
10919 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10920 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10921 addr = remote_address_masked (addr);
10922 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10923 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c 10924 putpkt (rs->buf);
aa7b36b8 10925 getpkt (&rs->buf);
96baa820 10926
24a601dd
TV
10927 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10928 + to_underlying (packet))))
d471ea57
AC
10929 {
10930 case PACKET_ERROR:
10931 case PACKET_UNKNOWN:
10932 return -1;
10933 case PACKET_OK:
10934 return 0;
10935 }
f34652de 10936 internal_error (_("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10937}
10938
3c3bea1c 10939
60fcc1c3
TT
10940static int remote_hw_watchpoint_limit = -1;
10941static int remote_hw_watchpoint_length_limit = -1;
10942static int remote_hw_breakpoint_limit = -1;
d471ea57 10943
f6ac5f3d
PA
10944int
10945remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10946{
10947 if (remote_hw_watchpoint_length_limit == 0)
10948 return 0;
10949 else if (remote_hw_watchpoint_length_limit < 0)
10950 return 1;
10951 else if (len <= remote_hw_watchpoint_length_limit)
10952 return 1;
10953 else
10954 return 0;
10955}
10956
f6ac5f3d
PA
10957int
10958remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10959{
3c3bea1c
GS
10960 if (type == bp_hardware_breakpoint)
10961 {
10962 if (remote_hw_breakpoint_limit == 0)
10963 return 0;
501eef12
AC
10964 else if (remote_hw_breakpoint_limit < 0)
10965 return 1;
3c3bea1c
GS
10966 else if (cnt <= remote_hw_breakpoint_limit)
10967 return 1;
10968 }
10969 else
10970 {
10971 if (remote_hw_watchpoint_limit == 0)
10972 return 0;
501eef12
AC
10973 else if (remote_hw_watchpoint_limit < 0)
10974 return 1;
3c3bea1c
GS
10975 else if (ot)
10976 return -1;
10977 else if (cnt <= remote_hw_watchpoint_limit)
10978 return 1;
10979 }
10980 return -1;
10981}
10982
f7e6eed5
PA
10983/* The to_stopped_by_sw_breakpoint method of target remote. */
10984
57810aa7 10985bool
f6ac5f3d 10986remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10987{
799a2abe 10988 struct thread_info *thread = inferior_thread ();
f7e6eed5 10989
799a2abe 10990 return (thread->priv != NULL
7aabaf9d
SM
10991 && (get_remote_thread_info (thread)->stop_reason
10992 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10993}
10994
10995/* The to_supports_stopped_by_sw_breakpoint method of target
10996 remote. */
10997
57810aa7 10998bool
f6ac5f3d 10999remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 11000{
ff52c073 11001 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
f7e6eed5
PA
11002}
11003
11004/* The to_stopped_by_hw_breakpoint method of target remote. */
11005
57810aa7 11006bool
f6ac5f3d 11007remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 11008{
799a2abe 11009 struct thread_info *thread = inferior_thread ();
f7e6eed5 11010
799a2abe 11011 return (thread->priv != NULL
7aabaf9d
SM
11012 && (get_remote_thread_info (thread)->stop_reason
11013 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
11014}
11015
11016/* The to_supports_stopped_by_hw_breakpoint method of target
11017 remote. */
11018
57810aa7 11019bool
f6ac5f3d 11020remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 11021{
ff52c073 11022 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
f7e6eed5
PA
11023}
11024
57810aa7 11025bool
f6ac5f3d 11026remote_target::stopped_by_watchpoint ()
3c3bea1c 11027{
799a2abe 11028 struct thread_info *thread = inferior_thread ();
ee154bee 11029
799a2abe 11030 return (thread->priv != NULL
7aabaf9d
SM
11031 && (get_remote_thread_info (thread)->stop_reason
11032 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
11033}
11034
57810aa7 11035bool
f6ac5f3d 11036remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 11037{
799a2abe 11038 struct thread_info *thread = inferior_thread ();
a744cf53 11039
799a2abe 11040 if (thread->priv != NULL
7aabaf9d
SM
11041 && (get_remote_thread_info (thread)->stop_reason
11042 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 11043 {
7aabaf9d 11044 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 11045 return true;
4aa7a7f5
JJ
11046 }
11047
57810aa7 11048 return false;
3c3bea1c
GS
11049}
11050
11051
f6ac5f3d
PA
11052int
11053remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11054 struct bp_target_info *bp_tgt)
3c3bea1c 11055{
0d5ed153 11056 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 11057 struct remote_state *rs;
bba74b36 11058 char *p, *endbuf;
dd61ec5c 11059 char *message;
3c3bea1c 11060
ff52c073 11061 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 11062 return -1;
2bc416ba 11063
28439a30
PA
11064 /* Make sure the remote is pointing at the right process, if
11065 necessary. */
99d9c3b9 11066 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
28439a30
PA
11067 set_general_process ();
11068
4fff2411 11069 rs = get_remote_state ();
8d64371b
TT
11070 p = rs->buf.data ();
11071 endbuf = p + get_remote_packet_size ();
4fff2411 11072
96baa820
JM
11073 *(p++) = 'Z';
11074 *(p++) = '1';
11075 *(p++) = ',';
802188a7 11076
0d5ed153 11077 addr = remote_address_masked (addr);
96baa820 11078 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 11079 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 11080
f6ac5f3d 11081 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 11082 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 11083
f6ac5f3d 11084 if (can_run_breakpoint_commands ())
d3ce09f5
SS
11085 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11086
6d820c5c 11087 putpkt (rs->buf);
aa7b36b8 11088 getpkt (&rs->buf);
96baa820 11089
ff52c073 11090 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
d471ea57
AC
11091 {
11092 case PACKET_ERROR:
dd61ec5c 11093 if (rs->buf[1] == '.')
dda83cd7
SM
11094 {
11095 message = strchr (&rs->buf[2], '.');
11096 if (message)
11097 error (_("Remote failure reply: %s"), message + 1);
11098 }
dd61ec5c 11099 return -1;
d471ea57
AC
11100 case PACKET_UNKNOWN:
11101 return -1;
11102 case PACKET_OK:
11103 return 0;
11104 }
f34652de 11105 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
11106}
11107
d471ea57 11108
f6ac5f3d
PA
11109int
11110remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11111 struct bp_target_info *bp_tgt)
96baa820 11112{
8181d85f 11113 CORE_ADDR addr;
d01949b6 11114 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11115 char *p = rs->buf.data ();
11116 char *endbuf = p + get_remote_packet_size ();
c8189ed1 11117
ff52c073 11118 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 11119 return -1;
802188a7 11120
28439a30
PA
11121 /* Make sure the remote is pointing at the right process, if
11122 necessary. */
99d9c3b9 11123 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
28439a30
PA
11124 set_general_process ();
11125
96baa820
JM
11126 *(p++) = 'z';
11127 *(p++) = '1';
11128 *(p++) = ',';
802188a7 11129
8181d85f 11130 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 11131 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 11132 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 11133
6d820c5c 11134 putpkt (rs->buf);
aa7b36b8 11135 getpkt (&rs->buf);
802188a7 11136
ff52c073 11137 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
d471ea57
AC
11138 {
11139 case PACKET_ERROR:
11140 case PACKET_UNKNOWN:
11141 return -1;
11142 case PACKET_OK:
11143 return 0;
11144 }
f34652de 11145 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
96baa820 11146}
96baa820 11147
4a5e7a5b
PA
11148/* Verify memory using the "qCRC:" request. */
11149
f6ac5f3d
PA
11150int
11151remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
11152{
11153 struct remote_state *rs = get_remote_state ();
11154 unsigned long host_crc, target_crc;
11155 char *tmp;
11156
936d2992
PA
11157 /* It doesn't make sense to use qCRC if the remote target is
11158 connected but not running. */
55f6301a 11159 if (target_has_execution ()
ff52c073 11160 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
936d2992
PA
11161 {
11162 enum packet_result result;
28439a30 11163
936d2992
PA
11164 /* Make sure the remote is pointing at the right process. */
11165 set_general_process ();
4a5e7a5b 11166
936d2992 11167 /* FIXME: assumes lma can fit into long. */
8d64371b 11168 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
936d2992
PA
11169 (long) lma, (long) size);
11170 putpkt (rs->buf);
4a5e7a5b 11171
936d2992
PA
11172 /* Be clever; compute the host_crc before waiting for target
11173 reply. */
11174 host_crc = xcrc32 (data, size, 0xffffffff);
11175
aa7b36b8 11176 getpkt (&rs->buf);
4a5e7a5b 11177
ff52c073 11178 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
936d2992
PA
11179 if (result == PACKET_ERROR)
11180 return -1;
11181 else if (result == PACKET_OK)
11182 {
11183 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11184 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 11185
936d2992
PA
11186 return (host_crc == target_crc);
11187 }
11188 }
4a5e7a5b 11189
f6ac5f3d 11190 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
11191}
11192
c906108c
SS
11193/* compare-sections command
11194
11195 With no arguments, compares each loadable section in the exec bfd
11196 with the same memory range on the target, and reports mismatches.
4a5e7a5b 11197 Useful for verifying the image on the target against the exec file. */
e514a9d6 11198
c906108c 11199static void
ac88e2de 11200compare_sections_command (const char *args, int from_tty)
c906108c
SS
11201{
11202 asection *s;
ce359b09 11203 const char *sectname;
c906108c
SS
11204 bfd_size_type size;
11205 bfd_vma lma;
11206 int matched = 0;
11207 int mismatched = 0;
4a5e7a5b 11208 int res;
95cf3b38 11209 int read_only = 0;
c906108c 11210
7e10abd1 11211 if (!current_program_space->exec_bfd ())
8a3fe4f8 11212 error (_("command cannot be used without an exec file"));
c906108c 11213
95cf3b38
DT
11214 if (args != NULL && strcmp (args, "-r") == 0)
11215 {
11216 read_only = 1;
11217 args = NULL;
11218 }
11219
7e10abd1 11220 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
c906108c
SS
11221 {
11222 if (!(s->flags & SEC_LOAD))
0df8b418 11223 continue; /* Skip non-loadable section. */
c906108c 11224
95cf3b38
DT
11225 if (read_only && (s->flags & SEC_READONLY) == 0)
11226 continue; /* Skip writeable sections */
11227
fd361982 11228 size = bfd_section_size (s);
c906108c 11229 if (size == 0)
0df8b418 11230 continue; /* Skip zero-length section. */
c906108c 11231
fd361982 11232 sectname = bfd_section_name (s);
c906108c 11233 if (args && strcmp (args, sectname) != 0)
0df8b418 11234 continue; /* Not the section selected by user. */
c906108c 11235
0df8b418 11236 matched = 1; /* Do this section. */
c906108c 11237 lma = s->lma;
c906108c 11238
b80406ac 11239 gdb::byte_vector sectdata (size);
7e10abd1
TT
11240 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11241 sectdata.data (), 0, size);
c906108c 11242
b80406ac 11243 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
11244
11245 if (res == -1)
5af949e3 11246 error (_("target memory fault, section %s, range %s -- %s"), sectname,
99d9c3b9
SM
11247 paddress (current_inferior ()->arch (), lma),
11248 paddress (current_inferior ()->arch (), lma + size));
c906108c 11249
6cb06a8c 11250 gdb_printf ("Section %s, range %s -- %s: ", sectname,
99d9c3b9
SM
11251 paddress (current_inferior ()->arch (), lma),
11252 paddress (current_inferior ()->arch (), lma + size));
4a5e7a5b 11253 if (res)
6cb06a8c 11254 gdb_printf ("matched.\n");
c906108c 11255 else
c5aa993b 11256 {
6cb06a8c 11257 gdb_printf ("MIS-MATCHED!\n");
c5aa993b
JM
11258 mismatched++;
11259 }
c906108c
SS
11260 }
11261 if (mismatched > 0)
131287d9
AB
11262 warning (_("One or more sections of the target image does "
11263 "not match the loaded file"));
c906108c 11264 if (args && !matched)
6cb06a8c 11265 gdb_printf (_("No loaded section named '%s'.\n"), args);
c906108c
SS
11266}
11267
0e7f50da
UW
11268/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11269 into remote target. The number of bytes written to the remote
11270 target is returned, or -1 for error. */
11271
6b8edb51
PA
11272target_xfer_status
11273remote_target::remote_write_qxfer (const char *object_name,
11274 const char *annex, const gdb_byte *writebuf,
11275 ULONGEST offset, LONGEST len,
11276 ULONGEST *xfered_len,
ff52c073 11277 const unsigned int which_packet)
0e7f50da
UW
11278{
11279 int i, buf_len;
11280 ULONGEST n;
0e7f50da 11281 struct remote_state *rs = get_remote_state ();
7a78108a 11282 int max_size = get_memory_write_packet_size ();
0e7f50da 11283
ff52c073 11284 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
2ed4b548 11285 return TARGET_XFER_E_IO;
0e7f50da
UW
11286
11287 /* Insert header. */
7a78108a 11288 i = snprintf (rs->buf.data (), max_size,
0e7f50da
UW
11289 "qXfer:%s:write:%s:%s:",
11290 object_name, annex ? annex : "",
11291 phex_nz (offset, sizeof offset));
11292 max_size -= (i + 1);
11293
11294 /* Escape as much data as fits into rs->buf. */
7a78108a 11295 buf_len = remote_escape_output
8d64371b 11296 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
0e7f50da 11297
8d64371b 11298 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
aa7b36b8 11299 || getpkt (&rs->buf) < 0
ff52c073 11300 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
2ed4b548 11301 return TARGET_XFER_E_IO;
0e7f50da 11302
8d64371b 11303 unpack_varlen_hex (rs->buf.data (), &n);
9b409511
YQ
11304
11305 *xfered_len = n;
92ffd475 11306 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
11307}
11308
0876f84a
DJ
11309/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11310 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11311 number of bytes read is returned, or 0 for EOF, or -1 for error.
11312 The number of bytes read may be less than LEN without indicating an
11313 EOF. PACKET is checked and updated to indicate whether the remote
11314 target supports this object. */
11315
6b8edb51
PA
11316target_xfer_status
11317remote_target::remote_read_qxfer (const char *object_name,
11318 const char *annex,
11319 gdb_byte *readbuf, ULONGEST offset,
11320 LONGEST len,
11321 ULONGEST *xfered_len,
ff52c073 11322 const unsigned int which_packet)
0876f84a 11323{
0876f84a 11324 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
11325 LONGEST i, n, packet_len;
11326
ff52c073 11327 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
2ed4b548 11328 return TARGET_XFER_E_IO;
0876f84a
DJ
11329
11330 /* Check whether we've cached an end-of-object packet that matches
11331 this request. */
8e88304f 11332 if (rs->finished_object)
0876f84a 11333 {
8e88304f
TT
11334 if (strcmp (object_name, rs->finished_object) == 0
11335 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11336 && offset == rs->finished_offset)
9b409511
YQ
11337 return TARGET_XFER_EOF;
11338
0876f84a
DJ
11339
11340 /* Otherwise, we're now reading something different. Discard
11341 the cache. */
8e88304f
TT
11342 xfree (rs->finished_object);
11343 xfree (rs->finished_annex);
11344 rs->finished_object = NULL;
11345 rs->finished_annex = NULL;
0876f84a
DJ
11346 }
11347
11348 /* Request only enough to fit in a single packet. The actual data
11349 may not, since we don't know how much of it will need to be escaped;
11350 the target is free to respond with slightly less data. We subtract
11351 five to account for the response type and the protocol frame. */
768adc05 11352 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
8d64371b
TT
11353 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11354 "qXfer:%s:read:%s:%s,%s",
0876f84a
DJ
11355 object_name, annex ? annex : "",
11356 phex_nz (offset, sizeof offset),
11357 phex_nz (n, sizeof n));
11358 i = putpkt (rs->buf);
11359 if (i < 0)
2ed4b548 11360 return TARGET_XFER_E_IO;
0876f84a
DJ
11361
11362 rs->buf[0] = '\0';
aa7b36b8 11363 packet_len = getpkt (&rs->buf);
ff52c073
CS
11364 if (packet_len < 0
11365 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
2ed4b548 11366 return TARGET_XFER_E_IO;
0876f84a
DJ
11367
11368 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8d64371b 11369 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
0876f84a
DJ
11370
11371 /* 'm' means there is (or at least might be) more data after this
11372 batch. That does not make sense unless there's at least one byte
11373 of data in this reply. */
11374 if (rs->buf[0] == 'm' && packet_len == 1)
11375 error (_("Remote qXfer reply contained no data."));
11376
11377 /* Got some data. */
8d64371b 11378 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
bc20a4af 11379 packet_len - 1, readbuf, n);
0876f84a
DJ
11380
11381 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
11382 or possibly empty. If we have the final block of a non-empty
11383 object, record this fact to bypass a subsequent partial read. */
11384 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 11385 {
8e88304f
TT
11386 rs->finished_object = xstrdup (object_name);
11387 rs->finished_annex = xstrdup (annex ? annex : "");
11388 rs->finished_offset = offset + i;
0876f84a
DJ
11389 }
11390
9b409511
YQ
11391 if (i == 0)
11392 return TARGET_XFER_EOF;
11393 else
11394 {
11395 *xfered_len = i;
11396 return TARGET_XFER_OK;
11397 }
0876f84a
DJ
11398}
11399
f6ac5f3d
PA
11400enum target_xfer_status
11401remote_target::xfer_partial (enum target_object object,
11402 const char *annex, gdb_byte *readbuf,
11403 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11404 ULONGEST *xfered_len)
c906108c 11405{
82f73884 11406 struct remote_state *rs;
c906108c 11407 int i;
6d820c5c 11408 char *p2;
1e3ff5ad 11409 char query_type;
99d9c3b9
SM
11410 int unit_size
11411 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
c906108c 11412
e6e4e701 11413 set_remote_traceframe ();
82f73884
PA
11414 set_general_thread (inferior_ptid);
11415
11416 rs = get_remote_state ();
11417
b2182ed2 11418 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
11419 if (object == TARGET_OBJECT_MEMORY)
11420 {
2d717e4f
DJ
11421 /* If the remote target is connected but not running, we should
11422 pass this request down to a lower stratum (e.g. the executable
11423 file). */
55f6301a 11424 if (!target_has_execution ())
9b409511 11425 return TARGET_XFER_EOF;
2d717e4f 11426
21e3b9b9 11427 if (writebuf != NULL)
124e13d9
SM
11428 return remote_write_bytes (offset, writebuf, len, unit_size,
11429 xfered_len);
21e3b9b9 11430 else
6b8edb51 11431 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 11432 xfered_len);
21e3b9b9
DJ
11433 }
11434
4aa995e1
PA
11435 /* Handle extra signal info using qxfer packets. */
11436 if (object == TARGET_OBJECT_SIGNAL_INFO)
11437 {
11438 if (readbuf)
f6ac5f3d 11439 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
ff52c073 11440 xfered_len, PACKET_qXfer_siginfo_read);
4aa995e1 11441 else
ff52c073
CS
11442 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11443 xfered_len, PACKET_qXfer_siginfo_write);
4aa995e1
PA
11444 }
11445
0fb4aa4b
PA
11446 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11447 {
11448 if (readbuf)
f6ac5f3d 11449 return remote_read_qxfer ("statictrace", annex,
9b409511 11450 readbuf, offset, len, xfered_len,
ff52c073 11451 PACKET_qXfer_statictrace_read);
0fb4aa4b 11452 else
2ed4b548 11453 return TARGET_XFER_E_IO;
0fb4aa4b
PA
11454 }
11455
a76d924d
DJ
11456 /* Only handle flash writes. */
11457 if (writebuf != NULL)
11458 {
a76d924d
DJ
11459 switch (object)
11460 {
11461 case TARGET_OBJECT_FLASH:
6b8edb51 11462 return remote_flash_write (offset, len, xfered_len,
9b409511 11463 writebuf);
a76d924d
DJ
11464
11465 default:
2ed4b548 11466 return TARGET_XFER_E_IO;
a76d924d
DJ
11467 }
11468 }
4b8a223f 11469
1e3ff5ad
AC
11470 /* Map pre-existing objects onto letters. DO NOT do this for new
11471 objects!!! Instead specify new query packets. */
11472 switch (object)
c906108c 11473 {
1e3ff5ad
AC
11474 case TARGET_OBJECT_AVR:
11475 query_type = 'R';
11476 break;
802188a7
RM
11477
11478 case TARGET_OBJECT_AUXV:
0876f84a 11479 gdb_assert (annex == NULL);
ff52c073
CS
11480 return remote_read_qxfer
11481 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
802188a7 11482
23181151
DJ
11483 case TARGET_OBJECT_AVAILABLE_FEATURES:
11484 return remote_read_qxfer
f6ac5f3d 11485 ("features", annex, readbuf, offset, len, xfered_len,
ff52c073 11486 PACKET_qXfer_features);
23181151 11487
cfa9d6d9
DJ
11488 case TARGET_OBJECT_LIBRARIES:
11489 return remote_read_qxfer
f6ac5f3d 11490 ("libraries", annex, readbuf, offset, len, xfered_len,
ff52c073 11491 PACKET_qXfer_libraries);
cfa9d6d9 11492
2268b414
JK
11493 case TARGET_OBJECT_LIBRARIES_SVR4:
11494 return remote_read_qxfer
f6ac5f3d 11495 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
ff52c073 11496 PACKET_qXfer_libraries_svr4);
2268b414 11497
fd79ecee
DJ
11498 case TARGET_OBJECT_MEMORY_MAP:
11499 gdb_assert (annex == NULL);
ff52c073
CS
11500 return remote_read_qxfer
11501 ("memory-map", annex, readbuf, offset, len, xfered_len,
11502 PACKET_qXfer_memory_map);
fd79ecee 11503
07e059b5
VP
11504 case TARGET_OBJECT_OSDATA:
11505 /* Should only get here if we're connected. */
5d93a237 11506 gdb_assert (rs->remote_desc);
07e059b5 11507 return remote_read_qxfer
f6ac5f3d 11508 ("osdata", annex, readbuf, offset, len, xfered_len,
ff52c073 11509 PACKET_qXfer_osdata);
07e059b5 11510
dc146f7c
VP
11511 case TARGET_OBJECT_THREADS:
11512 gdb_assert (annex == NULL);
ff52c073
CS
11513 return remote_read_qxfer
11514 ("threads", annex, readbuf, offset, len, xfered_len,
11515 PACKET_qXfer_threads);
dc146f7c 11516
b3b9301e
PA
11517 case TARGET_OBJECT_TRACEFRAME_INFO:
11518 gdb_assert (annex == NULL);
11519 return remote_read_qxfer
f6ac5f3d 11520 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
ff52c073 11521 PACKET_qXfer_traceframe_info);
78d85199
YQ
11522
11523 case TARGET_OBJECT_FDPIC:
ff52c073
CS
11524 return remote_read_qxfer
11525 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
169081d0
TG
11526
11527 case TARGET_OBJECT_OPENVMS_UIB:
ff52c073
CS
11528 return remote_read_qxfer
11529 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
169081d0 11530
9accd112 11531 case TARGET_OBJECT_BTRACE:
ff52c073
CS
11532 return remote_read_qxfer
11533 ("btrace", annex, readbuf, offset, len, xfered_len,
11534 PACKET_qXfer_btrace);
9accd112 11535
f4abbc16 11536 case TARGET_OBJECT_BTRACE_CONF:
ff52c073
CS
11537 return remote_read_qxfer
11538 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11539 PACKET_qXfer_btrace_conf);
f4abbc16 11540
c78fa86a 11541 case TARGET_OBJECT_EXEC_FILE:
ff52c073
CS
11542 return remote_read_qxfer
11543 ("exec-file", annex, readbuf, offset, len, xfered_len,
11544 PACKET_qXfer_exec_file);
c78fa86a 11545
1e3ff5ad 11546 default:
2ed4b548 11547 return TARGET_XFER_E_IO;
c906108c
SS
11548 }
11549
0df8b418 11550 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11551 large enough let the caller deal with it. */
ea9c271d 11552 if (len < get_remote_packet_size ())
2ed4b548 11553 return TARGET_XFER_E_IO;
ea9c271d 11554 len = get_remote_packet_size ();
1e3ff5ad 11555
23860348 11556 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11557 if (!rs->remote_desc)
8a3fe4f8 11558 error (_("remote query is only available after target open"));
c906108c 11559
1e3ff5ad 11560 gdb_assert (annex != NULL);
4b8a223f 11561 gdb_assert (readbuf != NULL);
c906108c 11562
8d64371b 11563 p2 = rs->buf.data ();
c906108c
SS
11564 *p2++ = 'q';
11565 *p2++ = query_type;
11566
23860348
MS
11567 /* We used one buffer char for the remote protocol q command and
11568 another for the query type. As the remote protocol encapsulation
11569 uses 4 chars plus one extra in case we are debugging
11570 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11571 string. */
c906108c 11572 i = 0;
ea9c271d 11573 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11574 {
1e3ff5ad
AC
11575 /* Bad caller may have sent forbidden characters. */
11576 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11577 *p2++ = annex[i];
c906108c
SS
11578 i++;
11579 }
1e3ff5ad
AC
11580 *p2 = '\0';
11581 gdb_assert (annex[i] == '\0');
c906108c 11582
6d820c5c 11583 i = putpkt (rs->buf);
c5aa993b 11584 if (i < 0)
2ed4b548 11585 return TARGET_XFER_E_IO;
c906108c 11586
aa7b36b8 11587 getpkt (&rs->buf);
8d64371b 11588 strcpy ((char *) readbuf, rs->buf.data ());
c906108c 11589
9b409511 11590 *xfered_len = strlen ((char *) readbuf);
92ffd475 11591 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11592}
11593
09c98b44
DB
11594/* Implementation of to_get_memory_xfer_limit. */
11595
f6ac5f3d
PA
11596ULONGEST
11597remote_target::get_memory_xfer_limit ()
09c98b44
DB
11598{
11599 return get_memory_write_packet_size ();
11600}
11601
f6ac5f3d
PA
11602int
11603remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11604 const gdb_byte *pattern, ULONGEST pattern_len,
11605 CORE_ADDR *found_addrp)
08388c79 11606{
99d9c3b9 11607 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
08388c79
DE
11608 struct remote_state *rs = get_remote_state ();
11609 int max_size = get_memory_write_packet_size ();
ff52c073 11610
0df8b418
MS
11611 /* Number of packet bytes used to encode the pattern;
11612 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11613 int escaped_pattern_len;
0df8b418 11614 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11615 int used_pattern_len;
11616 int i;
11617 int found;
11618 ULONGEST found_addr;
11619
5bd5fecd 11620 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
4a72de73
TT
11621 {
11622 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11623 == len);
11624 };
11625
7cc244de 11626 /* Don't go to the target if we don't have to. This is done before
ff52c073
CS
11627 checking packet_support to avoid the possibility that a success for this
11628 edge case means the facility works in general. */
08388c79
DE
11629 if (pattern_len > search_space_len)
11630 return 0;
11631 if (pattern_len == 0)
11632 {
11633 *found_addrp = start_addr;
11634 return 1;
11635 }
11636
11637 /* If we already know the packet isn't supported, fall back to the simple
11638 way of searching memory. */
11639
ff52c073 11640 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
08388c79
DE
11641 {
11642 /* Target doesn't provided special support, fall back and use the
11643 standard support (copy memory and do the search here). */
4a72de73 11644 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11645 pattern, pattern_len, found_addrp);
11646 }
11647
28439a30
PA
11648 /* Make sure the remote is pointing at the right process. */
11649 set_general_process ();
11650
08388c79 11651 /* Insert header. */
7a78108a 11652 i = snprintf (rs->buf.data (), max_size,
08388c79 11653 "qSearch:memory:%s;%s;",
5af949e3 11654 phex_nz (start_addr, addr_size),
08388c79
DE
11655 phex_nz (search_space_len, sizeof (search_space_len)));
11656 max_size -= (i + 1);
11657
11658 /* Escape as much data as fits into rs->buf. */
11659 escaped_pattern_len =
8d64371b
TT
11660 remote_escape_output (pattern, pattern_len, 1,
11661 (gdb_byte *) rs->buf.data () + i,
08388c79
DE
11662 &used_pattern_len, max_size);
11663
11664 /* Bail if the pattern is too large. */
11665 if (used_pattern_len != pattern_len)
9b20d036 11666 error (_("Pattern is too large to transmit to remote target."));
08388c79 11667
8d64371b 11668 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
aa7b36b8 11669 || getpkt (&rs->buf) < 0
ff52c073 11670 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
08388c79
DE
11671 {
11672 /* The request may not have worked because the command is not
11673 supported. If so, fall back to the simple way. */
ff52c073 11674 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
08388c79 11675 {
4a72de73 11676 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11677 pattern, pattern_len, found_addrp);
11678 }
11679 return -1;
11680 }
11681
11682 if (rs->buf[0] == '0')
11683 found = 0;
11684 else if (rs->buf[0] == '1')
11685 {
11686 found = 1;
11687 if (rs->buf[1] != ',')
8d64371b
TT
11688 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11689 unpack_varlen_hex (&rs->buf[2], &found_addr);
08388c79
DE
11690 *found_addrp = found_addr;
11691 }
11692 else
8d64371b 11693 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
08388c79
DE
11694
11695 return found;
11696}
11697
f6ac5f3d
PA
11698void
11699remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11700{
d01949b6 11701 struct remote_state *rs = get_remote_state ();
8d64371b 11702 char *p = rs->buf.data ();
96baa820 11703
5d93a237 11704 if (!rs->remote_desc)
8a3fe4f8 11705 error (_("remote rcmd is only available after target open"));
96baa820 11706
23860348 11707 /* Send a NULL command across as an empty command. */
7be570e7
JM
11708 if (command == NULL)
11709 command = "";
11710
23860348 11711 /* The query prefix. */
8d64371b
TT
11712 strcpy (rs->buf.data (), "qRcmd,");
11713 p = strchr (rs->buf.data (), '\0');
96baa820 11714
8d64371b 11715 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
3e43a32a 11716 > get_remote_packet_size ())
8a3fe4f8 11717 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11718
23860348 11719 /* Encode the actual command. */
a30bf1f1 11720 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11721
6d820c5c 11722 if (putpkt (rs->buf) < 0)
8a3fe4f8 11723 error (_("Communication problem with target."));
96baa820
JM
11724
11725 /* get/display the response */
11726 while (1)
11727 {
2e9f7625
DJ
11728 char *buf;
11729
00bf0b85 11730 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11731 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11732 rs->buf[0] = '\0';
aa7b36b8 11733 if (getpkt (&rs->buf) == -1)
7a78108a 11734 {
dda83cd7
SM
11735 /* Timeout. Continue to (try to) read responses.
11736 This is better than stopping with an error, assuming the stub
11737 is still executing the (long) monitor command.
11738 If needed, the user can interrupt gdb using C-c, obtaining
11739 an effect similar to stop on timeout. */
11740 continue;
11741 }
8d64371b 11742 buf = rs->buf.data ();
96baa820 11743 if (buf[0] == '\0')
8a3fe4f8 11744 error (_("Target does not support this command."));
96baa820
JM
11745 if (buf[0] == 'O' && buf[1] != 'K')
11746 {
23860348 11747 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11748 continue;
11749 }
11750 if (strcmp (buf, "OK") == 0)
11751 break;
7be570e7 11752 if (strlen (buf) == 3 && buf[0] == 'E'
d5ce6f2d 11753 && isxdigit (buf[1]) && isxdigit (buf[2]))
7be570e7 11754 {
8a3fe4f8 11755 error (_("Protocol error with Rcmd"));
7be570e7 11756 }
96baa820
JM
11757 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11758 {
11759 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11760
a11ac3b3 11761 gdb_putc (c, outbuf);
96baa820
JM
11762 }
11763 break;
11764 }
11765}
11766
f6ac5f3d
PA
11767std::vector<mem_region>
11768remote_target::memory_map ()
fd79ecee 11769{
a664f67e 11770 std::vector<mem_region> result;
9018be22 11771 gdb::optional<gdb::char_vector> text
328d42d8
SM
11772 = target_read_stralloc (current_inferior ()->top_target (),
11773 TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11774
11775 if (text)
9018be22 11776 result = parse_memory_map (text->data ());
fd79ecee
DJ
11777
11778 return result;
11779}
11780
e5b176f2
AB
11781/* Set of callbacks used to implement the 'maint packet' command. */
11782
11783struct cli_packet_command_callbacks : public send_remote_packet_callbacks
c906108c 11784{
e5b176f2
AB
11785 /* Called before the packet is sent. BUF is the packet content before
11786 the protocol specific prefix, suffix, and escaping is added. */
c906108c 11787
e5b176f2
AB
11788 void sending (gdb::array_view<const char> &buf) override
11789 {
0426ad51 11790 gdb_puts ("sending: ");
e5b176f2 11791 print_packet (buf);
0426ad51 11792 gdb_puts ("\n");
e5b176f2 11793 }
c906108c 11794
e5b176f2
AB
11795 /* Called with BUF, the reply from the remote target. */
11796
11797 void received (gdb::array_view<const char> &buf) override
11798 {
0426ad51 11799 gdb_puts ("received: \"");
e5b176f2 11800 print_packet (buf);
0426ad51 11801 gdb_puts ("\"\n");
e5b176f2
AB
11802 }
11803
11804private:
11805
11806 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11807 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11808
11809 static void
11810 print_packet (gdb::array_view<const char> &buf)
11811 {
11812 string_file stb;
11813
11814 for (int i = 0; i < buf.size (); ++i)
11815 {
11816 gdb_byte c = buf[i];
11817 if (isprint (c))
a11ac3b3 11818 gdb_putc (c, &stb);
e5b176f2 11819 else
6cb06a8c 11820 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
e5b176f2
AB
11821 }
11822
0426ad51 11823 gdb_puts (stb.string ().c_str ());
e5b176f2
AB
11824 }
11825};
11826
11827/* See remote.h. */
6b8edb51
PA
11828
11829void
e5b176f2
AB
11830send_remote_packet (gdb::array_view<const char> &buf,
11831 send_remote_packet_callbacks *callbacks)
6b8edb51 11832{
e5b176f2
AB
11833 if (buf.size () == 0 || buf.data ()[0] == '\0')
11834 error (_("a remote packet must not be empty"));
c906108c 11835
e5b176f2
AB
11836 remote_target *remote = get_current_remote_target ();
11837 if (remote == nullptr)
11838 error (_("packets can only be sent to a remote target"));
c906108c 11839
e5b176f2 11840 callbacks->sending (buf);
6b8edb51 11841
e5b176f2
AB
11842 remote->putpkt_binary (buf.data (), buf.size ());
11843 remote_state *rs = remote->get_remote_state ();
aa7b36b8 11844 int bytes = remote->getpkt (&rs->buf);
e5b176f2
AB
11845
11846 if (bytes < 0)
11847 error (_("error while fetching packet from remote target"));
11848
11849 gdb::array_view<const char> view (&rs->buf[0], bytes);
11850 callbacks->received (view);
11851}
11852
11853/* Entry point for the 'maint packet' command. */
11854
11855static void
11856cli_packet_command (const char *args, int from_tty)
11857{
11858 cli_packet_command_callbacks cb;
11859 gdb::array_view<const char> view
11860 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11861 send_remote_packet (view, &cb);
c906108c
SS
11862}
11863
11864#if 0
23860348 11865/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11866
a14ed312 11867static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11868
a14ed312 11869static void threadset_test_cmd (char *cmd, int tty);
c906108c 11870
a14ed312 11871static void threadalive_test (char *cmd, int tty);
c906108c 11872
a14ed312 11873static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11874
23860348 11875int get_and_display_threadinfo (threadref *ref);
c906108c 11876
a14ed312 11877static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11878
23860348 11879static int thread_display_step (threadref *ref, void *context);
c906108c 11880
a14ed312 11881static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11882
a14ed312 11883static void init_remote_threadtests (void);
c906108c 11884
23860348 11885#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11886
11887static void
0b39b52e 11888threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11889{
11890 int sample_thread = SAMPLE_THREAD;
11891
6cb06a8c 11892 gdb_printf (_("Remote threadset test\n"));
79d7f229 11893 set_general_thread (sample_thread);
c906108c
SS
11894}
11895
11896
11897static void
0b39b52e 11898threadalive_test (const char *cmd, int tty)
c906108c
SS
11899{
11900 int sample_thread = SAMPLE_THREAD;
e99b03dc 11901 int pid = inferior_ptid.pid ();
fd79271b 11902 ptid_t ptid = ptid_t (pid, sample_thread, 0);
c906108c 11903
79d7f229 11904 if (remote_thread_alive (ptid))
6cb06a8c 11905 gdb_printf ("PASS: Thread alive test\n");
c906108c 11906 else
6cb06a8c 11907 gdb_printf ("FAIL: Thread alive test\n");
c906108c
SS
11908}
11909
23860348 11910void output_threadid (char *title, threadref *ref);
c906108c
SS
11911
11912void
fba45db2 11913output_threadid (char *title, threadref *ref)
c906108c
SS
11914{
11915 char hexid[20];
11916
405feb71 11917 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
c906108c 11918 hexid[16] = 0;
6cb06a8c 11919 gdb_printf ("%s %s\n", title, (&hexid[0]));
c906108c
SS
11920}
11921
11922static void
0b39b52e 11923threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11924{
11925 int startflag = 1;
11926 threadref nextthread;
11927 int done, result_count;
11928 threadref threadlist[3];
11929
6cb06a8c 11930 gdb_printf ("Remote Threadlist test\n");
c906108c
SS
11931 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11932 &result_count, &threadlist[0]))
6cb06a8c 11933 gdb_printf ("FAIL: threadlist test\n");
c906108c
SS
11934 else
11935 {
11936 threadref *scan = threadlist;
11937 threadref *limit = scan + result_count;
11938
11939 while (scan < limit)
11940 output_threadid (" thread ", scan++);
11941 }
11942}
11943
11944void
fba45db2 11945display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11946{
11947 output_threadid ("Threadid: ", &info->threadid);
6cb06a8c
TT
11948 gdb_printf ("Name: %s\n ", info->shortname);
11949 gdb_printf ("State: %s\n", info->display);
11950 gdb_printf ("other: %s\n\n", info->more_display);
c906108c
SS
11951}
11952
11953int
fba45db2 11954get_and_display_threadinfo (threadref *ref)
c906108c
SS
11955{
11956 int result;
11957 int set;
11958 struct gdb_ext_thread_info threadinfo;
11959
11960 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11961 | TAG_MOREDISPLAY | TAG_DISPLAY;
11962 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11963 display_thread_info (&threadinfo);
11964 return result;
11965}
11966
11967static void
0b39b52e 11968threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11969{
11970 int athread = SAMPLE_THREAD;
11971 threadref thread;
11972 int set;
11973
11974 int_to_threadref (&thread, athread);
6cb06a8c 11975 gdb_printf ("Remote Threadinfo test\n");
c906108c 11976 if (!get_and_display_threadinfo (&thread))
6cb06a8c 11977 gdb_printf ("FAIL cannot get thread info\n");
c906108c
SS
11978}
11979
11980static int
fba45db2 11981thread_display_step (threadref *ref, void *context)
c906108c
SS
11982{
11983 /* output_threadid(" threadstep ",ref); *//* simple test */
11984 return get_and_display_threadinfo (ref);
11985}
11986
11987static void
0b39b52e 11988threadlist_update_test_cmd (const char *cmd, int tty)
c906108c 11989{
6cb06a8c 11990 gdb_printf ("Remote Threadlist update test\n");
c906108c
SS
11991 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11992}
11993
11994static void
11995init_remote_threadtests (void)
11996{
3e43a32a
MS
11997 add_com ("tlist", class_obscure, threadlist_test_cmd,
11998 _("Fetch and print the remote list of "
590042fc 11999 "thread identifiers, one pkt only."));
c906108c 12000 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
590042fc 12001 _("Fetch and display info about one thread."));
c906108c 12002 add_com ("tset", class_obscure, threadset_test_cmd,
590042fc 12003 _("Test setting to a different thread."));
c906108c 12004 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
590042fc 12005 _("Iterate through updating all remote thread info."));
c906108c 12006 add_com ("talive", class_obscure, threadalive_test,
590042fc 12007 _("Remote thread alive test."));
c906108c
SS
12008}
12009
12010#endif /* 0 */
12011
a068643d 12012/* Convert a thread ID to a string. */
f3fb8c85 12013
a068643d 12014std::string
f6ac5f3d 12015remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 12016{
d7e15655 12017 if (ptid == null_ptid)
7cee1e54 12018 return normal_pid_to_str (ptid);
0e998d96 12019 else if (ptid.is_pid ())
ecd0ada5
PA
12020 {
12021 /* Printing an inferior target id. */
12022
12023 /* When multi-process extensions are off, there's no way in the
12024 remote protocol to know the remote process id, if there's any
12025 at all. There's one exception --- when we're connected with
12026 target extended-remote, and we manually attached to a process
12027 with "attach PID". We don't record anywhere a flag that
12028 allows us to distinguish that case from the case of
12029 connecting with extended-remote and the stub already being
12030 attached to a process, and reporting yes to qAttached, hence
12031 no smart special casing here. */
ff52c073 12032 if (!m_features.remote_multi_process_p ())
a068643d 12033 return "Remote target";
ecd0ada5
PA
12034
12035 return normal_pid_to_str (ptid);
82f73884 12036 }
ecd0ada5 12037 else
79d7f229 12038 {
d7e15655 12039 if (magic_null_ptid == ptid)
a068643d 12040 return "Thread <main>";
ff52c073 12041 else if (m_features.remote_multi_process_p ())
e38504b3 12042 if (ptid.lwp () == 0)
de0d863e
DB
12043 return normal_pid_to_str (ptid);
12044 else
a068643d
TT
12045 return string_printf ("Thread %d.%ld",
12046 ptid.pid (), ptid.lwp ());
ecd0ada5 12047 else
a068643d 12048 return string_printf ("Thread %ld", ptid.lwp ());
79d7f229 12049 }
f3fb8c85
MS
12050}
12051
38691318
KB
12052/* Get the address of the thread local variable in OBJFILE which is
12053 stored at OFFSET within the thread local storage for thread PTID. */
12054
f6ac5f3d
PA
12055CORE_ADDR
12056remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12057 CORE_ADDR offset)
38691318 12058{
ff52c073 12059 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
12060 {
12061 struct remote_state *rs = get_remote_state ();
8d64371b
TT
12062 char *p = rs->buf.data ();
12063 char *endp = p + get_remote_packet_size ();
571dd617 12064 enum packet_result result;
38691318
KB
12065
12066 strcpy (p, "qGetTLSAddr:");
12067 p += strlen (p);
82f73884 12068 p = write_ptid (p, endp, ptid);
38691318
KB
12069 *p++ = ',';
12070 p += hexnumstr (p, offset);
12071 *p++ = ',';
12072 p += hexnumstr (p, lm);
12073 *p++ = '\0';
12074
6d820c5c 12075 putpkt (rs->buf);
aa7b36b8 12076 getpkt (&rs->buf);
ff52c073 12077 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
571dd617 12078 if (result == PACKET_OK)
38691318 12079 {
b926417a 12080 ULONGEST addr;
38691318 12081
8d64371b 12082 unpack_varlen_hex (rs->buf.data (), &addr);
b926417a 12083 return addr;
38691318 12084 }
571dd617 12085 else if (result == PACKET_UNKNOWN)
109c3e39
AC
12086 throw_error (TLS_GENERIC_ERROR,
12087 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 12088 else
109c3e39
AC
12089 throw_error (TLS_GENERIC_ERROR,
12090 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
12091 }
12092 else
109c3e39
AC
12093 throw_error (TLS_GENERIC_ERROR,
12094 _("TLS not supported or disabled on this target"));
38691318
KB
12095 /* Not reached. */
12096 return 0;
12097}
12098
711e434b
PM
12099/* Provide thread local base, i.e. Thread Information Block address.
12100 Returns 1 if ptid is found and thread_local_base is non zero. */
12101
57810aa7 12102bool
f6ac5f3d 12103remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 12104{
ff52c073 12105 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
12106 {
12107 struct remote_state *rs = get_remote_state ();
8d64371b
TT
12108 char *p = rs->buf.data ();
12109 char *endp = p + get_remote_packet_size ();
711e434b
PM
12110 enum packet_result result;
12111
12112 strcpy (p, "qGetTIBAddr:");
12113 p += strlen (p);
12114 p = write_ptid (p, endp, ptid);
12115 *p++ = '\0';
12116
12117 putpkt (rs->buf);
aa7b36b8 12118 getpkt (&rs->buf);
ff52c073 12119 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
711e434b
PM
12120 if (result == PACKET_OK)
12121 {
b926417a 12122 ULONGEST val;
8d64371b 12123 unpack_varlen_hex (rs->buf.data (), &val);
711e434b 12124 if (addr)
b926417a 12125 *addr = (CORE_ADDR) val;
57810aa7 12126 return true;
711e434b
PM
12127 }
12128 else if (result == PACKET_UNKNOWN)
12129 error (_("Remote target doesn't support qGetTIBAddr packet"));
12130 else
12131 error (_("Remote target failed to process qGetTIBAddr request"));
12132 }
12133 else
12134 error (_("qGetTIBAddr not supported or disabled on this target"));
12135 /* Not reached. */
57810aa7 12136 return false;
711e434b
PM
12137}
12138
29709017
DJ
12139/* Support for inferring a target description based on the current
12140 architecture and the size of a 'g' packet. While the 'g' packet
12141 can have any size (since optional registers can be left off the
12142 end), some sizes are easily recognizable given knowledge of the
12143 approximate architecture. */
12144
12145struct remote_g_packet_guess
12146{
eefce37f
TT
12147 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12148 : bytes (bytes_),
12149 tdesc (tdesc_)
12150 {
12151 }
12152
29709017
DJ
12153 int bytes;
12154 const struct target_desc *tdesc;
12155};
29709017 12156
cb275538 12157struct remote_g_packet_data
29709017 12158{
eefce37f 12159 std::vector<remote_g_packet_guess> guesses;
29709017
DJ
12160};
12161
cb275538
TT
12162static const registry<gdbarch>::key<struct remote_g_packet_data>
12163 remote_g_packet_data_handle;
29709017 12164
cb275538
TT
12165static struct remote_g_packet_data *
12166get_g_packet_data (struct gdbarch *gdbarch)
29709017 12167{
cb275538
TT
12168 struct remote_g_packet_data *data
12169 = remote_g_packet_data_handle.get (gdbarch);
12170 if (data == nullptr)
12171 data = remote_g_packet_data_handle.emplace (gdbarch);
12172 return data;
29709017
DJ
12173}
12174
12175void
12176register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12177 const struct target_desc *tdesc)
12178{
cb275538 12179 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
29709017
DJ
12180
12181 gdb_assert (tdesc != NULL);
12182
eefce37f
TT
12183 for (const remote_g_packet_guess &guess : data->guesses)
12184 if (guess.bytes == bytes)
f34652de 12185 internal_error (_("Duplicate g packet description added for size %d"),
29709017
DJ
12186 bytes);
12187
eefce37f 12188 data->guesses.emplace_back (bytes, tdesc);
29709017
DJ
12189}
12190
eefce37f
TT
12191/* Return true if remote_read_description would do anything on this target
12192 and architecture, false otherwise. */
d962ef82 12193
eefce37f 12194static bool
d962ef82
DJ
12195remote_read_description_p (struct target_ops *target)
12196{
99d9c3b9 12197 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
d962ef82 12198
eefce37f 12199 return !data->guesses.empty ();
d962ef82
DJ
12200}
12201
f6ac5f3d
PA
12202const struct target_desc *
12203remote_target::read_description ()
29709017 12204{
99d9c3b9 12205 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
29709017 12206
d962ef82
DJ
12207 /* Do not try this during initial connection, when we do not know
12208 whether there is a running but stopped thread. */
55f6301a 12209 if (!target_has_execution () || inferior_ptid == null_ptid)
b6a8c27b 12210 return beneath ()->read_description ();
d962ef82 12211
eefce37f 12212 if (!data->guesses.empty ())
29709017 12213 {
29709017
DJ
12214 int bytes = send_g_packet ();
12215
eefce37f
TT
12216 for (const remote_g_packet_guess &guess : data->guesses)
12217 if (guess.bytes == bytes)
12218 return guess.tdesc;
29709017
DJ
12219
12220 /* We discard the g packet. A minor optimization would be to
12221 hold on to it, and fill the register cache once we have selected
12222 an architecture, but it's too tricky to do safely. */
12223 }
12224
b6a8c27b 12225 return beneath ()->read_description ();
29709017
DJ
12226}
12227
a6b151f1
DJ
12228/* Remote file transfer support. This is host-initiated I/O, not
12229 target-initiated; for target-initiated, see remote-fileio.c. */
12230
12231/* If *LEFT is at least the length of STRING, copy STRING to
12232 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12233 decrease *LEFT. Otherwise raise an error. */
12234
12235static void
a121b7c1 12236remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
12237{
12238 int len = strlen (string);
12239
12240 if (len > *left)
12241 error (_("Packet too long for target."));
12242
12243 memcpy (*buffer, string, len);
12244 *buffer += len;
12245 *left -= len;
12246
12247 /* NUL-terminate the buffer as a convenience, if there is
12248 room. */
12249 if (*left)
12250 **buffer = '\0';
12251}
12252
12253/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12254 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12255 decrease *LEFT. Otherwise raise an error. */
12256
12257static void
12258remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12259 int len)
12260{
12261 if (2 * len > *left)
12262 error (_("Packet too long for target."));
12263
12264 bin2hex (bytes, *buffer, len);
12265 *buffer += 2 * len;
12266 *left -= 2 * len;
12267
12268 /* NUL-terminate the buffer as a convenience, if there is
12269 room. */
12270 if (*left)
12271 **buffer = '\0';
12272}
12273
12274/* If *LEFT is large enough, convert VALUE to hex and add it to
12275 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12276 decrease *LEFT. Otherwise raise an error. */
12277
12278static void
12279remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12280{
12281 int len = hexnumlen (value);
12282
12283 if (len > *left)
12284 error (_("Packet too long for target."));
12285
12286 hexnumstr (*buffer, value);
12287 *buffer += len;
12288 *left -= len;
12289
12290 /* NUL-terminate the buffer as a convenience, if there is
12291 room. */
12292 if (*left)
12293 **buffer = '\0';
12294}
12295
12296/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
b872057a 12297 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
a6b151f1
DJ
12298 was included, and *ATTACHMENT to point to the start of the annex
12299 if any. The length of the packet isn't needed here; there may
12300 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12301
12302 Return 0 if the packet could be parsed, -1 if it could not. If
12303 -1 is returned, the other variables may not be initialized. */
12304
12305static int
aa2838cc 12306remote_hostio_parse_result (const char *buffer, int *retcode,
b872057a 12307 fileio_error *remote_errno, const char **attachment)
a6b151f1
DJ
12308{
12309 char *p, *p2;
12310
b872057a 12311 *remote_errno = FILEIO_SUCCESS;
a6b151f1
DJ
12312 *attachment = NULL;
12313
12314 if (buffer[0] != 'F')
12315 return -1;
12316
12317 errno = 0;
12318 *retcode = strtol (&buffer[1], &p, 16);
12319 if (errno != 0 || p == &buffer[1])
12320 return -1;
12321
12322 /* Check for ",errno". */
12323 if (*p == ',')
12324 {
12325 errno = 0;
b872057a 12326 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
a6b151f1
DJ
12327 if (errno != 0 || p + 1 == p2)
12328 return -1;
12329 p = p2;
12330 }
12331
12332 /* Check for ";attachment". If there is no attachment, the
12333 packet should end here. */
12334 if (*p == ';')
12335 {
12336 *attachment = p + 1;
12337 return 0;
12338 }
12339 else if (*p == '\0')
12340 return 0;
12341 else
12342 return -1;
12343}
12344
12345/* Send a prepared I/O packet to the target and read its response.
12346 The prepared packet is in the global RS->BUF before this function
12347 is called, and the answer is there when we return.
12348
12349 COMMAND_BYTES is the length of the request to send, which may include
12350 binary data. WHICH_PACKET is the packet configuration to check
12351 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12352 is set to the error number and -1 is returned. Otherwise the value
12353 returned by the function is returned.
12354
12355 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12356 attachment is expected; an error will be reported if there's a
12357 mismatch. If one is found, *ATTACHMENT will be set to point into
12358 the packet buffer and *ATTACHMENT_LEN will be set to the
12359 attachment's length. */
12360
6b8edb51
PA
12361int
12362remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
b872057a 12363 fileio_error *remote_errno, const char **attachment,
6b8edb51 12364 int *attachment_len)
a6b151f1
DJ
12365{
12366 struct remote_state *rs = get_remote_state ();
12367 int ret, bytes_read;
aa2838cc 12368 const char *attachment_tmp;
a6b151f1 12369
ff52c073 12370 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
12371 {
12372 *remote_errno = FILEIO_ENOSYS;
12373 return -1;
12374 }
12375
8d64371b 12376 putpkt_binary (rs->buf.data (), command_bytes);
aa7b36b8 12377 bytes_read = getpkt (&rs->buf);
a6b151f1
DJ
12378
12379 /* If it timed out, something is wrong. Don't try to parse the
12380 buffer. */
12381 if (bytes_read < 0)
12382 {
12383 *remote_errno = FILEIO_EINVAL;
12384 return -1;
12385 }
12386
ff52c073 12387 switch (m_features.packet_ok (rs->buf, which_packet))
a6b151f1
DJ
12388 {
12389 case PACKET_ERROR:
12390 *remote_errno = FILEIO_EINVAL;
12391 return -1;
12392 case PACKET_UNKNOWN:
12393 *remote_errno = FILEIO_ENOSYS;
12394 return -1;
12395 case PACKET_OK:
12396 break;
12397 }
12398
8d64371b 12399 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
a6b151f1
DJ
12400 &attachment_tmp))
12401 {
12402 *remote_errno = FILEIO_EINVAL;
12403 return -1;
12404 }
12405
12406 /* Make sure we saw an attachment if and only if we expected one. */
12407 if ((attachment_tmp == NULL && attachment != NULL)
12408 || (attachment_tmp != NULL && attachment == NULL))
12409 {
12410 *remote_errno = FILEIO_EINVAL;
12411 return -1;
12412 }
12413
12414 /* If an attachment was found, it must point into the packet buffer;
12415 work out how many bytes there were. */
12416 if (attachment_tmp != NULL)
12417 {
12418 *attachment = attachment_tmp;
8d64371b 12419 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
a6b151f1
DJ
12420 }
12421
12422 return ret;
12423}
12424
dd194f6b 12425/* See declaration.h. */
80152258 12426
dd194f6b
PA
12427void
12428readahead_cache::invalidate ()
80152258 12429{
dd194f6b 12430 this->fd = -1;
80152258
PA
12431}
12432
dd194f6b 12433/* See declaration.h. */
80152258 12434
dd194f6b
PA
12435void
12436readahead_cache::invalidate_fd (int fd)
80152258 12437{
dd194f6b
PA
12438 if (this->fd == fd)
12439 this->fd = -1;
80152258
PA
12440}
12441
15a201c8
GB
12442/* Set the filesystem remote_hostio functions that take FILENAME
12443 arguments will use. Return 0 on success, or -1 if an error
12444 occurs (and set *REMOTE_ERRNO). */
12445
6b8edb51
PA
12446int
12447remote_target::remote_hostio_set_filesystem (struct inferior *inf,
b872057a 12448 fileio_error *remote_errno)
15a201c8
GB
12449{
12450 struct remote_state *rs = get_remote_state ();
12451 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
8d64371b 12452 char *p = rs->buf.data ();
15a201c8
GB
12453 int left = get_remote_packet_size () - 1;
12454 char arg[9];
12455 int ret;
12456
ff52c073 12457 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
15a201c8
GB
12458 return 0;
12459
12460 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12461 return 0;
12462
12463 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12464
12465 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12466 remote_buffer_add_string (&p, &left, arg);
12467
8d64371b 12468 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
15a201c8
GB
12469 remote_errno, NULL, NULL);
12470
ff52c073 12471 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
15a201c8
GB
12472 return 0;
12473
12474 if (ret == 0)
12475 rs->fs_pid = required_pid;
12476
12477 return ret;
12478}
12479
12e2a5fd 12480/* Implementation of to_fileio_open. */
a6b151f1 12481
6b8edb51
PA
12482int
12483remote_target::remote_hostio_open (inferior *inf, const char *filename,
12484 int flags, int mode, int warn_if_slow,
b872057a 12485 fileio_error *remote_errno)
a6b151f1
DJ
12486{
12487 struct remote_state *rs = get_remote_state ();
8d64371b 12488 char *p = rs->buf.data ();
a6b151f1
DJ
12489 int left = get_remote_packet_size () - 1;
12490
4313b8c0
GB
12491 if (warn_if_slow)
12492 {
12493 static int warning_issued = 0;
12494
6cb06a8c
TT
12495 gdb_printf (_("Reading %s from remote target...\n"),
12496 filename);
4313b8c0
GB
12497
12498 if (!warning_issued)
12499 {
12500 warning (_("File transfers from remote targets can be slow."
12501 " Use \"set sysroot\" to access files locally"
12502 " instead."));
12503 warning_issued = 1;
12504 }
12505 }
12506
15a201c8
GB
12507 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12508 return -1;
12509
a6b151f1
DJ
12510 remote_buffer_add_string (&p, &left, "vFile:open:");
12511
12512 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12513 strlen (filename));
12514 remote_buffer_add_string (&p, &left, ",");
12515
12516 remote_buffer_add_int (&p, &left, flags);
12517 remote_buffer_add_string (&p, &left, ",");
12518
12519 remote_buffer_add_int (&p, &left, mode);
12520
8d64371b 12521 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
a6b151f1
DJ
12522 remote_errno, NULL, NULL);
12523}
12524
f6ac5f3d
PA
12525int
12526remote_target::fileio_open (struct inferior *inf, const char *filename,
12527 int flags, int mode, int warn_if_slow,
b872057a 12528 fileio_error *remote_errno)
f6ac5f3d 12529{
6b8edb51 12530 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
12531 remote_errno);
12532}
12533
12e2a5fd 12534/* Implementation of to_fileio_pwrite. */
a6b151f1 12535
6b8edb51
PA
12536int
12537remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 12538 ULONGEST offset, fileio_error *remote_errno)
a6b151f1
DJ
12539{
12540 struct remote_state *rs = get_remote_state ();
8d64371b 12541 char *p = rs->buf.data ();
a6b151f1
DJ
12542 int left = get_remote_packet_size ();
12543 int out_len;
12544
dd194f6b 12545 rs->readahead_cache.invalidate_fd (fd);
80152258 12546
a6b151f1
DJ
12547 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12548
12549 remote_buffer_add_int (&p, &left, fd);
12550 remote_buffer_add_string (&p, &left, ",");
12551
12552 remote_buffer_add_int (&p, &left, offset);
12553 remote_buffer_add_string (&p, &left, ",");
12554
124e13d9 12555 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
8d64371b
TT
12556 (get_remote_packet_size ()
12557 - (p - rs->buf.data ())));
a6b151f1 12558
8d64371b 12559 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
a6b151f1
DJ
12560 remote_errno, NULL, NULL);
12561}
12562
f6ac5f3d
PA
12563int
12564remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 12565 ULONGEST offset, fileio_error *remote_errno)
f6ac5f3d 12566{
6b8edb51 12567 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12568}
12569
80152258
PA
12570/* Helper for the implementation of to_fileio_pread. Read the file
12571 from the remote side with vFile:pread. */
a6b151f1 12572
6b8edb51
PA
12573int
12574remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
b872057a 12575 ULONGEST offset, fileio_error *remote_errno)
a6b151f1
DJ
12576{
12577 struct remote_state *rs = get_remote_state ();
8d64371b 12578 char *p = rs->buf.data ();
aa2838cc 12579 const char *attachment;
a6b151f1
DJ
12580 int left = get_remote_packet_size ();
12581 int ret, attachment_len;
12582 int read_len;
12583
12584 remote_buffer_add_string (&p, &left, "vFile:pread:");
12585
12586 remote_buffer_add_int (&p, &left, fd);
12587 remote_buffer_add_string (&p, &left, ",");
12588
12589 remote_buffer_add_int (&p, &left, len);
12590 remote_buffer_add_string (&p, &left, ",");
12591
12592 remote_buffer_add_int (&p, &left, offset);
12593
8d64371b 12594 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
a6b151f1
DJ
12595 remote_errno, &attachment,
12596 &attachment_len);
12597
12598 if (ret < 0)
12599 return ret;
12600
bc20a4af 12601 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12602 read_buf, len);
12603 if (read_len != ret)
12604 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12605
12606 return ret;
12607}
12608
dd194f6b 12609/* See declaration.h. */
80152258 12610
dd194f6b
PA
12611int
12612readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12613 ULONGEST offset)
80152258 12614{
dd194f6b
PA
12615 if (this->fd == fd
12616 && this->offset <= offset
6b19f38a 12617 && offset < this->offset + this->buf.size ())
80152258 12618 {
6b19f38a 12619 ULONGEST max = this->offset + this->buf.size ();
80152258
PA
12620
12621 if (offset + len > max)
12622 len = max - offset;
12623
6b19f38a 12624 memcpy (read_buf, &this->buf[offset - this->offset], len);
80152258
PA
12625 return len;
12626 }
12627
12628 return 0;
12629}
12630
12631/* Implementation of to_fileio_pread. */
12632
6b8edb51
PA
12633int
12634remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 12635 ULONGEST offset, fileio_error *remote_errno)
80152258
PA
12636{
12637 int ret;
12638 struct remote_state *rs = get_remote_state ();
dd194f6b 12639 readahead_cache *cache = &rs->readahead_cache;
80152258 12640
dd194f6b 12641 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12642 if (ret > 0)
12643 {
12644 cache->hit_count++;
12645
2189c312
SM
12646 remote_debug_printf ("readahead cache hit %s",
12647 pulongest (cache->hit_count));
80152258
PA
12648 return ret;
12649 }
12650
12651 cache->miss_count++;
2189c312
SM
12652
12653 remote_debug_printf ("readahead cache miss %s",
12654 pulongest (cache->miss_count));
80152258
PA
12655
12656 cache->fd = fd;
12657 cache->offset = offset;
6b19f38a 12658 cache->buf.resize (get_remote_packet_size ());
80152258 12659
6b19f38a
TT
12660 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12661 cache->buf.size (),
80152258
PA
12662 cache->offset, remote_errno);
12663 if (ret <= 0)
12664 {
dd194f6b 12665 cache->invalidate_fd (fd);
80152258
PA
12666 return ret;
12667 }
12668
6b19f38a 12669 cache->buf.resize (ret);
dd194f6b 12670 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12671}
12672
f6ac5f3d
PA
12673int
12674remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 12675 ULONGEST offset, fileio_error *remote_errno)
f6ac5f3d 12676{
6b8edb51 12677 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12678}
12679
12e2a5fd 12680/* Implementation of to_fileio_close. */
a6b151f1 12681
6b8edb51 12682int
b872057a 12683remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
a6b151f1
DJ
12684{
12685 struct remote_state *rs = get_remote_state ();
8d64371b 12686 char *p = rs->buf.data ();
a6b151f1
DJ
12687 int left = get_remote_packet_size () - 1;
12688
dd194f6b 12689 rs->readahead_cache.invalidate_fd (fd);
80152258 12690
a6b151f1
DJ
12691 remote_buffer_add_string (&p, &left, "vFile:close:");
12692
12693 remote_buffer_add_int (&p, &left, fd);
12694
8d64371b 12695 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
a6b151f1
DJ
12696 remote_errno, NULL, NULL);
12697}
12698
f6ac5f3d 12699int
b872057a 12700remote_target::fileio_close (int fd, fileio_error *remote_errno)
f6ac5f3d 12701{
6b8edb51 12702 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12703}
12704
12e2a5fd 12705/* Implementation of to_fileio_unlink. */
a6b151f1 12706
6b8edb51
PA
12707int
12708remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
b872057a 12709 fileio_error *remote_errno)
a6b151f1
DJ
12710{
12711 struct remote_state *rs = get_remote_state ();
8d64371b 12712 char *p = rs->buf.data ();
a6b151f1
DJ
12713 int left = get_remote_packet_size () - 1;
12714
15a201c8
GB
12715 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12716 return -1;
12717
a6b151f1
DJ
12718 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12719
12720 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12721 strlen (filename));
12722
8d64371b 12723 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
a6b151f1
DJ
12724 remote_errno, NULL, NULL);
12725}
12726
f6ac5f3d
PA
12727int
12728remote_target::fileio_unlink (struct inferior *inf, const char *filename,
b872057a 12729 fileio_error *remote_errno)
f6ac5f3d 12730{
6b8edb51 12731 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12732}
12733
12e2a5fd 12734/* Implementation of to_fileio_readlink. */
b9e7b9c3 12735
f6ac5f3d
PA
12736gdb::optional<std::string>
12737remote_target::fileio_readlink (struct inferior *inf, const char *filename,
b872057a 12738 fileio_error *remote_errno)
b9e7b9c3
UW
12739{
12740 struct remote_state *rs = get_remote_state ();
8d64371b 12741 char *p = rs->buf.data ();
aa2838cc 12742 const char *attachment;
b9e7b9c3
UW
12743 int left = get_remote_packet_size ();
12744 int len, attachment_len;
12745 int read_len;
b9e7b9c3 12746
15a201c8 12747 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12748 return {};
15a201c8 12749
b9e7b9c3
UW
12750 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12751
12752 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12753 strlen (filename));
12754
8d64371b 12755 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
b9e7b9c3
UW
12756 remote_errno, &attachment,
12757 &attachment_len);
12758
12759 if (len < 0)
e0d3522b 12760 return {};
b9e7b9c3 12761
e0d3522b 12762 std::string ret (len, '\0');
b9e7b9c3 12763
bc20a4af 12764 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12765 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12766 if (read_len != len)
12767 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12768
b9e7b9c3
UW
12769 return ret;
12770}
12771
12e2a5fd 12772/* Implementation of to_fileio_fstat. */
0a93529c 12773
f6ac5f3d 12774int
b872057a 12775remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
0a93529c
GB
12776{
12777 struct remote_state *rs = get_remote_state ();
8d64371b 12778 char *p = rs->buf.data ();
0a93529c
GB
12779 int left = get_remote_packet_size ();
12780 int attachment_len, ret;
aa2838cc 12781 const char *attachment;
0a93529c
GB
12782 struct fio_stat fst;
12783 int read_len;
12784
464b0089
GB
12785 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12786
12787 remote_buffer_add_int (&p, &left, fd);
12788
8d64371b 12789 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
464b0089
GB
12790 remote_errno, &attachment,
12791 &attachment_len);
12792 if (ret < 0)
0a93529c 12793 {
464b0089
GB
12794 if (*remote_errno != FILEIO_ENOSYS)
12795 return ret;
12796
0a93529c
GB
12797 /* Strictly we should return -1, ENOSYS here, but when
12798 "set sysroot remote:" was implemented in August 2008
12799 BFD's need for a stat function was sidestepped with
12800 this hack. This was not remedied until March 2015
12801 so we retain the previous behavior to avoid breaking
12802 compatibility.
12803
12804 Note that the memset is a March 2015 addition; older
12805 GDBs set st_size *and nothing else* so the structure
12806 would have garbage in all other fields. This might
12807 break something but retaining the previous behavior
12808 here would be just too wrong. */
12809
12810 memset (st, 0, sizeof (struct stat));
12811 st->st_size = INT_MAX;
12812 return 0;
12813 }
12814
0a93529c
GB
12815 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12816 (gdb_byte *) &fst, sizeof (fst));
12817
12818 if (read_len != ret)
12819 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12820
12821 if (read_len != sizeof (fst))
12822 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12823 read_len, (int) sizeof (fst));
12824
12825 remote_fileio_to_host_stat (&fst, st);
12826
12827 return 0;
12828}
12829
12e2a5fd 12830/* Implementation of to_filesystem_is_local. */
e3dd7556 12831
57810aa7 12832bool
f6ac5f3d 12833remote_target::filesystem_is_local ()
e3dd7556
GB
12834{
12835 /* Valgrind GDB presents itself as a remote target but works
12836 on the local filesystem: it does not implement remote get
12837 and users are not expected to set a sysroot. To handle
12838 this case we treat the remote filesystem as local if the
12839 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12840 does not support vFile:open. */
e0700ba4 12841 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
e3dd7556 12842 {
ff52c073 12843 packet_support ps = m_features.packet_support (PACKET_vFile_open);
e3dd7556
GB
12844
12845 if (ps == PACKET_SUPPORT_UNKNOWN)
12846 {
b872057a
SM
12847 int fd;
12848 fileio_error remote_errno;
e3dd7556
GB
12849
12850 /* Try opening a file to probe support. The supplied
12851 filename is irrelevant, we only care about whether
12852 the stub recognizes the packet or not. */
6b8edb51 12853 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12854 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12855 &remote_errno);
12856
12857 if (fd >= 0)
6b8edb51 12858 remote_hostio_close (fd, &remote_errno);
e3dd7556 12859
ff52c073 12860 ps = m_features.packet_support (PACKET_vFile_open);
e3dd7556
GB
12861 }
12862
12863 if (ps == PACKET_DISABLE)
12864 {
12865 static int warning_issued = 0;
12866
12867 if (!warning_issued)
12868 {
12869 warning (_("remote target does not support file"
12870 " transfer, attempting to access files"
12871 " from local filesystem."));
12872 warning_issued = 1;
12873 }
12874
57810aa7 12875 return true;
e3dd7556
GB
12876 }
12877 }
12878
57810aa7 12879 return false;
e3dd7556
GB
12880}
12881
a6b151f1 12882static char *
b872057a 12883remote_hostio_error (fileio_error errnum)
a6b151f1 12884{
517a63c2 12885 int host_error = fileio_error_to_host (errnum);
a6b151f1
DJ
12886
12887 if (host_error == -1)
12888 error (_("Unknown remote I/O error %d"), errnum);
12889 else
12890 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12891}
12892
440b7aec
PA
12893/* A RAII wrapper around a remote file descriptor. */
12894
12895class scoped_remote_fd
a6b151f1 12896{
440b7aec 12897public:
6b8edb51
PA
12898 scoped_remote_fd (remote_target *remote, int fd)
12899 : m_remote (remote), m_fd (fd)
440b7aec
PA
12900 {
12901 }
a6b151f1 12902
440b7aec
PA
12903 ~scoped_remote_fd ()
12904 {
12905 if (m_fd != -1)
12906 {
12907 try
12908 {
b872057a 12909 fileio_error remote_errno;
6b8edb51 12910 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12911 }
12912 catch (...)
12913 {
12914 /* Swallow exception before it escapes the dtor. If
12915 something goes wrong, likely the connection is gone,
12916 and there's nothing else that can be done. */
12917 }
12918 }
12919 }
12920
12921 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12922
12923 /* Release ownership of the file descriptor, and return it. */
88a774b9 12924 ATTRIBUTE_UNUSED_RESULT int release () noexcept
440b7aec
PA
12925 {
12926 int fd = m_fd;
12927 m_fd = -1;
12928 return fd;
12929 }
12930
12931 /* Return the owned file descriptor. */
12932 int get () const noexcept
12933 {
12934 return m_fd;
12935 }
12936
12937private:
6b8edb51
PA
12938 /* The remote target. */
12939 remote_target *m_remote;
12940
440b7aec
PA
12941 /* The owned remote I/O file descriptor. */
12942 int m_fd;
12943};
a6b151f1
DJ
12944
12945void
12946remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12947{
12948 remote_target *remote = get_current_remote_target ();
12949
12950 if (remote == nullptr)
12951 error (_("command can only be used with remote target"));
12952
12953 remote->remote_file_put (local_file, remote_file, from_tty);
12954}
12955
12956void
12957remote_target::remote_file_put (const char *local_file, const char *remote_file,
12958 int from_tty)
a6b151f1 12959{
b872057a
SM
12960 int retcode, bytes, io_size;
12961 fileio_error remote_errno;
a6b151f1
DJ
12962 int bytes_in_buffer;
12963 int saw_eof;
12964 ULONGEST offset;
a6b151f1 12965
d419f42d 12966 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12967 if (file == NULL)
12968 perror_with_name (local_file);
a6b151f1 12969
440b7aec 12970 scoped_remote_fd fd
6b8edb51
PA
12971 (this, remote_hostio_open (NULL,
12972 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12973 | FILEIO_O_TRUNC),
12974 0700, 0, &remote_errno));
440b7aec 12975 if (fd.get () == -1)
a6b151f1
DJ
12976 remote_hostio_error (remote_errno);
12977
12978 /* Send up to this many bytes at once. They won't all fit in the
12979 remote packet limit, so we'll transfer slightly fewer. */
12980 io_size = get_remote_packet_size ();
5ca3b260 12981 gdb::byte_vector buffer (io_size);
a6b151f1 12982
a6b151f1
DJ
12983 bytes_in_buffer = 0;
12984 saw_eof = 0;
12985 offset = 0;
12986 while (bytes_in_buffer || !saw_eof)
12987 {
12988 if (!saw_eof)
12989 {
5ca3b260 12990 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 12991 io_size - bytes_in_buffer,
d419f42d 12992 file.get ());
a6b151f1
DJ
12993 if (bytes == 0)
12994 {
d419f42d 12995 if (ferror (file.get ()))
a6b151f1
DJ
12996 error (_("Error reading %s."), local_file);
12997 else
12998 {
12999 /* EOF. Unless there is something still in the
13000 buffer from the last iteration, we are done. */
13001 saw_eof = 1;
13002 if (bytes_in_buffer == 0)
13003 break;
13004 }
13005 }
13006 }
13007 else
13008 bytes = 0;
13009
13010 bytes += bytes_in_buffer;
13011 bytes_in_buffer = 0;
13012
5ca3b260 13013 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 13014 offset, &remote_errno);
a6b151f1
DJ
13015
13016 if (retcode < 0)
13017 remote_hostio_error (remote_errno);
13018 else if (retcode == 0)
13019 error (_("Remote write of %d bytes returned 0!"), bytes);
13020 else if (retcode < bytes)
13021 {
13022 /* Short write. Save the rest of the read data for the next
13023 write. */
13024 bytes_in_buffer = bytes - retcode;
5ca3b260 13025 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
13026 }
13027
13028 offset += retcode;
13029 }
13030
6b8edb51 13031 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
13032 remote_hostio_error (remote_errno);
13033
13034 if (from_tty)
6cb06a8c 13035 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
a6b151f1
DJ
13036}
13037
13038void
13039remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
13040{
13041 remote_target *remote = get_current_remote_target ();
13042
13043 if (remote == nullptr)
13044 error (_("command can only be used with remote target"));
13045
13046 remote->remote_file_get (remote_file, local_file, from_tty);
13047}
13048
13049void
13050remote_target::remote_file_get (const char *remote_file, const char *local_file,
13051 int from_tty)
a6b151f1 13052{
b872057a
SM
13053 fileio_error remote_errno;
13054 int bytes, io_size;
a6b151f1 13055 ULONGEST offset;
a6b151f1 13056
440b7aec 13057 scoped_remote_fd fd
6b8edb51
PA
13058 (this, remote_hostio_open (NULL,
13059 remote_file, FILEIO_O_RDONLY, 0, 0,
13060 &remote_errno));
440b7aec 13061 if (fd.get () == -1)
a6b151f1
DJ
13062 remote_hostio_error (remote_errno);
13063
d419f42d 13064 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
13065 if (file == NULL)
13066 perror_with_name (local_file);
a6b151f1
DJ
13067
13068 /* Send up to this many bytes at once. They won't all fit in the
13069 remote packet limit, so we'll transfer slightly fewer. */
13070 io_size = get_remote_packet_size ();
5ca3b260 13071 gdb::byte_vector buffer (io_size);
a6b151f1 13072
a6b151f1
DJ
13073 offset = 0;
13074 while (1)
13075 {
5ca3b260 13076 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 13077 &remote_errno);
a6b151f1
DJ
13078 if (bytes == 0)
13079 /* Success, but no bytes, means end-of-file. */
13080 break;
13081 if (bytes == -1)
13082 remote_hostio_error (remote_errno);
13083
13084 offset += bytes;
13085
5ca3b260 13086 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
13087 if (bytes == 0)
13088 perror_with_name (local_file);
13089 }
13090
6b8edb51 13091 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
13092 remote_hostio_error (remote_errno);
13093
13094 if (from_tty)
6cb06a8c 13095 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
a6b151f1
DJ
13096}
13097
13098void
13099remote_file_delete (const char *remote_file, int from_tty)
13100{
6b8edb51 13101 remote_target *remote = get_current_remote_target ();
a6b151f1 13102
6b8edb51 13103 if (remote == nullptr)
a6b151f1
DJ
13104 error (_("command can only be used with remote target"));
13105
6b8edb51
PA
13106 remote->remote_file_delete (remote_file, from_tty);
13107}
13108
13109void
13110remote_target::remote_file_delete (const char *remote_file, int from_tty)
13111{
b872057a
SM
13112 int retcode;
13113 fileio_error remote_errno;
6b8edb51
PA
13114
13115 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
13116 if (retcode == -1)
13117 remote_hostio_error (remote_errno);
13118
13119 if (from_tty)
6cb06a8c 13120 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
a6b151f1
DJ
13121}
13122
13123static void
ac88e2de 13124remote_put_command (const char *args, int from_tty)
a6b151f1 13125{
d1a41061
PP
13126 if (args == NULL)
13127 error_no_arg (_("file to put"));
13128
773a1edc 13129 gdb_argv argv (args);
a6b151f1
DJ
13130 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13131 error (_("Invalid parameters to remote put"));
13132
13133 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
13134}
13135
13136static void
ac88e2de 13137remote_get_command (const char *args, int from_tty)
a6b151f1 13138{
d1a41061
PP
13139 if (args == NULL)
13140 error_no_arg (_("file to get"));
13141
773a1edc 13142 gdb_argv argv (args);
a6b151f1
DJ
13143 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13144 error (_("Invalid parameters to remote get"));
13145
13146 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
13147}
13148
13149static void
ac88e2de 13150remote_delete_command (const char *args, int from_tty)
a6b151f1 13151{
d1a41061
PP
13152 if (args == NULL)
13153 error_no_arg (_("file to delete"));
13154
773a1edc 13155 gdb_argv argv (args);
a6b151f1
DJ
13156 if (argv[0] == NULL || argv[1] != NULL)
13157 error (_("Invalid parameters to remote delete"));
13158
13159 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
13160}
13161
57810aa7 13162bool
f6ac5f3d 13163remote_target::can_execute_reverse ()
b2175913 13164{
ff52c073
CS
13165 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13166 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 13167 return true;
40ab02ce 13168 else
57810aa7 13169 return false;
b2175913
MS
13170}
13171
57810aa7 13172bool
f6ac5f3d 13173remote_target::supports_non_stop ()
74531fed 13174{
57810aa7 13175 return true;
74531fed
PA
13176}
13177
57810aa7 13178bool
f6ac5f3d 13179remote_target::supports_disable_randomization ()
03583c20
UW
13180{
13181 /* Only supported in extended mode. */
57810aa7 13182 return false;
03583c20
UW
13183}
13184
57810aa7 13185bool
f6ac5f3d 13186remote_target::supports_multi_process ()
8a305172 13187{
ff52c073 13188 return m_features.remote_multi_process_p ();
8a305172
PA
13189}
13190
ff52c073
CS
13191int
13192remote_target::remote_supports_cond_tracepoints ()
782b2b07 13193{
ff52c073
CS
13194 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13195 == PACKET_ENABLE);
782b2b07
SS
13196}
13197
57810aa7 13198bool
f6ac5f3d 13199remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 13200{
ff52c073
CS
13201 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13202 == PACKET_ENABLE);
3788aec7
LM
13203}
13204
ff52c073
CS
13205int
13206remote_target::remote_supports_fast_tracepoints ()
7a697b8d 13207{
ff52c073 13208 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
13209}
13210
ff52c073
CS
13211int
13212remote_target::remote_supports_static_tracepoints ()
0fb4aa4b 13213{
ff52c073 13214 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
13215}
13216
ff52c073
CS
13217int
13218remote_target::remote_supports_install_in_trace ()
1e4d1764 13219{
ff52c073 13220 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
13221}
13222
57810aa7 13223bool
f6ac5f3d 13224remote_target::supports_enable_disable_tracepoint ()
d248b706 13225{
ff52c073 13226 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
4082afcc 13227 == PACKET_ENABLE);
d248b706
KY
13228}
13229
57810aa7 13230bool
f6ac5f3d 13231remote_target::supports_string_tracing ()
3065dfb6 13232{
ff52c073 13233 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
13234}
13235
57810aa7 13236bool
f6ac5f3d 13237remote_target::can_run_breakpoint_commands ()
d3ce09f5 13238{
ff52c073 13239 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
13240}
13241
f6ac5f3d
PA
13242void
13243remote_target::trace_init ()
35b1e5cc 13244{
b6bb3468
PA
13245 struct remote_state *rs = get_remote_state ();
13246
35b1e5cc 13247 putpkt ("QTinit");
b6bb3468 13248 remote_get_noisy_reply ();
8d64371b 13249 if (strcmp (rs->buf.data (), "OK") != 0)
35b1e5cc
SS
13250 error (_("Target does not support this command."));
13251}
13252
409873ef
SS
13253/* Recursive routine to walk through command list including loops, and
13254 download packets for each command. */
13255
6b8edb51
PA
13256void
13257remote_target::remote_download_command_source (int num, ULONGEST addr,
13258 struct command_line *cmds)
409873ef
SS
13259{
13260 struct remote_state *rs = get_remote_state ();
13261 struct command_line *cmd;
13262
13263 for (cmd = cmds; cmd; cmd = cmd->next)
13264 {
0df8b418 13265 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13266 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13267 encode_source_string (num, addr, "cmd", cmd->line,
8d64371b
TT
13268 rs->buf.data () + strlen (rs->buf.data ()),
13269 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13270 putpkt (rs->buf);
b6bb3468 13271 remote_get_noisy_reply ();
8d64371b 13272 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13273 warning (_("Target does not support source download."));
13274
13275 if (cmd->control_type == while_control
13276 || cmd->control_type == while_stepping_control)
13277 {
12973681 13278 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 13279
0df8b418 13280 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13281 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13282 encode_source_string (num, addr, "cmd", "end",
8d64371b
TT
13283 rs->buf.data () + strlen (rs->buf.data ()),
13284 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13285 putpkt (rs->buf);
b6bb3468 13286 remote_get_noisy_reply ();
8d64371b 13287 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13288 warning (_("Target does not support source download."));
13289 }
13290 }
13291}
13292
f6ac5f3d
PA
13293void
13294remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc
SS
13295{
13296 CORE_ADDR tpaddr;
409873ef 13297 char addrbuf[40];
b44ec619
SM
13298 std::vector<std::string> tdp_actions;
13299 std::vector<std::string> stepping_actions;
35b1e5cc 13300 char *pkt;
e8ba3115 13301 struct breakpoint *b = loc->owner;
01bccc56 13302 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
b6bb3468 13303 struct remote_state *rs = get_remote_state ();
3df3a985 13304 int ret;
ff36536c 13305 const char *err_msg = _("Tracepoint packet too large for target.");
3df3a985
PFC
13306 size_t size_left;
13307
13308 /* We use a buffer other than rs->buf because we'll build strings
13309 across multiple statements, and other statements in between could
13310 modify rs->buf. */
13311 gdb::char_vector buf (get_remote_packet_size ());
35b1e5cc 13312
dc673c81 13313 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
13314
13315 tpaddr = loc->address;
53807e9f 13316 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
3df3a985
PFC
13317 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13318 b->number, addrbuf, /* address */
13319 (b->enable_state == bp_enabled ? 'E' : 'D'),
13320 t->step_count, t->pass_count);
13321
13322 if (ret < 0 || ret >= buf.size ())
a7f25a84 13323 error ("%s", err_msg);
3df3a985 13324
e8ba3115
YQ
13325 /* Fast tracepoints are mostly handled by the target, but we can
13326 tell the target how big of an instruction block should be moved
13327 around. */
13328 if (b->type == bp_fast_tracepoint)
13329 {
13330 /* Only test for support at download time; we may not know
13331 target capabilities at definition time. */
13332 if (remote_supports_fast_tracepoints ())
35b1e5cc 13333 {
6b940e6a
PL
13334 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13335 NULL))
3df3a985
PFC
13336 {
13337 size_left = buf.size () - strlen (buf.data ());
13338 ret = snprintf (buf.data () + strlen (buf.data ()),
13339 size_left, ":F%x",
13340 gdb_insn_length (loc->gdbarch, tpaddr));
13341
13342 if (ret < 0 || ret >= size_left)
a7f25a84 13343 error ("%s", err_msg);
3df3a985 13344 }
35b1e5cc 13345 else
e8ba3115
YQ
13346 /* If it passed validation at definition but fails now,
13347 something is very wrong. */
f34652de 13348 internal_error (_("Fast tracepoint not valid during download"));
35b1e5cc 13349 }
e8ba3115
YQ
13350 else
13351 /* Fast tracepoints are functionally identical to regular
13352 tracepoints, so don't take lack of support as a reason to
13353 give up on the trace run. */
13354 warning (_("Target does not support fast tracepoints, "
13355 "downloading %d as regular tracepoint"), b->number);
13356 }
7b572efb
TT
13357 else if (b->type == bp_static_tracepoint
13358 || b->type == bp_static_marker_tracepoint)
e8ba3115
YQ
13359 {
13360 /* Only test for support at download time; we may not know
13361 target capabilities at definition time. */
13362 if (remote_supports_static_tracepoints ())
0fb4aa4b 13363 {
e8ba3115 13364 struct static_tracepoint_marker marker;
0fb4aa4b 13365
e8ba3115 13366 if (target_static_tracepoint_marker_at (tpaddr, &marker))
3df3a985
PFC
13367 {
13368 size_left = buf.size () - strlen (buf.data ());
13369 ret = snprintf (buf.data () + strlen (buf.data ()),
13370 size_left, ":S");
13371
13372 if (ret < 0 || ret >= size_left)
a7f25a84 13373 error ("%s", err_msg);
3df3a985 13374 }
0fb4aa4b 13375 else
e8ba3115 13376 error (_("Static tracepoint not valid during download"));
0fb4aa4b 13377 }
e8ba3115
YQ
13378 else
13379 /* Fast tracepoints are functionally identical to regular
13380 tracepoints, so don't take lack of support as a reason
13381 to give up on the trace run. */
13382 error (_("Target does not support static tracepoints"));
13383 }
13384 /* If the tracepoint has a conditional, make it into an agent
13385 expression and append to the definition. */
13386 if (loc->cond)
13387 {
13388 /* Only test support at download time, we may not know target
13389 capabilities at definition time. */
13390 if (remote_supports_cond_tracepoints ())
35b1e5cc 13391 {
3df3a985
PFC
13392 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13393 loc->cond.get ());
13394
13395 size_left = buf.size () - strlen (buf.data ());
13396
13397 ret = snprintf (buf.data () + strlen (buf.data ()),
6f96f485 13398 size_left, ":X%x,", (int) aexpr->buf.size ());
3df3a985
PFC
13399
13400 if (ret < 0 || ret >= size_left)
a7f25a84 13401 error ("%s", err_msg);
3df3a985
PFC
13402
13403 size_left = buf.size () - strlen (buf.data ());
13404
13405 /* Two bytes to encode each aexpr byte, plus the terminating
13406 null byte. */
6f96f485 13407 if (aexpr->buf.size () * 2 + 1 > size_left)
a7f25a84 13408 error ("%s", err_msg);
3df3a985
PFC
13409
13410 pkt = buf.data () + strlen (buf.data ());
13411
6f96f485 13412 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
e8ba3115
YQ
13413 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13414 *pkt = '\0';
35b1e5cc 13415 }
e8ba3115
YQ
13416 else
13417 warning (_("Target does not support conditional tracepoints, "
13418 "ignoring tp %d cond"), b->number);
13419 }
35b1e5cc 13420
e0700ba4 13421 if (b->commands || !default_collect.empty ())
3df3a985
PFC
13422 {
13423 size_left = buf.size () - strlen (buf.data ());
13424
13425 ret = snprintf (buf.data () + strlen (buf.data ()),
13426 size_left, "-");
13427
13428 if (ret < 0 || ret >= size_left)
a7f25a84 13429 error ("%s", err_msg);
3df3a985
PFC
13430 }
13431
13432 putpkt (buf.data ());
b6bb3468 13433 remote_get_noisy_reply ();
8d64371b 13434 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13435 error (_("Target does not support tracepoints."));
35b1e5cc 13436
e8ba3115 13437 /* do_single_steps (t); */
b44ec619
SM
13438 for (auto action_it = tdp_actions.begin ();
13439 action_it != tdp_actions.end (); action_it++)
e8ba3115 13440 {
b44ec619
SM
13441 QUIT; /* Allow user to bail out with ^C. */
13442
aa6f3694 13443 bool has_more = ((action_it + 1) != tdp_actions.end ()
b44ec619
SM
13444 || !stepping_actions.empty ());
13445
3df3a985
PFC
13446 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13447 b->number, addrbuf, /* address */
13448 action_it->c_str (),
13449 has_more ? '-' : 0);
13450
13451 if (ret < 0 || ret >= buf.size ())
a7f25a84 13452 error ("%s", err_msg);
3df3a985
PFC
13453
13454 putpkt (buf.data ());
b44ec619 13455 remote_get_noisy_reply ();
8d64371b 13456 if (strcmp (rs->buf.data (), "OK"))
b44ec619 13457 error (_("Error on target while setting tracepoints."));
e8ba3115 13458 }
409873ef 13459
05abfc39
PFC
13460 for (auto action_it = stepping_actions.begin ();
13461 action_it != stepping_actions.end (); action_it++)
13462 {
13463 QUIT; /* Allow user to bail out with ^C. */
13464
13465 bool is_first = action_it == stepping_actions.begin ();
aa6f3694 13466 bool has_more = (action_it + 1) != stepping_actions.end ();
05abfc39 13467
3df3a985
PFC
13468 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13469 b->number, addrbuf, /* address */
13470 is_first ? "S" : "",
13471 action_it->c_str (),
13472 has_more ? "-" : "");
13473
13474 if (ret < 0 || ret >= buf.size ())
a7f25a84 13475 error ("%s", err_msg);
3df3a985
PFC
13476
13477 putpkt (buf.data ());
05abfc39 13478 remote_get_noisy_reply ();
8d64371b 13479 if (strcmp (rs->buf.data (), "OK"))
05abfc39
PFC
13480 error (_("Error on target while setting tracepoints."));
13481 }
b44ec619 13482
ff52c073 13483 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 13484 {
264f9890 13485 if (b->locspec != nullptr)
409873ef 13486 {
3df3a985
PFC
13487 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13488
13489 if (ret < 0 || ret >= buf.size ())
a7f25a84 13490 error ("%s", err_msg);
3df3a985 13491
709438c7 13492 const char *str = b->locspec->to_string ();
264f9890 13493 encode_source_string (b->number, loc->address, "at", str,
3df3a985
PFC
13494 buf.data () + strlen (buf.data ()),
13495 buf.size () - strlen (buf.data ()));
13496 putpkt (buf.data ());
b6bb3468 13497 remote_get_noisy_reply ();
8d64371b 13498 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13499 warning (_("Target does not support source download."));
409873ef 13500 }
e8ba3115
YQ
13501 if (b->cond_string)
13502 {
3df3a985
PFC
13503 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13504
13505 if (ret < 0 || ret >= buf.size ())
a7f25a84 13506 error ("%s", err_msg);
3df3a985 13507
e8ba3115 13508 encode_source_string (b->number, loc->address,
6f781ee3 13509 "cond", b->cond_string.get (),
3df3a985
PFC
13510 buf.data () + strlen (buf.data ()),
13511 buf.size () - strlen (buf.data ()));
13512 putpkt (buf.data ());
b6bb3468 13513 remote_get_noisy_reply ();
8d64371b 13514 if (strcmp (rs->buf.data (), "OK"))
e8ba3115
YQ
13515 warning (_("Target does not support source download."));
13516 }
13517 remote_download_command_source (b->number, loc->address,
13518 breakpoint_commands (b));
35b1e5cc 13519 }
35b1e5cc
SS
13520}
13521
57810aa7 13522bool
f6ac5f3d 13523remote_target::can_download_tracepoint ()
1e4d1764 13524{
1e51243a
PA
13525 struct remote_state *rs = get_remote_state ();
13526 struct trace_status *ts;
13527 int status;
13528
13529 /* Don't try to install tracepoints until we've relocated our
13530 symbols, and fetched and merged the target's tracepoint list with
13531 ours. */
13532 if (rs->starting_up)
57810aa7 13533 return false;
1e51243a
PA
13534
13535 ts = current_trace_status ();
f6ac5f3d 13536 status = get_trace_status (ts);
1e4d1764
YQ
13537
13538 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13539 return false;
1e4d1764
YQ
13540
13541 /* If we are in a tracing experiment, but remote stub doesn't support
13542 installing tracepoint in trace, we have to return. */
13543 if (!remote_supports_install_in_trace ())
57810aa7 13544 return false;
1e4d1764 13545
57810aa7 13546 return true;
1e4d1764
YQ
13547}
13548
13549
f6ac5f3d
PA
13550void
13551remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
13552{
13553 struct remote_state *rs = get_remote_state ();
00bf0b85 13554 char *p;
35b1e5cc 13555
8d64371b 13556 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
13557 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13558 tsv.builtin);
8d64371b
TT
13559 p = rs->buf.data () + strlen (rs->buf.data ());
13560 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13561 >= get_remote_packet_size ())
00bf0b85 13562 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 13563 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 13564 *p++ = '\0';
35b1e5cc 13565 putpkt (rs->buf);
b6bb3468 13566 remote_get_noisy_reply ();
8d64371b 13567 if (rs->buf[0] == '\0')
ad91cd99 13568 error (_("Target does not support this command."));
8d64371b 13569 if (strcmp (rs->buf.data (), "OK") != 0)
ad91cd99 13570 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13571}
13572
f6ac5f3d
PA
13573void
13574remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13575{
13576 struct remote_state *rs = get_remote_state ();
d248b706 13577
8d64371b 13578 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
53807e9f
TT
13579 location->owner->number,
13580 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13581 putpkt (rs->buf);
b6bb3468 13582 remote_get_noisy_reply ();
8d64371b 13583 if (rs->buf[0] == '\0')
d248b706 13584 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
8d64371b 13585 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13586 error (_("Error on target while enabling tracepoint."));
13587}
13588
f6ac5f3d
PA
13589void
13590remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13591{
13592 struct remote_state *rs = get_remote_state ();
d248b706 13593
8d64371b 13594 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
53807e9f
TT
13595 location->owner->number,
13596 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13597 putpkt (rs->buf);
b6bb3468 13598 remote_get_noisy_reply ();
8d64371b 13599 if (rs->buf[0] == '\0')
d248b706 13600 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
8d64371b 13601 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13602 error (_("Error on target while disabling tracepoint."));
13603}
13604
f6ac5f3d
PA
13605void
13606remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13607{
13608 asection *s;
13609 bfd_size_type size;
608bcef2 13610 bfd_vma vma;
35b1e5cc 13611 int anysecs = 0;
c2fa21f1 13612 int offset = 0;
f493c217 13613 bfd *abfd = current_program_space->exec_bfd ();
35b1e5cc 13614
f493c217 13615 if (!abfd)
35b1e5cc
SS
13616 return; /* No information to give. */
13617
b6bb3468
PA
13618 struct remote_state *rs = get_remote_state ();
13619
8d64371b
TT
13620 strcpy (rs->buf.data (), "QTro");
13621 offset = strlen (rs->buf.data ());
f493c217 13622 for (s = abfd->sections; s; s = s->next)
35b1e5cc
SS
13623 {
13624 char tmp1[40], tmp2[40];
c2fa21f1 13625 int sec_length;
35b1e5cc 13626
f493c217
AM
13627 if ((s->flags & SEC_LOAD) == 0
13628 /* || (s->flags & SEC_CODE) == 0 */
13629 || (s->flags & SEC_READONLY) == 0)
35b1e5cc
SS
13630 continue;
13631
13632 anysecs = 1;
fd361982
AM
13633 vma = bfd_section_vma (s);
13634 size = bfd_section_size (s);
f493c217
AM
13635 bfd_sprintf_vma (abfd, tmp1, vma);
13636 bfd_sprintf_vma (abfd, tmp2, vma + size);
c2fa21f1 13637 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
8d64371b 13638 if (offset + sec_length + 1 > rs->buf.size ())
c2fa21f1 13639 {
ff52c073
CS
13640 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13641 != PACKET_ENABLE)
864ac8a7 13642 warning (_("\
c2fa21f1
HZ
13643Too many sections for read-only sections definition packet."));
13644 break;
13645 }
8d64371b 13646 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
bba74b36 13647 tmp1, tmp2);
c2fa21f1 13648 offset += sec_length;
35b1e5cc
SS
13649 }
13650 if (anysecs)
13651 {
b6bb3468 13652 putpkt (rs->buf);
aa7b36b8 13653 getpkt (&rs->buf);
35b1e5cc
SS
13654 }
13655}
13656
f6ac5f3d
PA
13657void
13658remote_target::trace_start ()
35b1e5cc 13659{
b6bb3468
PA
13660 struct remote_state *rs = get_remote_state ();
13661
35b1e5cc 13662 putpkt ("QTStart");
b6bb3468 13663 remote_get_noisy_reply ();
8d64371b 13664 if (rs->buf[0] == '\0')
ad91cd99 13665 error (_("Target does not support this command."));
8d64371b
TT
13666 if (strcmp (rs->buf.data (), "OK") != 0)
13667 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13668}
13669
f6ac5f3d
PA
13670int
13671remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13672{
953b98d1 13673 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13674 char *p = NULL;
bd3eecc3 13675 enum packet_result result;
b6bb3468 13676 struct remote_state *rs = get_remote_state ();
bd3eecc3 13677
ff52c073 13678 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13679 return -1;
a744cf53 13680
7b9a15e1 13681 /* FIXME we need to get register block size some other way. */
5cd63fda 13682 trace_regblock_size
99d9c3b9 13683 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
00bf0b85 13684
049dc89b
JK
13685 putpkt ("qTStatus");
13686
a70b8144 13687 try
67f41397 13688 {
b6bb3468 13689 p = remote_get_noisy_reply ();
67f41397 13690 }
230d2906 13691 catch (const gdb_exception_error &ex)
67f41397 13692 {
598d3636
JK
13693 if (ex.error != TARGET_CLOSE_ERROR)
13694 {
13695 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13696 return -1;
13697 }
eedc3f4f 13698 throw;
67f41397 13699 }
00bf0b85 13700
ff52c073 13701 result = m_features.packet_ok (p, PACKET_qTStatus);
bd3eecc3 13702
00bf0b85 13703 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13704 if (result == PACKET_UNKNOWN)
00bf0b85 13705 return -1;
35b1e5cc 13706
00bf0b85 13707 /* We're working with a live target. */
f5911ea1 13708 ts->filename = NULL;
00bf0b85 13709
00bf0b85 13710 if (*p++ != 'T')
8d64371b 13711 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
35b1e5cc 13712
84cebc4a
YQ
13713 /* Function 'parse_trace_status' sets default value of each field of
13714 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13715 parse_trace_status (p, ts);
13716
13717 return ts->running;
35b1e5cc
SS
13718}
13719
f6ac5f3d 13720void
01bccc56 13721remote_target::get_tracepoint_status (tracepoint *tp,
f6ac5f3d 13722 struct uploaded_tp *utp)
f196051f
SS
13723{
13724 struct remote_state *rs = get_remote_state ();
f196051f 13725 char *reply;
bba74b36 13726 size_t size = get_remote_packet_size ();
f196051f
SS
13727
13728 if (tp)
13729 {
c1fc2657 13730 tp->hit_count = 0;
f196051f 13731 tp->traceframe_usage = 0;
b00b30b2 13732 for (bp_location &loc : tp->locations ())
f196051f
SS
13733 {
13734 /* If the tracepoint was never downloaded, don't go asking for
13735 any status. */
13736 if (tp->number_on_target == 0)
13737 continue;
8d64371b 13738 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
b00b30b2 13739 phex_nz (loc.address, 0));
f196051f 13740 putpkt (rs->buf);
b6bb3468 13741 reply = remote_get_noisy_reply ();
f196051f
SS
13742 if (reply && *reply)
13743 {
13744 if (*reply == 'V')
01bccc56 13745 parse_tracepoint_status (reply + 1, tp, utp);
f196051f
SS
13746 }
13747 }
13748 }
13749 else if (utp)
13750 {
13751 utp->hit_count = 0;
13752 utp->traceframe_usage = 0;
8d64371b 13753 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
bba74b36 13754 phex_nz (utp->addr, 0));
f196051f 13755 putpkt (rs->buf);
b6bb3468 13756 reply = remote_get_noisy_reply ();
f196051f
SS
13757 if (reply && *reply)
13758 {
13759 if (*reply == 'V')
01bccc56 13760 parse_tracepoint_status (reply + 1, tp, utp);
f196051f
SS
13761 }
13762 }
13763}
13764
f6ac5f3d
PA
13765void
13766remote_target::trace_stop ()
35b1e5cc 13767{
b6bb3468
PA
13768 struct remote_state *rs = get_remote_state ();
13769
35b1e5cc 13770 putpkt ("QTStop");
b6bb3468 13771 remote_get_noisy_reply ();
8d64371b 13772 if (rs->buf[0] == '\0')
ad91cd99 13773 error (_("Target does not support this command."));
8d64371b
TT
13774 if (strcmp (rs->buf.data (), "OK") != 0)
13775 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13776}
13777
f6ac5f3d
PA
13778int
13779remote_target::trace_find (enum trace_find_type type, int num,
13780 CORE_ADDR addr1, CORE_ADDR addr2,
13781 int *tpp)
35b1e5cc
SS
13782{
13783 struct remote_state *rs = get_remote_state ();
8d64371b 13784 char *endbuf = rs->buf.data () + get_remote_packet_size ();
35b1e5cc
SS
13785 char *p, *reply;
13786 int target_frameno = -1, target_tracept = -1;
13787
e6e4e701
PA
13788 /* Lookups other than by absolute frame number depend on the current
13789 trace selected, so make sure it is correct on the remote end
13790 first. */
13791 if (type != tfind_number)
13792 set_remote_traceframe ();
13793
8d64371b 13794 p = rs->buf.data ();
35b1e5cc
SS
13795 strcpy (p, "QTFrame:");
13796 p = strchr (p, '\0');
13797 switch (type)
13798 {
13799 case tfind_number:
bba74b36 13800 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13801 break;
13802 case tfind_pc:
bba74b36 13803 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13804 break;
13805 case tfind_tp:
bba74b36 13806 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13807 break;
13808 case tfind_range:
bba74b36
YQ
13809 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13810 phex_nz (addr2, 0));
35b1e5cc
SS
13811 break;
13812 case tfind_outside:
bba74b36
YQ
13813 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13814 phex_nz (addr2, 0));
35b1e5cc
SS
13815 break;
13816 default:
9b20d036 13817 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13818 }
13819
13820 putpkt (rs->buf);
b6bb3468 13821 reply = remote_get_noisy_reply ();
ad91cd99
PA
13822 if (*reply == '\0')
13823 error (_("Target does not support this command."));
35b1e5cc
SS
13824
13825 while (reply && *reply)
13826 switch (*reply)
13827 {
13828 case 'F':
f197e0f1
VP
13829 p = ++reply;
13830 target_frameno = (int) strtol (p, &reply, 16);
13831 if (reply == p)
13832 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13833 /* Don't update our remote traceframe number cache on failure
13834 to select a remote traceframe. */
f197e0f1
VP
13835 if (target_frameno == -1)
13836 return -1;
35b1e5cc
SS
13837 break;
13838 case 'T':
f197e0f1
VP
13839 p = ++reply;
13840 target_tracept = (int) strtol (p, &reply, 16);
13841 if (reply == p)
13842 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13843 break;
13844 case 'O': /* "OK"? */
13845 if (reply[1] == 'K' && reply[2] == '\0')
13846 reply += 2;
13847 else
13848 error (_("Bogus reply from target: %s"), reply);
13849 break;
13850 default:
13851 error (_("Bogus reply from target: %s"), reply);
13852 }
13853 if (tpp)
13854 *tpp = target_tracept;
e6e4e701 13855
262e1174 13856 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13857 return target_frameno;
13858}
13859
57810aa7 13860bool
f6ac5f3d 13861remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13862{
13863 struct remote_state *rs = get_remote_state ();
13864 char *reply;
13865 ULONGEST uval;
13866
e6e4e701
PA
13867 set_remote_traceframe ();
13868
8d64371b 13869 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13870 putpkt (rs->buf);
b6bb3468 13871 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13872 if (reply && *reply)
13873 {
13874 if (*reply == 'V')
13875 {
13876 unpack_varlen_hex (reply + 1, &uval);
13877 *val = (LONGEST) uval;
57810aa7 13878 return true;
35b1e5cc
SS
13879 }
13880 }
57810aa7 13881 return false;
35b1e5cc
SS
13882}
13883
f6ac5f3d
PA
13884int
13885remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13886{
13887 struct remote_state *rs = get_remote_state ();
13888 char *p, *reply;
13889
8d64371b 13890 p = rs->buf.data ();
00bf0b85
SS
13891 strcpy (p, "QTSave:");
13892 p += strlen (p);
8d64371b
TT
13893 if ((p - rs->buf.data ()) + strlen (filename) * 2
13894 >= get_remote_packet_size ())
00bf0b85 13895 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13896 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13897 *p++ = '\0';
13898 putpkt (rs->buf);
b6bb3468 13899 reply = remote_get_noisy_reply ();
d6c5869f 13900 if (*reply == '\0')
ad91cd99
PA
13901 error (_("Target does not support this command."));
13902 if (strcmp (reply, "OK") != 0)
13903 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13904 return 0;
13905}
13906
13907/* This is basically a memory transfer, but needs to be its own packet
13908 because we don't know how the target actually organizes its trace
13909 memory, plus we want to be able to ask for as much as possible, but
13910 not be unhappy if we don't get as much as we ask for. */
13911
f6ac5f3d
PA
13912LONGEST
13913remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13914{
13915 struct remote_state *rs = get_remote_state ();
13916 char *reply;
13917 char *p;
13918 int rslt;
13919
8d64371b 13920 p = rs->buf.data ();
00bf0b85
SS
13921 strcpy (p, "qTBuffer:");
13922 p += strlen (p);
13923 p += hexnumstr (p, offset);
13924 *p++ = ',';
13925 p += hexnumstr (p, len);
13926 *p++ = '\0';
13927
13928 putpkt (rs->buf);
b6bb3468 13929 reply = remote_get_noisy_reply ();
00bf0b85
SS
13930 if (reply && *reply)
13931 {
13932 /* 'l' by itself means we're at the end of the buffer and
13933 there is nothing more to get. */
13934 if (*reply == 'l')
13935 return 0;
13936
13937 /* Convert the reply into binary. Limit the number of bytes to
13938 convert according to our passed-in buffer size, rather than
13939 what was returned in the packet; if the target is
13940 unexpectedly generous and gives us a bigger reply than we
13941 asked for, we don't want to crash. */
b6bb3468 13942 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13943 return rslt;
13944 }
13945
13946 /* Something went wrong, flag as an error. */
13947 return -1;
13948}
13949
f6ac5f3d
PA
13950void
13951remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13952{
13953 struct remote_state *rs = get_remote_state ();
13954
ff52c073
CS
13955 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
13956 == PACKET_ENABLE)
33da3f1c 13957 {
ad91cd99
PA
13958 char *reply;
13959
8d64371b
TT
13960 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13961 "QTDisconnected:%x", val);
33da3f1c 13962 putpkt (rs->buf);
b6bb3468 13963 reply = remote_get_noisy_reply ();
ad91cd99 13964 if (*reply == '\0')
33da3f1c 13965 error (_("Target does not support this command."));
ad91cd99 13966 if (strcmp (reply, "OK") != 0)
dda83cd7 13967 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13968 }
13969 else if (val)
13970 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13971}
13972
f6ac5f3d
PA
13973int
13974remote_target::core_of_thread (ptid_t ptid)
dc146f7c 13975{
9213a6d7 13976 thread_info *info = this->find_thread (ptid);
a744cf53 13977
7aabaf9d
SM
13978 if (info != NULL && info->priv != NULL)
13979 return get_remote_thread_info (info)->core;
13980
dc146f7c
VP
13981 return -1;
13982}
13983
f6ac5f3d
PA
13984void
13985remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13986{
13987 struct remote_state *rs = get_remote_state ();
ad91cd99 13988 char *reply;
4daf5ac0 13989
8d64371b
TT
13990 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13991 "QTBuffer:circular:%x", val);
4daf5ac0 13992 putpkt (rs->buf);
b6bb3468 13993 reply = remote_get_noisy_reply ();
ad91cd99 13994 if (*reply == '\0')
4daf5ac0 13995 error (_("Target does not support this command."));
ad91cd99
PA
13996 if (strcmp (reply, "OK") != 0)
13997 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13998}
13999
f6ac5f3d
PA
14000traceframe_info_up
14001remote_target::traceframe_info ()
b3b9301e 14002{
9018be22 14003 gdb::optional<gdb::char_vector> text
328d42d8
SM
14004 = target_read_stralloc (current_inferior ()->top_target (),
14005 TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 14006 NULL);
9018be22
SM
14007 if (text)
14008 return parse_traceframe_info (text->data ());
b3b9301e
PA
14009
14010 return NULL;
14011}
14012
405f8e94
SS
14013/* Handle the qTMinFTPILen packet. Returns the minimum length of
14014 instruction on which a fast tracepoint may be placed. Returns -1
14015 if the packet is not supported, and 0 if the minimum instruction
14016 length is unknown. */
14017
f6ac5f3d
PA
14018int
14019remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
14020{
14021 struct remote_state *rs = get_remote_state ();
14022 char *reply;
14023
e886a173
PA
14024 /* If we're not debugging a process yet, the IPA can't be
14025 loaded. */
55f6301a 14026 if (!target_has_execution ())
e886a173
PA
14027 return 0;
14028
14029 /* Make sure the remote is pointing at the right process. */
14030 set_general_process ();
14031
8d64371b 14032 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
405f8e94 14033 putpkt (rs->buf);
b6bb3468 14034 reply = remote_get_noisy_reply ();
405f8e94
SS
14035 if (*reply == '\0')
14036 return -1;
14037 else
14038 {
14039 ULONGEST min_insn_len;
14040
14041 unpack_varlen_hex (reply, &min_insn_len);
14042
14043 return (int) min_insn_len;
14044 }
14045}
14046
f6ac5f3d
PA
14047void
14048remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 14049{
ff52c073 14050 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
14051 {
14052 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14053 char *buf = rs->buf.data ();
14054 char *endbuf = buf + get_remote_packet_size ();
f6f899bf
HAQ
14055 enum packet_result result;
14056
14057 gdb_assert (val >= 0 || val == -1);
14058 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14059 /* Send -1 as literal "-1" to avoid host size dependency. */
14060 if (val < 0)
14061 {
14062 *buf++ = '-';
dda83cd7 14063 buf += hexnumstr (buf, (ULONGEST) -val);
f6f899bf
HAQ
14064 }
14065 else
14066 buf += hexnumstr (buf, (ULONGEST) val);
14067
14068 putpkt (rs->buf);
b6bb3468 14069 remote_get_noisy_reply ();
ff52c073 14070 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
f6f899bf
HAQ
14071
14072 if (result != PACKET_OK)
8d64371b 14073 warning (_("Bogus reply from target: %s"), rs->buf.data ());
f6f899bf
HAQ
14074 }
14075}
14076
57810aa7 14077bool
f6ac5f3d
PA
14078remote_target::set_trace_notes (const char *user, const char *notes,
14079 const char *stop_notes)
f196051f
SS
14080{
14081 struct remote_state *rs = get_remote_state ();
14082 char *reply;
8d64371b
TT
14083 char *buf = rs->buf.data ();
14084 char *endbuf = buf + get_remote_packet_size ();
f196051f
SS
14085 int nbytes;
14086
14087 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14088 if (user)
14089 {
14090 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 14091 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
14092 buf += 2 * nbytes;
14093 *buf++ = ';';
14094 }
14095 if (notes)
14096 {
14097 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 14098 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
14099 buf += 2 * nbytes;
14100 *buf++ = ';';
14101 }
14102 if (stop_notes)
14103 {
14104 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 14105 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
14106 buf += 2 * nbytes;
14107 *buf++ = ';';
14108 }
14109 /* Ensure the buffer is terminated. */
14110 *buf = '\0';
14111
14112 putpkt (rs->buf);
b6bb3468 14113 reply = remote_get_noisy_reply ();
f196051f 14114 if (*reply == '\0')
57810aa7 14115 return false;
f196051f
SS
14116
14117 if (strcmp (reply, "OK") != 0)
14118 error (_("Bogus reply from target: %s"), reply);
14119
57810aa7 14120 return true;
f196051f
SS
14121}
14122
57810aa7
PA
14123bool
14124remote_target::use_agent (bool use)
d1feda86 14125{
ff52c073 14126 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
14127 {
14128 struct remote_state *rs = get_remote_state ();
14129
14130 /* If the stub supports QAgent. */
8d64371b 14131 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
d1feda86 14132 putpkt (rs->buf);
aa7b36b8 14133 getpkt (&rs->buf);
d1feda86 14134
8d64371b 14135 if (strcmp (rs->buf.data (), "OK") == 0)
d1feda86 14136 {
f6ac5f3d 14137 ::use_agent = use;
57810aa7 14138 return true;
d1feda86
YQ
14139 }
14140 }
14141
57810aa7 14142 return false;
d1feda86
YQ
14143}
14144
57810aa7 14145bool
f6ac5f3d 14146remote_target::can_use_agent ()
d1feda86 14147{
ff52c073 14148 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
14149}
14150
1bcb9dcf
MM
14151#if defined (HAVE_LIBEXPAT)
14152
14153/* Check the btrace document version. */
14154
14155static void
14156check_xml_btrace_version (struct gdb_xml_parser *parser,
14157 const struct gdb_xml_element *element,
14158 void *user_data,
14159 std::vector<gdb_xml_value> &attributes)
14160{
14161 const char *version
14162 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14163
14164 if (strcmp (version, "1.0") != 0)
14165 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14166}
14167
14168/* Parse a btrace "block" xml record. */
14169
14170static void
14171parse_xml_btrace_block (struct gdb_xml_parser *parser,
14172 const struct gdb_xml_element *element,
14173 void *user_data,
14174 std::vector<gdb_xml_value> &attributes)
14175{
14176 struct btrace_data *btrace;
14177 ULONGEST *begin, *end;
14178
14179 btrace = (struct btrace_data *) user_data;
14180
14181 switch (btrace->format)
14182 {
14183 case BTRACE_FORMAT_BTS:
14184 break;
14185
14186 case BTRACE_FORMAT_NONE:
14187 btrace->format = BTRACE_FORMAT_BTS;
14188 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14189 break;
14190
14191 default:
14192 gdb_xml_error (parser, _("Btrace format error."));
14193 }
14194
14195 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14196 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14197 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14198}
14199
14200/* Parse a "raw" xml record. */
14201
14202static void
14203parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14204 gdb_byte **pdata, size_t *psize)
14205{
14206 gdb_byte *bin;
14207 size_t len, size;
14208
14209 len = strlen (body_text);
14210 if (len % 2 != 0)
14211 gdb_xml_error (parser, _("Bad raw data size."));
14212
14213 size = len / 2;
14214
14215 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14216 bin = data.get ();
14217
14218 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14219 while (len > 0)
14220 {
14221 char hi, lo;
14222
14223 hi = *body_text++;
14224 lo = *body_text++;
14225
14226 if (hi == 0 || lo == 0)
14227 gdb_xml_error (parser, _("Bad hex encoding."));
14228
14229 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14230 len -= 2;
14231 }
14232
14233 *pdata = data.release ();
14234 *psize = size;
14235}
14236
14237/* Parse a btrace pt-config "cpu" xml record. */
14238
14239static void
14240parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14241 const struct gdb_xml_element *element,
14242 void *user_data,
14243 std::vector<gdb_xml_value> &attributes)
14244{
14245 struct btrace_data *btrace;
14246 const char *vendor;
14247 ULONGEST *family, *model, *stepping;
14248
14249 vendor
14250 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14251 family
14252 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14253 model
14254 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14255 stepping
14256 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14257
14258 btrace = (struct btrace_data *) user_data;
14259
14260 if (strcmp (vendor, "GenuineIntel") == 0)
14261 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14262
14263 btrace->variant.pt.config.cpu.family = *family;
14264 btrace->variant.pt.config.cpu.model = *model;
14265 btrace->variant.pt.config.cpu.stepping = *stepping;
14266}
14267
14268/* Parse a btrace pt "raw" xml record. */
14269
14270static void
14271parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14272 const struct gdb_xml_element *element,
14273 void *user_data, const char *body_text)
14274{
14275 struct btrace_data *btrace;
14276
14277 btrace = (struct btrace_data *) user_data;
14278 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14279 &btrace->variant.pt.size);
14280}
14281
14282/* Parse a btrace "pt" xml record. */
14283
14284static void
14285parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14286 const struct gdb_xml_element *element,
14287 void *user_data,
14288 std::vector<gdb_xml_value> &attributes)
14289{
14290 struct btrace_data *btrace;
14291
14292 btrace = (struct btrace_data *) user_data;
14293 btrace->format = BTRACE_FORMAT_PT;
14294 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14295 btrace->variant.pt.data = NULL;
14296 btrace->variant.pt.size = 0;
14297}
14298
14299static const struct gdb_xml_attribute block_attributes[] = {
14300 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14301 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14302 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14303};
14304
14305static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14306 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14307 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14308 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14309 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14310 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14311};
14312
14313static const struct gdb_xml_element btrace_pt_config_children[] = {
14314 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14315 parse_xml_btrace_pt_config_cpu, NULL },
14316 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14317};
14318
14319static const struct gdb_xml_element btrace_pt_children[] = {
14320 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14321 NULL },
14322 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14323 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14324};
14325
14326static const struct gdb_xml_attribute btrace_attributes[] = {
14327 { "version", GDB_XML_AF_NONE, NULL, NULL },
14328 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14329};
14330
14331static const struct gdb_xml_element btrace_children[] = {
14332 { "block", block_attributes, NULL,
14333 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14334 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14335 NULL },
14336 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14337};
14338
14339static const struct gdb_xml_element btrace_elements[] = {
14340 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14341 check_xml_btrace_version, NULL },
14342 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14343};
14344
14345#endif /* defined (HAVE_LIBEXPAT) */
14346
14347/* Parse a branch trace xml document XML into DATA. */
14348
14349static void
14350parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14351{
14352#if defined (HAVE_LIBEXPAT)
14353
14354 int errcode;
14355 btrace_data result;
14356 result.format = BTRACE_FORMAT_NONE;
14357
14358 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14359 buffer, &result);
14360 if (errcode != 0)
14361 error (_("Error parsing branch trace."));
14362
14363 /* Keep parse results. */
14364 *btrace = std::move (result);
14365
14366#else /* !defined (HAVE_LIBEXPAT) */
14367
14368 error (_("Cannot process branch trace. XML support was disabled at "
14369 "compile time."));
14370
14371#endif /* !defined (HAVE_LIBEXPAT) */
14372}
14373
14374#if defined (HAVE_LIBEXPAT)
14375
14376/* Parse a btrace-conf "bts" xml record. */
14377
14378static void
14379parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14380 const struct gdb_xml_element *element,
14381 void *user_data,
14382 std::vector<gdb_xml_value> &attributes)
14383{
14384 struct btrace_config *conf;
14385 struct gdb_xml_value *size;
14386
14387 conf = (struct btrace_config *) user_data;
14388 conf->format = BTRACE_FORMAT_BTS;
14389 conf->bts.size = 0;
14390
14391 size = xml_find_attribute (attributes, "size");
14392 if (size != NULL)
14393 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14394}
14395
14396/* Parse a btrace-conf "pt" xml record. */
14397
14398static void
14399parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14400 const struct gdb_xml_element *element,
14401 void *user_data,
14402 std::vector<gdb_xml_value> &attributes)
14403{
14404 struct btrace_config *conf;
14405 struct gdb_xml_value *size;
14406
14407 conf = (struct btrace_config *) user_data;
14408 conf->format = BTRACE_FORMAT_PT;
14409 conf->pt.size = 0;
14410
14411 size = xml_find_attribute (attributes, "size");
14412 if (size != NULL)
14413 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14414}
14415
14416static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14417 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14418 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14419};
14420
14421static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14422 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14423 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14424};
14425
14426static const struct gdb_xml_element btrace_conf_children[] = {
14427 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14428 parse_xml_btrace_conf_bts, NULL },
14429 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14430 parse_xml_btrace_conf_pt, NULL },
14431 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14432};
14433
14434static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14435 { "version", GDB_XML_AF_NONE, NULL, NULL },
14436 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14437};
14438
14439static const struct gdb_xml_element btrace_conf_elements[] = {
14440 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14441 GDB_XML_EF_NONE, NULL, NULL },
14442 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14443};
14444
14445#endif /* defined (HAVE_LIBEXPAT) */
14446
14447/* Parse a branch trace configuration xml document XML into CONF. */
14448
14449static void
14450parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14451{
14452#if defined (HAVE_LIBEXPAT)
14453
14454 int errcode;
14455 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14456 btrace_conf_elements, xml, conf);
14457 if (errcode != 0)
14458 error (_("Error parsing branch trace configuration."));
14459
14460#else /* !defined (HAVE_LIBEXPAT) */
14461
14462 error (_("Cannot process the branch trace configuration. XML support "
14463 "was disabled at compile time."));
14464
14465#endif /* !defined (HAVE_LIBEXPAT) */
14466}
14467
f4abbc16
MM
14468/* Reset our idea of our target's btrace configuration. */
14469
14470static void
6b8edb51 14471remote_btrace_reset (remote_state *rs)
f4abbc16 14472{
f4abbc16
MM
14473 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14474}
14475
f4abbc16
MM
14476/* Synchronize the configuration with the target. */
14477
6b8edb51
PA
14478void
14479remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 14480{
d33501a5
MM
14481 struct remote_state *rs;
14482 char *buf, *pos, *endbuf;
14483
14484 rs = get_remote_state ();
8d64371b 14485 buf = rs->buf.data ();
d33501a5
MM
14486 endbuf = buf + get_remote_packet_size ();
14487
ff52c073 14488 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
d33501a5
MM
14489 && conf->bts.size != rs->btrace_config.bts.size)
14490 {
14491 pos = buf;
ff52c073
CS
14492 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14493 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
dda83cd7 14494 conf->bts.size);
d33501a5
MM
14495
14496 putpkt (buf);
aa7b36b8 14497 getpkt (&rs->buf);
d33501a5 14498
ff52c073
CS
14499 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14500 == PACKET_ERROR)
d33501a5
MM
14501 {
14502 if (buf[0] == 'E' && buf[1] == '.')
14503 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14504 else
14505 error (_("Failed to configure the BTS buffer size."));
14506 }
14507
14508 rs->btrace_config.bts.size = conf->bts.size;
14509 }
b20a6524 14510
ff52c073 14511 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
b20a6524
MM
14512 && conf->pt.size != rs->btrace_config.pt.size)
14513 {
14514 pos = buf;
ff52c073
CS
14515 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14516 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
dda83cd7 14517 conf->pt.size);
b20a6524
MM
14518
14519 putpkt (buf);
aa7b36b8 14520 getpkt (&rs->buf);
b20a6524 14521
ff52c073
CS
14522 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14523 == PACKET_ERROR)
b20a6524
MM
14524 {
14525 if (buf[0] == 'E' && buf[1] == '.')
14526 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14527 else
14528 error (_("Failed to configure the trace buffer size."));
14529 }
14530
14531 rs->btrace_config.pt.size = conf->pt.size;
14532 }
f4abbc16
MM
14533}
14534
0d8cbc5f 14535/* Read TP's btrace configuration from the target and store it into CONF. */
f4abbc16
MM
14536
14537static void
cdda72c2 14538btrace_read_config (thread_info *tp, btrace_config *conf)
f4abbc16 14539{
0d8cbc5f
MM
14540 /* target_read_stralloc relies on INFERIOR_PTID. */
14541 scoped_restore_current_thread restore_thread;
14542 switch_to_thread (tp);
14543
9018be22 14544 gdb::optional<gdb::char_vector> xml
328d42d8
SM
14545 = target_read_stralloc (current_inferior ()->top_target (),
14546 TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
14547 if (xml)
14548 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
14549}
14550
c0272db5
TW
14551/* Maybe reopen target btrace. */
14552
6b8edb51
PA
14553void
14554remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
14555{
14556 struct remote_state *rs = get_remote_state ();
c0272db5 14557 int btrace_target_pushed = 0;
15766370 14558#if !defined (HAVE_LIBIPT)
c0272db5 14559 int warned = 0;
15766370 14560#endif
c0272db5 14561
aedbe3bb
CM
14562 /* Don't bother walking the entirety of the remote thread list when
14563 we know the feature isn't supported by the remote. */
ff52c073 14564 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
aedbe3bb
CM
14565 return;
14566
5b6d1e4f 14567 for (thread_info *tp : all_non_exited_threads (this))
c0272db5 14568 {
c0272db5 14569 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
0d8cbc5f 14570 btrace_read_config (tp, &rs->btrace_config);
c0272db5
TW
14571
14572 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14573 continue;
14574
14575#if !defined (HAVE_LIBIPT)
14576 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14577 {
14578 if (!warned)
14579 {
14580 warned = 1;
c4e12631
MM
14581 warning (_("Target is recording using Intel Processor Trace "
14582 "but support was disabled at compile time."));
c0272db5
TW
14583 }
14584
14585 continue;
14586 }
14587#endif /* !defined (HAVE_LIBIPT) */
14588
14589 /* Push target, once, but before anything else happens. This way our
14590 changes to the threads will be cleaned up by unpushing the target
14591 in case btrace_read_config () throws. */
14592 if (!btrace_target_pushed)
14593 {
14594 btrace_target_pushed = 1;
14595 record_btrace_push_target ();
6cb06a8c
TT
14596 gdb_printf (_("Target is recording using %s.\n"),
14597 btrace_format_string (rs->btrace_config.format));
c0272db5
TW
14598 }
14599
cdda72c2
MM
14600 tp->btrace.target
14601 = new btrace_target_info { tp->ptid, rs->btrace_config };
c0272db5 14602 }
c0272db5
TW
14603}
14604
9accd112
MM
14605/* Enable branch tracing. */
14606
f6ac5f3d 14607struct btrace_target_info *
696c0d5e
MM
14608remote_target::enable_btrace (thread_info *tp,
14609 const struct btrace_config *conf)
9accd112 14610{
b20a6524 14611 struct packet_config *packet = NULL;
9accd112 14612 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14613 char *buf = rs->buf.data ();
14614 char *endbuf = buf + get_remote_packet_size ();
9accd112 14615
ff52c073 14616 unsigned int which_packet;
b20a6524
MM
14617 switch (conf->format)
14618 {
14619 case BTRACE_FORMAT_BTS:
ff52c073 14620 which_packet = PACKET_Qbtrace_bts;
b20a6524 14621 break;
b20a6524 14622 case BTRACE_FORMAT_PT:
ff52c073 14623 which_packet = PACKET_Qbtrace_pt;
b20a6524 14624 break;
ff52c073
CS
14625 default:
14626 internal_error (_("Bad branch btrace format: %u."),
14627 (unsigned int) conf->format);
b20a6524
MM
14628 }
14629
ff52c073 14630 packet = &m_features.m_protocol_packets[which_packet];
b20a6524 14631 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
14632 error (_("Target does not support branch tracing."));
14633
f4abbc16
MM
14634 btrace_sync_conf (conf);
14635
696c0d5e 14636 ptid_t ptid = tp->ptid;
9accd112
MM
14637 set_general_thread (ptid);
14638
ff52c073
CS
14639 buf += xsnprintf (buf, endbuf - buf, "%s",
14640 packets_descriptions[which_packet].name);
9accd112 14641 putpkt (rs->buf);
aa7b36b8 14642 getpkt (&rs->buf);
9accd112 14643
ff52c073 14644 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
9accd112
MM
14645 {
14646 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14647 error (_("Could not enable branch tracing for %s: %s"),
a068643d 14648 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
9accd112
MM
14649 else
14650 error (_("Could not enable branch tracing for %s."),
a068643d 14651 target_pid_to_str (ptid).c_str ());
9accd112
MM
14652 }
14653
cdda72c2 14654 btrace_target_info *tinfo = new btrace_target_info { ptid };
9accd112 14655
f4abbc16
MM
14656 /* If we fail to read the configuration, we lose some information, but the
14657 tracing itself is not impacted. */
a70b8144 14658 try
492d29ea 14659 {
0d8cbc5f 14660 btrace_read_config (tp, &tinfo->conf);
492d29ea 14661 }
230d2906 14662 catch (const gdb_exception_error &err)
492d29ea
PA
14663 {
14664 if (err.message != NULL)
3d6e9d23 14665 warning ("%s", err.what ());
492d29ea 14666 }
f4abbc16 14667
9accd112
MM
14668 return tinfo;
14669}
14670
14671/* Disable branch tracing. */
14672
f6ac5f3d
PA
14673void
14674remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112 14675{
9accd112 14676 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14677 char *buf = rs->buf.data ();
14678 char *endbuf = buf + get_remote_packet_size ();
9accd112 14679
ff52c073 14680 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112
MM
14681 error (_("Target does not support branch tracing."));
14682
14683 set_general_thread (tinfo->ptid);
14684
ff52c073
CS
14685 buf += xsnprintf (buf, endbuf - buf, "%s",
14686 packets_descriptions[PACKET_Qbtrace_off].name);
9accd112 14687 putpkt (rs->buf);
aa7b36b8 14688 getpkt (&rs->buf);
9accd112 14689
ff52c073 14690 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
9accd112
MM
14691 {
14692 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14693 error (_("Could not disable branch tracing for %s: %s"),
a068643d 14694 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
9accd112
MM
14695 else
14696 error (_("Could not disable branch tracing for %s."),
a068643d 14697 target_pid_to_str (tinfo->ptid).c_str ());
9accd112
MM
14698 }
14699
cdda72c2 14700 delete tinfo;
9accd112
MM
14701}
14702
14703/* Teardown branch tracing. */
14704
f6ac5f3d
PA
14705void
14706remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
14707{
14708 /* We must not talk to the target during teardown. */
cdda72c2 14709 delete tinfo;
9accd112
MM
14710}
14711
14712/* Read the branch trace. */
14713
f6ac5f3d
PA
14714enum btrace_error
14715remote_target::read_btrace (struct btrace_data *btrace,
14716 struct btrace_target_info *tinfo,
14717 enum btrace_read_type type)
9accd112 14718{
9accd112 14719 const char *annex;
9accd112 14720
ff52c073 14721 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
14722 error (_("Target does not support branch tracing."));
14723
14724#if !defined(HAVE_LIBEXPAT)
14725 error (_("Cannot process branch tracing result. XML parsing not supported."));
14726#endif
14727
14728 switch (type)
14729 {
864089d2 14730 case BTRACE_READ_ALL:
9accd112
MM
14731 annex = "all";
14732 break;
864089d2 14733 case BTRACE_READ_NEW:
9accd112
MM
14734 annex = "new";
14735 break;
969c39fb
MM
14736 case BTRACE_READ_DELTA:
14737 annex = "delta";
14738 break;
9accd112 14739 default:
f34652de 14740 internal_error (_("Bad branch tracing read type: %u."),
9accd112
MM
14741 (unsigned int) type);
14742 }
14743
9018be22 14744 gdb::optional<gdb::char_vector> xml
328d42d8
SM
14745 = target_read_stralloc (current_inferior ()->top_target (),
14746 TARGET_OBJECT_BTRACE, annex);
9018be22 14747 if (!xml)
969c39fb 14748 return BTRACE_ERR_UNKNOWN;
9accd112 14749
9018be22 14750 parse_xml_btrace (btrace, xml->data ());
9accd112 14751
969c39fb 14752 return BTRACE_ERR_NONE;
9accd112
MM
14753}
14754
f6ac5f3d
PA
14755const struct btrace_config *
14756remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
14757{
14758 return &tinfo->conf;
14759}
14760
57810aa7 14761bool
f6ac5f3d 14762remote_target::augmented_libraries_svr4_read ()
ced63ec0 14763{
ff52c073
CS
14764 return
14765 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14766 == PACKET_ENABLE);
ced63ec0
GB
14767}
14768
9dd130a0
TT
14769/* Implementation of to_load. */
14770
f6ac5f3d
PA
14771void
14772remote_target::load (const char *name, int from_tty)
9dd130a0
TT
14773{
14774 generic_load (name, from_tty);
14775}
14776
c78fa86a
GB
14777/* Accepts an integer PID; returns a string representing a file that
14778 can be opened on the remote side to get the symbols for the child
14779 process. Returns NULL if the operation is not supported. */
14780
0e90c441 14781const char *
f6ac5f3d 14782remote_target::pid_to_exec_file (int pid)
c78fa86a 14783{
9018be22 14784 static gdb::optional<gdb::char_vector> filename;
835205d0 14785 char *annex = NULL;
c78fa86a 14786
ff52c073 14787 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
c78fa86a
GB
14788 return NULL;
14789
5b6d1e4f 14790 inferior *inf = find_inferior_pid (this, pid);
835205d0 14791 if (inf == NULL)
f34652de 14792 internal_error (_("not currently attached to process %d"), pid);
835205d0
GB
14793
14794 if (!inf->fake_pid_p)
14795 {
14796 const int annex_size = 9;
14797
224c3ddb 14798 annex = (char *) alloca (annex_size);
835205d0
GB
14799 xsnprintf (annex, annex_size, "%x", pid);
14800 }
14801
328d42d8 14802 filename = target_read_stralloc (current_inferior ()->top_target (),
c78fa86a
GB
14803 TARGET_OBJECT_EXEC_FILE, annex);
14804
9018be22 14805 return filename ? filename->data () : nullptr;
c78fa86a
GB
14806}
14807
750ce8d1
YQ
14808/* Implement the to_can_do_single_step target_ops method. */
14809
f6ac5f3d
PA
14810int
14811remote_target::can_do_single_step ()
750ce8d1
YQ
14812{
14813 /* We can only tell whether target supports single step or not by
14814 supported s and S vCont actions if the stub supports vContSupported
14815 feature. If the stub doesn't support vContSupported feature,
14816 we have conservatively to think target doesn't supports single
14817 step. */
ff52c073 14818 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
750ce8d1
YQ
14819 {
14820 struct remote_state *rs = get_remote_state ();
14821
750ce8d1
YQ
14822 return rs->supports_vCont.s && rs->supports_vCont.S;
14823 }
14824 else
14825 return 0;
14826}
14827
3a00c802
PA
14828/* Implementation of the to_execution_direction method for the remote
14829 target. */
14830
f6ac5f3d
PA
14831enum exec_direction_kind
14832remote_target::execution_direction ()
3a00c802
PA
14833{
14834 struct remote_state *rs = get_remote_state ();
14835
14836 return rs->last_resume_exec_dir;
14837}
14838
f6327dcb
KB
14839/* Return pointer to the thread_info struct which corresponds to
14840 THREAD_HANDLE (having length HANDLE_LEN). */
14841
f6ac5f3d
PA
14842thread_info *
14843remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14844 int handle_len,
14845 inferior *inf)
f6327dcb 14846{
5b6d1e4f 14847 for (thread_info *tp : all_non_exited_threads (this))
f6327dcb 14848 {
7aabaf9d 14849 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
14850
14851 if (tp->inf == inf && priv != NULL)
dda83cd7 14852 {
7aabaf9d 14853 if (handle_len != priv->thread_handle.size ())
f6327dcb 14854 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
dda83cd7 14855 handle_len, priv->thread_handle.size ());
7aabaf9d 14856 if (memcmp (thread_handle, priv->thread_handle.data (),
dda83cd7 14857 handle_len) == 0)
f6327dcb
KB
14858 return tp;
14859 }
14860 }
14861
14862 return NULL;
14863}
14864
1f08d324 14865gdb::array_view<const gdb_byte>
3d6c6204
KB
14866remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14867{
14868 remote_thread_info *priv = get_remote_thread_info (tp);
14869 return priv->thread_handle;
14870}
14871
57810aa7 14872bool
f6ac5f3d 14873remote_target::can_async_p ()
6426a772 14874{
fce6cd34
AB
14875 /* This flag should be checked in the common target.c code. */
14876 gdb_assert (target_async_permitted);
75c99385 14877
fce6cd34 14878 /* We're async whenever the serial device can. */
e84ffe7b 14879 return get_remote_state ()->can_async_p ();
6426a772
JM
14880}
14881
57810aa7 14882bool
f6ac5f3d 14883remote_target::is_async_p ()
6426a772 14884{
23860348 14885 /* We're async whenever the serial device is. */
e84ffe7b 14886 return get_remote_state ()->is_async_p ();
6426a772
JM
14887}
14888
2acceee2
JM
14889/* Pass the SERIAL event on and up to the client. One day this code
14890 will be able to delay notifying the client of an event until the
23860348 14891 point where an entire packet has been received. */
2acceee2 14892
2acceee2
JM
14893static serial_event_ftype remote_async_serial_handler;
14894
6426a772 14895static void
819cc324 14896remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14897{
2acceee2
JM
14898 /* Don't propogate error information up to the client. Instead let
14899 the client find out about the error by querying the target. */
b1a35af2 14900 inferior_event_handler (INF_REG_EVENT);
2acceee2
JM
14901}
14902
5b6d1e4f
PA
14903int
14904remote_target::async_wait_fd ()
14905{
14906 struct remote_state *rs = get_remote_state ();
14907 return rs->remote_desc->fd;
14908}
14909
f6ac5f3d 14910void
4a570176 14911remote_target::async (bool enable)
2acceee2 14912{
5d93a237
TT
14913 struct remote_state *rs = get_remote_state ();
14914
6a3753b3 14915 if (enable)
2acceee2 14916 {
88b496c3 14917 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14918
14919 /* If there are pending events in the stop reply queue tell the
14920 event loop to process them. */
953edf2b 14921 if (!rs->stop_reply_queue.empty ())
92b98b37
SM
14922 rs->mark_async_event_handler ();
14923
6efcd9a8
PA
14924 /* For simplicity, below we clear the pending events token
14925 without remembering whether it is marked, so here we always
14926 mark it. If there's actually no pending notification to
14927 process, this ends up being a no-op (other than a spurious
14928 event-loop wakeup). */
14929 if (target_is_non_stop_p ())
14930 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14931 }
14932 else
b7d2e916
PA
14933 {
14934 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14935 /* If the core is disabling async, it doesn't want to be
14936 disturbed with target events. Clear all async event sources
14937 too. */
92b98b37
SM
14938 rs->clear_async_event_handler ();
14939
6efcd9a8
PA
14940 if (target_is_non_stop_p ())
14941 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14942 }
6426a772
JM
14943}
14944
65706a29
PA
14945/* Implementation of the to_thread_events method. */
14946
f6ac5f3d
PA
14947void
14948remote_target::thread_events (int enable)
65706a29
PA
14949{
14950 struct remote_state *rs = get_remote_state ();
14951 size_t size = get_remote_packet_size ();
65706a29 14952
ff52c073 14953 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
65706a29
PA
14954 return;
14955
8d64371b 14956 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
65706a29 14957 putpkt (rs->buf);
aa7b36b8 14958 getpkt (&rs->buf);
65706a29 14959
ff52c073 14960 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
65706a29
PA
14961 {
14962 case PACKET_OK:
8d64371b
TT
14963 if (strcmp (rs->buf.data (), "OK") != 0)
14964 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
65706a29
PA
14965 break;
14966 case PACKET_ERROR:
8d64371b 14967 warning (_("Remote failure reply: %s"), rs->buf.data ());
65706a29
PA
14968 break;
14969 case PACKET_UNKNOWN:
14970 break;
14971 }
14972}
14973
d471ea57 14974static void
981a3fb3 14975show_remote_cmd (const char *args, int from_tty)
d471ea57 14976{
37a105a1 14977 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14978 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14979 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14980 struct ui_out *uiout = current_uiout;
37a105a1 14981
2e783024 14982 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14983 for (; list != NULL; list = list->next)
14984 if (strcmp (list->name, "Z-packet") == 0)
14985 continue;
427c3a89
DJ
14986 else if (list->type == not_set_cmd)
14987 /* Alias commands are exactly like the original, except they
14988 don't have the normal type. */
14989 continue;
14990 else
37a105a1 14991 {
2e783024 14992 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14993
112e8700
SM
14994 uiout->field_string ("name", list->name);
14995 uiout->text (": ");
427c3a89 14996 if (list->type == show_cmd)
f5c4fcd9 14997 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14998 else
14999 cmd_func (list, NULL, from_tty);
37a105a1 15000 }
d471ea57 15001}
5a2468f5 15002
74daa597
SM
15003/* Some change happened in PSPACE's objfile list (obfiles added or removed),
15004 offer all inferiors using that program space a change to look up symbols. */
0f71a2f6 15005
dc8acb97 15006static void
74daa597 15007remote_objfile_changed_check_symbols (program_space *pspace)
dc8acb97 15008{
06c7226e
SM
15009 /* The affected program space is possibly shared by multiple inferiors.
15010 Consider sending a qSymbol packet for each of the inferiors using that
15011 program space. */
15012 for (inferior *inf : all_inferiors ())
15013 {
15014 if (inf->pspace != pspace)
15015 continue;
122373f7 15016
06c7226e
SM
15017 /* Check whether the inferior's process target is a remote target. */
15018 remote_target *remote = as_remote_target (inf->process_target ());
15019 if (remote == nullptr)
15020 continue;
15021
15022 /* When we are attaching or handling a fork child and the shared library
15023 subsystem reads the list of loaded libraries, we receive new objfile
15024 events in between each found library. The libraries are read in an
15025 undefined order, so if we gave the remote side a chance to look up
15026 symbols between each objfile, we might give it an inconsistent picture
15027 of the inferior. It could appear that a library A appears loaded but
15028 a library B does not, even though library A requires library B. That
15029 would present a state that couldn't normally exist in the inferior.
15030
15031 So, skip these events, we'll give the remote a chance to look up
15032 symbols once all the loaded libraries and their symbols are known to
15033 GDB. */
15034 if (inf->in_initial_library_scan)
15035 continue;
15036
15037 if (!remote->has_execution (inf))
15038 continue;
15039
15040 /* Need to switch to a specific thread, because remote_check_symbols will
287de656 15041 set the general thread using INFERIOR_PTID.
122373f7 15042
06c7226e
SM
15043 It's possible to have inferiors with no thread here, because we are
15044 called very early in the connection process, while the inferior is
15045 being set up, before threads are added. Just skip it, start_remote_1
15046 also calls remote_check_symbols when it's done setting things up. */
15047 thread_info *thread = any_thread_of_inferior (inf);
15048 if (thread != nullptr)
15049 {
15050 scoped_restore_current_thread restore_thread;
15051 switch_to_thread (thread);
15052 remote->remote_check_symbols ();
15053 }
15054 }
dc8acb97
MS
15055}
15056
74daa597
SM
15057/* Function to be called whenever a new objfile (shlib) is detected. */
15058
15059static void
15060remote_new_objfile (struct objfile *objfile)
15061{
15062 remote_objfile_changed_check_symbols (objfile->pspace);
15063}
15064
00bf0b85
SS
15065/* Pull all the tracepoints defined on the target and create local
15066 data structures representing them. We don't want to create real
15067 tracepoints yet, we don't want to mess up the user's existing
15068 collection. */
7a78108a 15069
f6ac5f3d
PA
15070int
15071remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 15072{
00bf0b85
SS
15073 struct remote_state *rs = get_remote_state ();
15074 char *p;
d5551862 15075
00bf0b85
SS
15076 /* Ask for a first packet of tracepoint definition. */
15077 putpkt ("qTfP");
aa7b36b8 15078 getpkt (&rs->buf);
8d64371b 15079 p = rs->buf.data ();
00bf0b85 15080 while (*p && *p != 'l')
d5551862 15081 {
00bf0b85
SS
15082 parse_tracepoint_definition (p, utpp);
15083 /* Ask for another packet of tracepoint definition. */
15084 putpkt ("qTsP");
aa7b36b8 15085 getpkt (&rs->buf);
8d64371b 15086 p = rs->buf.data ();
d5551862 15087 }
00bf0b85 15088 return 0;
d5551862
SS
15089}
15090
f6ac5f3d
PA
15091int
15092remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 15093{
00bf0b85 15094 struct remote_state *rs = get_remote_state ();
d5551862 15095 char *p;
d5551862 15096
00bf0b85
SS
15097 /* Ask for a first packet of variable definition. */
15098 putpkt ("qTfV");
aa7b36b8 15099 getpkt (&rs->buf);
8d64371b 15100 p = rs->buf.data ();
00bf0b85 15101 while (*p && *p != 'l')
d5551862 15102 {
00bf0b85
SS
15103 parse_tsv_definition (p, utsvp);
15104 /* Ask for another packet of variable definition. */
15105 putpkt ("qTsV");
aa7b36b8 15106 getpkt (&rs->buf);
8d64371b 15107 p = rs->buf.data ();
d5551862 15108 }
00bf0b85 15109 return 0;
d5551862
SS
15110}
15111
c1e36e3e
PA
15112/* The "set/show range-stepping" show hook. */
15113
15114static void
15115show_range_stepping (struct ui_file *file, int from_tty,
15116 struct cmd_list_element *c,
15117 const char *value)
15118{
6cb06a8c
TT
15119 gdb_printf (file,
15120 _("Debugger's willingness to use range stepping "
15121 "is %s.\n"), value);
c1e36e3e
PA
15122}
15123
6b8edb51
PA
15124/* Return true if the vCont;r action is supported by the remote
15125 stub. */
15126
15127bool
15128remote_target::vcont_r_supported ()
15129{
ff52c073 15130 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
6b8edb51
PA
15131 && get_remote_state ()->supports_vCont.r);
15132}
15133
c1e36e3e
PA
15134/* The "set/show range-stepping" set hook. */
15135
15136static void
eb4c3f4a 15137set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
15138 struct cmd_list_element *c)
15139{
6b8edb51
PA
15140 /* When enabling, check whether range stepping is actually supported
15141 by the target, and warn if not. */
c1e36e3e
PA
15142 if (use_range_stepping)
15143 {
6b8edb51
PA
15144 remote_target *remote = get_current_remote_target ();
15145 if (remote == NULL
15146 || !remote->vcont_r_supported ())
15147 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
15148 }
15149}
15150
baf2b57f
SM
15151static void
15152show_remote_debug (struct ui_file *file, int from_tty,
15153 struct cmd_list_element *c, const char *value)
15154{
6cb06a8c
TT
15155 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15156 value);
baf2b57f
SM
15157}
15158
15159static void
15160show_remote_timeout (struct ui_file *file, int from_tty,
15161 struct cmd_list_element *c, const char *value)
15162{
6cb06a8c
TT
15163 gdb_printf (file,
15164 _("Timeout limit to wait for target to respond is %s.\n"),
15165 value);
baf2b57f
SM
15166}
15167
dbe692af
LM
15168/* Implement the "supports_memory_tagging" target_ops method. */
15169
15170bool
15171remote_target::supports_memory_tagging ()
15172{
ff52c073 15173 return m_features.remote_memory_tagging_p ();
2c2e7f87
LM
15174}
15175
15176/* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15177
15178static void
15179create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15180 size_t len, int type)
15181{
99d9c3b9 15182 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
2c2e7f87
LM
15183
15184 std::string request = string_printf ("qMemTags:%s,%s:%s",
15185 phex_nz (address, addr_size),
15186 phex_nz (len, sizeof (len)),
15187 phex_nz (type, sizeof (type)));
15188
15189 strcpy (packet.data (), request.c_str ());
15190}
15191
15192/* Parse the qMemTags packet reply into TAGS.
15193
15194 Return true if successful, false otherwise. */
15195
15196static bool
15197parse_fetch_memtags_reply (const gdb::char_vector &reply,
15198 gdb::byte_vector &tags)
15199{
15200 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15201 return false;
15202
15203 /* Copy the tag data. */
15204 tags = hex2bin (reply.data () + 1);
15205
15206 return true;
15207}
15208
15209/* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15210
15211static void
15212create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15213 size_t len, int type,
15214 const gdb::byte_vector &tags)
15215{
99d9c3b9 15216 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
2c2e7f87
LM
15217
15218 /* Put together the main packet, address and length. */
15219 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15220 phex_nz (address, addr_size),
15221 phex_nz (len, sizeof (len)),
15222 phex_nz (type, sizeof (type)));
15223 request += bin2hex (tags.data (), tags.size ());
15224
15225 /* Check if we have exceeded the maximum packet size. */
15226 if (packet.size () < request.length ())
15227 error (_("Contents too big for packet QMemTags."));
15228
15229 strcpy (packet.data (), request.c_str ());
dbe692af
LM
15230}
15231
15232/* Implement the "fetch_memtags" target_ops method. */
15233
15234bool
15235remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15236 gdb::byte_vector &tags, int type)
15237{
2c2e7f87 15238 /* Make sure the qMemTags packet is supported. */
ff52c073 15239 if (!m_features.remote_memory_tagging_p ())
2c2e7f87
LM
15240 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15241
15242 struct remote_state *rs = get_remote_state ();
15243
15244 create_fetch_memtags_request (rs->buf, address, len, type);
15245
15246 putpkt (rs->buf);
aa7b36b8 15247 getpkt (&rs->buf);
2c2e7f87
LM
15248
15249 return parse_fetch_memtags_reply (rs->buf, tags);
dbe692af
LM
15250}
15251
15252/* Implement the "store_memtags" target_ops method. */
15253
15254bool
15255remote_target::store_memtags (CORE_ADDR address, size_t len,
15256 const gdb::byte_vector &tags, int type)
15257{
2c2e7f87 15258 /* Make sure the QMemTags packet is supported. */
ff52c073 15259 if (!m_features.remote_memory_tagging_p ())
2c2e7f87
LM
15260 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15261
15262 struct remote_state *rs = get_remote_state ();
15263
15264 create_store_memtags_request (rs->buf, address, len, type, tags);
15265
15266 putpkt (rs->buf);
aa7b36b8 15267 getpkt (&rs->buf);
2c2e7f87
LM
15268
15269 /* Verify if the request was successful. */
15270 return packet_check_result (rs->buf.data ()) == PACKET_OK;
dbe692af
LM
15271}
15272
c39ebbf4
TV
15273/* Return true if remote target T is non-stop. */
15274
15275bool
15276remote_target_is_non_stop_p (remote_target *t)
15277{
15278 scoped_restore_current_thread restore_thread;
15279 switch_to_target_no_thread (t);
15280
15281 return target_is_non_stop_p ();
15282}
15283
754487e2
LM
15284#if GDB_SELF_TEST
15285
15286namespace selftests {
15287
15288static void
15289test_memory_tagging_functions ()
15290{
15291 remote_target remote;
15292
15293 struct packet_config *config
ff52c073 15294 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
754487e2
LM
15295
15296 scoped_restore restore_memtag_support_
15297 = make_scoped_restore (&config->support);
15298
15299 /* Test memory tagging packet support. */
15300 config->support = PACKET_SUPPORT_UNKNOWN;
15301 SELF_CHECK (remote.supports_memory_tagging () == false);
15302 config->support = PACKET_DISABLE;
15303 SELF_CHECK (remote.supports_memory_tagging () == false);
15304 config->support = PACKET_ENABLE;
15305 SELF_CHECK (remote.supports_memory_tagging () == true);
15306
15307 /* Setup testing. */
15308 gdb::char_vector packet;
15309 gdb::byte_vector tags, bv;
15310 std::string expected, reply;
15311 packet.resize (32000);
15312
15313 /* Test creating a qMemTags request. */
15314
15315 expected = "qMemTags:0,0:0";
15316 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15317 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15318
15319 expected = "qMemTags:deadbeef,10:1";
15320 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15321 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15322
15323 /* Test parsing a qMemTags reply. */
15324
15325 /* Error reply, tags vector unmodified. */
15326 reply = "E00";
15327 strcpy (packet.data (), reply.c_str ());
15328 tags.resize (0);
15329 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15330 SELF_CHECK (tags.size () == 0);
15331
15332 /* Valid reply, tags vector updated. */
15333 tags.resize (0);
15334 bv.resize (0);
15335
15336 for (int i = 0; i < 5; i++)
15337 bv.push_back (i);
15338
15339 reply = "m" + bin2hex (bv.data (), bv.size ());
15340 strcpy (packet.data (), reply.c_str ());
15341
15342 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15343 SELF_CHECK (tags.size () == 5);
15344
15345 for (int i = 0; i < 5; i++)
15346 SELF_CHECK (tags[i] == i);
15347
15348 /* Test creating a QMemTags request. */
15349
15350 /* Empty tag data. */
15351 tags.resize (0);
15352 expected = "QMemTags:0,0:0:";
15353 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15354 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15355 expected.length ()) == 0);
15356
15357 /* Non-empty tag data. */
15358 tags.resize (0);
15359 for (int i = 0; i < 5; i++)
15360 tags.push_back (i);
15361 expected = "QMemTags:deadbeef,ff:1:0001020304";
15362 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15363 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15364 expected.length ()) == 0);
15365}
15366
15367} // namespace selftests
15368#endif /* GDB_SELF_TEST */
15369
6c265988 15370void _initialize_remote ();
c906108c 15371void
6c265988 15372_initialize_remote ()
c906108c 15373{
d9f719f1
PA
15374 add_target (remote_target_info, remote_target::open);
15375 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 15376
dc8acb97 15377 /* Hook into new objfile notification. */
c90e7d63 15378 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
74daa597
SM
15379 gdb::observers::all_objfiles_removed.attach
15380 (remote_objfile_changed_check_symbols, "remote");
dc8acb97 15381
c906108c
SS
15382#if 0
15383 init_remote_threadtests ();
15384#endif
15385
23860348 15386 /* set/show remote ... */
d471ea57 15387
0743fc83 15388 add_basic_prefix_cmd ("remote", class_maintenance, _("\
590042fc 15389Remote protocol specific variables.\n\
5a2468f5 15390Configure various remote-protocol specific variables such as\n\
590042fc 15391the packets being used."),
2f822da5 15392 &remote_set_cmdlist,
0743fc83 15393 0 /* allow-unknown */, &setlist);
1bedd215 15394 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
590042fc 15395Remote protocol specific variables.\n\
5a2468f5 15396Configure various remote-protocol specific variables such as\n\
590042fc 15397the packets being used."),
2f822da5 15398 &remote_show_cmdlist,
23860348 15399 0 /* allow-unknown */, &showlist);
5a2468f5 15400
1a966eab
AC
15401 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15402Compare section data on target to the exec file.\n\
95cf3b38
DT
15403Argument is a single section name (default: all loaded sections).\n\
15404To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
15405 &cmdlist);
15406
e5b176f2 15407 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
1a966eab 15408Send an arbitrary packet to a remote target.\n\
c906108c
SS
15409 maintenance packet TEXT\n\
15410If GDB is talking to an inferior via the GDB serial protocol, then\n\
15411this command sends the string TEXT to the inferior, and displays the\n\
15412response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 15413terminating `#' character and checksum."),
c906108c
SS
15414 &maintenancelist);
15415
9f260536
SM
15416 set_show_commands remotebreak_cmds
15417 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7915a72c
AC
15418Set whether to send break if interrupted."), _("\
15419Show whether to send break if interrupted."), _("\
15420If set, a break, instead of a cntrl-c, is sent to the remote target."),
9f260536
SM
15421 set_remotebreak, show_remotebreak,
15422 &setlist, &showlist);
15423 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15424 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
9a7071a8
JB
15425
15426 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
15427 interrupt_sequence_modes, &interrupt_sequence_mode,
15428 _("\
9a7071a8
JB
15429Set interrupt sequence to remote target."), _("\
15430Show interrupt sequence to remote target."), _("\
15431Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15432 NULL, show_interrupt_sequence,
15433 &remote_set_cmdlist,
15434 &remote_show_cmdlist);
15435
15436 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15437 &interrupt_on_connect, _("\
590042fc
PW
15438Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15439Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
9a7071a8
JB
15440If set, interrupt sequence is sent to remote target."),
15441 NULL, NULL,
15442 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 15443
23860348 15444 /* Install commands for configuring memory read/write packets. */
11cf8741 15445
1a966eab
AC
15446 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15447Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 15448 &setlist);
1a966eab
AC
15449 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15450Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
15451 &showlist);
15452 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
15453 set_memory_write_packet_size, _("\
15454Set the maximum number of bytes per memory-write packet.\n\
15455Specify the number of bytes in a packet or 0 (zero) for the\n\
15456default packet size. The actual limit is further reduced\n\
fe4c3ca0
CS
15457dependent on the target. Specify \"fixed\" to disable the\n\
15458further restriction and \"limit\" to enable that restriction."),
11cf8741
JM
15459 &remote_set_cmdlist);
15460 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
15461 set_memory_read_packet_size, _("\
15462Set the maximum number of bytes per memory-read packet.\n\
15463Specify the number of bytes in a packet or 0 (zero) for the\n\
15464default packet size. The actual limit is further reduced\n\
fe4c3ca0
CS
15465dependent on the target. Specify \"fixed\" to disable the\n\
15466further restriction and \"limit\" to enable that restriction."),
11cf8741
JM
15467 &remote_set_cmdlist);
15468 add_cmd ("memory-write-packet-size", no_class,
15469 show_memory_write_packet_size,
1a966eab 15470 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
15471 &remote_show_cmdlist);
15472 add_cmd ("memory-read-packet-size", no_class,
15473 show_memory_read_packet_size,
1a966eab 15474 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 15475 &remote_show_cmdlist);
c906108c 15476
055303e2 15477 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
15478 &remote_hw_watchpoint_limit, _("\
15479Set the maximum number of target hardware watchpoints."), _("\
15480Show the maximum number of target hardware watchpoints."), _("\
055303e2
AB
15481Specify \"unlimited\" for unlimited hardware watchpoints."),
15482 NULL, show_hardware_watchpoint_limit,
15483 &remote_set_cmdlist,
15484 &remote_show_cmdlist);
15485 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15486 no_class,
480a3f21
PW
15487 &remote_hw_watchpoint_length_limit, _("\
15488Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15489Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
055303e2
AB
15490Specify \"unlimited\" to allow watchpoints of unlimited size."),
15491 NULL, show_hardware_watchpoint_length_limit,
480a3f21 15492 &remote_set_cmdlist, &remote_show_cmdlist);
055303e2 15493 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
15494 &remote_hw_breakpoint_limit, _("\
15495Set the maximum number of target hardware breakpoints."), _("\
15496Show the maximum number of target hardware breakpoints."), _("\
055303e2
AB
15497Specify \"unlimited\" for unlimited hardware breakpoints."),
15498 NULL, show_hardware_breakpoint_limit,
b3f42336 15499 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 15500
1b493192
PA
15501 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15502 &remote_address_size, _("\
4d28ad1e
AC
15503Set the maximum size of the address (in bits) in a memory packet."), _("\
15504Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
15505 NULL,
15506 NULL, /* FIXME: i18n: */
15507 &setlist, &showlist);
c906108c 15508
ca4f7f8b
PA
15509 init_all_packet_configs ();
15510
ff52c073 15511 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
0f71a2f6 15512
ff52c073 15513 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
506fb367 15514
ff52c073
CS
15515 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15516 0);
89be2091 15517
ff52c073
CS
15518 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15519 "catch-syscalls", 0);
82075af2 15520
ff52c073
CS
15521 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15522 "program-signals", 0);
9b224c5e 15523
ff52c073
CS
15524 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15525 "set-working-dir", 0);
bc3b087d 15526
ff52c073
CS
15527 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15528 "startup-with-shell", 0);
aefd8b33 15529
ff52c073
CS
15530 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15531 "environment-hex-encoded", 0);
0a2dde4a 15532
ff52c073
CS
15533 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15534 "environment-reset", 0);
0a2dde4a 15535
ff52c073
CS
15536 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15537 "environment-unset", 0);
0a2dde4a 15538
ff52c073 15539 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
dc8acb97 15540
ff52c073 15541 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
d471ea57 15542
ff52c073 15543 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
b96ec7ac 15544
ff52c073 15545 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
d471ea57 15546
ff52c073 15547 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
d471ea57 15548
ff52c073 15549 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
d471ea57 15550
ff52c073 15551 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
d471ea57 15552
ff52c073 15553 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
d471ea57 15554
ff52c073
CS
15555 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15556 "read-aux-vector", 0);
802188a7 15557
ff52c073
CS
15558 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15559 "pid-to-exec-file", 0);
c78fa86a 15560
ff52c073 15561 add_packet_config_cmd (PACKET_qXfer_features,
23181151
DJ
15562 "qXfer:features:read", "target-features", 0);
15563
ff52c073
CS
15564 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15565 "library-info", 0);
cfa9d6d9 15566
ff52c073 15567 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
2268b414
JK
15568 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15569
ff52c073
CS
15570 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15571 "memory-map", 0);
fd79ecee 15572
ff52c073 15573 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
07e059b5 15574
ff52c073
CS
15575 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15576 0);
dc146f7c 15577
ff52c073
CS
15578 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15579 "read-siginfo-object", 0);
4aa995e1 15580
ff52c073
CS
15581 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15582 "write-siginfo-object", 0);
4aa995e1 15583
ff52c073
CS
15584 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15585 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 15586
ff52c073
CS
15587 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15588 "unwind-info-block", 0);
169081d0 15589
ff52c073
CS
15590 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15591 "get-thread-local-storage-address", 0);
38691318 15592
ff52c073
CS
15593 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15594 "get-thread-information-block-address", 0);
711e434b 15595
ff52c073 15596 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
40ab02ce 15597
ff52c073 15598 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
40ab02ce 15599
ff52c073
CS
15600 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15601 0);
be2a5f71 15602
ff52c073
CS
15603 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15604 "search-memory", 0);
08388c79 15605
ff52c073 15606 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
bd3eecc3 15607
ff52c073 15608 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15a201c8 15609
ff52c073 15610 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
a6b151f1 15611
ff52c073 15612 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
a6b151f1 15613
ff52c073
CS
15614 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15615 0);
a6b151f1 15616
ff52c073 15617 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
a6b151f1 15618
ff52c073
CS
15619 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15620 0);
a6b151f1 15621
ff52c073
CS
15622 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15623 "hostio-readlink", 0);
b9e7b9c3 15624
ff52c073 15625 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
0a93529c 15626
ff52c073 15627 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
2d717e4f 15628
ff52c073 15629 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
2d717e4f 15630
ff52c073 15631 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
a6f3e723 15632
ff52c073 15633 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
82f73884 15634
ff52c073 15635 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
0b16c5cf 15636
ff52c073
CS
15637 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15638 "ConditionalTracepoints", "conditional-tracepoints",
15639 0);
3788aec7 15640
ff52c073
CS
15641 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15642 "ConditionalBreakpoints", "conditional-breakpoints",
15643 0);
3788aec7 15644
ff52c073 15645 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
d3ce09f5
SS
15646 "breakpoint-commands", 0);
15647
ff52c073
CS
15648 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15649 "fast-tracepoints", 0);
782b2b07 15650
ff52c073
CS
15651 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15652 "TracepointSource", 0);
409873ef 15653
ff52c073 15654 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
d914c394 15655
ff52c073
CS
15656 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15657 "static-tracepoints", 0);
0fb4aa4b 15658
ff52c073
CS
15659 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15660 "install-in-trace", 0);
1e4d1764 15661
ff52c073 15662 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
dda83cd7 15663 "qXfer:statictrace:read", "read-sdata-object", 0);
0fb4aa4b 15664
ff52c073
CS
15665 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15666 "read-fdpic-loadmap", 0);
78d85199 15667
ff52c073
CS
15668 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15669 "disable-randomization", 0);
03583c20 15670
ff52c073 15671 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
d1feda86 15672
ff52c073
CS
15673 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15674 "trace-buffer-size", 0);
f6f899bf 15675
ff52c073
CS
15676 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15677 0);
9accd112 15678
ff52c073
CS
15679 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15680 0);
b20a6524 15681
ff52c073
CS
15682 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15683 0);
9accd112 15684
ff52c073 15685 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
9accd112 15686
ff52c073
CS
15687 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15688 "read-btrace-conf", 0);
f4abbc16 15689
ff52c073
CS
15690 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15691 "btrace-conf-bts-size", 0);
d33501a5 15692
ff52c073
CS
15693 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15694 "multiprocess-feature", 0);
73b8c1fd 15695
ff52c073
CS
15696 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15697 "swbreak-feature", 0);
f7e6eed5 15698
ff52c073
CS
15699 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15700 "hwbreak-feature", 0);
f7e6eed5 15701
ff52c073
CS
15702 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15703 "fork-event-feature", 0);
89245bc0 15704
ff52c073
CS
15705 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15706 "vfork-event-feature", 0);
89245bc0 15707
ff52c073
CS
15708 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15709 "btrace-conf-pt-size", 0);
b20a6524 15710
ff52c073
CS
15711 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15712 "verbose-resume-supported", 0);
750ce8d1 15713
ff52c073
CS
15714 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15715 "exec-event-feature", 0);
94585166 15716
ff52c073 15717 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
de979965 15718
ff52c073
CS
15719 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15720 0);
65706a29 15721
ff52c073
CS
15722 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15723 "no-resumed-stop-reply", 0);
f2faf941 15724
ff52c073 15725 add_packet_config_cmd (PACKET_memory_tagging_feature,
2c2e7f87
LM
15726 "memory-tagging-feature", "memory-tagging-feature", 0);
15727
0b736949
DB
15728 /* Assert that we've registered "set remote foo-packet" commands
15729 for all packet configs. */
ca4f7f8b
PA
15730 {
15731 int i;
15732
15733 for (i = 0; i < PACKET_MAX; i++)
15734 {
15735 /* Ideally all configs would have a command associated. Some
15736 still don't though. */
15737 int excepted;
15738
15739 switch (i)
15740 {
15741 case PACKET_QNonStop:
ca4f7f8b
PA
15742 case PACKET_EnableDisableTracepoints_feature:
15743 case PACKET_tracenz_feature:
15744 case PACKET_DisconnectedTracing_feature:
15745 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
15746 case PACKET_qCRC:
15747 /* Additions to this list need to be well justified:
15748 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
15749 excepted = 1;
15750 break;
15751 default:
15752 excepted = 0;
15753 break;
15754 }
15755
15756 /* This catches both forgetting to add a config command, and
15757 forgetting to remove a packet from the exception list. */
ff52c073 15758 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
ca4f7f8b
PA
15759 }
15760 }
15761
37a105a1
DJ
15762 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15763 Z sub-packet has its own set and show commands, but users may
15764 have sets to this variable in their .gdbinit files (or in their
15765 documentation). */
e9e68a56 15766 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c 15767 &remote_Z_packet_detect, _("\
590042fc
PW
15768Set use of remote protocol `Z' packets."), _("\
15769Show use of remote protocol `Z' packets."), _("\
3b64bf98 15770When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 15771packets."),
e9e68a56 15772 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
15773 show_remote_protocol_Z_packet_cmd,
15774 /* FIXME: i18n: Use of remote protocol
15775 `Z' packets is %s. */
e9e68a56 15776 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 15777
0743fc83 15778 add_basic_prefix_cmd ("remote", class_files, _("\
590042fc 15779Manipulate files on the remote system.\n\
a6b151f1 15780Transfer files to and from the remote target system."),
2f822da5 15781 &remote_cmdlist,
0743fc83 15782 0 /* allow-unknown */, &cmdlist);
a6b151f1
DJ
15783
15784 add_cmd ("put", class_files, remote_put_command,
15785 _("Copy a local file to the remote system."),
15786 &remote_cmdlist);
15787
15788 add_cmd ("get", class_files, remote_get_command,
15789 _("Copy a remote file to the local system."),
15790 &remote_cmdlist);
15791
15792 add_cmd ("delete", class_files, remote_delete_command,
15793 _("Delete a remote file."),
15794 &remote_cmdlist);
15795
2d717e4f 15796 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 15797 &remote_exec_file_var, _("\
590042fc
PW
15798Set the remote pathname for \"run\"."), _("\
15799Show the remote pathname for \"run\"."), NULL,
94585166
DB
15800 set_remote_exec_file,
15801 show_remote_exec_file,
15802 &remote_set_cmdlist,
15803 &remote_show_cmdlist);
2d717e4f 15804
c1e36e3e
PA
15805 add_setshow_boolean_cmd ("range-stepping", class_run,
15806 &use_range_stepping, _("\
15807Enable or disable range stepping."), _("\
15808Show whether target-assisted range stepping is enabled."), _("\
15809If on, and the target supports it, when stepping a source line, GDB\n\
15810tells the target to step the corresponding range of addresses itself instead\n\
15811of issuing multiple single-steps. This speeds up source level\n\
15812stepping. If off, GDB always issues single-steps, even if range\n\
15813stepping is supported by the target. The default is on."),
15814 set_range_stepping,
15815 show_range_stepping,
15816 &setlist,
15817 &showlist);
15818
ed2b7c17
TT
15819 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15820Set watchdog timer."), _("\
15821Show watchdog timer."), _("\
15822When non-zero, this timeout is used instead of waiting forever for a target\n\
15823to finish a low-level step or continue operation. If the specified amount\n\
15824of time passes without a response from the target, an error occurs."),
15825 NULL,
15826 show_watchdog,
15827 &setlist, &showlist);
15828
6cc8564b
LM
15829 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15830 &remote_packet_max_chars, _("\
15831Set the maximum number of characters to display for each remote packet."), _("\
15832Show the maximum number of characters to display for each remote packet."), _("\
15833Specify \"unlimited\" to display all the characters."),
15834 NULL, show_remote_packet_max_chars,
15835 &setdebuglist, &showdebuglist);
15836
02349803
SM
15837 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15838 _("Set debugging of remote protocol."),
15839 _("Show debugging of remote protocol."),
15840 _("\
baf2b57f
SM
15841When enabled, each packet sent or received with the remote target\n\
15842is displayed."),
02349803
SM
15843 NULL,
15844 show_remote_debug,
15845 &setdebuglist, &showdebuglist);
baf2b57f
SM
15846
15847 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15848 &remote_timeout, _("\
15849Set timeout limit to wait for target to respond."), _("\
15850Show timeout limit to wait for target to respond."), _("\
15851This value is used to set the time limit for gdb to wait for a response\n\
15852from the target."),
15853 NULL,
15854 show_remote_timeout,
15855 &setlist, &showlist);
15856
449092f6 15857 /* Eventually initialize fileio. See fileio.c */
3f4d92eb 15858 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
754487e2
LM
15859
15860#if GDB_SELF_TEST
15861 selftests::register_test ("remote_memory_tagging",
15862 selftests::test_memory_tagging_functions);
15863#endif
c906108c 15864}