]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
Automatic date update in version.in
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
d01e8234 3 Copyright (C) 1988-2025 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
SS
22#include <ctype.h>
23#include <fcntl.h>
05d9d66d 24#include "exceptions.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"
5b9707eb 31#include "cli/cli-cmds.h"
c906108c 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"
9e69a2e1 42#include "cli/cli-style.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
268a13a5
TT
45#include "gdbsupport/filestuff.h"
46#include "gdbsupport/rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
268a13a5 50#include "gdbsupport/gdb_sys_time.h"
c906108c 51
400b5eca 52#include "gdbsupport/event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
7e10abd1 59#include "gdbcore.h"
6240bebf 60
449092f6 61#include "remote-fileio.h"
198f946f 62#include "gdbsupport/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
268a13a5 71#include "gdbsupport/agent.h"
9accd112 72#include "btrace.h"
c0272db5 73#include "record-btrace.h"
268a13a5
TT
74#include "gdbsupport/scoped_restore.h"
75#include "gdbsupport/environ.h"
76#include "gdbsupport/byte-vector.h"
4a72de73 77#include "gdbsupport/search.h"
39ef2f62 78#include <algorithm>
ff52c073 79#include <iterator>
93b54c8e 80#include "async-event.h"
754487e2 81#include "gdbsupport/selftest.h"
5260dcf0 82#include "cli/cli-style.h"
bd036f03 83#include "gdbsupport/remote-args.h"
35b1e5cc 84
f6ac5f3d
PA
85/* The remote target. */
86
d9f719f1
PA
87static const char remote_doc[] = N_("\
88Use a remote computer via a serial line, using a gdb-specific protocol.\n\
89Specify the serial device it is connected to\n\
90(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
91
cda09ec9
SM
92/* See remote.h */
93
02349803 94bool remote_debug = false;
cda09ec9 95
6b8edb51
PA
96#define OPAQUETHREADBYTES 8
97
98/* a 64 bit opaque identifier */
99typedef unsigned char threadref[OPAQUETHREADBYTES];
100
101struct gdb_ext_thread_info;
102struct threads_listing_context;
103typedef int (*rmt_thread_action) (threadref *ref, void *context);
104struct protocol_feature;
105struct packet_reg;
106
107struct stop_reply;
32603266 108typedef std::unique_ptr<stop_reply> stop_reply_up;
6b8edb51
PA
109
110/* Generic configuration support for packets the stub optionally
111 supports. Allows the user to specify the use of the packet as well
112 as allowing GDB to auto-detect support in the remote stub. */
113
114enum packet_support
115 {
116 PACKET_SUPPORT_UNKNOWN = 0,
117 PACKET_ENABLE,
118 PACKET_DISABLE
119 };
120
ff52c073
CS
121/* Convert the packet support auto_boolean to a name used for gdb printing. */
122
123static const char *
124get_packet_support_name (auto_boolean support)
125{
126 switch (support)
127 {
128 case AUTO_BOOLEAN_TRUE:
129 return "on";
130 case AUTO_BOOLEAN_FALSE:
131 return "off";
132 case AUTO_BOOLEAN_AUTO:
133 return "auto";
134 default:
135 gdb_assert_not_reached ("invalid var_auto_boolean");
136 }
137}
138
139/* Convert the target type (future remote target or currently connected target)
140 to a name used for gdb printing. */
141
142static const char *
143get_target_type_name (bool target_connected)
144{
145 if (target_connected)
146 return _("on the current remote target");
147 else
148 return _("on future remote targets");
149}
150
6b8edb51
PA
151/* Analyze a packet's return value and update the packet config
152 accordingly. */
153
7e9d8a36 154enum packet_status
6b8edb51
PA
155{
156 PACKET_ERROR,
157 PACKET_OK,
158 PACKET_UNKNOWN
159};
160
7e9d8a36
AH
161/* Keeps packet's return value. If packet's return value is PACKET_ERROR,
162 err_msg contains an error message string from E.string or the number
163 stored as a string from E.num. */
33befefc 164class packet_result
7e9d8a36 165{
33befefc
PA
166private:
167 /* Private ctors for internal use. Clients should use the public
168 factory static methods instead. */
169
170 /* Construct a PACKET_ERROR packet_result. */
171 packet_result (const char *err_msg, bool textual_err_msg)
172 : m_status (PACKET_ERROR),
173 m_err_msg (err_msg),
174 m_textual_err_msg (textual_err_msg)
175 {}
7e9d8a36 176
33befefc 177 /* Construct an PACKET_OK/PACKET_UNKNOWN packet_result. */
7e9d8a36
AH
178 explicit packet_result (enum packet_status status)
179 : m_status (status)
180 {
181 gdb_assert (status != PACKET_ERROR);
182 }
183
33befefc 184public:
7e9d8a36
AH
185 enum packet_status status () const
186 {
187 return this->m_status;
188 }
189
190 const char *err_msg () const
191 {
192 gdb_assert (this->m_status == PACKET_ERROR);
193 return this->m_err_msg.c_str ();
194 }
195
33befefc
PA
196 bool textual_err_msg () const
197 {
198 gdb_assert (this->m_status == PACKET_ERROR);
199 return this->m_textual_err_msg;
200 }
201
202 static packet_result make_numeric_error (const char *err_msg)
203 {
204 return packet_result (err_msg, false);
205 }
206
207 static packet_result make_textual_error (const char *err_msg)
208 {
209 return packet_result (err_msg, true);
210 }
211
212 static packet_result make_ok ()
213 {
214 return packet_result (PACKET_OK);
215 }
216
217 static packet_result make_unknown ()
218 {
219 return packet_result (PACKET_UNKNOWN);
220 }
221
7e9d8a36
AH
222private:
223 enum packet_status m_status;
224 std::string m_err_msg;
33befefc
PA
225
226 /* True if we have a textual error message, from an "E.MESSAGE"
227 response. */
89457440 228 bool m_textual_err_msg = false;
7e9d8a36
AH
229};
230
ff52c073
CS
231/* Enumeration of packets for a remote target. */
232
233enum {
234 PACKET_vCont = 0,
235 PACKET_X,
e16e6389 236 PACKET_x,
ff52c073
CS
237 PACKET_qSymbol,
238 PACKET_P,
239 PACKET_p,
240 PACKET_Z0,
241 PACKET_Z1,
242 PACKET_Z2,
243 PACKET_Z3,
244 PACKET_Z4,
245 PACKET_vFile_setfs,
246 PACKET_vFile_open,
247 PACKET_vFile_pread,
248 PACKET_vFile_pwrite,
249 PACKET_vFile_close,
250 PACKET_vFile_unlink,
251 PACKET_vFile_readlink,
252 PACKET_vFile_fstat,
3055e3d2 253 PACKET_vFile_stat,
2c91540a 254 PACKET_vFile_lstat,
ff52c073
CS
255 PACKET_qXfer_auxv,
256 PACKET_qXfer_features,
257 PACKET_qXfer_exec_file,
258 PACKET_qXfer_libraries,
259 PACKET_qXfer_libraries_svr4,
260 PACKET_qXfer_memory_map,
261 PACKET_qXfer_osdata,
262 PACKET_qXfer_threads,
263 PACKET_qXfer_statictrace_read,
264 PACKET_qXfer_traceframe_info,
265 PACKET_qXfer_uib,
266 PACKET_qGetTIBAddr,
267 PACKET_qGetTLSAddr,
268 PACKET_qSupported,
269 PACKET_qTStatus,
270 PACKET_QPassSignals,
271 PACKET_QCatchSyscalls,
272 PACKET_QProgramSignals,
273 PACKET_QSetWorkingDir,
274 PACKET_QStartupWithShell,
275 PACKET_QEnvironmentHexEncoded,
276 PACKET_QEnvironmentReset,
277 PACKET_QEnvironmentUnset,
278 PACKET_qCRC,
279 PACKET_qSearch_memory,
280 PACKET_vAttach,
281 PACKET_vRun,
282 PACKET_QStartNoAckMode,
283 PACKET_vKill,
284 PACKET_qXfer_siginfo_read,
285 PACKET_qXfer_siginfo_write,
286 PACKET_qAttached,
287
288 /* Support for conditional tracepoints. */
289 PACKET_ConditionalTracepoints,
290
291 /* Support for target-side breakpoint conditions. */
292 PACKET_ConditionalBreakpoints,
293
294 /* Support for target-side breakpoint commands. */
295 PACKET_BreakpointCommands,
296
297 /* Support for fast tracepoints. */
298 PACKET_FastTracepoints,
299
300 /* Support for static tracepoints. */
301 PACKET_StaticTracepoints,
302
303 /* Support for installing tracepoints while a trace experiment is
304 running. */
305 PACKET_InstallInTrace,
306
307 PACKET_bc,
308 PACKET_bs,
309 PACKET_TracepointSource,
310 PACKET_QAllow,
311 PACKET_qXfer_fdpic,
312 PACKET_QDisableRandomization,
313 PACKET_QAgent,
314 PACKET_QTBuffer_size,
315 PACKET_Qbtrace_off,
316 PACKET_Qbtrace_bts,
317 PACKET_Qbtrace_pt,
318 PACKET_qXfer_btrace,
319
320 /* Support for the QNonStop packet. */
321 PACKET_QNonStop,
322
323 /* Support for the QThreadEvents packet. */
324 PACKET_QThreadEvents,
325
65c459ab
PA
326 /* Support for the QThreadOptions packet. */
327 PACKET_QThreadOptions,
328
ff52c073
CS
329 /* Support for multi-process extensions. */
330 PACKET_multiprocess_feature,
331
332 /* Support for enabling and disabling tracepoints while a trace
333 experiment is running. */
334 PACKET_EnableDisableTracepoints_feature,
335
336 /* Support for collecting strings using the tracenz bytecode. */
337 PACKET_tracenz_feature,
338
339 /* Support for continuing to run a trace experiment while GDB is
340 disconnected. */
341 PACKET_DisconnectedTracing_feature,
342
343 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
344 PACKET_augmented_libraries_svr4_read_feature,
345
346 /* Support for the qXfer:btrace-conf:read packet. */
347 PACKET_qXfer_btrace_conf,
348
349 /* Support for the Qbtrace-conf:bts:size packet. */
350 PACKET_Qbtrace_conf_bts_size,
351
352 /* Support for swbreak+ feature. */
353 PACKET_swbreak_feature,
354
355 /* Support for hwbreak+ feature. */
356 PACKET_hwbreak_feature,
357
358 /* Support for fork events. */
359 PACKET_fork_event_feature,
360
361 /* Support for vfork events. */
362 PACKET_vfork_event_feature,
363
364 /* Support for the Qbtrace-conf:pt:size packet. */
365 PACKET_Qbtrace_conf_pt_size,
366
ccc48080
FW
367 /* Support for the Qbtrace-conf:pt:ptwrite packet. */
368 PACKET_Qbtrace_conf_pt_ptwrite,
369
13b3a89b
FW
370 /* Support for the Qbtrace-conf:pt:event-tracing packet. */
371 PACKET_Qbtrace_conf_pt_event_tracing,
372
ff52c073
CS
373 /* Support for exec events. */
374 PACKET_exec_event_feature,
375
376 /* Support for query supported vCont actions. */
377 PACKET_vContSupported,
378
379 /* Support remote CTRL-C. */
380 PACKET_vCtrlC,
381
382 /* Support TARGET_WAITKIND_NO_RESUMED. */
383 PACKET_no_resumed,
384
385 /* Support for memory tagging, allocation tag fetch/store
386 packets and the tag violation stop replies. */
387 PACKET_memory_tagging_feature,
388
c040e0b1
GR
389 /* Support for the qIsAddressTagged packet. */
390 PACKET_qIsAddressTagged,
391
ddb3f3d8
AH
392 /* Support for accepting error message in a E.errtext format.
393 This allows every remote packet to return E.errtext.
394
395 This feature only exists to fix a backwards compatibility issue
396 with the qRcmd and m packets. Historically, these two packets didn't
397 support E.errtext style errors, but when this feature is on
398 these two packets can receive E.errtext style errors.
399
400 All new packets should be written to always accept E.errtext style
401 errors, and so they should not need to check for this feature. */
402 PACKET_accept_error_message,
403
ff52c073
CS
404 PACKET_MAX
405};
406
6b8edb51 407struct threads_listing_context;
3c69da40
PA
408
409/* Stub vCont actions support.
410
411 Each field is a boolean flag indicating whether the stub reports
412 support for the corresponding action. */
413
414struct vCont_action_support
415{
416 /* vCont;t */
417 bool t = false;
418
419 /* vCont;r */
420 bool r = false;
421
422 /* vCont;s */
423 bool s = false;
424
425 /* vCont;S */
426 bool S = false;
427};
428
405feb71 429/* About this many threadids fit in a packet. */
3c69da40
PA
430
431#define MAXTHREADLISTRESULTS 32
432
433/* Data for the vFile:pread readahead cache. */
434
435struct readahead_cache
436{
437 /* Invalidate the readahead cache. */
438 void invalidate ();
439
440 /* Invalidate the readahead cache if it is holding data for FD. */
441 void invalidate_fd (int fd);
442
443 /* Serve pread from the readahead cache. Returns number of bytes
444 read, or 0 if the request can't be served from the cache. */
445 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
446
447 /* The file descriptor for the file that is being cached. -1 if the
448 cache is invalid. */
449 int fd = -1;
450
451 /* The offset into the file that the cache buffer corresponds
452 to. */
453 ULONGEST offset = 0;
454
455 /* The buffer holding the cache contents. */
6b19f38a 456 gdb::byte_vector buf;
3c69da40
PA
457
458 /* Cache hit and miss counters. */
459 ULONGEST hit_count = 0;
460 ULONGEST miss_count = 0;
461};
462
463/* Description of the remote protocol for a given architecture. */
464
465struct packet_reg
466{
467 long offset; /* Offset into G packet. */
468 long regnum; /* GDB's internal register number. */
469 LONGEST pnum; /* Remote protocol register number. */
480a1156 470 bool in_g_packet; /* Always part of G packet. */
99d9c3b9 471 /* long size in bytes; == register_size (arch, regnum);
3c69da40 472 at present. */
99d9c3b9 473 /* char *name; == gdbarch_register_name (arch, regnum);
3c69da40
PA
474 at present. */
475};
476
477struct remote_arch_state
478{
479 explicit remote_arch_state (struct gdbarch *gdbarch);
480
481 /* Description of the remote protocol registers. */
482 long sizeof_g_packet;
483
484 /* Description of the remote protocol registers indexed by REGNUM
485 (making an array gdbarch_num_regs in size). */
486 std::unique_ptr<packet_reg[]> regs;
487
488 /* This is the size (in chars) of the first response to the ``g''
489 packet. It is used as a heuristic when determining the maximum
490 size of memory-read and memory-write packets. A target will
491 typically only reserve a buffer large enough to hold the ``g''
492 packet. The size does not include packet overhead (headers and
493 trailers). */
494 long actual_register_packet_size;
495
496 /* This is the maximum size (in chars) of a non read/write packet.
497 It is also used as a cap on the size of read/write packets. */
498 long remote_packet_size;
499};
500
501/* Description of the remote protocol state for the currently
502 connected target. This is per-target state, and independent of the
503 selected architecture. */
504
505class remote_state
506{
507public:
508
509 remote_state ();
510 ~remote_state ();
511
512 /* Get the remote arch state for GDBARCH. */
513 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
514
92b98b37
SM
515 void create_async_event_handler ()
516 {
517 gdb_assert (m_async_event_handler_token == nullptr);
518 m_async_event_handler_token
519 = ::create_async_event_handler ([] (gdb_client_data data)
520 {
521 inferior_event_handler (INF_REG_EVENT);
522 },
523 nullptr, "remote");
524 }
525
526 void mark_async_event_handler ()
635b2dd9
SM
527 {
528 gdb_assert (this->is_async_p ());
529 ::mark_async_event_handler (m_async_event_handler_token);
530 }
92b98b37
SM
531
532 void clear_async_event_handler ()
533 { ::clear_async_event_handler (m_async_event_handler_token); }
534
535 bool async_event_handler_marked () const
536 { return ::async_event_handler_marked (m_async_event_handler_token); }
537
538 void delete_async_event_handler ()
539 {
540 if (m_async_event_handler_token != nullptr)
541 ::delete_async_event_handler (&m_async_event_handler_token);
542 }
543
e84ffe7b
SM
544 bool is_async_p () const
545 {
546 /* We're async whenever the serial device is. */
547 gdb_assert (this->remote_desc != nullptr);
548 return serial_is_async_p (this->remote_desc);
549 }
550
551 bool can_async_p () const
552 {
553 /* We can async whenever the serial device can. */
554 gdb_assert (this->remote_desc != nullptr);
555 return serial_can_async_p (this->remote_desc);
556 }
557
3c69da40
PA
558public: /* data */
559
560 /* A buffer to use for incoming packets, and its current size. The
561 buffer is grown dynamically for larger incoming packets.
562 Outgoing packets may also be constructed in this buffer.
8d64371b 563 The size of the buffer is always at least REMOTE_PACKET_SIZE;
3c69da40
PA
564 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
565 packets. */
8d64371b 566 gdb::char_vector buf;
3c69da40
PA
567
568 /* True if we're going through initial connection setup (finding out
569 about the remote side's threads, relocating symbols, etc.). */
570 bool starting_up = false;
571
572 /* If we negotiated packet size explicitly (and thus can bypass
573 heuristics for the largest packet size that will not overflow
574 a buffer in the stub), this will be set to that packet size.
575 Otherwise zero, meaning to use the guessed size. */
576 long explicit_packet_size = 0;
577
3c69da40
PA
578 /* True, if in no ack mode. That is, neither GDB nor the stub will
579 expect acks from each other. The connection is assumed to be
580 reliable. */
581 bool noack_mode = false;
582
583 /* True if we're connected in extended remote mode. */
584 bool extended = false;
585
586 /* True if we resumed the target and we're waiting for the target to
587 stop. In the mean time, we can't start another command/query.
588 The remote server wouldn't be ready to process it, so we'd
589 timeout waiting for a reply that would never come and eventually
590 we'd close the connection. This can happen in asynchronous mode
591 because we allow GDB commands while the target is running. */
592 bool waiting_for_stop_reply = false;
593
594 /* The status of the stub support for the various vCont actions. */
595 vCont_action_support supports_vCont;
596
597 /* True if the user has pressed Ctrl-C, but the target hasn't
598 responded to that. */
599 bool ctrlc_pending_p = false;
600
601 /* True if we saw a Ctrl-C while reading or writing from/to the
602 remote descriptor. At that point it is not safe to send a remote
603 interrupt packet, so we instead remember we saw the Ctrl-C and
604 process it once we're done with sending/receiving the current
605 packet, which should be shortly. If however that takes too long,
606 and the user presses Ctrl-C again, we offer to disconnect. */
607 bool got_ctrlc_during_io = false;
608
609 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
610 remote_open knows that we don't have a file open when the program
611 starts. */
612 struct serial *remote_desc = nullptr;
613
614 /* These are the threads which we last sent to the remote system. The
615 TID member will be -1 for all or -2 for not sent yet. */
616 ptid_t general_thread = null_ptid;
617 ptid_t continue_thread = null_ptid;
618
619 /* This is the traceframe which we last selected on the remote system.
620 It will be -1 if no traceframe is selected. */
621 int remote_traceframe_number = -1;
622
623 char *last_pass_packet = nullptr;
624
625 /* The last QProgramSignals packet sent to the target. We bypass
626 sending a new program signals list down to the target if the new
627 packet is exactly the same as the last we sent. IOW, we only let
628 the target know about program signals list changes. */
629 char *last_program_signals_packet = nullptr;
630
26f047ce
PA
631 /* Similarly, the last QThreadEvents state we sent to the
632 target. */
633 bool last_thread_events = false;
634
3c69da40
PA
635 gdb_signal last_sent_signal = GDB_SIGNAL_0;
636
637 bool last_sent_step = false;
638
639 /* The execution direction of the last resume we got. */
640 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
641
642 char *finished_object = nullptr;
643 char *finished_annex = nullptr;
644 ULONGEST finished_offset = 0;
645
646 /* Should we try the 'ThreadInfo' query packet?
647
648 This variable (NOT available to the user: auto-detect only!)
649 determines whether GDB will use the new, simpler "ThreadInfo"
650 query or the older, more complex syntax for thread queries.
651 This is an auto-detect variable (set to true at each connect,
652 and set to false when the target fails to recognize it). */
653 bool use_threadinfo_query = false;
654 bool use_threadextra_query = false;
655
656 threadref echo_nextthread {};
657 threadref nextthread {};
658 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
659
660 /* The state of remote notification. */
661 struct remote_notif_state *notif_state = nullptr;
662
663 /* The branch trace configuration. */
664 struct btrace_config btrace_config {};
665
666 /* The argument to the last "vFile:setfs:" packet we sent, used
667 to avoid sending repeated unnecessary "vFile:setfs:" packets.
668 Initialized to -1 to indicate that no "vFile:setfs:" packet
669 has yet been sent. */
670 int fs_pid = -1;
671
672 /* A readahead cache for vFile:pread. Often, reading a binary
673 involves a sequence of small reads. E.g., when parsing an ELF
674 file. A readahead cache helps mostly the case of remote
675 debugging on a connection with higher latency, due to the
676 request/reply nature of the RSP. We only cache data for a single
677 file descriptor at a time. */
678 struct readahead_cache readahead_cache;
679
680 /* The list of already fetched and acknowledged stop events. This
681 queue is used for notification Stop, and other notifications
682 don't need queue for their events, because the notification
683 events of Stop can't be consumed immediately, so that events
684 should be queued first, and be consumed by remote_wait_{ns,as}
685 one per time. Other notifications can consume their events
686 immediately, so queue is not needed for them. */
953edf2b 687 std::vector<stop_reply_up> stop_reply_queue;
3c69da40 688
3c69da40
PA
689 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
690 ``forever'' still use the normal timeout mechanism. This is
8f6606b6 691 currently used by the ASYNC code to guarantee that target reads
3c69da40
PA
692 during the initial connect always time-out. Once getpkt has been
693 modified to return a timeout indication and, in turn
694 remote_wait()/wait_for_inferior() have gained a timeout parameter
695 this can go away. */
8756b726 696 bool wait_forever_enabled_p = true;
3c69da40 697
65c459ab
PA
698 /* The set of thread options the target reported it supports, via
699 qSupported. */
700 gdb_thread_options supported_thread_options = 0;
701
94aedcf7
TJB
702 /* Contains the regnums of the expedited registers in the last stop
703 reply packet. */
8c830ad9 704 gdb::unordered_set<int> last_seen_expedited_registers;
94aedcf7 705
3c69da40 706private:
92b98b37
SM
707 /* Asynchronous signal handle registered as event loop source for
708 when we have pending events ready to be passed to the core. */
709 async_event_handler *m_async_event_handler_token = nullptr;
710
3c69da40
PA
711 /* Mapping of remote protocol data for each gdbarch. Usually there
712 is only one entry here, though we may see more with stubs that
713 support multi-process. */
8c830ad9 714 gdb::unordered_map<struct gdbarch *, remote_arch_state>
3c69da40
PA
715 m_arch_states;
716};
6b8edb51 717
d9f719f1
PA
718static const target_info remote_target_info = {
719 "remote",
ae9adb36 720 N_("Remote target using gdb-specific protocol"),
d9f719f1
PA
721 remote_doc
722};
723
ff52c073
CS
724/* Description of a remote packet. */
725
726struct packet_description
727{
728 /* Name of the packet used for gdb output. */
729 const char *name;
730
731 /* Title of the packet, used by the set/show remote name-packet
732 commands to identify the individual packages and gdb output. */
733 const char *title;
734};
735
736/* Configuration of a remote packet. */
737
738struct packet_config
739{
740 /* If auto, GDB auto-detects support for this packet or feature,
741 either through qSupported, or by trying the packet and looking
742 at the response. If true, GDB assumes the target supports this
743 packet. If false, the packet is disabled. Configs that don't
744 have an associated command always have this set to auto. */
745 enum auto_boolean detect;
746
747 /* Does the target support this packet? */
748 enum packet_support support;
749};
750
fe4c3ca0
CS
751/* User configurable variables for the number of characters in a
752 memory read/write packet. MIN (rsa->remote_packet_size,
753 rsa->sizeof_g_packet) is the default. Some targets need smaller
754 values (fifo overruns, et.al.) and some users need larger values
755 (speed up transfers). The variables ``preferred_*'' (the user
756 request), ``current_*'' (what was actually set) and ``forced_*''
757 (Positive - a soft limit, negative - a hard limit). */
758
759struct memory_packet_config
760{
761 const char *name;
762 long size;
763 int fixed_p;
764};
765
766/* These global variables contain the default configuration for every new
767 remote_feature object. */
768static memory_packet_config memory_read_packet_config =
769{
770 "memory-read-packet-size",
771};
772static memory_packet_config memory_write_packet_config =
773{
774 "memory-write-packet-size",
775};
776
ff52c073
CS
777/* This global array contains packet descriptions (name and title). */
778static packet_description packets_descriptions[PACKET_MAX];
779/* This global array contains the default configuration for every new
780 per-remote target array. */
781static packet_config remote_protocol_packets[PACKET_MAX];
782
783/* Description of a remote target's features. It stores the configuration
784 and provides functions to determine supported features of the target. */
785
786struct remote_features
787{
788 remote_features ()
789 {
fe4c3ca0
CS
790 m_memory_read_packet_config = memory_read_packet_config;
791 m_memory_write_packet_config = memory_write_packet_config;
792
ff52c073
CS
793 std::copy (std::begin (remote_protocol_packets),
794 std::end (remote_protocol_packets),
795 std::begin (m_protocol_packets));
796 }
797 ~remote_features () = default;
798
799 DISABLE_COPY_AND_ASSIGN (remote_features);
800
801 /* Returns whether a given packet defined by its enum value is supported. */
802 enum packet_support packet_support (int) const;
803
804 /* Returns the packet's corresponding "set remote foo-packet" command
805 state. See struct packet_config for more details. */
806 enum auto_boolean packet_set_cmd_state (int packet) const
807 { return m_protocol_packets[packet].detect; }
808
809 /* Returns true if the multi-process extensions are in effect. */
810 int remote_multi_process_p () const
811 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
812
813 /* Returns true if fork events are supported. */
814 int remote_fork_event_p () const
815 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
816
817 /* Returns true if vfork events are supported. */
818 int remote_vfork_event_p () const
819 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
820
821 /* Returns true if exec events are supported. */
822 int remote_exec_event_p () const
823 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
824
825 /* Returns true if memory tagging is supported, false otherwise. */
826 bool remote_memory_tagging_p () const
827 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
828
829 /* Reset all packets back to "unknown support". Called when opening a
830 new connection to a remote target. */
831 void reset_all_packet_configs_support ();
832
833/* Check result value in BUF for packet WHICH_PACKET and update the packet's
834 support configuration accordingly. */
94a94c90
AH
835 packet_result packet_ok (const char *buf, const int which_packet);
836 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
ff52c073 837
fe4c3ca0
CS
838 /* Configuration of a remote target's memory read packet. */
839 memory_packet_config m_memory_read_packet_config;
840 /* Configuration of a remote target's memory write packet. */
841 memory_packet_config m_memory_write_packet_config;
842
ff52c073
CS
843 /* The per-remote target array which stores a remote's packet
844 configurations. */
845 packet_config m_protocol_packets[PACKET_MAX];
846};
847
3b3dac9b 848class remote_target : public process_stratum_target
f6ac5f3d
PA
849{
850public:
3b3dac9b 851 remote_target () = default;
6b8edb51 852 ~remote_target () override;
f6ac5f3d 853
d9f719f1
PA
854 const target_info &info () const override
855 { return remote_target_info; }
f6ac5f3d 856
121b3efd
PA
857 const char *connection_string () override;
858
f6ac5f3d
PA
859 thread_control_capabilities get_thread_control_capabilities () override
860 { return tc_schedlock; }
861
d9f719f1
PA
862 /* Open a remote connection. */
863 static void open (const char *, int);
864
f6ac5f3d
PA
865 void close () override;
866
867 void detach (inferior *, int) override;
868 void disconnect (const char *, int) override;
869
65c459ab
PA
870 void commit_requested_thread_options ();
871
1192f124 872 void commit_resumed () override;
f6ac5f3d 873 void resume (ptid_t, int, enum gdb_signal) override;
b60cea74 874 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
b4b1a226 875 bool has_pending_events () override;
f6ac5f3d
PA
876
877 void fetch_registers (struct regcache *, int) override;
878 void store_registers (struct regcache *, int) override;
879 void prepare_to_store (struct regcache *) override;
880
f6ac5f3d
PA
881 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
882
883 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
884 enum remove_bp_reason) override;
885
886
57810aa7
PA
887 bool stopped_by_sw_breakpoint () override;
888 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 889
57810aa7 890 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 891
57810aa7 892 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 893
57810aa7 894 bool stopped_by_watchpoint () override;
f6ac5f3d 895
57810aa7 896 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 897
57810aa7 898 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
899
900 int can_use_hw_breakpoint (enum bptype, int, int) override;
901
902 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
903
904 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
905
906 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
907
908 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
909 struct expression *) override;
910
911 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
912 struct expression *) override;
913
914 void kill () override;
915
916 void load (const char *, int) override;
917
918 void mourn_inferior () override;
919
adc6a863 920 void pass_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d
PA
921
922 int set_syscall_catchpoint (int, bool, int,
923 gdb::array_view<const int>) override;
924
adc6a863 925 void program_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d 926
57810aa7 927 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
928
929 const char *thread_name (struct thread_info *) override;
930
931 void update_thread_list () override;
932
a068643d 933 std::string pid_to_str (ptid_t) override;
f6ac5f3d
PA
934
935 const char *extra_thread_info (struct thread_info *) override;
936
c80e29db 937 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
f6ac5f3d
PA
938
939 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
940 int handle_len,
941 inferior *inf) override;
942
1f08d324
TV
943 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
944 override;
3d6c6204 945
f6ac5f3d
PA
946 void stop (ptid_t) override;
947
948 void interrupt () override;
949
950 void pass_ctrlc () override;
951
952 enum target_xfer_status xfer_partial (enum target_object object,
953 const char *annex,
954 gdb_byte *readbuf,
955 const gdb_byte *writebuf,
956 ULONGEST offset, ULONGEST len,
957 ULONGEST *xfered_len) override;
958
959 ULONGEST get_memory_xfer_limit () override;
960
961 void rcmd (const char *command, struct ui_file *output) override;
962
0e90c441 963 const char *pid_to_exec_file (int pid) override;
f6ac5f3d
PA
964
965 void log_command (const char *cmd) override
966 {
967 serial_log_command (this, cmd);
968 }
969
970 CORE_ADDR get_thread_local_address (ptid_t ptid,
971 CORE_ADDR load_module_addr,
972 CORE_ADDR offset) override;
973
57810aa7 974 bool can_execute_reverse () override;
f6ac5f3d
PA
975
976 std::vector<mem_region> memory_map () override;
977
978 void flash_erase (ULONGEST address, LONGEST length) override;
979
980 void flash_done () override;
981
982 const struct target_desc *read_description () override;
983
984 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
985 const gdb_byte *pattern, ULONGEST pattern_len,
986 CORE_ADDR *found_addrp) override;
987
57810aa7 988 bool can_async_p () override;
f6ac5f3d 989
57810aa7 990 bool is_async_p () override;
f6ac5f3d 991
4a570176 992 void async (bool) override;
f6ac5f3d 993
5b6d1e4f
PA
994 int async_wait_fd () override;
995
2db17c87 996 void thread_events (bool) override;
f6ac5f3d 997
65c459ab
PA
998 bool supports_set_thread_options (gdb_thread_options) override;
999
f6ac5f3d
PA
1000 int can_do_single_step () override;
1001
1002 void terminal_inferior () override;
1003
1004 void terminal_ours () override;
1005
57810aa7 1006 bool supports_non_stop () override;
f6ac5f3d 1007
57810aa7 1008 bool supports_multi_process () override;
f6ac5f3d 1009
57810aa7 1010 bool supports_disable_randomization () override;
f6ac5f3d 1011
57810aa7 1012 bool filesystem_is_local () override;
f6ac5f3d
PA
1013
1014
1015 int fileio_open (struct inferior *inf, const char *filename,
1016 int flags, int mode, int warn_if_slow,
b872057a 1017 fileio_error *target_errno) override;
f6ac5f3d
PA
1018
1019 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 1020 ULONGEST offset, fileio_error *target_errno) override;
f6ac5f3d
PA
1021
1022 int fileio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 1023 ULONGEST offset, fileio_error *target_errno) override;
f6ac5f3d 1024
b872057a 1025 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
f6ac5f3d 1026
5d560402
AB
1027 int fileio_lstat (struct inferior *inf, const char *filename,
1028 struct stat *sb, fileio_error *target_errno) override;
3055e3d2 1029
b872057a 1030 int fileio_close (int fd, fileio_error *target_errno) override;
f6ac5f3d
PA
1031
1032 int fileio_unlink (struct inferior *inf,
1033 const char *filename,
b872057a 1034 fileio_error *target_errno) override;
f6ac5f3d 1035
6b09f134 1036 std::optional<std::string>
f6ac5f3d
PA
1037 fileio_readlink (struct inferior *inf,
1038 const char *filename,
b872057a 1039 fileio_error *target_errno) override;
f6ac5f3d 1040
57810aa7 1041 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 1042
57810aa7 1043 bool supports_string_tracing () override;
f6ac5f3d 1044
ff52c073
CS
1045 int remote_supports_cond_tracepoints ();
1046
57810aa7 1047 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 1048
ff52c073
CS
1049 int remote_supports_fast_tracepoints ();
1050
1051 int remote_supports_static_tracepoints ();
1052
1053 int remote_supports_install_in_trace ();
1054
57810aa7 1055 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
1056
1057 void trace_init () override;
1058
1059 void download_tracepoint (struct bp_location *location) override;
1060
57810aa7 1061 bool can_download_tracepoint () override;
f6ac5f3d
PA
1062
1063 void download_trace_state_variable (const trace_state_variable &tsv) override;
1064
1065 void enable_tracepoint (struct bp_location *location) override;
1066
1067 void disable_tracepoint (struct bp_location *location) override;
1068
1069 void trace_set_readonly_regions () override;
1070
1071 void trace_start () override;
1072
1073 int get_trace_status (struct trace_status *ts) override;
1074
01bccc56 1075 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
f6ac5f3d
PA
1076 override;
1077
1078 void trace_stop () override;
1079
1080 int trace_find (enum trace_find_type type, int num,
1081 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
1082
57810aa7 1083 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
1084
1085 int save_trace_data (const char *filename) override;
1086
1087 int upload_tracepoints (struct uploaded_tp **utpp) override;
1088
1089 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
1090
1091 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
1092
1093 int get_min_fast_tracepoint_insn_len () override;
1094
1095 void set_disconnected_tracing (int val) override;
1096
1097 void set_circular_trace_buffer (int val) override;
1098
1099 void set_trace_buffer_size (LONGEST val) override;
1100
57810aa7
PA
1101 bool set_trace_notes (const char *user, const char *notes,
1102 const char *stopnotes) override;
f6ac5f3d
PA
1103
1104 int core_of_thread (ptid_t ptid) override;
1105
1106 int verify_memory (const gdb_byte *data,
1107 CORE_ADDR memaddr, ULONGEST size) override;
1108
1109
57810aa7 1110 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
1111
1112 void set_permissions () override;
1113
1114 bool static_tracepoint_marker_at (CORE_ADDR,
1115 struct static_tracepoint_marker *marker)
1116 override;
1117
1118 std::vector<static_tracepoint_marker>
1119 static_tracepoint_markers_by_strid (const char *id) override;
1120
1121 traceframe_info_up traceframe_info () override;
1122
57810aa7
PA
1123 bool use_agent (bool use) override;
1124 bool can_use_agent () override;
f6ac5f3d 1125
696c0d5e
MM
1126 struct btrace_target_info *
1127 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
f6ac5f3d
PA
1128
1129 void disable_btrace (struct btrace_target_info *tinfo) override;
1130
1131 void teardown_btrace (struct btrace_target_info *tinfo) override;
1132
1133 enum btrace_error read_btrace (struct btrace_data *data,
1134 struct btrace_target_info *btinfo,
1135 enum btrace_read_type type) override;
1136
1137 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 1138 bool augmented_libraries_svr4_read () override;
82d1f134 1139 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
53de5394 1140 void follow_clone (ptid_t child_ptid) override;
294c36eb 1141 void follow_exec (inferior *, ptid_t, const char *) override;
f6ac5f3d
PA
1142 int insert_fork_catchpoint (int) override;
1143 int remove_fork_catchpoint (int) override;
1144 int insert_vfork_catchpoint (int) override;
1145 int remove_vfork_catchpoint (int) override;
1146 int insert_exec_catchpoint (int) override;
1147 int remove_exec_catchpoint (int) override;
1148 enum exec_direction_kind execution_direction () override;
1149
dbe692af
LM
1150 bool supports_memory_tagging () override;
1151
1152 bool fetch_memtags (CORE_ADDR address, size_t len,
1153 gdb::byte_vector &tags, int type) override;
1154
1155 bool store_memtags (CORE_ADDR address, size_t len,
1156 const gdb::byte_vector &tags, int type) override;
1157
7202f41f
GR
1158 bool is_address_tagged (gdbarch *gdbarch, CORE_ADDR address) override;
1159
6b8edb51
PA
1160public: /* Remote specific methods. */
1161
1162 void remote_download_command_source (int num, ULONGEST addr,
1163 struct command_line *cmds);
1164
1165 void remote_file_put (const char *local_file, const char *remote_file,
1166 int from_tty);
1167 void remote_file_get (const char *remote_file, const char *local_file,
1168 int from_tty);
1169 void remote_file_delete (const char *remote_file, int from_tty);
1170
1171 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 1172 ULONGEST offset, fileio_error *remote_errno);
6b8edb51 1173 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 1174 ULONGEST offset, fileio_error *remote_errno);
6b8edb51 1175 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
b872057a 1176 ULONGEST offset, fileio_error *remote_errno);
6b8edb51
PA
1177
1178 int remote_hostio_send_command (int command_bytes, int which_packet,
b872057a 1179 fileio_error *remote_errno, const char **attachment,
6b8edb51
PA
1180 int *attachment_len);
1181 int remote_hostio_set_filesystem (struct inferior *inf,
b872057a 1182 fileio_error *remote_errno);
6b8edb51
PA
1183 /* We should get rid of this and use fileio_open directly. */
1184 int remote_hostio_open (struct inferior *inf, const char *filename,
1185 int flags, int mode, int warn_if_slow,
b872057a
SM
1186 fileio_error *remote_errno);
1187 int remote_hostio_close (int fd, fileio_error *remote_errno);
6b8edb51
PA
1188
1189 int remote_hostio_unlink (inferior *inf, const char *filename,
b872057a 1190 fileio_error *remote_errno);
6b8edb51
PA
1191
1192 struct remote_state *get_remote_state ();
1193
1194 long get_remote_packet_size (void);
1195 long get_memory_packet_size (struct memory_packet_config *config);
1196
1197 long get_memory_write_packet_size ();
1198 long get_memory_read_packet_size ();
1199
1200 char *append_pending_thread_resumptions (char *p, char *endp,
1201 ptid_t ptid);
d9f719f1 1202 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d 1203 void start_remote (int from_tty, int extended_p);
00431a78 1204 void remote_detach_1 (struct inferior *inf, int from_tty);
6b8edb51
PA
1205
1206 char *append_resumption (char *p, char *endp,
1207 ptid_t ptid, int step, gdb_signal siggnal);
d51926f0 1208 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
6b8edb51
PA
1209 gdb_signal siggnal);
1210
64d38fdd 1211 thread_info *add_current_inferior_and_thread (const char *wait_status);
6b8edb51
PA
1212
1213 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
b60cea74 1214 target_wait_flags options);
6b8edb51 1215 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
b60cea74 1216 target_wait_flags options);
6b8edb51 1217
e2163381 1218 ptid_t process_stop_reply (stop_reply_up stop_reply,
6b8edb51
PA
1219 target_waitstatus *status);
1220
8f66807b 1221 ptid_t select_thread_for_ambiguous_stop_reply
c272a98c 1222 (const struct target_waitstatus &status);
8f66807b 1223
8a82de58 1224 void remote_notice_new_inferior (ptid_t currthread, bool executing);
6b8edb51 1225
1edb66d8 1226 void print_one_stopped_thread (thread_info *thread);
6b8edb51
PA
1227 void process_initial_stop_replies (int from_tty);
1228
b622494e
AB
1229 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1230 bool silent_p);
6b8edb51
PA
1231
1232 void btrace_sync_conf (const btrace_config *conf);
1233
1234 void remote_btrace_maybe_reopen ();
1235
53de5394 1236 void remove_new_children (threads_listing_context *context);
28561a65 1237 void kill_new_fork_children (inferior *inf);
6b8edb51
PA
1238 void discard_pending_stop_replies (struct inferior *inf);
1239 int stop_reply_queue_length ();
1240
1241 void check_pending_events_prevent_wildcard_vcont
2f63ec5c 1242 (bool *may_global_wildcard_vcont);
6b8edb51
PA
1243
1244 void discard_pending_stop_replies_in_queue ();
e2163381
PA
1245 stop_reply_up remote_notif_remove_queued_reply (ptid_t ptid);
1246 stop_reply_up queued_stop_reply (ptid_t ptid);
6b8edb51 1247 int peek_stop_reply (ptid_t ptid);
bb277751 1248 void remote_parse_stop_reply (const char *buf, stop_reply *event);
6b8edb51
PA
1249
1250 void remote_stop_ns (ptid_t ptid);
1251 void remote_interrupt_as ();
1252 void remote_interrupt_ns ();
1253
1254 char *remote_get_noisy_reply ();
1255 int remote_query_attached (int pid);
9ab8741a 1256 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51
PA
1257 int try_open_exec);
1258
1259 ptid_t remote_current_thread (ptid_t oldpid);
e3b2741b 1260 ptid_t get_current_thread (const char *wait_status);
6b8edb51
PA
1261
1262 void set_thread (ptid_t ptid, int gen);
1263 void set_general_thread (ptid_t ptid);
1264 void set_continue_thread (ptid_t ptid);
1265 void set_general_process ();
1266
1267 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1268
cecb1912 1269 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
6b8edb51
PA
1270 gdb_ext_thread_info *info);
1271 int remote_get_threadinfo (threadref *threadid, int fieldset,
1272 gdb_ext_thread_info *info);
1273
cecb1912 1274 int parse_threadlist_response (const char *pkt, int result_limit,
6b8edb51
PA
1275 threadref *original_echo,
1276 threadref *resultlist,
1277 int *doneflag);
1278 int remote_get_threadlist (int startflag, threadref *nextthread,
1279 int result_limit, int *done, int *result_count,
1280 threadref *threadlist);
1281
1282 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1283 void *context, int looplimit);
1284
1285 int remote_get_threads_with_ql (threads_listing_context *context);
1286 int remote_get_threads_with_qxfer (threads_listing_context *context);
1287 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1288
1289 void extended_remote_restart ();
1290
1291 void get_offsets ();
1292
1293 void remote_check_symbols ();
1294
1295 void remote_supported_packet (const struct protocol_feature *feature,
1296 enum packet_support support,
1297 const char *argument);
1298
1299 void remote_query_supported ();
1300
1301 void remote_packet_size (const protocol_feature *feature,
1302 packet_support support, const char *value);
65c459ab
PA
1303 void remote_supported_thread_options (const protocol_feature *feature,
1304 enum packet_support support,
1305 const char *value);
6b8edb51
PA
1306
1307 void remote_serial_quit_handler ();
1308
1309 void remote_detach_pid (int pid);
1310
1311 void remote_vcont_probe ();
1312
1313 void remote_resume_with_hc (ptid_t ptid, int step,
1314 gdb_signal siggnal);
1315
1316 void send_interrupt_sequence ();
1317 void interrupt_query ();
1318
42938c1a 1319 void remote_notif_get_pending_events (const notif_client *nc);
6b8edb51
PA
1320
1321 int fetch_register_using_p (struct regcache *regcache,
1322 packet_reg *reg);
1323 int send_g_packet ();
1324 void process_g_packet (struct regcache *regcache);
1325 void fetch_registers_using_g (struct regcache *regcache);
1326 int store_register_using_P (const struct regcache *regcache,
1327 packet_reg *reg);
1328 void store_registers_using_G (const struct regcache *regcache);
1329
1330 void set_remote_traceframe ();
1331
1332 void check_binary_download (CORE_ADDR addr);
1333
1334 target_xfer_status remote_write_bytes_aux (const char *header,
1335 CORE_ADDR memaddr,
1336 const gdb_byte *myaddr,
1337 ULONGEST len_units,
1338 int unit_size,
1339 ULONGEST *xfered_len_units,
1340 char packet_format,
1341 int use_length);
1342
1343 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1344 const gdb_byte *myaddr, ULONGEST len,
1345 int unit_size, ULONGEST *xfered_len);
1346
1347 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1348 ULONGEST len_units,
1349 int unit_size, ULONGEST *xfered_len_units);
1350
1351 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1352 ULONGEST memaddr,
1353 ULONGEST len,
1354 int unit_size,
1355 ULONGEST *xfered_len);
1356
1357 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1358 gdb_byte *myaddr, ULONGEST len,
1359 int unit_size,
1360 ULONGEST *xfered_len);
1361
7e9d8a36 1362 packet_status remote_send_printf (const char *format, ...)
6b8edb51
PA
1363 ATTRIBUTE_PRINTF (2, 3);
1364
1365 target_xfer_status remote_flash_write (ULONGEST address,
1366 ULONGEST length, ULONGEST *xfered_len,
1367 const gdb_byte *data);
1368
1369 int readchar (int timeout);
1370
1371 void remote_serial_write (const char *str, int len);
d69939bd 1372 void remote_serial_send_break ();
6b8edb51
PA
1373
1374 int putpkt (const char *buf);
1375 int putpkt_binary (const char *buf, int cnt);
1376
8d64371b
TT
1377 int putpkt (const gdb::char_vector &buf)
1378 {
1379 return putpkt (buf.data ());
1380 }
1381
6b8edb51 1382 void skip_frame ();
8d64371b 1383 long read_frame (gdb::char_vector *buf_p);
aa7b36b8
TT
1384 int getpkt (gdb::char_vector *buf, bool forever = false,
1385 bool *is_notif = nullptr);
6b8edb51
PA
1386 int remote_vkill (int pid);
1387 void remote_kill_k ();
1388
1389 void extended_remote_disable_randomization (int val);
1390 int extended_remote_run (const std::string &args);
1391
1392 void send_environment_packet (const char *action,
1393 const char *packet,
1394 const char *value);
1395
1396 void extended_remote_environment_support ();
3c69da40 1397 void extended_remote_set_inferior_cwd ();
80152258 1398
3c69da40
PA
1399 target_xfer_status remote_write_qxfer (const char *object_name,
1400 const char *annex,
1401 const gdb_byte *writebuf,
1402 ULONGEST offset, LONGEST len,
1403 ULONGEST *xfered_len,
ff52c073 1404 const unsigned int which_packet);
43c3a0e4 1405
3c69da40
PA
1406 target_xfer_status remote_read_qxfer (const char *object_name,
1407 const char *annex,
1408 gdb_byte *readbuf, ULONGEST offset,
1409 LONGEST len,
1410 ULONGEST *xfered_len,
ff52c073 1411 const unsigned int which_packet);
43c3a0e4 1412
e2163381 1413 void push_stop_reply (stop_reply_up new_event);
43c3a0e4 1414
3c69da40 1415 bool vcont_r_supported ();
43c3a0e4 1416
ff52c073
CS
1417 remote_features m_features;
1418
288712bb
AB
1419private:
1420
1421 bool start_remote_1 (int from_tty, int extended_p);
43c3a0e4 1422
3c69da40
PA
1423 /* The remote state. Don't reference this directly. Use the
1424 get_remote_state method instead. */
1425 remote_state m_remote_state;
43c3a0e4
PA
1426};
1427
3c69da40
PA
1428static const target_info extended_remote_target_info = {
1429 "extended-remote",
ae9adb36 1430 N_("Extended remote target using gdb-specific protocol"),
3c69da40
PA
1431 remote_doc
1432};
ea9c271d 1433
3c69da40
PA
1434/* Set up the extended remote target by extending the standard remote
1435 target and adding to it. */
1436
1437class extended_remote_target final : public remote_target
ea9c271d 1438{
9d6eea31 1439public:
3c69da40
PA
1440 const target_info &info () const override
1441 { return extended_remote_target_info; }
9d6eea31 1442
3c69da40
PA
1443 /* Open an extended-remote connection. */
1444 static void open (const char *, int);
de44f5a7 1445
3c69da40
PA
1446 bool can_create_inferior () override { return true; }
1447 void create_inferior (const char *, const std::string &,
1448 char **, int) override;
9d6eea31 1449
3c69da40 1450 void detach (inferior *, int) override;
9d6eea31 1451
3c69da40
PA
1452 bool can_attach () override { return true; }
1453 void attach (const char *, int) override;
be2a5f71 1454
3c69da40
PA
1455 void post_attach (int) override;
1456 bool supports_disable_randomization () override;
1457};
1e51243a 1458
a4543480
SM
1459struct stop_reply : public notif_event
1460{
a4543480
SM
1461 /* The identifier of the thread about this event */
1462 ptid_t ptid;
1463
1464 /* The remote state this event is associated with. When the remote
1465 connection, represented by a remote_state object, is closed,
1466 all the associated stop_reply events should be released. */
1467 struct remote_state *rs;
1468
1469 struct target_waitstatus ws;
1470
1471 /* The architecture associated with the expedited registers. */
1472 gdbarch *arch;
1473
1474 /* Expedited registers. This makes remote debugging a bit more
1475 efficient for those targets that provide critical registers as
1476 part of their normal status mechanism (as another roundtrip to
1477 fetch them is avoided). */
1478 std::vector<cached_reg_t> regcache;
1479
1480 enum target_stop_reason stop_reason;
1481
1482 CORE_ADDR watch_data_address;
1483
1484 int core;
1485};
1486
06c7226e
SM
1487/* Return TARGET as a remote_target if it is one, else nullptr. */
1488
1489static remote_target *
1490as_remote_target (process_stratum_target *target)
1491{
1492 return dynamic_cast<remote_target *> (target);
1493}
1494
24b2de7b
AB
1495/* See remote.h. */
1496
1497bool
1498is_remote_target (process_stratum_target *target)
1499{
06c7226e 1500 return as_remote_target (target) != nullptr;
24b2de7b
AB
1501}
1502
94aedcf7
TJB
1503/* See remote.h. */
1504
1505bool
1506remote_register_is_expedited (int regnum)
1507{
1508 remote_target *rt = as_remote_target (current_inferior ()->process_target ());
1509
1510 if (rt == nullptr)
1511 return false;
1512
1513 remote_state *rs = rt->get_remote_state ();
1514 return rs->last_seen_expedited_registers.count (regnum) > 0;
1515}
1516
3c69da40 1517/* Per-program-space data key. */
08b8a139 1518static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
7b4a314f 1519 remote_pspace_data;
2d717e4f 1520
3c69da40
PA
1521/* The variable registered as the control variable used by the
1522 remote exec-file commands. While the remote exec-file setting is
7a78108a 1523 per-program-space, the set/show machinery uses this as the
3c69da40 1524 location of the remote exec-file value. */
e0700ba4 1525static std::string remote_exec_file_var;
a6f3e723 1526
3c69da40
PA
1527/* The size to align memory write packets, when practical. The protocol
1528 does not guarantee any alignment, and gdb will generate short
1529 writes and unaligned writes, but even as a best-effort attempt this
1530 can improve bulk transfers. For instance, if a write is misaligned
1531 relative to the target's data bus, the stub may need to make an extra
1532 round trip fetching data from the target. This doesn't make a
1533 huge difference, but it's easy to do, so we try to be helpful.
82f73884 1534
3c69da40
PA
1535 The alignment chosen is arbitrary; usually data bus width is
1536 important here, not the possibly larger cache line size. */
1537enum { REMOTE_ALIGN_WRITES = 16 };
82f73884 1538
3c69da40 1539/* Prototypes for local functions. */
74531fed 1540
3c69da40 1541static int hexnumlen (ULONGEST num);
782b2b07 1542
3c69da40 1543static int stubhex (int ch);
5d93a237 1544
3c69da40 1545static int hexnumstr (char *, ULONGEST);
048094ac 1546
3c69da40 1547static int hexnumnstr (char *, ULONGEST, int);
47f8a51d 1548
3c69da40 1549static CORE_ADDR remote_address_masked (CORE_ADDR);
262e1174 1550
cecb1912 1551static int stub_unpack_int (const char *buff, int fieldlength);
5e4a05c4 1552
ff52c073
CS
1553static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1554 cmd_list_element *c);
1555
1556static void show_packet_config_cmd (ui_file *file,
1557 const unsigned int which_packet,
1558 remote_target *remote);
b73be471 1559
3c69da40
PA
1560static void show_remote_protocol_packet_cmd (struct ui_file *file,
1561 int from_tty,
1562 struct cmd_list_element *c,
1563 const char *value);
8e88304f 1564
3c69da40 1565static ptid_t read_ptid (const char *buf, const char **obuf);
3a00c802 1566
eefce37f 1567static bool remote_read_description_p (struct target_ops *target);
88b496c3 1568
c6100129 1569static void remote_console_output (const char *msg, ui_file *stream);
5965e028 1570
3c69da40 1571static void remote_btrace_reset (remote_state *rs);
f4abbc16 1572
d9deb60b 1573[[noreturn]] static void remote_unpush_and_throw (remote_target *target);
15a201c8 1574
3c69da40 1575/* For "remote". */
80152258 1576
3c69da40 1577static struct cmd_list_element *remote_cmdlist;
9d6eea31 1578
3c69da40 1579/* For "set remote" and "show remote". */
6b8edb51 1580
3c69da40
PA
1581static struct cmd_list_element *remote_set_cmdlist;
1582static struct cmd_list_element *remote_show_cmdlist;
6b8edb51 1583
3c69da40 1584/* Controls whether GDB is willing to use range stepping. */
6b8edb51 1585
491144b5 1586static bool use_range_stepping = true;
3c69da40 1587
c9d22089
SM
1588/* From the remote target's point of view, each thread is in one of these three
1589 states. */
1590enum class resume_state
1591{
1592 /* Not resumed - we haven't been asked to resume this thread. */
1593 NOT_RESUMED,
1594
1595 /* We have been asked to resume this thread, but haven't sent a vCont action
1596 for it yet. We'll need to consider it next time commit_resume is
1597 called. */
1598 RESUMED_PENDING_VCONT,
1599
1600 /* We have been asked to resume this thread, and we have sent a vCont action
1601 for it. */
1602 RESUMED,
1603};
1604
1605/* Information about a thread's pending vCont-resume. Used when a thread is in
1606 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1607 stores this information which is then picked up by
1608 remote_target::commit_resume to know which is the proper action for this
1609 thread to include in the vCont packet. */
1610struct resumed_pending_vcont_info
1611{
1612 /* True if the last resume call for this thread was a step request, false
1613 if a continue request. */
1614 bool step;
1615
1616 /* The signal specified in the last resume call for this thread. */
1617 gdb_signal sig;
1618};
1619
7aabaf9d
SM
1620/* Private data that we'll store in (struct thread_info)->priv. */
1621struct remote_thread_info : public private_thread_info
dc146f7c 1622{
7aabaf9d
SM
1623 std::string extra;
1624 std::string name;
1625 int core = -1;
799a2abe 1626
1dd0c745
TBA
1627 /* The string representation for the thread's id.
1628
1629 The target specifies this if they want to display the thread id
1630 in a specific way. If empty, the default approach is used. */
1631 std::string id_str;
1632
f6327dcb
KB
1633 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1634 sequence of bytes. */
7aabaf9d 1635 gdb::byte_vector thread_handle;
f6327dcb 1636
799a2abe 1637 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1638 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1639
1640 /* This is set to the data address of the access causing the target
1641 to stop for a watchpoint. */
7aabaf9d 1642 CORE_ADDR watch_data_address = 0;
85ad3aaf 1643
c9d22089 1644 /* Get the thread's resume state. */
a6c11cbb 1645 enum resume_state get_resume_state () const
c9d22089
SM
1646 {
1647 return m_resume_state;
1648 }
1649
1650 /* Put the thread in the NOT_RESUMED state. */
1651 void set_not_resumed ()
1652 {
1653 m_resume_state = resume_state::NOT_RESUMED;
1654 }
85ad3aaf 1655
c9d22089
SM
1656 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1657 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1658 {
1659 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1660 m_resumed_pending_vcont_info.step = step;
1661 m_resumed_pending_vcont_info.sig = sig;
1662 }
85ad3aaf 1663
c9d22089 1664 /* Get the information this thread's pending vCont-resumption.
85ad3aaf 1665
c9d22089
SM
1666 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1667 state. */
1668 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1669 {
1670 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1671
1672 return m_resumed_pending_vcont_info;
1673 }
1674
1675 /* Put the thread in the VCONT_RESUMED state. */
1676 void set_resumed ()
1677 {
1678 m_resume_state = resume_state::RESUMED;
1679 }
1680
1681private:
1682 /* Resume state for this thread. This is used to implement vCont action
1683 coalescing (only when the target operates in non-stop mode).
1684
1685 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1686 which notes that this thread must be considered in the next commit_resume
1687 call.
1688
1689 remote_target::commit_resume sends a vCont packet with actions for the
1690 threads in the RESUMED_PENDING_VCONT state and moves them to the
1691 VCONT_RESUMED state.
1692
1693 When reporting a stop to the core for a thread, that thread is moved back
1694 to the NOT_RESUMED state. */
1695 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1696
1697 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1698 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
dc146f7c
VP
1699};
1700
de44f5a7 1701remote_state::remote_state ()
8d64371b 1702 : buf (400)
de44f5a7 1703{
de44f5a7
PA
1704}
1705
1706remote_state::~remote_state ()
1707{
1708 xfree (this->last_pass_packet);
1709 xfree (this->last_program_signals_packet);
de44f5a7
PA
1710 xfree (this->finished_object);
1711 xfree (this->finished_annex);
cf792862
TT
1712}
1713
35b1e5cc
SS
1714/* Utility: generate error from an incoming stub packet. */
1715static void
1716trace_error (char *buf)
1717{
1718 if (*buf++ != 'E')
1719 return; /* not an error msg */
1720 switch (*buf)
1721 {
1722 case '1': /* malformed packet error */
1723 if (*++buf == '0') /* general case: */
1724 error (_("remote.c: error in outgoing packet."));
1725 else
1726 error (_("remote.c: error in outgoing packet at field #%ld."),
1727 strtol (buf, NULL, 16));
35b1e5cc
SS
1728 default:
1729 error (_("Target returns error code '%s'."), buf);
1730 }
1731}
1732
1733/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1734
6b8edb51
PA
1735char *
1736remote_target::remote_get_noisy_reply ()
35b1e5cc 1737{
b6bb3468
PA
1738 struct remote_state *rs = get_remote_state ();
1739
35b1e5cc
SS
1740 do /* Loop on reply from remote stub. */
1741 {
1742 char *buf;
a744cf53 1743
0df8b418 1744 QUIT; /* Allow user to bail out with ^C. */
aa7b36b8 1745 getpkt (&rs->buf);
8d64371b 1746 buf = rs->buf.data ();
ad91cd99 1747 if (buf[0] == 'E')
35b1e5cc 1748 trace_error (buf);
61012eef 1749 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1750 {
1751 ULONGEST ul;
1752 CORE_ADDR from, to, org_to;
256642e8 1753 const char *p, *pp;
dde08ee1 1754 int adjusted_size = 0;
7556d4a4 1755 int relocated = 0;
dde08ee1
PA
1756
1757 p = buf + strlen ("qRelocInsn:");
1758 pp = unpack_varlen_hex (p, &ul);
1759 if (*pp != ';')
cb91c06a 1760 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1761 from = ul;
1762
1763 p = pp + 1;
a9cbf802 1764 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1765 to = ul;
1766
1767 org_to = to;
1768
a70b8144 1769 try
dde08ee1 1770 {
99d9c3b9
SM
1771 gdbarch_relocate_instruction (current_inferior ()->arch (),
1772 &to, from);
7556d4a4 1773 relocated = 1;
dde08ee1 1774 }
230d2906 1775 catch (const gdb_exception &ex)
7556d4a4
PA
1776 {
1777 if (ex.error == MEMORY_ERROR)
1778 {
1779 /* Propagate memory errors silently back to the
1780 target. The stub may have limited the range of
1781 addresses we can write to, for example. */
1782 }
1783 else
1784 {
1785 /* Something unexpectedly bad happened. Be verbose
1786 so we can tell what, and propagate the error back
1787 to the stub, so it doesn't get stuck waiting for
1788 a response. */
1789 exception_fprintf (gdb_stderr, ex,
1790 _("warning: relocating instruction: "));
1791 }
1792 putpkt ("E01");
1793 }
1794
1795 if (relocated)
dde08ee1
PA
1796 {
1797 adjusted_size = to - org_to;
1798
8d64371b 1799 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1800 putpkt (buf);
1801 }
dde08ee1 1802 }
ad91cd99 1803 else if (buf[0] == 'O' && buf[1] != 'K')
c6100129
TT
1804 {
1805 /* 'O' message from stub */
1806 remote_console_output (buf + 1, gdb_stdtarg);
1807 }
35b1e5cc 1808 else
0df8b418 1809 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1810 }
1811 while (1);
1812}
3c3bea1c 1813
9d6eea31
PA
1814struct remote_arch_state *
1815remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1816{
43c3a0e4
PA
1817 remote_arch_state *rsa;
1818
1819 auto it = this->m_arch_states.find (gdbarch);
1820 if (it == this->m_arch_states.end ())
9d6eea31 1821 {
43c3a0e4
PA
1822 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1823 std::forward_as_tuple (gdbarch),
1824 std::forward_as_tuple (gdbarch));
1825 rsa = &p.first->second;
9d6eea31
PA
1826
1827 /* Make sure that the packet buffer is plenty big enough for
1828 this architecture. */
8d64371b
TT
1829 if (this->buf.size () < rsa->remote_packet_size)
1830 this->buf.resize (2 * rsa->remote_packet_size);
9d6eea31 1831 }
43c3a0e4
PA
1832 else
1833 rsa = &it->second;
1834
1835 return rsa;
d01949b6
AC
1836}
1837
0b83947e
DJ
1838/* Fetch the global remote target state. */
1839
6b8edb51
PA
1840remote_state *
1841remote_target::get_remote_state ()
0b83947e
DJ
1842{
1843 /* Make sure that the remote architecture state has been
1844 initialized, because doing so might reallocate rs->buf. Any
1845 function which calls getpkt also needs to be mindful of changes
1846 to rs->buf, but this call limits the number of places which run
1847 into trouble. */
99d9c3b9 1848 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
0b83947e 1849
3c69da40 1850 return &m_remote_state;
0b83947e
DJ
1851}
1852
94585166
DB
1853/* Fetch the remote exec-file from the current program space. */
1854
1855static const char *
1856get_remote_exec_file (void)
1857{
1858 char *remote_exec_file;
1859
7b4a314f 1860 remote_exec_file = remote_pspace_data.get (current_program_space);
94585166
DB
1861 if (remote_exec_file == NULL)
1862 return "";
1863
1864 return remote_exec_file;
1865}
1866
1867/* Set the remote exec file for PSPACE. */
1868
1869static void
1870set_pspace_remote_exec_file (struct program_space *pspace,
7b4a314f 1871 const char *remote_exec_file)
94585166 1872{
7b4a314f 1873 char *old_file = remote_pspace_data.get (pspace);
94585166
DB
1874
1875 xfree (old_file);
7b4a314f 1876 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
94585166
DB
1877}
1878
1879/* The "set/show remote exec-file" set command hook. */
1880
1881static void
eb4c3f4a 1882set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1883 struct cmd_list_element *c)
1884{
e0700ba4
SM
1885 set_pspace_remote_exec_file (current_program_space,
1886 remote_exec_file_var.c_str ());
94585166
DB
1887}
1888
1889/* The "set/show remote exec-file" show command hook. */
1890
1891static void
1892show_remote_exec_file (struct ui_file *file, int from_tty,
1893 struct cmd_list_element *cmd, const char *value)
1894{
6cb06a8c 1895 gdb_printf (file, "%s\n", get_remote_exec_file ());
94585166
DB
1896}
1897
c21236dc
PA
1898static int
1899map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1900{
74ca34ce 1901 int regnum, num_remote_regs, offset;
74ca34ce 1902 struct packet_reg **remote_regs;
ea9c271d 1903
4a22f64d 1904 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1905 {
c21236dc 1906 struct packet_reg *r = &regs[regnum];
baef701f 1907
4a22f64d 1908 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1909 /* Do not try to fetch zero-sized (placeholder) registers. */
1910 r->pnum = -1;
1911 else
1912 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1913
b323314b 1914 r->regnum = regnum;
74ca34ce
DJ
1915 }
1916
1917 /* Define the g/G packet format as the contents of each register
1918 with a remote protocol number, in order of ascending protocol
1919 number. */
1920
224c3ddb 1921 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1922 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1923 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1924 regnum++)
c21236dc
PA
1925 if (regs[regnum].pnum != -1)
1926 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1927
39ef2f62
CB
1928 std::sort (remote_regs, remote_regs + num_remote_regs,
1929 [] (const packet_reg *a, const packet_reg *b)
1930 { return a->pnum < b->pnum; });
74ca34ce
DJ
1931
1932 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1933 {
480a1156 1934 remote_regs[regnum]->in_g_packet = true;
74ca34ce 1935 remote_regs[regnum]->offset = offset;
4a22f64d 1936 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1937 }
1938
c21236dc
PA
1939 return offset;
1940}
1941
1942/* Given the architecture described by GDBARCH, return the remote
1943 protocol register's number and the register's offset in the g/G
1944 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1945 If the target does not have a mapping for REGNUM, return false,
1946 otherwise, return true. */
1947
1948int
1949remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1950 int *pnum, int *poffset)
1951{
c21236dc
PA
1952 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1953
b80406ac 1954 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1955
b80406ac 1956 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1957
1958 *pnum = regs[regnum].pnum;
1959 *poffset = regs[regnum].offset;
1960
c21236dc
PA
1961 return *pnum != -1;
1962}
1963
9d6eea31 1964remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1965{
c21236dc
PA
1966 /* Use the architecture to build a regnum<->pnum table, which will be
1967 1:1 unless a feature set specifies otherwise. */
9d6eea31 1968 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1969
74ca34ce
DJ
1970 /* Record the maximum possible size of the g packet - it may turn out
1971 to be smaller. */
9d6eea31
PA
1972 this->sizeof_g_packet
1973 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1974
0df8b418 1975 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1976 remote stubs have a hardwired buffer size of 400 bytes
1977 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1978 as the maximum packet-size to ensure that the packet and an extra
1979 NUL character can always fit in the buffer. This stops GDB
1980 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1981 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1982 this->remote_packet_size = 400 - 1;
d01949b6 1983
ea9c271d 1984 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1985 this->actual_register_packet_size = 0;
ea9c271d
DJ
1986
1987 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1988 default, adjust the size accordingly. Remember that each byte is
1989 encoded as two characters. 32 is the overhead for the packet
1990 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1991 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1992 little. */
9d6eea31
PA
1993 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1994 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1995}
1996
6b8edb51
PA
1997/* Get a pointer to the current remote target. If not connected to a
1998 remote target, return NULL. */
1999
2000static remote_target *
2001get_current_remote_target ()
2002{
5b6d1e4f 2003 target_ops *proc_target = current_inferior ()->process_target ();
6b8edb51
PA
2004 return dynamic_cast<remote_target *> (proc_target);
2005}
2006
ea9c271d
DJ
2007/* Return the current allowed size of a remote packet. This is
2008 inferred from the current architecture, and should be used to
2009 limit the length of outgoing packets. */
6b8edb51
PA
2010long
2011remote_target::get_remote_packet_size ()
ea9c271d 2012{
be2a5f71 2013 struct remote_state *rs = get_remote_state ();
99d9c3b9
SM
2014 remote_arch_state *rsa
2015 = rs->get_remote_arch_state (current_inferior ()->arch ());
ea9c271d 2016
be2a5f71
DJ
2017 if (rs->explicit_packet_size)
2018 return rs->explicit_packet_size;
2019
ea9c271d 2020 return rsa->remote_packet_size;
d01949b6
AC
2021}
2022
ad10f812 2023static struct packet_reg *
5cd63fda
PA
2024packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
2025 long regnum)
ad10f812 2026{
5cd63fda 2027 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
2028 return NULL;
2029 else
ad10f812 2030 {
ea9c271d 2031 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 2032
b323314b
AC
2033 gdb_assert (r->regnum == regnum);
2034 return r;
ad10f812 2035 }
ad10f812
AC
2036}
2037
2038static struct packet_reg *
5cd63fda
PA
2039packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
2040 LONGEST pnum)
ad10f812 2041{
b323314b 2042 int i;
a744cf53 2043
5cd63fda 2044 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 2045 {
ea9c271d 2046 struct packet_reg *r = &rsa->regs[i];
a744cf53 2047
b323314b
AC
2048 if (r->pnum == pnum)
2049 return r;
ad10f812
AC
2050 }
2051 return NULL;
d01949b6
AC
2052}
2053
9a7071a8
JB
2054/* Allow the user to specify what sequence to send to the remote
2055 when he requests a program interruption: Although ^C is usually
2056 what remote systems expect (this is the default, here), it is
2057 sometimes preferable to send a break. On other systems such
2058 as the Linux kernel, a break followed by g, which is Magic SysRq g
2059 is required in order to interrupt the execution. */
2060const char interrupt_sequence_control_c[] = "Ctrl-C";
2061const char interrupt_sequence_break[] = "BREAK";
2062const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 2063static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
2064 {
2065 interrupt_sequence_control_c,
2066 interrupt_sequence_break,
2067 interrupt_sequence_break_g,
2068 NULL
2069 };
2070static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
2071
2072static void
2073show_interrupt_sequence (struct ui_file *file, int from_tty,
2074 struct cmd_list_element *c,
2075 const char *value)
2076{
2077 if (interrupt_sequence_mode == interrupt_sequence_control_c)
6cb06a8c
TT
2078 gdb_printf (file,
2079 _("Send the ASCII ETX character (Ctrl-c) "
2080 "to the remote target to interrupt the "
2081 "execution of the program.\n"));
9a7071a8 2082 else if (interrupt_sequence_mode == interrupt_sequence_break)
6cb06a8c
TT
2083 gdb_printf (file,
2084 _("send a break signal to the remote target "
2085 "to interrupt the execution of the program.\n"));
9a7071a8 2086 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
6cb06a8c
TT
2087 gdb_printf (file,
2088 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
2089 "the remote target to interrupt the execution "
2090 "of Linux kernel.\n"));
9a7071a8 2091 else
f34652de 2092 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
9a7071a8
JB
2093 interrupt_sequence_mode);
2094}
6426a772 2095
9a7071a8
JB
2096/* This boolean variable specifies whether interrupt_sequence is sent
2097 to the remote target when gdb connects to it.
2098 This is mostly needed when you debug the Linux kernel: The Linux kernel
2099 expects BREAK g which is Magic SysRq g for connecting gdb. */
491144b5 2100static bool interrupt_on_connect = false;
c906108c 2101
9a7071a8
JB
2102/* This variable is used to implement the "set/show remotebreak" commands.
2103 Since these commands are now deprecated in favor of "set/show remote
2104 interrupt-sequence", it no longer has any effect on the code. */
491144b5 2105static bool remote_break;
c906108c 2106
9a7071a8 2107static void
eb4c3f4a 2108set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
2109{
2110 if (remote_break)
2111 interrupt_sequence_mode = interrupt_sequence_break;
2112 else
2113 interrupt_sequence_mode = interrupt_sequence_control_c;
2114}
2115
2116static void
2117show_remotebreak (struct ui_file *file, int from_tty,
2118 struct cmd_list_element *c,
2119 const char *value)
2120{
2121}
2122
c906108c
SS
2123/* This variable sets the number of bits in an address that are to be
2124 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 2125 leading zeros, the entire address would be sent. This variable
c906108c
SS
2126 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
2127 initial implementation of remote.c restricted the address sent in
2128 memory packets to ``host::sizeof long'' bytes - (typically 32
2129 bits). Consequently, for 64 bit targets, the upper 32 bits of an
2130 address was never sent. Since fixing this bug may cause a break in
85102364 2131 some remote targets this variable is principally provided to
23860348 2132 facilitate backward compatibility. */
c906108c 2133
883b9c6c 2134static unsigned int remote_address_size;
c906108c 2135
11cf8741 2136\f
cc0be08f
PA
2137/* The default max memory-write-packet-size, when the setting is
2138 "fixed". The 16k is historical. (It came from older GDB's using
2139 alloca for buffers and the knowledge (folklore?) that some hosts
2140 don't cope very well with large alloca calls.) */
2141#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
2142
2143/* The minimum remote packet size for memory transfers. Ensures we
2144 can write at least one byte. */
2145#define MIN_MEMORY_PACKET_SIZE 20
2146
cc0be08f
PA
2147/* Get the memory packet size, assuming it is fixed. */
2148
2149static long
2150get_fixed_memory_packet_size (struct memory_packet_config *config)
2151{
2152 gdb_assert (config->fixed_p);
2153
2154 if (config->size <= 0)
2155 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2156 else
2157 return config->size;
2158}
2159
11cf8741
JM
2160/* Compute the current size of a read/write packet. Since this makes
2161 use of ``actual_register_packet_size'' the computation is dynamic. */
2162
6b8edb51
PA
2163long
2164remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 2165{
d01949b6 2166 struct remote_state *rs = get_remote_state ();
99d9c3b9
SM
2167 remote_arch_state *rsa
2168 = rs->get_remote_arch_state (current_inferior ()->arch ());
ea9c271d 2169
11cf8741
JM
2170 long what_they_get;
2171 if (config->fixed_p)
cc0be08f 2172 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
2173 else
2174 {
ea9c271d 2175 what_they_get = get_remote_packet_size ();
23860348 2176 /* Limit the packet to the size specified by the user. */
11cf8741
JM
2177 if (config->size > 0
2178 && what_they_get > config->size)
2179 what_they_get = config->size;
be2a5f71
DJ
2180
2181 /* Limit it to the size of the targets ``g'' response unless we have
2182 permission from the stub to use a larger packet size. */
2183 if (rs->explicit_packet_size == 0
2184 && rsa->actual_register_packet_size > 0
2185 && what_they_get > rsa->actual_register_packet_size)
2186 what_they_get = rsa->actual_register_packet_size;
11cf8741 2187 }
a5c0808e
PA
2188 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2189 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
2190
2191 /* Make sure there is room in the global buffer for this packet
2192 (including its trailing NUL byte). */
8d64371b
TT
2193 if (rs->buf.size () < what_they_get + 1)
2194 rs->buf.resize (2 * what_they_get);
6d820c5c 2195
11cf8741
JM
2196 return what_they_get;
2197}
2198
0df8b418 2199/* Update the size of a read/write packet. If they user wants
23860348 2200 something really big then do a sanity check. */
11cf8741
JM
2201
2202static void
fe4c3ca0
CS
2203set_memory_packet_size (const char *args, struct memory_packet_config *config,
2204 bool target_connected)
11cf8741
JM
2205{
2206 int fixed_p = config->fixed_p;
2207 long size = config->size;
a744cf53 2208
11cf8741 2209 if (args == NULL)
fe4c3ca0 2210 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
11cf8741
JM
2211 else if (strcmp (args, "hard") == 0
2212 || strcmp (args, "fixed") == 0)
2213 fixed_p = 1;
2214 else if (strcmp (args, "soft") == 0
2215 || strcmp (args, "limit") == 0)
2216 fixed_p = 0;
2217 else
2218 {
2219 char *end;
a744cf53 2220
11cf8741
JM
2221 size = strtoul (args, &end, 0);
2222 if (args == end)
8a3fe4f8 2223 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
2224
2225 /* Instead of explicitly capping the size of a packet to or
2226 disallowing it, the user is allowed to set the size to
2227 something arbitrarily large. */
11cf8741 2228 }
a5c0808e 2229
23860348 2230 /* Extra checks? */
11cf8741
JM
2231 if (fixed_p && !config->fixed_p)
2232 {
cc0be08f
PA
2233 /* So that the query shows the correct value. */
2234 long query_size = (size <= 0
2235 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2236 : size);
2237
fe4c3ca0
CS
2238 if (target_connected
2239 && !query (_("The target may not be able to correctly handle a %s\n"
2240 "of %ld bytes. Change the packet size? "),
2241 config->name, query_size))
2242 error (_("Packet size not changed."));
2243 else if (!target_connected
2244 && !query (_("Future remote targets may not be able to "
2245 "correctly handle a %s\nof %ld bytes. Change the "
2246 "packet size for future remote targets? "),
2247 config->name, query_size))
8a3fe4f8 2248 error (_("Packet size not changed."));
11cf8741 2249 }
23860348 2250 /* Update the config. */
11cf8741
JM
2251 config->fixed_p = fixed_p;
2252 config->size = size;
fe4c3ca0
CS
2253
2254 const char *target_type = get_target_type_name (target_connected);
2255 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2256 args);
2257
11cf8741
JM
2258}
2259
fe4c3ca0
CS
2260/* Show the memory-read or write-packet size configuration CONFIG of the
2261 target REMOTE. If REMOTE is nullptr, the default configuration for future
2262 remote targets should be passed in CONFIG. */
2263
11cf8741 2264static void
fe4c3ca0 2265show_memory_packet_size (memory_packet_config *config, remote_target *remote)
11cf8741 2266{
fe4c3ca0
CS
2267 const char *target_type = get_target_type_name (remote != nullptr);
2268
cc0be08f 2269 if (config->size == 0)
fe4c3ca0 2270 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
cc0be08f 2271 else
fe4c3ca0
CS
2272 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2273 config->size);
2274
11cf8741 2275 if (config->fixed_p)
6cb06a8c
TT
2276 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2277 get_fixed_memory_packet_size (config));
11cf8741 2278 else
cc0be08f 2279 {
fe4c3ca0 2280 if (remote != nullptr)
6cb06a8c
TT
2281 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2282 remote->get_memory_packet_size (config));
cc0be08f 2283 else
0426ad51
TT
2284 gdb_puts ("The actual limit will be further reduced "
2285 "dependent on the target.\n");
cc0be08f 2286 }
11cf8741
JM
2287}
2288
fe4c3ca0
CS
2289/* Configure the memory-write-packet size of the currently selected target. If
2290 no target is available, the default configuration for future remote targets
2291 is configured. */
11cf8741
JM
2292
2293static void
ac88e2de 2294set_memory_write_packet_size (const char *args, int from_tty)
11cf8741 2295{
fe4c3ca0
CS
2296 remote_target *remote = get_current_remote_target ();
2297 if (remote != nullptr)
2298 {
2299 set_memory_packet_size
2300 (args, &remote->m_features.m_memory_write_packet_config, true);
2301 }
2302 else
2303 {
2304 memory_packet_config* config = &memory_write_packet_config;
2305 set_memory_packet_size (args, config, false);
2306 }
11cf8741
JM
2307}
2308
fe4c3ca0
CS
2309/* Display the memory-write-packet size of the currently selected target. If
2310 no target is available, the default configuration for future remote targets
2311 is shown. */
2312
11cf8741 2313static void
ac88e2de 2314show_memory_write_packet_size (const char *args, int from_tty)
11cf8741 2315{
fe4c3ca0
CS
2316 remote_target *remote = get_current_remote_target ();
2317 if (remote != nullptr)
2318 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2319 remote);
2320 else
2321 show_memory_packet_size (&memory_write_packet_config, nullptr);
11cf8741
JM
2322}
2323
055303e2
AB
2324/* Show the number of hardware watchpoints that can be used. */
2325
2326static void
2327show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2328 struct cmd_list_element *c,
2329 const char *value)
2330{
6cb06a8c
TT
2331 gdb_printf (file, _("The maximum number of target hardware "
2332 "watchpoints is %s.\n"), value);
055303e2
AB
2333}
2334
2335/* Show the length limit (in bytes) for hardware watchpoints. */
2336
2337static void
2338show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2339 struct cmd_list_element *c,
2340 const char *value)
2341{
6cb06a8c
TT
2342 gdb_printf (file, _("The maximum length (in bytes) of a target "
2343 "hardware watchpoint is %s.\n"), value);
055303e2
AB
2344}
2345
2346/* Show the number of hardware breakpoints that can be used. */
2347
2348static void
2349show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2350 struct cmd_list_element *c,
2351 const char *value)
2352{
6cb06a8c
TT
2353 gdb_printf (file, _("The maximum number of target hardware "
2354 "breakpoints is %s.\n"), value);
055303e2
AB
2355}
2356
6cc8564b
LM
2357/* Controls the maximum number of characters to display in the debug output
2358 for each remote packet. The remaining characters are omitted. */
2359
2360static int remote_packet_max_chars = 512;
2361
2362/* Show the maximum number of characters to display for each remote packet
2363 when remote debugging is enabled. */
2364
2365static void
2366show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2367 struct cmd_list_element *c,
2368 const char *value)
2369{
6cb06a8c
TT
2370 gdb_printf (file, _("Number of remote packet characters to "
2371 "display is %s.\n"), value);
6cc8564b
LM
2372}
2373
6b8edb51
PA
2374long
2375remote_target::get_memory_write_packet_size ()
11cf8741 2376{
fe4c3ca0 2377 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
11cf8741
JM
2378}
2379
fe4c3ca0
CS
2380/* Configure the memory-read-packet size of the currently selected target. If
2381 no target is available, the default configuration for future remote targets
2382 is adapted. */
11cf8741
JM
2383
2384static void
ac88e2de 2385set_memory_read_packet_size (const char *args, int from_tty)
11cf8741 2386{
fe4c3ca0
CS
2387 remote_target *remote = get_current_remote_target ();
2388 if (remote != nullptr)
2389 set_memory_packet_size
2390 (args, &remote->m_features.m_memory_read_packet_config, true);
2391 else
2392 {
2393 memory_packet_config* config = &memory_read_packet_config;
2394 set_memory_packet_size (args, config, false);
2395 }
2396
11cf8741
JM
2397}
2398
fe4c3ca0
CS
2399/* Display the memory-read-packet size of the currently selected target. If
2400 no target is available, the default configuration for future remote targets
2401 is shown. */
2402
11cf8741 2403static void
ac88e2de 2404show_memory_read_packet_size (const char *args, int from_tty)
11cf8741 2405{
fe4c3ca0
CS
2406 remote_target *remote = get_current_remote_target ();
2407 if (remote != nullptr)
2408 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2409 remote);
2410 else
2411 show_memory_packet_size (&memory_read_packet_config, nullptr);
11cf8741
JM
2412}
2413
6b8edb51
PA
2414long
2415remote_target::get_memory_read_packet_size ()
11cf8741 2416{
fe4c3ca0 2417 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
a744cf53 2418
11cf8741
JM
2419 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2420 extra buffer size argument before the memory read size can be
ea9c271d
DJ
2421 increased beyond this. */
2422 if (size > get_remote_packet_size ())
2423 size = get_remote_packet_size ();
11cf8741
JM
2424 return size;
2425}
2426
ff52c073 2427static enum packet_support packet_config_support (const packet_config *config);
5a2468f5 2428
4082afcc 2429
ff52c073
CS
2430static void
2431set_remote_protocol_packet_cmd (const char *args, int from_tty,
2432 cmd_list_element *c)
2433{
2434 remote_target *remote = get_current_remote_target ();
2435 gdb_assert (c->var.has_value ());
4082afcc 2436
ff52c073
CS
2437 auto *default_config = static_cast<packet_config *> (c->context ());
2438 const int packet_idx = std::distance (remote_protocol_packets,
2439 default_config);
fcef6471 2440
ff52c073
CS
2441 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2442 {
2443 const char *name = packets_descriptions[packet_idx].name;
2444 const auto_boolean value = c->var->get<auto_boolean> ();
2445 const char *support = get_packet_support_name (value);
2446 const char *target_type = get_target_type_name (remote != nullptr);
5a2468f5 2447
ff52c073
CS
2448 if (remote != nullptr)
2449 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2450 else
2451 remote_protocol_packets[packet_idx].detect = value;
2452
2453 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2454 target_type, support);
2455 return;
2456 }
2457
2458 internal_error (_("Could not find config for %s"), c->name);
2459}
5a2468f5
JM
2460
2461static void
ff52c073
CS
2462show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2463 remote_target *remote)
5a2468f5 2464{
a121b7c1 2465 const char *support = "internal-error";
ff52c073
CS
2466 const char *target_type = get_target_type_name (remote != nullptr);
2467
2468 packet_config *config;
2469 if (remote != nullptr)
2470 config = &remote->m_features.m_protocol_packets[which_packet];
2471 else
2472 config = &remote_protocol_packets[which_packet];
a744cf53 2473
4082afcc 2474 switch (packet_config_support (config))
5a2468f5
JM
2475 {
2476 case PACKET_ENABLE:
2477 support = "enabled";
2478 break;
2479 case PACKET_DISABLE:
2480 support = "disabled";
2481 break;
2482 case PACKET_SUPPORT_UNKNOWN:
2483 support = "unknown";
2484 break;
2485 }
2486 switch (config->detect)
2487 {
7f19b9a2 2488 case AUTO_BOOLEAN_AUTO:
6cb06a8c 2489 gdb_printf (file,
ff52c073
CS
2490 _("Support for the '%s' packet %s is \"auto\", "
2491 "currently %s.\n"),
2492 packets_descriptions[which_packet].name, target_type,
2493 support);
5a2468f5 2494 break;
7f19b9a2
AC
2495 case AUTO_BOOLEAN_TRUE:
2496 case AUTO_BOOLEAN_FALSE:
6cb06a8c 2497 gdb_printf (file,
ff52c073
CS
2498 _("Support for the '%s' packet %s is \"%s\".\n"),
2499 packets_descriptions[which_packet].name, target_type,
2500 get_packet_support_name (config->detect));
8e248173 2501 break;
5a2468f5
JM
2502 }
2503}
2504
2505static void
ff52c073 2506add_packet_config_cmd (const unsigned int which_packet, const char *name,
bb572ddd 2507 const char *title, int legacy)
d471ea57 2508{
ff52c073
CS
2509 packets_descriptions[which_packet].name = name;
2510 packets_descriptions[which_packet].title = title;
2511
2512 packet_config *config = &remote_protocol_packets[which_packet];
2513
8579fd13 2514 gdb::unique_xmalloc_ptr<char> set_doc
9f7ed4d5 2515 = xstrprintf ("Set use of remote protocol `%s' packet.", name);
8579fd13 2516 gdb::unique_xmalloc_ptr<char> show_doc
9f7ed4d5 2517 = xstrprintf ("Show current use of remote protocol `%s' packet.", name);
d471ea57 2518 /* set/show TITLE-packet {auto,on,off} */
8579fd13 2519 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
5e84b7ee 2520 set_show_commands cmds
8579fd13
AB
2521 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2522 &config->detect, set_doc.get (),
2523 show_doc.get (), NULL, /* help_doc */
ff52c073 2524 set_remote_protocol_packet_cmd,
5e84b7ee
SM
2525 show_remote_protocol_packet_cmd,
2526 &remote_set_cmdlist, &remote_show_cmdlist);
ff52c073
CS
2527 cmds.show->set_context (config);
2528 cmds.set->set_context (config);
5e84b7ee 2529
23860348 2530 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
2531 if (legacy)
2532 {
5f21c7aa
AB
2533 /* It's not clear who should take ownership of the LEGACY_NAME string
2534 created below, so, for now, place the string into a static vector
2535 which ensures the strings is released when GDB exits. */
2536 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2537 gdb::unique_xmalloc_ptr<char> legacy_name
8579fd13
AB
2538 = xstrprintf ("%s-packet", name);
2539 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
bb572ddd 2540 &remote_set_cmdlist);
8579fd13 2541 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
bb572ddd 2542 &remote_show_cmdlist);
5f21c7aa 2543 legacy_names.emplace_back (std::move (legacy_name));
d471ea57 2544 }
5a2468f5
JM
2545}
2546
36232719
AH
2547/* Check GDBserver's reply packet. Return packet_result structure
2548 which contains the packet_status enum and an error message for the
2549 PACKET_ERROR case.
2550
2551 An error packet can always take the form Exx (where xx is a hex
ddb3f3d8 2552 code). */
7e9d8a36 2553static packet_result
ddb3f3d8 2554packet_check_result (const char *buf)
5a2468f5 2555{
d471ea57 2556 if (buf[0] != '\0')
5a2468f5 2557 {
d471ea57 2558 /* The stub recognized the packet request. Check that the
23860348 2559 operation succeeded. */
a76d924d
DJ
2560 if (buf[0] == 'E'
2561 && isxdigit (buf[1]) && isxdigit (buf[2])
2562 && buf[3] == '\0')
85102364 2563 /* "Enn" - definitely an error. */
33befefc 2564 return packet_result::make_numeric_error (buf + 1);
a76d924d 2565
ddb3f3d8
AH
2566 /* Always treat "E." as an error. This will be used for
2567 more verbose error messages, such as E.memtypes. */
2568 if (buf[0] == 'E' && buf[1] == '.')
7e9d8a36 2569 {
ddb3f3d8
AH
2570 if (buf[2] != '\0')
2571 return packet_result::make_textual_error (buf + 2);
2572 else
2573 return packet_result::make_textual_error ("no error provided");
7e9d8a36 2574 }
a76d924d
DJ
2575
2576 /* The packet may or may not be OK. Just assume it is. */
33befefc 2577 return packet_result::make_ok ();
a76d924d
DJ
2578 }
2579 else
7e9d8a36 2580 {
a76d924d 2581 /* The stub does not support the packet. */
33befefc 2582 return packet_result::make_unknown ();
7e9d8a36 2583 }
a76d924d
DJ
2584}
2585
7e9d8a36 2586static packet_result
ddb3f3d8 2587packet_check_result (const gdb::char_vector &buf)
8d64371b 2588{
ddb3f3d8 2589 return packet_check_result (buf.data ());
8d64371b
TT
2590}
2591
94a94c90 2592packet_result
ff52c073 2593remote_features::packet_ok (const char *buf, const int which_packet)
a76d924d 2594{
ff52c073
CS
2595 packet_config *config = &m_protocol_packets[which_packet];
2596 packet_description *descr = &packets_descriptions[which_packet];
2597
4082afcc
PA
2598 if (config->detect != AUTO_BOOLEAN_TRUE
2599 && config->support == PACKET_DISABLE)
f34652de 2600 internal_error (_("packet_ok: attempt to use a disabled packet"));
4082afcc 2601
ddb3f3d8 2602 packet_result result = packet_check_result (buf);
7e9d8a36 2603 switch (result.status ())
a76d924d
DJ
2604 {
2605 case PACKET_OK:
2606 case PACKET_ERROR:
2607 /* The stub recognized the packet request. */
4082afcc 2608 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 2609 {
2189c312 2610 remote_debug_printf ("Packet %s (%s) is supported",
ff52c073 2611 descr->name, descr->title);
d471ea57 2612 config->support = PACKET_ENABLE;
d471ea57 2613 }
a76d924d
DJ
2614 break;
2615 case PACKET_UNKNOWN:
23860348 2616 /* The stub does not support the packet. */
4082afcc
PA
2617 if (config->detect == AUTO_BOOLEAN_AUTO
2618 && config->support == PACKET_ENABLE)
d471ea57 2619 {
4082afcc
PA
2620 /* If the stub previously indicated that the packet was
2621 supported then there is a protocol error. */
2622 error (_("Protocol error: %s (%s) conflicting enabled responses."),
ff52c073 2623 descr->name, descr->title);
4082afcc
PA
2624 }
2625 else if (config->detect == AUTO_BOOLEAN_TRUE)
2626 {
2627 /* The user set it wrong. */
2628 error (_("Enabled packet %s (%s) not recognized by stub"),
ff52c073 2629 descr->name, descr->title);
d471ea57 2630 }
4082afcc 2631
ff52c073
CS
2632 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2633 descr->title);
4082afcc 2634 config->support = PACKET_DISABLE;
a76d924d 2635 break;
5a2468f5 2636 }
a76d924d 2637
94a94c90 2638 return result;
5a2468f5
JM
2639}
2640
94a94c90 2641packet_result
ff52c073 2642remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
f7e6eed5 2643{
ff52c073 2644 return packet_ok (buf.data (), which_packet);
f7e6eed5
PA
2645}
2646
4082afcc
PA
2647/* Returns whether a given packet or feature is supported. This takes
2648 into account the state of the corresponding "set remote foo-packet"
2649 command, which may be used to bypass auto-detection. */
dc8acb97 2650
4082afcc 2651static enum packet_support
ff52c073 2652packet_config_support (const packet_config *config)
4082afcc
PA
2653{
2654 switch (config->detect)
444abaca 2655 {
4082afcc
PA
2656 case AUTO_BOOLEAN_TRUE:
2657 return PACKET_ENABLE;
2658 case AUTO_BOOLEAN_FALSE:
2659 return PACKET_DISABLE;
2660 case AUTO_BOOLEAN_AUTO:
2661 return config->support;
2662 default:
557b4d76 2663 gdb_assert_not_reached ("bad switch");
444abaca 2664 }
4082afcc
PA
2665}
2666
ff52c073
CS
2667packet_support
2668remote_features::packet_support (int packet) const
4082afcc 2669{
ff52c073 2670 const packet_config *config = &m_protocol_packets[packet];
4082afcc 2671 return packet_config_support (config);
dc8acb97
MS
2672}
2673
5a2468f5 2674static void
444abaca
DJ
2675show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2676 struct cmd_list_element *c,
2677 const char *value)
5a2468f5 2678{
ff52c073 2679 remote_target *remote = get_current_remote_target ();
1d7fe7f0 2680 gdb_assert (c->var.has_value ());
5a2468f5 2681
ff52c073
CS
2682 auto *default_config = static_cast<packet_config *> (c->context ());
2683 const int packet_idx = std::distance (remote_protocol_packets,
2684 default_config);
2685
2686 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
444abaca 2687 {
ff52c073
CS
2688 show_packet_config_cmd (file, packet_idx, remote);
2689 return;
444abaca 2690 }
ff52c073 2691 internal_error (_("Could not find config for %s"), c->name);
5a2468f5
JM
2692}
2693
d471ea57
AC
2694/* Should we try one of the 'Z' requests? */
2695
2696enum Z_packet_type
2697{
2698 Z_PACKET_SOFTWARE_BP,
2699 Z_PACKET_HARDWARE_BP,
2700 Z_PACKET_WRITE_WP,
2701 Z_PACKET_READ_WP,
2702 Z_PACKET_ACCESS_WP,
2703 NR_Z_PACKET_TYPES
2704};
96baa820 2705
d471ea57 2706/* For compatibility with older distributions. Provide a ``set remote
23860348 2707 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2708
7f19b9a2 2709static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2710
2711static void
eb4c3f4a 2712set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2713 struct cmd_list_element *c)
96baa820 2714{
ff52c073 2715 remote_target *remote = get_current_remote_target ();
d471ea57 2716 int i;
a744cf53 2717
d471ea57 2718 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
ff52c073
CS
2719 {
2720 if (remote != nullptr)
2721 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2722 = remote_Z_packet_detect;
2723 else
2724 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2725 }
2726
2727 const char *support = get_packet_support_name (remote_Z_packet_detect);
2728 const char *target_type = get_target_type_name (remote != nullptr);
2729 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2730 support);
2731
96baa820
JM
2732}
2733
2734static void
08546159
AC
2735show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2736 struct cmd_list_element *c,
2737 const char *value)
96baa820 2738{
ff52c073 2739 remote_target *remote = get_current_remote_target ();
d471ea57 2740 int i;
a744cf53 2741
d471ea57 2742 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
ff52c073 2743 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2c2e7f87
LM
2744}
2745
cbb8991c
DB
2746/* Insert fork catchpoint target routine. If fork events are enabled
2747 then return success, nothing more to do. */
2748
f6ac5f3d
PA
2749int
2750remote_target::insert_fork_catchpoint (int pid)
cbb8991c 2751{
ff52c073 2752 return !m_features.remote_fork_event_p ();
cbb8991c
DB
2753}
2754
2755/* Remove fork catchpoint target routine. Nothing to do, just
2756 return success. */
2757
f6ac5f3d
PA
2758int
2759remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2760{
2761 return 0;
2762}
2763
2764/* Insert vfork catchpoint target routine. If vfork events are enabled
2765 then return success, nothing more to do. */
2766
f6ac5f3d
PA
2767int
2768remote_target::insert_vfork_catchpoint (int pid)
cbb8991c 2769{
ff52c073 2770 return !m_features.remote_vfork_event_p ();
cbb8991c
DB
2771}
2772
2773/* Remove vfork catchpoint target routine. Nothing to do, just
2774 return success. */
2775
f6ac5f3d
PA
2776int
2777remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2778{
2779 return 0;
2780}
2781
d46addbb
DB
2782/* Insert exec catchpoint target routine. If exec events are
2783 enabled, just return success. */
2784
f6ac5f3d
PA
2785int
2786remote_target::insert_exec_catchpoint (int pid)
d46addbb 2787{
ff52c073 2788 return !m_features.remote_exec_event_p ();
d46addbb
DB
2789}
2790
2791/* Remove exec catchpoint target routine. Nothing to do, just
2792 return success. */
2793
f6ac5f3d
PA
2794int
2795remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2796{
2797 return 0;
2798}
2799
c906108c
SS
2800\f
2801
ffdd69cf
TT
2802/* Take advantage of the fact that the TID field is not used, to tag
2803 special ptids with it set to != 0. */
2804static const ptid_t magic_null_ptid (42000, -1, 1);
2805static const ptid_t not_sent_ptid (42000, -2, 1);
2806static const ptid_t any_thread_ptid (42000, 0, 1);
79d7f229 2807
0b16c5cf
PA
2808/* Find out if the stub attached to PID (and hence GDB should offer to
2809 detach instead of killing it when bailing out). */
2810
6b8edb51
PA
2811int
2812remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2813{
2814 struct remote_state *rs = get_remote_state ();
bba74b36 2815 size_t size = get_remote_packet_size ();
0b16c5cf 2816
ff52c073 2817 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2818 return 0;
2819
ff52c073 2820 if (m_features.remote_multi_process_p ())
8d64371b 2821 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
0b16c5cf 2822 else
8d64371b 2823 xsnprintf (rs->buf.data (), size, "qAttached");
0b16c5cf
PA
2824
2825 putpkt (rs->buf);
aa7b36b8 2826 getpkt (&rs->buf);
0b16c5cf 2827
94a94c90 2828 packet_result result = m_features.packet_ok (rs->buf, PACKET_qAttached);
9df979ca 2829 switch (result.status ())
0b16c5cf
PA
2830 {
2831 case PACKET_OK:
8d64371b 2832 if (strcmp (rs->buf.data (), "1") == 0)
0b16c5cf
PA
2833 return 1;
2834 break;
2835 case PACKET_ERROR:
9df979ca 2836 warning (_("Remote failure reply: %s"), result.err_msg ());
0b16c5cf
PA
2837 break;
2838 case PACKET_UNKNOWN:
2839 break;
2840 }
2841
2842 return 0;
2843}
2844
49c62f2e
PA
2845/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2846 has been invented by GDB, instead of reported by the target. Since
2847 we can be connected to a remote system before before knowing about
2848 any inferior, mark the target with execution when we find the first
2849 inferior. If ATTACHED is 1, then we had just attached to this
2850 inferior. If it is 0, then we just created this inferior. If it
2851 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2852 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2853 attempt to open this inferior's executable as the main executable
2854 if no main executable is open already. */
1941c569 2855
6b8edb51 2856inferior *
9ab8741a 2857remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51 2858 int try_open_exec)
1941c569 2859{
1941c569
PA
2860 struct inferior *inf;
2861
0b16c5cf
PA
2862 /* Check whether this process we're learning about is to be
2863 considered attached, or if is to be considered to have been
2864 spawned by the stub. */
2865 if (attached == -1)
2866 attached = remote_query_attached (pid);
2867
99d9c3b9 2868 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
6c95b8df
PA
2869 {
2870 /* If the target shares code across all inferiors, then every
2871 attach adds a new inferior. */
2872 inf = add_inferior (pid);
2873
2874 /* ... and every inferior is bound to the same program space.
2875 However, each inferior may still have its own address
2876 space. */
2877 inf->aspace = maybe_new_address_space ();
2878 inf->pspace = current_program_space;
2879 }
2880 else
2881 {
2882 /* In the traditional debugging scenario, there's a 1-1 match
2883 between program/address spaces. We simply bind the inferior
2884 to the program space's address space. */
2885 inf = current_inferior ();
78f2c40a
PA
2886
2887 /* However, if the current inferior is already bound to a
2888 process, find some other empty inferior. */
2889 if (inf->pid != 0)
2890 {
2891 inf = nullptr;
2892 for (inferior *it : all_inferiors ())
2893 if (it->pid == 0)
2894 {
2895 inf = it;
2896 break;
2897 }
2898 }
2899 if (inf == nullptr)
2900 {
2901 /* Since all inferiors were already bound to a process, add
2902 a new inferior. */
2903 inf = add_inferior_with_spaces ();
2904 }
2905 switch_to_inferior_no_thread (inf);
02980c56 2906 inf->push_target (this);
6c95b8df
PA
2907 inferior_appeared (inf, pid);
2908 }
1941c569 2909
0b16c5cf 2910 inf->attach_flag = attached;
49c62f2e 2911 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2912
1b6e6f5c
GB
2913 /* If no main executable is currently open then attempt to
2914 open the file that was executed to create this inferior. */
0a70e1a8 2915 if (try_open_exec && current_program_space->exec_filename () == nullptr)
bb805577 2916 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2917
a2fedca9
PW
2918 /* Check for exec file mismatch, and let the user solve it. */
2919 validate_exec_file (1);
2920
1941c569
PA
2921 return inf;
2922}
2923
7aabaf9d 2924static remote_thread_info *get_remote_thread_info (thread_info *thread);
5b6d1e4f
PA
2925static remote_thread_info *get_remote_thread_info (remote_target *target,
2926 ptid_t ptid);
85ad3aaf 2927
1941c569 2928/* Add thread PTID to GDB's thread list. Tag it as executing/running
b622494e
AB
2929 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2930 remote_state::starting_up flag) is true then the new thread is added
2931 silently, otherwise the new thread will be announced to the user. */
1941c569 2932
00431a78 2933thread_info *
b622494e
AB
2934remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2935 bool silent_p)
c906108c 2936{
b7ea362b 2937 struct remote_state *rs = get_remote_state ();
85ad3aaf 2938 struct thread_info *thread;
b7ea362b
PA
2939
2940 /* GDB historically didn't pull threads in the initial connection
2941 setup. If the remote target doesn't even have a concept of
2942 threads (e.g., a bare-metal target), even if internally we
2943 consider that a single-threaded target, mentioning a new thread
2944 might be confusing to the user. Be silent then, preserving the
2945 age old behavior. */
b622494e 2946 if (rs->starting_up || silent_p)
5b6d1e4f 2947 thread = add_thread_silent (this, ptid);
b7ea362b 2948 else
5b6d1e4f 2949 thread = add_thread (this, ptid);
1941c569 2950
53de5394
PA
2951 if (executing)
2952 get_remote_thread_info (thread)->set_resumed ();
5b6d1e4f
PA
2953 set_executing (this, ptid, executing);
2954 set_running (this, ptid, running);
00431a78
PA
2955
2956 return thread;
1941c569
PA
2957}
2958
2959/* Come here when we learn about a thread id from the remote target.
2960 It may be the first time we hear about such thread, so take the
2961 opportunity to add it to GDB's thread list. In case this is the
2962 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2963 GDB's inferior list as well. EXECUTING indicates whether the
2964 thread is (internally) executing or stopped. */
1941c569 2965
6b8edb51 2966void
8a82de58 2967remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
1941c569 2968{
0d5b594f
PA
2969 /* In non-stop mode, we assume new found threads are (externally)
2970 running until proven otherwise with a stop reply. In all-stop,
2971 we can only get here if all threads are stopped. */
8a82de58 2972 bool running = target_is_non_stop_p ();
0d5b594f 2973
c906108c
SS
2974 /* If this is a new thread, add it to GDB's thread list.
2975 If we leave it up to WFI to do this, bad things will happen. */
82f73884 2976
9213a6d7 2977 thread_info *tp = this->find_thread (currthread);
00431a78 2978 if (tp != NULL && tp->state == THREAD_EXITED)
82f73884
PA
2979 {
2980 /* We're seeing an event on a thread id we knew had exited.
2981 This has to be a new thread reusing the old id. Add it. */
b622494e 2982 remote_add_thread (currthread, running, executing, false);
82f73884
PA
2983 return;
2984 }
2985
5b6d1e4f 2986 if (!in_thread_list (this, currthread))
c0a2216e 2987 {
1941c569 2988 struct inferior *inf = NULL;
e99b03dc 2989 int pid = currthread.pid ();
1941c569 2990
0e998d96 2991 if (inferior_ptid.is_pid ()
e99b03dc 2992 && pid == inferior_ptid.pid ())
c0a2216e
PA
2993 {
2994 /* inferior_ptid has no thread member yet. This can happen
2995 with the vAttach -> remote_wait,"TAAthread:" path if the
2996 stub doesn't support qC. This is the first stop reported
2997 after an attach, so this is the main thread. Update the
2998 ptid in the thread list. */
5b6d1e4f
PA
2999 if (in_thread_list (this, ptid_t (pid)))
3000 thread_change_ptid (this, inferior_ptid, currthread);
bad34192
PA
3001 else
3002 {
0ac55310 3003 thread_info *thr
b622494e 3004 = remote_add_thread (currthread, running, executing, false);
0ac55310 3005 switch_to_thread (thr);
bad34192 3006 }
dc146f7c 3007 return;
c0a2216e 3008 }
82f73884 3009
d7e15655 3010 if (magic_null_ptid == inferior_ptid)
c0a2216e
PA
3011 {
3012 /* inferior_ptid is not set yet. This can happen with the
3013 vRun -> remote_wait,"TAAthread:" path if the stub
3014 doesn't support qC. This is the first stop reported
3015 after an attach, so this is the main thread. Update the
3016 ptid in the thread list. */
5b6d1e4f 3017 thread_change_ptid (this, inferior_ptid, currthread);
82f73884 3018 return;
c0a2216e 3019 }
82f73884 3020
29c87f7f
PA
3021 /* When connecting to a target remote, or to a target
3022 extended-remote which already was debugging an inferior, we
3023 may not know about it yet. Add it before adding its child
3024 thread, so notifications are emitted in a sensible order. */
5b6d1e4f 3025 if (find_inferior_pid (this, currthread.pid ()) == NULL)
49c62f2e 3026 {
ff52c073 3027 bool fake_pid_p = !m_features.remote_multi_process_p ();
49c62f2e
PA
3028
3029 inf = remote_add_inferior (fake_pid_p,
e99b03dc 3030 currthread.pid (), -1, 1);
49c62f2e 3031 }
29c87f7f 3032
82f73884 3033 /* This is really a new thread. Add it. */
00431a78 3034 thread_info *new_thr
b622494e 3035 = remote_add_thread (currthread, running, executing, false);
1941c569
PA
3036
3037 /* If we found a new inferior, let the common code do whatever
3038 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
3039 breakpoints), unless we're just setting up an all-stop
3040 connection. */
1941c569 3041 if (inf != NULL)
b7ea362b
PA
3042 {
3043 struct remote_state *rs = get_remote_state ();
3044
6efcd9a8 3045 if (!rs->starting_up)
00431a78 3046 notice_new_inferior (new_thr, executing, 0);
b7ea362b 3047 }
c0a2216e 3048 }
c906108c
SS
3049}
3050
85ad3aaf 3051/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 3052
7aabaf9d
SM
3053static remote_thread_info *
3054get_remote_thread_info (thread_info *thread)
dc146f7c 3055{
85ad3aaf 3056 gdb_assert (thread != NULL);
dc146f7c 3057
85ad3aaf 3058 if (thread->priv == NULL)
40ae603e 3059 thread->priv = std::make_unique<remote_thread_info> ();
dc146f7c 3060
98ed24fb 3061 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
3062}
3063
5b6d1e4f
PA
3064/* Return PTID's private thread data, creating it if necessary. */
3065
7aabaf9d 3066static remote_thread_info *
5b6d1e4f 3067get_remote_thread_info (remote_target *target, ptid_t ptid)
85ad3aaf 3068{
9213a6d7 3069 thread_info *thr = target->find_thread (ptid);
00431a78 3070 return get_remote_thread_info (thr);
dc146f7c
VP
3071}
3072
74531fed
PA
3073/* Call this function as a result of
3074 1) A halt indication (T packet) containing a thread id
3075 2) A direct query of currthread
0df8b418 3076 3) Successful execution of set thread */
74531fed
PA
3077
3078static void
47f8a51d 3079record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 3080{
47f8a51d 3081 rs->general_thread = currthread;
74531fed
PA
3082}
3083
89be2091
DJ
3084/* If 'QPassSignals' is supported, tell the remote stub what signals
3085 it can simply pass through to the inferior without reporting. */
3086
f6ac5f3d 3087void
adc6a863 3088remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
89be2091 3089{
ff52c073 3090 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
3091 {
3092 char *pass_packet, *p;
adc6a863 3093 int count = 0;
747dc59d 3094 struct remote_state *rs = get_remote_state ();
89be2091 3095
adc6a863
PA
3096 gdb_assert (pass_signals.size () < 256);
3097 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 3098 {
2455069d 3099 if (pass_signals[i])
89be2091
DJ
3100 count++;
3101 }
224c3ddb 3102 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
3103 strcpy (pass_packet, "QPassSignals:");
3104 p = pass_packet + strlen (pass_packet);
adc6a863 3105 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 3106 {
2455069d 3107 if (pass_signals[i])
89be2091
DJ
3108 {
3109 if (i >= 16)
3110 *p++ = tohex (i >> 4);
3111 *p++ = tohex (i & 15);
3112 if (count)
3113 *p++ = ';';
3114 else
3115 break;
3116 count--;
3117 }
3118 }
3119 *p = 0;
747dc59d 3120 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 3121 {
89be2091 3122 putpkt (pass_packet);
aa7b36b8 3123 getpkt (&rs->buf);
ff52c073 3124 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
84d53fa9 3125 xfree (rs->last_pass_packet);
747dc59d 3126 rs->last_pass_packet = pass_packet;
89be2091
DJ
3127 }
3128 else
3129 xfree (pass_packet);
3130 }
3131}
3132
82075af2
JS
3133/* If 'QCatchSyscalls' is supported, tell the remote stub
3134 to report syscalls to GDB. */
3135
f6ac5f3d
PA
3136int
3137remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
3138 gdb::array_view<const int> syscall_counts)
82075af2 3139{
b80406ac 3140 const char *catch_packet;
82075af2
JS
3141 int n_sysno = 0;
3142
ff52c073 3143 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
82075af2
JS
3144 {
3145 /* Not supported. */
3146 return 1;
3147 }
3148
649a140c 3149 if (needed && any_count == 0)
82075af2 3150 {
649a140c
PA
3151 /* Count how many syscalls are to be caught. */
3152 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 3153 {
649a140c 3154 if (syscall_counts[i] != 0)
82075af2
JS
3155 n_sysno++;
3156 }
3157 }
3158
2189c312
SM
3159 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3160 pid, needed, any_count, n_sysno);
82075af2 3161
1b81856f 3162 std::string built_packet;
82075af2
JS
3163 if (needed)
3164 {
3165 /* Prepare a packet with the sysno list, assuming max 8+1
3166 characters for a sysno. If the resulting packet size is too
3167 big, fallback on the non-selective packet. */
3168 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
3169 built_packet.reserve (maxpktsz);
3170 built_packet = "QCatchSyscalls:1";
649a140c 3171 if (any_count == 0)
82075af2 3172 {
649a140c
PA
3173 /* Add in each syscall to be caught. */
3174 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 3175 {
649a140c
PA
3176 if (syscall_counts[i] != 0)
3177 string_appendf (built_packet, ";%zx", i);
82075af2
JS
3178 }
3179 }
1b81856f 3180 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
3181 {
3182 /* catch_packet too big. Fallback to less efficient
3183 non selective mode, with GDB doing the filtering. */
b80406ac 3184 catch_packet = "QCatchSyscalls:1";
82075af2 3185 }
b80406ac 3186 else
1b81856f 3187 catch_packet = built_packet.c_str ();
82075af2
JS
3188 }
3189 else
b80406ac 3190 catch_packet = "QCatchSyscalls:0";
82075af2 3191
b80406ac 3192 struct remote_state *rs = get_remote_state ();
82075af2 3193
b80406ac 3194 putpkt (catch_packet);
aa7b36b8 3195 getpkt (&rs->buf);
94a94c90 3196 packet_result result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
9df979ca 3197 if (result.status () == PACKET_OK)
b80406ac
TT
3198 return 0;
3199 else
3200 return -1;
82075af2
JS
3201}
3202
9b224c5e
PA
3203/* If 'QProgramSignals' is supported, tell the remote stub what
3204 signals it should pass through to the inferior when detaching. */
3205
f6ac5f3d 3206void
adc6a863 3207remote_target::program_signals (gdb::array_view<const unsigned char> signals)
9b224c5e 3208{
ff52c073 3209 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
3210 {
3211 char *packet, *p;
adc6a863 3212 int count = 0;
5e4a05c4 3213 struct remote_state *rs = get_remote_state ();
9b224c5e 3214
adc6a863
PA
3215 gdb_assert (signals.size () < 256);
3216 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
3217 {
3218 if (signals[i])
3219 count++;
3220 }
224c3ddb 3221 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
3222 strcpy (packet, "QProgramSignals:");
3223 p = packet + strlen (packet);
adc6a863 3224 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
3225 {
3226 if (signal_pass_state (i))
3227 {
3228 if (i >= 16)
3229 *p++ = tohex (i >> 4);
3230 *p++ = tohex (i & 15);
3231 if (count)
3232 *p++ = ';';
3233 else
3234 break;
3235 count--;
3236 }
3237 }
3238 *p = 0;
5e4a05c4
TT
3239 if (!rs->last_program_signals_packet
3240 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 3241 {
9b224c5e 3242 putpkt (packet);
aa7b36b8 3243 getpkt (&rs->buf);
ff52c073 3244 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
5e4a05c4
TT
3245 xfree (rs->last_program_signals_packet);
3246 rs->last_program_signals_packet = packet;
9b224c5e
PA
3247 }
3248 else
3249 xfree (packet);
3250 }
3251}
3252
79d7f229
PA
3253/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3254 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3255 thread. If GEN is set, set the general thread, if not, then set
3256 the step/continue thread. */
6b8edb51
PA
3257void
3258remote_target::set_thread (ptid_t ptid, int gen)
c906108c 3259{
d01949b6 3260 struct remote_state *rs = get_remote_state ();
47f8a51d 3261 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
8d64371b
TT
3262 char *buf = rs->buf.data ();
3263 char *endbuf = buf + get_remote_packet_size ();
c906108c 3264
d7e15655 3265 if (state == ptid)
c906108c
SS
3266 return;
3267
79d7f229
PA
3268 *buf++ = 'H';
3269 *buf++ = gen ? 'g' : 'c';
d7e15655 3270 if (ptid == magic_null_ptid)
79d7f229 3271 xsnprintf (buf, endbuf - buf, "0");
d7e15655 3272 else if (ptid == any_thread_ptid)
79d7f229 3273 xsnprintf (buf, endbuf - buf, "0");
d7e15655 3274 else if (ptid == minus_one_ptid)
79d7f229
PA
3275 xsnprintf (buf, endbuf - buf, "-1");
3276 else
82f73884 3277 write_ptid (buf, endbuf, ptid);
79d7f229 3278 putpkt (rs->buf);
aa7b36b8 3279 getpkt (&rs->buf);
c906108c 3280 if (gen)
47f8a51d 3281 rs->general_thread = ptid;
c906108c 3282 else
47f8a51d 3283 rs->continue_thread = ptid;
c906108c 3284}
79d7f229 3285
6b8edb51
PA
3286void
3287remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
3288{
3289 set_thread (ptid, 1);
3290}
3291
6b8edb51
PA
3292void
3293remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
3294{
3295 set_thread (ptid, 0);
3296}
3297
3c9c4b83
PA
3298/* Change the remote current process. Which thread within the process
3299 ends up selected isn't important, as long as it is the same process
3300 as what INFERIOR_PTID points to.
3301
3302 This comes from that fact that there is no explicit notion of
3303 "selected process" in the protocol. The selected process for
3304 general operations is the process the selected general thread
3305 belongs to. */
3306
6b8edb51
PA
3307void
3308remote_target::set_general_process ()
3c9c4b83 3309{
3c9c4b83 3310 /* If the remote can't handle multiple processes, don't bother. */
ff52c073 3311 if (!m_features.remote_multi_process_p ())
3c9c4b83
PA
3312 return;
3313
ff52c073
CS
3314 remote_state *rs = get_remote_state ();
3315
3c9c4b83
PA
3316 /* We only need to change the remote current thread if it's pointing
3317 at some other process. */
e99b03dc 3318 if (rs->general_thread.pid () != inferior_ptid.pid ())
3c9c4b83
PA
3319 set_general_thread (inferior_ptid);
3320}
3321
c906108c 3322\f
7d1a114c
PA
3323/* Return nonzero if this is the main thread that we made up ourselves
3324 to model non-threaded targets as single-threaded. */
c906108c
SS
3325
3326static int
f6ac5f3d 3327remote_thread_always_alive (ptid_t ptid)
c906108c 3328{
d7e15655 3329 if (ptid == magic_null_ptid)
c0a2216e
PA
3330 /* The main thread is always alive. */
3331 return 1;
3332
e38504b3 3333 if (ptid.pid () != 0 && ptid.lwp () == 0)
c0a2216e
PA
3334 /* The main thread is always alive. This can happen after a
3335 vAttach, if the remote side doesn't support
3336 multi-threading. */
3337 return 1;
3338
7d1a114c
PA
3339 return 0;
3340}
3341
3342/* Return nonzero if the thread PTID is still alive on the remote
3343 system. */
3344
57810aa7 3345bool
f6ac5f3d 3346remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
3347{
3348 struct remote_state *rs = get_remote_state ();
3349 char *p, *endp;
3350
3351 /* Check if this is a thread that we made up ourselves to model
3352 non-threaded targets as single-threaded. */
f6ac5f3d 3353 if (remote_thread_always_alive (ptid))
7d1a114c
PA
3354 return 1;
3355
8d64371b
TT
3356 p = rs->buf.data ();
3357 endp = p + get_remote_packet_size ();
82f73884
PA
3358
3359 *p++ = 'T';
3360 write_ptid (p, endp, ptid);
3361
2e9f7625 3362 putpkt (rs->buf);
aa7b36b8 3363 getpkt (&rs->buf);
2e9f7625 3364 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
3365}
3366
79efa585
SM
3367/* Return a pointer to a thread name if we know it and NULL otherwise.
3368 The thread_info object owns the memory for the name. */
3369
f6ac5f3d
PA
3370const char *
3371remote_target::thread_name (struct thread_info *info)
79efa585
SM
3372{
3373 if (info->priv != NULL)
a9334058
SM
3374 {
3375 const std::string &name = get_remote_thread_info (info)->name;
3376 return !name.empty () ? name.c_str () : NULL;
3377 }
79efa585
SM
3378
3379 return NULL;
3380}
3381
c906108c
SS
3382/* About these extended threadlist and threadinfo packets. They are
3383 variable length packets but, the fields within them are often fixed
30baf67b 3384 length. They are redundant enough to send over UDP as is the
c906108c
SS
3385 remote protocol in general. There is a matching unit test module
3386 in libstub. */
3387
23860348 3388/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 3389 libstub protocol encoding, and remote.c. It is not particularly
33b5899f 3390 changeable. */
cce74817
JM
3391
3392/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 3393 Plan to fix this. */
cce74817 3394
23860348 3395typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 3396
9d1f7ab2 3397/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 3398 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
3399
3400struct gdb_ext_thread_info
c5aa993b 3401 {
23860348 3402 threadref threadid; /* External form of thread reference. */
2bc416ba 3403 int active; /* Has state interesting to GDB?
23860348 3404 regs, stack. */
2bc416ba 3405 char display[256]; /* Brief state display, name,
cedea757 3406 blocked/suspended. */
23860348 3407 char shortname[32]; /* To be used to name threads. */
2bc416ba 3408 char more_display[256]; /* Long info, statistics, queue depth,
23860348 3409 whatever. */
c5aa993b 3410 };
cce74817 3411
23860348 3412#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 3413
cecb1912 3414static const char *unpack_nibble (const char *buf, int *val);
cce74817 3415
cecb1912 3416static const char *unpack_byte (const char *buf, int *value);
cce74817 3417
a14ed312 3418static char *pack_int (char *buf, int value);
cce74817 3419
cecb1912 3420static const char *unpack_int (const char *buf, int *value);
cce74817 3421
cecb1912 3422static const char *unpack_string (const char *src, char *dest, int length);
cce74817 3423
23860348 3424static char *pack_threadid (char *pkt, threadref *id);
cce74817 3425
cecb1912 3426static const char *unpack_threadid (const char *inbuf, threadref *id);
cce74817 3427
23860348 3428void int_to_threadref (threadref *id, int value);
cce74817 3429
23860348 3430static int threadref_to_int (threadref *ref);
cce74817 3431
23860348 3432static void copy_threadref (threadref *dest, threadref *src);
cce74817 3433
23860348 3434static int threadmatch (threadref *dest, threadref *src);
cce74817 3435
2bc416ba 3436static char *pack_threadinfo_request (char *pkt, int mode,
23860348 3437 threadref *id);
cce74817 3438
a14ed312
KB
3439static char *pack_threadlist_request (char *pkt, int startflag,
3440 int threadcount,
23860348 3441 threadref *nextthread);
cce74817 3442
23860348 3443static int remote_newthread_step (threadref *ref, void *context);
cce74817 3444
82f73884
PA
3445
3446/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3447 buffer we're allowed to write to. Returns
3448 BUF+CHARACTERS_WRITTEN. */
3449
6b8edb51
PA
3450char *
3451remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
3452{
3453 int pid, tid;
82f73884 3454
ff52c073 3455 if (m_features.remote_multi_process_p ())
82f73884 3456 {
e99b03dc 3457 pid = ptid.pid ();
82f73884
PA
3458 if (pid < 0)
3459 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3460 else
3461 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3462 }
e38504b3 3463 tid = ptid.lwp ();
82f73884
PA
3464 if (tid < 0)
3465 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3466 else
3467 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3468
3469 return buf;
3470}
3471
256642e8
PA
3472/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3473 last parsed char. Returns null_ptid if no thread id is found, and
3474 throws an error if the thread id has an invalid format. */
82f73884
PA
3475
3476static ptid_t
256642e8 3477read_ptid (const char *buf, const char **obuf)
82f73884 3478{
256642e8
PA
3479 const char *p = buf;
3480 const char *pp;
82f73884 3481 ULONGEST pid = 0, tid = 0;
82f73884
PA
3482
3483 if (*p == 'p')
3484 {
3485 /* Multi-process ptid. */
3486 pp = unpack_varlen_hex (p + 1, &pid);
3487 if (*pp != '.')
b37520b6 3488 error (_("invalid remote ptid: %s"), p);
82f73884
PA
3489
3490 p = pp;
3491 pp = unpack_varlen_hex (p + 1, &tid);
3492 if (obuf)
3493 *obuf = pp;
184ea2f7 3494 return ptid_t (pid, tid);
82f73884
PA
3495 }
3496
3497 /* No multi-process. Just a tid. */
3498 pp = unpack_varlen_hex (p, &tid);
3499
c9f35b34
KB
3500 /* Return null_ptid when no thread id is found. */
3501 if (p == pp)
3502 {
3503 if (obuf)
3504 *obuf = pp;
3505 return null_ptid;
3506 }
3507
2f761de2
TBA
3508 /* Since the stub is not sending a process id, default to what's
3509 current_inferior, unless it doesn't have a PID yet. If so,
ca19bf23
PA
3510 then since there's no way to know the pid of the reported
3511 threads, use the magic number. */
2f761de2
TBA
3512 inferior *inf = current_inferior ();
3513 if (inf->pid == 0)
e99b03dc 3514 pid = magic_null_ptid.pid ();
ca19bf23 3515 else
2f761de2 3516 pid = inf->pid;
82f73884
PA
3517
3518 if (obuf)
3519 *obuf = pp;
184ea2f7 3520 return ptid_t (pid, tid);
82f73884
PA
3521}
3522
c906108c 3523static int
fba45db2 3524stubhex (int ch)
c906108c
SS
3525{
3526 if (ch >= 'a' && ch <= 'f')
3527 return ch - 'a' + 10;
3528 if (ch >= '0' && ch <= '9')
3529 return ch - '0';
3530 if (ch >= 'A' && ch <= 'F')
3531 return ch - 'A' + 10;
3532 return -1;
3533}
3534
3535static int
cecb1912 3536stub_unpack_int (const char *buff, int fieldlength)
c906108c
SS
3537{
3538 int nibble;
3539 int retval = 0;
3540
3541 while (fieldlength)
3542 {
3543 nibble = stubhex (*buff++);
3544 retval |= nibble;
3545 fieldlength--;
3546 if (fieldlength)
3547 retval = retval << 4;
3548 }
3549 return retval;
3550}
3551
cecb1912
SM
3552static const char *
3553unpack_nibble (const char *buf, int *val)
c906108c 3554{
b7589f7d 3555 *val = fromhex (*buf++);
c906108c
SS
3556 return buf;
3557}
3558
cecb1912
SM
3559static const char *
3560unpack_byte (const char *buf, int *value)
c906108c
SS
3561{
3562 *value = stub_unpack_int (buf, 2);
3563 return buf + 2;
3564}
3565
3566static char *
fba45db2 3567pack_int (char *buf, int value)
c906108c
SS
3568{
3569 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3570 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3571 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3572 buf = pack_hex_byte (buf, (value & 0xff));
3573 return buf;
3574}
3575
cecb1912
SM
3576static const char *
3577unpack_int (const char *buf, int *value)
c906108c
SS
3578{
3579 *value = stub_unpack_int (buf, 8);
3580 return buf + 8;
3581}
3582
23860348 3583#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3584static char *pack_string (char *pkt, char *string);
c906108c
SS
3585
3586static char *
fba45db2 3587pack_string (char *pkt, char *string)
c906108c
SS
3588{
3589 char ch;
3590 int len;
3591
3592 len = strlen (string);
3593 if (len > 200)
23860348 3594 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3595 pkt = pack_hex_byte (pkt, len);
3596 while (len-- > 0)
3597 {
3598 ch = *string++;
3599 if ((ch == '\0') || (ch == '#'))
23860348 3600 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3601 *pkt++ = ch;
3602 }
3603 return pkt;
3604}
3605#endif /* 0 (unused) */
3606
cecb1912
SM
3607static const char *
3608unpack_string (const char *src, char *dest, int length)
c906108c
SS
3609{
3610 while (length--)
3611 *dest++ = *src++;
3612 *dest = '\0';
3613 return src;
3614}
3615
3616static char *
fba45db2 3617pack_threadid (char *pkt, threadref *id)
c906108c
SS
3618{
3619 char *limit;
3620 unsigned char *altid;
3621
3622 altid = (unsigned char *) id;
3623 limit = pkt + BUF_THREAD_ID_SIZE;
3624 while (pkt < limit)
3625 pkt = pack_hex_byte (pkt, *altid++);
3626 return pkt;
3627}
3628
3629
cecb1912
SM
3630static const char *
3631unpack_threadid (const char *inbuf, threadref *id)
c906108c
SS
3632{
3633 char *altref;
cecb1912 3634 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
c906108c
SS
3635 int x, y;
3636
3637 altref = (char *) id;
3638
3639 while (inbuf < limit)
3640 {
3641 x = stubhex (*inbuf++);
3642 y = stubhex (*inbuf++);
3643 *altref++ = (x << 4) | y;
3644 }
3645 return inbuf;
3646}
3647
3648/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3649 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3650 to use 64bit thread references internally. This is an adapter
3651 function. */
3652
3653void
fba45db2 3654int_to_threadref (threadref *id, int value)
c906108c
SS
3655{
3656 unsigned char *scan;
3657
3658 scan = (unsigned char *) id;
3659 {
3660 int i = 4;
3661 while (i--)
3662 *scan++ = 0;
3663 }
3664 *scan++ = (value >> 24) & 0xff;
3665 *scan++ = (value >> 16) & 0xff;
3666 *scan++ = (value >> 8) & 0xff;
3667 *scan++ = (value & 0xff);
3668}
3669
3670static int
fba45db2 3671threadref_to_int (threadref *ref)
c906108c
SS
3672{
3673 int i, value = 0;
3674 unsigned char *scan;
3675
cfd77fa1 3676 scan = *ref;
c906108c
SS
3677 scan += 4;
3678 i = 4;
3679 while (i-- > 0)
3680 value = (value << 8) | ((*scan++) & 0xff);
3681 return value;
3682}
3683
3684static void
fba45db2 3685copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3686{
3687 int i;
3688 unsigned char *csrc, *cdest;
3689
3690 csrc = (unsigned char *) src;
3691 cdest = (unsigned char *) dest;
3692 i = 8;
3693 while (i--)
3694 *cdest++ = *csrc++;
3695}
3696
3697static int
fba45db2 3698threadmatch (threadref *dest, threadref *src)
c906108c 3699{
23860348 3700 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3701#if 0
3702 unsigned char *srcp, *destp;
3703 int i, result;
3704 srcp = (char *) src;
3705 destp = (char *) dest;
3706
3707 result = 1;
3708 while (i-- > 0)
3709 result &= (*srcp++ == *destp++) ? 1 : 0;
3710 return result;
3711#endif
3712 return 1;
3713}
3714
3715/*
c5aa993b
JM
3716 threadid:1, # always request threadid
3717 context_exists:2,
3718 display:4,
3719 unique_name:8,
3720 more_display:16
3721 */
c906108c
SS
3722
3723/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3724
3725static char *
fba45db2 3726pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3727{
23860348
MS
3728 *pkt++ = 'q'; /* Info Query */
3729 *pkt++ = 'P'; /* process or thread info */
3730 pkt = pack_int (pkt, mode); /* mode */
c906108c 3731 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3732 *pkt = '\0'; /* terminate */
c906108c
SS
3733 return pkt;
3734}
3735
23860348 3736/* These values tag the fields in a thread info response packet. */
c906108c 3737/* Tagging the fields allows us to request specific fields and to
23860348 3738 add more fields as time goes by. */
c906108c 3739
23860348 3740#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3741#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3742 fetch registers and its stack? */
c5aa993b 3743#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3744#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3745#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3746 the process. */
c906108c 3747
6b8edb51 3748int
cecb1912 3749remote_target::remote_unpack_thread_info_response (const char *pkt,
6b8edb51
PA
3750 threadref *expectedref,
3751 gdb_ext_thread_info *info)
c906108c 3752{
d01949b6 3753 struct remote_state *rs = get_remote_state ();
c906108c 3754 int mask, length;
cfd77fa1 3755 int tag;
c906108c 3756 threadref ref;
cecb1912 3757 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
c906108c
SS
3758 int retval = 1;
3759
23860348 3760 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3761 info->active = 0;
3762 info->display[0] = '\0';
3763 info->shortname[0] = '\0';
3764 info->more_display[0] = '\0';
3765
23860348
MS
3766 /* Assume the characters indicating the packet type have been
3767 stripped. */
c906108c
SS
3768 pkt = unpack_int (pkt, &mask); /* arg mask */
3769 pkt = unpack_threadid (pkt, &ref);
3770
3771 if (mask == 0)
8a3fe4f8 3772 warning (_("Incomplete response to threadinfo request."));
c906108c 3773 if (!threadmatch (&ref, expectedref))
23860348 3774 { /* This is an answer to a different request. */
8a3fe4f8 3775 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3776 return 0;
3777 }
3778 copy_threadref (&info->threadid, &ref);
3779
405feb71 3780 /* Loop on tagged fields , try to bail if something goes wrong. */
c906108c 3781
23860348
MS
3782 /* Packets are terminated with nulls. */
3783 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3784 {
3785 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3786 pkt = unpack_byte (pkt, &length); /* length */
3787 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3788 {
8a3fe4f8 3789 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3790 retval = 0;
3791 break;
3792 }
3793 if (tag == TAG_THREADID)
3794 {
3795 if (length != 16)
3796 {
8a3fe4f8 3797 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3798 retval = 0;
3799 break;
3800 }
3801 pkt = unpack_threadid (pkt, &ref);
3802 mask = mask & ~TAG_THREADID;
3803 continue;
3804 }
3805 if (tag == TAG_EXISTS)
3806 {
3807 info->active = stub_unpack_int (pkt, length);
3808 pkt += length;
3809 mask = mask & ~(TAG_EXISTS);
3810 if (length > 8)
3811 {
8a3fe4f8 3812 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3813 retval = 0;
3814 break;
3815 }
3816 continue;
3817 }
3818 if (tag == TAG_THREADNAME)
3819 {
3820 pkt = unpack_string (pkt, &info->shortname[0], length);
3821 mask = mask & ~TAG_THREADNAME;
3822 continue;
3823 }
3824 if (tag == TAG_DISPLAY)
3825 {
3826 pkt = unpack_string (pkt, &info->display[0], length);
3827 mask = mask & ~TAG_DISPLAY;
3828 continue;
3829 }
3830 if (tag == TAG_MOREDISPLAY)
3831 {
3832 pkt = unpack_string (pkt, &info->more_display[0], length);
3833 mask = mask & ~TAG_MOREDISPLAY;
3834 continue;
3835 }
8a3fe4f8 3836 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3837 break; /* Not a tag we know about. */
c906108c
SS
3838 }
3839 return retval;
3840}
3841
6b8edb51
PA
3842int
3843remote_target::remote_get_threadinfo (threadref *threadid,
3844 int fieldset,
3845 gdb_ext_thread_info *info)
c906108c 3846{
d01949b6 3847 struct remote_state *rs = get_remote_state ();
c906108c 3848 int result;
c906108c 3849
8d64371b 3850 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
2e9f7625 3851 putpkt (rs->buf);
aa7b36b8 3852 getpkt (&rs->buf);
3084dd77
PA
3853
3854 if (rs->buf[0] == '\0')
3855 return 0;
3856
8d64371b 3857 result = remote_unpack_thread_info_response (&rs->buf[2],
23860348 3858 threadid, info);
c906108c
SS
3859 return result;
3860}
3861
c906108c
SS
3862/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3863
3864static char *
fba45db2
KB
3865pack_threadlist_request (char *pkt, int startflag, int threadcount,
3866 threadref *nextthread)
c906108c
SS
3867{
3868 *pkt++ = 'q'; /* info query packet */
3869 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3870 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3871 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3872 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3873 *pkt = '\0';
3874 return pkt;
3875}
3876
3877/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3878
6b8edb51 3879int
cecb1912 3880remote_target::parse_threadlist_response (const char *pkt, int result_limit,
6b8edb51
PA
3881 threadref *original_echo,
3882 threadref *resultlist,
3883 int *doneflag)
c906108c 3884{
d01949b6 3885 struct remote_state *rs = get_remote_state ();
c906108c
SS
3886 int count, resultcount, done;
3887
3888 resultcount = 0;
3889 /* Assume the 'q' and 'M chars have been stripped. */
cecb1912 3890 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
23860348 3891 /* done parse past here */
c906108c
SS
3892 pkt = unpack_byte (pkt, &count); /* count field */
3893 pkt = unpack_nibble (pkt, &done);
3894 /* The first threadid is the argument threadid. */
3895 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3896 while ((count-- > 0) && (pkt < limit))
3897 {
3898 pkt = unpack_threadid (pkt, resultlist++);
3899 if (resultcount++ >= result_limit)
3900 break;
3901 }
3902 if (doneflag)
3903 *doneflag = done;
3904 return resultcount;
3905}
3906
6dc54d91
PA
3907/* Fetch the next batch of threads from the remote. Returns -1 if the
3908 qL packet is not supported, 0 on error and 1 on success. */
3909
6b8edb51
PA
3910int
3911remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3912 int result_limit, int *done, int *result_count,
3913 threadref *threadlist)
c906108c 3914{
d01949b6 3915 struct remote_state *rs = get_remote_state ();
c906108c
SS
3916 int result = 1;
3917
405feb71 3918 /* Truncate result limit to be smaller than the packet size. */
3e43a32a
MS
3919 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3920 >= get_remote_packet_size ())
ea9c271d 3921 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3922
8d64371b
TT
3923 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3924 nextthread);
6d820c5c 3925 putpkt (rs->buf);
aa7b36b8 3926 getpkt (&rs->buf);
8d64371b 3927 if (rs->buf[0] == '\0')
6dc54d91
PA
3928 {
3929 /* Packet not supported. */
3930 return -1;
3931 }
3932
3933 *result_count =
8d64371b 3934 parse_threadlist_response (&rs->buf[2], result_limit,
6dc54d91 3935 &rs->echo_nextthread, threadlist, done);
c906108c 3936
0d031856 3937 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3938 {
23860348 3939 /* FIXME: This is a good reason to drop the packet. */
405feb71
TV
3940 /* Possibly, there is a duplicate response. */
3941 /* Possibilities :
8f6606b6 3942 retransmit immediately - race conditions
dda83cd7
SM
3943 retransmit after timeout - yes
3944 exit
3945 wait for packet, then exit
c906108c 3946 */
8a3fe4f8 3947 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3948 return 0; /* I choose simply exiting. */
c906108c
SS
3949 }
3950 if (*result_count <= 0)
3951 {
3952 if (*done != 1)
3953 {
8a3fe4f8 3954 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3955 result = 0;
3956 }
3957 return result; /* break; */
3958 }
3959 if (*result_count > result_limit)
3960 {
3961 *result_count = 0;
8a3fe4f8 3962 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3963 return 0;
3964 }
3965 return result;
3966}
3967
6dc54d91
PA
3968/* Fetch the list of remote threads, with the qL packet, and call
3969 STEPFUNCTION for each thread found. Stops iterating and returns 1
3970 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3971 STEPFUNCTION returns false. If the packet is not supported,
3972 returns -1. */
c906108c 3973
6b8edb51
PA
3974int
3975remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3976 void *context, int looplimit)
c906108c 3977{
0d031856 3978 struct remote_state *rs = get_remote_state ();
c906108c
SS
3979 int done, i, result_count;
3980 int startflag = 1;
3981 int result = 1;
3982 int loopcount = 0;
c906108c
SS
3983
3984 done = 0;
3985 while (!done)
3986 {
3987 if (loopcount++ > looplimit)
3988 {
3989 result = 0;
8a3fe4f8 3990 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3991 break;
3992 }
6dc54d91
PA
3993 result = remote_get_threadlist (startflag, &rs->nextthread,
3994 MAXTHREADLISTRESULTS,
3995 &done, &result_count,
3996 rs->resultthreadlist);
3997 if (result <= 0)
3998 break;
23860348 3999 /* Clear for later iterations. */
c906108c
SS
4000 startflag = 0;
4001 /* Setup to resume next batch of thread references, set nextthread. */
4002 if (result_count >= 1)
0d031856
TT
4003 copy_threadref (&rs->nextthread,
4004 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
4005 i = 0;
4006 while (result_count--)
6dc54d91
PA
4007 {
4008 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
4009 {
4010 result = 0;
4011 break;
4012 }
4013 }
c906108c
SS
4014 }
4015 return result;
4016}
4017
6dc54d91
PA
4018/* A thread found on the remote target. */
4019
21fe1c75 4020struct thread_item
6dc54d91 4021{
21fe1c75
SM
4022 explicit thread_item (ptid_t ptid_)
4023 : ptid (ptid_)
4024 {}
4025
4026 thread_item (thread_item &&other) = default;
4027 thread_item &operator= (thread_item &&other) = default;
4028
4029 DISABLE_COPY_AND_ASSIGN (thread_item);
4030
6dc54d91
PA
4031 /* The thread's PTID. */
4032 ptid_t ptid;
4033
21fe1c75
SM
4034 /* The thread's extra info. */
4035 std::string extra;
6dc54d91 4036
21fe1c75
SM
4037 /* The thread's name. */
4038 std::string name;
79efa585 4039
1dd0c745
TBA
4040 /* The thread's id, translated to a string for displaying. */
4041 std::string id_str;
4042
6dc54d91 4043 /* The core the thread was running on. -1 if not known. */
21fe1c75 4044 int core = -1;
f6327dcb
KB
4045
4046 /* The thread handle associated with the thread. */
21fe1c75 4047 gdb::byte_vector thread_handle;
21fe1c75 4048};
6dc54d91
PA
4049
4050/* Context passed around to the various methods listing remote
4051 threads. As new threads are found, they're added to the ITEMS
4052 vector. */
4053
4054struct threads_listing_context
4055{
21fe1c75
SM
4056 /* Return true if this object contains an entry for a thread with ptid
4057 PTID. */
6dc54d91 4058
21fe1c75
SM
4059 bool contains_thread (ptid_t ptid) const
4060 {
4061 auto match_ptid = [&] (const thread_item &item)
4062 {
4063 return item.ptid == ptid;
4064 };
80134cf5 4065
21fe1c75
SM
4066 auto it = std::find_if (this->items.begin (),
4067 this->items.end (),
4068 match_ptid);
80134cf5 4069
21fe1c75
SM
4070 return it != this->items.end ();
4071 }
80134cf5 4072
21fe1c75 4073 /* Remove the thread with ptid PTID. */
80134cf5 4074
21fe1c75
SM
4075 void remove_thread (ptid_t ptid)
4076 {
4077 auto match_ptid = [&] (const thread_item &item)
4078 {
dda83cd7 4079 return item.ptid == ptid;
21fe1c75 4080 };
cbb8991c 4081
21fe1c75
SM
4082 auto it = std::remove_if (this->items.begin (),
4083 this->items.end (),
4084 match_ptid);
cbb8991c 4085
21fe1c75
SM
4086 if (it != this->items.end ())
4087 this->items.erase (it);
4088 }
4089
4090 /* The threads found on the remote target. */
4091 std::vector<thread_item> items;
4092};
cbb8991c 4093
c906108c 4094static int
6dc54d91 4095remote_newthread_step (threadref *ref, void *data)
c906108c 4096{
19ba03f4
SM
4097 struct threads_listing_context *context
4098 = (struct threads_listing_context *) data;
21fe1c75
SM
4099 int pid = inferior_ptid.pid ();
4100 int lwp = threadref_to_int (ref);
4101 ptid_t ptid (pid, lwp);
6dc54d91 4102
21fe1c75 4103 context->items.emplace_back (ptid);
6dc54d91 4104
c906108c
SS
4105 return 1; /* continue iterator */
4106}
4107
4108#define CRAZY_MAX_THREADS 1000
4109
6b8edb51
PA
4110ptid_t
4111remote_target::remote_current_thread (ptid_t oldpid)
c906108c 4112{
d01949b6 4113 struct remote_state *rs = get_remote_state ();
c906108c
SS
4114
4115 putpkt ("qC");
aa7b36b8 4116 getpkt (&rs->buf);
2e9f7625 4117 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 4118 {
256642e8 4119 const char *obuf;
c9f35b34
KB
4120 ptid_t result;
4121
4122 result = read_ptid (&rs->buf[2], &obuf);
2189c312
SM
4123 if (*obuf != '\0')
4124 remote_debug_printf ("warning: garbage in qC reply");
c9f35b34
KB
4125
4126 return result;
4127 }
c906108c
SS
4128 else
4129 return oldpid;
4130}
4131
6dc54d91 4132/* List remote threads using the deprecated qL packet. */
cce74817 4133
6b8edb51
PA
4134int
4135remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 4136{
6dc54d91
PA
4137 if (remote_threadlist_iterator (remote_newthread_step, context,
4138 CRAZY_MAX_THREADS) >= 0)
4139 return 1;
4140
4141 return 0;
c906108c
SS
4142}
4143
dc146f7c
VP
4144#if defined(HAVE_LIBEXPAT)
4145
dc146f7c
VP
4146static void
4147start_thread (struct gdb_xml_parser *parser,
4148 const struct gdb_xml_element *element,
4d0fdd9b
SM
4149 void *user_data,
4150 std::vector<gdb_xml_value> &attributes)
dc146f7c 4151{
19ba03f4
SM
4152 struct threads_listing_context *data
4153 = (struct threads_listing_context *) user_data;
3d2c1d41 4154 struct gdb_xml_value *attr;
dc146f7c 4155
4d0fdd9b 4156 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
4157 ptid_t ptid = read_ptid (id, NULL);
4158
b36a2634 4159 thread_item &item = data->items.emplace_back (ptid);
dc146f7c 4160
3d2c1d41
PA
4161 attr = xml_find_attribute (attributes, "core");
4162 if (attr != NULL)
4d0fdd9b 4163 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 4164
79efa585 4165 attr = xml_find_attribute (attributes, "name");
21fe1c75 4166 if (attr != NULL)
4d0fdd9b 4167 item.name = (const char *) attr->value.get ();
79efa585 4168
1dd0c745
TBA
4169 attr = xml_find_attribute (attributes, "id_str");
4170 if (attr != nullptr)
4171 item.id_str = (const char *) attr->value.get ();
4172
f6327dcb
KB
4173 attr = xml_find_attribute (attributes, "handle");
4174 if (attr != NULL)
4d0fdd9b 4175 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
4176}
4177
4178static void
4179end_thread (struct gdb_xml_parser *parser,
4180 const struct gdb_xml_element *element,
4181 void *user_data, const char *body_text)
4182{
19ba03f4
SM
4183 struct threads_listing_context *data
4184 = (struct threads_listing_context *) user_data;
dc146f7c 4185
21fe1c75
SM
4186 if (body_text != NULL && *body_text != '\0')
4187 data->items.back ().extra = body_text;
dc146f7c
VP
4188}
4189
4190const struct gdb_xml_attribute thread_attributes[] = {
4191 { "id", GDB_XML_AF_NONE, NULL, NULL },
4192 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 4193 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
1dd0c745 4194 { "id_str", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 4195 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
4196 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4197};
4198
4199const struct gdb_xml_element thread_children[] = {
4200 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4201};
4202
4203const struct gdb_xml_element threads_children[] = {
4204 { "thread", thread_attributes, thread_children,
4205 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4206 start_thread, end_thread },
4207 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4208};
4209
4210const struct gdb_xml_element threads_elements[] = {
4211 { "threads", NULL, threads_children,
4212 GDB_XML_EF_NONE, NULL, NULL },
4213 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4214};
4215
4216#endif
4217
6dc54d91 4218/* List remote threads using qXfer:threads:read. */
9d1f7ab2 4219
6b8edb51
PA
4220int
4221remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 4222{
dc146f7c 4223#if defined(HAVE_LIBEXPAT)
ff52c073 4224 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 4225 {
6b09f134 4226 std::optional<gdb::char_vector> xml
6b8edb51 4227 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 4228
9018be22 4229 if (xml && (*xml)[0] != '\0')
dc146f7c 4230 {
6dc54d91 4231 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 4232 threads_elements, xml->data (), context);
dc146f7c
VP
4233 }
4234
6dc54d91 4235 return 1;
dc146f7c
VP
4236 }
4237#endif
4238
6dc54d91
PA
4239 return 0;
4240}
4241
4242/* List remote threads using qfThreadInfo/qsThreadInfo. */
4243
6b8edb51
PA
4244int
4245remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
4246{
4247 struct remote_state *rs = get_remote_state ();
4248
b80fafe3 4249 if (rs->use_threadinfo_query)
9d1f7ab2 4250 {
256642e8 4251 const char *bufp;
6dc54d91 4252
9d1f7ab2 4253 putpkt ("qfThreadInfo");
aa7b36b8 4254 getpkt (&rs->buf);
8d64371b 4255 bufp = rs->buf.data ();
9d1f7ab2 4256 if (bufp[0] != '\0') /* q packet recognized */
802188a7 4257 {
9d1f7ab2
MS
4258 while (*bufp++ == 'm') /* reply contains one or more TID */
4259 {
4260 do
4261 {
21fe1c75
SM
4262 ptid_t ptid = read_ptid (bufp, &bufp);
4263 context->items.emplace_back (ptid);
9d1f7ab2
MS
4264 }
4265 while (*bufp++ == ','); /* comma-separated list */
4266 putpkt ("qsThreadInfo");
aa7b36b8 4267 getpkt (&rs->buf);
8d64371b 4268 bufp = rs->buf.data ();
9d1f7ab2 4269 }
6dc54d91
PA
4270 return 1;
4271 }
4272 else
4273 {
4274 /* Packet not recognized. */
4275 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
4276 }
4277 }
4278
6dc54d91
PA
4279 return 0;
4280}
4281
a05575d3
TBA
4282/* Return true if INF only has one non-exited thread. */
4283
4284static bool
4285has_single_non_exited_thread (inferior *inf)
4286{
4287 int count = 0;
4288 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4289 if (++count > 1)
4290 break;
4291 return count == 1;
4292}
4293
e8032dde 4294/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
4295 targets. */
4296
f6ac5f3d
PA
4297void
4298remote_target::update_thread_list ()
6dc54d91 4299{
6dc54d91 4300 struct threads_listing_context context;
ab970af1 4301 int got_list = 0;
e8032dde 4302
6dc54d91
PA
4303 /* We have a few different mechanisms to fetch the thread list. Try
4304 them all, starting with the most preferred one first, falling
4305 back to older methods. */
6b8edb51
PA
4306 if (remote_get_threads_with_qxfer (&context)
4307 || remote_get_threads_with_qthreadinfo (&context)
4308 || remote_get_threads_with_ql (&context))
6dc54d91 4309 {
ab970af1
PA
4310 got_list = 1;
4311
21fe1c75 4312 if (context.items.empty ()
f6ac5f3d 4313 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
4314 {
4315 /* Some targets don't really support threads, but still
4316 reply an (empty) thread list in response to the thread
4317 listing packets, instead of replying "packet not
4318 supported". Exit early so we don't delete the main
4319 thread. */
7d1a114c
PA
4320 return;
4321 }
4322
ab970af1
PA
4323 /* CONTEXT now holds the current thread list on the remote
4324 target end. Delete GDB-side threads no longer found on the
4325 target. */
08036331 4326 for (thread_info *tp : all_threads_safe ())
cbb8991c 4327 {
5b6d1e4f
PA
4328 if (tp->inf->process_target () != this)
4329 continue;
4330
21fe1c75 4331 if (!context.contains_thread (tp->ptid))
ab970af1 4332 {
a05575d3
TBA
4333 /* Do not remove the thread if it is the last thread in
4334 the inferior. This situation happens when we have a
4335 pending exit process status to process. Otherwise we
4336 may end up with a seemingly live inferior (i.e. pid
4337 != 0) that has no threads. */
4338 if (has_single_non_exited_thread (tp->inf))
4339 continue;
4340
d8d96409
PA
4341 /* Do not remove the thread if we've requested to be
4342 notified of its exit. For example, the thread may be
4343 displaced stepping, infrun will need to handle the
4344 exit event, and displaced stepping info is recorded
4345 in the thread object. If we deleted the thread now,
4346 we'd lose that info. */
4347 if ((tp->thread_options () & GDB_THREAD_OPTION_EXIT) != 0)
4348 continue;
4349
ab970af1 4350 /* Not found. */
00431a78 4351 delete_thread (tp);
ab970af1 4352 }
cbb8991c
DB
4353 }
4354
53de5394
PA
4355 /* Remove any unreported fork/vfork/clone child threads from
4356 CONTEXT so that we don't interfere with follow
4357 fork/vfork/clone, which is where creation of such threads is
4358 handled. */
4359 remove_new_children (&context);
74531fed 4360
ab970af1 4361 /* And now add threads we don't know about yet to our list. */
21fe1c75 4362 for (thread_item &item : context.items)
6dc54d91 4363 {
21fe1c75 4364 if (item.ptid != null_ptid)
6dc54d91 4365 {
6dc54d91 4366 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
4367 executing until proven otherwise with a stop reply.
4368 In all-stop, we can only get here if all threads are
6dc54d91 4369 stopped. */
8a82de58 4370 bool executing = target_is_non_stop_p ();
6dc54d91 4371
21fe1c75 4372 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 4373
9213a6d7 4374 thread_info *tp = this->find_thread (item.ptid);
00431a78 4375 remote_thread_info *info = get_remote_thread_info (tp);
21fe1c75 4376 info->core = item.core;
7aabaf9d
SM
4377 info->extra = std::move (item.extra);
4378 info->name = std::move (item.name);
1dd0c745 4379 info->id_str = std::move (item.id_str);
7aabaf9d 4380 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
4381 }
4382 }
4383 }
4384
ab970af1
PA
4385 if (!got_list)
4386 {
4387 /* If no thread listing method is supported, then query whether
4388 each known thread is alive, one by one, with the T packet.
4389 If the target doesn't support threads at all, then this is a
4390 no-op. See remote_thread_alive. */
4391 prune_threads ();
4392 }
9d1f7ab2
MS
4393}
4394
802188a7 4395/*
9d1f7ab2
MS
4396 * Collect a descriptive string about the given thread.
4397 * The target may say anything it wants to about the thread
4398 * (typically info about its blocked / runnable state, name, etc.).
4399 * This string will appear in the info threads display.
802188a7 4400 *
9d1f7ab2
MS
4401 * Optional: targets are not required to implement this function.
4402 */
4403
f6ac5f3d
PA
4404const char *
4405remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 4406{
d01949b6 4407 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
4408 int set;
4409 threadref id;
4410 struct gdb_ext_thread_info threadinfo;
9d1f7ab2 4411
5d93a237 4412 if (rs->remote_desc == 0) /* paranoia */
f34652de 4413 internal_error (_("remote_threads_extra_info"));
9d1f7ab2 4414
d7e15655 4415 if (tp->ptid == magic_null_ptid
e38504b3 4416 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
60e569b9
PA
4417 /* This is the main thread which was added by GDB. The remote
4418 server doesn't know about it. */
4419 return NULL;
4420
c76a8ea3
PA
4421 std::string &extra = get_remote_thread_info (tp)->extra;
4422
4423 /* If already have cached info, use it. */
4424 if (!extra.empty ())
4425 return extra.c_str ();
4426
ff52c073 4427 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 4428 {
c76a8ea3
PA
4429 /* If we're using qXfer:threads:read, then the extra info is
4430 included in the XML. So if we didn't have anything cached,
4431 it's because there's really no extra info. */
4432 return NULL;
dc146f7c
VP
4433 }
4434
b80fafe3 4435 if (rs->use_threadextra_query)
9d1f7ab2 4436 {
8d64371b
TT
4437 char *b = rs->buf.data ();
4438 char *endb = b + get_remote_packet_size ();
82f73884
PA
4439
4440 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4441 b += strlen (b);
4442 write_ptid (b, endb, tp->ptid);
4443
2e9f7625 4444 putpkt (rs->buf);
aa7b36b8 4445 getpkt (&rs->buf);
2e9f7625 4446 if (rs->buf[0] != 0)
9d1f7ab2 4447 {
8d64371b
TT
4448 extra.resize (strlen (rs->buf.data ()) / 2);
4449 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
c76a8ea3 4450 return extra.c_str ();
9d1f7ab2 4451 }
0f71a2f6 4452 }
9d1f7ab2
MS
4453
4454 /* If the above query fails, fall back to the old method. */
b80fafe3 4455 rs->use_threadextra_query = 0;
9d1f7ab2
MS
4456 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4457 | TAG_MOREDISPLAY | TAG_DISPLAY;
e38504b3 4458 int_to_threadref (&id, tp->ptid.lwp ());
9d1f7ab2
MS
4459 if (remote_get_threadinfo (&id, set, &threadinfo))
4460 if (threadinfo.active)
0f71a2f6 4461 {
9d1f7ab2 4462 if (*threadinfo.shortname)
c76a8ea3 4463 string_appendf (extra, " Name: %s", threadinfo.shortname);
9d1f7ab2 4464 if (*threadinfo.display)
c76a8ea3
PA
4465 {
4466 if (!extra.empty ())
4467 extra += ',';
4468 string_appendf (extra, " State: %s", threadinfo.display);
4469 }
9d1f7ab2 4470 if (*threadinfo.more_display)
c5aa993b 4471 {
c76a8ea3
PA
4472 if (!extra.empty ())
4473 extra += ',';
4474 string_appendf (extra, " Priority: %s", threadinfo.more_display);
c5aa993b 4475 }
c76a8ea3 4476 return extra.c_str ();
0f71a2f6 4477 }
9d1f7ab2 4478 return NULL;
0f71a2f6 4479}
c906108c 4480\f
c5aa993b 4481
f6ac5f3d
PA
4482bool
4483remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4484 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
4485{
4486 struct remote_state *rs = get_remote_state ();
8d64371b 4487 char *p = rs->buf.data ();
0fb4aa4b 4488
bba74b36 4489 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
4490 p += strlen (p);
4491 p += hexnumstr (p, addr);
4492 putpkt (rs->buf);
aa7b36b8 4493 getpkt (&rs->buf);
8d64371b 4494 p = rs->buf.data ();
0fb4aa4b
PA
4495
4496 if (*p == 'E')
4497 error (_("Remote failure reply: %s"), p);
4498
4499 if (*p++ == 'm')
4500 {
256642e8 4501 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 4502 return true;
0fb4aa4b
PA
4503 }
4504
5d9310c4 4505 return false;
0fb4aa4b
PA
4506}
4507
f6ac5f3d
PA
4508std::vector<static_tracepoint_marker>
4509remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
4510{
4511 struct remote_state *rs = get_remote_state ();
5d9310c4 4512 std::vector<static_tracepoint_marker> markers;
256642e8 4513 const char *p;
5d9310c4 4514 static_tracepoint_marker marker;
0fb4aa4b
PA
4515
4516 /* Ask for a first packet of static tracepoint marker
4517 definition. */
4518 putpkt ("qTfSTM");
aa7b36b8 4519 getpkt (&rs->buf);
8d64371b 4520 p = rs->buf.data ();
0fb4aa4b
PA
4521 if (*p == 'E')
4522 error (_("Remote failure reply: %s"), p);
4523
0fb4aa4b
PA
4524 while (*p++ == 'm')
4525 {
0fb4aa4b
PA
4526 do
4527 {
5d9310c4 4528 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 4529
5d9310c4
SM
4530 if (strid == NULL || marker.str_id == strid)
4531 markers.push_back (std::move (marker));
0fb4aa4b
PA
4532 }
4533 while (*p++ == ','); /* comma-separated list */
4534 /* Ask for another packet of static tracepoint definition. */
4535 putpkt ("qTsSTM");
aa7b36b8 4536 getpkt (&rs->buf);
8d64371b 4537 p = rs->buf.data ();
0fb4aa4b
PA
4538 }
4539
0fb4aa4b
PA
4540 return markers;
4541}
4542
4543\f
10760264
JB
4544/* Implement the to_get_ada_task_ptid function for the remote targets. */
4545
f6ac5f3d 4546ptid_t
c80e29db 4547remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
10760264 4548{
184ea2f7 4549 return ptid_t (inferior_ptid.pid (), lwp);
10760264
JB
4550}
4551\f
4552
24b06219 4553/* Restart the remote side; this is an extended protocol operation. */
c906108c 4554
6b8edb51
PA
4555void
4556remote_target::extended_remote_restart ()
c906108c 4557{
d01949b6 4558 struct remote_state *rs = get_remote_state ();
c906108c
SS
4559
4560 /* Send the restart command; for reasons I don't understand the
4561 remote side really expects a number after the "R". */
8d64371b 4562 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
6d820c5c 4563 putpkt (rs->buf);
c906108c 4564
ad9a8f3f 4565 remote_fileio_reset ();
c906108c
SS
4566}
4567\f
4568/* Clean up connection to a remote debugger. */
4569
f6ac5f3d
PA
4570void
4571remote_target::close ()
c906108c 4572{
048094ac 4573 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4574 terminal_ours ();
ce5ce7ed 4575
6b8edb51
PA
4576 trace_reset_local_state ();
4577
4578 delete this;
4579}
4580
4581remote_target::~remote_target ()
4582{
4583 struct remote_state *rs = get_remote_state ();
4584
4585 /* Check for NULL because we may get here with a partially
4586 constructed target/connection. */
4587 if (rs->remote_desc == nullptr)
4588 return;
4589
4590 serial_close (rs->remote_desc);
4591
4592 /* We are destroying the remote target, so we should discard
f48ff2a7 4593 everything of this target. */
6b8edb51 4594 discard_pending_stop_replies_in_queue ();
74531fed 4595
92b98b37 4596 rs->delete_async_event_handler ();
722247f1 4597
97dfbadd 4598 delete rs->notif_state;
c906108c
SS
4599}
4600
23860348 4601/* Query the remote side for the text, data and bss offsets. */
c906108c 4602
6b8edb51
PA
4603void
4604remote_target::get_offsets ()
c906108c 4605{
d01949b6 4606 struct remote_state *rs = get_remote_state ();
2e9f7625 4607 char *buf;
085dd6e6 4608 char *ptr;
31d99776
DJ
4609 int lose, num_segments = 0, do_sections, do_segments;
4610 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
31d99776 4611
a42d7dd8 4612 if (current_program_space->symfile_object_file == NULL)
31d99776 4613 return;
c906108c
SS
4614
4615 putpkt ("qOffsets");
aa7b36b8 4616 getpkt (&rs->buf);
8d64371b 4617 buf = rs->buf.data ();
c906108c
SS
4618
4619 if (buf[0] == '\000')
4620 return; /* Return silently. Stub doesn't support
23860348 4621 this command. */
c906108c
SS
4622 if (buf[0] == 'E')
4623 {
8a3fe4f8 4624 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4625 return;
4626 }
4627
4628 /* Pick up each field in turn. This used to be done with scanf, but
4629 scanf will make trouble if CORE_ADDR size doesn't match
4630 conversion directives correctly. The following code will work
4631 with any size of CORE_ADDR. */
4632 text_addr = data_addr = bss_addr = 0;
4633 ptr = buf;
4634 lose = 0;
4635
61012eef 4636 if (startswith (ptr, "Text="))
c906108c
SS
4637 {
4638 ptr += 5;
4639 /* Don't use strtol, could lose on big values. */
4640 while (*ptr && *ptr != ';')
4641 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4642
61012eef 4643 if (startswith (ptr, ";Data="))
31d99776
DJ
4644 {
4645 ptr += 6;
4646 while (*ptr && *ptr != ';')
4647 data_addr = (data_addr << 4) + fromhex (*ptr++);
4648 }
4649 else
4650 lose = 1;
4651
61012eef 4652 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4653 {
4654 ptr += 5;
4655 while (*ptr && *ptr != ';')
4656 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4657
31d99776
DJ
4658 if (bss_addr != data_addr)
4659 warning (_("Target reported unsupported offsets: %s"), buf);
4660 }
4661 else
4662 lose = 1;
4663 }
61012eef 4664 else if (startswith (ptr, "TextSeg="))
c906108c 4665 {
31d99776
DJ
4666 ptr += 8;
4667 /* Don't use strtol, could lose on big values. */
c906108c 4668 while (*ptr && *ptr != ';')
31d99776
DJ
4669 text_addr = (text_addr << 4) + fromhex (*ptr++);
4670 num_segments = 1;
4671
61012eef 4672 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4673 {
4674 ptr += 9;
4675 while (*ptr && *ptr != ';')
4676 data_addr = (data_addr << 4) + fromhex (*ptr++);
4677 num_segments++;
4678 }
c906108c
SS
4679 }
4680 else
4681 lose = 1;
4682
4683 if (lose)
8a3fe4f8 4684 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4685 else if (*ptr != '\0')
4686 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4687
a42d7dd8
TT
4688 objfile *objf = current_program_space->symfile_object_file;
4689 section_offsets offs = objf->section_offsets;
c906108c 4690
98badbfd 4691 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
31d99776
DJ
4692 do_segments = (data != NULL);
4693 do_sections = num_segments == 0;
c906108c 4694
28c32713 4695 if (num_segments > 0)
31d99776 4696 {
31d99776
DJ
4697 segments[0] = text_addr;
4698 segments[1] = data_addr;
4699 }
28c32713
JB
4700 /* If we have two segments, we can still try to relocate everything
4701 by assuming that the .text and .data offsets apply to the whole
4702 text and data segments. Convert the offsets given in the packet
4703 to base addresses for symfile_map_offsets_to_segments. */
68b888ff 4704 else if (data != nullptr && data->segments.size () == 2)
28c32713 4705 {
68b888ff
SM
4706 segments[0] = data->segments[0].base + text_addr;
4707 segments[1] = data->segments[1].base + data_addr;
28c32713
JB
4708 num_segments = 2;
4709 }
8d385431
DJ
4710 /* If the object file has only one segment, assume that it is text
4711 rather than data; main programs with no writable data are rare,
4712 but programs with no code are useless. Of course the code might
4713 have ended up in the data segment... to detect that we would need
4714 the permissions here. */
68b888ff 4715 else if (data && data->segments.size () == 1)
8d385431 4716 {
68b888ff 4717 segments[0] = data->segments[0].base + text_addr;
8d385431
DJ
4718 num_segments = 1;
4719 }
28c32713
JB
4720 /* There's no way to relocate by segment. */
4721 else
4722 do_segments = 0;
31d99776
DJ
4723
4724 if (do_segments)
4725 {
98badbfd 4726 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
62982abd
SM
4727 data.get (), offs,
4728 num_segments, segments);
31d99776
DJ
4729
4730 if (ret == 0 && !do_sections)
3e43a32a
MS
4731 error (_("Can not handle qOffsets TextSeg "
4732 "response with this symbol file"));
31d99776
DJ
4733
4734 if (ret > 0)
4735 do_sections = 0;
4736 }
c906108c 4737
31d99776
DJ
4738 if (do_sections)
4739 {
a42d7dd8 4740 offs[SECT_OFF_TEXT (objf)] = text_addr;
31d99776 4741
3e43a32a
MS
4742 /* This is a temporary kludge to force data and bss to use the
4743 same offsets because that's what nlmconv does now. The real
4744 solution requires changes to the stub and remote.c that I
4745 don't have time to do right now. */
31d99776 4746
a42d7dd8
TT
4747 offs[SECT_OFF_DATA (objf)] = data_addr;
4748 offs[SECT_OFF_BSS (objf)] = data_addr;
31d99776 4749 }
c906108c 4750
a42d7dd8 4751 objfile_relocate (objf, offs);
c906108c
SS
4752}
4753
9a7071a8 4754/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4755
4756void
4757remote_target::send_interrupt_sequence ()
9a7071a8
JB
4758{
4759 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4760 remote_serial_write ("\x03", 1);
9a7071a8 4761 else if (interrupt_sequence_mode == interrupt_sequence_break)
d69939bd 4762 remote_serial_send_break ();
9a7071a8
JB
4763 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4764 {
d69939bd 4765 remote_serial_send_break ();
c33e31fd 4766 remote_serial_write ("g", 1);
9a7071a8
JB
4767 }
4768 else
f34652de 4769 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
9a7071a8
JB
4770 interrupt_sequence_mode);
4771}
4772
3405876a
PA
4773/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4774 and extract the PTID. Returns NULL_PTID if not found. */
4775
4776static ptid_t
e3b2741b 4777stop_reply_extract_thread (const char *stop_reply)
3405876a
PA
4778{
4779 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4780 {
256642e8 4781 const char *p;
3405876a
PA
4782
4783 /* Txx r:val ; r:val (...) */
4784 p = &stop_reply[3];
4785
4786 /* Look for "register" named "thread". */
4787 while (*p != '\0')
4788 {
256642e8 4789 const char *p1;
3405876a
PA
4790
4791 p1 = strchr (p, ':');
4792 if (p1 == NULL)
4793 return null_ptid;
4794
4795 if (strncmp (p, "thread", p1 - p) == 0)
4796 return read_ptid (++p1, &p);
4797
4798 p1 = strchr (p, ';');
4799 if (p1 == NULL)
4800 return null_ptid;
4801 p1++;
4802
4803 p = p1;
4804 }
4805 }
4806
4807 return null_ptid;
4808}
4809
b7ea362b
PA
4810/* Determine the remote side's current thread. If we have a stop
4811 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4812 "thread" register we can extract the current thread from. If not,
4813 ask the remote which is the current thread with qC. The former
4814 method avoids a roundtrip. */
4815
6b8edb51 4816ptid_t
e3b2741b 4817remote_target::get_current_thread (const char *wait_status)
b7ea362b 4818{
6a49a997 4819 ptid_t ptid = null_ptid;
b7ea362b
PA
4820
4821 /* Note we don't use remote_parse_stop_reply as that makes use of
4822 the target architecture, which we haven't yet fully determined at
4823 this point. */
4824 if (wait_status != NULL)
4825 ptid = stop_reply_extract_thread (wait_status);
d7e15655 4826 if (ptid == null_ptid)
b7ea362b
PA
4827 ptid = remote_current_thread (inferior_ptid);
4828
4829 return ptid;
4830}
4831
49c62f2e
PA
4832/* Query the remote target for which is the current thread/process,
4833 add it to our tables, and update INFERIOR_PTID. The caller is
4834 responsible for setting the state such that the remote end is ready
3405876a
PA
4835 to return the current thread.
4836
4837 This function is called after handling the '?' or 'vRun' packets,
4838 whose response is a stop reply from which we can also try
4839 extracting the thread. If the target doesn't support the explicit
4840 qC query, we infer the current thread from that stop reply, passed
64d38fdd 4841 in in WAIT_STATUS, which may be NULL.
49c62f2e 4842
64d38fdd
JM
4843 The function returns pointer to the main thread of the inferior. */
4844
4845thread_info *
e3b2741b 4846remote_target::add_current_inferior_and_thread (const char *wait_status)
49c62f2e 4847{
9ab8741a 4848 bool fake_pid_p = false;
49c62f2e 4849
0ac55310 4850 switch_to_no_thread ();
49c62f2e 4851
0ac55310
PA
4852 /* Now, if we have thread information, update the current thread's
4853 ptid. */
87215ad1 4854 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4855
87215ad1 4856 if (curr_ptid != null_ptid)
49c62f2e 4857 {
ff52c073 4858 if (!m_features.remote_multi_process_p ())
9ab8741a 4859 fake_pid_p = true;
49c62f2e
PA
4860 }
4861 else
4862 {
4863 /* Without this, some commands which require an active target
4864 (such as kill) won't work. This variable serves (at least)
4865 double duty as both the pid of the target process (if it has
4866 such), and as a flag indicating that a target is active. */
87215ad1 4867 curr_ptid = magic_null_ptid;
9ab8741a 4868 fake_pid_p = true;
49c62f2e
PA
4869 }
4870
e99b03dc 4871 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
49c62f2e 4872
87215ad1
SDJ
4873 /* Add the main thread and switch to it. Don't try reading
4874 registers yet, since we haven't fetched the target description
4875 yet. */
5b6d1e4f 4876 thread_info *tp = add_thread_silent (this, curr_ptid);
87215ad1 4877 switch_to_thread_no_regs (tp);
64d38fdd
JM
4878
4879 return tp;
49c62f2e
PA
4880}
4881
6efcd9a8
PA
4882/* Print info about a thread that was found already stopped on
4883 connection. */
4884
1edb66d8
SM
4885void
4886remote_target::print_one_stopped_thread (thread_info *thread)
6efcd9a8 4887{
1edb66d8
SM
4888 target_waitstatus ws;
4889
4890 /* If there is a pending waitstatus, use it. If there isn't it's because
4891 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4892 and process_initial_stop_replies decided it wasn't interesting to save
4893 and report to the core. */
4894 if (thread->has_pending_waitstatus ())
4895 {
4896 ws = thread->pending_waitstatus ();
4897 thread->clear_pending_waitstatus ();
4898 }
4899 else
4900 {
183be222 4901 ws.set_stopped (GDB_SIGNAL_0);
1edb66d8 4902 }
6efcd9a8 4903
00431a78 4904 switch_to_thread (thread);
1edb66d8 4905 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
6efcd9a8
PA
4906 set_current_sal_from_frame (get_current_frame ());
4907
1edb66d8
SM
4908 /* For "info program". */
4909 set_last_target_status (this, thread->ptid, ws);
6efcd9a8 4910
183be222 4911 if (ws.kind () == TARGET_WAITKIND_STOPPED)
6efcd9a8 4912 {
183be222 4913 enum gdb_signal sig = ws.sig ();
6efcd9a8
PA
4914
4915 if (signal_print_state (sig))
3f75a984 4916 notify_signal_received (sig);
6efcd9a8 4917 }
87829267
SM
4918
4919 notify_normal_stop (nullptr, 1);
6efcd9a8
PA
4920}
4921
221e1a37
PA
4922/* Process all initial stop replies the remote side sent in response
4923 to the ? packet. These indicate threads that were already stopped
4924 on initial connection. We mark these threads as stopped and print
4925 their current frame before giving the user the prompt. */
4926
6b8edb51
PA
4927void
4928remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4929{
4930 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4931 struct thread_info *selected = NULL;
4932 struct thread_info *lowest_stopped = NULL;
4933 struct thread_info *first = NULL;
221e1a37 4934
1edb66d8
SM
4935 /* This is only used when the target is non-stop. */
4936 gdb_assert (target_is_non_stop_p ());
4937
221e1a37
PA
4938 /* Consume the initial pending events. */
4939 while (pending_stop_replies-- > 0)
4940 {
4941 ptid_t waiton_ptid = minus_one_ptid;
4942 ptid_t event_ptid;
4943 struct target_waitstatus ws;
4944 int ignore_event = 0;
4945
221e1a37
PA
4946 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4947 if (remote_debug)
3559d599 4948 print_target_wait_results (waiton_ptid, event_ptid, ws, this);
221e1a37 4949
183be222 4950 switch (ws.kind ())
221e1a37
PA
4951 {
4952 case TARGET_WAITKIND_IGNORE:
4953 case TARGET_WAITKIND_NO_RESUMED:
4954 case TARGET_WAITKIND_SIGNALLED:
4955 case TARGET_WAITKIND_EXITED:
4956 /* We shouldn't see these, but if we do, just ignore. */
2189c312 4957 remote_debug_printf ("event ignored");
221e1a37
PA
4958 ignore_event = 1;
4959 break;
4960
221e1a37
PA
4961 default:
4962 break;
4963 }
4964
4965 if (ignore_event)
4966 continue;
4967
9213a6d7 4968 thread_info *evthread = this->find_thread (event_ptid);
221e1a37 4969
183be222 4970 if (ws.kind () == TARGET_WAITKIND_STOPPED)
221e1a37 4971 {
183be222 4972 enum gdb_signal sig = ws.sig ();
221e1a37
PA
4973
4974 /* Stubs traditionally report SIGTRAP as initial signal,
4975 instead of signal 0. Suppress it. */
4976 if (sig == GDB_SIGNAL_TRAP)
4977 sig = GDB_SIGNAL_0;
1edb66d8 4978 evthread->set_stop_signal (sig);
183be222 4979 ws.set_stopped (sig);
6efcd9a8 4980 }
221e1a37 4981
183be222
SM
4982 if (ws.kind () != TARGET_WAITKIND_STOPPED
4983 || ws.sig () != GDB_SIGNAL_0)
1edb66d8 4984 evthread->set_pending_waitstatus (ws);
6efcd9a8 4985
719546c4
SM
4986 set_executing (this, event_ptid, false);
4987 set_running (this, event_ptid, false);
c9d22089 4988 get_remote_thread_info (evthread)->set_not_resumed ();
6efcd9a8
PA
4989 }
4990
4991 /* "Notice" the new inferiors before anything related to
4992 registers/memory. */
5b6d1e4f 4993 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4994 {
30220b46 4995 inf->needs_setup = true;
6efcd9a8
PA
4996
4997 if (non_stop)
4998 {
08036331 4999 thread_info *thread = any_live_thread_of_inferior (inf);
00431a78 5000 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
6efcd9a8
PA
5001 from_tty);
5002 }
5003 }
5004
5005 /* If all-stop on top of non-stop, pause all threads. Note this
5006 records the threads' stop pc, so must be done after "noticing"
5007 the inferiors. */
5008 if (!non_stop)
5009 {
abe8cab7
SM
5010 {
5011 /* At this point, the remote target is not async. It needs to be for
5012 the poll in stop_all_threads to consider events from it, so enable
5013 it temporarily. */
5014 gdb_assert (!this->is_async_p ());
4a570176
TT
5015 SCOPE_EXIT { target_async (false); };
5016 target_async (true);
4f5539f0 5017 stop_all_threads ("remote connect in all-stop");
abe8cab7 5018 }
6efcd9a8
PA
5019
5020 /* If all threads of an inferior were already stopped, we
5021 haven't setup the inferior yet. */
5b6d1e4f 5022 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 5023 {
6efcd9a8
PA
5024 if (inf->needs_setup)
5025 {
08036331 5026 thread_info *thread = any_live_thread_of_inferior (inf);
6efcd9a8
PA
5027 switch_to_thread_no_regs (thread);
5028 setup_inferior (0);
5029 }
5030 }
221e1a37 5031 }
6efcd9a8
PA
5032
5033 /* Now go over all threads that are stopped, and print their current
5034 frame. If all-stop, then if there's a signalled thread, pick
5035 that as current. */
5b6d1e4f 5036 for (thread_info *thread : all_non_exited_threads (this))
6efcd9a8 5037 {
6efcd9a8
PA
5038 if (first == NULL)
5039 first = thread;
5040
5041 if (!non_stop)
00431a78 5042 thread->set_running (false);
6efcd9a8
PA
5043 else if (thread->state != THREAD_STOPPED)
5044 continue;
5045
1edb66d8 5046 if (selected == nullptr && thread->has_pending_waitstatus ())
6efcd9a8
PA
5047 selected = thread;
5048
5d5658a1
PA
5049 if (lowest_stopped == NULL
5050 || thread->inf->num < lowest_stopped->inf->num
5051 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
5052 lowest_stopped = thread;
5053
5054 if (non_stop)
5055 print_one_stopped_thread (thread);
5056 }
5057
5058 /* In all-stop, we only print the status of one thread, and leave
5059 others with their status pending. */
5060 if (!non_stop)
5061 {
08036331 5062 thread_info *thread = selected;
6efcd9a8
PA
5063 if (thread == NULL)
5064 thread = lowest_stopped;
5065 if (thread == NULL)
5066 thread = first;
5067
5068 print_one_stopped_thread (thread);
5069 }
221e1a37
PA
5070}
5071
45664f16 5072/* Mark a remote_target as starting (by setting the starting_up flag within
7a34f66b
AB
5073 its remote_state) for the lifetime of this object. The reference count
5074 on the remote target is temporarily incremented, to prevent the target
5075 being deleted under our feet. */
5076
5077struct scoped_mark_target_starting
5078{
5079 /* Constructor, TARGET is the target to be marked as starting, its
5080 reference count will be incremented. */
5081 scoped_mark_target_starting (remote_target *target)
45664f16
AB
5082 : m_remote_target (remote_target_ref::new_reference (target)),
5083 m_restore_starting_up (set_starting_up_flag (target))
5084 { /* Nothing. */ }
5085
5086private:
7a34f66b 5087
45664f16
AB
5088 /* Helper function, set the starting_up flag on TARGET and return an
5089 object which, when it goes out of scope, will restore the previous
5090 value of the starting_up flag. */
5091 static scoped_restore_tmpl<bool>
5092 set_starting_up_flag (remote_target *target)
7a34f66b 5093 {
45664f16
AB
5094 remote_state *rs = target->get_remote_state ();
5095 gdb_assert (!rs->starting_up);
5096 return make_scoped_restore (&rs->starting_up, true);
7a34f66b
AB
5097 }
5098
45664f16
AB
5099 /* A gdb::ref_ptr pointer to a remote_target. */
5100 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
5101
5102 /* A reference to the target on which we are operating. */
5103 remote_target_ref m_remote_target;
7a34f66b 5104
45664f16
AB
5105 /* An object which restores the previous value of the starting_up flag
5106 when it goes out of scope. */
5107 scoped_restore_tmpl<bool> m_restore_starting_up;
7a34f66b
AB
5108};
5109
e2163381
PA
5110/* Transfer ownership of the stop_reply owned by EVENT to a
5111 stop_reply_up object. */
5112
5113static stop_reply_up
5114as_stop_reply_up (notif_event_up event)
5115{
5116 auto *stop_reply = static_cast<struct stop_reply *> (event.release ());
5117 return stop_reply_up (stop_reply);
5118}
5119
288712bb
AB
5120/* Helper for remote_target::start_remote, start the remote connection and
5121 sync state. Return true if everything goes OK, otherwise, return false.
5122 This function exists so that the scoped_restore created within it will
5123 expire before we return to remote_target::start_remote. */
048094ac 5124
288712bb
AB
5125bool
5126remote_target::start_remote_1 (int from_tty, int extended_p)
c906108c 5127{
2189c312
SM
5128 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
5129
c8d104ad 5130 struct remote_state *rs = get_remote_state ();
8621d6a9 5131
048094ac
PA
5132 /* Signal other parts that we're going through the initial setup,
5133 and so things may not be stable yet. E.g., we don't try to
5134 install tracepoints until we've relocated symbols. Also, a
5135 Ctrl-C before we're connected and synced up can't interrupt the
5136 target. Instead, it offers to drop the (potentially wedged)
5137 connection. */
7a34f66b 5138 scoped_mark_target_starting target_is_starting (this);
048094ac 5139
522002f9 5140 QUIT;
c906108c 5141
9a7071a8
JB
5142 if (interrupt_on_connect)
5143 send_interrupt_sequence ();
5144
57e12211 5145 /* Ack any packet which the remote side has already sent. */
048094ac 5146 remote_serial_write ("+", 1);
1e51243a 5147
c8d104ad
PA
5148 /* The first packet we send to the target is the optional "supported
5149 packets" request. If the target can answer this, it will tell us
5150 which later probes to skip. */
5151 remote_query_supported ();
5152
34f0de5a
CS
5153 /* Check vCont support and set the remote state's vCont_action_support
5154 attribute. */
5155 remote_vcont_probe ();
5156
d914c394 5157 /* If the stub wants to get a QAllow, compose one and send it. */
ff52c073 5158 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 5159 set_permissions ();
d914c394 5160
57809e5e
JK
5161 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
5162 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5163 as a reply to known packet. For packet "vFile:setfs:" it is an
5164 invalid reply and GDB would return error in
5165 remote_hostio_set_filesystem, making remote files access impossible.
5166 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5167 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5168 {
5169 const char v_mustreplyempty[] = "vMustReplyEmpty";
5170
5171 putpkt (v_mustreplyempty);
aa7b36b8 5172 getpkt (&rs->buf);
8d64371b 5173 if (strcmp (rs->buf.data (), "OK") == 0)
ff52c073
CS
5174 {
5175 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5176 = PACKET_DISABLE;
5177 }
8d64371b 5178 else if (strcmp (rs->buf.data (), "") != 0)
57809e5e 5179 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
8d64371b 5180 rs->buf.data ());
57809e5e
JK
5181 }
5182
c8d104ad
PA
5183 /* Next, we possibly activate noack mode.
5184
5185 If the QStartNoAckMode packet configuration is set to AUTO,
5186 enable noack mode if the stub reported a wish for it with
5187 qSupported.
5188
5189 If set to TRUE, then enable noack mode even if the stub didn't
5190 report it in qSupported. If the stub doesn't reply OK, the
5191 session ends with an error.
5192
5193 If FALSE, then don't activate noack mode, regardless of what the
5194 stub claimed should be the default with qSupported. */
5195
ff52c073 5196 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
c8d104ad
PA
5197 {
5198 putpkt ("QStartNoAckMode");
aa7b36b8 5199 getpkt (&rs->buf);
94a94c90
AH
5200 if ((m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode)).status ()
5201 == PACKET_OK)
c8d104ad
PA
5202 rs->noack_mode = 1;
5203 }
5204
04bd08de 5205 if (extended_p)
5fe04517
PA
5206 {
5207 /* Tell the remote that we are using the extended protocol. */
5208 putpkt ("!");
aa7b36b8 5209 getpkt (&rs->buf);
5fe04517
PA
5210 }
5211
9b224c5e
PA
5212 /* Let the target know which signals it is allowed to pass down to
5213 the program. */
5214 update_signals_program_target ();
5215
d962ef82
DJ
5216 /* Next, if the target can specify a description, read it. We do
5217 this before anything involving memory or registers. */
5218 target_find_description ();
5219
6c95b8df
PA
5220 /* Next, now that we know something about the target, update the
5221 address spaces in the program spaces. */
5222 update_address_spaces ();
5223
50c71eaf
PA
5224 /* On OSs where the list of libraries is global to all
5225 processes, we fetch them early. */
99d9c3b9 5226 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
e696b3ad 5227 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 5228
6efcd9a8 5229 if (target_is_non_stop_p ())
74531fed 5230 {
ff52c073 5231 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
5232 error (_("Non-stop mode requested, but remote "
5233 "does not support non-stop"));
74531fed
PA
5234
5235 putpkt ("QNonStop:1");
aa7b36b8 5236 getpkt (&rs->buf);
74531fed 5237
8d64371b
TT
5238 if (strcmp (rs->buf.data (), "OK") != 0)
5239 error (_("Remote refused setting non-stop mode with: %s"),
5240 rs->buf.data ());
74531fed
PA
5241
5242 /* Find about threads and processes the stub is already
5243 controlling. We default to adding them in the running state.
5244 The '?' query below will then tell us about which threads are
5245 stopped. */
f6ac5f3d 5246 this->update_thread_list ();
74531fed 5247 }
ff52c073 5248 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
5249 {
5250 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 5251 Request it explicitly. */
74531fed 5252 putpkt ("QNonStop:0");
aa7b36b8 5253 getpkt (&rs->buf);
74531fed 5254
8d64371b
TT
5255 if (strcmp (rs->buf.data (), "OK") != 0)
5256 error (_("Remote refused setting all-stop mode with: %s"),
5257 rs->buf.data ());
74531fed
PA
5258 }
5259
a0743c90
YQ
5260 /* Upload TSVs regardless of whether the target is running or not. The
5261 remote stub, such as GDBserver, may have some predefined or builtin
5262 TSVs, even if the target is not running. */
f6ac5f3d 5263 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
5264 {
5265 struct uploaded_tsv *uploaded_tsvs = NULL;
5266
f6ac5f3d 5267 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
5268 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5269 }
5270
2d717e4f
DJ
5271 /* Check whether the target is running now. */
5272 putpkt ("?");
aa7b36b8 5273 getpkt (&rs->buf);
2d717e4f 5274
6efcd9a8 5275 if (!target_is_non_stop_p ())
2d717e4f 5276 {
b5c8f22d
SM
5277 char *wait_status = NULL;
5278
74531fed 5279 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 5280 {
04bd08de 5281 if (!extended_p)
74531fed 5282 error (_("The target is not running (try extended-remote?)"));
288712bb 5283 return false;
2d717e4f
DJ
5284 }
5285 else
74531fed 5286 {
74531fed 5287 /* Save the reply for later. */
8d64371b
TT
5288 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5289 strcpy (wait_status, rs->buf.data ());
74531fed
PA
5290 }
5291
b7ea362b 5292 /* Fetch thread list. */
e8032dde 5293 target_update_thread_list ();
b7ea362b 5294
74531fed
PA
5295 /* Let the stub know that we want it to return the thread. */
5296 set_continue_thread (minus_one_ptid);
5297
5b6d1e4f 5298 if (thread_count (this) == 0)
b7ea362b
PA
5299 {
5300 /* Target has no concept of threads at all. GDB treats
5301 non-threaded target as single-threaded; add a main
5302 thread. */
64d38fdd
JM
5303 thread_info *tp = add_current_inferior_and_thread (wait_status);
5304 get_remote_thread_info (tp)->set_resumed ();
b7ea362b
PA
5305 }
5306 else
5307 {
5308 /* We have thread information; select the thread the target
5309 says should be current. If we're reconnecting to a
5310 multi-threaded program, this will ideally be the thread
5311 that last reported an event before GDB disconnected. */
75c6c844
PA
5312 ptid_t curr_thread = get_current_thread (wait_status);
5313 if (curr_thread == null_ptid)
b7ea362b
PA
5314 {
5315 /* Odd... The target was able to list threads, but not
5316 tell us which thread was current (no "thread"
5317 register in T stop reply?). Just pick the first
5318 thread in the thread list then. */
2189c312
SM
5319
5320 remote_debug_printf ("warning: couldn't determine remote "
5321 "current thread; picking first in list.");
c9f35b34 5322
5b6d1e4f
PA
5323 for (thread_info *tp : all_non_exited_threads (this,
5324 minus_one_ptid))
75c6c844
PA
5325 {
5326 switch_to_thread (tp);
5327 break;
5328 }
b7ea362b 5329 }
75c6c844 5330 else
9213a6d7 5331 switch_to_thread (this->find_thread (curr_thread));
53de5394
PA
5332
5333 get_remote_thread_info (inferior_thread ())->set_resumed ();
b7ea362b 5334 }
74531fed 5335
6e586cc5
YQ
5336 /* init_wait_for_inferior should be called before get_offsets in order
5337 to manage `inserted' flag in bp loc in a correct state.
5338 breakpoint_init_inferior, called from init_wait_for_inferior, set
5339 `inserted' flag to 0, while before breakpoint_re_set, called from
5340 start_remote, set `inserted' flag to 1. In the initialization of
5341 inferior, breakpoint_init_inferior should be called first, and then
5342 breakpoint_re_set can be called. If this order is broken, state of
5343 `inserted' flag is wrong, and cause some problems on breakpoint
5344 manipulation. */
5345 init_wait_for_inferior ();
5346
74531fed
PA
5347 get_offsets (); /* Get text, data & bss offsets. */
5348
d962ef82
DJ
5349 /* If we could not find a description using qXfer, and we know
5350 how to do it some other way, try again. This is not
5351 supported for non-stop; it could be, but it is tricky if
5352 there are no stopped threads when we connect. */
f6ac5f3d 5353 if (remote_read_description_p (this)
99d9c3b9 5354 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
d962ef82
DJ
5355 {
5356 target_clear_description ();
5357 target_find_description ();
5358 }
5359
74531fed
PA
5360 /* Use the previously fetched status. */
5361 gdb_assert (wait_status != NULL);
e2163381 5362 notif_event_up reply
4f626cad 5363 = remote_notif_parse (this, &notif_client_stop, wait_status);
e2163381 5364 push_stop_reply (as_stop_reply_up (std::move (reply)));
74531fed 5365
f6ac5f3d 5366 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
5367 }
5368 else
5369 {
68c97600
PA
5370 /* Clear WFI global state. Do this before finding about new
5371 threads and inferiors, and setting the current inferior.
5372 Otherwise we would clear the proceed status of the current
5373 inferior when we want its stop_soon state to be preserved
5374 (see notice_new_inferior). */
5375 init_wait_for_inferior ();
5376
74531fed
PA
5377 /* In non-stop, we will either get an "OK", meaning that there
5378 are no stopped threads at this time; or, a regular stop
5379 reply. In the latter case, there may be more than one thread
5380 stopped --- we pull them all out using the vStopped
5381 mechanism. */
8d64371b 5382 if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 5383 {
42938c1a 5384 const notif_client *notif = &notif_client_stop;
2d717e4f 5385
722247f1
YQ
5386 /* remote_notif_get_pending_replies acks this one, and gets
5387 the rest out. */
f48ff2a7 5388 rs->notif_state->pending_event[notif_client_stop.id]
8d64371b 5389 = remote_notif_parse (this, notif, rs->buf.data ());
722247f1 5390 remote_notif_get_pending_events (notif);
74531fed 5391 }
2d717e4f 5392
5b6d1e4f 5393 if (thread_count (this) == 0)
74531fed 5394 {
04bd08de 5395 if (!extended_p)
74531fed 5396 error (_("The target is not running (try extended-remote?)"));
288712bb 5397 return false;
c35b1492 5398 }
74531fed 5399
2455069d 5400 /* Report all signals during attach/startup. */
adc6a863 5401 pass_signals ({});
221e1a37
PA
5402
5403 /* If there are already stopped threads, mark them stopped and
5404 report their stops before giving the prompt to the user. */
6efcd9a8 5405 process_initial_stop_replies (from_tty);
221e1a37
PA
5406
5407 if (target_can_async_p ())
4a570176 5408 target_async (true);
74531fed 5409 }
c8d104ad 5410
901e4e8d
SM
5411 /* Give the target a chance to look up symbols. */
5412 for (inferior *inf : all_inferiors (this))
c8d104ad 5413 {
901e4e8d
SM
5414 /* The inferiors that exist at this point were created from what
5415 was found already running on the remote side, so we know they
5416 have execution. */
5417 gdb_assert (this->has_execution (inf));
5418
a42d7dd8 5419 /* No use without a symbol-file. */
901e4e8d
SM
5420 if (inf->pspace->symfile_object_file == nullptr)
5421 continue;
5422
5423 /* Need to switch to a specific thread, because remote_check_symbols
287de656 5424 uses INFERIOR_PTID to set the general thread. */
901e4e8d
SM
5425 scoped_restore_current_thread restore_thread;
5426 thread_info *thread = any_thread_of_inferior (inf);
5427 switch_to_thread (thread);
5428 this->remote_check_symbols ();
c8d104ad 5429 }
50c71eaf 5430
d5551862
SS
5431 /* Possibly the target has been engaged in a trace run started
5432 previously; find out where things are at. */
f6ac5f3d 5433 if (get_trace_status (current_trace_status ()) != -1)
d5551862 5434 {
00bf0b85 5435 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 5436
00bf0b85 5437 if (current_trace_status ()->running)
6cb06a8c 5438 gdb_printf (_("Trace is already running on the target.\n"));
00bf0b85 5439
f6ac5f3d 5440 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
5441
5442 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
5443 }
5444
c0272db5
TW
5445 /* Possibly the target has been engaged in a btrace record started
5446 previously; find out where things are at. */
5447 remote_btrace_maybe_reopen ();
5448
288712bb
AB
5449 return true;
5450}
5451
5452/* Start the remote connection and sync state. */
1e51243a 5453
288712bb
AB
5454void
5455remote_target::start_remote (int from_tty, int extended_p)
5456{
5457 if (start_remote_1 (from_tty, extended_p)
5458 && breakpoints_should_be_inserted_now ())
50c71eaf 5459 insert_breakpoints ();
c906108c
SS
5460}
5461
121b3efd
PA
5462const char *
5463remote_target::connection_string ()
5464{
5465 remote_state *rs = get_remote_state ();
5466
5467 if (rs->remote_desc->name != NULL)
5468 return rs->remote_desc->name;
5469 else
5470 return NULL;
5471}
5472
c906108c
SS
5473/* Open a connection to a remote debugger.
5474 NAME is the filename used for communication. */
5475
f6ac5f3d
PA
5476void
5477remote_target::open (const char *name, int from_tty)
c906108c 5478{
f6ac5f3d 5479 open_1 (name, from_tty, 0);
43ff13b4
JM
5480}
5481
c906108c
SS
5482/* Open a connection to a remote debugger using the extended
5483 remote gdb protocol. NAME is the filename used for communication. */
5484
f6ac5f3d
PA
5485void
5486extended_remote_target::open (const char *name, int from_tty)
c906108c 5487{
f6ac5f3d 5488 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
5489}
5490
ff52c073
CS
5491void
5492remote_features::reset_all_packet_configs_support ()
d471ea57
AC
5493{
5494 int i;
a744cf53 5495
444abaca 5496 for (i = 0; i < PACKET_MAX; i++)
ff52c073 5497 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
5498}
5499
ca4f7f8b
PA
5500/* Initialize all packet configs. */
5501
5502static void
5503init_all_packet_configs (void)
5504{
5505 int i;
5506
5507 for (i = 0; i < PACKET_MAX; i++)
5508 {
5509 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5510 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5511 }
5512}
5513
23860348 5514/* Symbol look-up. */
dc8acb97 5515
6b8edb51
PA
5516void
5517remote_target::remote_check_symbols ()
dc8acb97 5518{
8d64371b 5519 char *tmp;
dc8acb97
MS
5520 int end;
5521
06c7226e
SM
5522 /* It doesn't make sense to send a qSymbol packet for an inferior that
5523 doesn't have execution, because the remote side doesn't know about
5524 inferiors without execution. */
5525 gdb_assert (target_has_execution ());
63154eca 5526
ff52c073 5527 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
5528 return;
5529
63154eca
PA
5530 /* Make sure the remote is pointing at the right process. Note
5531 there's no way to select "no process". */
3c9c4b83
PA
5532 set_general_process ();
5533
6d820c5c
DJ
5534 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5535 because we need both at the same time. */
66644cd3 5536 gdb::char_vector msg (get_remote_packet_size ());
8d64371b 5537 gdb::char_vector reply (get_remote_packet_size ());
6d820c5c 5538
23860348 5539 /* Invite target to request symbol lookups. */
dc8acb97
MS
5540
5541 putpkt ("qSymbol::");
aa7b36b8 5542 getpkt (&reply);
ff52c073 5543 m_features.packet_ok (reply, PACKET_qSymbol);
dc8acb97 5544
8d64371b 5545 while (startswith (reply.data (), "qSymbol:"))
dc8acb97
MS
5546 {
5547 tmp = &reply[8];
66644cd3
AB
5548 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5549 strlen (tmp) / 2);
dc8acb97 5550 msg[end] = '\0';
4144d36a
SM
5551 bound_minimal_symbol sym
5552 = lookup_minimal_symbol (current_program_space, msg.data ());
3b7344d5 5553 if (sym.minsym == NULL)
66644cd3
AB
5554 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5555 &reply[8]);
dc8acb97 5556 else
2bbe3cc1 5557 {
99d9c3b9 5558 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
4aeddc50 5559 CORE_ADDR sym_addr = sym.value_address ();
2bbe3cc1
DJ
5560
5561 /* If this is a function address, return the start of code
5562 instead of any data function descriptor. */
328d42d8 5563 sym_addr = gdbarch_convert_from_func_ptr_addr
99d9c3b9
SM
5564 (current_inferior ()->arch (), sym_addr,
5565 current_inferior ()->top_target ());
2bbe3cc1 5566
66644cd3 5567 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 5568 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1 5569 }
66644cd3
AB
5570
5571 putpkt (msg.data ());
aa7b36b8 5572 getpkt (&reply);
dc8acb97
MS
5573 }
5574}
5575
9db8d71f 5576static struct serial *
baa336ce 5577remote_serial_open (const char *name)
9db8d71f
DJ
5578{
5579 static int udp_warning = 0;
5580
5581 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5582 of in ser-tcp.c, because it is the remote protocol assuming that the
5583 serial connection is reliable and not the serial connection promising
5584 to be. */
61012eef 5585 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 5586 {
3e43a32a
MS
5587 warning (_("The remote protocol may be unreliable over UDP.\n"
5588 "Some events may be lost, rendering further debugging "
5589 "impossible."));
9db8d71f
DJ
5590 udp_warning = 1;
5591 }
5592
5593 return serial_open (name);
5594}
5595
d914c394
SS
5596/* Inform the target of our permission settings. The permission flags
5597 work without this, but if the target knows the settings, it can do
5598 a couple things. First, it can add its own check, to catch cases
5599 that somehow manage to get by the permissions checks in target
5600 methods. Second, if the target is wired to disallow particular
5601 settings (for instance, a system in the field that is not set up to
5602 be able to stop at a breakpoint), it can object to any unavailable
5603 permissions. */
5604
5605void
f6ac5f3d 5606remote_target::set_permissions ()
d914c394
SS
5607{
5608 struct remote_state *rs = get_remote_state ();
5609
8d64371b 5610 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
bba74b36
YQ
5611 "WriteReg:%x;WriteMem:%x;"
5612 "InsertBreak:%x;InsertTrace:%x;"
5613 "InsertFastTrace:%x;Stop:%x",
5614 may_write_registers, may_write_memory,
5615 may_insert_breakpoints, may_insert_tracepoints,
5616 may_insert_fast_tracepoints, may_stop);
d914c394 5617 putpkt (rs->buf);
aa7b36b8 5618 getpkt (&rs->buf);
d914c394
SS
5619
5620 /* If the target didn't like the packet, warn the user. Do not try
5621 to undo the user's settings, that would just be maddening. */
8d64371b
TT
5622 if (strcmp (rs->buf.data (), "OK") != 0)
5623 warning (_("Remote refused setting permissions with: %s"),
5624 rs->buf.data ());
d914c394
SS
5625}
5626
be2a5f71
DJ
5627/* This type describes each known response to the qSupported
5628 packet. */
5629struct protocol_feature
5630{
5631 /* The name of this protocol feature. */
5632 const char *name;
5633
5634 /* The default for this protocol feature. */
5635 enum packet_support default_support;
5636
5637 /* The function to call when this feature is reported, or after
5638 qSupported processing if the feature is not supported.
5639 The first argument points to this structure. The second
5640 argument indicates whether the packet requested support be
5641 enabled, disabled, or probed (or the default, if this function
5642 is being called at the end of processing and this feature was
5643 not reported). The third argument may be NULL; if not NULL, it
5644 is a NUL-terminated string taken from the packet following
5645 this feature's name and an equals sign. */
6b8edb51
PA
5646 void (*func) (remote_target *remote, const struct protocol_feature *,
5647 enum packet_support, const char *);
be2a5f71
DJ
5648
5649 /* The corresponding packet for this feature. Only used if
5650 FUNC is remote_supported_packet. */
5651 int packet;
5652};
5653
be2a5f71 5654static void
6b8edb51
PA
5655remote_supported_packet (remote_target *remote,
5656 const struct protocol_feature *feature,
be2a5f71
DJ
5657 enum packet_support support,
5658 const char *argument)
5659{
5660 if (argument)
5661 {
5662 warning (_("Remote qSupported response supplied an unexpected value for"
5663 " \"%s\"."), feature->name);
5664 return;
5665 }
5666
ff52c073 5667 remote->m_features.m_protocol_packets[feature->packet].support = support;
be2a5f71 5668}
be2a5f71 5669
6b8edb51
PA
5670void
5671remote_target::remote_packet_size (const protocol_feature *feature,
65c459ab
PA
5672 enum packet_support support,
5673 const char *value)
be2a5f71
DJ
5674{
5675 struct remote_state *rs = get_remote_state ();
5676
5677 int packet_size;
5678 char *value_end;
5679
5680 if (support != PACKET_ENABLE)
5681 return;
5682
5683 if (value == NULL || *value == '\0')
5684 {
5685 warning (_("Remote target reported \"%s\" without a size."),
5686 feature->name);
5687 return;
5688 }
5689
5690 errno = 0;
5691 packet_size = strtol (value, &value_end, 16);
5692 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5693 {
5694 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5695 feature->name, value);
5696 return;
5697 }
5698
be2a5f71
DJ
5699 /* Record the new maximum packet size. */
5700 rs->explicit_packet_size = packet_size;
5701}
5702
cb8c24b6 5703static void
6b8edb51
PA
5704remote_packet_size (remote_target *remote, const protocol_feature *feature,
5705 enum packet_support support, const char *value)
5706{
5707 remote->remote_packet_size (feature, support, value);
5708}
5709
65c459ab
PA
5710void
5711remote_target::remote_supported_thread_options (const protocol_feature *feature,
5712 enum packet_support support,
5713 const char *value)
5714{
5715 struct remote_state *rs = get_remote_state ();
5716
5717 m_features.m_protocol_packets[feature->packet].support = support;
5718
5719 if (support != PACKET_ENABLE)
5720 return;
5721
5722 if (value == nullptr || *value == '\0')
5723 {
5724 warning (_("Remote target reported \"%s\" without supported options."),
5725 feature->name);
5726 return;
5727 }
5728
5729 ULONGEST options = 0;
5730 const char *p = unpack_varlen_hex (value, &options);
5731
5732 if (*p != '\0')
5733 {
5734 warning (_("Remote target reported \"%s\" with "
5735 "bad thread options: \"%s\"."),
5736 feature->name, value);
5737 return;
5738 }
5739
5740 /* Record the set of supported options. */
5741 rs->supported_thread_options = (gdb_thread_option) options;
5742}
5743
5744static void
5745remote_supported_thread_options (remote_target *remote,
5746 const protocol_feature *feature,
5747 enum packet_support support,
5748 const char *value)
5749{
5750 remote->remote_supported_thread_options (feature, support, value);
5751}
5752
dc473cfb 5753static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5754 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5755 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5756 PACKET_qXfer_auxv },
c78fa86a
GB
5757 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5758 PACKET_qXfer_exec_file },
23181151
DJ
5759 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5760 PACKET_qXfer_features },
cfa9d6d9
DJ
5761 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5762 PACKET_qXfer_libraries },
2268b414
JK
5763 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5764 PACKET_qXfer_libraries_svr4 },
ced63ec0 5765 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5766 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5767 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5768 PACKET_qXfer_memory_map },
07e059b5
VP
5769 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5770 PACKET_qXfer_osdata },
dc146f7c
VP
5771 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5772 PACKET_qXfer_threads },
b3b9301e
PA
5773 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5774 PACKET_qXfer_traceframe_info },
89be2091
DJ
5775 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5776 PACKET_QPassSignals },
82075af2
JS
5777 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5778 PACKET_QCatchSyscalls },
9b224c5e
PA
5779 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5780 PACKET_QProgramSignals },
bc3b087d
SDJ
5781 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5782 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5783 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5784 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5785 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5786 PACKET_QEnvironmentHexEncoded },
5787 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5788 PACKET_QEnvironmentReset },
5789 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5790 PACKET_QEnvironmentUnset },
a6f3e723
SL
5791 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5792 PACKET_QStartNoAckMode },
4082afcc
PA
5793 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5794 PACKET_multiprocess_feature },
5795 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5796 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5797 PACKET_qXfer_siginfo_read },
5798 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5799 PACKET_qXfer_siginfo_write },
4082afcc 5800 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5801 PACKET_ConditionalTracepoints },
4082afcc 5802 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5803 PACKET_ConditionalBreakpoints },
4082afcc 5804 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5805 PACKET_BreakpointCommands },
4082afcc 5806 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5807 PACKET_FastTracepoints },
4082afcc 5808 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5809 PACKET_StaticTracepoints },
4082afcc 5810 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5811 PACKET_InstallInTrace},
4082afcc
PA
5812 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5813 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5814 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5815 PACKET_bc },
5816 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5817 PACKET_bs },
409873ef
SS
5818 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5819 PACKET_TracepointSource },
d914c394
SS
5820 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5821 PACKET_QAllow },
4082afcc
PA
5822 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5823 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5824 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5825 PACKET_qXfer_fdpic },
169081d0
TG
5826 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5827 PACKET_qXfer_uib },
03583c20
UW
5828 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5829 PACKET_QDisableRandomization },
d1feda86 5830 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5831 { "QTBuffer:size", PACKET_DISABLE,
5832 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5833 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5834 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5835 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5836 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5837 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5838 PACKET_qXfer_btrace },
5839 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5840 PACKET_qXfer_btrace_conf },
5841 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5842 PACKET_Qbtrace_conf_bts_size },
5843 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5844 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5845 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5846 PACKET_fork_event_feature },
5847 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5848 PACKET_vfork_event_feature },
94585166
DB
5849 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5850 PACKET_exec_event_feature },
b20a6524 5851 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5852 PACKET_Qbtrace_conf_pt_size },
ccc48080
FW
5853 { "Qbtrace-conf:pt:ptwrite", PACKET_DISABLE, remote_supported_packet,
5854 PACKET_Qbtrace_conf_pt_ptwrite },
13b3a89b
FW
5855 { "Qbtrace-conf:pt:event-tracing", PACKET_DISABLE, remote_supported_packet,
5856 PACKET_Qbtrace_conf_pt_event_tracing },
65706a29
PA
5857 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5858 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
65c459ab
PA
5859 { "QThreadOptions", PACKET_DISABLE, remote_supported_thread_options,
5860 PACKET_QThreadOptions },
f2faf941 5861 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
2c2e7f87
LM
5862 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5863 PACKET_memory_tagging_feature },
ddb3f3d8
AH
5864 { "error-message", PACKET_ENABLE, remote_supported_packet,
5865 PACKET_accept_error_message },
9b381fd1 5866 { "binary-upload", PACKET_DISABLE, remote_supported_packet, PACKET_x },
be2a5f71
DJ
5867};
5868
c8d5aac9
L
5869static char *remote_support_xml;
5870
5871/* Register string appended to "xmlRegisters=" in qSupported query. */
5872
5873void
6e39997a 5874register_remote_support_xml (const char *xml)
c8d5aac9
L
5875{
5876#if defined(HAVE_LIBEXPAT)
5877 if (remote_support_xml == NULL)
c4f7c687 5878 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5879 else
5880 {
5881 char *copy = xstrdup (remote_support_xml + 13);
ca3a04f6
CB
5882 char *saveptr;
5883 char *p = strtok_r (copy, ",", &saveptr);
c8d5aac9
L
5884
5885 do
5886 {
5887 if (strcmp (p, xml) == 0)
5888 {
5889 /* already there */
5890 xfree (copy);
5891 return;
5892 }
5893 }
ca3a04f6 5894 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
c8d5aac9
L
5895 xfree (copy);
5896
94b0dee1
PA
5897 remote_support_xml = reconcat (remote_support_xml,
5898 remote_support_xml, ",", xml,
5899 (char *) NULL);
c8d5aac9
L
5900 }
5901#endif
5902}
5903
69b6ecb0
TT
5904static void
5905remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5906{
69b6ecb0
TT
5907 if (!msg->empty ())
5908 msg->append (";");
5909 msg->append (append);
c8d5aac9
L
5910}
5911
6b8edb51
PA
5912void
5913remote_target::remote_query_supported ()
be2a5f71
DJ
5914{
5915 struct remote_state *rs = get_remote_state ();
5916 char *next;
5917 int i;
5918 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5919
5920 /* The packet support flags are handled differently for this packet
5921 than for most others. We treat an error, a disabled packet, and
5922 an empty response identically: any features which must be reported
5923 to be used will be automatically disabled. An empty buffer
5924 accomplishes this, since that is also the representation for a list
5925 containing no features. */
5926
5927 rs->buf[0] = 0;
ff52c073 5928 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5929 {
69b6ecb0 5930 std::string q;
c8d5aac9 5931
ff52c073
CS
5932 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5933 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5934 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5935
ff52c073
CS
5936 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5937 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5938 remote_query_supported_append (&q, "swbreak+");
ff52c073
CS
5939
5940 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5941 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5942 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5943
69b6ecb0 5944 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5945
ff52c073 5946 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
8020350c 5947 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5948 remote_query_supported_append (&q, "fork-events+");
ff52c073
CS
5949
5950 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
8020350c 5951 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5952 remote_query_supported_append (&q, "vfork-events+");
ff52c073
CS
5953
5954 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
8020350c 5955 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5956 remote_query_supported_append (&q, "exec-events+");
89245bc0 5957
ff52c073
CS
5958 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5959 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5960 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5961
ff52c073
CS
5962 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5963 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5964 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5965
65c459ab
PA
5966 if (m_features.packet_set_cmd_state (PACKET_QThreadOptions)
5967 != AUTO_BOOLEAN_FALSE)
5968 remote_query_supported_append (&q, "QThreadOptions+");
5969
ff52c073
CS
5970 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5971 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5972 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5973
ff52c073 5974 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
2c2e7f87
LM
5975 != AUTO_BOOLEAN_FALSE)
5976 remote_query_supported_append (&q, "memory-tagging+");
5977
b35d5edb
PA
5978 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5979 the qSupported:xmlRegisters=i386 handling. */
7cc244de 5980 if (remote_support_xml != NULL
ff52c073
CS
5981 && (m_features.packet_support (PACKET_qXfer_features)
5982 != PACKET_DISABLE))
69b6ecb0 5983 remote_query_supported_append (&q, remote_support_xml);
82f73884 5984
ddb3f3d8
AH
5985 if (m_features.packet_set_cmd_state (PACKET_accept_error_message)
5986 != AUTO_BOOLEAN_FALSE)
9153eb8a 5987 remote_query_supported_append (&q, "error-message+");
ddb3f3d8 5988
69b6ecb0
TT
5989 q = "qSupported:" + q;
5990 putpkt (q.c_str ());
94b0dee1 5991
aa7b36b8 5992 getpkt (&rs->buf);
be2a5f71 5993
33b5899f 5994 /* If an error occurred, warn, but do not return - just reset the
be2a5f71 5995 buffer to empty and go on to disable features. */
94a94c90
AH
5996 packet_result result = m_features.packet_ok (rs->buf, PACKET_qSupported);
5997 if (result.status () == PACKET_ERROR)
be2a5f71 5998 {
94a94c90 5999 warning (_("Remote failure reply: %s"), result.err_msg ());
be2a5f71
DJ
6000 rs->buf[0] = 0;
6001 }
6002 }
6003
6004 memset (seen, 0, sizeof (seen));
6005
8d64371b 6006 next = rs->buf.data ();
be2a5f71
DJ
6007 while (*next)
6008 {
6009 enum packet_support is_supported;
6010 char *p, *end, *name_end, *value;
6011
6012 /* First separate out this item from the rest of the packet. If
6013 there's another item after this, we overwrite the separator
6014 (terminated strings are much easier to work with). */
6015 p = next;
6016 end = strchr (p, ';');
6017 if (end == NULL)
6018 {
6019 end = p + strlen (p);
6020 next = end;
6021 }
6022 else
6023 {
89be2091
DJ
6024 *end = '\0';
6025 next = end + 1;
6026
be2a5f71
DJ
6027 if (end == p)
6028 {
6029 warning (_("empty item in \"qSupported\" response"));
6030 continue;
6031 }
be2a5f71
DJ
6032 }
6033
6034 name_end = strchr (p, '=');
6035 if (name_end)
6036 {
6037 /* This is a name=value entry. */
6038 is_supported = PACKET_ENABLE;
6039 value = name_end + 1;
6040 *name_end = '\0';
6041 }
6042 else
6043 {
6044 value = NULL;
6045 switch (end[-1])
6046 {
6047 case '+':
6048 is_supported = PACKET_ENABLE;
6049 break;
6050
6051 case '-':
6052 is_supported = PACKET_DISABLE;
6053 break;
6054
6055 case '?':
6056 is_supported = PACKET_SUPPORT_UNKNOWN;
6057 break;
6058
6059 default:
3e43a32a
MS
6060 warning (_("unrecognized item \"%s\" "
6061 "in \"qSupported\" response"), p);
be2a5f71
DJ
6062 continue;
6063 }
6064 end[-1] = '\0';
6065 }
6066
6067 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
6068 if (strcmp (remote_protocol_features[i].name, p) == 0)
6069 {
6070 const struct protocol_feature *feature;
6071
6072 seen[i] = 1;
6073 feature = &remote_protocol_features[i];
6b8edb51 6074 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
6075 break;
6076 }
6077 }
6078
6079 /* If we increased the packet size, make sure to increase the global
6080 buffer size also. We delay this until after parsing the entire
6081 qSupported packet, because this is the same buffer we were
6082 parsing. */
8d64371b
TT
6083 if (rs->buf.size () < rs->explicit_packet_size)
6084 rs->buf.resize (rs->explicit_packet_size);
be2a5f71
DJ
6085
6086 /* Handle the defaults for unmentioned features. */
6087 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
6088 if (!seen[i])
6089 {
6090 const struct protocol_feature *feature;
6091
6092 feature = &remote_protocol_features[i];
6b8edb51 6093 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
6094 }
6095}
6096
048094ac
PA
6097/* Serial QUIT handler for the remote serial descriptor.
6098
6099 Defers handling a Ctrl-C until we're done with the current
6100 command/response packet sequence, unless:
6101
6102 - We're setting up the connection. Don't send a remote interrupt
6103 request, as we're not fully synced yet. Quit immediately
6104 instead.
6105
6106 - The target has been resumed in the foreground
223ffa71 6107 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
6108 packet, and we're blocked waiting for the stop reply, thus a
6109 Ctrl-C should be immediately sent to the target.
6110
6111 - We get a second Ctrl-C while still within the same serial read or
6112 write. In that case the serial is seemingly wedged --- offer to
6113 quit/disconnect.
6114
6115 - We see a second Ctrl-C without target response, after having
6116 previously interrupted the target. In that case the target/stub
6117 is probably wedged --- offer to quit/disconnect.
6118*/
6119
6b8edb51
PA
6120void
6121remote_target::remote_serial_quit_handler ()
048094ac
PA
6122{
6123 struct remote_state *rs = get_remote_state ();
6124
6125 if (check_quit_flag ())
6126 {
6127 /* If we're starting up, we're not fully synced yet. Quit
6128 immediately. */
6129 if (rs->starting_up)
6130 quit ();
6131 else if (rs->got_ctrlc_during_io)
6132 {
6133 if (query (_("The target is not responding to GDB commands.\n"
6134 "Stop debugging it? ")))
5b6d1e4f 6135 remote_unpush_and_throw (this);
048094ac
PA
6136 }
6137 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 6138 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
6139 interrupt_query ();
6140 /* All-stop protocol, and blocked waiting for stop reply. Send
6141 an interrupt request. */
223ffa71 6142 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 6143 target_interrupt ();
048094ac
PA
6144 else
6145 rs->got_ctrlc_during_io = 1;
6146 }
6147}
6148
6b8edb51
PA
6149/* The remote_target that is current while the quit handler is
6150 overridden with remote_serial_quit_handler. */
6151static remote_target *curr_quit_handler_target;
6152
6153static void
6154remote_serial_quit_handler ()
6155{
6156 curr_quit_handler_target->remote_serial_quit_handler ();
6157}
6158
5b6d1e4f
PA
6159/* Remove the remote target from the target stack of each inferior
6160 that is using it. Upper targets depend on it so remove them
6161 first. */
78a095c3
JK
6162
6163static void
5b6d1e4f 6164remote_unpush_target (remote_target *target)
78a095c3 6165{
5b6d1e4f
PA
6166 /* We have to unpush the target from all inferiors, even those that
6167 aren't running. */
6168 scoped_restore_current_inferior restore_current_inferior;
6169
6170 for (inferior *inf : all_inferiors (target))
6171 {
6172 switch_to_inferior_no_thread (inf);
c8181f70 6173 inf->pop_all_targets_at_and_above (process_stratum);
5b6d1e4f
PA
6174 generic_mourn_inferior ();
6175 }
d7cb0ef3
PA
6176
6177 /* Don't rely on target_close doing this when the target is popped
6178 from the last remote inferior above, because something may be
6179 holding a reference to the target higher up on the stack, meaning
6180 target_close won't be called yet. We lost the connection to the
6181 target, so clear these now, otherwise we may later throw
6182 TARGET_CLOSE_ERROR while trying to tell the remote target to
6183 close the file. */
6184 fileio_handles_invalidate_target (target);
78a095c3 6185}
be2a5f71 6186
d9deb60b 6187[[noreturn]] static void
5b6d1e4f 6188remote_unpush_and_throw (remote_target *target)
048094ac 6189{
5b6d1e4f 6190 remote_unpush_target (target);
048094ac
PA
6191 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6192}
6193
f6ac5f3d
PA
6194void
6195remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 6196{
6b8edb51 6197 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 6198
c906108c 6199 if (name == 0)
8a3fe4f8 6200 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 6201 "serial device is attached to the remote system\n"
8a3fe4f8 6202 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 6203
2d717e4f 6204 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
6205 Ask this question first, before target_preopen has a chance to kill
6206 anything. */
55f6301a 6207 if (curr_remote != NULL && !target_has_execution ())
2d717e4f 6208 {
78a095c3
JK
6209 if (from_tty
6210 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
6211 error (_("Still connected."));
6212 }
6213
78a095c3 6214 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
6215 target_preopen (from_tty);
6216
ad9a8f3f 6217 remote_fileio_reset ();
1dd41f16 6218 reopen_exec_file ();
9dec38d3 6219 reread_symbols (from_tty);
1dd41f16 6220
6b8edb51
PA
6221 remote_target *remote
6222 = (extended_p ? new extended_remote_target () : new remote_target ());
6223 target_ops_up target_holder (remote);
6224
6225 remote_state *rs = remote->get_remote_state ();
6226
6227 /* See FIXME above. */
6228 if (!target_async_permitted)
8756b726 6229 rs->wait_forever_enabled_p = true;
6b8edb51 6230
5d93a237 6231 rs->remote_desc = remote_serial_open (name);
c906108c
SS
6232
6233 if (baud_rate != -1)
6234 {
ad3cf8c6
TT
6235 try
6236 {
6237 serial_setbaudrate (rs->remote_desc, baud_rate);
6238 }
6239 catch (const gdb_exception_error &)
c906108c 6240 {
9b74d5d3
KB
6241 /* The requested speed could not be set. Error out to
6242 top level after closing remote_desc. Take care to
6243 set remote_desc to NULL to avoid closing remote_desc
6244 more than once. */
5d93a237
TT
6245 serial_close (rs->remote_desc);
6246 rs->remote_desc = NULL;
ad3cf8c6 6247 throw;
c906108c
SS
6248 }
6249 }
6250
236af5e3 6251 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 6252 serial_raw (rs->remote_desc);
c906108c
SS
6253
6254 /* If there is something sitting in the buffer we might take it as a
6255 response to a command, which would be bad. */
5d93a237 6256 serial_flush_input (rs->remote_desc);
c906108c
SS
6257
6258 if (from_tty)
6259 {
0426ad51
TT
6260 gdb_puts ("Remote debugging using ");
6261 gdb_puts (name);
6262 gdb_puts ("\n");
c906108c 6263 }
d9f719f1 6264
6b8edb51 6265 /* Switch to using the remote target now. */
02980c56 6266 current_inferior ()->push_target (std::move (target_holder));
c906108c 6267
74531fed 6268 /* Register extra event sources in the event loop. */
92b98b37
SM
6269 rs->create_async_event_handler ();
6270
6b8edb51 6271 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 6272
be2a5f71
DJ
6273 /* Reset the target state; these things will be queried either by
6274 remote_query_supported or as they are needed. */
ff52c073 6275 remote->m_features.reset_all_packet_configs_support ();
be2a5f71 6276 rs->explicit_packet_size = 0;
a6f3e723 6277 rs->noack_mode = 0;
82f73884 6278 rs->extended = extended_p;
e24a49d8 6279 rs->waiting_for_stop_reply = 0;
3a29589a 6280 rs->ctrlc_pending_p = 0;
048094ac 6281 rs->got_ctrlc_during_io = 0;
802188a7 6282
47f8a51d
TT
6283 rs->general_thread = not_sent_ptid;
6284 rs->continue_thread = not_sent_ptid;
262e1174 6285 rs->remote_traceframe_number = -1;
c906108c 6286
3a00c802
PA
6287 rs->last_resume_exec_dir = EXEC_FORWARD;
6288
9d1f7ab2 6289 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
6290 rs->use_threadinfo_query = 1;
6291 rs->use_threadextra_query = 1;
9d1f7ab2 6292
dd194f6b 6293 rs->readahead_cache.invalidate ();
80152258 6294
c6ebd6cf 6295 if (target_async_permitted)
92d1e331 6296 {
92d1e331
DJ
6297 /* FIXME: cagney/1999-09-23: During the initial connection it is
6298 assumed that the target is already ready and able to respond to
0df8b418 6299 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 6300 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 6301 around this. Eventually a mechanism that allows
92d1e331 6302 wait_for_inferior() to expect/get timeouts will be
23860348 6303 implemented. */
8756b726 6304 rs->wait_forever_enabled_p = false;
92d1e331
DJ
6305 }
6306
23860348 6307 /* First delete any symbols previously loaded from shared libraries. */
b8c9d0de 6308 no_shared_libraries (current_program_space);
f78f6cf1 6309
36918e70 6310 /* Start the remote connection. If error() or QUIT, discard this
165b8e33 6311 target (we'd otherwise be in an inconsistent state) and then
8f6606b6 6312 propagate the error on up the exception chain. This ensures that
165b8e33
AC
6313 the caller doesn't stumble along blindly assuming that the
6314 function succeeded. The CLI doesn't have this problem but other
6315 UI's, such as MI do.
36918e70
AC
6316
6317 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6318 this function should return an error indication letting the
ce2826aa 6319 caller restore the previous state. Unfortunately the command
36918e70
AC
6320 ``target remote'' is directly wired to this function making that
6321 impossible. On a positive note, the CLI side of this problem has
6322 been fixed - the function set_cmd_context() makes it possible for
6323 all the ``target ....'' commands to share a common callback
6324 function. See cli-dump.c. */
109c3e39 6325 {
2d717e4f 6326
a70b8144 6327 try
04bd08de 6328 {
6b8edb51 6329 remote->start_remote (from_tty, extended_p);
04bd08de 6330 }
230d2906 6331 catch (const gdb_exception &ex)
109c3e39 6332 {
c8d104ad
PA
6333 /* Pop the partially set up target - unless something else did
6334 already before throwing the exception. */
6b8edb51 6335 if (ex.error != TARGET_CLOSE_ERROR)
5b6d1e4f 6336 remote_unpush_target (remote);
eedc3f4f 6337 throw;
109c3e39
AC
6338 }
6339 }
c906108c 6340
6b8edb51 6341 remote_btrace_reset (rs);
f4abbc16 6342
c6ebd6cf 6343 if (target_async_permitted)
8756b726 6344 rs->wait_forever_enabled_p = true;
43ff13b4
JM
6345}
6346
28561a65 6347/* Determine if WS represents a fork status. */
a4543480 6348
28561a65
SM
6349static bool
6350is_fork_status (target_waitkind kind)
a4543480 6351{
28561a65
SM
6352 return (kind == TARGET_WAITKIND_FORKED
6353 || kind == TARGET_WAITKIND_VFORKED);
a4543480
SM
6354}
6355
53de5394
PA
6356/* Return a reference to the field where a pending child status, if
6357 there's one, is recorded. If there's no child event pending, the
6358 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6359
6360static const target_waitstatus &
6361thread_pending_status (struct thread_info *thread)
6362{
6363 return (thread->has_pending_waitstatus ()
6364 ? thread->pending_waitstatus ()
6365 : thread->pending_follow);
6366}
6367
6368/* Return THREAD's pending status if it is a pending fork/vfork (but
6369 not clone) parent, else return nullptr. */
a4543480 6370
28561a65 6371static const target_waitstatus *
a4543480
SM
6372thread_pending_fork_status (struct thread_info *thread)
6373{
53de5394 6374 const target_waitstatus &ws = thread_pending_status (thread);
a4543480 6375
28561a65
SM
6376 if (!is_fork_status (ws.kind ()))
6377 return nullptr;
a4543480 6378
28561a65 6379 return &ws;
a4543480
SM
6380}
6381
53de5394
PA
6382/* Return THREAD's pending status if is is a pending fork/vfork/clone
6383 event, else return nullptr. */
6384
6385static const target_waitstatus *
6386thread_pending_child_status (thread_info *thread)
6387{
6388 const target_waitstatus &ws = thread_pending_status (thread);
6389
6390 if (!is_new_child_status (ws.kind ()))
6391 return nullptr;
6392
6393 return &ws;
6394}
6395
de0d863e
DB
6396/* Detach the specified process. */
6397
6b8edb51
PA
6398void
6399remote_target::remote_detach_pid (int pid)
de0d863e
DB
6400{
6401 struct remote_state *rs = get_remote_state ();
6402
4c7333b3
PA
6403 /* This should not be necessary, but the handling for D;PID in
6404 GDBserver versions prior to 8.2 incorrectly assumes that the
6405 selected process points to the same process we're detaching,
6406 leading to misbehavior (and possibly GDBserver crashing) when it
6407 does not. Since it's easy and cheap, work around it by forcing
6408 GDBserver to select GDB's current process. */
6409 set_general_process ();
6410
ff52c073 6411 if (m_features.remote_multi_process_p ())
8d64371b 6412 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
de0d863e 6413 else
8d64371b 6414 strcpy (rs->buf.data (), "D");
de0d863e
DB
6415
6416 putpkt (rs->buf);
aa7b36b8 6417 getpkt (&rs->buf);
de0d863e
DB
6418
6419 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6420 ;
6421 else if (rs->buf[0] == '\0')
6422 error (_("Remote doesn't know how to detach"));
6423 else
fd492bf1
AB
6424 {
6425 /* It is possible that we have an unprocessed exit event for this
6426 pid. If this is the case then we can ignore the failure to detach
6427 and just pretend that the detach worked, as far as the user is
6428 concerned, the process exited immediately after the detach. */
6429 bool process_has_already_exited = false;
6430 remote_notif_get_pending_events (&notif_client_stop);
6431 for (stop_reply_up &reply : rs->stop_reply_queue)
6432 {
6433 if (reply->ptid.pid () != pid)
6434 continue;
6435
6436 enum target_waitkind kind = reply->ws.kind ();
6437 if (kind == TARGET_WAITKIND_EXITED
6438 || kind == TARGET_WAITKIND_SIGNALLED)
6439 {
6440 process_has_already_exited = true;
6441 remote_debug_printf
6442 ("detach failed, but process already exited");
6443 break;
6444 }
6445 }
6446
6447 if (!process_has_already_exited)
6448 error (_("can't detach process: %s"), (char *) rs->buf.data ());
6449 }
de0d863e
DB
6450}
6451
6452/* This detaches a program to which we previously attached, using
6453 inferior_ptid to identify the process. After this is done, GDB
6454 can be used to debug some other program. We better not have left
6455 any breakpoints in the target program or it'll die when it hits
6456 one. */
c906108c 6457
6b8edb51 6458void
00431a78 6459remote_target::remote_detach_1 (inferior *inf, int from_tty)
c906108c 6460{
e99b03dc 6461 int pid = inferior_ptid.pid ();
d01949b6 6462 struct remote_state *rs = get_remote_state ();
de0d863e 6463 int is_fork_parent;
c906108c 6464
55f6301a 6465 if (!target_has_execution ())
2d717e4f
DJ
6466 error (_("No process to detach from."));
6467
0f48b757 6468 target_announce_detach (from_tty);
7cee1e54 6469
99d9c3b9 6470 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
e87f0fe8
PA
6471 {
6472 /* If we're in breakpoints-always-inserted mode, or the inferior
6473 is running, we have to remove breakpoints before detaching.
6474 We don't do this in common code instead because not all
6475 targets support removing breakpoints while the target is
6476 running. The remote target / gdbserver does, though. */
6477 remove_breakpoints_inf (current_inferior ());
6478 }
6479
c906108c 6480 /* Tell the remote target to detach. */
de0d863e 6481 remote_detach_pid (pid);
82f73884 6482
8020350c 6483 /* Exit only if this is the only active inferior. */
5b6d1e4f 6484 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
0426ad51 6485 gdb_puts (_("Ending remote debugging.\n"));
82f73884 6486
df5ad102
SM
6487 /* See if any thread of the inferior we are detaching has a pending fork
6488 status. In that case, we must detach from the child resulting from
6489 that fork. */
6490 for (thread_info *thread : inf->non_exited_threads ())
6491 {
6492 const target_waitstatus *ws = thread_pending_fork_status (thread);
6493
6494 if (ws == nullptr)
6495 continue;
6496
6497 remote_detach_pid (ws->child_ptid ().pid ());
6498 }
6499
6500 /* Check also for any pending fork events in the stop reply queue. */
6501 remote_notif_get_pending_events (&notif_client_stop);
6502 for (stop_reply_up &reply : rs->stop_reply_queue)
6503 {
6504 if (reply->ptid.pid () != pid)
6505 continue;
6506
6507 if (!is_fork_status (reply->ws.kind ()))
6508 continue;
6509
6510 remote_detach_pid (reply->ws.child_ptid ().pid ());
6511 }
6512
9213a6d7 6513 thread_info *tp = this->find_thread (inferior_ptid);
00431a78 6514
de0d863e
DB
6515 /* Check to see if we are detaching a fork parent. Note that if we
6516 are detaching a fork child, tp == NULL. */
6517 is_fork_parent = (tp != NULL
183be222 6518 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
de0d863e
DB
6519
6520 /* If doing detach-on-fork, we don't mourn, because that will delete
6521 breakpoints that should be available for the followed inferior. */
6522 if (!is_fork_parent)
f67c0c91 6523 {
249b5733
PA
6524 /* Save the pid as a string before mourning, since that will
6525 unpush the remote target, and we need the string after. */
f2907e49 6526 std::string infpid = target_pid_to_str (ptid_t (pid));
f67c0c91
SDJ
6527
6528 target_mourn_inferior (inferior_ptid);
6529 if (print_inferior_events)
6cb06a8c
TT
6530 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6531 inf->num, infpid.c_str ());
f67c0c91 6532 }
de0d863e
DB
6533 else
6534 {
0ac55310 6535 switch_to_no_thread ();
00431a78 6536 detach_inferior (current_inferior ());
de0d863e 6537 }
2d717e4f
DJ
6538}
6539
f6ac5f3d
PA
6540void
6541remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6542{
00431a78 6543 remote_detach_1 (inf, from_tty);
2d717e4f
DJ
6544}
6545
f6ac5f3d
PA
6546void
6547extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6548{
00431a78 6549 remote_detach_1 (inf, from_tty);
de0d863e
DB
6550}
6551
6552/* Target follow-fork function for remote targets. On entry, and
6553 at return, the current inferior is the fork parent.
6554
6555 Note that although this is currently only used for extended-remote,
6556 it is named remote_follow_fork in anticipation of using it for the
6557 remote target as well. */
6558
e97007b6 6559void
82d1f134
SM
6560remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6561 target_waitkind fork_kind, bool follow_child,
6562 bool detach_fork)
de0d863e 6563{
82d1f134
SM
6564 process_stratum_target::follow_fork (child_inf, child_ptid,
6565 fork_kind, follow_child, detach_fork);
6566
ff52c073
CS
6567 if ((fork_kind == TARGET_WAITKIND_FORKED
6568 && m_features.remote_fork_event_p ())
6569 || (fork_kind == TARGET_WAITKIND_VFORKED
6570 && m_features.remote_vfork_event_p ()))
de0d863e
DB
6571 {
6572 /* When following the parent and detaching the child, we detach
6573 the child here. For the case of following the child and
6574 detaching the parent, the detach is done in the target-
6575 independent follow fork code in infrun.c. We can't use
6576 target_detach when detaching an unfollowed child because
6577 the client side doesn't know anything about the child. */
6578 if (detach_fork && !follow_child)
6579 {
6580 /* Detach the fork child. */
3a849a34 6581 remote_detach_pid (child_ptid.pid ());
de0d863e
DB
6582 }
6583 }
c906108c
SS
6584}
6585
53de5394
PA
6586void
6587remote_target::follow_clone (ptid_t child_ptid)
6588{
6589 remote_add_thread (child_ptid, false, false, false);
6590}
6591
94585166 6592/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
294c36eb 6593 in the program space of the new inferior. */
94585166 6594
f6ac5f3d 6595void
294c36eb
SM
6596remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6597 const char *execd_pathname)
94585166 6598{
294c36eb
SM
6599 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6600
94585166
DB
6601 /* We know that this is a target file name, so if it has the "target:"
6602 prefix we strip it off before saving it in the program space. */
6603 if (is_target_filename (execd_pathname))
6604 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6605
294c36eb 6606 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
94585166
DB
6607}
6608
6ad8ae5c
DJ
6609/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6610
f6ac5f3d
PA
6611void
6612remote_target::disconnect (const char *args, int from_tty)
43ff13b4 6613{
43ff13b4 6614 if (args)
2d717e4f 6615 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 6616
8020350c 6617 /* Make sure we unpush even the extended remote targets. Calling
5b6d1e4f
PA
6618 target_mourn_inferior won't unpush, and
6619 remote_target::mourn_inferior won't unpush if there is more than
6620 one inferior left. */
6621 remote_unpush_target (this);
2d717e4f 6622
43ff13b4 6623 if (from_tty)
0426ad51 6624 gdb_puts ("Ending remote debugging.\n");
43ff13b4
JM
6625}
6626
2d717e4f
DJ
6627/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6628 be chatty about it. */
6629
f6ac5f3d
PA
6630void
6631extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
6632{
6633 struct remote_state *rs = get_remote_state ();
be86555c 6634 int pid;
96ef3384 6635 char *wait_status = NULL;
2d717e4f 6636
74164c56 6637 pid = parse_pid_to_attach (args);
2d717e4f 6638
74164c56
JK
6639 /* Remote PID can be freely equal to getpid, do not check it here the same
6640 way as in other targets. */
2d717e4f 6641
ff52c073 6642 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
6643 error (_("This target does not support attaching to a process"));
6644
bc521517 6645 target_announce_attach (from_tty, pid);
7cee1e54 6646
8d64371b 6647 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f 6648 putpkt (rs->buf);
aa7b36b8 6649 getpkt (&rs->buf);
2d717e4f 6650
94a94c90
AH
6651 packet_result result = m_features.packet_ok (rs->buf, PACKET_vAttach);
6652 switch (result.status ())
2d717e4f 6653 {
4082afcc 6654 case PACKET_OK:
6efcd9a8 6655 if (!target_is_non_stop_p ())
74531fed
PA
6656 {
6657 /* Save the reply for later. */
8d64371b
TT
6658 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6659 strcpy (wait_status, rs->buf.data ());
74531fed 6660 }
8d64371b 6661 else if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 6662 error (_("Attaching to %s failed with: %s"),
a068643d 6663 target_pid_to_str (ptid_t (pid)).c_str (),
8d64371b 6664 rs->buf.data ());
4082afcc
PA
6665 break;
6666 case PACKET_UNKNOWN:
6667 error (_("This target does not support attaching to a process"));
94a94c90
AH
6668 case PACKET_ERROR:
6669 error (_("Attaching to %s failed: %s"),
6670 target_pid_to_str (ptid_t (pid)).c_str (), result.err_msg ());
2d717e4f 6671 }
2d717e4f 6672
0ac55310 6673 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
bad34192 6674
f2907e49 6675 inferior_ptid = ptid_t (pid);
79d7f229 6676
6efcd9a8 6677 if (target_is_non_stop_p ())
bad34192 6678 {
bad34192 6679 /* Get list of threads. */
f6ac5f3d 6680 update_thread_list ();
82f73884 6681
0ac55310
PA
6682 thread_info *thread = first_thread_of_inferior (current_inferior ());
6683 if (thread != nullptr)
6684 switch_to_thread (thread);
bad34192
PA
6685
6686 /* Invalidate our notion of the remote current thread. */
47f8a51d 6687 record_currthread (rs, minus_one_ptid);
bad34192 6688 }
74531fed 6689 else
bad34192 6690 {
0ac55310
PA
6691 /* Now, if we have thread information, update the main thread's
6692 ptid. */
6693 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
bad34192 6694
b622494e
AB
6695 /* Add the main thread to the thread list. We add the thread
6696 silently in this case (the final true parameter). */
6697 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
0ac55310
PA
6698
6699 switch_to_thread (thr);
bad34192 6700 }
c0a2216e 6701
96ef3384
UW
6702 /* Next, if the target can specify a description, read it. We do
6703 this before anything involving memory or registers. */
6704 target_find_description ();
6705
6efcd9a8 6706 if (!target_is_non_stop_p ())
74531fed
PA
6707 {
6708 /* Use the previously fetched status. */
6709 gdb_assert (wait_status != NULL);
6710
e2163381
PA
6711 notif_event_up reply
6712 = remote_notif_parse (this, &notif_client_stop, wait_status);
6713 push_stop_reply (as_stop_reply_up (std::move (reply)));
74531fed
PA
6714 }
6715 else
621cc310
PA
6716 {
6717 gdb_assert (wait_status == NULL);
6718
6719 gdb_assert (target_can_async_p ());
621cc310 6720 }
2d717e4f
DJ
6721}
6722
b9c1d481
AS
6723/* Implementation of the to_post_attach method. */
6724
f6ac5f3d
PA
6725void
6726extended_remote_target::post_attach (int pid)
b9c1d481 6727{
6efcd9a8
PA
6728 /* Get text, data & bss offsets. */
6729 get_offsets ();
6730
b9c1d481
AS
6731 /* In certain cases GDB might not have had the chance to start
6732 symbol lookup up until now. This could happen if the debugged
6733 binary is not using shared libraries, the vsyscall page is not
6734 present (on Linux) and the binary itself hadn't changed since the
6735 debugging process was started. */
a42d7dd8 6736 if (current_program_space->symfile_object_file != NULL)
b9c1d481
AS
6737 remote_check_symbols();
6738}
6739
c906108c 6740\f
506fb367
DJ
6741/* Check for the availability of vCont. This function should also check
6742 the response. */
c906108c 6743
6b8edb51
PA
6744void
6745remote_target::remote_vcont_probe ()
c906108c 6746{
6b8edb51 6747 remote_state *rs = get_remote_state ();
2e9f7625 6748 char *buf;
6d820c5c 6749
8d64371b 6750 strcpy (rs->buf.data (), "vCont?");
2e9f7625 6751 putpkt (rs->buf);
aa7b36b8 6752 getpkt (&rs->buf);
8d64371b 6753 buf = rs->buf.data ();
c906108c 6754
506fb367 6755 /* Make sure that the features we assume are supported. */
61012eef 6756 if (startswith (buf, "vCont"))
506fb367
DJ
6757 {
6758 char *p = &buf[5];
750ce8d1 6759 int support_c, support_C;
506fb367 6760
750ce8d1
YQ
6761 rs->supports_vCont.s = 0;
6762 rs->supports_vCont.S = 0;
506fb367
DJ
6763 support_c = 0;
6764 support_C = 0;
d458bd84 6765 rs->supports_vCont.t = 0;
c1e36e3e 6766 rs->supports_vCont.r = 0;
506fb367
DJ
6767 while (p && *p == ';')
6768 {
6769 p++;
6770 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6771 rs->supports_vCont.s = 1;
506fb367 6772 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6773 rs->supports_vCont.S = 1;
506fb367
DJ
6774 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6775 support_c = 1;
6776 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6777 support_C = 1;
74531fed 6778 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 6779 rs->supports_vCont.t = 1;
c1e36e3e
PA
6780 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6781 rs->supports_vCont.r = 1;
506fb367
DJ
6782
6783 p = strchr (p, ';');
6784 }
c906108c 6785
750ce8d1
YQ
6786 /* If c, and C are not all supported, we can't use vCont. Clearing
6787 BUF will make packet_ok disable the packet. */
6788 if (!support_c || !support_C)
506fb367
DJ
6789 buf[0] = 0;
6790 }
c906108c 6791
ff52c073 6792 m_features.packet_ok (rs->buf, PACKET_vCont);
506fb367 6793}
c906108c 6794
0d8f58ca
PA
6795/* Helper function for building "vCont" resumptions. Write a
6796 resumption to P. ENDP points to one-passed-the-end of the buffer
6797 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6798 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6799 resumed thread should be single-stepped and/or signalled. If PTID
6800 equals minus_one_ptid, then all threads are resumed; if PTID
d51926f0
PA
6801 represents a process, then all threads of the process are
6802 resumed. */
0d8f58ca 6803
6b8edb51
PA
6804char *
6805remote_target::append_resumption (char *p, char *endp,
6806 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
6807{
6808 struct remote_state *rs = get_remote_state ();
6809
a493e3e2 6810 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 6811 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
6812 else if (step
6813 /* GDB is willing to range step. */
6814 && use_range_stepping
6815 /* Target supports range stepping. */
6816 && rs->supports_vCont.r
6817 /* We don't currently support range stepping multiple
6818 threads with a wildcard (though the protocol allows it,
6819 so stubs shouldn't make an active effort to forbid
6820 it). */
ff52c073 6821 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
c1e36e3e
PA
6822 {
6823 struct thread_info *tp;
6824
d7e15655 6825 if (ptid == minus_one_ptid)
c1e36e3e
PA
6826 {
6827 /* If we don't know about the target thread's tid, then
6828 we're resuming magic_null_ptid (see caller). */
9213a6d7 6829 tp = this->find_thread (magic_null_ptid);
c1e36e3e
PA
6830 }
6831 else
9213a6d7 6832 tp = this->find_thread (ptid);
c1e36e3e
PA
6833 gdb_assert (tp != NULL);
6834
6835 if (tp->control.may_range_step)
6836 {
99d9c3b9 6837 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
c1e36e3e
PA
6838
6839 p += xsnprintf (p, endp - p, ";r%s,%s",
6840 phex_nz (tp->control.step_range_start,
6841 addr_size),
6842 phex_nz (tp->control.step_range_end,
6843 addr_size));
6844 }
6845 else
6846 p += xsnprintf (p, endp - p, ";s");
6847 }
0d8f58ca
PA
6848 else if (step)
6849 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6850 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6851 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6852 else
6853 p += xsnprintf (p, endp - p, ";c");
6854
ff52c073 6855 if (m_features.remote_multi_process_p () && ptid.is_pid ())
0d8f58ca
PA
6856 {
6857 ptid_t nptid;
6858
6859 /* All (-1) threads of process. */
184ea2f7 6860 nptid = ptid_t (ptid.pid (), -1);
0d8f58ca
PA
6861
6862 p += xsnprintf (p, endp - p, ":");
6863 p = write_ptid (p, endp, nptid);
6864 }
d7e15655 6865 else if (ptid != minus_one_ptid)
0d8f58ca
PA
6866 {
6867 p += xsnprintf (p, endp - p, ":");
6868 p = write_ptid (p, endp, ptid);
6869 }
6870
6871 return p;
6872}
6873
799a2abe
PA
6874/* Clear the thread's private info on resume. */
6875
6876static void
6877resume_clear_thread_private_info (struct thread_info *thread)
6878{
6879 if (thread->priv != NULL)
6880 {
7aabaf9d
SM
6881 remote_thread_info *priv = get_remote_thread_info (thread);
6882
6883 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6884 priv->watch_data_address = 0;
799a2abe
PA
6885 }
6886}
6887
e5ef252a
PA
6888/* Append a vCont continue-with-signal action for threads that have a
6889 non-zero stop signal. */
6890
6b8edb51
PA
6891char *
6892remote_target::append_pending_thread_resumptions (char *p, char *endp,
6893 ptid_t ptid)
e5ef252a 6894{
5b6d1e4f 6895 for (thread_info *thread : all_non_exited_threads (this, ptid))
08036331 6896 if (inferior_ptid != thread->ptid
1edb66d8 6897 && thread->stop_signal () != GDB_SIGNAL_0)
e5ef252a
PA
6898 {
6899 p = append_resumption (p, endp, thread->ptid,
1edb66d8
SM
6900 0, thread->stop_signal ());
6901 thread->set_stop_signal (GDB_SIGNAL_0);
799a2abe 6902 resume_clear_thread_private_info (thread);
e5ef252a
PA
6903 }
6904
6905 return p;
6906}
6907
7b68ffbb
PA
6908/* Set the target running, using the packets that use Hc
6909 (c/s/C/S). */
6910
6b8edb51
PA
6911void
6912remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6913 gdb_signal siggnal)
7b68ffbb
PA
6914{
6915 struct remote_state *rs = get_remote_state ();
7b68ffbb
PA
6916 char *buf;
6917
6918 rs->last_sent_signal = siggnal;
6919 rs->last_sent_step = step;
6920
6921 /* The c/s/C/S resume packets use Hc, so set the continue
6922 thread. */
d7e15655 6923 if (ptid == minus_one_ptid)
7b68ffbb
PA
6924 set_continue_thread (any_thread_ptid);
6925 else
6926 set_continue_thread (ptid);
6927
5b6d1e4f 6928 for (thread_info *thread : all_non_exited_threads (this))
7b68ffbb
PA
6929 resume_clear_thread_private_info (thread);
6930
8d64371b 6931 buf = rs->buf.data ();
6b8edb51 6932 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6933 {
6934 /* We don't pass signals to the target in reverse exec mode. */
6935 if (info_verbose && siggnal != GDB_SIGNAL_0)
6936 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6937 siggnal);
6938
ff52c073 6939 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
7b68ffbb 6940 error (_("Remote reverse-step not supported."));
ff52c073 6941 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
7b68ffbb
PA
6942 error (_("Remote reverse-continue not supported."));
6943
6944 strcpy (buf, step ? "bs" : "bc");
6945 }
6946 else if (siggnal != GDB_SIGNAL_0)
6947 {
6948 buf[0] = step ? 'S' : 'C';
6949 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6950 buf[2] = tohex (((int) siggnal) & 0xf);
6951 buf[3] = '\0';
6952 }
6953 else
6954 strcpy (buf, step ? "s" : "c");
6955
6956 putpkt (buf);
6957}
6958
d51926f0
PA
6959/* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6960 STEP, and SIGGNAL have the same meaning as in target_resume. This
6961 function returns non-zero iff it resumes the inferior.
44eaed12 6962
7b68ffbb
PA
6963 This function issues a strict subset of all possible vCont commands
6964 at the moment. */
44eaed12 6965
6b8edb51 6966int
d51926f0 6967remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6b8edb51 6968 enum gdb_signal siggnal)
506fb367
DJ
6969{
6970 struct remote_state *rs = get_remote_state ();
82f73884
PA
6971 char *p;
6972 char *endp;
44eaed12 6973
7b68ffbb 6974 /* No reverse execution actions defined for vCont. */
6b8edb51 6975 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6976 return 0;
6977
ff52c073 6978 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6979 return 0;
44eaed12 6980
8d64371b
TT
6981 p = rs->buf.data ();
6982 endp = p + get_remote_packet_size ();
82f73884 6983
506fb367
DJ
6984 /* If we could generate a wider range of packets, we'd have to worry
6985 about overflowing BUF. Should there be a generic
6986 "multi-part-packet" packet? */
6987
0d8f58ca
PA
6988 p += xsnprintf (p, endp - p, "vCont");
6989
d51926f0 6990 if (scope_ptid == magic_null_ptid)
c906108c 6991 {
79d7f229
PA
6992 /* MAGIC_NULL_PTID means that we don't have any active threads,
6993 so we don't have any TID numbers the inferior will
6994 understand. Make sure to only send forms that do not specify
6995 a TID. */
a9cbf802 6996 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6997 }
d51926f0 6998 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
506fb367 6999 {
0d8f58ca
PA
7000 /* Resume all threads (of all processes, or of a single
7001 process), with preference for INFERIOR_PTID. This assumes
7002 inferior_ptid belongs to the set of all threads we are about
7003 to resume. */
a493e3e2 7004 if (step || siggnal != GDB_SIGNAL_0)
82f73884 7005 {
0d8f58ca
PA
7006 /* Step inferior_ptid, with or without signal. */
7007 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 7008 }
0d8f58ca 7009
e5ef252a
PA
7010 /* Also pass down any pending signaled resumption for other
7011 threads not the current. */
d51926f0 7012 p = append_pending_thread_resumptions (p, endp, scope_ptid);
e5ef252a 7013
0d8f58ca 7014 /* And continue others without a signal. */
d51926f0 7015 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
7016 }
7017 else
506fb367 7018 {
d51926f0
PA
7019 /* Scheduler locking; resume only SCOPE_PTID. */
7020 append_resumption (p, endp, scope_ptid, step, siggnal);
506fb367 7021 }
c906108c 7022
8d64371b 7023 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
82f73884 7024 putpkt (rs->buf);
506fb367 7025
6efcd9a8 7026 if (target_is_non_stop_p ())
74531fed
PA
7027 {
7028 /* In non-stop, the stub replies to vCont with "OK". The stop
7029 reply will be reported asynchronously by means of a `%Stop'
7030 notification. */
aa7b36b8 7031 getpkt (&rs->buf);
8d64371b
TT
7032 if (strcmp (rs->buf.data (), "OK") != 0)
7033 error (_("Unexpected vCont reply in non-stop mode: %s"),
7034 rs->buf.data ());
74531fed
PA
7035 }
7036
506fb367 7037 return 1;
c906108c 7038}
43ff13b4 7039
506fb367
DJ
7040/* Tell the remote machine to resume. */
7041
f6ac5f3d 7042void
d51926f0 7043remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
43ff13b4 7044{
d01949b6 7045 struct remote_state *rs = get_remote_state ();
43ff13b4 7046
85ad3aaf
PA
7047 /* When connected in non-stop mode, the core resumes threads
7048 individually. Resuming remote threads directly in target_resume
7049 would thus result in sending one packet per thread. Instead, to
7050 minimize roundtrip latency, here we just store the resume
c9d22089
SM
7051 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
7052 resumption will be done in remote_target::commit_resume, where we'll be
7053 able to do vCont action coalescing. */
f6ac5f3d 7054 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 7055 {
d51926f0
PA
7056 remote_thread_info *remote_thr
7057 = get_remote_thread_info (inferior_thread ());
7aabaf9d 7058
c9d22089 7059 /* We don't expect the core to ask to resume an already resumed (from
287de656 7060 its point of view) thread. */
a6c11cbb 7061 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
c9d22089
SM
7062
7063 remote_thr->set_resumed_pending_vcont (step, siggnal);
d51926f0
PA
7064
7065 /* There's actually nothing that says that the core can't
7066 request a wildcard resume in non-stop mode, though. It's
7067 just that we know it doesn't currently, so we don't bother
7068 with it. */
7069 gdb_assert (scope_ptid == inferior_ptid);
85ad3aaf
PA
7070 return;
7071 }
7072
65c459ab
PA
7073 commit_requested_thread_options ();
7074
722247f1
YQ
7075 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
7076 (explained in remote-notif.c:handle_notification) so
7077 remote_notif_process is not called. We need find a place where
7078 it is safe to start a 'vNotif' sequence. It is good to do it
7079 before resuming inferior, because inferior was stopped and no RSP
7080 traffic at that moment. */
6efcd9a8 7081 if (!target_is_non_stop_p ())
5965e028 7082 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 7083
f6ac5f3d 7084 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 7085
7b68ffbb 7086 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
d51926f0
PA
7087 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
7088 remote_resume_with_hc (scope_ptid, step, siggnal);
43ff13b4 7089
c9d22089 7090 /* Update resumed state tracked by the remote target. */
d51926f0 7091 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
c9d22089
SM
7092 get_remote_thread_info (tp)->set_resumed ();
7093
e24a49d8
PA
7094 /* We've just told the target to resume. The remote server will
7095 wait for the inferior to stop, and then send a stop reply. In
7096 the mean time, we can't start another command/query ourselves
74531fed
PA
7097 because the stub wouldn't be ready to process it. This applies
7098 only to the base all-stop protocol, however. In non-stop (which
7099 only supports vCont), the stub replies with an "OK", and is
7100 immediate able to process further serial input. */
6efcd9a8 7101 if (!target_is_non_stop_p ())
74531fed 7102 rs->waiting_for_stop_reply = 1;
43ff13b4 7103}
85ad3aaf 7104
85ad3aaf
PA
7105/* Private per-inferior info for target remote processes. */
7106
089354bb 7107struct remote_inferior : public private_inferior
85ad3aaf
PA
7108{
7109 /* Whether we can send a wildcard vCont for this process. */
089354bb 7110 bool may_wildcard_vcont = true;
85ad3aaf
PA
7111};
7112
089354bb
SM
7113/* Get the remote private inferior data associated to INF. */
7114
7115static remote_inferior *
7116get_remote_inferior (inferior *inf)
7117{
7118 if (inf->priv == NULL)
40ae603e 7119 inf->priv = std::make_unique<remote_inferior> ();
089354bb 7120
98ed24fb 7121 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
089354bb
SM
7122}
7123
f5db4863 7124/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
7125 outgoing packet buffer. This is used to send multiple vCont
7126 packets if we have more actions than would fit a single packet. */
7127
f5db4863 7128class vcont_builder
85ad3aaf 7129{
f5db4863 7130public:
6b8edb51
PA
7131 explicit vcont_builder (remote_target *remote)
7132 : m_remote (remote)
f5db4863
PA
7133 {
7134 restart ();
7135 }
7136
7137 void flush ();
7138 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
7139
7140private:
7141 void restart ();
7142
6b8edb51
PA
7143 /* The remote target. */
7144 remote_target *m_remote;
7145
85ad3aaf
PA
7146 /* Pointer to the first action. P points here if no action has been
7147 appended yet. */
f5db4863 7148 char *m_first_action;
85ad3aaf
PA
7149
7150 /* Where the next action will be appended. */
f5db4863 7151 char *m_p;
85ad3aaf
PA
7152
7153 /* The end of the buffer. Must never write past this. */
f5db4863 7154 char *m_endp;
85ad3aaf
PA
7155};
7156
7157/* Prepare the outgoing buffer for a new vCont packet. */
7158
f5db4863
PA
7159void
7160vcont_builder::restart ()
85ad3aaf 7161{
6b8edb51 7162 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 7163
8d64371b
TT
7164 m_p = rs->buf.data ();
7165 m_endp = m_p + m_remote->get_remote_packet_size ();
f5db4863
PA
7166 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
7167 m_first_action = m_p;
85ad3aaf
PA
7168}
7169
7170/* If the vCont packet being built has any action, send it to the
7171 remote end. */
7172
f5db4863
PA
7173void
7174vcont_builder::flush ()
85ad3aaf
PA
7175{
7176 struct remote_state *rs;
7177
f5db4863 7178 if (m_p == m_first_action)
85ad3aaf
PA
7179 return;
7180
6b8edb51
PA
7181 rs = m_remote->get_remote_state ();
7182 m_remote->putpkt (rs->buf);
aa7b36b8 7183 m_remote->getpkt (&rs->buf);
8d64371b
TT
7184 if (strcmp (rs->buf.data (), "OK") != 0)
7185 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
85ad3aaf
PA
7186}
7187
7188/* The largest action is range-stepping, with its two addresses. This
7189 is more than sufficient. If a new, bigger action is created, it'll
7190 quickly trigger a failed assertion in append_resumption (and we'll
7191 just bump this). */
7192#define MAX_ACTION_SIZE 200
7193
7194/* Append a new vCont action in the outgoing packet being built. If
7195 the action doesn't fit the packet along with previous actions, push
7196 what we've got so far to the remote end and start over a new vCont
7197 packet (with the new action). */
7198
f5db4863
PA
7199void
7200vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
7201{
7202 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 7203
6b8edb51
PA
7204 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
7205 ptid, step, siggnal);
85ad3aaf
PA
7206
7207 /* Check whether this new action would fit in the vCont packet along
7208 with previous actions. If not, send what we've got so far and
7209 start a new vCont packet. */
f5db4863
PA
7210 size_t rsize = endp - buf;
7211 if (rsize > m_endp - m_p)
85ad3aaf 7212 {
f5db4863
PA
7213 flush ();
7214 restart ();
85ad3aaf
PA
7215
7216 /* Should now fit. */
f5db4863 7217 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
7218 }
7219
f5db4863
PA
7220 memcpy (m_p, buf, rsize);
7221 m_p += rsize;
7222 *m_p = '\0';
85ad3aaf
PA
7223}
7224
7225/* to_commit_resume implementation. */
7226
f6ac5f3d 7227void
1192f124 7228remote_target::commit_resumed ()
85ad3aaf 7229{
85ad3aaf
PA
7230 /* If connected in all-stop mode, we'd send the remote resume
7231 request directly from remote_resume. Likewise if
7232 reverse-debugging, as there are no defined vCont actions for
7233 reverse execution. */
f6ac5f3d 7234 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
7235 return;
7236
65c459ab
PA
7237 commit_requested_thread_options ();
7238
85ad3aaf
PA
7239 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7240 instead of resuming all threads of each process individually.
7241 However, if any thread of a process must remain halted, we can't
7242 send wildcard resumes and must send one action per thread.
7243
7244 Care must be taken to not resume threads/processes the server
7245 side already told us are stopped, but the core doesn't know about
7246 yet, because the events are still in the vStopped notification
7247 queue. For example:
7248
7249 #1 => vCont s:p1.1;c
7250 #2 <= OK
7251 #3 <= %Stopped T05 p1.1
7252 #4 => vStopped
7253 #5 <= T05 p1.2
7254 #6 => vStopped
7255 #7 <= OK
7256 #8 (infrun handles the stop for p1.1 and continues stepping)
7257 #9 => vCont s:p1.1;c
7258
7259 The last vCont above would resume thread p1.2 by mistake, because
7260 the server has no idea that the event for p1.2 had not been
7261 handled yet.
7262
7263 The server side must similarly ignore resume actions for the
7264 thread that has a pending %Stopped notification (and any other
7265 threads with events pending), until GDB acks the notification
7266 with vStopped. Otherwise, e.g., the following case is
7267 mishandled:
7268
7269 #1 => g (or any other packet)
7270 #2 <= [registers]
7271 #3 <= %Stopped T05 p1.2
7272 #4 => vCont s:p1.1;c
7273 #5 <= OK
7274
7275 Above, the server must not resume thread p1.2. GDB can't know
7276 that p1.2 stopped until it acks the %Stopped notification, and
7277 since from GDB's perspective all threads should be running, it
7278 sends a "c" action.
7279
7280 Finally, special care must also be given to handling fork/vfork
7281 events. A (v)fork event actually tells us that two processes
7282 stopped -- the parent and the child. Until we follow the fork,
7283 we must not resume the child. Therefore, if we have a pending
7284 fork follow, we must not send a global wildcard resume action
7285 (vCont;c). We can still send process-wide wildcards though. */
7286
7287 /* Start by assuming a global wildcard (vCont;c) is possible. */
2f63ec5c 7288 bool may_global_wildcard_vcont = true;
85ad3aaf
PA
7289
7290 /* And assume every process is individually wildcard-able too. */
5b6d1e4f 7291 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 7292 {
089354bb
SM
7293 remote_inferior *priv = get_remote_inferior (inf);
7294
7295 priv->may_wildcard_vcont = true;
85ad3aaf
PA
7296 }
7297
7298 /* Check for any pending events (not reported or processed yet) and
7299 disable process and global wildcard resumes appropriately. */
7300 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7301
1192f124
SM
7302 bool any_pending_vcont_resume = false;
7303
5b6d1e4f 7304 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 7305 {
c9d22089
SM
7306 remote_thread_info *priv = get_remote_thread_info (tp);
7307
85ad3aaf
PA
7308 /* If a thread of a process is not meant to be resumed, then we
7309 can't wildcard that process. */
a6c11cbb 7310 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
85ad3aaf 7311 {
089354bb 7312 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
7313
7314 /* And if we can't wildcard a process, we can't wildcard
7315 everything either. */
2f63ec5c 7316 may_global_wildcard_vcont = false;
85ad3aaf
PA
7317 continue;
7318 }
7319
1192f124
SM
7320 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7321 any_pending_vcont_resume = true;
7322
53de5394
PA
7323 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7324 then we can't do a global wildcard, as that would resume the
7325 pending child. */
7326 if (thread_pending_child_status (tp) != nullptr)
2f63ec5c 7327 may_global_wildcard_vcont = false;
85ad3aaf
PA
7328 }
7329
1192f124
SM
7330 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7331 do. */
7332 if (!any_pending_vcont_resume)
7333 return;
7334
85ad3aaf
PA
7335 /* Now let's build the vCont packet(s). Actions must be appended
7336 from narrower to wider scopes (thread -> process -> global). If
7337 we end up with too many actions for a single packet vcont_builder
7338 flushes the current vCont packet to the remote side and starts a
7339 new one. */
6b8edb51 7340 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
7341
7342 /* Threads first. */
5b6d1e4f 7343 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 7344 {
7aabaf9d 7345 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf 7346
c9d22089
SM
7347 /* If the thread was previously vCont-resumed, no need to send a specific
7348 action for it. If we didn't receive a resume request for it, don't
7349 send an action for it either. */
a6c11cbb 7350 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
85ad3aaf
PA
7351 continue;
7352
7353 gdb_assert (!thread_is_in_step_over_chain (tp));
7354
1192f124 7355 /* We should never be commit-resuming a thread that has a stop reply.
287de656 7356 Otherwise, we would end up reporting a stop event for a thread while
1192f124
SM
7357 it is running on the remote target. */
7358 remote_state *rs = get_remote_state ();
7359 for (const auto &stop_reply : rs->stop_reply_queue)
7360 gdb_assert (stop_reply->ptid != tp->ptid);
7361
c9d22089
SM
7362 const resumed_pending_vcont_info &info
7363 = remote_thr->resumed_pending_vcont_info ();
85ad3aaf 7364
c9d22089 7365 /* Check if we need to send a specific action for this thread. If not,
287de656 7366 it will be included in a wildcard resume instead. */
c9d22089
SM
7367 if (info.step || info.sig != GDB_SIGNAL_0
7368 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7369 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7370
7371 remote_thr->set_resumed ();
85ad3aaf
PA
7372 }
7373
7374 /* Now check whether we can send any process-wide wildcard. This is
7375 to avoid sending a global wildcard in the case nothing is
7376 supposed to be resumed. */
2f63ec5c 7377 bool any_process_wildcard = false;
85ad3aaf 7378
5b6d1e4f 7379 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 7380 {
089354bb 7381 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 7382 {
2f63ec5c 7383 any_process_wildcard = true;
85ad3aaf
PA
7384 break;
7385 }
7386 }
7387
7388 if (any_process_wildcard)
7389 {
7390 /* If all processes are wildcard-able, then send a single "c"
7391 action, otherwise, send an "all (-1) threads of process"
7392 continue action for each running process, if any. */
7393 if (may_global_wildcard_vcont)
7394 {
f5db4863
PA
7395 vcont_builder.push_action (minus_one_ptid,
7396 false, GDB_SIGNAL_0);
85ad3aaf
PA
7397 }
7398 else
7399 {
5b6d1e4f 7400 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 7401 {
089354bb 7402 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 7403 {
f2907e49 7404 vcont_builder.push_action (ptid_t (inf->pid),
f5db4863 7405 false, GDB_SIGNAL_0);
85ad3aaf
PA
7406 }
7407 }
7408 }
7409 }
7410
f5db4863 7411 vcont_builder.flush ();
85ad3aaf
PA
7412}
7413
b4b1a226
SM
7414/* Implementation of target_has_pending_events. */
7415
7416bool
7417remote_target::has_pending_events ()
7418{
7419 if (target_can_async_p ())
7420 {
7421 remote_state *rs = get_remote_state ();
7422
92b98b37 7423 if (rs->async_event_handler_marked ())
b4b1a226
SM
7424 return true;
7425
7426 /* Note that BUFCNT can be negative, indicating sticky
7427 error. */
7428 if (rs->remote_desc->bufcnt != 0)
7429 return true;
7430 }
7431 return false;
7432}
7433
c906108c 7434\f
43ff13b4 7435
74531fed
PA
7436/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7437 thread, all threads of a remote process, or all threads of all
7438 processes. */
7439
6b8edb51
PA
7440void
7441remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
7442{
7443 struct remote_state *rs = get_remote_state ();
8d64371b
TT
7444 char *p = rs->buf.data ();
7445 char *endp = p + get_remote_packet_size ();
74531fed 7446
1192f124
SM
7447 /* If any thread that needs to stop was resumed but pending a vCont
7448 resume, generate a phony stop_reply. However, first check
7449 whether the thread wasn't resumed with a signal. Generating a
7450 phony stop in that case would result in losing the signal. */
7451 bool needs_commit = false;
7452 for (thread_info *tp : all_non_exited_threads (this, ptid))
7453 {
7454 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7455
7456 if (remote_thr->get_resume_state ()
7457 == resume_state::RESUMED_PENDING_VCONT)
7458 {
7459 const resumed_pending_vcont_info &info
7460 = remote_thr->resumed_pending_vcont_info ();
7461 if (info.sig != GDB_SIGNAL_0)
7462 {
7463 /* This signal must be forwarded to the inferior. We
7464 could commit-resume just this thread, but its simpler
7465 to just commit-resume everything. */
7466 needs_commit = true;
7467 break;
7468 }
7469 }
7470 }
7471
7472 if (needs_commit)
7473 commit_resumed ();
7474 else
7475 for (thread_info *tp : all_non_exited_threads (this, ptid))
7476 {
7477 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7478
7479 if (remote_thr->get_resume_state ()
7480 == resume_state::RESUMED_PENDING_VCONT)
7481 {
7482 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
96bbe3ef
TT
7483 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7484 tp->ptid.lwp (),
7485 pulongest (tp->ptid.tid ()));
1192f124
SM
7486
7487 /* Check that the thread wasn't resumed with a signal.
7488 Generating a phony stop would result in losing the
7489 signal. */
7490 const resumed_pending_vcont_info &info
7491 = remote_thr->resumed_pending_vcont_info ();
7492 gdb_assert (info.sig == GDB_SIGNAL_0);
7493
e2163381 7494 stop_reply_up sr = std::make_unique<stop_reply> ();
1192f124
SM
7495 sr->ptid = tp->ptid;
7496 sr->rs = rs;
183be222 7497 sr->ws.set_stopped (GDB_SIGNAL_0);
27b1f19f 7498 sr->arch = tp->inf->arch ();
1192f124
SM
7499 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7500 sr->watch_data_address = 0;
7501 sr->core = 0;
e2163381 7502 this->push_stop_reply (std::move (sr));
1192f124
SM
7503
7504 /* Pretend that this thread was actually resumed on the
7505 remote target, then stopped. If we leave it in the
7506 RESUMED_PENDING_VCONT state and the commit_resumed
7507 method is called while the stop reply is still in the
7508 queue, we'll end up reporting a stop event to the core
7509 for that thread while it is running on the remote
7510 target... that would be bad. */
7511 remote_thr->set_resumed ();
7512 }
7513 }
7514
d458bd84 7515 if (!rs->supports_vCont.t)
74531fed
PA
7516 error (_("Remote server does not support stopping threads"));
7517
d7e15655 7518 if (ptid == minus_one_ptid
ff52c073 7519 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
74531fed
PA
7520 p += xsnprintf (p, endp - p, "vCont;t");
7521 else
7522 {
7523 ptid_t nptid;
7524
74531fed
PA
7525 p += xsnprintf (p, endp - p, "vCont;t:");
7526
0e998d96 7527 if (ptid.is_pid ())
74531fed 7528 /* All (-1) threads of process. */
184ea2f7 7529 nptid = ptid_t (ptid.pid (), -1);
74531fed
PA
7530 else
7531 {
7532 /* Small optimization: if we already have a stop reply for
7533 this thread, no use in telling the stub we want this
7534 stopped. */
7535 if (peek_stop_reply (ptid))
7536 return;
7537
7538 nptid = ptid;
7539 }
7540
a9cbf802 7541 write_ptid (p, endp, nptid);
74531fed
PA
7542 }
7543
7544 /* In non-stop, we get an immediate OK reply. The stop reply will
7545 come in asynchronously by notification. */
7546 putpkt (rs->buf);
aa7b36b8 7547 getpkt (&rs->buf);
8d64371b 7548 if (strcmp (rs->buf.data (), "OK") != 0)
a068643d 7549 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
8d64371b 7550 rs->buf.data ());
74531fed
PA
7551}
7552
bfedc46a
PA
7553/* All-stop version of target_interrupt. Sends a break or a ^C to
7554 interrupt the remote target. It is undefined which thread of which
7555 process reports the interrupt. */
74531fed 7556
6b8edb51
PA
7557void
7558remote_target::remote_interrupt_as ()
74531fed
PA
7559{
7560 struct remote_state *rs = get_remote_state ();
7561
3a29589a
DJ
7562 rs->ctrlc_pending_p = 1;
7563
74531fed 7564 /* If the inferior is stopped already, but the core didn't know
4f626cad 7565 about it yet, just ignore the request. The pending stop events
74531fed 7566 will be collected in remote_wait. */
4f626cad 7567 if (stop_reply_queue_length () > 0)
74531fed
PA
7568 return;
7569
9a7071a8
JB
7570 /* Send interrupt_sequence to remote target. */
7571 send_interrupt_sequence ();
74531fed
PA
7572}
7573
de979965
PA
7574/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7575 the remote target. It is undefined which thread of which process
e42de8c7
PA
7576 reports the interrupt. Throws an error if the packet is not
7577 supported by the server. */
de979965 7578
6b8edb51
PA
7579void
7580remote_target::remote_interrupt_ns ()
de979965
PA
7581{
7582 struct remote_state *rs = get_remote_state ();
8d64371b
TT
7583 char *p = rs->buf.data ();
7584 char *endp = p + get_remote_packet_size ();
de979965
PA
7585
7586 xsnprintf (p, endp - p, "vCtrlC");
7587
7588 /* In non-stop, we get an immediate OK reply. The stop reply will
7589 come in asynchronously by notification. */
7590 putpkt (rs->buf);
aa7b36b8 7591 getpkt (&rs->buf);
de979965 7592
94a94c90
AH
7593 packet_result result = m_features.packet_ok (rs->buf, PACKET_vCtrlC);
7594 switch (result.status ())
de979965
PA
7595 {
7596 case PACKET_OK:
7597 break;
7598 case PACKET_UNKNOWN:
e42de8c7 7599 error (_("No support for interrupting the remote target."));
de979965 7600 case PACKET_ERROR:
94a94c90 7601 error (_("Interrupting target failed: %s"), result.err_msg ());
de979965 7602 }
de979965
PA
7603}
7604
bfedc46a 7605/* Implement the to_stop function for the remote targets. */
74531fed 7606
f6ac5f3d
PA
7607void
7608remote_target::stop (ptid_t ptid)
c906108c 7609{
2189c312 7610 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
c906108c 7611
6efcd9a8 7612 if (target_is_non_stop_p ())
74531fed 7613 remote_stop_ns (ptid);
c906108c 7614 else
bfedc46a
PA
7615 {
7616 /* We don't currently have a way to transparently pause the
7617 remote target in all-stop mode. Interrupt it instead. */
de979965 7618 remote_interrupt_as ();
bfedc46a
PA
7619 }
7620}
7621
7622/* Implement the to_interrupt function for the remote targets. */
7623
f6ac5f3d
PA
7624void
7625remote_target::interrupt ()
bfedc46a 7626{
2189c312 7627 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
bfedc46a 7628
e42de8c7
PA
7629 if (target_is_non_stop_p ())
7630 remote_interrupt_ns ();
bfedc46a 7631 else
e42de8c7 7632 remote_interrupt_as ();
c906108c
SS
7633}
7634
93692b58
PA
7635/* Implement the to_pass_ctrlc function for the remote targets. */
7636
f6ac5f3d
PA
7637void
7638remote_target::pass_ctrlc ()
93692b58 7639{
2189c312 7640 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
93692b58 7641
2189c312 7642 struct remote_state *rs = get_remote_state ();
93692b58
PA
7643
7644 /* If we're starting up, we're not fully synced yet. Quit
7645 immediately. */
7646 if (rs->starting_up)
7647 quit ();
7648 /* If ^C has already been sent once, offer to disconnect. */
7649 else if (rs->ctrlc_pending_p)
7650 interrupt_query ();
7651 else
e671cd59 7652 target_interrupt ();
93692b58
PA
7653}
7654
c906108c
SS
7655/* Ask the user what to do when an interrupt is received. */
7656
6b8edb51
PA
7657void
7658remote_target::interrupt_query ()
c906108c 7659{
abc56d60 7660 struct remote_state *rs = get_remote_state ();
c906108c 7661
abc56d60 7662 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 7663 {
abc56d60
PA
7664 if (query (_("The target is not responding to interrupt requests.\n"
7665 "Stop debugging it? ")))
74531fed 7666 {
5b6d1e4f 7667 remote_unpush_target (this);
abc56d60 7668 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
7669 }
7670 }
abc56d60
PA
7671 else
7672 {
7673 if (query (_("Interrupted while waiting for the program.\n"
7674 "Give up waiting? ")))
7675 quit ();
7676 }
c906108c
SS
7677}
7678
6426a772
JM
7679/* Enable/disable target terminal ownership. Most targets can use
7680 terminal groups to control terminal ownership. Remote targets are
7681 different in that explicit transfer of ownership to/from GDB/target
23860348 7682 is required. */
6426a772 7683
f6ac5f3d
PA
7684void
7685remote_target::terminal_inferior ()
6426a772 7686{
6426a772
JM
7687 /* NOTE: At this point we could also register our selves as the
7688 recipient of all input. Any characters typed could then be
23860348 7689 passed on down to the target. */
6426a772
JM
7690}
7691
f6ac5f3d
PA
7692void
7693remote_target::terminal_ours ()
6426a772 7694{
6426a772
JM
7695}
7696
176a6961 7697static void
c6100129 7698remote_console_output (const char *msg, ui_file *stream)
c906108c 7699{
05be00a8 7700 const char *p;
c906108c 7701
c5aa993b 7702 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
7703 {
7704 char tb[2];
7705 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 7706
c906108c
SS
7707 tb[0] = c;
7708 tb[1] = 0;
c6100129 7709 stream->puts (tb);
c906108c 7710 }
c6100129 7711 stream->flush ();
00db5b94 7712}
74531fed 7713
221e1a37
PA
7714/* Return the length of the stop reply queue. */
7715
6b8edb51
PA
7716int
7717remote_target::stop_reply_queue_length ()
221e1a37 7718{
6b8edb51 7719 remote_state *rs = get_remote_state ();
953edf2b 7720 return rs->stop_reply_queue.size ();
221e1a37
PA
7721}
7722
cb8c24b6 7723static void
6b8edb51 7724remote_notif_stop_parse (remote_target *remote,
42938c1a 7725 const notif_client *self, const char *buf,
722247f1
YQ
7726 struct notif_event *event)
7727{
6b8edb51 7728 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
7729}
7730
7731static void
6b8edb51 7732remote_notif_stop_ack (remote_target *remote,
42938c1a 7733 const notif_client *self, const char *buf,
e2163381 7734 notif_event_up event)
722247f1 7735{
e2163381 7736 stop_reply_up stop_reply = as_stop_reply_up (std::move (event));
722247f1
YQ
7737
7738 /* acknowledge */
6b8edb51 7739 putpkt (remote, self->ack_command);
722247f1 7740
b0083dd7
PA
7741 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7742 the notification. It was left in the queue because we need to
7743 acknowledge it and pull the rest of the notifications out. */
183be222 7744 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
e2163381 7745 remote->push_stop_reply (std::move (stop_reply));
722247f1
YQ
7746}
7747
7748static int
6b8edb51 7749remote_notif_stop_can_get_pending_events (remote_target *remote,
42938c1a 7750 const notif_client *self)
722247f1
YQ
7751{
7752 /* We can't get pending events in remote_notif_process for
7753 notification stop, and we have to do this in remote_wait_ns
7754 instead. If we fetch all queued events from stub, remote stub
7755 may exit and we have no chance to process them back in
7756 remote_wait_ns. */
6b8edb51 7757 remote_state *rs = remote->get_remote_state ();
92b98b37 7758 rs->mark_async_event_handler ();
722247f1
YQ
7759 return 0;
7760}
7761
32603266
TT
7762static notif_event_up
7763remote_notif_stop_alloc_reply ()
722247f1 7764{
32603266 7765 return notif_event_up (new struct stop_reply ());
722247f1
YQ
7766}
7767
7768/* A client of notification Stop. */
7769
42938c1a 7770const notif_client notif_client_stop =
722247f1
YQ
7771{
7772 "Stop",
7773 "vStopped",
7774 remote_notif_stop_parse,
7775 remote_notif_stop_ack,
7776 remote_notif_stop_can_get_pending_events,
7777 remote_notif_stop_alloc_reply,
f48ff2a7 7778 REMOTE_NOTIF_STOP,
722247f1
YQ
7779};
7780
53de5394
PA
7781/* If CONTEXT contains any fork/vfork/clone child threads that have
7782 not been reported yet, remove them from the CONTEXT list. If such
7783 a thread exists it is because we are stopped at a fork/vfork/clone
7784 catchpoint and have not yet called follow_fork/follow_clone, which
7785 will set up the host-side data structures for the new child. */
cbb8991c 7786
6b8edb51 7787void
53de5394 7788remote_target::remove_new_children (threads_listing_context *context)
cbb8991c 7789{
42938c1a 7790 const notif_client *notif = &notif_client_stop;
cbb8991c 7791
53de5394
PA
7792 /* For any threads stopped at a (v)fork/clone event, remove the
7793 corresponding child threads from the CONTEXT list. */
5b6d1e4f 7794 for (thread_info *thread : all_non_exited_threads (this))
cbb8991c 7795 {
53de5394 7796 const target_waitstatus *ws = thread_pending_child_status (thread);
28561a65
SM
7797
7798 if (ws == nullptr)
7799 continue;
cbb8991c 7800
28561a65 7801 context->remove_thread (ws->child_ptid ());
cbb8991c
DB
7802 }
7803
53de5394
PA
7804 /* Check for any pending (v)fork/clone events (not reported or
7805 processed yet) in process PID and remove those child threads from
7806 the CONTEXT list as well. */
cbb8991c 7807 remote_notif_get_pending_events (notif);
953edf2b 7808 for (auto &event : get_remote_state ()->stop_reply_queue)
53de5394 7809 if (is_new_child_status (event->ws.kind ()))
183be222 7810 context->remove_thread (event->ws.child_ptid ());
3890f02a
SM
7811 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7812 context->remove_thread (event->ptid);
85ad3aaf
PA
7813}
7814
2f63ec5c
AB
7815/* Check whether any event pending in the vStopped queue would prevent a
7816 global or process wildcard vCont action. Set *may_global_wildcard to
7817 false if we can't do a global wildcard (vCont;c), and clear the event
7818 inferior's may_wildcard_vcont flag if we can't do a process-wide
7819 wildcard resume (vCont;c:pPID.-1). */
85ad3aaf 7820
6b8edb51
PA
7821void
7822remote_target::check_pending_events_prevent_wildcard_vcont
2f63ec5c 7823 (bool *may_global_wildcard)
85ad3aaf 7824{
42938c1a 7825 const notif_client *notif = &notif_client_stop;
85ad3aaf
PA
7826
7827 remote_notif_get_pending_events (notif);
953edf2b
TT
7828 for (auto &event : get_remote_state ()->stop_reply_queue)
7829 {
183be222
SM
7830 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7831 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
953edf2b 7832 continue;
85ad3aaf 7833
183be222
SM
7834 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7835 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
2f63ec5c 7836 *may_global_wildcard = false;
722247f1 7837
953edf2b
TT
7838 /* This may be the first time we heard about this process.
7839 Regardless, we must not do a global wildcard resume, otherwise
7840 we'd resume this process too. */
2f63ec5c 7841 *may_global_wildcard = false;
323fd5b9
PA
7842 if (event->ptid != null_ptid)
7843 {
7844 inferior *inf = find_inferior_ptid (this, event->ptid);
7845 if (inf != NULL)
7846 get_remote_inferior (inf)->may_wildcard_vcont = false;
7847 }
722247f1 7848 }
722247f1
YQ
7849}
7850
f48ff2a7 7851/* Discard all pending stop replies of inferior INF. */
c906108c 7852
6b8edb51
PA
7853void
7854remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7855{
f48ff2a7
YQ
7856 struct remote_state *rs = get_remote_state ();
7857 struct remote_notif_state *rns = rs->notif_state;
7858
7859 /* This function can be notified when an inferior exists. When the
7860 target is not remote, the notification state is NULL. */
7861 if (rs->remote_desc == NULL)
7862 return;
7863
aed77b16
PA
7864 struct notif_event *notif_event
7865 = rns->pending_event[notif_client_stop.id].get ();
7866 auto *reply = static_cast<stop_reply *> (notif_event);
c906108c 7867
74531fed 7868 /* Discard the in-flight notification. */
e99b03dc 7869 if (reply != NULL && reply->ptid.pid () == inf->pid)
74531fed 7870 {
b0083dd7
PA
7871 /* Leave the notification pending, since the server expects that
7872 we acknowledge it with vStopped. But clear its contents, so
7873 that later on when we acknowledge it, we also discard it. */
df5ad102
SM
7874 remote_debug_printf
7875 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7876 reply->ptid.to_string().c_str(),
7877 reply->ws.to_string ().c_str ());
183be222 7878 reply->ws.set_ignore ();
74531fed 7879 }
c906108c 7880
74531fed
PA
7881 /* Discard the stop replies we have already pulled with
7882 vStopped. */
953edf2b
TT
7883 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7884 rs->stop_reply_queue.end (),
7885 [=] (const stop_reply_up &event)
7886 {
7887 return event->ptid.pid () == inf->pid;
7888 });
df5ad102
SM
7889 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7890 remote_debug_printf
7891 ("discarding queued stop reply: ptid: %s, ws: %s\n",
1720b64f
AB
7892 (*it)->ptid.to_string().c_str(),
7893 (*it)->ws.to_string ().c_str ());
953edf2b 7894 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
bcc75809
YQ
7895}
7896
7897/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7898
6b8edb51
PA
7899void
7900remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7901{
6b8edb51 7902 remote_state *rs = get_remote_state ();
f48ff2a7 7903
f48ff2a7
YQ
7904 /* Discard the stop replies we have already pulled with
7905 vStopped. */
953edf2b
TT
7906 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7907 rs->stop_reply_queue.end (),
7908 [=] (const stop_reply_up &event)
7909 {
7910 return event->rs == rs;
7911 });
7912 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
74531fed 7913}
43ff13b4 7914
722247f1
YQ
7915/* Remove the first reply in 'stop_reply_queue' which matches
7916 PTID. */
2e9f7625 7917
e2163381 7918stop_reply_up
6b8edb51 7919remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7920{
953edf2b 7921 remote_state *rs = get_remote_state ();
722247f1 7922
953edf2b
TT
7923 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7924 rs->stop_reply_queue.end (),
7925 [=] (const stop_reply_up &event)
7926 {
7927 return event->ptid.matches (ptid);
7928 });
e2163381
PA
7929 stop_reply_up result;
7930 if (iter != rs->stop_reply_queue.end ())
953edf2b 7931 {
e2163381 7932 result = std::move (*iter);
953edf2b
TT
7933 rs->stop_reply_queue.erase (iter);
7934 }
722247f1 7935
722247f1 7936 if (notif_debug)
6cb06a8c
TT
7937 gdb_printf (gdb_stdlog,
7938 "notif: discard queued event: 'Stop' in %s\n",
7939 ptid.to_string ().c_str ());
a744cf53 7940
953edf2b 7941 return result;
74531fed 7942}
75c99385 7943
74531fed
PA
7944/* Look for a queued stop reply belonging to PTID. If one is found,
7945 remove it from the queue, and return it. Returns NULL if none is
7946 found. If there are still queued events left to process, tell the
7947 event loop to get back to target_wait soon. */
e24a49d8 7948
e2163381 7949stop_reply_up
6b8edb51 7950remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7951{
953edf2b 7952 remote_state *rs = get_remote_state ();
e2163381 7953 stop_reply_up r = remote_notif_remove_queued_reply (ptid);
74531fed 7954
4f626cad 7955 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
6b8edb51 7956 {
6b8edb51 7957 /* There's still at least an event left. */
92b98b37 7958 rs->mark_async_event_handler ();
6b8edb51 7959 }
74531fed 7960
722247f1 7961 return r;
74531fed
PA
7962}
7963
7964/* Push a fully parsed stop reply in the stop reply queue. Since we
7965 know that we now have at least one queued event left to pass to the
7966 core side, tell the event loop to get back to target_wait soon. */
7967
6b8edb51 7968void
e2163381 7969remote_target::push_stop_reply (stop_reply_up new_event)
74531fed 7970{
6b8edb51 7971 remote_state *rs = get_remote_state ();
e2163381 7972 rs->stop_reply_queue.push_back (std::move (new_event));
74531fed 7973
722247f1 7974 if (notif_debug)
6cb06a8c
TT
7975 gdb_printf (gdb_stdlog,
7976 "notif: push 'Stop' %s to queue %d\n",
7977 new_event->ptid.to_string ().c_str (),
7978 int (rs->stop_reply_queue.size ()));
74531fed 7979
4f626cad
AB
7980 /* Mark the pending event queue only if async mode is currently enabled.
7981 If async mode is not currently enabled, then, if it later becomes
7982 enabled, and there are events in this queue, we will mark the event
7983 token at that point, see remote_target::async. */
7984 if (target_is_async_p ())
92b98b37 7985 rs->mark_async_event_handler ();
74531fed
PA
7986}
7987
7988/* Returns true if we have a stop reply for PTID. */
7989
6b8edb51
PA
7990int
7991remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7992{
6b8edb51 7993 remote_state *rs = get_remote_state ();
953edf2b
TT
7994 for (auto &event : rs->stop_reply_queue)
7995 if (ptid == event->ptid
183be222 7996 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
953edf2b
TT
7997 return 1;
7998 return 0;
74531fed
PA
7999}
8000
26d56a93
SL
8001/* Helper for remote_parse_stop_reply. Return nonzero if the substring
8002 starting with P and ending with PEND matches PREFIX. */
8003
8004static int
8005strprefix (const char *p, const char *pend, const char *prefix)
8006{
8007 for ( ; p < pend; p++, prefix++)
8008 if (*p != *prefix)
8009 return 0;
8010 return *prefix == '\0';
8011}
8012
74531fed
PA
8013/* Parse the stop reply in BUF. Either the function succeeds, and the
8014 result is stored in EVENT, or throws an error. */
8015
6b8edb51 8016void
bb277751 8017remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
74531fed 8018{
5cd63fda 8019 remote_arch_state *rsa = NULL;
74531fed 8020 ULONGEST addr;
256642e8 8021 const char *p;
94585166 8022 int skipregs = 0;
74531fed
PA
8023
8024 event->ptid = null_ptid;
bcc75809 8025 event->rs = get_remote_state ();
183be222 8026 event->ws.set_ignore ();
f7e6eed5 8027 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
32603266 8028 event->regcache.clear ();
dc146f7c 8029 event->core = -1;
74531fed
PA
8030
8031 switch (buf[0])
8032 {
8033 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
8034 /* Expedited reply, containing Signal, {regno, reg} repeat. */
8035 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
8036 ss = signal number
8037 n... = register number
8038 r... = register contents
8039 */
8040
8041 p = &buf[3]; /* after Txx */
8042 while (*p)
8043 {
256642e8 8044 const char *p1;
cea39f65 8045 int fieldsize;
43ff13b4 8046
1f10ba14
PA
8047 p1 = strchr (p, ':');
8048 if (p1 == NULL)
8049 error (_("Malformed packet(a) (missing colon): %s\n\
8050Packet: '%s'\n"),
8051 p, buf);
8052 if (p == p1)
8053 error (_("Malformed packet(a) (missing register number): %s\n\
8054Packet: '%s'\n"),
8055 p, buf);
3c3bea1c 8056
1f10ba14
PA
8057 /* Some "registers" are actually extended stop information.
8058 Note if you're adding a new entry here: GDB 7.9 and
8059 earlier assume that all register "numbers" that start
8060 with an hex digit are real register numbers. Make sure
8061 the server only sends such a packet if it knows the
8062 client understands it. */
c8e38a49 8063
26d56a93 8064 if (strprefix (p, p1, "thread"))
1f10ba14 8065 event->ptid = read_ptid (++p1, &p);
82075af2
JS
8066 else if (strprefix (p, p1, "syscall_entry"))
8067 {
8068 ULONGEST sysno;
8069
82075af2 8070 p = unpack_varlen_hex (++p1, &sysno);
183be222 8071 event->ws.set_syscall_entry ((int) sysno);
82075af2
JS
8072 }
8073 else if (strprefix (p, p1, "syscall_return"))
8074 {
8075 ULONGEST sysno;
8076
82075af2 8077 p = unpack_varlen_hex (++p1, &sysno);
183be222 8078 event->ws.set_syscall_return ((int) sysno);
82075af2 8079 }
26d56a93
SL
8080 else if (strprefix (p, p1, "watch")
8081 || strprefix (p, p1, "rwatch")
8082 || strprefix (p, p1, "awatch"))
cea39f65 8083 {
f7e6eed5 8084 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
8085 p = unpack_varlen_hex (++p1, &addr);
8086 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 8087 }
26d56a93 8088 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
8089 {
8090 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
8091
8092 /* Make sure the stub doesn't forget to indicate support
8093 with qSupported. */
ff52c073
CS
8094 if (m_features.packet_support (PACKET_swbreak_feature)
8095 != PACKET_ENABLE)
f7e6eed5
PA
8096 error (_("Unexpected swbreak stop reason"));
8097
8098 /* The value part is documented as "must be empty",
8099 though we ignore it, in case we ever decide to make
8100 use of it in a backward compatible way. */
8424cc97 8101 p = strchrnul (p1 + 1, ';');
f7e6eed5 8102 }
26d56a93 8103 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
8104 {
8105 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
8106
8107 /* Make sure the stub doesn't forget to indicate support
8108 with qSupported. */
ff52c073
CS
8109 if (m_features.packet_support (PACKET_hwbreak_feature)
8110 != PACKET_ENABLE)
f7e6eed5
PA
8111 error (_("Unexpected hwbreak stop reason"));
8112
8113 /* See above. */
8424cc97 8114 p = strchrnul (p1 + 1, ';');
f7e6eed5 8115 }
26d56a93 8116 else if (strprefix (p, p1, "library"))
cea39f65 8117 {
183be222 8118 event->ws.set_loaded ();
8424cc97 8119 p = strchrnul (p1 + 1, ';');
1f10ba14 8120 }
26d56a93 8121 else if (strprefix (p, p1, "replaylog"))
1f10ba14 8122 {
183be222 8123 event->ws.set_no_history ();
1f10ba14
PA
8124 /* p1 will indicate "begin" or "end", but it makes
8125 no difference for now, so ignore it. */
8424cc97 8126 p = strchrnul (p1 + 1, ';');
1f10ba14 8127 }
26d56a93 8128 else if (strprefix (p, p1, "core"))
1f10ba14
PA
8129 {
8130 ULONGEST c;
a744cf53 8131
1f10ba14
PA
8132 p = unpack_varlen_hex (++p1, &c);
8133 event->core = c;
cea39f65 8134 }
26d56a93 8135 else if (strprefix (p, p1, "fork"))
183be222 8136 event->ws.set_forked (read_ptid (++p1, &p));
26d56a93 8137 else if (strprefix (p, p1, "vfork"))
183be222 8138 event->ws.set_vforked (read_ptid (++p1, &p));
53de5394
PA
8139 else if (strprefix (p, p1, "clone"))
8140 event->ws.set_thread_cloned (read_ptid (++p1, &p));
26d56a93 8141 else if (strprefix (p, p1, "vforkdone"))
c269dbdb 8142 {
183be222 8143 event->ws.set_vfork_done ();
8424cc97 8144 p = strchrnul (p1 + 1, ';');
c269dbdb 8145 }
6ab24463 8146 else if (strprefix (p, p1, "exec"))
94585166
DB
8147 {
8148 ULONGEST ignored;
94585166
DB
8149 int pathlen;
8150
8151 /* Determine the length of the execd pathname. */
8152 p = unpack_varlen_hex (++p1, &ignored);
8153 pathlen = (p - p1) / 2;
8154
8155 /* Save the pathname for event reporting and for
8156 the next run command. */
183be222 8157 gdb::unique_xmalloc_ptr<char> pathname
c6321f19
TT
8158 ((char *) xmalloc (pathlen + 1));
8159 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
183be222 8160 pathname.get ()[pathlen] = '\0';
94585166
DB
8161
8162 /* This is freed during event handling. */
183be222 8163 event->ws.set_execd (std::move (pathname));
94585166
DB
8164
8165 /* Skip the registers included in this packet, since
8166 they may be for an architecture different from the
8167 one used by the original program. */
8168 skipregs = 1;
8169 }
65706a29
PA
8170 else if (strprefix (p, p1, "create"))
8171 {
183be222 8172 event->ws.set_thread_created ();
8424cc97 8173 p = strchrnul (p1 + 1, ';');
65706a29 8174 }
cea39f65
MS
8175 else
8176 {
1f10ba14 8177 ULONGEST pnum;
256642e8 8178 const char *p_temp;
1f10ba14 8179
94585166
DB
8180 if (skipregs)
8181 {
8424cc97 8182 p = strchrnul (p1 + 1, ';');
94585166
DB
8183 p++;
8184 continue;
8185 }
8186
1f10ba14
PA
8187 /* Maybe a real ``P'' register number. */
8188 p_temp = unpack_varlen_hex (p, &pnum);
8189 /* If the first invalid character is the colon, we got a
8190 register number. Otherwise, it's an unknown stop
8191 reason. */
8192 if (p_temp == p1)
8193 {
5cd63fda
PA
8194 /* If we haven't parsed the event's thread yet, find
8195 it now, in order to find the architecture of the
8196 reported expedited registers. */
8197 if (event->ptid == null_ptid)
8198 {
24ed6739
AB
8199 /* If there is no thread-id information then leave
8200 the event->ptid as null_ptid. Later in
8201 process_stop_reply we will pick a suitable
8202 thread. */
5cd63fda
PA
8203 const char *thr = strstr (p1 + 1, ";thread:");
8204 if (thr != NULL)
8205 event->ptid = read_ptid (thr + strlen (";thread:"),
8206 NULL);
5cd63fda
PA
8207 }
8208
8209 if (rsa == NULL)
8210 {
5b6d1e4f
PA
8211 inferior *inf
8212 = (event->ptid == null_ptid
8213 ? NULL
8214 : find_inferior_ptid (this, event->ptid));
5cd63fda
PA
8215 /* If this is the first time we learn anything
8216 about this process, skip the registers
8217 included in this packet, since we don't yet
8218 know which architecture to use to parse them.
8219 We'll determine the architecture later when
8220 we process the stop reply and retrieve the
8221 target description, via
8222 remote_notice_new_inferior ->
8223 post_create_inferior. */
8224 if (inf == NULL)
8225 {
8226 p = strchrnul (p1 + 1, ';');
8227 p++;
8228 continue;
8229 }
8230
27b1f19f 8231 event->arch = inf->arch ();
9d6eea31 8232 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
8233 }
8234
8235 packet_reg *reg
8236 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 8237 cached_reg_t cached_reg;
43ff13b4 8238
1f10ba14
PA
8239 if (reg == NULL)
8240 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 8241Packet: '%s'\n"),
1f10ba14 8242 hex_string (pnum), p, buf);
c8e38a49 8243
ad592596 8244 int reg_size = register_size (event->arch, reg->regnum);
1f10ba14 8245 cached_reg.num = reg->regnum;
ad592596 8246 cached_reg.data.resize (reg_size);
4100683b 8247
1f10ba14 8248 p = p1 + 1;
ad592596
TJB
8249 fieldsize = hex2bin (p, cached_reg.data.data (),
8250 cached_reg.data.size ());
1f10ba14 8251 p += 2 * fieldsize;
ad592596 8252 if (fieldsize < reg_size)
1f10ba14 8253 warning (_("Remote reply is too short: %s"), buf);
74531fed 8254
d5cebea1 8255 event->regcache.push_back (std::move (cached_reg));
1f10ba14
PA
8256 }
8257 else
8258 {
8259 /* Not a number. Silently skip unknown optional
8260 info. */
8424cc97 8261 p = strchrnul (p1 + 1, ';');
1f10ba14 8262 }
cea39f65 8263 }
c8e38a49 8264
cea39f65
MS
8265 if (*p != ';')
8266 error (_("Remote register badly formatted: %s\nhere: %s"),
8267 buf, p);
8268 ++p;
8269 }
5b5596ff 8270
183be222 8271 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
5b5596ff
PA
8272 break;
8273
d182e398 8274 [[fallthrough]];
c8e38a49 8275 case 'S': /* Old style status, just signal only. */
3a09da41
PA
8276 {
8277 int sig;
8278
3a09da41
PA
8279 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
8280 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
183be222 8281 event->ws.set_stopped ((enum gdb_signal) sig);
3a09da41 8282 else
183be222 8283 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
3a09da41 8284 }
c8e38a49 8285 break;
65706a29
PA
8286 case 'w': /* Thread exited. */
8287 {
65706a29
PA
8288 ULONGEST value;
8289
65706a29 8290 p = unpack_varlen_hex (&buf[1], &value);
183be222 8291 event->ws.set_thread_exited (value);
65706a29
PA
8292 if (*p != ';')
8293 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 8294 event->ptid = read_ptid (++p, NULL);
65706a29
PA
8295 break;
8296 }
c8e38a49
PA
8297 case 'W': /* Target exited. */
8298 case 'X':
8299 {
c8e38a49 8300 ULONGEST value;
82f73884 8301
c8e38a49
PA
8302 /* GDB used to accept only 2 hex chars here. Stubs should
8303 only send more if they detect GDB supports multi-process
8304 support. */
8305 p = unpack_varlen_hex (&buf[1], &value);
82f73884 8306
c8e38a49
PA
8307 if (buf[0] == 'W')
8308 {
8309 /* The remote process exited. */
183be222 8310 event->ws.set_exited (value);
c8e38a49
PA
8311 }
8312 else
8313 {
8314 /* The remote process exited with a signal. */
3a09da41 8315 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
183be222 8316 event->ws.set_signalled ((enum gdb_signal) value);
3a09da41 8317 else
183be222 8318 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
c8e38a49 8319 }
82f73884 8320
e7af6c70
TBA
8321 /* If no process is specified, return null_ptid, and let the
8322 caller figure out the right process to use. */
8323 int pid = 0;
c8e38a49
PA
8324 if (*p == '\0')
8325 ;
8326 else if (*p == ';')
8327 {
8328 p++;
8329
0b24eb2d 8330 if (*p == '\0')
82f73884 8331 ;
61012eef 8332 else if (startswith (p, "process:"))
82f73884 8333 {
c8e38a49 8334 ULONGEST upid;
a744cf53 8335
c8e38a49
PA
8336 p += sizeof ("process:") - 1;
8337 unpack_varlen_hex (p, &upid);
8338 pid = upid;
82f73884
PA
8339 }
8340 else
8341 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 8342 }
c8e38a49
PA
8343 else
8344 error (_("unknown stop reply packet: %s"), buf);
f2907e49 8345 event->ptid = ptid_t (pid);
74531fed
PA
8346 }
8347 break;
f2faf941 8348 case 'N':
183be222 8349 event->ws.set_no_resumed ();
f2faf941
PA
8350 event->ptid = minus_one_ptid;
8351 break;
74531fed 8352 }
74531fed
PA
8353}
8354
722247f1
YQ
8355/* When the stub wants to tell GDB about a new notification reply, it
8356 sends a notification (%Stop, for example). Those can come it at
8357 any time, hence, we have to make sure that any pending
8358 putpkt/getpkt sequence we're making is finished, before querying
8359 the stub for more events with the corresponding ack command
8360 (vStopped, for example). E.g., if we started a vStopped sequence
8361 immediately upon receiving the notification, something like this
8362 could happen:
74531fed
PA
8363
8364 1.1) --> Hg 1
8365 1.2) <-- OK
8366 1.3) --> g
8367 1.4) <-- %Stop
8368 1.5) --> vStopped
8369 1.6) <-- (registers reply to step #1.3)
8370
8371 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8372 query.
8373
796cb314 8374 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
8375 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8376 doing whatever we were doing:
8377
8378 2.1) --> Hg 1
8379 2.2) <-- OK
8380 2.3) --> g
8381 2.4) <-- %Stop
8382 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8383 2.5) <-- (registers reply to step #2.3)
8384
85102364 8385 Eventually after step #2.5, we return to the event loop, which
74531fed
PA
8386 notices there's an event on the
8387 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8388 associated callback --- the function below. At this point, we're
8389 always safe to start a vStopped sequence. :
8390
8391 2.6) --> vStopped
8392 2.7) <-- T05 thread:2
8393 2.8) --> vStopped
8394 2.9) --> OK
8395*/
8396
722247f1 8397void
42938c1a 8398remote_target::remote_notif_get_pending_events (const notif_client *nc)
74531fed
PA
8399{
8400 struct remote_state *rs = get_remote_state ();
74531fed 8401
f48ff2a7 8402 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 8403 {
722247f1 8404 if (notif_debug)
6cb06a8c
TT
8405 gdb_printf (gdb_stdlog,
8406 "notif: process: '%s' ack pending event\n",
8407 nc->name);
74531fed 8408
722247f1 8409 /* acknowledge */
8d64371b 8410 nc->ack (this, nc, rs->buf.data (),
e2163381 8411 std::move (rs->notif_state->pending_event[nc->id]));
74531fed
PA
8412
8413 while (1)
8414 {
aa7b36b8 8415 getpkt (&rs->buf);
8d64371b 8416 if (strcmp (rs->buf.data (), "OK") == 0)
74531fed
PA
8417 break;
8418 else
8d64371b 8419 remote_notif_ack (this, nc, rs->buf.data ());
74531fed
PA
8420 }
8421 }
722247f1
YQ
8422 else
8423 {
8424 if (notif_debug)
6cb06a8c
TT
8425 gdb_printf (gdb_stdlog,
8426 "notif: process: '%s' no pending reply\n",
8427 nc->name);
722247f1 8428 }
74531fed
PA
8429}
8430
6b8edb51
PA
8431/* Wrapper around remote_target::remote_notif_get_pending_events to
8432 avoid having to export the whole remote_target class. */
8433
8434void
42938c1a 8435remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
6b8edb51
PA
8436{
8437 remote->remote_notif_get_pending_events (nc);
8438}
8439
8f66807b
AB
8440/* Called from process_stop_reply when the stop packet we are responding
8441 to didn't include a process-id or thread-id. STATUS is the stop event
8442 we are responding to.
8443
8444 It is the task of this function to select a suitable thread (or process)
8445 and return its ptid, this is the thread (or process) we will assume the
8446 stop event came from.
8447
8448 In some cases there isn't really any choice about which thread (or
8449 process) is selected, a basic remote with a single process containing a
8450 single thread might choose not to send any process-id or thread-id in
8451 its stop packets, this function will select and return the one and only
8452 thread.
8453
8454 However, if a target supports multiple threads (or processes) and still
8455 doesn't include a thread-id (or process-id) in its stop packet then
8456 first, this is a badly behaving target, and second, we're going to have
8457 to select a thread (or process) at random and use that. This function
8458 will print a warning to the user if it detects that there is the
8459 possibility that GDB is guessing which thread (or process) to
8460 report.
8461
8462 Note that this is called before GDB fetches the updated thread list from the
8463 target. So it's possible for the stop reply to be ambiguous and for GDB to
8464 not realize it. For example, if there's initially one thread, the target
8465 spawns a second thread, and then sends a stop reply without an id that
8466 concerns the first thread. GDB will assume the stop reply is about the
8467 first thread - the only thread it knows about - without printing a warning.
8468 Anyway, if the remote meant for the stop reply to be about the second thread,
8469 then it would be really broken, because GDB doesn't know about that thread
8470 yet. */
74531fed 8471
6b8edb51 8472ptid_t
8f66807b 8473remote_target::select_thread_for_ambiguous_stop_reply
c272a98c 8474 (const target_waitstatus &status)
74531fed 8475{
4351271e
AB
8476 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8477
8f66807b
AB
8478 /* Some stop events apply to all threads in an inferior, while others
8479 only apply to a single thread. */
8480 bool process_wide_stop
c272a98c
SM
8481 = (status.kind () == TARGET_WAITKIND_EXITED
8482 || status.kind () == TARGET_WAITKIND_SIGNALLED);
74531fed 8483
4351271e
AB
8484 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8485
8f66807b
AB
8486 thread_info *first_resumed_thread = nullptr;
8487 bool ambiguous = false;
74531fed 8488
8f66807b
AB
8489 /* Consider all non-exited threads of the target, find the first resumed
8490 one. */
8491 for (thread_info *thr : all_non_exited_threads (this))
24ed6739 8492 {
8f66807b 8493 remote_thread_info *remote_thr = get_remote_thread_info (thr);
cada5fc9 8494
a6c11cbb 8495 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8f66807b 8496 continue;
24ed6739 8497
8f66807b
AB
8498 if (first_resumed_thread == nullptr)
8499 first_resumed_thread = thr;
8500 else if (!process_wide_stop
8501 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8502 ambiguous = true;
8503 }
8504
b622494e
AB
8505 gdb_assert (first_resumed_thread != nullptr);
8506
4351271e
AB
8507 remote_debug_printf ("first resumed thread is %s",
8508 pid_to_str (first_resumed_thread->ptid).c_str ());
8509 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8510
8f66807b
AB
8511 /* Warn if the remote target is sending ambiguous stop replies. */
8512 if (ambiguous)
8513 {
8514 static bool warned = false;
8515
8516 if (!warned)
8517 {
8518 /* If you are seeing this warning then the remote target has
8519 stopped without specifying a thread-id, but the target
8520 does have multiple threads (or inferiors), and so GDB is
8521 having to guess which thread stopped.
8522
8523 Examples of what might cause this are the target sending
8524 and 'S' stop packet, or a 'T' stop packet and not
8525 including a thread-id.
8526
8527 Additionally, the target might send a 'W' or 'X packet
8528 without including a process-id, when the target has
8529 multiple running inferiors. */
8530 if (process_wide_stop)
8531 warning (_("multi-inferior target stopped without "
8532 "sending a process-id, using first "
8533 "non-exited inferior"));
cada5fc9 8534 else
8f66807b
AB
8535 warning (_("multi-threaded target stopped without "
8536 "sending a thread-id, using first "
8537 "non-exited thread"));
8538 warned = true;
24ed6739 8539 }
24ed6739 8540 }
74531fed 8541
8f66807b
AB
8542 /* If this is a stop for all threads then don't use a particular threads
8543 ptid, instead create a new ptid where only the pid field is set. */
8544 if (process_wide_stop)
8545 return ptid_t (first_resumed_thread->ptid.pid ());
8546 else
8547 return first_resumed_thread->ptid;
8548}
8549
8550/* Called when it is decided that STOP_REPLY holds the info of the
8551 event that is to be returned to the core. This function always
8552 destroys STOP_REPLY. */
8553
8554ptid_t
e2163381 8555remote_target::process_stop_reply (stop_reply_up stop_reply,
8f66807b
AB
8556 struct target_waitstatus *status)
8557{
8558 *status = stop_reply->ws;
8559 ptid_t ptid = stop_reply->ptid;
94aedcf7
TJB
8560 struct remote_state *rs = get_remote_state ();
8561
8562 /* Forget about last reply's expedited registers. */
8563 rs->last_seen_expedited_registers.clear ();
8f66807b
AB
8564
8565 /* If no thread/process was reported by the stub then select a suitable
8566 thread/process. */
8567 if (ptid == null_ptid)
c272a98c 8568 ptid = select_thread_for_ambiguous_stop_reply (*status);
8f66807b
AB
8569 gdb_assert (ptid != null_ptid);
8570
183be222
SM
8571 if (status->kind () != TARGET_WAITKIND_EXITED
8572 && status->kind () != TARGET_WAITKIND_SIGNALLED
8573 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
74531fed 8574 {
74387712
SM
8575 remote_notice_new_inferior (ptid, false);
8576
5f3563ea 8577 /* Expedited registers. */
32603266 8578 if (!stop_reply->regcache.empty ())
5f3563ea 8579 {
00b0dc81
PA
8580 /* 'w' stop replies don't cary expedited registers (which
8581 wouldn't make any sense for a thread that is gone
8582 already). */
8583 gdb_assert (status->kind () != TARGET_WAITKIND_THREAD_EXITED);
8584
74387712
SM
8585 regcache *regcache
8586 = get_thread_arch_regcache (find_inferior_ptid (this, ptid), ptid,
8587 stop_reply->arch);
5f3563ea 8588
32603266 8589 for (cached_reg_t &reg : stop_reply->regcache)
94aedcf7 8590 {
ad592596 8591 regcache->raw_supply (reg.num, reg.data);
94aedcf7
TJB
8592 rs->last_seen_expedited_registers.insert (reg.num);
8593 }
5f3563ea 8594 }
74531fed 8595
5b6d1e4f 8596 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
799a2abe
PA
8597 remote_thr->core = stop_reply->core;
8598 remote_thr->stop_reason = stop_reply->stop_reason;
8599 remote_thr->watch_data_address = stop_reply->watch_data_address;
c9d22089
SM
8600
8601 if (target_is_non_stop_p ())
8602 {
8603 /* If the target works in non-stop mode, a stop-reply indicates that
8604 only this thread stopped. */
8605 remote_thr->set_not_resumed ();
8606 }
8607 else
8608 {
8609 /* If the target works in all-stop mode, a stop-reply indicates that
8610 all the target's threads stopped. */
8611 for (thread_info *tp : all_non_exited_threads (this))
8612 get_remote_thread_info (tp)->set_not_resumed ();
8613 }
74531fed
PA
8614 }
8615
74531fed
PA
8616 return ptid;
8617}
8618
8619/* The non-stop mode version of target_wait. */
8620
6b8edb51 8621ptid_t
b60cea74
TT
8622remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8623 target_wait_flags options)
74531fed
PA
8624{
8625 struct remote_state *rs = get_remote_state ();
74531fed 8626 int ret;
8756b726 8627 bool is_notif = false;
74531fed
PA
8628
8629 /* If in non-stop mode, get out of getpkt even if a
8630 notification is received. */
8631
a60f93c7 8632 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
74531fed
PA
8633 while (1)
8634 {
fee9eda9 8635 if (ret != -1 && !is_notif)
74531fed
PA
8636 switch (rs->buf[0])
8637 {
8638 case 'E': /* Error of some sort. */
8639 /* We're out of sync with the target now. Did it continue
8640 or not? We can't tell which thread it was in non-stop,
8641 so just ignore this. */
8d64371b 8642 warning (_("Remote failure reply: %s"), rs->buf.data ());
74531fed
PA
8643 break;
8644 case 'O': /* Console output. */
c6100129 8645 remote_console_output (&rs->buf[1], gdb_stdtarg);
74531fed
PA
8646 break;
8647 default:
8d64371b 8648 warning (_("Invalid remote reply: %s"), rs->buf.data ());
74531fed
PA
8649 break;
8650 }
8651
8652 /* Acknowledge a pending stop reply that may have arrived in the
8653 mean time. */
f48ff2a7 8654 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 8655 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
8656
8657 /* If indeed we noticed a stop reply, we're done. */
e2163381 8658 stop_reply_up stop_reply = queued_stop_reply (ptid);
74531fed 8659 if (stop_reply != NULL)
e2163381 8660 return process_stop_reply (std::move (stop_reply), status);
74531fed 8661
47608cb1 8662 /* Still no event. If we're just polling for an event, then
74531fed 8663 return to the event loop. */
47608cb1 8664 if (options & TARGET_WNOHANG)
74531fed 8665 {
183be222 8666 status->set_ignore ();
74531fed
PA
8667 return minus_one_ptid;
8668 }
8669
47608cb1 8670 /* Otherwise do a blocking wait. */
a60f93c7 8671 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
74531fed
PA
8672 }
8673}
8674
31ba933e
PA
8675/* Return the first resumed thread. */
8676
8677static ptid_t
5b6d1e4f 8678first_remote_resumed_thread (remote_target *target)
31ba933e 8679{
5b6d1e4f 8680 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
7846f3aa 8681 if (tp->resumed ())
31ba933e
PA
8682 return tp->ptid;
8683 return null_ptid;
8684}
8685
74531fed
PA
8686/* Wait until the remote machine stops, then return, storing status in
8687 STATUS just as `wait' would. */
8688
6b8edb51 8689ptid_t
b60cea74
TT
8690remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8691 target_wait_flags options)
74531fed
PA
8692{
8693 struct remote_state *rs = get_remote_state ();
74531fed 8694 ptid_t event_ptid = null_ptid;
cea39f65 8695 char *buf;
e2163381 8696 stop_reply_up stop_reply;
74531fed 8697
47608cb1
PA
8698 again:
8699
183be222 8700 status->set_ignore ();
74531fed
PA
8701
8702 stop_reply = queued_stop_reply (ptid);
8703 if (stop_reply != NULL)
4f626cad
AB
8704 {
8705 /* None of the paths that push a stop reply onto the queue should
8706 have set the waiting_for_stop_reply flag. */
8707 gdb_assert (!rs->waiting_for_stop_reply);
e2163381 8708 event_ptid = process_stop_reply (std::move (stop_reply), status);
4f626cad 8709 }
74531fed
PA
8710 else
8711 {
8756b726
TT
8712 bool forever = ((options & TARGET_WNOHANG) == 0
8713 && rs->wait_forever_enabled_p);
567420d1
PA
8714
8715 if (!rs->waiting_for_stop_reply)
8716 {
183be222 8717 status->set_no_resumed ();
567420d1
PA
8718 return minus_one_ptid;
8719 }
74531fed 8720
74531fed
PA
8721 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8722 _never_ wait for ever -> test on target_is_async_p().
8723 However, before we do that we need to ensure that the caller
8724 knows how to take the target into/out of async mode. */
8756b726 8725 bool is_notif;
a60f93c7 8726 int ret = getpkt (&rs->buf, forever, &is_notif);
722247f1
YQ
8727
8728 /* GDB gets a notification. Return to core as this event is
8729 not interesting. */
8730 if (ret != -1 && is_notif)
8731 return minus_one_ptid;
567420d1
PA
8732
8733 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8734 return minus_one_ptid;
74531fed 8735
4f626cad 8736 buf = rs->buf.data ();
74531fed 8737
4f626cad
AB
8738 /* Assume that the target has acknowledged Ctrl-C unless we receive
8739 an 'F' or 'O' packet. */
8740 if (buf[0] != 'F' && buf[0] != 'O')
8741 rs->ctrlc_pending_p = 0;
3a29589a 8742
4f626cad
AB
8743 switch (buf[0])
8744 {
8745 case 'E': /* Error of some sort. */
8746 /* We're out of sync with the target now. Did it continue or
8747 not? Not is more likely, so report a stop. */
8748 rs->waiting_for_stop_reply = 0;
29090fb6 8749
4f626cad
AB
8750 warning (_("Remote failure reply: %s"), buf);
8751 status->set_stopped (GDB_SIGNAL_0);
8752 break;
8753 case 'F': /* File-I/O request. */
8754 /* GDB may access the inferior memory while handling the File-I/O
8755 request, but we don't want GDB accessing memory while waiting
8756 for a stop reply. See the comments in putpkt_binary. Set
8757 waiting_for_stop_reply to 0 temporarily. */
8758 rs->waiting_for_stop_reply = 0;
8759 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8760 rs->ctrlc_pending_p = 0;
8761 /* GDB handled the File-I/O request, and the target is running
8762 again. Keep waiting for events. */
8763 rs->waiting_for_stop_reply = 1;
8764 break;
00b0dc81 8765 case 'N': case 'T': case 'S': case 'X': case 'W': case 'w':
4f626cad
AB
8766 {
8767 /* There is a stop reply to handle. */
8768 rs->waiting_for_stop_reply = 0;
29090fb6 8769
4f626cad 8770 stop_reply
e2163381
PA
8771 = as_stop_reply_up (remote_notif_parse (this,
8772 &notif_client_stop,
8773 rs->buf.data ()));
74531fed 8774
e2163381 8775 event_ptid = process_stop_reply (std::move (stop_reply), status);
4f626cad
AB
8776 break;
8777 }
8778 case 'O': /* Console output. */
c6100129 8779 remote_console_output (buf + 1, gdb_stdtarg);
4f626cad
AB
8780 break;
8781 case '\0':
8782 if (rs->last_sent_signal != GDB_SIGNAL_0)
8783 {
8784 /* Zero length reply means that we tried 'S' or 'C' and the
8785 remote system doesn't support it. */
8786 target_terminal::ours_for_output ();
6cb06a8c 8787 gdb_printf
4f626cad
AB
8788 ("Can't send signals to this remote system. %s not sent.\n",
8789 gdb_signal_to_name (rs->last_sent_signal));
8790 rs->last_sent_signal = GDB_SIGNAL_0;
8791 target_terminal::inferior ();
8792
8793 strcpy (buf, rs->last_sent_step ? "s" : "c");
8794 putpkt (buf);
8795 break;
8796 }
d182e398 8797 [[fallthrough]];
4f626cad
AB
8798 default:
8799 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 8800 break;
43ff13b4
JM
8801 }
8802 }
c8e38a49 8803
183be222 8804 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
f2faf941 8805 return minus_one_ptid;
183be222 8806 else if (status->kind () == TARGET_WAITKIND_IGNORE)
47608cb1
PA
8807 {
8808 /* Nothing interesting happened. If we're doing a non-blocking
8809 poll, we're done. Otherwise, go back to waiting. */
8810 if (options & TARGET_WNOHANG)
8811 return minus_one_ptid;
8812 else
8813 goto again;
8814 }
183be222
SM
8815 else if (status->kind () != TARGET_WAITKIND_EXITED
8816 && status->kind () != TARGET_WAITKIND_SIGNALLED)
82f73884 8817 {
d7e15655 8818 if (event_ptid != null_ptid)
47f8a51d 8819 record_currthread (rs, event_ptid);
82f73884 8820 else
5b6d1e4f 8821 event_ptid = first_remote_resumed_thread (this);
43ff13b4 8822 }
74531fed 8823 else
e7af6c70
TBA
8824 {
8825 /* A process exit. Invalidate our notion of current thread. */
8826 record_currthread (rs, minus_one_ptid);
8827 /* It's possible that the packet did not include a pid. */
8828 if (event_ptid == null_ptid)
5b6d1e4f 8829 event_ptid = first_remote_resumed_thread (this);
e7af6c70
TBA
8830 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8831 if (event_ptid == null_ptid)
8832 event_ptid = magic_null_ptid;
8833 }
79d7f229 8834
82f73884 8835 return event_ptid;
43ff13b4
JM
8836}
8837
74531fed
PA
8838/* Wait until the remote machine stops, then return, storing status in
8839 STATUS just as `wait' would. */
8840
f6ac5f3d 8841ptid_t
b60cea74
TT
8842remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8843 target_wait_flags options)
c8e38a49 8844{
2189c312
SM
8845 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8846
baa8575b
SM
8847 remote_state *rs = get_remote_state ();
8848
8849 /* Start by clearing the flag that asks for our wait method to be called,
8d34471f
AB
8850 we'll mark it again at the end if needed. If the target is not in
8851 async mode then the async token should not be marked. */
baa8575b 8852 if (target_is_async_p ())
92b98b37 8853 rs->clear_async_event_handler ();
8d34471f 8854 else
92b98b37 8855 gdb_assert (!rs->async_event_handler_marked ());
baa8575b 8856
c8e38a49
PA
8857 ptid_t event_ptid;
8858
6efcd9a8 8859 if (target_is_non_stop_p ())
6b8edb51 8860 event_ptid = wait_ns (ptid, status, options);
74531fed 8861 else
6b8edb51 8862 event_ptid = wait_as (ptid, status, options);
c8e38a49 8863
d9d41e78 8864 if (target_is_async_p ())
c8e38a49 8865 {
baa8575b
SM
8866 /* If there are events left in the queue, or unacknowledged
8867 notifications, then tell the event loop to call us again. */
8868 if (!rs->stop_reply_queue.empty ()
8869 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
92b98b37 8870 rs->mark_async_event_handler ();
c8e38a49 8871 }
c8e38a49
PA
8872
8873 return event_ptid;
8874}
8875
74ca34ce 8876/* Fetch a single register using a 'p' packet. */
c906108c 8877
6b8edb51
PA
8878int
8879remote_target::fetch_register_using_p (struct regcache *regcache,
8880 packet_reg *reg)
b96ec7ac 8881{
ac7936df 8882 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 8883 struct remote_state *rs = get_remote_state ();
2e9f7625 8884 char *buf, *p;
9890e433 8885 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
8886 int i;
8887
ff52c073 8888 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
8889 return 0;
8890
8891 if (reg->pnum == -1)
8892 return 0;
8893
8d64371b 8894 p = rs->buf.data ();
fcad0fa4 8895 *p++ = 'p';
74ca34ce 8896 p += hexnumstr (p, reg->pnum);
fcad0fa4 8897 *p++ = '\0';
1f4437a4 8898 putpkt (rs->buf);
aa7b36b8 8899 getpkt (&rs->buf);
3f9a994c 8900
8d64371b 8901 buf = rs->buf.data ();
2e9f7625 8902
94a94c90
AH
8903 packet_result result = m_features.packet_ok (rs->buf, PACKET_p);
8904 switch (result.status ())
74ca34ce
DJ
8905 {
8906 case PACKET_OK:
8907 break;
8908 case PACKET_UNKNOWN:
8909 return 0;
8910 case PACKET_ERROR:
27a9c0bf 8911 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7a78108a 8912 gdbarch_register_name (regcache->arch (), reg->regnum),
94a94c90 8913 result.err_msg ());
74ca34ce 8914 }
3f9a994c
JB
8915
8916 /* If this register is unfetchable, tell the regcache. */
8917 if (buf[0] == 'x')
8480adf2 8918 {
73e1c03f 8919 regcache->raw_supply (reg->regnum, NULL);
8480adf2 8920 return 1;
b96ec7ac 8921 }
b96ec7ac 8922
3f9a994c
JB
8923 /* Otherwise, parse and supply the value. */
8924 p = buf;
8925 i = 0;
8926 while (p[0] != 0)
8927 {
8928 if (p[1] == 0)
74ca34ce 8929 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
8930
8931 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8932 p += 2;
8933 }
73e1c03f 8934 regcache->raw_supply (reg->regnum, regp);
3f9a994c 8935 return 1;
b96ec7ac
AC
8936}
8937
74ca34ce
DJ
8938/* Fetch the registers included in the target's 'g' packet. */
8939
6b8edb51
PA
8940int
8941remote_target::send_g_packet ()
c906108c 8942{
d01949b6 8943 struct remote_state *rs = get_remote_state ();
cea39f65 8944 int buf_len;
c906108c 8945
8d64371b 8946 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
b75abf5b 8947 putpkt (rs->buf);
aa7b36b8 8948 getpkt (&rs->buf);
ddb3f3d8 8949 packet_result result = packet_check_result (rs->buf);
7e9d8a36 8950 if (result.status () == PACKET_ERROR)
b75abf5b 8951 error (_("Could not read registers; remote failure reply '%s'"),
7e9d8a36 8952 result.err_msg ());
c906108c 8953
29709017
DJ
8954 /* We can get out of synch in various cases. If the first character
8955 in the buffer is not a hex character, assume that has happened
8956 and try to fetch another packet to read. */
8957 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8958 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8959 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8960 && rs->buf[0] != 'x') /* New: unavailable register value. */
8961 {
2189c312 8962 remote_debug_printf ("Bad register packet; fetching a new packet");
aa7b36b8 8963 getpkt (&rs->buf);
29709017
DJ
8964 }
8965
8d64371b 8966 buf_len = strlen (rs->buf.data ());
74ca34ce
DJ
8967
8968 /* Sanity check the received packet. */
8969 if (buf_len % 2 != 0)
8d64371b 8970 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
29709017
DJ
8971
8972 return buf_len / 2;
8973}
8974
6b8edb51
PA
8975void
8976remote_target::process_g_packet (struct regcache *regcache)
29709017 8977{
ac7936df 8978 struct gdbarch *gdbarch = regcache->arch ();
29709017 8979 struct remote_state *rs = get_remote_state ();
9d6eea31 8980 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8981 int i, buf_len;
8982 char *p;
8983 char *regs;
8984
8d64371b 8985 buf_len = strlen (rs->buf.data ());
29709017
DJ
8986
8987 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8988 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827 8989 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8d64371b
TT
8990 "bytes): %s"),
8991 rsa->sizeof_g_packet, buf_len / 2,
8992 rs->buf.data ());
74ca34ce
DJ
8993
8994 /* Save the size of the packet sent to us by the target. It is used
8995 as a heuristic when determining the max size of packets that the
8996 target can safely receive. */
8997 if (rsa->actual_register_packet_size == 0)
8998 rsa->actual_register_packet_size = buf_len;
8999
9000 /* If this is smaller than we guessed the 'g' packet would be,
9001 update our records. A 'g' reply that doesn't include a register's
9002 value implies either that the register is not available, or that
9003 the 'p' packet must be used. */
9004 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 9005 {
9dc193c3 9006 long sizeof_g_packet = buf_len / 2;
74ca34ce 9007
4a22f64d 9008 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 9009 {
9dc193c3
LF
9010 long offset = rsa->regs[i].offset;
9011 long reg_size = register_size (gdbarch, i);
9012
74ca34ce
DJ
9013 if (rsa->regs[i].pnum == -1)
9014 continue;
9015
9dc193c3 9016 if (offset >= sizeof_g_packet)
480a1156 9017 rsa->regs[i].in_g_packet = false;
9dc193c3
LF
9018 else if (offset + reg_size > sizeof_g_packet)
9019 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 9020 else
480a1156 9021 rsa->regs[i].in_g_packet = true;
b96ec7ac 9022 }
9dc193c3
LF
9023
9024 /* Looks valid enough, we can assume this is the correct length
dda83cd7
SM
9025 for a 'g' packet. It's important not to adjust
9026 rsa->sizeof_g_packet if we have truncated registers otherwise
9027 this "if" won't be run the next time the method is called
9028 with a packet of the same size and one of the internal errors
9029 below will trigger instead. */
9dc193c3 9030 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 9031 }
b323314b 9032
224c3ddb 9033 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
9034
9035 /* Unimplemented registers read as all bits zero. */
ea9c271d 9036 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 9037
c906108c
SS
9038 /* Reply describes registers byte by byte, each byte encoded as two
9039 hex characters. Suck them all up, then supply them to the
973c5759 9040 register caching/storage mechanism. */
c906108c 9041
8d64371b 9042 p = rs->buf.data ();
ea9c271d 9043 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 9044 {
74ca34ce
DJ
9045 if (p[0] == 0 || p[1] == 0)
9046 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
f34652de 9047 internal_error (_("unexpected end of 'g' packet reply"));
74ca34ce 9048
c906108c 9049 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 9050 regs[i] = 0; /* 'x' */
c906108c
SS
9051 else
9052 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
9053 p += 2;
9054 }
9055
a744cf53
MS
9056 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9057 {
9058 struct packet_reg *r = &rsa->regs[i];
9dc193c3 9059 long reg_size = register_size (gdbarch, i);
a744cf53
MS
9060
9061 if (r->in_g_packet)
9062 {
8d64371b 9063 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
a744cf53 9064 /* This shouldn't happen - we adjusted in_g_packet above. */
f34652de 9065 internal_error (_("unexpected end of 'g' packet reply"));
a744cf53
MS
9066 else if (rs->buf[r->offset * 2] == 'x')
9067 {
8d64371b 9068 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
a744cf53
MS
9069 /* The register isn't available, mark it as such (at
9070 the same time setting the value to zero). */
73e1c03f 9071 regcache->raw_supply (r->regnum, NULL);
a744cf53
MS
9072 }
9073 else
73e1c03f 9074 regcache->raw_supply (r->regnum, regs + r->offset);
a744cf53
MS
9075 }
9076 }
c906108c
SS
9077}
9078
6b8edb51
PA
9079void
9080remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
9081{
9082 send_g_packet ();
56be3814 9083 process_g_packet (regcache);
29709017
DJ
9084}
9085
e6e4e701
PA
9086/* Make the remote selected traceframe match GDB's selected
9087 traceframe. */
9088
6b8edb51
PA
9089void
9090remote_target::set_remote_traceframe ()
e6e4e701
PA
9091{
9092 int newnum;
262e1174 9093 struct remote_state *rs = get_remote_state ();
e6e4e701 9094
262e1174 9095 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
9096 return;
9097
9098 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 9099 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
9100
9101 newnum = target_trace_find (tfind_number,
9102 get_traceframe_number (), 0, 0, NULL);
9103
9104 /* Should not happen. If it does, all bets are off. */
9105 if (newnum != get_traceframe_number ())
9106 warning (_("could not set remote traceframe"));
9107}
9108
f6ac5f3d
PA
9109void
9110remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 9111{
ac7936df 9112 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
9113 struct remote_state *rs = get_remote_state ();
9114 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
9115 int i;
9116
e6e4e701 9117 set_remote_traceframe ();
222312d3 9118 set_general_thread (regcache->ptid ());
74ca34ce
DJ
9119
9120 if (regnum >= 0)
9121 {
5cd63fda 9122 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 9123
74ca34ce
DJ
9124 gdb_assert (reg != NULL);
9125
9126 /* If this register might be in the 'g' packet, try that first -
9127 we are likely to read more than one register. If this is the
9128 first 'g' packet, we might be overly optimistic about its
9129 contents, so fall back to 'p'. */
9130 if (reg->in_g_packet)
9131 {
56be3814 9132 fetch_registers_using_g (regcache);
74ca34ce
DJ
9133 if (reg->in_g_packet)
9134 return;
9135 }
9136
56be3814 9137 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
9138 return;
9139
9140 /* This register is not available. */
73e1c03f 9141 regcache->raw_supply (reg->regnum, NULL);
74ca34ce
DJ
9142
9143 return;
9144 }
9145
56be3814 9146 fetch_registers_using_g (regcache);
74ca34ce 9147
5cd63fda 9148 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 9149 if (!rsa->regs[i].in_g_packet)
56be3814 9150 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
9151 {
9152 /* This register is not available. */
73e1c03f 9153 regcache->raw_supply (i, NULL);
74ca34ce
DJ
9154 }
9155}
9156
c906108c
SS
9157/* Prepare to store registers. Since we may send them all (using a
9158 'G' request), we have to read out the ones we don't want to change
9159 first. */
9160
f6ac5f3d
PA
9161void
9162remote_target::prepare_to_store (struct regcache *regcache)
c906108c 9163{
9d6eea31
PA
9164 struct remote_state *rs = get_remote_state ();
9165 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 9166 int i;
cf0e1e0d 9167
c906108c 9168 /* Make sure the entire registers array is valid. */
ff52c073 9169 switch (m_features.packet_support (PACKET_P))
5a2468f5
JM
9170 {
9171 case PACKET_DISABLE:
9172 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 9173 /* Make sure all the necessary registers are cached. */
ac7936df 9174 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 9175 if (rsa->regs[i].in_g_packet)
0b47d985 9176 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
9177 break;
9178 case PACKET_ENABLE:
9179 break;
9180 }
9181}
9182
ad10f812 9183/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 9184 packet was not recognized. */
5a2468f5 9185
6b8edb51
PA
9186int
9187remote_target::store_register_using_P (const struct regcache *regcache,
9188 packet_reg *reg)
5a2468f5 9189{
ac7936df 9190 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 9191 struct remote_state *rs = get_remote_state ();
5a2468f5 9192 /* Try storing a single register. */
8d64371b 9193 char *buf = rs->buf.data ();
9890e433 9194 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 9195 char *p;
5a2468f5 9196
ff52c073 9197 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
9198 return 0;
9199
9200 if (reg->pnum == -1)
9201 return 0;
9202
ea9c271d 9203 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 9204 p = buf + strlen (buf);
34a79281 9205 regcache->raw_collect (reg->regnum, regp);
4a22f64d 9206 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4 9207 putpkt (rs->buf);
aa7b36b8 9208 getpkt (&rs->buf);
5a2468f5 9209
94a94c90
AH
9210 packet_result result = m_features.packet_ok (rs->buf, PACKET_P);
9211 switch (result.status ())
74ca34ce
DJ
9212 {
9213 case PACKET_OK:
9214 return 1;
9215 case PACKET_ERROR:
27a9c0bf 9216 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
94a94c90 9217 gdbarch_register_name (gdbarch, reg->regnum), result.err_msg ());
74ca34ce
DJ
9218 case PACKET_UNKNOWN:
9219 return 0;
9220 default:
f34652de 9221 internal_error (_("Bad result from packet_ok"));
74ca34ce 9222 }
c906108c
SS
9223}
9224
23860348
MS
9225/* Store register REGNUM, or all registers if REGNUM == -1, from the
9226 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 9227
6b8edb51
PA
9228void
9229remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 9230{
d01949b6 9231 struct remote_state *rs = get_remote_state ();
9d6eea31 9232 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 9233 gdb_byte *regs;
c906108c
SS
9234 char *p;
9235
193cb69f
AC
9236 /* Extract all the registers in the regcache copying them into a
9237 local buffer. */
9238 {
b323314b 9239 int i;
a744cf53 9240
224c3ddb 9241 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 9242 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 9243 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 9244 {
ea9c271d 9245 struct packet_reg *r = &rsa->regs[i];
a744cf53 9246
b323314b 9247 if (r->in_g_packet)
34a79281 9248 regcache->raw_collect (r->regnum, regs + r->offset);
193cb69f
AC
9249 }
9250 }
c906108c
SS
9251
9252 /* Command describes registers byte by byte,
9253 each byte encoded as two hex characters. */
8d64371b 9254 p = rs->buf.data ();
193cb69f 9255 *p++ = 'G';
74ca34ce 9256 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4 9257 putpkt (rs->buf);
aa7b36b8 9258 getpkt (&rs->buf);
ddb3f3d8 9259 packet_result pkt_status = packet_check_result (rs->buf);
7e9d8a36 9260 if (pkt_status.status () == PACKET_ERROR)
7a78108a 9261 error (_("Could not write registers; remote failure reply '%s'"),
7e9d8a36 9262 pkt_status.err_msg ());
c906108c 9263}
74ca34ce
DJ
9264
9265/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9266 of the register cache buffer. FIXME: ignores errors. */
9267
f6ac5f3d
PA
9268void
9269remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 9270{
5cd63fda 9271 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
9272 struct remote_state *rs = get_remote_state ();
9273 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
9274 int i;
9275
e6e4e701 9276 set_remote_traceframe ();
222312d3 9277 set_general_thread (regcache->ptid ());
74ca34ce
DJ
9278
9279 if (regnum >= 0)
9280 {
5cd63fda 9281 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 9282
74ca34ce
DJ
9283 gdb_assert (reg != NULL);
9284
9285 /* Always prefer to store registers using the 'P' packet if
9286 possible; we often change only a small number of registers.
9287 Sometimes we change a larger number; we'd need help from a
9288 higher layer to know to use 'G'. */
56be3814 9289 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
9290 return;
9291
9292 /* For now, don't complain if we have no way to write the
9293 register. GDB loses track of unavailable registers too
9294 easily. Some day, this may be an error. We don't have
0df8b418 9295 any way to read the register, either... */
74ca34ce
DJ
9296 if (!reg->in_g_packet)
9297 return;
9298
56be3814 9299 store_registers_using_G (regcache);
74ca34ce
DJ
9300 return;
9301 }
9302
56be3814 9303 store_registers_using_G (regcache);
74ca34ce 9304
5cd63fda 9305 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 9306 if (!rsa->regs[i].in_g_packet)
56be3814 9307 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
9308 /* See above for why we do not issue an error here. */
9309 continue;
9310}
c906108c
SS
9311\f
9312
9313/* Return the number of hex digits in num. */
9314
9315static int
fba45db2 9316hexnumlen (ULONGEST num)
c906108c
SS
9317{
9318 int i;
9319
9320 for (i = 0; num != 0; i++)
9321 num >>= 4;
9322
325fac50 9323 return std::max (i, 1);
c906108c
SS
9324}
9325
2df3850c 9326/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
9327
9328static int
fba45db2 9329hexnumstr (char *buf, ULONGEST num)
c906108c 9330{
c906108c 9331 int len = hexnumlen (num);
a744cf53 9332
2df3850c
JM
9333 return hexnumnstr (buf, num, len);
9334}
9335
c906108c 9336
2df3850c 9337/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 9338
2df3850c 9339static int
fba45db2 9340hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
9341{
9342 int i;
9343
9344 buf[width] = '\0';
9345
9346 for (i = width - 1; i >= 0; i--)
c906108c 9347 {
c5aa993b 9348 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
9349 num >>= 4;
9350 }
9351
2df3850c 9352 return width;
c906108c
SS
9353}
9354
23860348 9355/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
9356
9357static CORE_ADDR
fba45db2 9358remote_address_masked (CORE_ADDR addr)
c906108c 9359{
883b9c6c 9360 unsigned int address_size = remote_address_size;
a744cf53 9361
911c95a5
UW
9362 /* If "remoteaddresssize" was not set, default to target address size. */
9363 if (!address_size)
99d9c3b9 9364 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
911c95a5
UW
9365
9366 if (address_size > 0
9367 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
9368 {
9369 /* Only create a mask when that mask can safely be constructed
dda83cd7 9370 in a ULONGEST variable. */
c906108c 9371 ULONGEST mask = 1;
a744cf53 9372
911c95a5 9373 mask = (mask << address_size) - 1;
c906108c
SS
9374 addr &= mask;
9375 }
9376 return addr;
9377}
9378
9379/* Determine whether the remote target supports binary downloading.
9380 This is accomplished by sending a no-op memory write of zero length
9381 to the target at the specified address. It does not suffice to send
23860348
MS
9382 the whole packet, since many stubs strip the eighth bit and
9383 subsequently compute a wrong checksum, which causes real havoc with
9384 remote_write_bytes.
7a292a7a 9385
96baa820 9386 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 9387 clean. In cases like this, the user should clear "remote
23860348 9388 X-packet". */
96baa820 9389
6b8edb51
PA
9390void
9391remote_target::check_binary_download (CORE_ADDR addr)
c906108c 9392{
d01949b6 9393 struct remote_state *rs = get_remote_state ();
24b06219 9394
ff52c073 9395 switch (m_features.packet_support (PACKET_X))
c906108c 9396 {
96baa820
JM
9397 case PACKET_DISABLE:
9398 break;
9399 case PACKET_ENABLE:
9400 break;
9401 case PACKET_SUPPORT_UNKNOWN:
9402 {
96baa820 9403 char *p;
802188a7 9404
8d64371b 9405 p = rs->buf.data ();
96baa820
JM
9406 *p++ = 'X';
9407 p += hexnumstr (p, (ULONGEST) addr);
9408 *p++ = ',';
9409 p += hexnumstr (p, (ULONGEST) 0);
9410 *p++ = ':';
9411 *p = '\0';
802188a7 9412
8d64371b 9413 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
aa7b36b8 9414 getpkt (&rs->buf);
c906108c 9415
2e9f7625 9416 if (rs->buf[0] == '\0')
96baa820 9417 {
2189c312 9418 remote_debug_printf ("binary downloading NOT supported by target");
ff52c073 9419 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
9420 }
9421 else
9422 {
2189c312 9423 remote_debug_printf ("binary downloading supported by target");
ff52c073 9424 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
9425 }
9426 break;
9427 }
c906108c
SS
9428 }
9429}
9430
124e13d9
SM
9431/* Helper function to resize the payload in order to try to get a good
9432 alignment. We try to write an amount of data such that the next write will
9433 start on an address aligned on REMOTE_ALIGN_WRITES. */
9434
9435static int
9436align_for_efficient_write (int todo, CORE_ADDR memaddr)
9437{
9438 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9439}
9440
c906108c
SS
9441/* Write memory data directly to the remote machine.
9442 This does not inform the data cache; the data cache uses this.
a76d924d 9443 HEADER is the starting part of the packet.
c906108c
SS
9444 MEMADDR is the address in the remote memory space.
9445 MYADDR is the address of the buffer in our space.
124e13d9
SM
9446 LEN_UNITS is the number of addressable units to write.
9447 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
9448 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9449 should send data as binary ('X'), or hex-encoded ('M').
9450
9451 The function creates packet of the form
9452 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9453
124e13d9 9454 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
9455
9456 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9457 are omitted.
9458
9b409511 9459 Return the transferred status, error or OK (an
124e13d9
SM
9460 'enum target_xfer_status' value). Save the number of addressable units
9461 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9462
9463 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9464 exchange between gdb and the stub could look like (?? in place of the
9465 checksum):
9466
9467 -> $m1000,4#??
9468 <- aaaabbbbccccdddd
9469
9470 -> $M1000,3:eeeeffffeeee#??
9471 <- OK
9472
9473 -> $m1000,4#??
9474 <- eeeeffffeeeedddd */
c906108c 9475
6b8edb51
PA
9476target_xfer_status
9477remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9478 const gdb_byte *myaddr,
9479 ULONGEST len_units,
9480 int unit_size,
9481 ULONGEST *xfered_len_units,
9482 char packet_format, int use_length)
c906108c 9483{
6d820c5c 9484 struct remote_state *rs = get_remote_state ();
cfd77fa1 9485 char *p;
a76d924d
DJ
9486 char *plen = NULL;
9487 int plenlen = 0;
124e13d9
SM
9488 int todo_units;
9489 int units_written;
9490 int payload_capacity_bytes;
9491 int payload_length_bytes;
a76d924d
DJ
9492
9493 if (packet_format != 'X' && packet_format != 'M')
f34652de 9494 internal_error (_("remote_write_bytes_aux: bad packet format"));
c906108c 9495
124e13d9 9496 if (len_units == 0)
9b409511 9497 return TARGET_XFER_EOF;
b2182ed2 9498
124e13d9 9499 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 9500
6d820c5c
DJ
9501 /* The packet buffer will be large enough for the payload;
9502 get_memory_packet_size ensures this. */
a76d924d 9503 rs->buf[0] = '\0';
c906108c 9504
a257b5bb 9505 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
9506 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9507
124e13d9 9508 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 9509 if (!use_length)
0df8b418 9510 /* The comma won't be used. */
124e13d9
SM
9511 payload_capacity_bytes += 1;
9512 payload_capacity_bytes -= strlen (header);
9513 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 9514
a76d924d 9515 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 9516
8d64371b
TT
9517 strcat (rs->buf.data (), header);
9518 p = rs->buf.data () + strlen (header);
a76d924d 9519
3be7119d 9520 /* Compute a best guess of the number of bytes actually transferred. */
a76d924d 9521 if (packet_format == 'X')
c906108c 9522 {
23860348 9523 /* Best guess at number of bytes that will fit. */
325fac50
PA
9524 todo_units = std::min (len_units,
9525 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 9526 if (use_length)
124e13d9 9527 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 9528 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
9529 }
9530 else
9531 {
124e13d9 9532 /* Number of bytes that will fit. */
325fac50
PA
9533 todo_units
9534 = std::min (len_units,
9535 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 9536 if (use_length)
124e13d9 9537 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
9538 todo_units = std::min (todo_units,
9539 (payload_capacity_bytes / unit_size) / 2);
917317f4 9540 }
a76d924d 9541
124e13d9 9542 if (todo_units <= 0)
f34652de 9543 internal_error (_("minimum packet size too small to write data"));
802188a7 9544
6765f3e5
DJ
9545 /* If we already need another packet, then try to align the end
9546 of this packet to a useful boundary. */
124e13d9
SM
9547 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9548 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 9549
a257b5bb 9550 /* Append "<memaddr>". */
917317f4
JM
9551 memaddr = remote_address_masked (memaddr);
9552 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 9553
a76d924d
DJ
9554 if (use_length)
9555 {
9556 /* Append ",". */
9557 *p++ = ',';
802188a7 9558
124e13d9 9559 /* Append the length and retain its location and size. It may need to be
dda83cd7 9560 adjusted once the packet body has been created. */
a76d924d 9561 plen = p;
124e13d9 9562 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
9563 p += plenlen;
9564 }
a257b5bb
AC
9565
9566 /* Append ":". */
917317f4
JM
9567 *p++ = ':';
9568 *p = '\0';
802188a7 9569
a257b5bb 9570 /* Append the packet body. */
a76d924d 9571 if (packet_format == 'X')
917317f4 9572 {
917317f4
JM
9573 /* Binary mode. Send target system values byte by byte, in
9574 increasing byte addresses. Only escape certain critical
9575 characters. */
124e13d9
SM
9576 payload_length_bytes =
9577 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9578 &units_written, payload_capacity_bytes);
6765f3e5 9579
124e13d9 9580 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
9581 a second try to keep the end of the packet aligned. Don't do
9582 this if the packet is tiny. */
124e13d9 9583 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 9584 {
124e13d9
SM
9585 int new_todo_units;
9586
9587 new_todo_units = align_for_efficient_write (units_written, memaddr);
9588
9589 if (new_todo_units != units_written)
9590 payload_length_bytes =
9591 remote_escape_output (myaddr, new_todo_units, unit_size,
9592 (gdb_byte *) p, &units_written,
9593 payload_capacity_bytes);
6765f3e5
DJ
9594 }
9595
124e13d9
SM
9596 p += payload_length_bytes;
9597 if (use_length && units_written < todo_units)
c906108c 9598 {
802188a7 9599 /* Escape chars have filled up the buffer prematurely,
124e13d9 9600 and we have actually sent fewer units than planned.
917317f4
JM
9601 Fix-up the length field of the packet. Use the same
9602 number of characters as before. */
124e13d9
SM
9603 plen += hexnumnstr (plen, (ULONGEST) units_written,
9604 plenlen);
917317f4 9605 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 9606 }
a76d924d
DJ
9607 }
9608 else
9609 {
917317f4
JM
9610 /* Normal mode: Send target system values byte by byte, in
9611 increasing byte addresses. Each byte is encoded as a two hex
9612 value. */
124e13d9
SM
9613 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9614 units_written = todo_units;
c906108c 9615 }
802188a7 9616
8d64371b 9617 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
aa7b36b8 9618 getpkt (&rs->buf);
802188a7 9619
2e9f7625 9620 if (rs->buf[0] == 'E')
00d84524 9621 return TARGET_XFER_E_IO;
802188a7 9622
124e13d9
SM
9623 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9624 send fewer units than we'd planned. */
9625 *xfered_len_units = (ULONGEST) units_written;
92ffd475 9626 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
9627}
9628
a76d924d
DJ
9629/* Write memory data directly to the remote machine.
9630 This does not inform the data cache; the data cache uses this.
9631 MEMADDR is the address in the remote memory space.
9632 MYADDR is the address of the buffer in our space.
9633 LEN is the number of bytes.
9634
9b409511
YQ
9635 Return the transferred status, error or OK (an
9636 'enum target_xfer_status' value). Save the number of bytes
9637 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 9638
6b8edb51
PA
9639target_xfer_status
9640remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9641 ULONGEST len, int unit_size,
9642 ULONGEST *xfered_len)
a76d924d 9643{
a121b7c1 9644 const char *packet_format = NULL;
a76d924d
DJ
9645
9646 /* Check whether the target supports binary download. */
9647 check_binary_download (memaddr);
9648
ff52c073 9649 switch (m_features.packet_support (PACKET_X))
a76d924d
DJ
9650 {
9651 case PACKET_ENABLE:
9652 packet_format = "X";
9653 break;
9654 case PACKET_DISABLE:
9655 packet_format = "M";
9656 break;
9657 case PACKET_SUPPORT_UNKNOWN:
f34652de 9658 internal_error (_("remote_write_bytes: bad internal state"));
a76d924d 9659 default:
f34652de 9660 internal_error (_("bad switch"));
a76d924d
DJ
9661 }
9662
9663 return remote_write_bytes_aux (packet_format,
124e13d9 9664 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 9665 packet_format[0], 1);
a76d924d
DJ
9666}
9667
9217e74e
YQ
9668/* Read memory data directly from the remote machine.
9669 This does not use the data cache; the data cache uses this.
9670 MEMADDR is the address in the remote memory space.
9671 MYADDR is the address of the buffer in our space.
124e13d9
SM
9672 LEN_UNITS is the number of addressable memory units to read..
9673 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
9674
9675 Return the transferred status, error or OK (an
9676 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
9677 transferred in *XFERED_LEN_UNITS.
9678
9679 See the comment of remote_write_bytes_aux for an example of
9680 memory read/write exchange between gdb and the stub. */
9217e74e 9681
6b8edb51
PA
9682target_xfer_status
9683remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9684 ULONGEST len_units,
9685 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
9686{
9687 struct remote_state *rs = get_remote_state ();
124e13d9 9688 int buf_size_bytes; /* Max size of packet output buffer. */
124e13d9
SM
9689 int todo_units;
9690 int decoded_bytes;
9217e74e 9691
124e13d9 9692 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
9693 /* The packet buffer will be large enough for the payload;
9694 get_memory_packet_size ensures this. */
9695
124e13d9 9696 /* Number of units that will fit. */
325fac50
PA
9697 todo_units = std::min (len_units,
9698 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e 9699
9217e74e 9700 memaddr = remote_address_masked (memaddr);
e16e6389
TBA
9701
9702 /* Construct "m/x"<memaddr>","<len>". */
9703 auto send_request = [this, rs, memaddr, todo_units] (char format) -> void
9704 {
9705 char *buffer = rs->buf.data ();
9706 *buffer++ = format;
9707 buffer += hexnumstr (buffer, (ULONGEST) memaddr);
9708 *buffer++ = ',';
9709 buffer += hexnumstr (buffer, (ULONGEST) todo_units);
9710 *buffer = '\0';
9711 putpkt (rs->buf);
9712 };
9713
9714 /* Determine which packet format to use. The target's support for
9715 'x' may be unknown. We just try. If it doesn't work, we try
9716 again using 'm'. */
9717 char packet_format;
9718 if (m_features.packet_support (PACKET_x) == PACKET_DISABLE)
9719 packet_format = 'm';
9720 else
9721 packet_format = 'x';
9722
9723 send_request (packet_format);
9724 int packet_len = getpkt (&rs->buf);
9725 if (packet_len < 0)
9726 return TARGET_XFER_E_IO;
9727
9728 if (m_features.packet_support (PACKET_x) == PACKET_SUPPORT_UNKNOWN)
9729 {
9730 if (rs->buf[0] == '\0')
9731 {
9732 remote_debug_printf ("binary uploading NOT supported by target");
9733 m_features.m_protocol_packets[PACKET_x].support = PACKET_DISABLE;
9734
9735 /* Try again using 'm'. */
9736 packet_format = 'm';
9737 send_request (packet_format);
9738 packet_len = getpkt (&rs->buf);
9739 if (packet_len < 0)
9740 return TARGET_XFER_E_IO;
9741 }
9742 else
9743 {
9744 remote_debug_printf ("binary uploading supported by target");
9745 m_features.m_protocol_packets[PACKET_x].support = PACKET_ENABLE;
9746 }
9747 }
9748
ddb3f3d8 9749 packet_result result = packet_check_result (rs->buf);
36232719 9750 if (result.status () == PACKET_ERROR)
9217e74e 9751 return TARGET_XFER_E_IO;
e16e6389
TBA
9752
9753 char *p = rs->buf.data ();
9754 if (packet_format == 'x')
9755 {
9756 if (*p != 'b')
9757 return TARGET_XFER_E_IO;
9758
9759 /* Adjust for 'b'. */
9760 p++;
9761 packet_len--;
9762 decoded_bytes = remote_unescape_input ((const gdb_byte *) p,
9763 packet_len, myaddr,
9764 todo_units * unit_size);
9765 }
9766 else
9767 {
9768 /* Reply describes memory byte by byte, each byte encoded as two hex
9769 characters. */
9770 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9771 }
9772
9217e74e 9773 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 9774 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 9775 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
9776}
9777
b55fbac4
YQ
9778/* Using the set of read-only target sections of remote, read live
9779 read-only memory.
8acf9577
YQ
9780
9781 For interface/parameters/return description see target.h,
9782 to_xfer_partial. */
9783
6b8edb51
PA
9784target_xfer_status
9785remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9786 ULONGEST memaddr,
9787 ULONGEST len,
9788 int unit_size,
9789 ULONGEST *xfered_len)
8acf9577 9790{
19cf757a 9791 const struct target_section *secp;
8acf9577 9792
6b8edb51 9793 secp = target_section_by_addr (this, memaddr);
8acf9577 9794 if (secp != NULL
fd361982 9795 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
8acf9577 9796 {
8acf9577
YQ
9797 ULONGEST memend = memaddr + len;
9798
25b5a04e
SM
9799 const std::vector<target_section> *table
9800 = target_get_section_table (this);
19cf757a 9801 for (const target_section &p : *table)
8acf9577 9802 {
bb2a6777 9803 if (memaddr >= p.addr)
8acf9577 9804 {
bb2a6777 9805 if (memend <= p.endaddr)
8acf9577
YQ
9806 {
9807 /* Entire transfer is within this section. */
124e13d9 9808 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9809 xfered_len);
8acf9577 9810 }
bb2a6777 9811 else if (memaddr >= p.endaddr)
8acf9577
YQ
9812 {
9813 /* This section ends before the transfer starts. */
9814 continue;
9815 }
9816 else
9817 {
9818 /* This section overlaps the transfer. Just do half. */
bb2a6777 9819 len = p.endaddr - memaddr;
124e13d9 9820 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9821 xfered_len);
8acf9577
YQ
9822 }
9823 }
9824 }
9825 }
9826
9827 return TARGET_XFER_EOF;
9828}
9829
9217e74e
YQ
9830/* Similar to remote_read_bytes_1, but it reads from the remote stub
9831 first if the requested memory is unavailable in traceframe.
9832 Otherwise, fall back to remote_read_bytes_1. */
c906108c 9833
6b8edb51
PA
9834target_xfer_status
9835remote_target::remote_read_bytes (CORE_ADDR memaddr,
9836 gdb_byte *myaddr, ULONGEST len, int unit_size,
9837 ULONGEST *xfered_len)
c906108c 9838{
6b6aa828 9839 if (len == 0)
96c4f946 9840 return TARGET_XFER_EOF;
b2182ed2 9841
8acf9577
YQ
9842 if (get_traceframe_number () != -1)
9843 {
a79b1bc6 9844 std::vector<mem_range> available;
8acf9577
YQ
9845
9846 /* If we fail to get the set of available memory, then the
9847 target does not support querying traceframe info, and so we
9848 attempt reading from the traceframe anyway (assuming the
9849 target implements the old QTro packet then). */
9850 if (traceframe_available_memory (&available, memaddr, len))
9851 {
a79b1bc6 9852 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
9853 {
9854 enum target_xfer_status res;
9855
9856 /* Don't read into the traceframe's available
9857 memory. */
a79b1bc6 9858 if (!available.empty ())
8acf9577
YQ
9859 {
9860 LONGEST oldlen = len;
9861
a79b1bc6 9862 len = available[0].start - memaddr;
8acf9577
YQ
9863 gdb_assert (len <= oldlen);
9864 }
9865
8acf9577 9866 /* This goes through the topmost target again. */
6b8edb51 9867 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 9868 len, unit_size, xfered_len);
8acf9577
YQ
9869 if (res == TARGET_XFER_OK)
9870 return TARGET_XFER_OK;
9871 else
9872 {
9873 /* No use trying further, we know some memory starting
9874 at MEMADDR isn't available. */
9875 *xfered_len = len;
92ffd475
PC
9876 return (*xfered_len != 0) ?
9877 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
9878 }
9879 }
9880
9881 /* Don't try to read more than how much is available, in
9882 case the target implements the deprecated QTro packet to
9883 cater for older GDBs (the target's knowledge of read-only
9884 sections may be outdated by now). */
a79b1bc6 9885 len = available[0].length;
8acf9577
YQ
9886 }
9887 }
9888
124e13d9 9889 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 9890}
74531fed 9891
c906108c 9892\f
c906108c 9893
a76d924d
DJ
9894/* Sends a packet with content determined by the printf format string
9895 FORMAT and the remaining arguments, then gets the reply. Returns
9896 whether the packet was a success, a failure, or unknown. */
9897
7e9d8a36 9898packet_status
6b8edb51 9899remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
9900{
9901 struct remote_state *rs = get_remote_state ();
9902 int max_size = get_remote_packet_size ();
a76d924d 9903 va_list ap;
a744cf53 9904
a76d924d
DJ
9905 va_start (ap, format);
9906
9907 rs->buf[0] = '\0';
8d64371b 9908 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
33b031ce
GB
9909
9910 va_end (ap);
9911
9912 if (size >= max_size)
f34652de 9913 internal_error (_("Too long remote packet."));
a76d924d
DJ
9914
9915 if (putpkt (rs->buf) < 0)
9916 error (_("Communication problem with target."));
9917
9918 rs->buf[0] = '\0';
aa7b36b8 9919 getpkt (&rs->buf);
a76d924d 9920
ddb3f3d8 9921 return packet_check_result (rs->buf).status ();
a76d924d
DJ
9922}
9923
a76d924d
DJ
9924/* Flash writing can take quite some time. We'll set
9925 effectively infinite timeout for flash operations.
9926 In future, we'll need to decide on a better approach. */
9927static const int remote_flash_timeout = 1000;
9928
f6ac5f3d
PA
9929void
9930remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 9931{
99d9c3b9 9932 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
7e9d8a36 9933 enum packet_status ret;
2ec845e7
TT
9934 scoped_restore restore_timeout
9935 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
9936
9937 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 9938 phex (address, addr_size),
a76d924d
DJ
9939 phex (length, 4));
9940 switch (ret)
9941 {
9942 case PACKET_UNKNOWN:
9943 error (_("Remote target does not support flash erase"));
9944 case PACKET_ERROR:
9945 error (_("Error erasing flash with vFlashErase packet"));
9946 default:
9947 break;
9948 }
a76d924d
DJ
9949}
9950
6b8edb51
PA
9951target_xfer_status
9952remote_target::remote_flash_write (ULONGEST address,
9953 ULONGEST length, ULONGEST *xfered_len,
9954 const gdb_byte *data)
a76d924d 9955{
2ec845e7
TT
9956 scoped_restore restore_timeout
9957 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9958 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9959 xfered_len,'X', 0);
a76d924d
DJ
9960}
9961
f6ac5f3d
PA
9962void
9963remote_target::flash_done ()
a76d924d 9964{
a76d924d 9965 int ret;
a76d924d 9966
2ec845e7
TT
9967 scoped_restore restore_timeout
9968 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9969
a76d924d 9970 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
9971
9972 switch (ret)
9973 {
9974 case PACKET_UNKNOWN:
9975 error (_("Remote target does not support vFlashDone"));
9976 case PACKET_ERROR:
9977 error (_("Error finishing flash operation"));
9978 default:
9979 break;
9980 }
9981}
9982
c906108c
SS
9983\f
9984/* Stuff for dealing with the packets which are part of this protocol.
9985 See comment at top of file for details. */
9986
048094ac
PA
9987/* Read a single character from the remote end. The current quit
9988 handler is overridden to avoid quitting in the middle of packet
9989 sequence, as that would break communication with the remote server.
9990 See remote_serial_quit_handler for more detail. */
c906108c 9991
6b8edb51
PA
9992int
9993remote_target::readchar (int timeout)
c906108c
SS
9994{
9995 int ch;
5d93a237 9996 struct remote_state *rs = get_remote_state ();
048094ac 9997
0da23004
TT
9998 try
9999 {
10000 scoped_restore restore_quit_target
10001 = make_scoped_restore (&curr_quit_handler_target, this);
10002 scoped_restore restore_quit
10003 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 10004
0da23004 10005 rs->got_ctrlc_during_io = 0;
c906108c 10006
0da23004 10007 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 10008
0da23004
TT
10009 if (rs->got_ctrlc_during_io)
10010 set_quit_flag ();
10011 }
10012 catch (const gdb_exception_error &ex)
10013 {
10014 remote_unpush_target (this);
10015 throw_error (TARGET_CLOSE_ERROR,
10016 _("Remote communication error. "
10017 "Target disconnected: %s"),
10018 ex.what ());
10019 }
048094ac 10020
2acceee2 10021 if (ch >= 0)
0876f84a 10022 return ch;
2acceee2 10023
0da23004 10024 if (ch == SERIAL_EOF)
c906108c 10025 {
5b6d1e4f 10026 remote_unpush_target (this);
598d3636 10027 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
c906108c 10028 }
0da23004 10029
2acceee2 10030 return ch;
c906108c
SS
10031}
10032
c33e31fd 10033/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
10034 writing fails. The current quit handler is overridden to avoid
10035 quitting in the middle of packet sequence, as that would break
10036 communication with the remote server. See
10037 remote_serial_quit_handler for more detail. */
c33e31fd 10038
6b8edb51
PA
10039void
10040remote_target::remote_serial_write (const char *str, int len)
c33e31fd 10041{
5d93a237 10042 struct remote_state *rs = get_remote_state ();
048094ac 10043
6b8edb51
PA
10044 scoped_restore restore_quit_target
10045 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 10046 scoped_restore restore_quit
6b8edb51 10047 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
10048
10049 rs->got_ctrlc_during_io = 0;
5d93a237 10050
d69939bd 10051 try
c33e31fd 10052 {
d69939bd
TT
10053 serial_write (rs->remote_desc, str, len);
10054 }
10055 catch (const gdb_exception_error &ex)
10056 {
10057 remote_unpush_target (this);
10058 throw_error (TARGET_CLOSE_ERROR,
10059 _("Remote communication error. "
10060 "Target disconnected: %s"),
10061 ex.what ());
c33e31fd 10062 }
048094ac
PA
10063
10064 if (rs->got_ctrlc_during_io)
10065 set_quit_flag ();
c33e31fd
PA
10066}
10067
d69939bd
TT
10068void
10069remote_target::remote_serial_send_break ()
10070{
10071 struct remote_state *rs = get_remote_state ();
10072
10073 try
10074 {
10075 serial_send_break (rs->remote_desc);
10076 }
10077 catch (const gdb_exception_error &ex)
10078 {
10079 remote_unpush_target (this);
10080 throw_error (TARGET_CLOSE_ERROR,
10081 _("Remote communication error. "
10082 "Target disconnected: %s"),
10083 ex.what ());
10084 }
10085}
10086
b3ced9ba
PA
10087/* Return a string representing an escaped version of BUF, of len N.
10088 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 10089
b3ced9ba 10090static std::string
6e5abd65
PA
10091escape_buffer (const char *buf, int n)
10092{
d7e74731 10093 string_file stb;
6e5abd65 10094
d7e74731 10095 stb.putstrn (buf, n, '\\');
5d10a204 10096 return stb.release ();
6e5abd65
PA
10097}
10098
c906108c 10099int
6b8edb51 10100remote_target::putpkt (const char *buf)
c906108c
SS
10101{
10102 return putpkt_binary (buf, strlen (buf));
10103}
10104
6b8edb51
PA
10105/* Wrapper around remote_target::putpkt to avoid exporting
10106 remote_target. */
10107
10108int
10109putpkt (remote_target *remote, const char *buf)
10110{
10111 return remote->putpkt (buf);
10112}
10113
c906108c 10114/* Send a packet to the remote machine, with error checking. The data
23860348 10115 of the packet is in BUF. The string in BUF can be at most
ea9c271d 10116 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
10117 and for a possible /0 if we are debugging (remote_debug) and want
10118 to print the sent packet as a string. */
c906108c 10119
6b8edb51
PA
10120int
10121remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 10122{
2d717e4f 10123 struct remote_state *rs = get_remote_state ();
c906108c
SS
10124 int i;
10125 unsigned char csum = 0;
b80406ac
TT
10126 gdb::def_vector<char> data (cnt + 6);
10127 char *buf2 = data.data ();
085dd6e6 10128
c906108c
SS
10129 int ch;
10130 int tcount = 0;
10131 char *p;
10132
e24a49d8
PA
10133 /* Catch cases like trying to read memory or listing threads while
10134 we're waiting for a stop reply. The remote server wouldn't be
10135 ready to handle this request, so we'd hang and timeout. We don't
10136 have to worry about this in synchronous mode, because in that
10137 case it's not possible to issue a command while the target is
74531fed
PA
10138 running. This is not a problem in non-stop mode, because in that
10139 case, the stub is always ready to process serial input. */
6efcd9a8
PA
10140 if (!target_is_non_stop_p ()
10141 && target_is_async_p ()
10142 && rs->waiting_for_stop_reply)
9597b22a
DE
10143 {
10144 error (_("Cannot execute this command while the target is running.\n"
10145 "Use the \"interrupt\" command to stop the target\n"
10146 "and then try again."));
10147 }
e24a49d8 10148
c906108c
SS
10149 /* Copy the packet into buffer BUF2, encapsulating it
10150 and giving it a checksum. */
10151
c906108c
SS
10152 p = buf2;
10153 *p++ = '$';
10154
10155 for (i = 0; i < cnt; i++)
10156 {
10157 csum += buf[i];
10158 *p++ = buf[i];
10159 }
10160 *p++ = '#';
10161 *p++ = tohex ((csum >> 4) & 0xf);
10162 *p++ = tohex (csum & 0xf);
10163
10164 /* Send it over and over until we get a positive ack. */
10165
10166 while (1)
10167 {
c906108c
SS
10168 if (remote_debug)
10169 {
10170 *p = '\0';
b3ced9ba 10171
6f8976bf 10172 int len = (int) (p - buf2);
6cc8564b
LM
10173 int max_chars;
10174
10175 if (remote_packet_max_chars < 0)
10176 max_chars = len;
10177 else
10178 max_chars = remote_packet_max_chars;
6f8976bf
YQ
10179
10180 std::string str
6cc8564b 10181 = escape_buffer (buf2, std::min (len, max_chars));
6f8976bf 10182
6cc8564b 10183 if (len > max_chars)
2189c312
SM
10184 remote_debug_printf_nofunc
10185 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
10186 len - max_chars);
10187 else
10188 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
c906108c 10189 }
c33e31fd 10190 remote_serial_write (buf2, p - buf2);
c906108c 10191
a6f3e723
SL
10192 /* If this is a no acks version of the remote protocol, send the
10193 packet and move on. */
10194 if (rs->noack_mode)
dda83cd7 10195 break;
a6f3e723 10196
74531fed
PA
10197 /* Read until either a timeout occurs (-2) or '+' is read.
10198 Handle any notification that arrives in the mean time. */
c906108c
SS
10199 while (1)
10200 {
10201 ch = readchar (remote_timeout);
10202
c906108c
SS
10203 switch (ch)
10204 {
10205 case '+':
2189c312 10206 remote_debug_printf_nofunc ("Received Ack");
c906108c 10207 return 1;
1216fa2c 10208 case '-':
2189c312 10209 remote_debug_printf_nofunc ("Received Nak");
d182e398 10210 [[fallthrough]];
c906108c 10211 case SERIAL_TIMEOUT:
c5aa993b 10212 tcount++;
c906108c 10213 if (tcount > 3)
b80406ac 10214 return 0;
23860348 10215 break; /* Retransmit buffer. */
c906108c
SS
10216 case '$':
10217 {
2189c312 10218 remote_debug_printf ("Packet instead of Ack, ignoring it");
d6f7abdf
AC
10219 /* It's probably an old response sent because an ACK
10220 was lost. Gobble up the packet and ack it so it
10221 doesn't get retransmitted when we resend this
10222 packet. */
6d820c5c 10223 skip_frame ();
c33e31fd 10224 remote_serial_write ("+", 1);
23860348 10225 continue; /* Now, go look for +. */
c906108c 10226 }
74531fed
PA
10227
10228 case '%':
10229 {
10230 int val;
10231
10232 /* If we got a notification, handle it, and go back to looking
10233 for an ack. */
10234 /* We've found the start of a notification. Now
10235 collect the data. */
8d64371b 10236 val = read_frame (&rs->buf);
74531fed
PA
10237 if (val >= 0)
10238 {
2189c312
SM
10239 remote_debug_printf_nofunc
10240 (" Notification received: %s",
10241 escape_buffer (rs->buf.data (), val).c_str ());
6e5abd65 10242
8d64371b 10243 handle_notification (rs->notif_state, rs->buf.data ());
74531fed
PA
10244 /* We're in sync now, rewait for the ack. */
10245 tcount = 0;
10246 }
10247 else
2189c312
SM
10248 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10249 rs->buf.data ());
74531fed
PA
10250 continue;
10251 }
c906108c 10252 default:
2189c312
SM
10253 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10254 rs->buf.data ());
c906108c
SS
10255 continue;
10256 }
23860348 10257 break; /* Here to retransmit. */
c906108c
SS
10258 }
10259
10260#if 0
10261 /* This is wrong. If doing a long backtrace, the user should be
dda83cd7
SM
10262 able to get out next time we call QUIT, without anything as
10263 violent as interrupt_query. If we want to provide a way out of
10264 here without getting to the next QUIT, it should be based on
10265 hitting ^C twice as in remote_wait. */
c906108c
SS
10266 if (quit_flag)
10267 {
10268 quit_flag = 0;
10269 interrupt_query ();
10270 }
10271#endif
10272 }
a5c0808e 10273
a6f3e723 10274 return 0;
c906108c
SS
10275}
10276
6d820c5c
DJ
10277/* Come here after finding the start of a frame when we expected an
10278 ack. Do our best to discard the rest of this packet. */
10279
6b8edb51
PA
10280void
10281remote_target::skip_frame ()
6d820c5c
DJ
10282{
10283 int c;
10284
10285 while (1)
10286 {
10287 c = readchar (remote_timeout);
10288 switch (c)
10289 {
10290 case SERIAL_TIMEOUT:
10291 /* Nothing we can do. */
10292 return;
10293 case '#':
10294 /* Discard the two bytes of checksum and stop. */
10295 c = readchar (remote_timeout);
10296 if (c >= 0)
10297 c = readchar (remote_timeout);
10298
10299 return;
10300 case '*': /* Run length encoding. */
10301 /* Discard the repeat count. */
10302 c = readchar (remote_timeout);
10303 if (c < 0)
10304 return;
10305 break;
10306 default:
10307 /* A regular character. */
10308 break;
10309 }
10310 }
10311}
10312
c906108c 10313/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
10314 into *BUF, verifying the checksum, length, and handling run-length
10315 compression. NUL terminate the buffer. If there is not enough room,
8d64371b 10316 expand *BUF.
c906108c 10317
c2d11a7d
JM
10318 Returns -1 on error, number of characters in buffer (ignoring the
10319 trailing NULL) on success. (could be extended to return one of the
23860348 10320 SERIAL status indications). */
c2d11a7d 10321
6b8edb51 10322long
8d64371b 10323remote_target::read_frame (gdb::char_vector *buf_p)
c906108c
SS
10324{
10325 unsigned char csum;
c2d11a7d 10326 long bc;
c906108c 10327 int c;
8d64371b 10328 char *buf = buf_p->data ();
a6f3e723 10329 struct remote_state *rs = get_remote_state ();
c906108c
SS
10330
10331 csum = 0;
c2d11a7d 10332 bc = 0;
c906108c
SS
10333
10334 while (1)
10335 {
10336 c = readchar (remote_timeout);
c906108c
SS
10337 switch (c)
10338 {
10339 case SERIAL_TIMEOUT:
2189c312 10340 remote_debug_printf ("Timeout in mid-packet, retrying");
c2d11a7d 10341 return -1;
2189c312 10342
c906108c 10343 case '$':
2189c312 10344 remote_debug_printf ("Saw new packet start in middle of old one");
23860348 10345 return -1; /* Start a new packet, count retries. */
2189c312 10346
c906108c
SS
10347 case '#':
10348 {
10349 unsigned char pktcsum;
e1b09194
AC
10350 int check_0 = 0;
10351 int check_1 = 0;
c906108c 10352
c2d11a7d 10353 buf[bc] = '\0';
c906108c 10354
e1b09194
AC
10355 check_0 = readchar (remote_timeout);
10356 if (check_0 >= 0)
10357 check_1 = readchar (remote_timeout);
802188a7 10358
e1b09194
AC
10359 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
10360 {
2189c312 10361 remote_debug_printf ("Timeout in checksum, retrying");
e1b09194
AC
10362 return -1;
10363 }
10364 else if (check_0 < 0 || check_1 < 0)
40e3f985 10365 {
2189c312 10366 remote_debug_printf ("Communication error in checksum");
40e3f985
FN
10367 return -1;
10368 }
c906108c 10369
a6f3e723
SL
10370 /* Don't recompute the checksum; with no ack packets we
10371 don't have any way to indicate a packet retransmission
10372 is necessary. */
10373 if (rs->noack_mode)
10374 return bc;
10375
e1b09194 10376 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 10377 if (csum == pktcsum)
dda83cd7 10378 return bc;
c906108c 10379
2189c312
SM
10380 remote_debug_printf
10381 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10382 pktcsum, csum, escape_buffer (buf, bc).c_str ());
6e5abd65 10383
c2d11a7d 10384 /* Number of characters in buffer ignoring trailing
dda83cd7 10385 NULL. */
c2d11a7d 10386 return -1;
c906108c 10387 }
23860348 10388 case '*': /* Run length encoding. */
dda83cd7 10389 {
c2c6d25f 10390 int repeat;
c906108c 10391
24b21115 10392 csum += c;
b4501125
AC
10393 c = readchar (remote_timeout);
10394 csum += c;
23860348 10395 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 10396
23860348 10397 /* The character before ``*'' is repeated. */
c2d11a7d 10398
6d820c5c 10399 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 10400 {
8d64371b 10401 if (bc + repeat - 1 >= buf_p->size () - 1)
6d820c5c
DJ
10402 {
10403 /* Make some more room in the buffer. */
8d64371b
TT
10404 buf_p->resize (buf_p->size () + repeat);
10405 buf = buf_p->data ();
6d820c5c
DJ
10406 }
10407
c2d11a7d
JM
10408 memset (&buf[bc], buf[bc - 1], repeat);
10409 bc += repeat;
c2c6d25f
JM
10410 continue;
10411 }
10412
c2d11a7d 10413 buf[bc] = '\0';
6cb06a8c 10414 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 10415 return -1;
c2c6d25f 10416 }
c906108c 10417 default:
8d64371b 10418 if (bc >= buf_p->size () - 1)
c906108c 10419 {
6d820c5c 10420 /* Make some more room in the buffer. */
8d64371b
TT
10421 buf_p->resize (buf_p->size () * 2);
10422 buf = buf_p->data ();
c906108c
SS
10423 }
10424
6d820c5c
DJ
10425 buf[bc++] = c;
10426 csum += c;
10427 continue;
c906108c
SS
10428 }
10429 }
10430}
10431
ed2b7c17
TT
10432/* Set this to the maximum number of seconds to wait instead of waiting forever
10433 in target_wait(). If this timer times out, then it generates an error and
10434 the command is aborted. This replaces most of the need for timeouts in the
10435 GDB test suite, and makes it possible to distinguish between a hung target
10436 and one with slow communications. */
10437
10438static int watchdog = 0;
10439static void
10440show_watchdog (struct ui_file *file, int from_tty,
10441 struct cmd_list_element *c, const char *value)
10442{
6cb06a8c 10443 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
ed2b7c17
TT
10444}
10445
d9fcf2fb 10446/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
10447 store it in *BUF. Resize *BUF if necessary to hold the result. If
10448 FOREVER, wait forever rather than timing out; this is used (in
10449 synchronous mode) to wait for a target that is is executing user
8756b726 10450 code to stop. If FOREVER == false, this function is allowed to time
8d64371b 10451 out gracefully and return an indication of this to the caller.
ef6a9843
TT
10452 Otherwise return the number of bytes read. If IS_NOTIF is not
10453 NULL, then consider receiving a notification enough reason to
10454 return to the caller. In this case, *IS_NOTIF is an output boolean
10455 that indicates whether *BUF holds a notification or not (a regular
10456 packet). */
74531fed 10457
6b8edb51 10458int
a60f93c7 10459remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
c906108c 10460{
2d717e4f 10461 struct remote_state *rs = get_remote_state ();
c906108c
SS
10462 int c;
10463 int tries;
10464 int timeout;
df4b58fe 10465 int val = -1;
c906108c 10466
8d64371b 10467 strcpy (buf->data (), "timeout");
c906108c
SS
10468
10469 if (forever)
74531fed 10470 timeout = watchdog > 0 ? watchdog : -1;
ef6a9843 10471 else if (is_notif != nullptr)
74531fed
PA
10472 timeout = 0; /* There should already be a char in the buffer. If
10473 not, bail out. */
c906108c
SS
10474 else
10475 timeout = remote_timeout;
10476
10477#define MAX_TRIES 3
10478
74531fed
PA
10479 /* Process any number of notifications, and then return when
10480 we get a packet. */
10481 for (;;)
c906108c 10482 {
d9c43928 10483 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
10484 times. */
10485 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 10486 {
74531fed
PA
10487 /* This can loop forever if the remote side sends us
10488 characters continuously, but if it pauses, we'll get
10489 SERIAL_TIMEOUT from readchar because of timeout. Then
10490 we'll count that as a retry.
10491
10492 Note that even when forever is set, we will only wait
10493 forever prior to the start of a packet. After that, we
10494 expect characters to arrive at a brisk pace. They should
10495 show up within remote_timeout intervals. */
10496 do
10497 c = readchar (timeout);
10498 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
10499
10500 if (c == SERIAL_TIMEOUT)
10501 {
ef6a9843 10502 if (is_notif != nullptr)
74531fed
PA
10503 return -1; /* Don't complain, it's normal to not get
10504 anything in this case. */
10505
23860348 10506 if (forever) /* Watchdog went off? Kill the target. */
c906108c 10507 {
5b6d1e4f 10508 remote_unpush_target (this);
598d3636
JK
10509 throw_error (TARGET_CLOSE_ERROR,
10510 _("Watchdog timeout has expired. "
10511 "Target detached."));
c906108c 10512 }
2189c312
SM
10513
10514 remote_debug_printf ("Timed out.");
c906108c 10515 }
74531fed
PA
10516 else
10517 {
10518 /* We've found the start of a packet or notification.
10519 Now collect the data. */
8d64371b 10520 val = read_frame (buf);
74531fed
PA
10521 if (val >= 0)
10522 break;
10523 }
10524
c33e31fd 10525 remote_serial_write ("-", 1);
c906108c 10526 }
c906108c 10527
74531fed
PA
10528 if (tries > MAX_TRIES)
10529 {
10530 /* We have tried hard enough, and just can't receive the
10531 packet/notification. Give up. */
6cb06a8c 10532 gdb_printf (_("Ignoring packet error, continuing...\n"));
c906108c 10533
74531fed
PA
10534 /* Skip the ack char if we're in no-ack mode. */
10535 if (!rs->noack_mode)
c33e31fd 10536 remote_serial_write ("+", 1);
74531fed
PA
10537 return -1;
10538 }
c906108c 10539
74531fed
PA
10540 /* If we got an ordinary packet, return that to our caller. */
10541 if (c == '$')
c906108c
SS
10542 {
10543 if (remote_debug)
43e526b9 10544 {
6cc8564b
LM
10545 int max_chars;
10546
10547 if (remote_packet_max_chars < 0)
10548 max_chars = val;
10549 else
10550 max_chars = remote_packet_max_chars;
10551
6f8976bf 10552 std::string str
8d64371b 10553 = escape_buffer (buf->data (),
6cc8564b 10554 std::min (val, max_chars));
6f8976bf 10555
6cc8564b 10556 if (val > max_chars)
2189c312 10557 remote_debug_printf_nofunc
1f493519
TJB
10558 ("Packet received: %s [%d of %d bytes omitted]", str.c_str (),
10559 val - max_chars, val);
2189c312
SM
10560 else
10561 remote_debug_printf_nofunc ("Packet received: %s",
10562 str.c_str ());
43e526b9 10563 }
a6f3e723
SL
10564
10565 /* Skip the ack char if we're in no-ack mode. */
10566 if (!rs->noack_mode)
c33e31fd 10567 remote_serial_write ("+", 1);
fee9eda9 10568 if (is_notif != NULL)
8756b726 10569 *is_notif = false;
0876f84a 10570 return val;
c906108c
SS
10571 }
10572
74531fed
PA
10573 /* If we got a notification, handle it, and go back to looking
10574 for a packet. */
10575 else
10576 {
10577 gdb_assert (c == '%');
10578
2189c312
SM
10579 remote_debug_printf_nofunc
10580 (" Notification received: %s",
10581 escape_buffer (buf->data (), val).c_str ());
6e5abd65 10582
fee9eda9 10583 if (is_notif != NULL)
8756b726 10584 *is_notif = true;
c906108c 10585
8d64371b 10586 handle_notification (rs->notif_state, buf->data ());
c906108c 10587
74531fed 10588 /* Notifications require no acknowledgement. */
a6f3e723 10589
ef6a9843 10590 if (is_notif != nullptr)
fee9eda9 10591 return val;
74531fed
PA
10592 }
10593 }
10594}
10595
28561a65 10596/* Kill any new fork children of inferior INF that haven't been
cbb8991c
DB
10597 processed by follow_fork. */
10598
6b8edb51 10599void
28561a65 10600remote_target::kill_new_fork_children (inferior *inf)
cbb8991c 10601{
6b8edb51 10602 remote_state *rs = get_remote_state ();
42938c1a 10603 const notif_client *notif = &notif_client_stop;
cbb8991c 10604
28561a65
SM
10605 /* Kill the fork child threads of any threads in inferior INF that are stopped
10606 at a fork event. */
10607 for (thread_info *thread : inf->non_exited_threads ())
cbb8991c 10608 {
28561a65 10609 const target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c 10610
28561a65
SM
10611 if (ws == nullptr)
10612 continue;
cbb8991c 10613
28561a65
SM
10614 int child_pid = ws->child_ptid ().pid ();
10615 int res = remote_vkill (child_pid);
10616
10617 if (res != 0)
10618 error (_("Can't kill fork child process %d"), child_pid);
cbb8991c
DB
10619 }
10620
10621 /* Check for any pending fork events (not reported or processed yet)
28561a65 10622 in inferior INF and kill those fork child threads as well. */
cbb8991c 10623 remote_notif_get_pending_events (notif);
953edf2b 10624 for (auto &event : rs->stop_reply_queue)
28561a65
SM
10625 {
10626 if (event->ptid.pid () != inf->pid)
10627 continue;
953edf2b 10628
28561a65
SM
10629 if (!is_fork_status (event->ws.kind ()))
10630 continue;
10631
10632 int child_pid = event->ws.child_ptid ().pid ();
10633 int res = remote_vkill (child_pid);
10634
10635 if (res != 0)
10636 error (_("Can't kill fork child process %d"), child_pid);
10637 }
cbb8991c
DB
10638}
10639
c906108c 10640\f
8020350c
DB
10641/* Target hook to kill the current inferior. */
10642
f6ac5f3d
PA
10643void
10644remote_target::kill ()
43ff13b4 10645{
8020350c 10646 int res = -1;
28561a65 10647 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
0fdf84ca 10648
28561a65
SM
10649 gdb_assert (inf != nullptr);
10650
ff52c073 10651 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 10652 {
8020350c
DB
10653 /* If we're stopped while forking and we haven't followed yet,
10654 kill the child task. We need to do this before killing the
10655 parent task because if this is a vfork then the parent will
10656 be sleeping. */
28561a65 10657 kill_new_fork_children (inf);
8020350c 10658
28561a65 10659 res = remote_vkill (inf->pid);
8020350c 10660 if (res == 0)
0fdf84ca 10661 {
bc1e6c81 10662 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
10663 return;
10664 }
8020350c 10665 }
0fdf84ca 10666
8020350c
DB
10667 /* If we are in 'target remote' mode and we are killing the only
10668 inferior, then we will tell gdbserver to exit and unpush the
10669 target. */
ff52c073 10670 if (res == -1 && !m_features.remote_multi_process_p ()
5b6d1e4f 10671 && number_of_live_inferiors (this) == 1)
8020350c
DB
10672 {
10673 remote_kill_k ();
10674
10675 /* We've killed the remote end, we get to mourn it. If we are
10676 not in extended mode, mourning the inferior also unpushes
10677 remote_ops from the target stack, which closes the remote
10678 connection. */
bc1e6c81 10679 target_mourn_inferior (inferior_ptid);
8020350c
DB
10680
10681 return;
0fdf84ca 10682 }
43ff13b4 10683
8020350c 10684 error (_("Can't kill process"));
43ff13b4
JM
10685}
10686
8020350c
DB
10687/* Send a kill request to the target using the 'vKill' packet. */
10688
6b8edb51
PA
10689int
10690remote_target::remote_vkill (int pid)
82f73884 10691{
ff52c073 10692 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
10693 return -1;
10694
6b8edb51
PA
10695 remote_state *rs = get_remote_state ();
10696
82f73884 10697 /* Tell the remote target to detach. */
8d64371b 10698 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
82f73884 10699 putpkt (rs->buf);
aa7b36b8 10700 getpkt (&rs->buf);
82f73884 10701
94a94c90 10702 switch ((m_features.packet_ok (rs->buf, PACKET_vKill)).status ())
4082afcc
PA
10703 {
10704 case PACKET_OK:
10705 return 0;
10706 case PACKET_ERROR:
10707 return 1;
10708 case PACKET_UNKNOWN:
10709 return -1;
10710 default:
f34652de 10711 internal_error (_("Bad result from packet_ok"));
4082afcc 10712 }
82f73884
PA
10713}
10714
8020350c
DB
10715/* Send a kill request to the target using the 'k' packet. */
10716
6b8edb51
PA
10717void
10718remote_target::remote_kill_k ()
82f73884 10719{
8020350c
DB
10720 /* Catch errors so the user can quit from gdb even when we
10721 aren't on speaking terms with the remote system. */
a70b8144 10722 try
82f73884 10723 {
82f73884 10724 putpkt ("k");
82f73884 10725 }
230d2906 10726 catch (const gdb_exception_error &ex)
8020350c
DB
10727 {
10728 if (ex.error == TARGET_CLOSE_ERROR)
10729 {
10730 /* If we got an (EOF) error that caused the target
10731 to go away, then we're done, that's what we wanted.
10732 "k" is susceptible to cause a premature EOF, given
10733 that the remote server isn't actually required to
10734 reply to "k", and it can happen that it doesn't
10735 even get to reply ACK to the "k". */
10736 return;
10737 }
82f73884 10738
8020350c
DB
10739 /* Otherwise, something went wrong. We didn't actually kill
10740 the target. Just propagate the exception, and let the
10741 user or higher layers decide what to do. */
eedc3f4f 10742 throw;
8020350c 10743 }
82f73884
PA
10744}
10745
f6ac5f3d
PA
10746void
10747remote_target::mourn_inferior ()
c906108c 10748{
8020350c 10749 struct remote_state *rs = get_remote_state ();
ce5ce7ed 10750
9607784a
PA
10751 /* We're no longer interested in notification events of an inferior
10752 that exited or was killed/detached. */
10753 discard_pending_stop_replies (current_inferior ());
10754
8020350c 10755 /* In 'target remote' mode with one inferior, we close the connection. */
5b6d1e4f 10756 if (!rs->extended && number_of_live_inferiors (this) <= 1)
8020350c 10757 {
5b6d1e4f 10758 remote_unpush_target (this);
8020350c
DB
10759 return;
10760 }
c906108c 10761
e24a49d8
PA
10762 /* In case we got here due to an error, but we're going to stay
10763 connected. */
10764 rs->waiting_for_stop_reply = 0;
10765
dc1981d7
PA
10766 /* If the current general thread belonged to the process we just
10767 detached from or has exited, the remote side current general
10768 thread becomes undefined. Considering a case like this:
10769
10770 - We just got here due to a detach.
10771 - The process that we're detaching from happens to immediately
10772 report a global breakpoint being hit in non-stop mode, in the
10773 same thread we had selected before.
10774 - GDB attaches to this process again.
10775 - This event happens to be the next event we handle.
10776
10777 GDB would consider that the current general thread didn't need to
10778 be set on the stub side (with Hg), since for all it knew,
10779 GENERAL_THREAD hadn't changed.
10780
10781 Notice that although in all-stop mode, the remote server always
10782 sets the current thread to the thread reporting the stop event,
10783 that doesn't happen in non-stop mode; in non-stop, the stub *must
10784 not* change the current thread when reporting a breakpoint hit,
10785 due to the decoupling of event reporting and event handling.
10786
10787 To keep things simple, we always invalidate our notion of the
10788 current thread. */
47f8a51d 10789 record_currthread (rs, minus_one_ptid);
dc1981d7 10790
8020350c 10791 /* Call common code to mark the inferior as not running. */
48aa3c27 10792 generic_mourn_inferior ();
2d717e4f 10793}
c906108c 10794
57810aa7 10795bool
f6ac5f3d 10796extended_remote_target::supports_disable_randomization ()
03583c20 10797{
ff52c073
CS
10798 return (m_features.packet_support (PACKET_QDisableRandomization)
10799 == PACKET_ENABLE);
03583c20
UW
10800}
10801
6b8edb51
PA
10802void
10803remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
10804{
10805 struct remote_state *rs = get_remote_state ();
10806 char *reply;
10807
8d64371b
TT
10808 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10809 "QDisableRandomization:%x", val);
03583c20 10810 putpkt (rs->buf);
b6bb3468 10811 reply = remote_get_noisy_reply ();
03583c20
UW
10812 if (*reply == '\0')
10813 error (_("Target does not support QDisableRandomization."));
10814 if (strcmp (reply, "OK") != 0)
10815 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10816}
10817
6b8edb51
PA
10818int
10819remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
10820{
10821 struct remote_state *rs = get_remote_state ();
2d717e4f 10822 int len;
94585166 10823 const char *remote_exec_file = get_remote_exec_file ();
c906108c 10824
2d717e4f
DJ
10825 /* If the user has disabled vRun support, or we have detected that
10826 support is not available, do not try it. */
ff52c073 10827 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 10828 return -1;
424163ea 10829
8d64371b
TT
10830 strcpy (rs->buf.data (), "vRun;");
10831 len = strlen (rs->buf.data ());
c906108c 10832
2d717e4f
DJ
10833 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10834 error (_("Remote file name too long for run packet"));
8d64371b 10835 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
9f1b45b0 10836 strlen (remote_exec_file));
2d717e4f 10837
7c5ded6a 10838 if (!args.empty ())
2d717e4f 10839 {
bd036f03 10840 std::vector<std::string> split_args = gdb::remote_args::split (args);
2d717e4f 10841
bd036f03 10842 for (const auto &a : split_args)
2d717e4f 10843 {
bd036f03 10844 if (a.size () * 2 + 1 + len >= get_remote_packet_size ())
2d717e4f
DJ
10845 error (_("Argument list too long for run packet"));
10846 rs->buf[len++] = ';';
bd036f03
AB
10847 len += 2 * bin2hex ((gdb_byte *) a.c_str (), rs->buf.data () + len,
10848 a.size ());
2d717e4f 10849 }
2d717e4f
DJ
10850 }
10851
10852 rs->buf[len++] = '\0';
10853
10854 putpkt (rs->buf);
aa7b36b8 10855 getpkt (&rs->buf);
2d717e4f 10856
33befefc
PA
10857 packet_result result = m_features.packet_ok (rs->buf, PACKET_vRun);
10858 switch (result.status ())
2d717e4f 10859 {
4082afcc 10860 case PACKET_OK:
3405876a 10861 /* We have a wait response. All is well. */
2d717e4f 10862 return 0;
4082afcc
PA
10863 case PACKET_UNKNOWN:
10864 return -1;
10865 case PACKET_ERROR:
33befefc
PA
10866 /* If we have a textual error message, print just that. This
10867 makes remote debugging output the same as native output, when
10868 possible. */
10869 if (result.textual_err_msg ())
10870 error (("%s"), result.err_msg ());
2d717e4f
DJ
10871 if (remote_exec_file[0] == '\0')
10872 error (_("Running the default executable on the remote target failed; "
10873 "try \"set remote exec-file\"?"));
10874 else
10875 error (_("Running \"%s\" on the remote target failed"),
10876 remote_exec_file);
4082afcc 10877 default:
557b4d76 10878 gdb_assert_not_reached ("bad switch");
2d717e4f 10879 }
c906108c
SS
10880}
10881
0a2dde4a
SDJ
10882/* Helper function to send set/unset environment packets. ACTION is
10883 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10884 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10885 sent. */
10886
6b8edb51
PA
10887void
10888remote_target::send_environment_packet (const char *action,
10889 const char *packet,
10890 const char *value)
0a2dde4a 10891{
6b8edb51
PA
10892 remote_state *rs = get_remote_state ();
10893
0a2dde4a
SDJ
10894 /* Convert the environment variable to an hex string, which
10895 is the best format to be transmitted over the wire. */
10896 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10897 strlen (value));
10898
8d64371b 10899 xsnprintf (rs->buf.data (), get_remote_packet_size (),
0a2dde4a
SDJ
10900 "%s:%s", packet, encoded_value.c_str ());
10901
10902 putpkt (rs->buf);
aa7b36b8 10903 getpkt (&rs->buf);
8d64371b 10904 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10905 warning (_("Unable to %s environment variable '%s' on remote."),
10906 action, value);
10907}
10908
10909/* Helper function to handle the QEnvironment* packets. */
10910
6b8edb51
PA
10911void
10912remote_target::extended_remote_environment_support ()
0a2dde4a 10913{
6b8edb51
PA
10914 remote_state *rs = get_remote_state ();
10915
ff52c073 10916 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
0a2dde4a
SDJ
10917 {
10918 putpkt ("QEnvironmentReset");
aa7b36b8 10919 getpkt (&rs->buf);
8d64371b 10920 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10921 warning (_("Unable to reset environment on remote."));
10922 }
10923
10924 gdb_environ *e = &current_inferior ()->environment;
10925
ff52c073
CS
10926 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10927 != PACKET_DISABLE)
10928 {
10929 for (const std::string &el : e->user_set_env ())
10930 send_environment_packet ("set", "QEnvironmentHexEncoded",
10931 el.c_str ());
10932 }
10933
0a2dde4a 10934
ff52c073 10935 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
0a2dde4a 10936 for (const std::string &el : e->user_unset_env ())
6b8edb51 10937 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10938}
10939
bc3b087d
SDJ
10940/* Helper function to set the current working directory for the
10941 inferior in the remote target. */
10942
6b8edb51
PA
10943void
10944remote_target::extended_remote_set_inferior_cwd ()
bc3b087d 10945{
ff52c073 10946 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
bc3b087d 10947 {
11bd012e 10948 const std::string &inferior_cwd = current_inferior ()->cwd ();
6b8edb51 10949 remote_state *rs = get_remote_state ();
bc3b087d 10950
11bd012e 10951 if (!inferior_cwd.empty ())
bc3b087d 10952 {
11bd012e
SM
10953 std::string hexpath
10954 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10955 inferior_cwd.size ());
bc3b087d 10956
8d64371b 10957 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10958 "QSetWorkingDir:%s", hexpath.c_str ());
10959 }
10960 else
10961 {
10962 /* An empty inferior_cwd means that the user wants us to
10963 reset the remote server's inferior's cwd. */
8d64371b 10964 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10965 "QSetWorkingDir:");
10966 }
10967
10968 putpkt (rs->buf);
aa7b36b8 10969 getpkt (&rs->buf);
94a94c90
AH
10970 packet_result result = m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir);
10971 if (result.status () == PACKET_ERROR)
bc3b087d
SDJ
10972 error (_("\
10973Remote replied unexpectedly while setting the inferior's working\n\
10974directory: %s"),
94a94c90
AH
10975 result.err_msg ());
10976 if (result.status () == PACKET_UNKNOWN)
10977 error (_("Remote target failed to process setting the inferior's working directory"));
bc3b087d
SDJ
10978
10979 }
10980}
10981
2d717e4f
DJ
10982/* In the extended protocol we want to be able to do things like
10983 "run" and have them basically work as expected. So we need
10984 a special create_inferior function. We support changing the
10985 executable file and the command line arguments, but not the
10986 environment. */
10987
f6ac5f3d
PA
10988void
10989extended_remote_target::create_inferior (const char *exec_file,
10990 const std::string &args,
10991 char **env, int from_tty)
43ff13b4 10992{
3405876a
PA
10993 int run_worked;
10994 char *stop_reply;
10995 struct remote_state *rs = get_remote_state ();
94585166 10996 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10997
43ff13b4 10998 /* If running asynchronously, register the target file descriptor
23860348 10999 with the event loop. */
75c99385 11000 if (target_can_async_p ())
4a570176 11001 target_async (true);
43ff13b4 11002
03583c20 11003 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 11004 if (supports_disable_randomization ())
03583c20
UW
11005 extended_remote_disable_randomization (disable_randomization);
11006
aefd8b33
SDJ
11007 /* If startup-with-shell is on, we inform gdbserver to start the
11008 remote inferior using a shell. */
ff52c073 11009 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
aefd8b33 11010 {
8d64371b 11011 xsnprintf (rs->buf.data (), get_remote_packet_size (),
aefd8b33
SDJ
11012 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
11013 putpkt (rs->buf);
aa7b36b8 11014 getpkt (&rs->buf);
8d64371b 11015 if (strcmp (rs->buf.data (), "OK") != 0)
aefd8b33
SDJ
11016 error (_("\
11017Remote replied unexpectedly while setting startup-with-shell: %s"),
8d64371b 11018 rs->buf.data ());
aefd8b33
SDJ
11019 }
11020
6b8edb51 11021 extended_remote_environment_support ();
0a2dde4a 11022
6b8edb51 11023 extended_remote_set_inferior_cwd ();
bc3b087d 11024
43ff13b4 11025 /* Now restart the remote server. */
3405876a
PA
11026 run_worked = extended_remote_run (args) != -1;
11027 if (!run_worked)
2d717e4f
DJ
11028 {
11029 /* vRun was not supported. Fail if we need it to do what the
11030 user requested. */
11031 if (remote_exec_file[0])
11032 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 11033 if (!args.empty ())
65e65158 11034 error (_("Remote target does not support \"set args\" or run ARGS"));
43ff13b4 11035
2d717e4f
DJ
11036 /* Fall back to "R". */
11037 extended_remote_restart ();
11038 }
424163ea 11039
3405876a 11040 /* vRun's success return is a stop reply. */
8d64371b 11041 stop_reply = run_worked ? rs->buf.data () : NULL;
3405876a 11042 add_current_inferior_and_thread (stop_reply);
c0a2216e 11043
2d717e4f
DJ
11044 /* Get updated offsets, if the stub uses qOffsets. */
11045 get_offsets ();
2d717e4f 11046}
c906108c 11047\f
c5aa993b 11048
b775012e
LM
11049/* Given a location's target info BP_TGT and the packet buffer BUF, output
11050 the list of conditions (in agent expression bytecode format), if any, the
11051 target needs to evaluate. The output is placed into the packet buffer
bba74b36 11052 started from BUF and ended at BUF_END. */
b775012e
LM
11053
11054static int
11055remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
11056 struct bp_target_info *bp_tgt, char *buf,
11057 char *buf_end)
b775012e 11058{
3cde5c42 11059 if (bp_tgt->conditions.empty ())
b775012e
LM
11060 return 0;
11061
11062 buf += strlen (buf);
bba74b36 11063 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
11064 buf++;
11065
83621223 11066 /* Send conditions to the target. */
d538e36d 11067 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 11068 {
6f96f485 11069 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
b775012e 11070 buf += strlen (buf);
6f96f485 11071 for (int i = 0; i < aexpr->buf.size (); ++i)
b775012e
LM
11072 buf = pack_hex_byte (buf, aexpr->buf[i]);
11073 *buf = '\0';
11074 }
b775012e
LM
11075 return 0;
11076}
11077
d3ce09f5
SS
11078static void
11079remote_add_target_side_commands (struct gdbarch *gdbarch,
11080 struct bp_target_info *bp_tgt, char *buf)
11081{
3cde5c42 11082 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
11083 return;
11084
11085 buf += strlen (buf);
11086
11087 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
11088 buf += strlen (buf);
11089
11090 /* Concatenate all the agent expressions that are commands into the
11091 cmds parameter. */
df97be55 11092 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5 11093 {
6f96f485 11094 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
d3ce09f5 11095 buf += strlen (buf);
6f96f485 11096 for (int i = 0; i < aexpr->buf.size (); ++i)
d3ce09f5
SS
11097 buf = pack_hex_byte (buf, aexpr->buf[i]);
11098 *buf = '\0';
11099 }
d3ce09f5
SS
11100}
11101
8181d85f
DJ
11102/* Insert a breakpoint. On targets that have software breakpoint
11103 support, we ask the remote target to do the work; on targets
11104 which don't, we insert a traditional memory breakpoint. */
c906108c 11105
f6ac5f3d
PA
11106int
11107remote_target::insert_breakpoint (struct gdbarch *gdbarch,
11108 struct bp_target_info *bp_tgt)
c906108c 11109{
d471ea57
AC
11110 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
11111 If it succeeds, then set the support to PACKET_ENABLE. If it
11112 fails, and the user has explicitly requested the Z support then
23860348 11113 report an error, otherwise, mark it disabled and go on. */
802188a7 11114
ff52c073 11115 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 11116 {
0d5ed153 11117 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 11118 struct remote_state *rs;
bba74b36 11119 char *p, *endbuf;
4fff2411 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
4fff2411 11126 rs = get_remote_state ();
8d64371b
TT
11127 p = rs->buf.data ();
11128 endbuf = p + get_remote_packet_size ();
802188a7 11129
96baa820
JM
11130 *(p++) = 'Z';
11131 *(p++) = '0';
11132 *(p++) = ',';
7c0f6dcc 11133 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 11134 p += hexnumstr (p, addr);
579c6ad9 11135 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 11136
f6ac5f3d 11137 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 11138 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 11139
f6ac5f3d 11140 if (can_run_breakpoint_commands ())
d3ce09f5
SS
11141 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11142
6d820c5c 11143 putpkt (rs->buf);
aa7b36b8 11144 getpkt (&rs->buf);
96baa820 11145
94a94c90 11146 switch ((m_features.packet_ok (rs->buf, PACKET_Z0)).status ())
96baa820 11147 {
d471ea57
AC
11148 case PACKET_ERROR:
11149 return -1;
11150 case PACKET_OK:
11151 return 0;
11152 case PACKET_UNKNOWN:
11153 break;
96baa820
JM
11154 }
11155 }
c906108c 11156
0000e5cc
PA
11157 /* If this breakpoint has target-side commands but this stub doesn't
11158 support Z0 packets, throw error. */
3cde5c42 11159 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
11160 throw_error (NOT_SUPPORTED_ERROR, _("\
11161Target doesn't support breakpoints that have target side commands."));
11162
f6ac5f3d 11163 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
11164}
11165
f6ac5f3d
PA
11166int
11167remote_target::remove_breakpoint (struct gdbarch *gdbarch,
11168 struct bp_target_info *bp_tgt,
11169 enum remove_bp_reason reason)
c906108c 11170{
8181d85f 11171 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 11172 struct remote_state *rs = get_remote_state ();
96baa820 11173
ff52c073 11174 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 11175 {
8d64371b
TT
11176 char *p = rs->buf.data ();
11177 char *endbuf = p + get_remote_packet_size ();
802188a7 11178
28439a30
PA
11179 /* Make sure the remote is pointing at the right process, if
11180 necessary. */
99d9c3b9 11181 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
28439a30
PA
11182 set_general_process ();
11183
96baa820
JM
11184 *(p++) = 'z';
11185 *(p++) = '0';
11186 *(p++) = ',';
11187
8181d85f
DJ
11188 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
11189 p += hexnumstr (p, addr);
579c6ad9 11190 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 11191
6d820c5c 11192 putpkt (rs->buf);
aa7b36b8 11193 getpkt (&rs->buf);
96baa820 11194
6d820c5c 11195 return (rs->buf[0] == 'E');
96baa820
JM
11196 }
11197
f6ac5f3d 11198 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
11199}
11200
f486487f 11201static enum Z_packet_type
d471ea57
AC
11202watchpoint_to_Z_packet (int type)
11203{
11204 switch (type)
11205 {
11206 case hw_write:
bb858e6a 11207 return Z_PACKET_WRITE_WP;
d471ea57
AC
11208 break;
11209 case hw_read:
bb858e6a 11210 return Z_PACKET_READ_WP;
d471ea57
AC
11211 break;
11212 case hw_access:
bb858e6a 11213 return Z_PACKET_ACCESS_WP;
d471ea57
AC
11214 break;
11215 default:
f34652de 11216 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
11217 }
11218}
11219
f6ac5f3d
PA
11220int
11221remote_target::insert_watchpoint (CORE_ADDR addr, int len,
11222 enum target_hw_bp_type type, struct expression *cond)
96baa820 11223{
d01949b6 11224 struct remote_state *rs = get_remote_state ();
8d64371b 11225 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 11226 char *p;
d471ea57 11227 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 11228
24a601dd
TV
11229 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11230 + to_underlying (packet))) == PACKET_DISABLE)
85d721b8 11231 return 1;
802188a7 11232
28439a30
PA
11233 /* Make sure the remote is pointing at the right process, if
11234 necessary. */
99d9c3b9 11235 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
28439a30
PA
11236 set_general_process ();
11237
8d64371b
TT
11238 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
11239 p = strchr (rs->buf.data (), '\0');
96baa820
JM
11240 addr = remote_address_masked (addr);
11241 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 11242 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 11243
6d820c5c 11244 putpkt (rs->buf);
aa7b36b8 11245 getpkt (&rs->buf);
96baa820 11246
94a94c90
AH
11247 switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11248 + to_underlying (packet)))).status ())
d471ea57
AC
11249 {
11250 case PACKET_ERROR:
d471ea57 11251 return -1;
85d721b8
PA
11252 case PACKET_UNKNOWN:
11253 return 1;
d471ea57
AC
11254 case PACKET_OK:
11255 return 0;
11256 }
f34652de 11257 internal_error (_("remote_insert_watchpoint: reached end of function"));
96baa820
JM
11258}
11259
57810aa7 11260bool
f6ac5f3d
PA
11261remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
11262 CORE_ADDR start, int length)
283002cf
MR
11263{
11264 CORE_ADDR diff = remote_address_masked (addr - start);
11265
11266 return diff < length;
11267}
11268
d471ea57 11269
f6ac5f3d
PA
11270int
11271remote_target::remove_watchpoint (CORE_ADDR addr, int len,
11272 enum target_hw_bp_type type, struct expression *cond)
96baa820 11273{
d01949b6 11274 struct remote_state *rs = get_remote_state ();
8d64371b 11275 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 11276 char *p;
d471ea57
AC
11277 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11278
24a601dd
TV
11279 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11280 + to_underlying (packet))) == PACKET_DISABLE)
5cffb350 11281 return -1;
802188a7 11282
28439a30
PA
11283 /* Make sure the remote is pointing at the right process, if
11284 necessary. */
99d9c3b9 11285 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
28439a30
PA
11286 set_general_process ();
11287
8d64371b
TT
11288 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
11289 p = strchr (rs->buf.data (), '\0');
96baa820
JM
11290 addr = remote_address_masked (addr);
11291 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 11292 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c 11293 putpkt (rs->buf);
aa7b36b8 11294 getpkt (&rs->buf);
96baa820 11295
94a94c90
AH
11296 switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11297 + to_underlying (packet)))).status ())
d471ea57
AC
11298 {
11299 case PACKET_ERROR:
11300 case PACKET_UNKNOWN:
11301 return -1;
11302 case PACKET_OK:
11303 return 0;
11304 }
f34652de 11305 internal_error (_("remote_remove_watchpoint: reached end of function"));
96baa820
JM
11306}
11307
3c3bea1c 11308
60fcc1c3
TT
11309static int remote_hw_watchpoint_limit = -1;
11310static int remote_hw_watchpoint_length_limit = -1;
11311static int remote_hw_breakpoint_limit = -1;
d471ea57 11312
f6ac5f3d
PA
11313int
11314remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
11315{
11316 if (remote_hw_watchpoint_length_limit == 0)
11317 return 0;
11318 else if (remote_hw_watchpoint_length_limit < 0)
11319 return 1;
11320 else if (len <= remote_hw_watchpoint_length_limit)
11321 return 1;
11322 else
11323 return 0;
11324}
11325
f6ac5f3d
PA
11326int
11327remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 11328{
3c3bea1c
GS
11329 if (type == bp_hardware_breakpoint)
11330 {
11331 if (remote_hw_breakpoint_limit == 0)
11332 return 0;
501eef12
AC
11333 else if (remote_hw_breakpoint_limit < 0)
11334 return 1;
3c3bea1c
GS
11335 else if (cnt <= remote_hw_breakpoint_limit)
11336 return 1;
11337 }
11338 else
11339 {
11340 if (remote_hw_watchpoint_limit == 0)
11341 return 0;
501eef12
AC
11342 else if (remote_hw_watchpoint_limit < 0)
11343 return 1;
3c3bea1c
GS
11344 else if (ot)
11345 return -1;
11346 else if (cnt <= remote_hw_watchpoint_limit)
11347 return 1;
11348 }
11349 return -1;
11350}
11351
f7e6eed5
PA
11352/* The to_stopped_by_sw_breakpoint method of target remote. */
11353
57810aa7 11354bool
f6ac5f3d 11355remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 11356{
799a2abe 11357 struct thread_info *thread = inferior_thread ();
f7e6eed5 11358
799a2abe 11359 return (thread->priv != NULL
7aabaf9d
SM
11360 && (get_remote_thread_info (thread)->stop_reason
11361 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
11362}
11363
11364/* The to_supports_stopped_by_sw_breakpoint method of target
11365 remote. */
11366
57810aa7 11367bool
f6ac5f3d 11368remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 11369{
ff52c073 11370 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
f7e6eed5
PA
11371}
11372
11373/* The to_stopped_by_hw_breakpoint method of target remote. */
11374
57810aa7 11375bool
f6ac5f3d 11376remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 11377{
799a2abe 11378 struct thread_info *thread = inferior_thread ();
f7e6eed5 11379
799a2abe 11380 return (thread->priv != NULL
7aabaf9d
SM
11381 && (get_remote_thread_info (thread)->stop_reason
11382 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
11383}
11384
11385/* The to_supports_stopped_by_hw_breakpoint method of target
11386 remote. */
11387
57810aa7 11388bool
f6ac5f3d 11389remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 11390{
ff52c073 11391 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
f7e6eed5
PA
11392}
11393
57810aa7 11394bool
f6ac5f3d 11395remote_target::stopped_by_watchpoint ()
3c3bea1c 11396{
799a2abe 11397 struct thread_info *thread = inferior_thread ();
ee154bee 11398
799a2abe 11399 return (thread->priv != NULL
7aabaf9d
SM
11400 && (get_remote_thread_info (thread)->stop_reason
11401 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
11402}
11403
57810aa7 11404bool
f6ac5f3d 11405remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 11406{
799a2abe 11407 struct thread_info *thread = inferior_thread ();
a744cf53 11408
799a2abe 11409 if (thread->priv != NULL
7aabaf9d
SM
11410 && (get_remote_thread_info (thread)->stop_reason
11411 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 11412 {
7aabaf9d 11413 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 11414 return true;
4aa7a7f5
JJ
11415 }
11416
57810aa7 11417 return false;
3c3bea1c
GS
11418}
11419
11420
f6ac5f3d
PA
11421int
11422remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11423 struct bp_target_info *bp_tgt)
3c3bea1c 11424{
0d5ed153 11425 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 11426 struct remote_state *rs;
bba74b36 11427 char *p, *endbuf;
3c3bea1c 11428
ff52c073 11429 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 11430 return -1;
2bc416ba 11431
28439a30
PA
11432 /* Make sure the remote is pointing at the right process, if
11433 necessary. */
99d9c3b9 11434 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
28439a30
PA
11435 set_general_process ();
11436
4fff2411 11437 rs = get_remote_state ();
8d64371b
TT
11438 p = rs->buf.data ();
11439 endbuf = p + get_remote_packet_size ();
4fff2411 11440
96baa820
JM
11441 *(p++) = 'Z';
11442 *(p++) = '1';
11443 *(p++) = ',';
802188a7 11444
0d5ed153 11445 addr = remote_address_masked (addr);
96baa820 11446 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 11447 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 11448
f6ac5f3d 11449 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 11450 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 11451
f6ac5f3d 11452 if (can_run_breakpoint_commands ())
d3ce09f5
SS
11453 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11454
6d820c5c 11455 putpkt (rs->buf);
aa7b36b8 11456 getpkt (&rs->buf);
96baa820 11457
94a94c90
AH
11458 packet_result result = m_features.packet_ok (rs->buf, PACKET_Z1);
11459 switch (result.status ())
d471ea57
AC
11460 {
11461 case PACKET_ERROR:
94a94c90 11462 error (_("Remote failure reply: %s"), result.err_msg ());
d471ea57
AC
11463 case PACKET_UNKNOWN:
11464 return -1;
11465 case PACKET_OK:
11466 return 0;
11467 }
f34652de 11468 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
11469}
11470
d471ea57 11471
f6ac5f3d
PA
11472int
11473remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11474 struct bp_target_info *bp_tgt)
96baa820 11475{
8181d85f 11476 CORE_ADDR addr;
d01949b6 11477 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11478 char *p = rs->buf.data ();
11479 char *endbuf = p + get_remote_packet_size ();
c8189ed1 11480
ff52c073 11481 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 11482 return -1;
802188a7 11483
28439a30
PA
11484 /* Make sure the remote is pointing at the right process, if
11485 necessary. */
99d9c3b9 11486 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
28439a30
PA
11487 set_general_process ();
11488
96baa820
JM
11489 *(p++) = 'z';
11490 *(p++) = '1';
11491 *(p++) = ',';
802188a7 11492
8181d85f 11493 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 11494 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 11495 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 11496
6d820c5c 11497 putpkt (rs->buf);
aa7b36b8 11498 getpkt (&rs->buf);
802188a7 11499
94a94c90 11500 switch ((m_features.packet_ok (rs->buf, PACKET_Z1)).status ())
d471ea57
AC
11501 {
11502 case PACKET_ERROR:
11503 case PACKET_UNKNOWN:
11504 return -1;
11505 case PACKET_OK:
11506 return 0;
11507 }
f34652de 11508 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
96baa820 11509}
96baa820 11510
4a5e7a5b
PA
11511/* Verify memory using the "qCRC:" request. */
11512
f6ac5f3d
PA
11513int
11514remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
11515{
11516 struct remote_state *rs = get_remote_state ();
11517 unsigned long host_crc, target_crc;
11518 char *tmp;
11519
936d2992
PA
11520 /* It doesn't make sense to use qCRC if the remote target is
11521 connected but not running. */
55f6301a 11522 if (target_has_execution ()
ff52c073 11523 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
936d2992 11524 {
7e9d8a36 11525 enum packet_status status;
28439a30 11526
936d2992
PA
11527 /* Make sure the remote is pointing at the right process. */
11528 set_general_process ();
4a5e7a5b 11529
936d2992 11530 /* FIXME: assumes lma can fit into long. */
8d64371b 11531 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
936d2992
PA
11532 (long) lma, (long) size);
11533 putpkt (rs->buf);
4a5e7a5b 11534
936d2992
PA
11535 /* Be clever; compute the host_crc before waiting for target
11536 reply. */
11537 host_crc = xcrc32 (data, size, 0xffffffff);
11538
aa7b36b8 11539 getpkt (&rs->buf);
4a5e7a5b 11540
94a94c90 11541 status = (m_features.packet_ok (rs->buf, PACKET_qCRC)).status ();
7e9d8a36 11542 if (status == PACKET_ERROR)
936d2992 11543 return -1;
7e9d8a36 11544 else if (status == PACKET_OK)
936d2992
PA
11545 {
11546 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11547 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 11548
936d2992
PA
11549 return (host_crc == target_crc);
11550 }
11551 }
4a5e7a5b 11552
f6ac5f3d 11553 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
11554}
11555
c906108c
SS
11556/* compare-sections command
11557
11558 With no arguments, compares each loadable section in the exec bfd
11559 with the same memory range on the target, and reports mismatches.
4a5e7a5b 11560 Useful for verifying the image on the target against the exec file. */
e514a9d6 11561
c906108c 11562static void
ac88e2de 11563compare_sections_command (const char *args, int from_tty)
c906108c
SS
11564{
11565 asection *s;
ce359b09 11566 const char *sectname;
c906108c
SS
11567 bfd_size_type size;
11568 bfd_vma lma;
11569 int matched = 0;
11570 int mismatched = 0;
4a5e7a5b 11571 int res;
95cf3b38 11572 int read_only = 0;
c906108c 11573
7e10abd1 11574 if (!current_program_space->exec_bfd ())
8a3fe4f8 11575 error (_("command cannot be used without an exec file"));
c906108c 11576
95cf3b38
DT
11577 if (args != NULL && strcmp (args, "-r") == 0)
11578 {
11579 read_only = 1;
11580 args = NULL;
11581 }
11582
7e10abd1 11583 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
c906108c
SS
11584 {
11585 if (!(s->flags & SEC_LOAD))
0df8b418 11586 continue; /* Skip non-loadable section. */
c906108c 11587
95cf3b38
DT
11588 if (read_only && (s->flags & SEC_READONLY) == 0)
11589 continue; /* Skip writeable sections */
11590
fd361982 11591 size = bfd_section_size (s);
c906108c 11592 if (size == 0)
0df8b418 11593 continue; /* Skip zero-length section. */
c906108c 11594
fd361982 11595 sectname = bfd_section_name (s);
c906108c 11596 if (args && strcmp (args, sectname) != 0)
0df8b418 11597 continue; /* Not the section selected by user. */
c906108c 11598
0df8b418 11599 matched = 1; /* Do this section. */
c906108c 11600 lma = s->lma;
c906108c 11601
b80406ac 11602 gdb::byte_vector sectdata (size);
7e10abd1
TT
11603 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11604 sectdata.data (), 0, size);
c906108c 11605
b80406ac 11606 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
11607
11608 if (res == -1)
5af949e3 11609 error (_("target memory fault, section %s, range %s -- %s"), sectname,
99d9c3b9
SM
11610 paddress (current_inferior ()->arch (), lma),
11611 paddress (current_inferior ()->arch (), lma + size));
c906108c 11612
6cb06a8c 11613 gdb_printf ("Section %s, range %s -- %s: ", sectname,
99d9c3b9
SM
11614 paddress (current_inferior ()->arch (), lma),
11615 paddress (current_inferior ()->arch (), lma + size));
4a5e7a5b 11616 if (res)
6cb06a8c 11617 gdb_printf ("matched.\n");
c906108c 11618 else
c5aa993b 11619 {
6cb06a8c 11620 gdb_printf ("MIS-MATCHED!\n");
c5aa993b
JM
11621 mismatched++;
11622 }
c906108c
SS
11623 }
11624 if (mismatched > 0)
131287d9
AB
11625 warning (_("One or more sections of the target image does "
11626 "not match the loaded file"));
c906108c 11627 if (args && !matched)
6cb06a8c 11628 gdb_printf (_("No loaded section named '%s'.\n"), args);
c906108c
SS
11629}
11630
0e7f50da
UW
11631/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11632 into remote target. The number of bytes written to the remote
11633 target is returned, or -1 for error. */
11634
6b8edb51
PA
11635target_xfer_status
11636remote_target::remote_write_qxfer (const char *object_name,
11637 const char *annex, const gdb_byte *writebuf,
11638 ULONGEST offset, LONGEST len,
11639 ULONGEST *xfered_len,
ff52c073 11640 const unsigned int which_packet)
0e7f50da
UW
11641{
11642 int i, buf_len;
11643 ULONGEST n;
0e7f50da 11644 struct remote_state *rs = get_remote_state ();
7a78108a 11645 int max_size = get_memory_write_packet_size ();
0e7f50da 11646
ff52c073 11647 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
2ed4b548 11648 return TARGET_XFER_E_IO;
0e7f50da
UW
11649
11650 /* Insert header. */
7a78108a 11651 i = snprintf (rs->buf.data (), max_size,
0e7f50da
UW
11652 "qXfer:%s:write:%s:%s:",
11653 object_name, annex ? annex : "",
9c1f84c9 11654 phex_nz (offset));
0e7f50da
UW
11655 max_size -= (i + 1);
11656
11657 /* Escape as much data as fits into rs->buf. */
7a78108a 11658 buf_len = remote_escape_output
8d64371b 11659 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
0e7f50da 11660
8d64371b 11661 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
aa7b36b8 11662 || getpkt (&rs->buf) < 0
94a94c90 11663 || (m_features.packet_ok (rs->buf, which_packet)).status () != PACKET_OK)
2ed4b548 11664 return TARGET_XFER_E_IO;
0e7f50da 11665
8d64371b 11666 unpack_varlen_hex (rs->buf.data (), &n);
9b409511
YQ
11667
11668 *xfered_len = n;
92ffd475 11669 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
11670}
11671
0876f84a
DJ
11672/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11673 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11674 number of bytes read is returned, or 0 for EOF, or -1 for error.
11675 The number of bytes read may be less than LEN without indicating an
11676 EOF. PACKET is checked and updated to indicate whether the remote
11677 target supports this object. */
11678
6b8edb51
PA
11679target_xfer_status
11680remote_target::remote_read_qxfer (const char *object_name,
11681 const char *annex,
11682 gdb_byte *readbuf, ULONGEST offset,
11683 LONGEST len,
11684 ULONGEST *xfered_len,
ff52c073 11685 const unsigned int which_packet)
0876f84a 11686{
0876f84a 11687 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
11688 LONGEST i, n, packet_len;
11689
ff52c073 11690 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
2ed4b548 11691 return TARGET_XFER_E_IO;
0876f84a
DJ
11692
11693 /* Check whether we've cached an end-of-object packet that matches
11694 this request. */
8e88304f 11695 if (rs->finished_object)
0876f84a 11696 {
8e88304f
TT
11697 if (strcmp (object_name, rs->finished_object) == 0
11698 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11699 && offset == rs->finished_offset)
9b409511
YQ
11700 return TARGET_XFER_EOF;
11701
0876f84a
DJ
11702
11703 /* Otherwise, we're now reading something different. Discard
11704 the cache. */
8e88304f
TT
11705 xfree (rs->finished_object);
11706 xfree (rs->finished_annex);
11707 rs->finished_object = NULL;
11708 rs->finished_annex = NULL;
0876f84a
DJ
11709 }
11710
11711 /* Request only enough to fit in a single packet. The actual data
11712 may not, since we don't know how much of it will need to be escaped;
11713 the target is free to respond with slightly less data. We subtract
11714 five to account for the response type and the protocol frame. */
768adc05 11715 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
8d64371b
TT
11716 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11717 "qXfer:%s:read:%s:%s,%s",
0876f84a 11718 object_name, annex ? annex : "",
9c1f84c9
TV
11719 phex_nz (offset),
11720 phex_nz (n));
0876f84a
DJ
11721 i = putpkt (rs->buf);
11722 if (i < 0)
2ed4b548 11723 return TARGET_XFER_E_IO;
0876f84a
DJ
11724
11725 rs->buf[0] = '\0';
aa7b36b8 11726 packet_len = getpkt (&rs->buf);
ff52c073 11727 if (packet_len < 0
94a94c90 11728 || m_features.packet_ok (rs->buf, which_packet).status () != PACKET_OK)
2ed4b548 11729 return TARGET_XFER_E_IO;
0876f84a
DJ
11730
11731 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8d64371b 11732 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
0876f84a
DJ
11733
11734 /* 'm' means there is (or at least might be) more data after this
11735 batch. That does not make sense unless there's at least one byte
11736 of data in this reply. */
11737 if (rs->buf[0] == 'm' && packet_len == 1)
11738 error (_("Remote qXfer reply contained no data."));
11739
11740 /* Got some data. */
8d64371b 11741 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
bc20a4af 11742 packet_len - 1, readbuf, n);
0876f84a
DJ
11743
11744 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
11745 or possibly empty. If we have the final block of a non-empty
11746 object, record this fact to bypass a subsequent partial read. */
11747 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 11748 {
8e88304f
TT
11749 rs->finished_object = xstrdup (object_name);
11750 rs->finished_annex = xstrdup (annex ? annex : "");
11751 rs->finished_offset = offset + i;
0876f84a
DJ
11752 }
11753
9b409511
YQ
11754 if (i == 0)
11755 return TARGET_XFER_EOF;
11756 else
11757 {
11758 *xfered_len = i;
11759 return TARGET_XFER_OK;
11760 }
0876f84a
DJ
11761}
11762
f6ac5f3d
PA
11763enum target_xfer_status
11764remote_target::xfer_partial (enum target_object object,
11765 const char *annex, gdb_byte *readbuf,
11766 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11767 ULONGEST *xfered_len)
c906108c 11768{
82f73884 11769 struct remote_state *rs;
c906108c 11770 int i;
6d820c5c 11771 char *p2;
1e3ff5ad 11772 char query_type;
99d9c3b9
SM
11773 int unit_size
11774 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
c906108c 11775
e6e4e701 11776 set_remote_traceframe ();
82f73884
PA
11777 set_general_thread (inferior_ptid);
11778
11779 rs = get_remote_state ();
11780
b2182ed2 11781 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
11782 if (object == TARGET_OBJECT_MEMORY)
11783 {
2d717e4f
DJ
11784 /* If the remote target is connected but not running, we should
11785 pass this request down to a lower stratum (e.g. the executable
11786 file). */
55f6301a 11787 if (!target_has_execution ())
9b409511 11788 return TARGET_XFER_EOF;
2d717e4f 11789
21e3b9b9 11790 if (writebuf != NULL)
124e13d9
SM
11791 return remote_write_bytes (offset, writebuf, len, unit_size,
11792 xfered_len);
21e3b9b9 11793 else
6b8edb51 11794 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 11795 xfered_len);
21e3b9b9
DJ
11796 }
11797
4aa995e1
PA
11798 /* Handle extra signal info using qxfer packets. */
11799 if (object == TARGET_OBJECT_SIGNAL_INFO)
11800 {
11801 if (readbuf)
f6ac5f3d 11802 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
ff52c073 11803 xfered_len, PACKET_qXfer_siginfo_read);
4aa995e1 11804 else
ff52c073
CS
11805 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11806 xfered_len, PACKET_qXfer_siginfo_write);
4aa995e1
PA
11807 }
11808
0fb4aa4b
PA
11809 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11810 {
11811 if (readbuf)
f6ac5f3d 11812 return remote_read_qxfer ("statictrace", annex,
9b409511 11813 readbuf, offset, len, xfered_len,
ff52c073 11814 PACKET_qXfer_statictrace_read);
0fb4aa4b 11815 else
2ed4b548 11816 return TARGET_XFER_E_IO;
0fb4aa4b
PA
11817 }
11818
a76d924d
DJ
11819 /* Only handle flash writes. */
11820 if (writebuf != NULL)
11821 {
a76d924d
DJ
11822 switch (object)
11823 {
11824 case TARGET_OBJECT_FLASH:
6b8edb51 11825 return remote_flash_write (offset, len, xfered_len,
9b409511 11826 writebuf);
a76d924d
DJ
11827
11828 default:
2ed4b548 11829 return TARGET_XFER_E_IO;
a76d924d
DJ
11830 }
11831 }
4b8a223f 11832
1e3ff5ad
AC
11833 /* Map pre-existing objects onto letters. DO NOT do this for new
11834 objects!!! Instead specify new query packets. */
11835 switch (object)
c906108c 11836 {
1e3ff5ad
AC
11837 case TARGET_OBJECT_AVR:
11838 query_type = 'R';
11839 break;
802188a7
RM
11840
11841 case TARGET_OBJECT_AUXV:
0876f84a 11842 gdb_assert (annex == NULL);
ff52c073
CS
11843 return remote_read_qxfer
11844 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
802188a7 11845
23181151
DJ
11846 case TARGET_OBJECT_AVAILABLE_FEATURES:
11847 return remote_read_qxfer
f6ac5f3d 11848 ("features", annex, readbuf, offset, len, xfered_len,
ff52c073 11849 PACKET_qXfer_features);
23181151 11850
cfa9d6d9
DJ
11851 case TARGET_OBJECT_LIBRARIES:
11852 return remote_read_qxfer
f6ac5f3d 11853 ("libraries", annex, readbuf, offset, len, xfered_len,
ff52c073 11854 PACKET_qXfer_libraries);
cfa9d6d9 11855
2268b414
JK
11856 case TARGET_OBJECT_LIBRARIES_SVR4:
11857 return remote_read_qxfer
f6ac5f3d 11858 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
ff52c073 11859 PACKET_qXfer_libraries_svr4);
2268b414 11860
fd79ecee
DJ
11861 case TARGET_OBJECT_MEMORY_MAP:
11862 gdb_assert (annex == NULL);
ff52c073
CS
11863 return remote_read_qxfer
11864 ("memory-map", annex, readbuf, offset, len, xfered_len,
11865 PACKET_qXfer_memory_map);
fd79ecee 11866
07e059b5
VP
11867 case TARGET_OBJECT_OSDATA:
11868 /* Should only get here if we're connected. */
5d93a237 11869 gdb_assert (rs->remote_desc);
07e059b5 11870 return remote_read_qxfer
f6ac5f3d 11871 ("osdata", annex, readbuf, offset, len, xfered_len,
ff52c073 11872 PACKET_qXfer_osdata);
07e059b5 11873
dc146f7c
VP
11874 case TARGET_OBJECT_THREADS:
11875 gdb_assert (annex == NULL);
ff52c073
CS
11876 return remote_read_qxfer
11877 ("threads", annex, readbuf, offset, len, xfered_len,
11878 PACKET_qXfer_threads);
dc146f7c 11879
b3b9301e
PA
11880 case TARGET_OBJECT_TRACEFRAME_INFO:
11881 gdb_assert (annex == NULL);
11882 return remote_read_qxfer
f6ac5f3d 11883 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
ff52c073 11884 PACKET_qXfer_traceframe_info);
78d85199
YQ
11885
11886 case TARGET_OBJECT_FDPIC:
ff52c073
CS
11887 return remote_read_qxfer
11888 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
169081d0
TG
11889
11890 case TARGET_OBJECT_OPENVMS_UIB:
ff52c073
CS
11891 return remote_read_qxfer
11892 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
169081d0 11893
9accd112 11894 case TARGET_OBJECT_BTRACE:
ff52c073
CS
11895 return remote_read_qxfer
11896 ("btrace", annex, readbuf, offset, len, xfered_len,
11897 PACKET_qXfer_btrace);
9accd112 11898
f4abbc16 11899 case TARGET_OBJECT_BTRACE_CONF:
ff52c073
CS
11900 return remote_read_qxfer
11901 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11902 PACKET_qXfer_btrace_conf);
f4abbc16 11903
c78fa86a 11904 case TARGET_OBJECT_EXEC_FILE:
ff52c073
CS
11905 return remote_read_qxfer
11906 ("exec-file", annex, readbuf, offset, len, xfered_len,
11907 PACKET_qXfer_exec_file);
c78fa86a 11908
1e3ff5ad 11909 default:
2ed4b548 11910 return TARGET_XFER_E_IO;
c906108c
SS
11911 }
11912
0df8b418 11913 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11914 large enough let the caller deal with it. */
ea9c271d 11915 if (len < get_remote_packet_size ())
2ed4b548 11916 return TARGET_XFER_E_IO;
ea9c271d 11917 len = get_remote_packet_size ();
1e3ff5ad 11918
23860348 11919 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11920 if (!rs->remote_desc)
8a3fe4f8 11921 error (_("remote query is only available after target open"));
c906108c 11922
1e3ff5ad 11923 gdb_assert (annex != NULL);
4b8a223f 11924 gdb_assert (readbuf != NULL);
c906108c 11925
8d64371b 11926 p2 = rs->buf.data ();
c906108c
SS
11927 *p2++ = 'q';
11928 *p2++ = query_type;
11929
23860348
MS
11930 /* We used one buffer char for the remote protocol q command and
11931 another for the query type. As the remote protocol encapsulation
11932 uses 4 chars plus one extra in case we are debugging
11933 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11934 string. */
c906108c 11935 i = 0;
ea9c271d 11936 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11937 {
1e3ff5ad
AC
11938 /* Bad caller may have sent forbidden characters. */
11939 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11940 *p2++ = annex[i];
c906108c
SS
11941 i++;
11942 }
1e3ff5ad
AC
11943 *p2 = '\0';
11944 gdb_assert (annex[i] == '\0');
c906108c 11945
6d820c5c 11946 i = putpkt (rs->buf);
c5aa993b 11947 if (i < 0)
2ed4b548 11948 return TARGET_XFER_E_IO;
c906108c 11949
aa7b36b8 11950 getpkt (&rs->buf);
8d64371b 11951 strcpy ((char *) readbuf, rs->buf.data ());
c906108c 11952
9b409511 11953 *xfered_len = strlen ((char *) readbuf);
92ffd475 11954 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11955}
11956
09c98b44
DB
11957/* Implementation of to_get_memory_xfer_limit. */
11958
f6ac5f3d
PA
11959ULONGEST
11960remote_target::get_memory_xfer_limit ()
09c98b44
DB
11961{
11962 return get_memory_write_packet_size ();
11963}
11964
f6ac5f3d
PA
11965int
11966remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11967 const gdb_byte *pattern, ULONGEST pattern_len,
11968 CORE_ADDR *found_addrp)
08388c79 11969{
99d9c3b9 11970 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
08388c79
DE
11971 struct remote_state *rs = get_remote_state ();
11972 int max_size = get_memory_write_packet_size ();
ff52c073 11973
0df8b418
MS
11974 /* Number of packet bytes used to encode the pattern;
11975 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11976 int escaped_pattern_len;
0df8b418 11977 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11978 int used_pattern_len;
11979 int i;
11980 int found;
11981 ULONGEST found_addr;
11982
5bd5fecd 11983 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
4a72de73
TT
11984 {
11985 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11986 == len);
11987 };
11988
7cc244de 11989 /* Don't go to the target if we don't have to. This is done before
ff52c073
CS
11990 checking packet_support to avoid the possibility that a success for this
11991 edge case means the facility works in general. */
08388c79
DE
11992 if (pattern_len > search_space_len)
11993 return 0;
11994 if (pattern_len == 0)
11995 {
11996 *found_addrp = start_addr;
11997 return 1;
11998 }
11999
12000 /* If we already know the packet isn't supported, fall back to the simple
12001 way of searching memory. */
12002
ff52c073 12003 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
08388c79
DE
12004 {
12005 /* Target doesn't provided special support, fall back and use the
12006 standard support (copy memory and do the search here). */
4a72de73 12007 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
12008 pattern, pattern_len, found_addrp);
12009 }
12010
28439a30
PA
12011 /* Make sure the remote is pointing at the right process. */
12012 set_general_process ();
12013
08388c79 12014 /* Insert header. */
7a78108a 12015 i = snprintf (rs->buf.data (), max_size,
08388c79 12016 "qSearch:memory:%s;%s;",
5af949e3 12017 phex_nz (start_addr, addr_size),
9c1f84c9 12018 phex_nz (search_space_len));
08388c79
DE
12019 max_size -= (i + 1);
12020
12021 /* Escape as much data as fits into rs->buf. */
12022 escaped_pattern_len =
8d64371b
TT
12023 remote_escape_output (pattern, pattern_len, 1,
12024 (gdb_byte *) rs->buf.data () + i,
08388c79
DE
12025 &used_pattern_len, max_size);
12026
12027 /* Bail if the pattern is too large. */
12028 if (used_pattern_len != pattern_len)
9b20d036 12029 error (_("Pattern is too large to transmit to remote target."));
08388c79 12030
8d64371b 12031 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
aa7b36b8 12032 || getpkt (&rs->buf) < 0
94a94c90
AH
12033 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory).status ()
12034 != PACKET_OK)
08388c79
DE
12035 {
12036 /* The request may not have worked because the command is not
12037 supported. If so, fall back to the simple way. */
ff52c073 12038 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
08388c79 12039 {
4a72de73 12040 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
12041 pattern, pattern_len, found_addrp);
12042 }
12043 return -1;
12044 }
12045
12046 if (rs->buf[0] == '0')
12047 found = 0;
12048 else if (rs->buf[0] == '1')
12049 {
12050 found = 1;
12051 if (rs->buf[1] != ',')
8d64371b
TT
12052 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
12053 unpack_varlen_hex (&rs->buf[2], &found_addr);
08388c79
DE
12054 *found_addrp = found_addr;
12055 }
12056 else
8d64371b 12057 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
08388c79
DE
12058
12059 return found;
12060}
12061
f6ac5f3d
PA
12062void
12063remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 12064{
d01949b6 12065 struct remote_state *rs = get_remote_state ();
8d64371b 12066 char *p = rs->buf.data ();
96baa820 12067
5d93a237 12068 if (!rs->remote_desc)
8a3fe4f8 12069 error (_("remote rcmd is only available after target open"));
96baa820 12070
23860348 12071 /* Send a NULL command across as an empty command. */
7be570e7
JM
12072 if (command == NULL)
12073 command = "";
12074
bd217f6d
CW
12075 /* It might be important for this command to know the current thread. */
12076 set_general_thread (inferior_ptid);
12077
23860348 12078 /* The query prefix. */
8d64371b
TT
12079 strcpy (rs->buf.data (), "qRcmd,");
12080 p = strchr (rs->buf.data (), '\0');
96baa820 12081
8d64371b 12082 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
3e43a32a 12083 > get_remote_packet_size ())
8a3fe4f8 12084 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 12085
23860348 12086 /* Encode the actual command. */
a30bf1f1 12087 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 12088
6d820c5c 12089 if (putpkt (rs->buf) < 0)
8a3fe4f8 12090 error (_("Communication problem with target."));
96baa820
JM
12091
12092 /* get/display the response */
12093 while (1)
12094 {
2e9f7625
DJ
12095 char *buf;
12096
00bf0b85 12097 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 12098 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 12099 rs->buf[0] = '\0';
aa7b36b8 12100 if (getpkt (&rs->buf) == -1)
7a78108a 12101 {
dda83cd7
SM
12102 /* Timeout. Continue to (try to) read responses.
12103 This is better than stopping with an error, assuming the stub
12104 is still executing the (long) monitor command.
12105 If needed, the user can interrupt gdb using C-c, obtaining
12106 an effect similar to stop on timeout. */
12107 continue;
12108 }
8d64371b 12109 buf = rs->buf.data ();
96baa820
JM
12110 if (buf[0] == 'O' && buf[1] != 'K')
12111 {
c6100129
TT
12112 /* 'O' message from stub. */
12113 remote_console_output (buf + 1, outbuf);
96baa820
JM
12114 continue;
12115 }
ddb3f3d8 12116 packet_result result = packet_check_result (buf);
c541d537 12117 switch (result.status ())
96baa820 12118 {
c541d537
AB
12119 case PACKET_UNKNOWN:
12120 error (_("Target does not support this command."));
12121 case PACKET_ERROR:
12122 error (_("Protocol error with Rcmd: %s."), result.err_msg ());
12123 case PACKET_OK:
12124 break;
12125 }
a744cf53 12126
c541d537
AB
12127 if (strcmp (buf, "OK") != 0)
12128 {
12129 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
12130 {
12131 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
12132 gdb_putc (c, outbuf);
12133 }
96baa820
JM
12134 }
12135 break;
12136 }
12137}
12138
f6ac5f3d
PA
12139std::vector<mem_region>
12140remote_target::memory_map ()
fd79ecee 12141{
a664f67e 12142 std::vector<mem_region> result;
6b09f134 12143 std::optional<gdb::char_vector> text
328d42d8
SM
12144 = target_read_stralloc (current_inferior ()->top_target (),
12145 TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
12146
12147 if (text)
9018be22 12148 result = parse_memory_map (text->data ());
fd79ecee
DJ
12149
12150 return result;
12151}
12152
e5b176f2
AB
12153/* Set of callbacks used to implement the 'maint packet' command. */
12154
12155struct cli_packet_command_callbacks : public send_remote_packet_callbacks
c906108c 12156{
e5b176f2
AB
12157 /* Called before the packet is sent. BUF is the packet content before
12158 the protocol specific prefix, suffix, and escaping is added. */
c906108c 12159
e5b176f2
AB
12160 void sending (gdb::array_view<const char> &buf) override
12161 {
0426ad51 12162 gdb_puts ("sending: ");
e5b176f2 12163 print_packet (buf);
0426ad51 12164 gdb_puts ("\n");
e5b176f2 12165 }
c906108c 12166
e5b176f2
AB
12167 /* Called with BUF, the reply from the remote target. */
12168
12169 void received (gdb::array_view<const char> &buf) override
12170 {
0426ad51 12171 gdb_puts ("received: \"");
e5b176f2 12172 print_packet (buf);
0426ad51 12173 gdb_puts ("\"\n");
e5b176f2
AB
12174 }
12175
12176private:
12177
12178 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
12179 '\x??' with '??' replaced by the hexadecimal value of the byte. */
12180
12181 static void
12182 print_packet (gdb::array_view<const char> &buf)
12183 {
12184 string_file stb;
12185
12186 for (int i = 0; i < buf.size (); ++i)
12187 {
12188 gdb_byte c = buf[i];
12189 if (isprint (c))
a11ac3b3 12190 gdb_putc (c, &stb);
e5b176f2 12191 else
6cb06a8c 12192 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
e5b176f2
AB
12193 }
12194
0426ad51 12195 gdb_puts (stb.string ().c_str ());
e5b176f2
AB
12196 }
12197};
12198
12199/* See remote.h. */
6b8edb51
PA
12200
12201void
e5b176f2
AB
12202send_remote_packet (gdb::array_view<const char> &buf,
12203 send_remote_packet_callbacks *callbacks)
6b8edb51 12204{
e5b176f2
AB
12205 if (buf.size () == 0 || buf.data ()[0] == '\0')
12206 error (_("a remote packet must not be empty"));
c906108c 12207
e5b176f2
AB
12208 remote_target *remote = get_current_remote_target ();
12209 if (remote == nullptr)
12210 error (_("packets can only be sent to a remote target"));
c906108c 12211
e5b176f2 12212 callbacks->sending (buf);
6b8edb51 12213
e5b176f2
AB
12214 remote->putpkt_binary (buf.data (), buf.size ());
12215 remote_state *rs = remote->get_remote_state ();
aa7b36b8 12216 int bytes = remote->getpkt (&rs->buf);
e5b176f2
AB
12217
12218 if (bytes < 0)
12219 error (_("error while fetching packet from remote target"));
12220
12221 gdb::array_view<const char> view (&rs->buf[0], bytes);
12222 callbacks->received (view);
12223}
12224
12225/* Entry point for the 'maint packet' command. */
12226
12227static void
12228cli_packet_command (const char *args, int from_tty)
12229{
12230 cli_packet_command_callbacks cb;
12231 gdb::array_view<const char> view
12232 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
12233 send_remote_packet (view, &cb);
c906108c
SS
12234}
12235
12236#if 0
23860348 12237/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 12238
a14ed312 12239static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 12240
a14ed312 12241static void threadset_test_cmd (char *cmd, int tty);
c906108c 12242
a14ed312 12243static void threadalive_test (char *cmd, int tty);
c906108c 12244
a14ed312 12245static void threadlist_test_cmd (char *cmd, int tty);
c906108c 12246
23860348 12247int get_and_display_threadinfo (threadref *ref);
c906108c 12248
a14ed312 12249static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 12250
23860348 12251static int thread_display_step (threadref *ref, void *context);
c906108c 12252
a14ed312 12253static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 12254
a14ed312 12255static void init_remote_threadtests (void);
c906108c 12256
23860348 12257#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
12258
12259static void
0b39b52e 12260threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
12261{
12262 int sample_thread = SAMPLE_THREAD;
12263
6cb06a8c 12264 gdb_printf (_("Remote threadset test\n"));
79d7f229 12265 set_general_thread (sample_thread);
c906108c
SS
12266}
12267
12268
12269static void
0b39b52e 12270threadalive_test (const char *cmd, int tty)
c906108c
SS
12271{
12272 int sample_thread = SAMPLE_THREAD;
e99b03dc 12273 int pid = inferior_ptid.pid ();
fd79271b 12274 ptid_t ptid = ptid_t (pid, sample_thread, 0);
c906108c 12275
79d7f229 12276 if (remote_thread_alive (ptid))
6cb06a8c 12277 gdb_printf ("PASS: Thread alive test\n");
c906108c 12278 else
6cb06a8c 12279 gdb_printf ("FAIL: Thread alive test\n");
c906108c
SS
12280}
12281
23860348 12282void output_threadid (char *title, threadref *ref);
c906108c
SS
12283
12284void
fba45db2 12285output_threadid (char *title, threadref *ref)
c906108c
SS
12286{
12287 char hexid[20];
12288
405feb71 12289 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
c906108c 12290 hexid[16] = 0;
6cb06a8c 12291 gdb_printf ("%s %s\n", title, (&hexid[0]));
c906108c
SS
12292}
12293
12294static void
0b39b52e 12295threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
12296{
12297 int startflag = 1;
12298 threadref nextthread;
12299 int done, result_count;
12300 threadref threadlist[3];
12301
6cb06a8c 12302 gdb_printf ("Remote Threadlist test\n");
c906108c
SS
12303 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
12304 &result_count, &threadlist[0]))
6cb06a8c 12305 gdb_printf ("FAIL: threadlist test\n");
c906108c
SS
12306 else
12307 {
12308 threadref *scan = threadlist;
12309 threadref *limit = scan + result_count;
12310
12311 while (scan < limit)
12312 output_threadid (" thread ", scan++);
12313 }
12314}
12315
12316void
fba45db2 12317display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
12318{
12319 output_threadid ("Threadid: ", &info->threadid);
6cb06a8c
TT
12320 gdb_printf ("Name: %s\n ", info->shortname);
12321 gdb_printf ("State: %s\n", info->display);
12322 gdb_printf ("other: %s\n\n", info->more_display);
c906108c
SS
12323}
12324
12325int
fba45db2 12326get_and_display_threadinfo (threadref *ref)
c906108c
SS
12327{
12328 int result;
12329 int set;
12330 struct gdb_ext_thread_info threadinfo;
12331
12332 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
12333 | TAG_MOREDISPLAY | TAG_DISPLAY;
12334 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
12335 display_thread_info (&threadinfo);
12336 return result;
12337}
12338
12339static void
0b39b52e 12340threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
12341{
12342 int athread = SAMPLE_THREAD;
12343 threadref thread;
12344 int set;
12345
12346 int_to_threadref (&thread, athread);
6cb06a8c 12347 gdb_printf ("Remote Threadinfo test\n");
c906108c 12348 if (!get_and_display_threadinfo (&thread))
6cb06a8c 12349 gdb_printf ("FAIL cannot get thread info\n");
c906108c
SS
12350}
12351
12352static int
fba45db2 12353thread_display_step (threadref *ref, void *context)
c906108c
SS
12354{
12355 /* output_threadid(" threadstep ",ref); *//* simple test */
12356 return get_and_display_threadinfo (ref);
12357}
12358
12359static void
0b39b52e 12360threadlist_update_test_cmd (const char *cmd, int tty)
c906108c 12361{
6cb06a8c 12362 gdb_printf ("Remote Threadlist update test\n");
c906108c
SS
12363 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
12364}
12365
12366static void
12367init_remote_threadtests (void)
12368{
3e43a32a
MS
12369 add_com ("tlist", class_obscure, threadlist_test_cmd,
12370 _("Fetch and print the remote list of "
590042fc 12371 "thread identifiers, one pkt only."));
c906108c 12372 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
590042fc 12373 _("Fetch and display info about one thread."));
c906108c 12374 add_com ("tset", class_obscure, threadset_test_cmd,
590042fc 12375 _("Test setting to a different thread."));
c906108c 12376 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
590042fc 12377 _("Iterate through updating all remote thread info."));
c906108c 12378 add_com ("talive", class_obscure, threadalive_test,
590042fc 12379 _("Remote thread alive test."));
c906108c
SS
12380}
12381
12382#endif /* 0 */
12383
a068643d 12384/* Convert a thread ID to a string. */
f3fb8c85 12385
a068643d 12386std::string
f6ac5f3d 12387remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 12388{
d7e15655 12389 if (ptid == null_ptid)
7cee1e54 12390 return normal_pid_to_str (ptid);
0e998d96 12391 else if (ptid.is_pid ())
ecd0ada5
PA
12392 {
12393 /* Printing an inferior target id. */
12394
12395 /* When multi-process extensions are off, there's no way in the
12396 remote protocol to know the remote process id, if there's any
12397 at all. There's one exception --- when we're connected with
12398 target extended-remote, and we manually attached to a process
12399 with "attach PID". We don't record anywhere a flag that
12400 allows us to distinguish that case from the case of
12401 connecting with extended-remote and the stub already being
12402 attached to a process, and reporting yes to qAttached, hence
12403 no smart special casing here. */
ff52c073 12404 if (!m_features.remote_multi_process_p ())
a068643d 12405 return "Remote target";
ecd0ada5
PA
12406
12407 return normal_pid_to_str (ptid);
82f73884 12408 }
ecd0ada5 12409 else
79d7f229 12410 {
d7e15655 12411 if (magic_null_ptid == ptid)
a068643d 12412 return "Thread <main>";
1dd0c745
TBA
12413
12414 thread_info *thread = this->find_thread (ptid);
12415 if ((thread != nullptr) && (thread->priv != nullptr))
12416 {
12417 remote_thread_info *priv = get_remote_thread_info (thread);
12418 if (!priv->id_str.empty ())
12419 return priv->id_str;
12420 }
12421
12422 if (m_features.remote_multi_process_p ())
e38504b3 12423 if (ptid.lwp () == 0)
de0d863e
DB
12424 return normal_pid_to_str (ptid);
12425 else
a068643d
TT
12426 return string_printf ("Thread %d.%ld",
12427 ptid.pid (), ptid.lwp ());
ecd0ada5 12428 else
a068643d 12429 return string_printf ("Thread %ld", ptid.lwp ());
79d7f229 12430 }
f3fb8c85
MS
12431}
12432
38691318
KB
12433/* Get the address of the thread local variable in OBJFILE which is
12434 stored at OFFSET within the thread local storage for thread PTID. */
12435
f6ac5f3d
PA
12436CORE_ADDR
12437remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12438 CORE_ADDR offset)
38691318 12439{
ff52c073 12440 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
12441 {
12442 struct remote_state *rs = get_remote_state ();
8d64371b
TT
12443 char *p = rs->buf.data ();
12444 char *endp = p + get_remote_packet_size ();
38691318
KB
12445
12446 strcpy (p, "qGetTLSAddr:");
12447 p += strlen (p);
82f73884 12448 p = write_ptid (p, endp, ptid);
38691318
KB
12449 *p++ = ',';
12450 p += hexnumstr (p, offset);
12451 *p++ = ',';
12452 p += hexnumstr (p, lm);
12453 *p++ = '\0';
12454
6d820c5c 12455 putpkt (rs->buf);
aa7b36b8 12456 getpkt (&rs->buf);
94a94c90
AH
12457 packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12458 if (result.status () == PACKET_OK)
38691318 12459 {
b926417a 12460 ULONGEST addr;
38691318 12461
8d64371b 12462 unpack_varlen_hex (rs->buf.data (), &addr);
b926417a 12463 return addr;
38691318 12464 }
94a94c90 12465 else if (result.status () == PACKET_UNKNOWN)
109c3e39
AC
12466 throw_error (TLS_GENERIC_ERROR,
12467 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 12468 else
109c3e39
AC
12469 throw_error (TLS_GENERIC_ERROR,
12470 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
12471 }
12472 else
109c3e39
AC
12473 throw_error (TLS_GENERIC_ERROR,
12474 _("TLS not supported or disabled on this target"));
38691318
KB
12475 /* Not reached. */
12476 return 0;
12477}
12478
57810aa7 12479bool
f6ac5f3d 12480remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 12481{
ff52c073 12482 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
12483 {
12484 struct remote_state *rs = get_remote_state ();
8d64371b
TT
12485 char *p = rs->buf.data ();
12486 char *endp = p + get_remote_packet_size ();
711e434b
PM
12487
12488 strcpy (p, "qGetTIBAddr:");
12489 p += strlen (p);
12490 p = write_ptid (p, endp, ptid);
12491 *p++ = '\0';
12492
12493 putpkt (rs->buf);
aa7b36b8 12494 getpkt (&rs->buf);
94a94c90
AH
12495 packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12496 if (result.status () == PACKET_OK)
711e434b 12497 {
b926417a 12498 ULONGEST val;
8d64371b 12499 unpack_varlen_hex (rs->buf.data (), &val);
711e434b 12500 if (addr)
b926417a 12501 *addr = (CORE_ADDR) val;
57810aa7 12502 return true;
711e434b 12503 }
94a94c90 12504 else if (result.status () == PACKET_UNKNOWN)
df50675d 12505 return false;
711e434b 12506 else
94a94c90
AH
12507 error (_("Remote target failed to process qGetTIBAddr request, %s"),
12508 result.err_msg ());
711e434b 12509 }
df50675d 12510
57810aa7 12511 return false;
711e434b
PM
12512}
12513
29709017
DJ
12514/* Support for inferring a target description based on the current
12515 architecture and the size of a 'g' packet. While the 'g' packet
12516 can have any size (since optional registers can be left off the
12517 end), some sizes are easily recognizable given knowledge of the
12518 approximate architecture. */
12519
12520struct remote_g_packet_guess
12521{
eefce37f
TT
12522 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12523 : bytes (bytes_),
12524 tdesc (tdesc_)
12525 {
12526 }
12527
29709017
DJ
12528 int bytes;
12529 const struct target_desc *tdesc;
12530};
29709017 12531
cb275538 12532struct remote_g_packet_data
29709017 12533{
eefce37f 12534 std::vector<remote_g_packet_guess> guesses;
29709017
DJ
12535};
12536
cb275538
TT
12537static const registry<gdbarch>::key<struct remote_g_packet_data>
12538 remote_g_packet_data_handle;
29709017 12539
cb275538
TT
12540static struct remote_g_packet_data *
12541get_g_packet_data (struct gdbarch *gdbarch)
29709017 12542{
cb275538
TT
12543 struct remote_g_packet_data *data
12544 = remote_g_packet_data_handle.get (gdbarch);
12545 if (data == nullptr)
12546 data = remote_g_packet_data_handle.emplace (gdbarch);
12547 return data;
29709017
DJ
12548}
12549
12550void
12551register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12552 const struct target_desc *tdesc)
12553{
cb275538 12554 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
29709017
DJ
12555
12556 gdb_assert (tdesc != NULL);
12557
eefce37f
TT
12558 for (const remote_g_packet_guess &guess : data->guesses)
12559 if (guess.bytes == bytes)
f34652de 12560 internal_error (_("Duplicate g packet description added for size %d"),
29709017
DJ
12561 bytes);
12562
eefce37f 12563 data->guesses.emplace_back (bytes, tdesc);
29709017
DJ
12564}
12565
eefce37f
TT
12566/* Return true if remote_read_description would do anything on this target
12567 and architecture, false otherwise. */
d962ef82 12568
eefce37f 12569static bool
d962ef82
DJ
12570remote_read_description_p (struct target_ops *target)
12571{
99d9c3b9 12572 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
d962ef82 12573
eefce37f 12574 return !data->guesses.empty ();
d962ef82
DJ
12575}
12576
f6ac5f3d
PA
12577const struct target_desc *
12578remote_target::read_description ()
29709017 12579{
99d9c3b9 12580 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
29709017 12581
d962ef82
DJ
12582 /* Do not try this during initial connection, when we do not know
12583 whether there is a running but stopped thread. */
55f6301a 12584 if (!target_has_execution () || inferior_ptid == null_ptid)
b6a8c27b 12585 return beneath ()->read_description ();
d962ef82 12586
eefce37f 12587 if (!data->guesses.empty ())
29709017 12588 {
29709017
DJ
12589 int bytes = send_g_packet ();
12590
eefce37f
TT
12591 for (const remote_g_packet_guess &guess : data->guesses)
12592 if (guess.bytes == bytes)
12593 return guess.tdesc;
29709017
DJ
12594
12595 /* We discard the g packet. A minor optimization would be to
12596 hold on to it, and fill the register cache once we have selected
12597 an architecture, but it's too tricky to do safely. */
12598 }
12599
b6a8c27b 12600 return beneath ()->read_description ();
29709017
DJ
12601}
12602
a6b151f1
DJ
12603/* Remote file transfer support. This is host-initiated I/O, not
12604 target-initiated; for target-initiated, see remote-fileio.c. */
12605
12606/* If *LEFT is at least the length of STRING, copy STRING to
12607 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12608 decrease *LEFT. Otherwise raise an error. */
12609
12610static void
a121b7c1 12611remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
12612{
12613 int len = strlen (string);
12614
12615 if (len > *left)
12616 error (_("Packet too long for target."));
12617
12618 memcpy (*buffer, string, len);
12619 *buffer += len;
12620 *left -= len;
12621
12622 /* NUL-terminate the buffer as a convenience, if there is
12623 room. */
12624 if (*left)
12625 **buffer = '\0';
12626}
12627
12628/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12629 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12630 decrease *LEFT. Otherwise raise an error. */
12631
12632static void
12633remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12634 int len)
12635{
12636 if (2 * len > *left)
12637 error (_("Packet too long for target."));
12638
12639 bin2hex (bytes, *buffer, len);
12640 *buffer += 2 * len;
12641 *left -= 2 * len;
12642
12643 /* NUL-terminate the buffer as a convenience, if there is
12644 room. */
12645 if (*left)
12646 **buffer = '\0';
12647}
12648
12649/* If *LEFT is large enough, convert VALUE to hex and add it to
12650 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12651 decrease *LEFT. Otherwise raise an error. */
12652
12653static void
12654remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12655{
12656 int len = hexnumlen (value);
12657
12658 if (len > *left)
12659 error (_("Packet too long for target."));
12660
12661 hexnumstr (*buffer, value);
12662 *buffer += len;
12663 *left -= len;
12664
12665 /* NUL-terminate the buffer as a convenience, if there is
12666 room. */
12667 if (*left)
12668 **buffer = '\0';
12669}
12670
12671/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
b872057a 12672 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
a6b151f1
DJ
12673 was included, and *ATTACHMENT to point to the start of the annex
12674 if any. The length of the packet isn't needed here; there may
12675 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12676
12677 Return 0 if the packet could be parsed, -1 if it could not. If
12678 -1 is returned, the other variables may not be initialized. */
12679
12680static int
aa2838cc 12681remote_hostio_parse_result (const char *buffer, int *retcode,
b872057a 12682 fileio_error *remote_errno, const char **attachment)
a6b151f1
DJ
12683{
12684 char *p, *p2;
12685
b872057a 12686 *remote_errno = FILEIO_SUCCESS;
a6b151f1
DJ
12687 *attachment = NULL;
12688
12689 if (buffer[0] != 'F')
12690 return -1;
12691
12692 errno = 0;
12693 *retcode = strtol (&buffer[1], &p, 16);
12694 if (errno != 0 || p == &buffer[1])
12695 return -1;
12696
12697 /* Check for ",errno". */
12698 if (*p == ',')
12699 {
12700 errno = 0;
b872057a 12701 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
a6b151f1
DJ
12702 if (errno != 0 || p + 1 == p2)
12703 return -1;
12704 p = p2;
12705 }
12706
12707 /* Check for ";attachment". If there is no attachment, the
12708 packet should end here. */
12709 if (*p == ';')
12710 {
12711 *attachment = p + 1;
12712 return 0;
12713 }
12714 else if (*p == '\0')
12715 return 0;
12716 else
12717 return -1;
12718}
12719
12720/* Send a prepared I/O packet to the target and read its response.
12721 The prepared packet is in the global RS->BUF before this function
12722 is called, and the answer is there when we return.
12723
12724 COMMAND_BYTES is the length of the request to send, which may include
12725 binary data. WHICH_PACKET is the packet configuration to check
12726 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12727 is set to the error number and -1 is returned. Otherwise the value
12728 returned by the function is returned.
12729
12730 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12731 attachment is expected; an error will be reported if there's a
12732 mismatch. If one is found, *ATTACHMENT will be set to point into
12733 the packet buffer and *ATTACHMENT_LEN will be set to the
12734 attachment's length. */
12735
6b8edb51
PA
12736int
12737remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
b872057a 12738 fileio_error *remote_errno, const char **attachment,
6b8edb51 12739 int *attachment_len)
a6b151f1
DJ
12740{
12741 struct remote_state *rs = get_remote_state ();
12742 int ret, bytes_read;
aa2838cc 12743 const char *attachment_tmp;
a6b151f1 12744
ff52c073 12745 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
12746 {
12747 *remote_errno = FILEIO_ENOSYS;
12748 return -1;
12749 }
12750
8d64371b 12751 putpkt_binary (rs->buf.data (), command_bytes);
aa7b36b8 12752 bytes_read = getpkt (&rs->buf);
a6b151f1
DJ
12753
12754 /* If it timed out, something is wrong. Don't try to parse the
12755 buffer. */
12756 if (bytes_read < 0)
12757 {
12758 *remote_errno = FILEIO_EINVAL;
12759 return -1;
12760 }
12761
94a94c90 12762 switch (m_features.packet_ok (rs->buf, which_packet).status ())
a6b151f1
DJ
12763 {
12764 case PACKET_ERROR:
12765 *remote_errno = FILEIO_EINVAL;
12766 return -1;
12767 case PACKET_UNKNOWN:
12768 *remote_errno = FILEIO_ENOSYS;
12769 return -1;
12770 case PACKET_OK:
12771 break;
12772 }
12773
8d64371b 12774 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
a6b151f1
DJ
12775 &attachment_tmp))
12776 {
12777 *remote_errno = FILEIO_EINVAL;
12778 return -1;
12779 }
12780
fc240bb1
AB
12781 if (*remote_errno != FILEIO_SUCCESS)
12782 return -1;
12783
a6b151f1
DJ
12784 /* Make sure we saw an attachment if and only if we expected one. */
12785 if ((attachment_tmp == NULL && attachment != NULL)
12786 || (attachment_tmp != NULL && attachment == NULL))
12787 {
12788 *remote_errno = FILEIO_EINVAL;
12789 return -1;
12790 }
12791
12792 /* If an attachment was found, it must point into the packet buffer;
12793 work out how many bytes there were. */
12794 if (attachment_tmp != NULL)
12795 {
12796 *attachment = attachment_tmp;
8d64371b 12797 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
a6b151f1
DJ
12798 }
12799
12800 return ret;
12801}
12802
dd194f6b 12803/* See declaration.h. */
80152258 12804
dd194f6b
PA
12805void
12806readahead_cache::invalidate ()
80152258 12807{
dd194f6b 12808 this->fd = -1;
80152258
PA
12809}
12810
dd194f6b 12811/* See declaration.h. */
80152258 12812
dd194f6b
PA
12813void
12814readahead_cache::invalidate_fd (int fd)
80152258 12815{
dd194f6b
PA
12816 if (this->fd == fd)
12817 this->fd = -1;
80152258
PA
12818}
12819
15a201c8
GB
12820/* Set the filesystem remote_hostio functions that take FILENAME
12821 arguments will use. Return 0 on success, or -1 if an error
12822 occurs (and set *REMOTE_ERRNO). */
12823
6b8edb51
PA
12824int
12825remote_target::remote_hostio_set_filesystem (struct inferior *inf,
b872057a 12826 fileio_error *remote_errno)
15a201c8
GB
12827{
12828 struct remote_state *rs = get_remote_state ();
12829 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
8d64371b 12830 char *p = rs->buf.data ();
15a201c8
GB
12831 int left = get_remote_packet_size () - 1;
12832 char arg[9];
12833 int ret;
12834
ff52c073 12835 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
15a201c8
GB
12836 return 0;
12837
12838 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12839 return 0;
12840
12841 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12842
12843 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12844 remote_buffer_add_string (&p, &left, arg);
12845
8d64371b 12846 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
15a201c8
GB
12847 remote_errno, NULL, NULL);
12848
ff52c073 12849 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
15a201c8
GB
12850 return 0;
12851
12852 if (ret == 0)
12853 rs->fs_pid = required_pid;
12854
12855 return ret;
12856}
12857
12e2a5fd 12858/* Implementation of to_fileio_open. */
a6b151f1 12859
6b8edb51
PA
12860int
12861remote_target::remote_hostio_open (inferior *inf, const char *filename,
12862 int flags, int mode, int warn_if_slow,
b872057a 12863 fileio_error *remote_errno)
a6b151f1
DJ
12864{
12865 struct remote_state *rs = get_remote_state ();
8d64371b 12866 char *p = rs->buf.data ();
a6b151f1
DJ
12867 int left = get_remote_packet_size () - 1;
12868
1d6f5804
AB
12869 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12870 return -1;
12871
12872 remote_buffer_add_string (&p, &left, "vFile:open:");
12873
12874 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12875 strlen (filename));
12876 remote_buffer_add_string (&p, &left, ",");
12877
12878 remote_buffer_add_int (&p, &left, flags);
12879 remote_buffer_add_string (&p, &left, ",");
12880
12881 remote_buffer_add_int (&p, &left, mode);
12882
12883 int res = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12884 remote_errno, nullptr, nullptr);
12885
12886 if (warn_if_slow && res != -1)
4313b8c0
GB
12887 {
12888 static int warning_issued = 0;
12889
5260dcf0
AB
12890 gdb_printf (_("Reading %ps from remote target...\n"),
12891 styled_string (file_name_style.style (), filename));
4313b8c0
GB
12892
12893 if (!warning_issued)
12894 {
12895 warning (_("File transfers from remote targets can be slow."
9e69a2e1
TT
12896 " Use \"%ps\" to access files locally"
12897 " instead."),
12898 styled_string (command_style.style (), "set sysroot"));
4313b8c0
GB
12899 warning_issued = 1;
12900 }
12901 }
12902
1d6f5804 12903 return res;
a6b151f1
DJ
12904}
12905
f6ac5f3d
PA
12906int
12907remote_target::fileio_open (struct inferior *inf, const char *filename,
12908 int flags, int mode, int warn_if_slow,
b872057a 12909 fileio_error *remote_errno)
f6ac5f3d 12910{
6b8edb51 12911 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
12912 remote_errno);
12913}
12914
12e2a5fd 12915/* Implementation of to_fileio_pwrite. */
a6b151f1 12916
6b8edb51
PA
12917int
12918remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 12919 ULONGEST offset, fileio_error *remote_errno)
a6b151f1
DJ
12920{
12921 struct remote_state *rs = get_remote_state ();
8d64371b 12922 char *p = rs->buf.data ();
a6b151f1
DJ
12923 int left = get_remote_packet_size ();
12924 int out_len;
12925
dd194f6b 12926 rs->readahead_cache.invalidate_fd (fd);
80152258 12927
a6b151f1
DJ
12928 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12929
12930 remote_buffer_add_int (&p, &left, fd);
12931 remote_buffer_add_string (&p, &left, ",");
12932
12933 remote_buffer_add_int (&p, &left, offset);
12934 remote_buffer_add_string (&p, &left, ",");
12935
124e13d9 12936 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
8d64371b
TT
12937 (get_remote_packet_size ()
12938 - (p - rs->buf.data ())));
a6b151f1 12939
8d64371b 12940 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
a6b151f1
DJ
12941 remote_errno, NULL, NULL);
12942}
12943
f6ac5f3d
PA
12944int
12945remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 12946 ULONGEST offset, fileio_error *remote_errno)
f6ac5f3d 12947{
6b8edb51 12948 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12949}
12950
80152258
PA
12951/* Helper for the implementation of to_fileio_pread. Read the file
12952 from the remote side with vFile:pread. */
a6b151f1 12953
6b8edb51
PA
12954int
12955remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
b872057a 12956 ULONGEST offset, fileio_error *remote_errno)
a6b151f1
DJ
12957{
12958 struct remote_state *rs = get_remote_state ();
8d64371b 12959 char *p = rs->buf.data ();
aa2838cc 12960 const char *attachment;
a6b151f1
DJ
12961 int left = get_remote_packet_size ();
12962 int ret, attachment_len;
12963 int read_len;
12964
12965 remote_buffer_add_string (&p, &left, "vFile:pread:");
12966
12967 remote_buffer_add_int (&p, &left, fd);
12968 remote_buffer_add_string (&p, &left, ",");
12969
12970 remote_buffer_add_int (&p, &left, len);
12971 remote_buffer_add_string (&p, &left, ",");
12972
12973 remote_buffer_add_int (&p, &left, offset);
12974
8d64371b 12975 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
a6b151f1
DJ
12976 remote_errno, &attachment,
12977 &attachment_len);
12978
12979 if (ret < 0)
12980 return ret;
12981
bc20a4af 12982 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12983 read_buf, len);
12984 if (read_len != ret)
12985 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12986
12987 return ret;
12988}
12989
dd194f6b 12990/* See declaration.h. */
80152258 12991
dd194f6b
PA
12992int
12993readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12994 ULONGEST offset)
80152258 12995{
dd194f6b
PA
12996 if (this->fd == fd
12997 && this->offset <= offset
6b19f38a 12998 && offset < this->offset + this->buf.size ())
80152258 12999 {
6b19f38a 13000 ULONGEST max = this->offset + this->buf.size ();
80152258
PA
13001
13002 if (offset + len > max)
13003 len = max - offset;
13004
6b19f38a 13005 memcpy (read_buf, &this->buf[offset - this->offset], len);
80152258
PA
13006 return len;
13007 }
13008
13009 return 0;
13010}
13011
13012/* Implementation of to_fileio_pread. */
13013
6b8edb51
PA
13014int
13015remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 13016 ULONGEST offset, fileio_error *remote_errno)
80152258
PA
13017{
13018 int ret;
13019 struct remote_state *rs = get_remote_state ();
dd194f6b 13020 readahead_cache *cache = &rs->readahead_cache;
80152258 13021
dd194f6b 13022 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
13023 if (ret > 0)
13024 {
13025 cache->hit_count++;
13026
2189c312
SM
13027 remote_debug_printf ("readahead cache hit %s",
13028 pulongest (cache->hit_count));
80152258
PA
13029 return ret;
13030 }
13031
13032 cache->miss_count++;
2189c312
SM
13033
13034 remote_debug_printf ("readahead cache miss %s",
13035 pulongest (cache->miss_count));
80152258
PA
13036
13037 cache->fd = fd;
13038 cache->offset = offset;
6b19f38a 13039 cache->buf.resize (get_remote_packet_size ());
80152258 13040
6b19f38a
TT
13041 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
13042 cache->buf.size (),
80152258
PA
13043 cache->offset, remote_errno);
13044 if (ret <= 0)
13045 {
dd194f6b 13046 cache->invalidate_fd (fd);
80152258
PA
13047 return ret;
13048 }
13049
6b19f38a 13050 cache->buf.resize (ret);
dd194f6b 13051 return cache->pread (fd, read_buf, len, offset);
80152258
PA
13052}
13053
f6ac5f3d
PA
13054int
13055remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 13056 ULONGEST offset, fileio_error *remote_errno)
f6ac5f3d 13057{
6b8edb51 13058 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
13059}
13060
12e2a5fd 13061/* Implementation of to_fileio_close. */
a6b151f1 13062
6b8edb51 13063int
b872057a 13064remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
a6b151f1
DJ
13065{
13066 struct remote_state *rs = get_remote_state ();
8d64371b 13067 char *p = rs->buf.data ();
a6b151f1
DJ
13068 int left = get_remote_packet_size () - 1;
13069
dd194f6b 13070 rs->readahead_cache.invalidate_fd (fd);
80152258 13071
a6b151f1
DJ
13072 remote_buffer_add_string (&p, &left, "vFile:close:");
13073
13074 remote_buffer_add_int (&p, &left, fd);
13075
8d64371b 13076 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
a6b151f1
DJ
13077 remote_errno, NULL, NULL);
13078}
13079
f6ac5f3d 13080int
b872057a 13081remote_target::fileio_close (int fd, fileio_error *remote_errno)
f6ac5f3d 13082{
6b8edb51 13083 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
13084}
13085
12e2a5fd 13086/* Implementation of to_fileio_unlink. */
a6b151f1 13087
6b8edb51
PA
13088int
13089remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
b872057a 13090 fileio_error *remote_errno)
a6b151f1
DJ
13091{
13092 struct remote_state *rs = get_remote_state ();
8d64371b 13093 char *p = rs->buf.data ();
a6b151f1
DJ
13094 int left = get_remote_packet_size () - 1;
13095
15a201c8
GB
13096 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
13097 return -1;
13098
a6b151f1
DJ
13099 remote_buffer_add_string (&p, &left, "vFile:unlink:");
13100
13101 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
13102 strlen (filename));
13103
8d64371b 13104 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
a6b151f1
DJ
13105 remote_errno, NULL, NULL);
13106}
13107
f6ac5f3d
PA
13108int
13109remote_target::fileio_unlink (struct inferior *inf, const char *filename,
b872057a 13110 fileio_error *remote_errno)
f6ac5f3d 13111{
6b8edb51 13112 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
13113}
13114
12e2a5fd 13115/* Implementation of to_fileio_readlink. */
b9e7b9c3 13116
6b09f134 13117std::optional<std::string>
f6ac5f3d 13118remote_target::fileio_readlink (struct inferior *inf, const char *filename,
b872057a 13119 fileio_error *remote_errno)
b9e7b9c3
UW
13120{
13121 struct remote_state *rs = get_remote_state ();
8d64371b 13122 char *p = rs->buf.data ();
aa2838cc 13123 const char *attachment;
b9e7b9c3
UW
13124 int left = get_remote_packet_size ();
13125 int len, attachment_len;
13126 int read_len;
b9e7b9c3 13127
15a201c8 13128 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 13129 return {};
15a201c8 13130
b9e7b9c3
UW
13131 remote_buffer_add_string (&p, &left, "vFile:readlink:");
13132
13133 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
13134 strlen (filename));
13135
8d64371b 13136 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
b9e7b9c3
UW
13137 remote_errno, &attachment,
13138 &attachment_len);
13139
13140 if (len < 0)
e0d3522b 13141 return {};
b9e7b9c3 13142
e0d3522b 13143 std::string ret (len, '\0');
b9e7b9c3 13144
bc20a4af 13145 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 13146 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
13147 if (read_len != len)
13148 error (_("Readlink returned %d, but %d bytes."), len, read_len);
13149
b9e7b9c3
UW
13150 return ret;
13151}
13152
5d560402 13153/* Helper function to handle ::fileio_fstat and ::fileio_lstat result
3055e3d2
AB
13154 processing. When this function is called the remote syscall has been
13155 performed and we know we didn't get an error back.
13156
13157 ATTACHMENT and ATTACHMENT_LEN are the attachment data extracted from the
13158 remote syscall reply. EXPECTED_LEN is the length returned from the
13159 fstat or stat call, this the length of the returned data (in ATTACHMENT)
13160 once it has been decoded. The fstat/stat result (from the ATTACHMENT
13161 data) is to be placed in ST. */
13162
13163static int
5d560402
AB
13164fileio_process_fstat_and_lstat_reply (const char *attachment,
13165 int attachment_len,
13166 int expected_len,
13167 struct stat *st)
3055e3d2
AB
13168{
13169 struct fio_stat fst;
13170
13171 int read_len
13172 = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
13173 (gdb_byte *) &fst, sizeof (fst));
13174
13175 if (read_len != expected_len)
13176 error (_("vFile:fstat returned %d, but %d bytes."),
13177 expected_len, read_len);
13178
13179 if (read_len != sizeof (fst))
13180 error (_("vFile:fstat returned %d bytes, but expecting %d."),
13181 read_len, (int) sizeof (fst));
13182
13183 remote_fileio_to_host_stat (&fst, st);
13184
13185 return 0;
13186}
13187
12e2a5fd 13188/* Implementation of to_fileio_fstat. */
0a93529c 13189
f6ac5f3d 13190int
b872057a 13191remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
0a93529c
GB
13192{
13193 struct remote_state *rs = get_remote_state ();
8d64371b 13194 char *p = rs->buf.data ();
0a93529c
GB
13195 int left = get_remote_packet_size ();
13196 int attachment_len, ret;
aa2838cc 13197 const char *attachment;
0a93529c 13198
464b0089
GB
13199 remote_buffer_add_string (&p, &left, "vFile:fstat:");
13200
13201 remote_buffer_add_int (&p, &left, fd);
13202
8d64371b 13203 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
464b0089
GB
13204 remote_errno, &attachment,
13205 &attachment_len);
13206 if (ret < 0)
0a93529c 13207 {
464b0089
GB
13208 if (*remote_errno != FILEIO_ENOSYS)
13209 return ret;
13210
0a93529c
GB
13211 /* Strictly we should return -1, ENOSYS here, but when
13212 "set sysroot remote:" was implemented in August 2008
13213 BFD's need for a stat function was sidestepped with
13214 this hack. This was not remedied until March 2015
13215 so we retain the previous behavior to avoid breaking
13216 compatibility.
13217
13218 Note that the memset is a March 2015 addition; older
13219 GDBs set st_size *and nothing else* so the structure
13220 would have garbage in all other fields. This might
13221 break something but retaining the previous behavior
13222 here would be just too wrong. */
13223
13224 memset (st, 0, sizeof (struct stat));
13225 st->st_size = INT_MAX;
13226 return 0;
13227 }
13228
5d560402
AB
13229 return fileio_process_fstat_and_lstat_reply (attachment, attachment_len,
13230 ret, st);
3055e3d2 13231}
0a93529c 13232
5d560402 13233/* Implementation of to_fileio_lstat. */
0a93529c 13234
3055e3d2 13235int
5d560402
AB
13236remote_target::fileio_lstat (struct inferior *inf, const char *filename,
13237 struct stat *st, fileio_error *remote_errno)
3055e3d2
AB
13238{
13239 struct remote_state *rs = get_remote_state ();
13240 char *p = rs->buf.data ();
13241 int left = get_remote_packet_size () - 1;
0a93529c 13242
3055e3d2
AB
13243 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
13244 return {};
0a93529c 13245
2c91540a 13246 remote_buffer_add_string (&p, &left, "vFile:lstat:");
3055e3d2
AB
13247
13248 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
13249 strlen (filename));
13250
13251 int attachment_len;
13252 const char *attachment;
2c91540a 13253 int ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_lstat,
3055e3d2
AB
13254 remote_errno, &attachment,
13255 &attachment_len);
13256
13257 /* Unlike ::fileio_fstat, the stat fileio call was added later on, and
13258 has none of the legacy bfd issues, so we can just return the error. */
13259 if (ret < 0)
13260 return ret;
13261
5d560402
AB
13262 return fileio_process_fstat_and_lstat_reply (attachment, attachment_len,
13263 ret, st);
0a93529c
GB
13264}
13265
12e2a5fd 13266/* Implementation of to_filesystem_is_local. */
e3dd7556 13267
57810aa7 13268bool
f6ac5f3d 13269remote_target::filesystem_is_local ()
e3dd7556
GB
13270{
13271 /* Valgrind GDB presents itself as a remote target but works
13272 on the local filesystem: it does not implement remote get
13273 and users are not expected to set a sysroot. To handle
13274 this case we treat the remote filesystem as local if the
13275 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
13276 does not support vFile:open. */
e0700ba4 13277 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
e3dd7556 13278 {
ff52c073 13279 packet_support ps = m_features.packet_support (PACKET_vFile_open);
e3dd7556
GB
13280
13281 if (ps == PACKET_SUPPORT_UNKNOWN)
13282 {
b872057a
SM
13283 int fd;
13284 fileio_error remote_errno;
e3dd7556
GB
13285
13286 /* Try opening a file to probe support. The supplied
13287 filename is irrelevant, we only care about whether
13288 the stub recognizes the packet or not. */
6b8edb51 13289 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 13290 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
13291 &remote_errno);
13292
13293 if (fd >= 0)
6b8edb51 13294 remote_hostio_close (fd, &remote_errno);
e3dd7556 13295
ff52c073 13296 ps = m_features.packet_support (PACKET_vFile_open);
e3dd7556
GB
13297 }
13298
13299 if (ps == PACKET_DISABLE)
13300 {
13301 static int warning_issued = 0;
13302
13303 if (!warning_issued)
13304 {
13305 warning (_("remote target does not support file"
13306 " transfer, attempting to access files"
13307 " from local filesystem."));
13308 warning_issued = 1;
13309 }
13310
57810aa7 13311 return true;
e3dd7556
GB
13312 }
13313 }
13314
57810aa7 13315 return false;
e3dd7556
GB
13316}
13317
a6b151f1 13318static char *
b872057a 13319remote_hostio_error (fileio_error errnum)
a6b151f1 13320{
517a63c2 13321 int host_error = fileio_error_to_host (errnum);
a6b151f1
DJ
13322
13323 if (host_error == -1)
13324 error (_("Unknown remote I/O error %d"), errnum);
13325 else
13326 error (_("Remote I/O error: %s"), safe_strerror (host_error));
13327}
13328
440b7aec
PA
13329/* A RAII wrapper around a remote file descriptor. */
13330
13331class scoped_remote_fd
a6b151f1 13332{
440b7aec 13333public:
6b8edb51
PA
13334 scoped_remote_fd (remote_target *remote, int fd)
13335 : m_remote (remote), m_fd (fd)
440b7aec
PA
13336 {
13337 }
a6b151f1 13338
440b7aec
PA
13339 ~scoped_remote_fd ()
13340 {
13341 if (m_fd != -1)
13342 {
13343 try
13344 {
b872057a 13345 fileio_error remote_errno;
6b8edb51 13346 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec 13347 }
07d74e51
TV
13348 catch (const gdb_exception_quit &ex)
13349 {
13350 /* We can't throw from a destructor, so re-set the quit flag
13351 for later QUIT checking. */
13352 set_quit_flag ();
13353 }
13354 catch (const gdb_exception_forced_quit &ex)
13355 {
13356 /* Like above, but (eventually) cause GDB to terminate by
13357 setting sync_quit_force_run. */
13358 set_force_quit_flag ();
13359 }
440b7aec
PA
13360 catch (...)
13361 {
13362 /* Swallow exception before it escapes the dtor. If
13363 something goes wrong, likely the connection is gone,
13364 and there's nothing else that can be done. */
13365 }
13366 }
13367 }
13368
13369 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
13370
13371 /* Release ownership of the file descriptor, and return it. */
88a774b9 13372 ATTRIBUTE_UNUSED_RESULT int release () noexcept
440b7aec
PA
13373 {
13374 int fd = m_fd;
13375 m_fd = -1;
13376 return fd;
13377 }
13378
13379 /* Return the owned file descriptor. */
13380 int get () const noexcept
13381 {
13382 return m_fd;
13383 }
13384
13385private:
6b8edb51
PA
13386 /* The remote target. */
13387 remote_target *m_remote;
13388
440b7aec
PA
13389 /* The owned remote I/O file descriptor. */
13390 int m_fd;
13391};
a6b151f1
DJ
13392
13393void
13394remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
13395{
13396 remote_target *remote = get_current_remote_target ();
13397
13398 if (remote == nullptr)
13399 error (_("command can only be used with remote target"));
13400
13401 remote->remote_file_put (local_file, remote_file, from_tty);
13402}
13403
13404void
13405remote_target::remote_file_put (const char *local_file, const char *remote_file,
13406 int from_tty)
a6b151f1 13407{
b872057a
SM
13408 int retcode, bytes, io_size;
13409 fileio_error remote_errno;
a6b151f1
DJ
13410 int bytes_in_buffer;
13411 int saw_eof;
13412 ULONGEST offset;
a6b151f1 13413
d419f42d 13414 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
13415 if (file == NULL)
13416 perror_with_name (local_file);
a6b151f1 13417
440b7aec 13418 scoped_remote_fd fd
6b8edb51
PA
13419 (this, remote_hostio_open (NULL,
13420 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
13421 | FILEIO_O_TRUNC),
13422 0700, 0, &remote_errno));
440b7aec 13423 if (fd.get () == -1)
a6b151f1
DJ
13424 remote_hostio_error (remote_errno);
13425
13426 /* Send up to this many bytes at once. They won't all fit in the
13427 remote packet limit, so we'll transfer slightly fewer. */
13428 io_size = get_remote_packet_size ();
5ca3b260 13429 gdb::byte_vector buffer (io_size);
a6b151f1 13430
a6b151f1
DJ
13431 bytes_in_buffer = 0;
13432 saw_eof = 0;
13433 offset = 0;
13434 while (bytes_in_buffer || !saw_eof)
13435 {
13436 if (!saw_eof)
13437 {
5ca3b260 13438 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 13439 io_size - bytes_in_buffer,
d419f42d 13440 file.get ());
a6b151f1
DJ
13441 if (bytes == 0)
13442 {
d419f42d 13443 if (ferror (file.get ()))
a6b151f1
DJ
13444 error (_("Error reading %s."), local_file);
13445 else
13446 {
13447 /* EOF. Unless there is something still in the
13448 buffer from the last iteration, we are done. */
13449 saw_eof = 1;
13450 if (bytes_in_buffer == 0)
13451 break;
13452 }
13453 }
13454 }
13455 else
13456 bytes = 0;
13457
13458 bytes += bytes_in_buffer;
13459 bytes_in_buffer = 0;
13460
5ca3b260 13461 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 13462 offset, &remote_errno);
a6b151f1
DJ
13463
13464 if (retcode < 0)
13465 remote_hostio_error (remote_errno);
13466 else if (retcode == 0)
13467 error (_("Remote write of %d bytes returned 0!"), bytes);
13468 else if (retcode < bytes)
13469 {
13470 /* Short write. Save the rest of the read data for the next
13471 write. */
13472 bytes_in_buffer = bytes - retcode;
5ca3b260 13473 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
13474 }
13475
13476 offset += retcode;
13477 }
13478
6b8edb51 13479 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
13480 remote_hostio_error (remote_errno);
13481
13482 if (from_tty)
5260dcf0
AB
13483 gdb_printf (_("Successfully sent file \"%ps\".\n"),
13484 styled_string (file_name_style.style (), local_file));
a6b151f1
DJ
13485}
13486
13487void
13488remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
13489{
13490 remote_target *remote = get_current_remote_target ();
13491
13492 if (remote == nullptr)
13493 error (_("command can only be used with remote target"));
13494
13495 remote->remote_file_get (remote_file, local_file, from_tty);
13496}
13497
13498void
13499remote_target::remote_file_get (const char *remote_file, const char *local_file,
13500 int from_tty)
a6b151f1 13501{
b872057a
SM
13502 fileio_error remote_errno;
13503 int bytes, io_size;
a6b151f1 13504 ULONGEST offset;
a6b151f1 13505
440b7aec 13506 scoped_remote_fd fd
6b8edb51
PA
13507 (this, remote_hostio_open (NULL,
13508 remote_file, FILEIO_O_RDONLY, 0, 0,
13509 &remote_errno));
440b7aec 13510 if (fd.get () == -1)
a6b151f1
DJ
13511 remote_hostio_error (remote_errno);
13512
d419f42d 13513 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
13514 if (file == NULL)
13515 perror_with_name (local_file);
a6b151f1
DJ
13516
13517 /* Send up to this many bytes at once. They won't all fit in the
13518 remote packet limit, so we'll transfer slightly fewer. */
13519 io_size = get_remote_packet_size ();
5ca3b260 13520 gdb::byte_vector buffer (io_size);
a6b151f1 13521
a6b151f1
DJ
13522 offset = 0;
13523 while (1)
13524 {
5ca3b260 13525 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 13526 &remote_errno);
a6b151f1
DJ
13527 if (bytes == 0)
13528 /* Success, but no bytes, means end-of-file. */
13529 break;
13530 if (bytes == -1)
13531 remote_hostio_error (remote_errno);
13532
13533 offset += bytes;
13534
5ca3b260 13535 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
13536 if (bytes == 0)
13537 perror_with_name (local_file);
13538 }
13539
6b8edb51 13540 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
13541 remote_hostio_error (remote_errno);
13542
13543 if (from_tty)
5260dcf0
AB
13544 gdb_printf (_("Successfully fetched file \"%ps\".\n"),
13545 styled_string (file_name_style.style (), remote_file));
a6b151f1
DJ
13546}
13547
13548void
13549remote_file_delete (const char *remote_file, int from_tty)
13550{
6b8edb51 13551 remote_target *remote = get_current_remote_target ();
a6b151f1 13552
6b8edb51 13553 if (remote == nullptr)
a6b151f1
DJ
13554 error (_("command can only be used with remote target"));
13555
6b8edb51
PA
13556 remote->remote_file_delete (remote_file, from_tty);
13557}
13558
13559void
13560remote_target::remote_file_delete (const char *remote_file, int from_tty)
13561{
b872057a
SM
13562 int retcode;
13563 fileio_error remote_errno;
6b8edb51
PA
13564
13565 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
13566 if (retcode == -1)
13567 remote_hostio_error (remote_errno);
13568
13569 if (from_tty)
5260dcf0
AB
13570 gdb_printf (_("Successfully deleted file \"%ps\".\n"),
13571 styled_string (file_name_style.style (), remote_file));
a6b151f1
DJ
13572}
13573
13574static void
ac88e2de 13575remote_put_command (const char *args, int from_tty)
a6b151f1 13576{
d1a41061
PP
13577 if (args == NULL)
13578 error_no_arg (_("file to put"));
13579
773a1edc 13580 gdb_argv argv (args);
a6b151f1
DJ
13581 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13582 error (_("Invalid parameters to remote put"));
13583
13584 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
13585}
13586
13587static void
ac88e2de 13588remote_get_command (const char *args, int from_tty)
a6b151f1 13589{
d1a41061
PP
13590 if (args == NULL)
13591 error_no_arg (_("file to get"));
13592
773a1edc 13593 gdb_argv argv (args);
a6b151f1
DJ
13594 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13595 error (_("Invalid parameters to remote get"));
13596
13597 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
13598}
13599
13600static void
ac88e2de 13601remote_delete_command (const char *args, int from_tty)
a6b151f1 13602{
d1a41061
PP
13603 if (args == NULL)
13604 error_no_arg (_("file to delete"));
13605
773a1edc 13606 gdb_argv argv (args);
a6b151f1
DJ
13607 if (argv[0] == NULL || argv[1] != NULL)
13608 error (_("Invalid parameters to remote delete"));
13609
13610 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
13611}
13612
57810aa7 13613bool
f6ac5f3d 13614remote_target::can_execute_reverse ()
b2175913 13615{
ff52c073
CS
13616 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13617 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 13618 return true;
40ab02ce 13619 else
57810aa7 13620 return false;
b2175913
MS
13621}
13622
57810aa7 13623bool
f6ac5f3d 13624remote_target::supports_non_stop ()
74531fed 13625{
57810aa7 13626 return true;
74531fed
PA
13627}
13628
57810aa7 13629bool
f6ac5f3d 13630remote_target::supports_disable_randomization ()
03583c20
UW
13631{
13632 /* Only supported in extended mode. */
57810aa7 13633 return false;
03583c20
UW
13634}
13635
57810aa7 13636bool
f6ac5f3d 13637remote_target::supports_multi_process ()
8a305172 13638{
ff52c073 13639 return m_features.remote_multi_process_p ();
8a305172
PA
13640}
13641
ff52c073
CS
13642int
13643remote_target::remote_supports_cond_tracepoints ()
782b2b07 13644{
ff52c073
CS
13645 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13646 == PACKET_ENABLE);
782b2b07
SS
13647}
13648
57810aa7 13649bool
f6ac5f3d 13650remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 13651{
ff52c073
CS
13652 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13653 == PACKET_ENABLE);
3788aec7
LM
13654}
13655
ff52c073
CS
13656int
13657remote_target::remote_supports_fast_tracepoints ()
7a697b8d 13658{
ff52c073 13659 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
13660}
13661
ff52c073
CS
13662int
13663remote_target::remote_supports_static_tracepoints ()
0fb4aa4b 13664{
ff52c073 13665 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
13666}
13667
ff52c073
CS
13668int
13669remote_target::remote_supports_install_in_trace ()
1e4d1764 13670{
ff52c073 13671 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
13672}
13673
57810aa7 13674bool
f6ac5f3d 13675remote_target::supports_enable_disable_tracepoint ()
d248b706 13676{
ff52c073 13677 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
4082afcc 13678 == PACKET_ENABLE);
d248b706
KY
13679}
13680
57810aa7 13681bool
f6ac5f3d 13682remote_target::supports_string_tracing ()
3065dfb6 13683{
ff52c073 13684 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
13685}
13686
57810aa7 13687bool
f6ac5f3d 13688remote_target::can_run_breakpoint_commands ()
d3ce09f5 13689{
ff52c073 13690 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
13691}
13692
f6ac5f3d
PA
13693void
13694remote_target::trace_init ()
35b1e5cc 13695{
b6bb3468
PA
13696 struct remote_state *rs = get_remote_state ();
13697
35b1e5cc 13698 putpkt ("QTinit");
b6bb3468 13699 remote_get_noisy_reply ();
8d64371b 13700 if (strcmp (rs->buf.data (), "OK") != 0)
35b1e5cc
SS
13701 error (_("Target does not support this command."));
13702}
13703
409873ef
SS
13704/* Recursive routine to walk through command list including loops, and
13705 download packets for each command. */
13706
6b8edb51
PA
13707void
13708remote_target::remote_download_command_source (int num, ULONGEST addr,
13709 struct command_line *cmds)
409873ef
SS
13710{
13711 struct remote_state *rs = get_remote_state ();
13712 struct command_line *cmd;
13713
13714 for (cmd = cmds; cmd; cmd = cmd->next)
13715 {
0df8b418 13716 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13717 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13718 encode_source_string (num, addr, "cmd", cmd->line,
8d64371b
TT
13719 rs->buf.data () + strlen (rs->buf.data ()),
13720 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13721 putpkt (rs->buf);
b6bb3468 13722 remote_get_noisy_reply ();
8d64371b 13723 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13724 warning (_("Target does not support source download."));
13725
13726 if (cmd->control_type == while_control
13727 || cmd->control_type == while_stepping_control)
13728 {
12973681 13729 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 13730
0df8b418 13731 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13732 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13733 encode_source_string (num, addr, "cmd", "end",
8d64371b
TT
13734 rs->buf.data () + strlen (rs->buf.data ()),
13735 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13736 putpkt (rs->buf);
b6bb3468 13737 remote_get_noisy_reply ();
8d64371b 13738 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13739 warning (_("Target does not support source download."));
13740 }
13741 }
13742}
13743
f6ac5f3d
PA
13744void
13745remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc
SS
13746{
13747 CORE_ADDR tpaddr;
409873ef 13748 char addrbuf[40];
b44ec619
SM
13749 std::vector<std::string> tdp_actions;
13750 std::vector<std::string> stepping_actions;
35b1e5cc 13751 char *pkt;
e8ba3115 13752 struct breakpoint *b = loc->owner;
01bccc56 13753 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
b6bb3468 13754 struct remote_state *rs = get_remote_state ();
3df3a985 13755 int ret;
ff36536c 13756 const char *err_msg = _("Tracepoint packet too large for target.");
3df3a985
PFC
13757 size_t size_left;
13758
13759 /* We use a buffer other than rs->buf because we'll build strings
13760 across multiple statements, and other statements in between could
13761 modify rs->buf. */
13762 gdb::char_vector buf (get_remote_packet_size ());
35b1e5cc 13763
dc673c81 13764 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
13765
13766 tpaddr = loc->address;
9c1f84c9 13767 strcpy (addrbuf, phex (tpaddr));
3df3a985
PFC
13768 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13769 b->number, addrbuf, /* address */
13770 (b->enable_state == bp_enabled ? 'E' : 'D'),
13771 t->step_count, t->pass_count);
13772
13773 if (ret < 0 || ret >= buf.size ())
a7f25a84 13774 error ("%s", err_msg);
3df3a985 13775
e8ba3115
YQ
13776 /* Fast tracepoints are mostly handled by the target, but we can
13777 tell the target how big of an instruction block should be moved
13778 around. */
13779 if (b->type == bp_fast_tracepoint)
13780 {
13781 /* Only test for support at download time; we may not know
13782 target capabilities at definition time. */
13783 if (remote_supports_fast_tracepoints ())
35b1e5cc 13784 {
6b940e6a
PL
13785 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13786 NULL))
3df3a985
PFC
13787 {
13788 size_left = buf.size () - strlen (buf.data ());
13789 ret = snprintf (buf.data () + strlen (buf.data ()),
13790 size_left, ":F%x",
13791 gdb_insn_length (loc->gdbarch, tpaddr));
13792
13793 if (ret < 0 || ret >= size_left)
a7f25a84 13794 error ("%s", err_msg);
3df3a985 13795 }
35b1e5cc 13796 else
e8ba3115
YQ
13797 /* If it passed validation at definition but fails now,
13798 something is very wrong. */
f34652de 13799 internal_error (_("Fast tracepoint not valid during download"));
35b1e5cc 13800 }
e8ba3115
YQ
13801 else
13802 /* Fast tracepoints are functionally identical to regular
13803 tracepoints, so don't take lack of support as a reason to
13804 give up on the trace run. */
13805 warning (_("Target does not support fast tracepoints, "
13806 "downloading %d as regular tracepoint"), b->number);
13807 }
7b572efb
TT
13808 else if (b->type == bp_static_tracepoint
13809 || b->type == bp_static_marker_tracepoint)
e8ba3115
YQ
13810 {
13811 /* Only test for support at download time; we may not know
13812 target capabilities at definition time. */
13813 if (remote_supports_static_tracepoints ())
0fb4aa4b 13814 {
e8ba3115 13815 struct static_tracepoint_marker marker;
0fb4aa4b 13816
e8ba3115 13817 if (target_static_tracepoint_marker_at (tpaddr, &marker))
3df3a985
PFC
13818 {
13819 size_left = buf.size () - strlen (buf.data ());
13820 ret = snprintf (buf.data () + strlen (buf.data ()),
13821 size_left, ":S");
13822
13823 if (ret < 0 || ret >= size_left)
a7f25a84 13824 error ("%s", err_msg);
3df3a985 13825 }
0fb4aa4b 13826 else
e8ba3115 13827 error (_("Static tracepoint not valid during download"));
0fb4aa4b 13828 }
e8ba3115
YQ
13829 else
13830 /* Fast tracepoints are functionally identical to regular
13831 tracepoints, so don't take lack of support as a reason
13832 to give up on the trace run. */
13833 error (_("Target does not support static tracepoints"));
13834 }
13835 /* If the tracepoint has a conditional, make it into an agent
13836 expression and append to the definition. */
13837 if (loc->cond)
13838 {
13839 /* Only test support at download time, we may not know target
13840 capabilities at definition time. */
13841 if (remote_supports_cond_tracepoints ())
35b1e5cc 13842 {
3df3a985
PFC
13843 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13844 loc->cond.get ());
13845
13846 size_left = buf.size () - strlen (buf.data ());
13847
13848 ret = snprintf (buf.data () + strlen (buf.data ()),
6f96f485 13849 size_left, ":X%x,", (int) aexpr->buf.size ());
3df3a985
PFC
13850
13851 if (ret < 0 || ret >= size_left)
a7f25a84 13852 error ("%s", err_msg);
3df3a985
PFC
13853
13854 size_left = buf.size () - strlen (buf.data ());
13855
13856 /* Two bytes to encode each aexpr byte, plus the terminating
13857 null byte. */
6f96f485 13858 if (aexpr->buf.size () * 2 + 1 > size_left)
a7f25a84 13859 error ("%s", err_msg);
3df3a985
PFC
13860
13861 pkt = buf.data () + strlen (buf.data ());
13862
6f96f485 13863 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
e8ba3115
YQ
13864 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13865 *pkt = '\0';
35b1e5cc 13866 }
e8ba3115
YQ
13867 else
13868 warning (_("Target does not support conditional tracepoints, "
13869 "ignoring tp %d cond"), b->number);
13870 }
35b1e5cc 13871
e0700ba4 13872 if (b->commands || !default_collect.empty ())
3df3a985
PFC
13873 {
13874 size_left = buf.size () - strlen (buf.data ());
13875
13876 ret = snprintf (buf.data () + strlen (buf.data ()),
13877 size_left, "-");
13878
13879 if (ret < 0 || ret >= size_left)
a7f25a84 13880 error ("%s", err_msg);
3df3a985
PFC
13881 }
13882
13883 putpkt (buf.data ());
b6bb3468 13884 remote_get_noisy_reply ();
8d64371b 13885 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13886 error (_("Target does not support tracepoints."));
35b1e5cc 13887
e8ba3115 13888 /* do_single_steps (t); */
b44ec619
SM
13889 for (auto action_it = tdp_actions.begin ();
13890 action_it != tdp_actions.end (); action_it++)
e8ba3115 13891 {
b44ec619
SM
13892 QUIT; /* Allow user to bail out with ^C. */
13893
aa6f3694 13894 bool has_more = ((action_it + 1) != tdp_actions.end ()
b44ec619
SM
13895 || !stepping_actions.empty ());
13896
3df3a985
PFC
13897 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13898 b->number, addrbuf, /* address */
13899 action_it->c_str (),
13900 has_more ? '-' : 0);
13901
13902 if (ret < 0 || ret >= buf.size ())
a7f25a84 13903 error ("%s", err_msg);
3df3a985
PFC
13904
13905 putpkt (buf.data ());
b44ec619 13906 remote_get_noisy_reply ();
8d64371b 13907 if (strcmp (rs->buf.data (), "OK"))
b44ec619 13908 error (_("Error on target while setting tracepoints."));
e8ba3115 13909 }
409873ef 13910
05abfc39
PFC
13911 for (auto action_it = stepping_actions.begin ();
13912 action_it != stepping_actions.end (); action_it++)
13913 {
13914 QUIT; /* Allow user to bail out with ^C. */
13915
13916 bool is_first = action_it == stepping_actions.begin ();
aa6f3694 13917 bool has_more = (action_it + 1) != stepping_actions.end ();
05abfc39 13918
3df3a985
PFC
13919 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13920 b->number, addrbuf, /* address */
13921 is_first ? "S" : "",
13922 action_it->c_str (),
13923 has_more ? "-" : "");
13924
13925 if (ret < 0 || ret >= buf.size ())
a7f25a84 13926 error ("%s", err_msg);
3df3a985
PFC
13927
13928 putpkt (buf.data ());
05abfc39 13929 remote_get_noisy_reply ();
8d64371b 13930 if (strcmp (rs->buf.data (), "OK"))
05abfc39
PFC
13931 error (_("Error on target while setting tracepoints."));
13932 }
b44ec619 13933
ff52c073 13934 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 13935 {
264f9890 13936 if (b->locspec != nullptr)
409873ef 13937 {
3df3a985
PFC
13938 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13939
13940 if (ret < 0 || ret >= buf.size ())
a7f25a84 13941 error ("%s", err_msg);
3df3a985 13942
709438c7 13943 const char *str = b->locspec->to_string ();
264f9890 13944 encode_source_string (b->number, loc->address, "at", str,
3df3a985
PFC
13945 buf.data () + strlen (buf.data ()),
13946 buf.size () - strlen (buf.data ()));
13947 putpkt (buf.data ());
b6bb3468 13948 remote_get_noisy_reply ();
8d64371b 13949 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13950 warning (_("Target does not support source download."));
409873ef 13951 }
e8ba3115
YQ
13952 if (b->cond_string)
13953 {
3df3a985
PFC
13954 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13955
13956 if (ret < 0 || ret >= buf.size ())
a7f25a84 13957 error ("%s", err_msg);
3df3a985 13958
e8ba3115 13959 encode_source_string (b->number, loc->address,
6f781ee3 13960 "cond", b->cond_string.get (),
3df3a985
PFC
13961 buf.data () + strlen (buf.data ()),
13962 buf.size () - strlen (buf.data ()));
13963 putpkt (buf.data ());
b6bb3468 13964 remote_get_noisy_reply ();
8d64371b 13965 if (strcmp (rs->buf.data (), "OK"))
e8ba3115
YQ
13966 warning (_("Target does not support source download."));
13967 }
13968 remote_download_command_source (b->number, loc->address,
13969 breakpoint_commands (b));
35b1e5cc 13970 }
35b1e5cc
SS
13971}
13972
57810aa7 13973bool
f6ac5f3d 13974remote_target::can_download_tracepoint ()
1e4d1764 13975{
1e51243a
PA
13976 struct remote_state *rs = get_remote_state ();
13977 struct trace_status *ts;
13978 int status;
13979
13980 /* Don't try to install tracepoints until we've relocated our
13981 symbols, and fetched and merged the target's tracepoint list with
13982 ours. */
13983 if (rs->starting_up)
57810aa7 13984 return false;
1e51243a
PA
13985
13986 ts = current_trace_status ();
f6ac5f3d 13987 status = get_trace_status (ts);
1e4d1764
YQ
13988
13989 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13990 return false;
1e4d1764
YQ
13991
13992 /* If we are in a tracing experiment, but remote stub doesn't support
13993 installing tracepoint in trace, we have to return. */
13994 if (!remote_supports_install_in_trace ())
57810aa7 13995 return false;
1e4d1764 13996
57810aa7 13997 return true;
1e4d1764
YQ
13998}
13999
14000
f6ac5f3d
PA
14001void
14002remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
14003{
14004 struct remote_state *rs = get_remote_state ();
00bf0b85 14005 char *p;
35b1e5cc 14006
8d64371b 14007 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
14008 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
14009 tsv.builtin);
8d64371b
TT
14010 p = rs->buf.data () + strlen (rs->buf.data ());
14011 if ((p - rs->buf.data ()) + tsv.name.length () * 2
14012 >= get_remote_packet_size ())
00bf0b85 14013 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 14014 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 14015 *p++ = '\0';
35b1e5cc 14016 putpkt (rs->buf);
b6bb3468 14017 remote_get_noisy_reply ();
8d64371b 14018 if (rs->buf[0] == '\0')
ad91cd99 14019 error (_("Target does not support this command."));
8d64371b 14020 if (strcmp (rs->buf.data (), "OK") != 0)
ad91cd99 14021 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
14022}
14023
f6ac5f3d
PA
14024void
14025remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
14026{
14027 struct remote_state *rs = get_remote_state ();
d248b706 14028
8d64371b 14029 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
53807e9f 14030 location->owner->number,
9c1f84c9 14031 phex (location->address));
d248b706 14032 putpkt (rs->buf);
b6bb3468 14033 remote_get_noisy_reply ();
8d64371b 14034 if (rs->buf[0] == '\0')
d248b706 14035 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
8d64371b 14036 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
14037 error (_("Error on target while enabling tracepoint."));
14038}
14039
f6ac5f3d
PA
14040void
14041remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
14042{
14043 struct remote_state *rs = get_remote_state ();
d248b706 14044
8d64371b 14045 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
53807e9f 14046 location->owner->number,
9c1f84c9 14047 phex (location->address));
d248b706 14048 putpkt (rs->buf);
b6bb3468 14049 remote_get_noisy_reply ();
8d64371b 14050 if (rs->buf[0] == '\0')
d248b706 14051 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
8d64371b 14052 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
14053 error (_("Error on target while disabling tracepoint."));
14054}
14055
f6ac5f3d
PA
14056void
14057remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
14058{
14059 asection *s;
14060 bfd_size_type size;
608bcef2 14061 bfd_vma vma;
35b1e5cc 14062 int anysecs = 0;
c2fa21f1 14063 int offset = 0;
f493c217 14064 bfd *abfd = current_program_space->exec_bfd ();
35b1e5cc 14065
f493c217 14066 if (!abfd)
35b1e5cc
SS
14067 return; /* No information to give. */
14068
b6bb3468
PA
14069 struct remote_state *rs = get_remote_state ();
14070
8d64371b
TT
14071 strcpy (rs->buf.data (), "QTro");
14072 offset = strlen (rs->buf.data ());
f493c217 14073 for (s = abfd->sections; s; s = s->next)
35b1e5cc
SS
14074 {
14075 char tmp1[40], tmp2[40];
c2fa21f1 14076 int sec_length;
35b1e5cc 14077
f493c217
AM
14078 if ((s->flags & SEC_LOAD) == 0
14079 /* || (s->flags & SEC_CODE) == 0 */
14080 || (s->flags & SEC_READONLY) == 0)
35b1e5cc
SS
14081 continue;
14082
14083 anysecs = 1;
fd361982
AM
14084 vma = bfd_section_vma (s);
14085 size = bfd_section_size (s);
f493c217
AM
14086 bfd_sprintf_vma (abfd, tmp1, vma);
14087 bfd_sprintf_vma (abfd, tmp2, vma + size);
c2fa21f1 14088 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
8d64371b 14089 if (offset + sec_length + 1 > rs->buf.size ())
c2fa21f1 14090 {
ff52c073
CS
14091 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
14092 != PACKET_ENABLE)
864ac8a7 14093 warning (_("\
c2fa21f1
HZ
14094Too many sections for read-only sections definition packet."));
14095 break;
14096 }
8d64371b 14097 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
bba74b36 14098 tmp1, tmp2);
c2fa21f1 14099 offset += sec_length;
35b1e5cc
SS
14100 }
14101 if (anysecs)
14102 {
b6bb3468 14103 putpkt (rs->buf);
aa7b36b8 14104 getpkt (&rs->buf);
35b1e5cc
SS
14105 }
14106}
14107
f6ac5f3d
PA
14108void
14109remote_target::trace_start ()
35b1e5cc 14110{
b6bb3468
PA
14111 struct remote_state *rs = get_remote_state ();
14112
35b1e5cc 14113 putpkt ("QTStart");
b6bb3468 14114 remote_get_noisy_reply ();
8d64371b 14115 if (rs->buf[0] == '\0')
ad91cd99 14116 error (_("Target does not support this command."));
8d64371b
TT
14117 if (strcmp (rs->buf.data (), "OK") != 0)
14118 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
14119}
14120
f6ac5f3d
PA
14121int
14122remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 14123{
953b98d1 14124 /* Initialize it just to avoid a GCC false warning. */
f652de6f 14125 char *p = NULL;
b6bb3468 14126 struct remote_state *rs = get_remote_state ();
bd3eecc3 14127
ff52c073 14128 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 14129 return -1;
a744cf53 14130
7b9a15e1 14131 /* FIXME we need to get register block size some other way. */
5cd63fda 14132 trace_regblock_size
99d9c3b9 14133 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
00bf0b85 14134
049dc89b
JK
14135 putpkt ("qTStatus");
14136
a70b8144 14137 try
67f41397 14138 {
b6bb3468 14139 p = remote_get_noisy_reply ();
67f41397 14140 }
230d2906 14141 catch (const gdb_exception_error &ex)
67f41397 14142 {
598d3636
JK
14143 if (ex.error != TARGET_CLOSE_ERROR)
14144 {
14145 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
14146 return -1;
14147 }
eedc3f4f 14148 throw;
67f41397 14149 }
00bf0b85 14150
94a94c90 14151 packet_result result = m_features.packet_ok (p, PACKET_qTStatus);
bd3eecc3 14152
94a94c90
AH
14153 switch (result.status ())
14154 {
14155 case PACKET_ERROR:
14156 error (_("Remote failure reply: %s"), result.err_msg ());
14157 /* If the remote target doesn't do tracing, flag it. */
14158 case PACKET_UNKNOWN:
14159 return -1;
14160 }
35b1e5cc 14161
00bf0b85 14162 /* We're working with a live target. */
f5911ea1 14163 ts->filename = NULL;
00bf0b85 14164
00bf0b85 14165 if (*p++ != 'T')
8d64371b 14166 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
35b1e5cc 14167
84cebc4a
YQ
14168 /* Function 'parse_trace_status' sets default value of each field of
14169 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
14170 parse_trace_status (p, ts);
14171
14172 return ts->running;
35b1e5cc
SS
14173}
14174
f6ac5f3d 14175void
01bccc56 14176remote_target::get_tracepoint_status (tracepoint *tp,
f6ac5f3d 14177 struct uploaded_tp *utp)
f196051f
SS
14178{
14179 struct remote_state *rs = get_remote_state ();
f196051f 14180 char *reply;
bba74b36 14181 size_t size = get_remote_packet_size ();
f196051f
SS
14182
14183 if (tp)
14184 {
c1fc2657 14185 tp->hit_count = 0;
f196051f 14186 tp->traceframe_usage = 0;
b00b30b2 14187 for (bp_location &loc : tp->locations ())
f196051f
SS
14188 {
14189 /* If the tracepoint was never downloaded, don't go asking for
14190 any status. */
14191 if (tp->number_on_target == 0)
14192 continue;
8d64371b 14193 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
b00b30b2 14194 phex_nz (loc.address, 0));
f196051f 14195 putpkt (rs->buf);
b6bb3468 14196 reply = remote_get_noisy_reply ();
f196051f
SS
14197 if (reply && *reply)
14198 {
14199 if (*reply == 'V')
01bccc56 14200 parse_tracepoint_status (reply + 1, tp, utp);
f196051f
SS
14201 }
14202 }
14203 }
14204 else if (utp)
14205 {
14206 utp->hit_count = 0;
14207 utp->traceframe_usage = 0;
8d64371b 14208 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
bba74b36 14209 phex_nz (utp->addr, 0));
f196051f 14210 putpkt (rs->buf);
b6bb3468 14211 reply = remote_get_noisy_reply ();
f196051f
SS
14212 if (reply && *reply)
14213 {
14214 if (*reply == 'V')
01bccc56 14215 parse_tracepoint_status (reply + 1, tp, utp);
f196051f
SS
14216 }
14217 }
14218}
14219
f6ac5f3d
PA
14220void
14221remote_target::trace_stop ()
35b1e5cc 14222{
b6bb3468
PA
14223 struct remote_state *rs = get_remote_state ();
14224
35b1e5cc 14225 putpkt ("QTStop");
b6bb3468 14226 remote_get_noisy_reply ();
8d64371b 14227 if (rs->buf[0] == '\0')
ad91cd99 14228 error (_("Target does not support this command."));
8d64371b
TT
14229 if (strcmp (rs->buf.data (), "OK") != 0)
14230 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
14231}
14232
f6ac5f3d
PA
14233int
14234remote_target::trace_find (enum trace_find_type type, int num,
14235 CORE_ADDR addr1, CORE_ADDR addr2,
14236 int *tpp)
35b1e5cc
SS
14237{
14238 struct remote_state *rs = get_remote_state ();
8d64371b 14239 char *endbuf = rs->buf.data () + get_remote_packet_size ();
35b1e5cc
SS
14240 char *p, *reply;
14241 int target_frameno = -1, target_tracept = -1;
14242
e6e4e701
PA
14243 /* Lookups other than by absolute frame number depend on the current
14244 trace selected, so make sure it is correct on the remote end
14245 first. */
14246 if (type != tfind_number)
14247 set_remote_traceframe ();
14248
8d64371b 14249 p = rs->buf.data ();
35b1e5cc
SS
14250 strcpy (p, "QTFrame:");
14251 p = strchr (p, '\0');
14252 switch (type)
14253 {
14254 case tfind_number:
bba74b36 14255 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
14256 break;
14257 case tfind_pc:
bba74b36 14258 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
14259 break;
14260 case tfind_tp:
bba74b36 14261 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
14262 break;
14263 case tfind_range:
bba74b36
YQ
14264 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
14265 phex_nz (addr2, 0));
35b1e5cc
SS
14266 break;
14267 case tfind_outside:
bba74b36
YQ
14268 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
14269 phex_nz (addr2, 0));
35b1e5cc
SS
14270 break;
14271 default:
9b20d036 14272 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
14273 }
14274
14275 putpkt (rs->buf);
b6bb3468 14276 reply = remote_get_noisy_reply ();
ad91cd99
PA
14277 if (*reply == '\0')
14278 error (_("Target does not support this command."));
35b1e5cc
SS
14279
14280 while (reply && *reply)
14281 switch (*reply)
14282 {
14283 case 'F':
f197e0f1
VP
14284 p = ++reply;
14285 target_frameno = (int) strtol (p, &reply, 16);
14286 if (reply == p)
14287 error (_("Unable to parse trace frame number"));
e6e4e701
PA
14288 /* Don't update our remote traceframe number cache on failure
14289 to select a remote traceframe. */
f197e0f1
VP
14290 if (target_frameno == -1)
14291 return -1;
35b1e5cc
SS
14292 break;
14293 case 'T':
f197e0f1
VP
14294 p = ++reply;
14295 target_tracept = (int) strtol (p, &reply, 16);
14296 if (reply == p)
14297 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
14298 break;
14299 case 'O': /* "OK"? */
14300 if (reply[1] == 'K' && reply[2] == '\0')
14301 reply += 2;
14302 else
14303 error (_("Bogus reply from target: %s"), reply);
14304 break;
14305 default:
14306 error (_("Bogus reply from target: %s"), reply);
14307 }
14308 if (tpp)
14309 *tpp = target_tracept;
e6e4e701 14310
262e1174 14311 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
14312 return target_frameno;
14313}
14314
57810aa7 14315bool
f6ac5f3d 14316remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
14317{
14318 struct remote_state *rs = get_remote_state ();
14319 char *reply;
14320 ULONGEST uval;
14321
e6e4e701
PA
14322 set_remote_traceframe ();
14323
8d64371b 14324 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 14325 putpkt (rs->buf);
b6bb3468 14326 reply = remote_get_noisy_reply ();
35b1e5cc
SS
14327 if (reply && *reply)
14328 {
14329 if (*reply == 'V')
14330 {
14331 unpack_varlen_hex (reply + 1, &uval);
14332 *val = (LONGEST) uval;
57810aa7 14333 return true;
35b1e5cc
SS
14334 }
14335 }
57810aa7 14336 return false;
35b1e5cc
SS
14337}
14338
f6ac5f3d
PA
14339int
14340remote_target::save_trace_data (const char *filename)
00bf0b85
SS
14341{
14342 struct remote_state *rs = get_remote_state ();
14343 char *p, *reply;
14344
8d64371b 14345 p = rs->buf.data ();
00bf0b85
SS
14346 strcpy (p, "QTSave:");
14347 p += strlen (p);
8d64371b
TT
14348 if ((p - rs->buf.data ()) + strlen (filename) * 2
14349 >= get_remote_packet_size ())
00bf0b85 14350 error (_("Remote file name too long for trace save packet"));
9f1b45b0 14351 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
14352 *p++ = '\0';
14353 putpkt (rs->buf);
b6bb3468 14354 reply = remote_get_noisy_reply ();
d6c5869f 14355 if (*reply == '\0')
ad91cd99
PA
14356 error (_("Target does not support this command."));
14357 if (strcmp (reply, "OK") != 0)
14358 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
14359 return 0;
14360}
14361
14362/* This is basically a memory transfer, but needs to be its own packet
14363 because we don't know how the target actually organizes its trace
14364 memory, plus we want to be able to ask for as much as possible, but
14365 not be unhappy if we don't get as much as we ask for. */
14366
f6ac5f3d
PA
14367LONGEST
14368remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
14369{
14370 struct remote_state *rs = get_remote_state ();
14371 char *reply;
14372 char *p;
14373 int rslt;
14374
8d64371b 14375 p = rs->buf.data ();
00bf0b85
SS
14376 strcpy (p, "qTBuffer:");
14377 p += strlen (p);
14378 p += hexnumstr (p, offset);
14379 *p++ = ',';
14380 p += hexnumstr (p, len);
14381 *p++ = '\0';
14382
14383 putpkt (rs->buf);
b6bb3468 14384 reply = remote_get_noisy_reply ();
00bf0b85
SS
14385 if (reply && *reply)
14386 {
14387 /* 'l' by itself means we're at the end of the buffer and
14388 there is nothing more to get. */
14389 if (*reply == 'l')
14390 return 0;
14391
14392 /* Convert the reply into binary. Limit the number of bytes to
14393 convert according to our passed-in buffer size, rather than
14394 what was returned in the packet; if the target is
14395 unexpectedly generous and gives us a bigger reply than we
14396 asked for, we don't want to crash. */
b6bb3468 14397 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
14398 return rslt;
14399 }
14400
14401 /* Something went wrong, flag as an error. */
14402 return -1;
14403}
14404
f6ac5f3d
PA
14405void
14406remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
14407{
14408 struct remote_state *rs = get_remote_state ();
14409
ff52c073
CS
14410 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
14411 == PACKET_ENABLE)
33da3f1c 14412 {
ad91cd99
PA
14413 char *reply;
14414
8d64371b
TT
14415 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14416 "QTDisconnected:%x", val);
33da3f1c 14417 putpkt (rs->buf);
b6bb3468 14418 reply = remote_get_noisy_reply ();
ad91cd99 14419 if (*reply == '\0')
33da3f1c 14420 error (_("Target does not support this command."));
ad91cd99 14421 if (strcmp (reply, "OK") != 0)
dda83cd7 14422 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
14423 }
14424 else if (val)
14425 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
14426}
14427
f6ac5f3d
PA
14428int
14429remote_target::core_of_thread (ptid_t ptid)
dc146f7c 14430{
9213a6d7 14431 thread_info *info = this->find_thread (ptid);
a744cf53 14432
7aabaf9d
SM
14433 if (info != NULL && info->priv != NULL)
14434 return get_remote_thread_info (info)->core;
14435
dc146f7c
VP
14436 return -1;
14437}
14438
f6ac5f3d
PA
14439void
14440remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
14441{
14442 struct remote_state *rs = get_remote_state ();
ad91cd99 14443 char *reply;
4daf5ac0 14444
8d64371b
TT
14445 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14446 "QTBuffer:circular:%x", val);
4daf5ac0 14447 putpkt (rs->buf);
b6bb3468 14448 reply = remote_get_noisy_reply ();
ad91cd99 14449 if (*reply == '\0')
4daf5ac0 14450 error (_("Target does not support this command."));
ad91cd99
PA
14451 if (strcmp (reply, "OK") != 0)
14452 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
14453}
14454
f6ac5f3d
PA
14455traceframe_info_up
14456remote_target::traceframe_info ()
b3b9301e 14457{
6b09f134 14458 std::optional<gdb::char_vector> text
328d42d8
SM
14459 = target_read_stralloc (current_inferior ()->top_target (),
14460 TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 14461 NULL);
9018be22
SM
14462 if (text)
14463 return parse_traceframe_info (text->data ());
b3b9301e
PA
14464
14465 return NULL;
14466}
14467
405f8e94
SS
14468/* Handle the qTMinFTPILen packet. Returns the minimum length of
14469 instruction on which a fast tracepoint may be placed. Returns -1
14470 if the packet is not supported, and 0 if the minimum instruction
14471 length is unknown. */
14472
f6ac5f3d
PA
14473int
14474remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
14475{
14476 struct remote_state *rs = get_remote_state ();
14477 char *reply;
14478
e886a173
PA
14479 /* If we're not debugging a process yet, the IPA can't be
14480 loaded. */
55f6301a 14481 if (!target_has_execution ())
e886a173
PA
14482 return 0;
14483
14484 /* Make sure the remote is pointing at the right process. */
14485 set_general_process ();
14486
8d64371b 14487 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
405f8e94 14488 putpkt (rs->buf);
b6bb3468 14489 reply = remote_get_noisy_reply ();
405f8e94
SS
14490 if (*reply == '\0')
14491 return -1;
14492 else
14493 {
14494 ULONGEST min_insn_len;
14495
14496 unpack_varlen_hex (reply, &min_insn_len);
14497
14498 return (int) min_insn_len;
14499 }
14500}
14501
f6ac5f3d
PA
14502void
14503remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 14504{
ff52c073 14505 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
14506 {
14507 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14508 char *buf = rs->buf.data ();
14509 char *endbuf = buf + get_remote_packet_size ();
f6f899bf
HAQ
14510
14511 gdb_assert (val >= 0 || val == -1);
14512 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14513 /* Send -1 as literal "-1" to avoid host size dependency. */
14514 if (val < 0)
14515 {
14516 *buf++ = '-';
dda83cd7 14517 buf += hexnumstr (buf, (ULONGEST) -val);
f6f899bf
HAQ
14518 }
14519 else
14520 buf += hexnumstr (buf, (ULONGEST) val);
14521
14522 putpkt (rs->buf);
b6bb3468 14523 remote_get_noisy_reply ();
94a94c90
AH
14524 packet_result result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14525 switch (result.status ())
14526 {
14527 case PACKET_ERROR:
14528 warning (_("Error reply from target: %s"), result.err_msg ());
14529 break;
14530 case PACKET_UNKNOWN:
14531 warning (_("Remote target failed to process the request "));
14532 }
f6f899bf
HAQ
14533 }
14534}
14535
57810aa7 14536bool
f6ac5f3d
PA
14537remote_target::set_trace_notes (const char *user, const char *notes,
14538 const char *stop_notes)
f196051f
SS
14539{
14540 struct remote_state *rs = get_remote_state ();
14541 char *reply;
8d64371b
TT
14542 char *buf = rs->buf.data ();
14543 char *endbuf = buf + get_remote_packet_size ();
f196051f
SS
14544 int nbytes;
14545
14546 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14547 if (user)
14548 {
14549 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 14550 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
14551 buf += 2 * nbytes;
14552 *buf++ = ';';
14553 }
14554 if (notes)
14555 {
14556 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 14557 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
14558 buf += 2 * nbytes;
14559 *buf++ = ';';
14560 }
14561 if (stop_notes)
14562 {
14563 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 14564 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
14565 buf += 2 * nbytes;
14566 *buf++ = ';';
14567 }
14568 /* Ensure the buffer is terminated. */
14569 *buf = '\0';
14570
14571 putpkt (rs->buf);
b6bb3468 14572 reply = remote_get_noisy_reply ();
f196051f 14573 if (*reply == '\0')
57810aa7 14574 return false;
f196051f
SS
14575
14576 if (strcmp (reply, "OK") != 0)
14577 error (_("Bogus reply from target: %s"), reply);
14578
57810aa7 14579 return true;
f196051f
SS
14580}
14581
57810aa7
PA
14582bool
14583remote_target::use_agent (bool use)
d1feda86 14584{
ff52c073 14585 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
14586 {
14587 struct remote_state *rs = get_remote_state ();
14588
14589 /* If the stub supports QAgent. */
8d64371b 14590 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
d1feda86 14591 putpkt (rs->buf);
aa7b36b8 14592 getpkt (&rs->buf);
d1feda86 14593
8d64371b 14594 if (strcmp (rs->buf.data (), "OK") == 0)
d1feda86 14595 {
f6ac5f3d 14596 ::use_agent = use;
57810aa7 14597 return true;
d1feda86
YQ
14598 }
14599 }
14600
57810aa7 14601 return false;
d1feda86
YQ
14602}
14603
57810aa7 14604bool
f6ac5f3d 14605remote_target::can_use_agent ()
d1feda86 14606{
ff52c073 14607 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
14608}
14609
1bcb9dcf
MM
14610#if defined (HAVE_LIBEXPAT)
14611
14612/* Check the btrace document version. */
14613
14614static void
14615check_xml_btrace_version (struct gdb_xml_parser *parser,
14616 const struct gdb_xml_element *element,
14617 void *user_data,
14618 std::vector<gdb_xml_value> &attributes)
14619{
14620 const char *version
14621 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14622
14623 if (strcmp (version, "1.0") != 0)
14624 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14625}
14626
14627/* Parse a btrace "block" xml record. */
14628
14629static void
14630parse_xml_btrace_block (struct gdb_xml_parser *parser,
14631 const struct gdb_xml_element *element,
14632 void *user_data,
14633 std::vector<gdb_xml_value> &attributes)
14634{
14635 struct btrace_data *btrace;
14636 ULONGEST *begin, *end;
14637
14638 btrace = (struct btrace_data *) user_data;
14639
14640 switch (btrace->format)
14641 {
14642 case BTRACE_FORMAT_BTS:
14643 break;
14644
14645 case BTRACE_FORMAT_NONE:
14646 btrace->format = BTRACE_FORMAT_BTS;
14647 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14648 break;
14649
14650 default:
14651 gdb_xml_error (parser, _("Btrace format error."));
14652 }
14653
14654 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14655 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14656 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14657}
14658
14659/* Parse a "raw" xml record. */
14660
14661static void
14662parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14663 gdb_byte **pdata, size_t *psize)
14664{
14665 gdb_byte *bin;
14666 size_t len, size;
14667
14668 len = strlen (body_text);
14669 if (len % 2 != 0)
14670 gdb_xml_error (parser, _("Bad raw data size."));
14671
14672 size = len / 2;
14673
14674 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14675 bin = data.get ();
14676
14677 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14678 while (len > 0)
14679 {
14680 char hi, lo;
14681
14682 hi = *body_text++;
14683 lo = *body_text++;
14684
14685 if (hi == 0 || lo == 0)
14686 gdb_xml_error (parser, _("Bad hex encoding."));
14687
14688 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14689 len -= 2;
14690 }
14691
14692 *pdata = data.release ();
14693 *psize = size;
14694}
14695
14696/* Parse a btrace pt-config "cpu" xml record. */
14697
14698static void
14699parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14700 const struct gdb_xml_element *element,
14701 void *user_data,
14702 std::vector<gdb_xml_value> &attributes)
14703{
14704 struct btrace_data *btrace;
14705 const char *vendor;
14706 ULONGEST *family, *model, *stepping;
14707
14708 vendor
14709 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14710 family
14711 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14712 model
14713 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14714 stepping
14715 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14716
14717 btrace = (struct btrace_data *) user_data;
14718
14719 if (strcmp (vendor, "GenuineIntel") == 0)
14720 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14721
14722 btrace->variant.pt.config.cpu.family = *family;
14723 btrace->variant.pt.config.cpu.model = *model;
14724 btrace->variant.pt.config.cpu.stepping = *stepping;
14725}
14726
14727/* Parse a btrace pt "raw" xml record. */
14728
14729static void
14730parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14731 const struct gdb_xml_element *element,
14732 void *user_data, const char *body_text)
14733{
14734 struct btrace_data *btrace;
14735
14736 btrace = (struct btrace_data *) user_data;
14737 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14738 &btrace->variant.pt.size);
14739}
14740
14741/* Parse a btrace "pt" xml record. */
14742
14743static void
14744parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14745 const struct gdb_xml_element *element,
14746 void *user_data,
14747 std::vector<gdb_xml_value> &attributes)
14748{
14749 struct btrace_data *btrace;
14750
14751 btrace = (struct btrace_data *) user_data;
14752 btrace->format = BTRACE_FORMAT_PT;
14753 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14754 btrace->variant.pt.data = NULL;
14755 btrace->variant.pt.size = 0;
14756}
14757
14758static const struct gdb_xml_attribute block_attributes[] = {
14759 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14760 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14761 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14762};
14763
14764static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14765 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14766 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14767 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14768 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14769 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14770};
14771
14772static const struct gdb_xml_element btrace_pt_config_children[] = {
14773 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14774 parse_xml_btrace_pt_config_cpu, NULL },
14775 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14776};
14777
14778static const struct gdb_xml_element btrace_pt_children[] = {
14779 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14780 NULL },
14781 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14782 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14783};
14784
14785static const struct gdb_xml_attribute btrace_attributes[] = {
14786 { "version", GDB_XML_AF_NONE, NULL, NULL },
14787 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14788};
14789
14790static const struct gdb_xml_element btrace_children[] = {
14791 { "block", block_attributes, NULL,
14792 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14793 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14794 NULL },
14795 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14796};
14797
14798static const struct gdb_xml_element btrace_elements[] = {
14799 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14800 check_xml_btrace_version, NULL },
14801 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14802};
14803
14804#endif /* defined (HAVE_LIBEXPAT) */
14805
14806/* Parse a branch trace xml document XML into DATA. */
14807
14808static void
14809parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14810{
14811#if defined (HAVE_LIBEXPAT)
14812
14813 int errcode;
14814 btrace_data result;
14815 result.format = BTRACE_FORMAT_NONE;
14816
14817 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14818 buffer, &result);
14819 if (errcode != 0)
14820 error (_("Error parsing branch trace."));
14821
14822 /* Keep parse results. */
14823 *btrace = std::move (result);
14824
14825#else /* !defined (HAVE_LIBEXPAT) */
14826
14827 error (_("Cannot process branch trace. XML support was disabled at "
14828 "compile time."));
14829
14830#endif /* !defined (HAVE_LIBEXPAT) */
14831}
14832
14833#if defined (HAVE_LIBEXPAT)
14834
14835/* Parse a btrace-conf "bts" xml record. */
14836
14837static void
14838parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14839 const struct gdb_xml_element *element,
14840 void *user_data,
14841 std::vector<gdb_xml_value> &attributes)
14842{
14843 struct btrace_config *conf;
14844 struct gdb_xml_value *size;
14845
14846 conf = (struct btrace_config *) user_data;
14847 conf->format = BTRACE_FORMAT_BTS;
14848 conf->bts.size = 0;
14849
14850 size = xml_find_attribute (attributes, "size");
14851 if (size != NULL)
14852 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14853}
14854
14855/* Parse a btrace-conf "pt" xml record. */
14856
14857static void
14858parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14859 const struct gdb_xml_element *element,
14860 void *user_data,
14861 std::vector<gdb_xml_value> &attributes)
14862{
14863 struct btrace_config *conf;
13b3a89b 14864 struct gdb_xml_value *size, *ptwrite, *event_tracing;
1bcb9dcf
MM
14865
14866 conf = (struct btrace_config *) user_data;
14867 conf->format = BTRACE_FORMAT_PT;
14868 conf->pt.size = 0;
14869
14870 size = xml_find_attribute (attributes, "size");
14871 if (size != NULL)
14872 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
ccc48080
FW
14873
14874 ptwrite = xml_find_attribute (attributes, "ptwrite");
14875 if (ptwrite != nullptr)
14876 conf->pt.ptwrite = (bool) *(ULONGEST *) ptwrite->value.get ();
13b3a89b
FW
14877
14878 event_tracing = xml_find_attribute (attributes, "event-tracing");
14879 if (event_tracing != nullptr)
14880 conf->pt.event_tracing = (bool) *(ULONGEST *) event_tracing->value.get ();
1bcb9dcf
MM
14881}
14882
14883static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14884 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
ccc48080
FW
14885 { "ptwrite", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_enum,
14886 gdb_xml_enums_boolean },
13b3a89b
FW
14887 { "event-tracing", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_enum,
14888 gdb_xml_enums_boolean },
1bcb9dcf
MM
14889 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14890};
14891
14892static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14893 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14894 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14895};
14896
14897static const struct gdb_xml_element btrace_conf_children[] = {
14898 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14899 parse_xml_btrace_conf_bts, NULL },
14900 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14901 parse_xml_btrace_conf_pt, NULL },
14902 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14903};
14904
14905static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14906 { "version", GDB_XML_AF_NONE, NULL, NULL },
14907 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14908};
14909
14910static const struct gdb_xml_element btrace_conf_elements[] = {
14911 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14912 GDB_XML_EF_NONE, NULL, NULL },
14913 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14914};
14915
14916#endif /* defined (HAVE_LIBEXPAT) */
14917
14918/* Parse a branch trace configuration xml document XML into CONF. */
14919
14920static void
14921parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14922{
14923#if defined (HAVE_LIBEXPAT)
14924
14925 int errcode;
14926 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14927 btrace_conf_elements, xml, conf);
14928 if (errcode != 0)
14929 error (_("Error parsing branch trace configuration."));
14930
14931#else /* !defined (HAVE_LIBEXPAT) */
14932
14933 error (_("Cannot process the branch trace configuration. XML support "
14934 "was disabled at compile time."));
14935
14936#endif /* !defined (HAVE_LIBEXPAT) */
14937}
14938
f4abbc16
MM
14939/* Reset our idea of our target's btrace configuration. */
14940
14941static void
6b8edb51 14942remote_btrace_reset (remote_state *rs)
f4abbc16 14943{
f4abbc16
MM
14944 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14945}
14946
f4abbc16
MM
14947/* Synchronize the configuration with the target. */
14948
6b8edb51
PA
14949void
14950remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 14951{
d33501a5
MM
14952 struct remote_state *rs;
14953 char *buf, *pos, *endbuf;
14954
14955 rs = get_remote_state ();
8d64371b 14956 buf = rs->buf.data ();
d33501a5
MM
14957 endbuf = buf + get_remote_packet_size ();
14958
ff52c073 14959 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
d33501a5
MM
14960 && conf->bts.size != rs->btrace_config.bts.size)
14961 {
14962 pos = buf;
ff52c073
CS
14963 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14964 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
dda83cd7 14965 conf->bts.size);
d33501a5
MM
14966
14967 putpkt (buf);
aa7b36b8 14968 getpkt (&rs->buf);
d33501a5 14969
94a94c90
AH
14970 packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size);
14971 if (result.status () == PACKET_ERROR)
14972 error (_("Failed to configure the BTS buffer size: %s"), result.err_msg ());
d33501a5
MM
14973
14974 rs->btrace_config.bts.size = conf->bts.size;
14975 }
b20a6524 14976
ff52c073 14977 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
b20a6524
MM
14978 && conf->pt.size != rs->btrace_config.pt.size)
14979 {
14980 pos = buf;
ff52c073
CS
14981 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14982 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
dda83cd7 14983 conf->pt.size);
b20a6524
MM
14984
14985 putpkt (buf);
aa7b36b8 14986 getpkt (&rs->buf);
b20a6524 14987
94a94c90
AH
14988 packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size);
14989 if (result.status () == PACKET_ERROR)
14990 error (_("Failed to configure the trace buffer size: %s"), result.err_msg ());
b20a6524
MM
14991
14992 rs->btrace_config.pt.size = conf->pt.size;
14993 }
ccc48080
FW
14994
14995 if ((m_features.packet_support (PACKET_Qbtrace_conf_pt_ptwrite)
14996 == PACKET_ENABLE)
14997 && conf->pt.ptwrite != rs->btrace_config.pt.ptwrite)
14998 {
14999 pos = buf;
15000 const char *ptw = conf->pt.ptwrite ? "yes" : "no";
15001 const char *name
15002 = packets_descriptions[PACKET_Qbtrace_conf_pt_ptwrite].name;
15003 pos += xsnprintf (pos, endbuf - pos, "%s=\"%s\"", name, ptw);
15004
15005 putpkt (buf);
15006 getpkt (&rs->buf, 0);
15007
15008 packet_result result
15009 = m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_ptwrite);
15010 if (result.status () == PACKET_ERROR)
15011 {
15012 if (buf[0] == 'E' && buf[1] == '.')
15013 error (_("Failed to sync ptwrite config: %s"), buf + 2);
15014 else
15015 error (_("Failed to sync ptwrite config."));
15016 }
15017
15018 rs->btrace_config.pt.ptwrite = conf->pt.ptwrite;
15019 }
13b3a89b
FW
15020
15021 /* Event tracing is a user setting, warn if it is set but the target
15022 doesn't support it. */
15023 if ((m_features.packet_support (PACKET_Qbtrace_conf_pt_event_tracing)
15024 != PACKET_ENABLE)
15025 && conf->pt.event_tracing)
15026 warning (_("Target does not support event-tracing."));
15027
15028 if ((m_features.packet_support (PACKET_Qbtrace_conf_pt_event_tracing)
15029 == PACKET_ENABLE)
15030 && conf->pt.event_tracing != rs->btrace_config.pt.event_tracing)
15031 {
15032 pos = buf;
15033 const char *event_tracing = conf->pt.event_tracing ? "yes" : "no";
15034 const char *name
15035 = packets_descriptions[PACKET_Qbtrace_conf_pt_event_tracing].name;
15036 pos += xsnprintf (pos, endbuf - pos, "%s=\"%s\"", name, event_tracing);
15037
15038 putpkt (buf);
15039 getpkt (&rs->buf, 0);
15040
15041 packet_result result
15042 = m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_event_tracing);
15043 if (result.status () == PACKET_ERROR)
15044 {
15045 if (buf[0] == 'E' && buf[1] == '.')
15046 error (_("Failed to sync event-tracing config: %s"), buf + 2);
15047 else
15048 error (_("Failed to sync event-tracing config."));
15049 }
15050
15051 rs->btrace_config.pt.event_tracing = conf->pt.event_tracing;
15052 }
f4abbc16
MM
15053}
15054
0d8cbc5f 15055/* Read TP's btrace configuration from the target and store it into CONF. */
f4abbc16
MM
15056
15057static void
cdda72c2 15058btrace_read_config (thread_info *tp, btrace_config *conf)
f4abbc16 15059{
0d8cbc5f
MM
15060 /* target_read_stralloc relies on INFERIOR_PTID. */
15061 scoped_restore_current_thread restore_thread;
15062 switch_to_thread (tp);
15063
6b09f134 15064 std::optional<gdb::char_vector> xml
328d42d8
SM
15065 = target_read_stralloc (current_inferior ()->top_target (),
15066 TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
15067 if (xml)
15068 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
15069}
15070
c0272db5
TW
15071/* Maybe reopen target btrace. */
15072
6b8edb51
PA
15073void
15074remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
15075{
15076 struct remote_state *rs = get_remote_state ();
c0272db5 15077 int btrace_target_pushed = 0;
15766370 15078#if !defined (HAVE_LIBIPT)
c0272db5 15079 int warned = 0;
15766370 15080#endif
c0272db5 15081
aedbe3bb
CM
15082 /* Don't bother walking the entirety of the remote thread list when
15083 we know the feature isn't supported by the remote. */
ff52c073 15084 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
aedbe3bb
CM
15085 return;
15086
5b6d1e4f 15087 for (thread_info *tp : all_non_exited_threads (this))
c0272db5 15088 {
c0272db5 15089 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
0d8cbc5f 15090 btrace_read_config (tp, &rs->btrace_config);
c0272db5
TW
15091
15092 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
15093 continue;
15094
15095#if !defined (HAVE_LIBIPT)
15096 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
15097 {
15098 if (!warned)
15099 {
15100 warned = 1;
c4e12631
MM
15101 warning (_("Target is recording using Intel Processor Trace "
15102 "but support was disabled at compile time."));
c0272db5
TW
15103 }
15104
15105 continue;
15106 }
15107#endif /* !defined (HAVE_LIBIPT) */
15108
15109 /* Push target, once, but before anything else happens. This way our
15110 changes to the threads will be cleaned up by unpushing the target
15111 in case btrace_read_config () throws. */
15112 if (!btrace_target_pushed)
15113 {
15114 btrace_target_pushed = 1;
15115 record_btrace_push_target ();
6cb06a8c
TT
15116 gdb_printf (_("Target is recording using %s.\n"),
15117 btrace_format_string (rs->btrace_config.format));
c0272db5
TW
15118 }
15119
cdda72c2
MM
15120 tp->btrace.target
15121 = new btrace_target_info { tp->ptid, rs->btrace_config };
c0272db5 15122 }
c0272db5
TW
15123}
15124
9accd112
MM
15125/* Enable branch tracing. */
15126
f6ac5f3d 15127struct btrace_target_info *
696c0d5e
MM
15128remote_target::enable_btrace (thread_info *tp,
15129 const struct btrace_config *conf)
9accd112 15130{
b20a6524 15131 struct packet_config *packet = NULL;
9accd112 15132 struct remote_state *rs = get_remote_state ();
8d64371b
TT
15133 char *buf = rs->buf.data ();
15134 char *endbuf = buf + get_remote_packet_size ();
9accd112 15135
ff52c073 15136 unsigned int which_packet;
b20a6524
MM
15137 switch (conf->format)
15138 {
15139 case BTRACE_FORMAT_BTS:
ff52c073 15140 which_packet = PACKET_Qbtrace_bts;
b20a6524 15141 break;
b20a6524 15142 case BTRACE_FORMAT_PT:
ff52c073 15143 which_packet = PACKET_Qbtrace_pt;
b20a6524 15144 break;
ff52c073
CS
15145 default:
15146 internal_error (_("Bad branch btrace format: %u."),
15147 (unsigned int) conf->format);
b20a6524
MM
15148 }
15149
ff52c073 15150 packet = &m_features.m_protocol_packets[which_packet];
b20a6524 15151 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
15152 error (_("Target does not support branch tracing."));
15153
f4abbc16
MM
15154 btrace_sync_conf (conf);
15155
696c0d5e 15156 ptid_t ptid = tp->ptid;
9accd112
MM
15157 set_general_thread (ptid);
15158
ff52c073
CS
15159 buf += xsnprintf (buf, endbuf - buf, "%s",
15160 packets_descriptions[which_packet].name);
9accd112 15161 putpkt (rs->buf);
aa7b36b8 15162 getpkt (&rs->buf);
9accd112 15163
94a94c90
AH
15164 packet_result result = m_features.packet_ok (rs->buf, which_packet);
15165 if (result.status () == PACKET_ERROR)
15166 error (_("Could not enable branch tracing for %s: %s"),
15167 target_pid_to_str (ptid).c_str (), result.err_msg ());
9accd112 15168
cdda72c2 15169 btrace_target_info *tinfo = new btrace_target_info { ptid };
9accd112 15170
f4abbc16
MM
15171 /* If we fail to read the configuration, we lose some information, but the
15172 tracing itself is not impacted. */
a70b8144 15173 try
492d29ea 15174 {
0d8cbc5f 15175 btrace_read_config (tp, &tinfo->conf);
492d29ea 15176 }
230d2906 15177 catch (const gdb_exception_error &err)
492d29ea
PA
15178 {
15179 if (err.message != NULL)
3d6e9d23 15180 warning ("%s", err.what ());
492d29ea 15181 }
f4abbc16 15182
9accd112
MM
15183 return tinfo;
15184}
15185
15186/* Disable branch tracing. */
15187
f6ac5f3d
PA
15188void
15189remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112 15190{
9accd112 15191 struct remote_state *rs = get_remote_state ();
8d64371b
TT
15192 char *buf = rs->buf.data ();
15193 char *endbuf = buf + get_remote_packet_size ();
9accd112 15194
ff52c073 15195 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112
MM
15196 error (_("Target does not support branch tracing."));
15197
15198 set_general_thread (tinfo->ptid);
15199
ff52c073
CS
15200 buf += xsnprintf (buf, endbuf - buf, "%s",
15201 packets_descriptions[PACKET_Qbtrace_off].name);
9accd112 15202 putpkt (rs->buf);
aa7b36b8 15203 getpkt (&rs->buf);
9accd112 15204
94a94c90
AH
15205 packet_result result = m_features.packet_ok (rs->buf, PACKET_Qbtrace_off);
15206 if (result.status () == PACKET_ERROR)
9accd112 15207 error (_("Could not disable branch tracing for %s: %s"),
94a94c90 15208 target_pid_to_str (tinfo->ptid).c_str (), result.err_msg ());
9accd112 15209
cdda72c2 15210 delete tinfo;
9accd112
MM
15211}
15212
15213/* Teardown branch tracing. */
15214
f6ac5f3d
PA
15215void
15216remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
15217{
15218 /* We must not talk to the target during teardown. */
cdda72c2 15219 delete tinfo;
9accd112
MM
15220}
15221
15222/* Read the branch trace. */
15223
f6ac5f3d
PA
15224enum btrace_error
15225remote_target::read_btrace (struct btrace_data *btrace,
15226 struct btrace_target_info *tinfo,
15227 enum btrace_read_type type)
9accd112 15228{
9accd112 15229 const char *annex;
9accd112 15230
ff52c073 15231 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
15232 error (_("Target does not support branch tracing."));
15233
15234#if !defined(HAVE_LIBEXPAT)
15235 error (_("Cannot process branch tracing result. XML parsing not supported."));
15236#endif
15237
15238 switch (type)
15239 {
864089d2 15240 case BTRACE_READ_ALL:
9accd112
MM
15241 annex = "all";
15242 break;
864089d2 15243 case BTRACE_READ_NEW:
9accd112
MM
15244 annex = "new";
15245 break;
969c39fb
MM
15246 case BTRACE_READ_DELTA:
15247 annex = "delta";
15248 break;
9accd112 15249 default:
f34652de 15250 internal_error (_("Bad branch tracing read type: %u."),
9accd112
MM
15251 (unsigned int) type);
15252 }
15253
6b09f134 15254 std::optional<gdb::char_vector> xml
328d42d8
SM
15255 = target_read_stralloc (current_inferior ()->top_target (),
15256 TARGET_OBJECT_BTRACE, annex);
9018be22 15257 if (!xml)
969c39fb 15258 return BTRACE_ERR_UNKNOWN;
9accd112 15259
9018be22 15260 parse_xml_btrace (btrace, xml->data ());
9accd112 15261
969c39fb 15262 return BTRACE_ERR_NONE;
9accd112
MM
15263}
15264
f6ac5f3d
PA
15265const struct btrace_config *
15266remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
15267{
15268 return &tinfo->conf;
15269}
15270
57810aa7 15271bool
f6ac5f3d 15272remote_target::augmented_libraries_svr4_read ()
ced63ec0 15273{
ff52c073
CS
15274 return
15275 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
15276 == PACKET_ENABLE);
ced63ec0
GB
15277}
15278
9dd130a0
TT
15279/* Implementation of to_load. */
15280
f6ac5f3d
PA
15281void
15282remote_target::load (const char *name, int from_tty)
9dd130a0
TT
15283{
15284 generic_load (name, from_tty);
15285}
15286
c78fa86a
GB
15287/* Accepts an integer PID; returns a string representing a file that
15288 can be opened on the remote side to get the symbols for the child
15289 process. Returns NULL if the operation is not supported. */
15290
0e90c441 15291const char *
f6ac5f3d 15292remote_target::pid_to_exec_file (int pid)
c78fa86a 15293{
6b09f134 15294 static std::optional<gdb::char_vector> filename;
835205d0 15295 char *annex = NULL;
c78fa86a 15296
ff52c073 15297 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
c78fa86a
GB
15298 return NULL;
15299
5b6d1e4f 15300 inferior *inf = find_inferior_pid (this, pid);
835205d0 15301 if (inf == NULL)
f34652de 15302 internal_error (_("not currently attached to process %d"), pid);
835205d0
GB
15303
15304 if (!inf->fake_pid_p)
15305 {
15306 const int annex_size = 9;
15307
224c3ddb 15308 annex = (char *) alloca (annex_size);
835205d0
GB
15309 xsnprintf (annex, annex_size, "%x", pid);
15310 }
15311
328d42d8 15312 filename = target_read_stralloc (current_inferior ()->top_target (),
c78fa86a
GB
15313 TARGET_OBJECT_EXEC_FILE, annex);
15314
9018be22 15315 return filename ? filename->data () : nullptr;
c78fa86a
GB
15316}
15317
750ce8d1
YQ
15318/* Implement the to_can_do_single_step target_ops method. */
15319
f6ac5f3d
PA
15320int
15321remote_target::can_do_single_step ()
750ce8d1
YQ
15322{
15323 /* We can only tell whether target supports single step or not by
15324 supported s and S vCont actions if the stub supports vContSupported
15325 feature. If the stub doesn't support vContSupported feature,
15326 we have conservatively to think target doesn't supports single
15327 step. */
ff52c073 15328 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
750ce8d1
YQ
15329 {
15330 struct remote_state *rs = get_remote_state ();
15331
750ce8d1
YQ
15332 return rs->supports_vCont.s && rs->supports_vCont.S;
15333 }
15334 else
15335 return 0;
15336}
15337
3a00c802
PA
15338/* Implementation of the to_execution_direction method for the remote
15339 target. */
15340
f6ac5f3d
PA
15341enum exec_direction_kind
15342remote_target::execution_direction ()
3a00c802
PA
15343{
15344 struct remote_state *rs = get_remote_state ();
15345
15346 return rs->last_resume_exec_dir;
15347}
15348
f6327dcb
KB
15349/* Return pointer to the thread_info struct which corresponds to
15350 THREAD_HANDLE (having length HANDLE_LEN). */
15351
f6ac5f3d
PA
15352thread_info *
15353remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
15354 int handle_len,
15355 inferior *inf)
f6327dcb 15356{
5b6d1e4f 15357 for (thread_info *tp : all_non_exited_threads (this))
f6327dcb 15358 {
7aabaf9d 15359 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
15360
15361 if (tp->inf == inf && priv != NULL)
dda83cd7 15362 {
7aabaf9d 15363 if (handle_len != priv->thread_handle.size ())
f6327dcb 15364 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
dda83cd7 15365 handle_len, priv->thread_handle.size ());
7aabaf9d 15366 if (memcmp (thread_handle, priv->thread_handle.data (),
dda83cd7 15367 handle_len) == 0)
f6327dcb
KB
15368 return tp;
15369 }
15370 }
15371
15372 return NULL;
15373}
15374
1f08d324 15375gdb::array_view<const gdb_byte>
3d6c6204
KB
15376remote_target::thread_info_to_thread_handle (struct thread_info *tp)
15377{
15378 remote_thread_info *priv = get_remote_thread_info (tp);
15379 return priv->thread_handle;
15380}
15381
57810aa7 15382bool
f6ac5f3d 15383remote_target::can_async_p ()
6426a772 15384{
fce6cd34
AB
15385 /* This flag should be checked in the common target.c code. */
15386 gdb_assert (target_async_permitted);
75c99385 15387
fce6cd34 15388 /* We're async whenever the serial device can. */
e84ffe7b 15389 return get_remote_state ()->can_async_p ();
6426a772
JM
15390}
15391
57810aa7 15392bool
f6ac5f3d 15393remote_target::is_async_p ()
6426a772 15394{
23860348 15395 /* We're async whenever the serial device is. */
e84ffe7b 15396 return get_remote_state ()->is_async_p ();
6426a772
JM
15397}
15398
2acceee2
JM
15399/* Pass the SERIAL event on and up to the client. One day this code
15400 will be able to delay notifying the client of an event until the
23860348 15401 point where an entire packet has been received. */
2acceee2 15402
2acceee2
JM
15403static serial_event_ftype remote_async_serial_handler;
15404
6426a772 15405static void
819cc324 15406remote_async_serial_handler (struct serial *scb, void *context)
6426a772 15407{
8f6606b6 15408 /* Don't propagate error information up to the client. Instead let
2acceee2 15409 the client find out about the error by querying the target. */
b1a35af2 15410 inferior_event_handler (INF_REG_EVENT);
2acceee2
JM
15411}
15412
5b6d1e4f
PA
15413int
15414remote_target::async_wait_fd ()
15415{
15416 struct remote_state *rs = get_remote_state ();
15417 return rs->remote_desc->fd;
15418}
15419
f6ac5f3d 15420void
4a570176 15421remote_target::async (bool enable)
2acceee2 15422{
5d93a237
TT
15423 struct remote_state *rs = get_remote_state ();
15424
6a3753b3 15425 if (enable)
2acceee2 15426 {
88b496c3 15427 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
15428
15429 /* If there are pending events in the stop reply queue tell the
15430 event loop to process them. */
953edf2b 15431 if (!rs->stop_reply_queue.empty ())
92b98b37
SM
15432 rs->mark_async_event_handler ();
15433
6efcd9a8
PA
15434 /* For simplicity, below we clear the pending events token
15435 without remembering whether it is marked, so here we always
15436 mark it. If there's actually no pending notification to
15437 process, this ends up being a no-op (other than a spurious
15438 event-loop wakeup). */
15439 if (target_is_non_stop_p ())
15440 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
15441 }
15442 else
b7d2e916
PA
15443 {
15444 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
15445 /* If the core is disabling async, it doesn't want to be
15446 disturbed with target events. Clear all async event sources
15447 too. */
92b98b37
SM
15448 rs->clear_async_event_handler ();
15449
6efcd9a8
PA
15450 if (target_is_non_stop_p ())
15451 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 15452 }
6426a772
JM
15453}
15454
65706a29
PA
15455/* Implementation of the to_thread_events method. */
15456
f6ac5f3d 15457void
2db17c87 15458remote_target::thread_events (bool enable)
65706a29
PA
15459{
15460 struct remote_state *rs = get_remote_state ();
15461 size_t size = get_remote_packet_size ();
65706a29 15462
ff52c073 15463 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
65706a29
PA
15464 return;
15465
26f047ce
PA
15466 if (rs->last_thread_events == enable)
15467 return;
15468
8d64371b 15469 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
65706a29 15470 putpkt (rs->buf);
aa7b36b8 15471 getpkt (&rs->buf);
65706a29 15472
94a94c90
AH
15473 packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadEvents);
15474 switch (result.status ())
65706a29
PA
15475 {
15476 case PACKET_OK:
8d64371b
TT
15477 if (strcmp (rs->buf.data (), "OK") != 0)
15478 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
26f047ce 15479 rs->last_thread_events = enable;
65706a29
PA
15480 break;
15481 case PACKET_ERROR:
94a94c90 15482 warning (_("Remote failure reply: %s"), result.err_msg ());
65706a29
PA
15483 break;
15484 case PACKET_UNKNOWN:
15485 break;
15486 }
15487}
15488
65c459ab
PA
15489/* Implementation of the supports_set_thread_options target
15490 method. */
15491
15492bool
15493remote_target::supports_set_thread_options (gdb_thread_options options)
15494{
15495 remote_state *rs = get_remote_state ();
15496 return (m_features.packet_support (PACKET_QThreadOptions) == PACKET_ENABLE
15497 && (rs->supported_thread_options & options) == options);
15498}
15499
15500/* For coalescing reasons, actually sending the options to the target
15501 happens at resume time, via this function. See target_resume for
15502 all-stop, and target_commit_resumed for non-stop. */
15503
15504void
15505remote_target::commit_requested_thread_options ()
15506{
15507 struct remote_state *rs = get_remote_state ();
15508
15509 if (m_features.packet_support (PACKET_QThreadOptions) != PACKET_ENABLE)
15510 return;
15511
15512 char *p = rs->buf.data ();
15513 char *endp = p + get_remote_packet_size ();
15514
15515 /* Clear options for all threads by default. Note that unlike
15516 vCont, the rightmost options that match a thread apply, so we
15517 don't have to worry about whether we can use wildcard ptids. */
15518 strcpy (p, "QThreadOptions;0");
15519 p += strlen (p);
15520
15521 /* Send the QThreadOptions packet stored in P. */
15522 auto flush = [&] ()
15523 {
15524 *p++ = '\0';
15525
15526 putpkt (rs->buf);
15527 getpkt (&rs->buf, 0);
15528
94a94c90
AH
15529 packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadOptions);
15530 switch (result.status ())
65c459ab
PA
15531 {
15532 case PACKET_OK:
15533 if (strcmp (rs->buf.data (), "OK") != 0)
15534 error (_("Remote refused setting thread options: %s"), rs->buf.data ());
15535 break;
15536 case PACKET_ERROR:
94a94c90 15537 error (_("Remote failure reply: %s"), result.err_msg ());
65c459ab
PA
15538 case PACKET_UNKNOWN:
15539 gdb_assert_not_reached ("PACKET_UNKNOWN");
15540 break;
15541 }
15542 };
15543
15544 /* Prepare P for another QThreadOptions packet. */
15545 auto restart = [&] ()
15546 {
15547 p = rs->buf.data ();
15548 strcpy (p, "QThreadOptions");
15549 p += strlen (p);
15550 };
15551
15552 /* Now set non-zero options for threads that need them. We don't
15553 bother with the case of all threads of a process wanting the same
15554 non-zero options as that's not an expected scenario. */
15555 for (thread_info *tp : all_non_exited_threads (this))
15556 {
15557 gdb_thread_options options = tp->thread_options ();
15558
15559 if (options == 0)
15560 continue;
15561
15562 /* It might be possible to we have more threads with options
15563 than can fit a single QThreadOptions packet. So build each
15564 options/thread pair in this separate buffer to make sure it
15565 fits. */
15566 constexpr size_t max_options_size = 100;
15567 char obuf[max_options_size];
15568 char *obuf_p = obuf;
15569 char *obuf_endp = obuf + max_options_size;
15570
15571 *obuf_p++ = ';';
15572 obuf_p += xsnprintf (obuf_p, obuf_endp - obuf_p, "%s",
9c1f84c9 15573 phex_nz (options));
65c459ab
PA
15574 if (tp->ptid != magic_null_ptid)
15575 {
15576 *obuf_p++ = ':';
15577 obuf_p = write_ptid (obuf_p, obuf_endp, tp->ptid);
15578 }
15579
15580 size_t osize = obuf_p - obuf;
15581 if (osize > endp - p)
15582 {
15583 /* This new options/thread pair doesn't fit the packet
15584 buffer. Send what we have already. */
15585 flush ();
15586 restart ();
15587
15588 /* Should now fit. */
15589 gdb_assert (osize <= endp - p);
15590 }
15591
15592 memcpy (p, obuf, osize);
15593 p += osize;
15594 }
15595
15596 flush ();
15597}
15598
d471ea57 15599static void
981a3fb3 15600show_remote_cmd (const char *args, int from_tty)
d471ea57 15601{
37a105a1 15602 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 15603 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 15604 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 15605 struct ui_out *uiout = current_uiout;
37a105a1 15606
2e783024 15607 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
7627b430 15608 const ui_file_style cmd_style = command_style.style ();
37a105a1
DJ
15609 for (; list != NULL; list = list->next)
15610 if (strcmp (list->name, "Z-packet") == 0)
15611 continue;
427c3a89
DJ
15612 else if (list->type == not_set_cmd)
15613 /* Alias commands are exactly like the original, except they
15614 don't have the normal type. */
15615 continue;
15616 else
37a105a1 15617 {
2e783024 15618 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 15619
7627b430 15620 uiout->field_string ("name", list->name, cmd_style);
112e8700 15621 uiout->text (": ");
427c3a89 15622 if (list->type == show_cmd)
f5c4fcd9 15623 do_show_command (NULL, from_tty, list);
427c3a89
DJ
15624 else
15625 cmd_func (list, NULL, from_tty);
37a105a1 15626 }
d471ea57 15627}
5a2468f5 15628
74daa597
SM
15629/* Some change happened in PSPACE's objfile list (obfiles added or removed),
15630 offer all inferiors using that program space a change to look up symbols. */
0f71a2f6 15631
dc8acb97 15632static void
74daa597 15633remote_objfile_changed_check_symbols (program_space *pspace)
dc8acb97 15634{
06c7226e
SM
15635 /* The affected program space is possibly shared by multiple inferiors.
15636 Consider sending a qSymbol packet for each of the inferiors using that
15637 program space. */
15638 for (inferior *inf : all_inferiors ())
15639 {
15640 if (inf->pspace != pspace)
15641 continue;
122373f7 15642
06c7226e
SM
15643 /* Check whether the inferior's process target is a remote target. */
15644 remote_target *remote = as_remote_target (inf->process_target ());
15645 if (remote == nullptr)
15646 continue;
15647
15648 /* When we are attaching or handling a fork child and the shared library
15649 subsystem reads the list of loaded libraries, we receive new objfile
15650 events in between each found library. The libraries are read in an
15651 undefined order, so if we gave the remote side a chance to look up
15652 symbols between each objfile, we might give it an inconsistent picture
15653 of the inferior. It could appear that a library A appears loaded but
15654 a library B does not, even though library A requires library B. That
15655 would present a state that couldn't normally exist in the inferior.
15656
15657 So, skip these events, we'll give the remote a chance to look up
15658 symbols once all the loaded libraries and their symbols are known to
15659 GDB. */
15660 if (inf->in_initial_library_scan)
15661 continue;
15662
15663 if (!remote->has_execution (inf))
15664 continue;
15665
15666 /* Need to switch to a specific thread, because remote_check_symbols will
287de656 15667 set the general thread using INFERIOR_PTID.
122373f7 15668
06c7226e
SM
15669 It's possible to have inferiors with no thread here, because we are
15670 called very early in the connection process, while the inferior is
15671 being set up, before threads are added. Just skip it, start_remote_1
15672 also calls remote_check_symbols when it's done setting things up. */
15673 thread_info *thread = any_thread_of_inferior (inf);
15674 if (thread != nullptr)
15675 {
15676 scoped_restore_current_thread restore_thread;
15677 switch_to_thread (thread);
15678 remote->remote_check_symbols ();
15679 }
15680 }
dc8acb97
MS
15681}
15682
74daa597
SM
15683/* Function to be called whenever a new objfile (shlib) is detected. */
15684
15685static void
15686remote_new_objfile (struct objfile *objfile)
15687{
134a0a10 15688 remote_objfile_changed_check_symbols (objfile->pspace ());
74daa597
SM
15689}
15690
00bf0b85
SS
15691/* Pull all the tracepoints defined on the target and create local
15692 data structures representing them. We don't want to create real
15693 tracepoints yet, we don't want to mess up the user's existing
15694 collection. */
7a78108a 15695
f6ac5f3d
PA
15696int
15697remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 15698{
00bf0b85
SS
15699 struct remote_state *rs = get_remote_state ();
15700 char *p;
d5551862 15701
00bf0b85
SS
15702 /* Ask for a first packet of tracepoint definition. */
15703 putpkt ("qTfP");
aa7b36b8 15704 getpkt (&rs->buf);
8d64371b 15705 p = rs->buf.data ();
00bf0b85 15706 while (*p && *p != 'l')
d5551862 15707 {
00bf0b85
SS
15708 parse_tracepoint_definition (p, utpp);
15709 /* Ask for another packet of tracepoint definition. */
15710 putpkt ("qTsP");
aa7b36b8 15711 getpkt (&rs->buf);
8d64371b 15712 p = rs->buf.data ();
d5551862 15713 }
00bf0b85 15714 return 0;
d5551862
SS
15715}
15716
f6ac5f3d
PA
15717int
15718remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 15719{
00bf0b85 15720 struct remote_state *rs = get_remote_state ();
d5551862 15721 char *p;
d5551862 15722
00bf0b85
SS
15723 /* Ask for a first packet of variable definition. */
15724 putpkt ("qTfV");
aa7b36b8 15725 getpkt (&rs->buf);
8d64371b 15726 p = rs->buf.data ();
00bf0b85 15727 while (*p && *p != 'l')
d5551862 15728 {
00bf0b85
SS
15729 parse_tsv_definition (p, utsvp);
15730 /* Ask for another packet of variable definition. */
15731 putpkt ("qTsV");
aa7b36b8 15732 getpkt (&rs->buf);
8d64371b 15733 p = rs->buf.data ();
d5551862 15734 }
00bf0b85 15735 return 0;
d5551862
SS
15736}
15737
c1e36e3e
PA
15738/* The "set/show range-stepping" show hook. */
15739
15740static void
15741show_range_stepping (struct ui_file *file, int from_tty,
15742 struct cmd_list_element *c,
15743 const char *value)
15744{
6cb06a8c
TT
15745 gdb_printf (file,
15746 _("Debugger's willingness to use range stepping "
15747 "is %s.\n"), value);
c1e36e3e
PA
15748}
15749
6b8edb51
PA
15750/* Return true if the vCont;r action is supported by the remote
15751 stub. */
15752
15753bool
15754remote_target::vcont_r_supported ()
15755{
ff52c073 15756 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
6b8edb51
PA
15757 && get_remote_state ()->supports_vCont.r);
15758}
15759
c1e36e3e
PA
15760/* The "set/show range-stepping" set hook. */
15761
15762static void
eb4c3f4a 15763set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
15764 struct cmd_list_element *c)
15765{
6b8edb51
PA
15766 /* When enabling, check whether range stepping is actually supported
15767 by the target, and warn if not. */
c1e36e3e
PA
15768 if (use_range_stepping)
15769 {
6b8edb51
PA
15770 remote_target *remote = get_current_remote_target ();
15771 if (remote == NULL
15772 || !remote->vcont_r_supported ())
15773 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
15774 }
15775}
15776
baf2b57f
SM
15777static void
15778show_remote_debug (struct ui_file *file, int from_tty,
15779 struct cmd_list_element *c, const char *value)
15780{
6cb06a8c
TT
15781 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15782 value);
baf2b57f
SM
15783}
15784
15785static void
15786show_remote_timeout (struct ui_file *file, int from_tty,
15787 struct cmd_list_element *c, const char *value)
15788{
6cb06a8c
TT
15789 gdb_printf (file,
15790 _("Timeout limit to wait for target to respond is %s.\n"),
15791 value);
baf2b57f
SM
15792}
15793
dbe692af
LM
15794/* Implement the "supports_memory_tagging" target_ops method. */
15795
15796bool
15797remote_target::supports_memory_tagging ()
15798{
ff52c073 15799 return m_features.remote_memory_tagging_p ();
2c2e7f87
LM
15800}
15801
15802/* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15803
15804static void
15805create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15806 size_t len, int type)
15807{
99d9c3b9 15808 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
2c2e7f87
LM
15809
15810 std::string request = string_printf ("qMemTags:%s,%s:%s",
15811 phex_nz (address, addr_size),
9c1f84c9
TV
15812 phex_nz (len),
15813 phex_nz (type));
2c2e7f87
LM
15814
15815 strcpy (packet.data (), request.c_str ());
15816}
15817
15818/* Parse the qMemTags packet reply into TAGS.
15819
15820 Return true if successful, false otherwise. */
15821
15822static bool
15823parse_fetch_memtags_reply (const gdb::char_vector &reply,
15824 gdb::byte_vector &tags)
15825{
15826 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15827 return false;
15828
15829 /* Copy the tag data. */
15830 tags = hex2bin (reply.data () + 1);
15831
15832 return true;
15833}
15834
15835/* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15836
15837static void
15838create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15839 size_t len, int type,
15840 const gdb::byte_vector &tags)
15841{
99d9c3b9 15842 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
2c2e7f87
LM
15843
15844 /* Put together the main packet, address and length. */
15845 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15846 phex_nz (address, addr_size),
9c1f84c9
TV
15847 phex_nz (len),
15848 phex_nz (type));
2c2e7f87
LM
15849 request += bin2hex (tags.data (), tags.size ());
15850
15851 /* Check if we have exceeded the maximum packet size. */
15852 if (packet.size () < request.length ())
15853 error (_("Contents too big for packet QMemTags."));
15854
15855 strcpy (packet.data (), request.c_str ());
dbe692af
LM
15856}
15857
c040e0b1
GR
15858static void
15859create_is_address_tagged_request (gdbarch *gdbarch, gdb::char_vector &packet,
15860 CORE_ADDR address)
15861{
15862 int addr_size;
15863 std::string request;
15864
15865 addr_size = gdbarch_addr_bit (gdbarch) / 8;
15866 request = string_printf ("qIsAddressTagged:%s", phex_nz (address, addr_size));
15867
15868 if (packet.size () < request.length () + 1)
15869 error (_("Contents too big for packet qIsAddressTagged."));
15870
15871 strcpy (packet.data (), request.c_str ());
15872}
15873
15874static bool
15875check_is_address_tagged_reply (remote_target *remote, gdb::char_vector &packet,
15876 bool &tagged)
15877{
15878 gdb_assert (remote != nullptr);
15879 /* Check reply and disable qIsAddressTagged usage if it's not supported. */
15880 packet_result result = remote->m_features.packet_ok (packet,
15881 PACKET_qIsAddressTagged);
15882
15883 /* Return false on error (Exx), empty reply (packet not supported), or reply
15884 size doesn't match 2 hex digits. */
15885 if ((result.status () != PACKET_OK) || (strlen (packet.data ()) != 2))
15886 return false;
15887
15888 gdb_byte reply;
15889 /* Convert only 2 hex digits, i.e. 1 byte in hex format. */
15890 hex2bin (packet.data (), &reply, 1);
15891
15892 if (reply == 0x00 || reply == 0x01)
15893 {
15894 tagged = !!reply;
15895 return true;
15896 }
15897
15898 /* Invalid reply. */
15899 return false;
15900}
15901
dbe692af
LM
15902/* Implement the "fetch_memtags" target_ops method. */
15903
15904bool
15905remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15906 gdb::byte_vector &tags, int type)
15907{
2c2e7f87 15908 /* Make sure the qMemTags packet is supported. */
ff52c073 15909 if (!m_features.remote_memory_tagging_p ())
2c2e7f87
LM
15910 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15911
15912 struct remote_state *rs = get_remote_state ();
15913
15914 create_fetch_memtags_request (rs->buf, address, len, type);
15915
15916 putpkt (rs->buf);
aa7b36b8 15917 getpkt (&rs->buf);
2c2e7f87
LM
15918
15919 return parse_fetch_memtags_reply (rs->buf, tags);
dbe692af
LM
15920}
15921
15922/* Implement the "store_memtags" target_ops method. */
15923
15924bool
15925remote_target::store_memtags (CORE_ADDR address, size_t len,
15926 const gdb::byte_vector &tags, int type)
15927{
2c2e7f87 15928 /* Make sure the QMemTags packet is supported. */
ff52c073 15929 if (!m_features.remote_memory_tagging_p ())
2c2e7f87
LM
15930 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15931
15932 struct remote_state *rs = get_remote_state ();
15933
15934 create_store_memtags_request (rs->buf, address, len, type, tags);
15935
15936 putpkt (rs->buf);
aa7b36b8 15937 getpkt (&rs->buf);
2c2e7f87
LM
15938
15939 /* Verify if the request was successful. */
ddb3f3d8 15940 return packet_check_result (rs->buf).status () == PACKET_OK;
dbe692af
LM
15941}
15942
7202f41f
GR
15943/* Implement the "is_address_tagged" target_ops method. */
15944
15945bool
15946remote_target::is_address_tagged (gdbarch *gdbarch, CORE_ADDR address)
15947{
c040e0b1
GR
15948 /* Firstly, attempt to check the address using the qIsAddressTagged
15949 packet. */
15950 if (m_features.packet_support (PACKET_qIsAddressTagged) != PACKET_DISABLE)
15951 {
15952 remote_target *remote = get_current_remote_target ();
15953 struct remote_state *rs = get_remote_state ();
15954 bool is_addr_tagged;
15955
15956 create_is_address_tagged_request (gdbarch, rs->buf, address);
15957
15958 putpkt (rs->buf);
15959 getpkt (&rs->buf);
15960
15961 /* If qIsAddressTagged is not supported PACKET_qIsAddressTagged will be
15962 set to PACKET_DISABLE so no further attempt is made to check addresses
15963 using this packet and the fallback mechanism below will be used
15964 instead. Also, if the check fails due to an error (Exx reply) the
15965 fallback is used too. Otherwise, the qIsAddressTagged query succeeded
15966 and is_addr_tagged is valid. */
15967 if (check_is_address_tagged_reply (remote, rs->buf, is_addr_tagged))
15968 return is_addr_tagged;
15969 }
15970
15971 /* Fallback to arch-specific method of checking whether an address is tagged
15972 in case check via qIsAddressTagged fails. */
7202f41f
GR
15973 return gdbarch_tagged_address_p (gdbarch, address);
15974}
15975
c39ebbf4
TV
15976/* Return true if remote target T is non-stop. */
15977
15978bool
15979remote_target_is_non_stop_p (remote_target *t)
15980{
15981 scoped_restore_current_thread restore_thread;
15982 switch_to_target_no_thread (t);
15983
15984 return target_is_non_stop_p ();
15985}
15986
754487e2
LM
15987#if GDB_SELF_TEST
15988
15989namespace selftests {
15990
15991static void
15992test_memory_tagging_functions ()
15993{
15994 remote_target remote;
15995
15996 struct packet_config *config
ff52c073 15997 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
754487e2
LM
15998
15999 scoped_restore restore_memtag_support_
16000 = make_scoped_restore (&config->support);
16001
648a8c61
GR
16002 struct gdbarch *gdbarch = current_inferior ()->arch ();
16003
754487e2
LM
16004 /* Test memory tagging packet support. */
16005 config->support = PACKET_SUPPORT_UNKNOWN;
16006 SELF_CHECK (remote.supports_memory_tagging () == false);
16007 config->support = PACKET_DISABLE;
16008 SELF_CHECK (remote.supports_memory_tagging () == false);
16009 config->support = PACKET_ENABLE;
16010 SELF_CHECK (remote.supports_memory_tagging () == true);
16011
16012 /* Setup testing. */
16013 gdb::char_vector packet;
16014 gdb::byte_vector tags, bv;
16015 std::string expected, reply;
16016 packet.resize (32000);
16017
16018 /* Test creating a qMemTags request. */
16019
16020 expected = "qMemTags:0,0:0";
16021 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
16022 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
16023
16024 expected = "qMemTags:deadbeef,10:1";
16025 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
16026 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
16027
16028 /* Test parsing a qMemTags reply. */
16029
16030 /* Error reply, tags vector unmodified. */
16031 reply = "E00";
16032 strcpy (packet.data (), reply.c_str ());
16033 tags.resize (0);
16034 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
16035 SELF_CHECK (tags.size () == 0);
16036
16037 /* Valid reply, tags vector updated. */
16038 tags.resize (0);
16039 bv.resize (0);
16040
16041 for (int i = 0; i < 5; i++)
16042 bv.push_back (i);
16043
16044 reply = "m" + bin2hex (bv.data (), bv.size ());
16045 strcpy (packet.data (), reply.c_str ());
16046
16047 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
16048 SELF_CHECK (tags.size () == 5);
16049
16050 for (int i = 0; i < 5; i++)
16051 SELF_CHECK (tags[i] == i);
16052
16053 /* Test creating a QMemTags request. */
16054
16055 /* Empty tag data. */
16056 tags.resize (0);
16057 expected = "QMemTags:0,0:0:";
16058 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
16059 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
16060 expected.length ()) == 0);
16061
16062 /* Non-empty tag data. */
16063 tags.resize (0);
16064 for (int i = 0; i < 5; i++)
16065 tags.push_back (i);
16066 expected = "QMemTags:deadbeef,ff:1:0001020304";
16067 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
16068 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
16069 expected.length ()) == 0);
648a8c61
GR
16070
16071 /* Test creating a qIsAddressTagged request. */
16072 expected = "qIsAddressTagged:deadbeef";
16073 create_is_address_tagged_request (gdbarch, packet, 0xdeadbeef);
16074 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
16075
16076 /* Test error reply on qIsAddressTagged request. */
16077 reply = "E00";
16078 strcpy (packet.data (), reply.c_str ());
16079 /* is_tagged must not change, hence it's tested too. */
16080 bool is_tagged = false;
16081 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16082 false);
16083 SELF_CHECK (is_tagged == false);
16084
16085 /* Test 'tagged' as reply. */
16086 reply = "01";
16087 strcpy (packet.data (), reply.c_str ());
16088 /* Because the byte is 01, is_tagged should be set to true. */
16089 is_tagged = false;
16090 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16091 true);
16092 SELF_CHECK (is_tagged == true);
16093
16094 /* Test 'not tagged' as reply. */
16095 reply = "00";
16096 strcpy (packet.data (), reply.c_str ());
16097 /* Because the byte is 00, is_tagged should be set to false. */
16098 is_tagged = true;
16099 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16100 true);
16101 SELF_CHECK (is_tagged == false);
16102
16103 /* Test an invalid reply (neither 00 nor 01). */
16104 reply = "04";
16105 strcpy (packet.data (), reply.c_str ());
16106 /* Because the byte is invalid is_tagged must not change. */
16107 is_tagged = false;
16108 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16109 false);
16110 SELF_CHECK (is_tagged == false);
16111
16112 /* Test malformed reply of incorrect length. */
16113 reply = "0104A590001234006";
16114 strcpy (packet.data (), reply.c_str ());
16115 /* Because this is a malformed reply is_tagged must not change. */
16116 is_tagged = false;
16117 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16118 false);
16119 SELF_CHECK (is_tagged == false);
16120
16121 /* Test empty reply. */
16122 reply = "";
16123 strcpy (packet.data (), reply.c_str ());
16124 /* is_tagged must not change, hence it's tested too. */
16125 is_tagged = true;
16126 /* On the previous tests, qIsAddressTagged packet was auto detected and set
16127 as supported. But an empty reply means the packet is unsupported, so for
16128 testing the empty reply the support is reset to unknown state, otherwise
16129 packet_ok will complain. */
16130 remote.m_features.m_protocol_packets[PACKET_qIsAddressTagged].support =
16131 PACKET_SUPPORT_UNKNOWN;
16132 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16133 false);
16134 SELF_CHECK (is_tagged == true);
754487e2
LM
16135}
16136
7e9d8a36
AH
16137static void
16138test_packet_check_result ()
16139{
16140 std::string buf = "E.msg";
ddb3f3d8 16141 packet_result result = packet_check_result (buf.data ());
7e9d8a36
AH
16142
16143 SELF_CHECK (result.status () == PACKET_ERROR);
16144 SELF_CHECK (strcmp(result.err_msg (), "msg") == 0);
16145
ddb3f3d8 16146 result = packet_check_result ("E01");
7e9d8a36
AH
16147 SELF_CHECK (result.status () == PACKET_ERROR);
16148 SELF_CHECK (strcmp(result.err_msg (), "01") == 0);
16149
ddb3f3d8 16150 SELF_CHECK (packet_check_result ("E1").status () == PACKET_OK);
7e9d8a36 16151
ddb3f3d8 16152 SELF_CHECK (packet_check_result ("E000").status () == PACKET_OK);
7e9d8a36 16153
ddb3f3d8 16154 result = packet_check_result ("E.");
7e9d8a36
AH
16155 SELF_CHECK (result.status () == PACKET_ERROR);
16156 SELF_CHECK (strcmp(result.err_msg (), "no error provided") == 0);
16157
ddb3f3d8 16158 SELF_CHECK (packet_check_result ("some response").status () == PACKET_OK);
36232719 16159
ddb3f3d8 16160 SELF_CHECK (packet_check_result ("").status () == PACKET_UNKNOWN);
7e9d8a36 16161}
b6fb76ec 16162} /* namespace selftests */
754487e2
LM
16163#endif /* GDB_SELF_TEST */
16164
5fe70629 16165INIT_GDB_FILE (remote)
c906108c 16166{
d9f719f1
PA
16167 add_target (remote_target_info, remote_target::open);
16168 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 16169
dc8acb97 16170 /* Hook into new objfile notification. */
c90e7d63 16171 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
74daa597
SM
16172 gdb::observers::all_objfiles_removed.attach
16173 (remote_objfile_changed_check_symbols, "remote");
dc8acb97 16174
c906108c
SS
16175#if 0
16176 init_remote_threadtests ();
16177#endif
16178
23860348 16179 /* set/show remote ... */
d471ea57 16180
0743fc83 16181 add_basic_prefix_cmd ("remote", class_maintenance, _("\
590042fc 16182Remote protocol specific variables.\n\
5a2468f5 16183Configure various remote-protocol specific variables such as\n\
590042fc 16184the packets being used."),
2f822da5 16185 &remote_set_cmdlist,
0743fc83 16186 0 /* allow-unknown */, &setlist);
1bedd215 16187 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
590042fc 16188Remote protocol specific variables.\n\
5a2468f5 16189Configure various remote-protocol specific variables such as\n\
590042fc 16190the packets being used."),
2f822da5 16191 &remote_show_cmdlist,
23860348 16192 0 /* allow-unknown */, &showlist);
5a2468f5 16193
1a966eab
AC
16194 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
16195Compare section data on target to the exec file.\n\
95cf3b38
DT
16196Argument is a single section name (default: all loaded sections).\n\
16197To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
16198 &cmdlist);
16199
e5b176f2 16200 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
1a966eab 16201Send an arbitrary packet to a remote target.\n\
c906108c
SS
16202 maintenance packet TEXT\n\
16203If GDB is talking to an inferior via the GDB serial protocol, then\n\
16204this command sends the string TEXT to the inferior, and displays the\n\
16205response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 16206terminating `#' character and checksum."),
c906108c
SS
16207 &maintenancelist);
16208
9f260536
SM
16209 set_show_commands remotebreak_cmds
16210 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7915a72c
AC
16211Set whether to send break if interrupted."), _("\
16212Show whether to send break if interrupted."), _("\
16213If set, a break, instead of a cntrl-c, is sent to the remote target."),
9f260536
SM
16214 set_remotebreak, show_remotebreak,
16215 &setlist, &showlist);
16216 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
16217 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
9a7071a8
JB
16218
16219 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
16220 interrupt_sequence_modes, &interrupt_sequence_mode,
16221 _("\
9a7071a8
JB
16222Set interrupt sequence to remote target."), _("\
16223Show interrupt sequence to remote target."), _("\
16224Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
16225 NULL, show_interrupt_sequence,
16226 &remote_set_cmdlist,
16227 &remote_show_cmdlist);
16228
16229 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
16230 &interrupt_on_connect, _("\
590042fc
PW
16231Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
16232Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
9a7071a8
JB
16233If set, interrupt sequence is sent to remote target."),
16234 NULL, NULL,
16235 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 16236
23860348 16237 /* Install commands for configuring memory read/write packets. */
11cf8741 16238
1a966eab
AC
16239 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
16240Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 16241 &setlist);
1a966eab
AC
16242 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
16243Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
16244 &showlist);
16245 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
16246 set_memory_write_packet_size, _("\
16247Set the maximum number of bytes per memory-write packet.\n\
16248Specify the number of bytes in a packet or 0 (zero) for the\n\
16249default packet size. The actual limit is further reduced\n\
fe4c3ca0
CS
16250dependent on the target. Specify \"fixed\" to disable the\n\
16251further restriction and \"limit\" to enable that restriction."),
11cf8741
JM
16252 &remote_set_cmdlist);
16253 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
16254 set_memory_read_packet_size, _("\
16255Set the maximum number of bytes per memory-read packet.\n\
16256Specify the number of bytes in a packet or 0 (zero) for the\n\
16257default packet size. The actual limit is further reduced\n\
fe4c3ca0
CS
16258dependent on the target. Specify \"fixed\" to disable the\n\
16259further restriction and \"limit\" to enable that restriction."),
11cf8741
JM
16260 &remote_set_cmdlist);
16261 add_cmd ("memory-write-packet-size", no_class,
16262 show_memory_write_packet_size,
1a966eab 16263 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
16264 &remote_show_cmdlist);
16265 add_cmd ("memory-read-packet-size", no_class,
16266 show_memory_read_packet_size,
1a966eab 16267 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 16268 &remote_show_cmdlist);
c906108c 16269
055303e2 16270 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
16271 &remote_hw_watchpoint_limit, _("\
16272Set the maximum number of target hardware watchpoints."), _("\
16273Show the maximum number of target hardware watchpoints."), _("\
055303e2
AB
16274Specify \"unlimited\" for unlimited hardware watchpoints."),
16275 NULL, show_hardware_watchpoint_limit,
16276 &remote_set_cmdlist,
16277 &remote_show_cmdlist);
16278 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
16279 no_class,
480a3f21
PW
16280 &remote_hw_watchpoint_length_limit, _("\
16281Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
16282Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
055303e2
AB
16283Specify \"unlimited\" to allow watchpoints of unlimited size."),
16284 NULL, show_hardware_watchpoint_length_limit,
480a3f21 16285 &remote_set_cmdlist, &remote_show_cmdlist);
055303e2 16286 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
16287 &remote_hw_breakpoint_limit, _("\
16288Set the maximum number of target hardware breakpoints."), _("\
16289Show the maximum number of target hardware breakpoints."), _("\
055303e2
AB
16290Specify \"unlimited\" for unlimited hardware breakpoints."),
16291 NULL, show_hardware_breakpoint_limit,
b3f42336 16292 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 16293
1b493192
PA
16294 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
16295 &remote_address_size, _("\
4d28ad1e
AC
16296Set the maximum size of the address (in bits) in a memory packet."), _("\
16297Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
16298 NULL,
16299 NULL, /* FIXME: i18n: */
16300 &setlist, &showlist);
c906108c 16301
ca4f7f8b
PA
16302 init_all_packet_configs ();
16303
ff52c073 16304 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
0f71a2f6 16305
e16e6389
TBA
16306 add_packet_config_cmd (PACKET_x, "x", "binary-upload", 0);
16307
ff52c073 16308 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
506fb367 16309
ff52c073
CS
16310 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
16311 0);
89be2091 16312
ff52c073
CS
16313 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
16314 "catch-syscalls", 0);
82075af2 16315
ff52c073
CS
16316 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
16317 "program-signals", 0);
9b224c5e 16318
ff52c073
CS
16319 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
16320 "set-working-dir", 0);
bc3b087d 16321
ff52c073
CS
16322 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
16323 "startup-with-shell", 0);
aefd8b33 16324
ff52c073
CS
16325 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
16326 "environment-hex-encoded", 0);
0a2dde4a 16327
ff52c073
CS
16328 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
16329 "environment-reset", 0);
0a2dde4a 16330
ff52c073
CS
16331 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
16332 "environment-unset", 0);
0a2dde4a 16333
ff52c073 16334 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
dc8acb97 16335
ff52c073 16336 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
d471ea57 16337
ff52c073 16338 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
b96ec7ac 16339
ff52c073 16340 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
d471ea57 16341
ff52c073 16342 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
d471ea57 16343
ff52c073 16344 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
d471ea57 16345
ff52c073 16346 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
d471ea57 16347
ff52c073 16348 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
d471ea57 16349
ff52c073
CS
16350 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
16351 "read-aux-vector", 0);
802188a7 16352
ff52c073
CS
16353 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
16354 "pid-to-exec-file", 0);
c78fa86a 16355
ff52c073 16356 add_packet_config_cmd (PACKET_qXfer_features,
23181151
DJ
16357 "qXfer:features:read", "target-features", 0);
16358
ff52c073
CS
16359 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
16360 "library-info", 0);
cfa9d6d9 16361
ff52c073 16362 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
2268b414
JK
16363 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
16364
ff52c073
CS
16365 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
16366 "memory-map", 0);
fd79ecee 16367
ff52c073 16368 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
07e059b5 16369
ff52c073
CS
16370 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
16371 0);
dc146f7c 16372
ff52c073
CS
16373 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
16374 "read-siginfo-object", 0);
4aa995e1 16375
ff52c073
CS
16376 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
16377 "write-siginfo-object", 0);
4aa995e1 16378
ff52c073
CS
16379 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
16380 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 16381
ff52c073
CS
16382 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
16383 "unwind-info-block", 0);
169081d0 16384
ff52c073
CS
16385 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
16386 "get-thread-local-storage-address", 0);
38691318 16387
ff52c073
CS
16388 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
16389 "get-thread-information-block-address", 0);
711e434b 16390
ff52c073 16391 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
40ab02ce 16392
ff52c073 16393 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
40ab02ce 16394
ff52c073
CS
16395 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
16396 0);
be2a5f71 16397
ff52c073
CS
16398 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
16399 "search-memory", 0);
08388c79 16400
ff52c073 16401 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
bd3eecc3 16402
ff52c073 16403 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15a201c8 16404
ff52c073 16405 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
a6b151f1 16406
ff52c073 16407 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
a6b151f1 16408
ff52c073
CS
16409 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
16410 0);
a6b151f1 16411
ff52c073 16412 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
a6b151f1 16413
ff52c073
CS
16414 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
16415 0);
a6b151f1 16416
ff52c073
CS
16417 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
16418 "hostio-readlink", 0);
b9e7b9c3 16419
ff52c073 16420 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
0a93529c 16421
3055e3d2
AB
16422 add_packet_config_cmd (PACKET_vFile_stat, "vFile:stat", "hostio-stat", 0);
16423
2c91540a
AB
16424 add_packet_config_cmd (PACKET_vFile_lstat, "vFile:lstat", "hostio-lstat", 0);
16425
ff52c073 16426 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
2d717e4f 16427
ff52c073 16428 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
2d717e4f 16429
ff52c073 16430 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
a6f3e723 16431
ff52c073 16432 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
82f73884 16433
ff52c073 16434 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
0b16c5cf 16435
ff52c073
CS
16436 add_packet_config_cmd (PACKET_ConditionalTracepoints,
16437 "ConditionalTracepoints", "conditional-tracepoints",
16438 0);
3788aec7 16439
ff52c073
CS
16440 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
16441 "ConditionalBreakpoints", "conditional-breakpoints",
16442 0);
3788aec7 16443
ff52c073 16444 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
d3ce09f5
SS
16445 "breakpoint-commands", 0);
16446
ff52c073
CS
16447 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
16448 "fast-tracepoints", 0);
782b2b07 16449
ff52c073
CS
16450 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
16451 "TracepointSource", 0);
409873ef 16452
ff52c073 16453 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
d914c394 16454
ff52c073
CS
16455 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
16456 "static-tracepoints", 0);
0fb4aa4b 16457
ff52c073
CS
16458 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
16459 "install-in-trace", 0);
1e4d1764 16460
ff52c073 16461 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
dda83cd7 16462 "qXfer:statictrace:read", "read-sdata-object", 0);
0fb4aa4b 16463
ff52c073
CS
16464 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
16465 "read-fdpic-loadmap", 0);
78d85199 16466
ff52c073
CS
16467 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
16468 "disable-randomization", 0);
03583c20 16469
ff52c073 16470 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
d1feda86 16471
ff52c073
CS
16472 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
16473 "trace-buffer-size", 0);
f6f899bf 16474
ff52c073
CS
16475 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
16476 0);
9accd112 16477
ff52c073
CS
16478 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
16479 0);
b20a6524 16480
ff52c073
CS
16481 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
16482 0);
9accd112 16483
ff52c073 16484 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
9accd112 16485
ff52c073
CS
16486 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
16487 "read-btrace-conf", 0);
f4abbc16 16488
ff52c073
CS
16489 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
16490 "btrace-conf-bts-size", 0);
d33501a5 16491
ff52c073
CS
16492 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
16493 "multiprocess-feature", 0);
73b8c1fd 16494
ff52c073
CS
16495 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
16496 "swbreak-feature", 0);
f7e6eed5 16497
ff52c073
CS
16498 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
16499 "hwbreak-feature", 0);
f7e6eed5 16500
ff52c073
CS
16501 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
16502 "fork-event-feature", 0);
89245bc0 16503
ff52c073
CS
16504 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
16505 "vfork-event-feature", 0);
89245bc0 16506
ff52c073
CS
16507 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
16508 "btrace-conf-pt-size", 0);
b20a6524 16509
ccc48080
FW
16510 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_ptwrite, "Qbtrace-conf:pt:ptwrite",
16511 "btrace-conf-pt-ptwrite", 0);
16512
13b3a89b
FW
16513 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_event_tracing,
16514 "Qbtrace-conf:pt:event-tracing",
16515 "btrace-conf-pt-event-tracing", 0);
16516
ff52c073
CS
16517 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
16518 "verbose-resume-supported", 0);
750ce8d1 16519
ff52c073
CS
16520 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
16521 "exec-event-feature", 0);
94585166 16522
ff52c073 16523 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
de979965 16524
ff52c073
CS
16525 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
16526 0);
65706a29 16527
65c459ab
PA
16528 add_packet_config_cmd (PACKET_QThreadOptions, "QThreadOptions",
16529 "thread-options", 0);
16530
ff52c073
CS
16531 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
16532 "no-resumed-stop-reply", 0);
f2faf941 16533
ff52c073 16534 add_packet_config_cmd (PACKET_memory_tagging_feature,
2c2e7f87
LM
16535 "memory-tagging-feature", "memory-tagging-feature", 0);
16536
c040e0b1
GR
16537 add_packet_config_cmd (PACKET_qIsAddressTagged,
16538 "qIsAddressTagged", "memory-tagging-address-check", 0);
16539
ddb3f3d8
AH
16540 add_packet_config_cmd (PACKET_accept_error_message,
16541 "error-message", "error-message", 0);
16542
0b736949
DB
16543 /* Assert that we've registered "set remote foo-packet" commands
16544 for all packet configs. */
ca4f7f8b
PA
16545 {
16546 int i;
16547
16548 for (i = 0; i < PACKET_MAX; i++)
16549 {
16550 /* Ideally all configs would have a command associated. Some
16551 still don't though. */
16552 int excepted;
16553
16554 switch (i)
16555 {
16556 case PACKET_QNonStop:
ca4f7f8b
PA
16557 case PACKET_EnableDisableTracepoints_feature:
16558 case PACKET_tracenz_feature:
16559 case PACKET_DisconnectedTracing_feature:
16560 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
16561 case PACKET_qCRC:
16562 /* Additions to this list need to be well justified:
16563 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
16564 excepted = 1;
16565 break;
16566 default:
16567 excepted = 0;
16568 break;
16569 }
16570
16571 /* This catches both forgetting to add a config command, and
16572 forgetting to remove a packet from the exception list. */
ff52c073 16573 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
ca4f7f8b
PA
16574 }
16575 }
16576
37a105a1
DJ
16577 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16578 Z sub-packet has its own set and show commands, but users may
16579 have sets to this variable in their .gdbinit files (or in their
16580 documentation). */
e9e68a56 16581 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c 16582 &remote_Z_packet_detect, _("\
590042fc
PW
16583Set use of remote protocol `Z' packets."), _("\
16584Show use of remote protocol `Z' packets."), _("\
3b64bf98 16585When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 16586packets."),
e9e68a56 16587 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
16588 show_remote_protocol_Z_packet_cmd,
16589 /* FIXME: i18n: Use of remote protocol
16590 `Z' packets is %s. */
e9e68a56 16591 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 16592
0743fc83 16593 add_basic_prefix_cmd ("remote", class_files, _("\
590042fc 16594Manipulate files on the remote system.\n\
a6b151f1 16595Transfer files to and from the remote target system."),
2f822da5 16596 &remote_cmdlist,
0743fc83 16597 0 /* allow-unknown */, &cmdlist);
a6b151f1
DJ
16598
16599 add_cmd ("put", class_files, remote_put_command,
16600 _("Copy a local file to the remote system."),
16601 &remote_cmdlist);
16602
16603 add_cmd ("get", class_files, remote_get_command,
16604 _("Copy a remote file to the local system."),
16605 &remote_cmdlist);
16606
16607 add_cmd ("delete", class_files, remote_delete_command,
16608 _("Delete a remote file."),
16609 &remote_cmdlist);
16610
2d717e4f 16611 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 16612 &remote_exec_file_var, _("\
590042fc
PW
16613Set the remote pathname for \"run\"."), _("\
16614Show the remote pathname for \"run\"."), NULL,
94585166
DB
16615 set_remote_exec_file,
16616 show_remote_exec_file,
16617 &remote_set_cmdlist,
16618 &remote_show_cmdlist);
2d717e4f 16619
c1e36e3e
PA
16620 add_setshow_boolean_cmd ("range-stepping", class_run,
16621 &use_range_stepping, _("\
16622Enable or disable range stepping."), _("\
16623Show whether target-assisted range stepping is enabled."), _("\
16624If on, and the target supports it, when stepping a source line, GDB\n\
16625tells the target to step the corresponding range of addresses itself instead\n\
16626of issuing multiple single-steps. This speeds up source level\n\
16627stepping. If off, GDB always issues single-steps, even if range\n\
16628stepping is supported by the target. The default is on."),
16629 set_range_stepping,
16630 show_range_stepping,
16631 &setlist,
16632 &showlist);
16633
ed2b7c17
TT
16634 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
16635Set watchdog timer."), _("\
16636Show watchdog timer."), _("\
16637When non-zero, this timeout is used instead of waiting forever for a target\n\
16638to finish a low-level step or continue operation. If the specified amount\n\
16639of time passes without a response from the target, an error occurs."),
16640 NULL,
16641 show_watchdog,
16642 &setlist, &showlist);
16643
6cc8564b
LM
16644 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
16645 &remote_packet_max_chars, _("\
16646Set the maximum number of characters to display for each remote packet."), _("\
16647Show the maximum number of characters to display for each remote packet."), _("\
16648Specify \"unlimited\" to display all the characters."),
16649 NULL, show_remote_packet_max_chars,
16650 &setdebuglist, &showdebuglist);
16651
02349803
SM
16652 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
16653 _("Set debugging of remote protocol."),
16654 _("Show debugging of remote protocol."),
16655 _("\
baf2b57f
SM
16656When enabled, each packet sent or received with the remote target\n\
16657is displayed."),
02349803
SM
16658 NULL,
16659 show_remote_debug,
16660 &setdebuglist, &showdebuglist);
baf2b57f
SM
16661
16662 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
16663 &remote_timeout, _("\
16664Set timeout limit to wait for target to respond."), _("\
16665Show timeout limit to wait for target to respond."), _("\
16666This value is used to set the time limit for gdb to wait for a response\n\
16667from the target."),
16668 NULL,
16669 show_remote_timeout,
16670 &setlist, &showlist);
16671
449092f6 16672 /* Eventually initialize fileio. See fileio.c */
3f4d92eb 16673 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
754487e2
LM
16674
16675#if GDB_SELF_TEST
16676 selftests::register_test ("remote_memory_tagging",
16677 selftests::test_memory_tagging_functions);
7e9d8a36
AH
16678 selftests::register_test ("packet_check_result",
16679 selftests::test_packet_check_result);
754487e2 16680#endif
c906108c 16681}