]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
gdb: Make global feature array a per-remote target array
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
213516ef 3 Copyright (C) 1988-2023 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
3b3dac9b 30#include "process-stratum-target.h"
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
c906108c 33#include "gdbthread.h"
c2c6d25f 34#include "remote.h"
722247f1 35#include "remote-notif.h"
4e052eda 36#include "regcache.h"
fd0407d6 37#include "value.h"
76727919 38#include "observable.h"
a77053c2 39#include "solib.h"
37a105a1
DJ
40#include "cli/cli-decode.h"
41#include "cli/cli-setshow.h"
424163ea 42#include "target-descriptions.h"
a4453b7e 43#include "gdb_bfd.h"
268a13a5
TT
44#include "gdbsupport/filestuff.h"
45#include "gdbsupport/rsp-low.h"
6b940e6a 46#include "disasm.h"
f00aae0f 47#include "location.h"
c906108c 48
268a13a5 49#include "gdbsupport/gdb_sys_time.h"
c906108c 50
400b5eca 51#include "gdbsupport/event-loop.h"
c2c6d25f 52#include "event-top.h"
2acceee2 53#include "inf-loop.h"
43ff13b4 54
c906108c
SS
55#include <signal.h>
56#include "serial.h"
57
7e10abd1 58#include "gdbcore.h"
6240bebf 59
449092f6 60#include "remote-fileio.h"
198f946f 61#include "gdbsupport/fileio.h"
53ce3c39 62#include <sys/stat.h>
dc146f7c 63#include "xml-support.h"
449092f6 64
fd79ecee
DJ
65#include "memory-map.h"
66
35b1e5cc
SS
67#include "tracepoint.h"
68#include "ax.h"
69#include "ax-gdb.h"
268a13a5 70#include "gdbsupport/agent.h"
9accd112 71#include "btrace.h"
c0272db5 72#include "record-btrace.h"
268a13a5
TT
73#include "gdbsupport/scoped_restore.h"
74#include "gdbsupport/environ.h"
75#include "gdbsupport/byte-vector.h"
4a72de73 76#include "gdbsupport/search.h"
39ef2f62 77#include <algorithm>
ff52c073 78#include <iterator>
9d6eea31 79#include <unordered_map>
93b54c8e 80#include "async-event.h"
754487e2 81#include "gdbsupport/selftest.h"
35b1e5cc 82
f6ac5f3d
PA
83/* The remote target. */
84
d9f719f1
PA
85static const char remote_doc[] = N_("\
86Use a remote computer via a serial line, using a gdb-specific protocol.\n\
87Specify the serial device it is connected to\n\
88(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
89
cda09ec9
SM
90/* See remote.h */
91
02349803 92bool remote_debug = false;
cda09ec9 93
6b8edb51
PA
94#define OPAQUETHREADBYTES 8
95
96/* a 64 bit opaque identifier */
97typedef unsigned char threadref[OPAQUETHREADBYTES];
98
99struct gdb_ext_thread_info;
100struct threads_listing_context;
101typedef int (*rmt_thread_action) (threadref *ref, void *context);
102struct protocol_feature;
103struct packet_reg;
104
105struct stop_reply;
32603266 106typedef std::unique_ptr<stop_reply> stop_reply_up;
6b8edb51
PA
107
108/* Generic configuration support for packets the stub optionally
109 supports. Allows the user to specify the use of the packet as well
110 as allowing GDB to auto-detect support in the remote stub. */
111
112enum packet_support
113 {
114 PACKET_SUPPORT_UNKNOWN = 0,
115 PACKET_ENABLE,
116 PACKET_DISABLE
117 };
118
ff52c073
CS
119/* Convert the packet support auto_boolean to a name used for gdb printing. */
120
121static const char *
122get_packet_support_name (auto_boolean support)
123{
124 switch (support)
125 {
126 case AUTO_BOOLEAN_TRUE:
127 return "on";
128 case AUTO_BOOLEAN_FALSE:
129 return "off";
130 case AUTO_BOOLEAN_AUTO:
131 return "auto";
132 default:
133 gdb_assert_not_reached ("invalid var_auto_boolean");
134 }
135}
136
137/* Convert the target type (future remote target or currently connected target)
138 to a name used for gdb printing. */
139
140static const char *
141get_target_type_name (bool target_connected)
142{
143 if (target_connected)
144 return _("on the current remote target");
145 else
146 return _("on future remote targets");
147}
148
6b8edb51
PA
149/* Analyze a packet's return value and update the packet config
150 accordingly. */
151
152enum packet_result
153{
154 PACKET_ERROR,
155 PACKET_OK,
156 PACKET_UNKNOWN
157};
158
ff52c073
CS
159/* Enumeration of packets for a remote target. */
160
161enum {
162 PACKET_vCont = 0,
163 PACKET_X,
164 PACKET_qSymbol,
165 PACKET_P,
166 PACKET_p,
167 PACKET_Z0,
168 PACKET_Z1,
169 PACKET_Z2,
170 PACKET_Z3,
171 PACKET_Z4,
172 PACKET_vFile_setfs,
173 PACKET_vFile_open,
174 PACKET_vFile_pread,
175 PACKET_vFile_pwrite,
176 PACKET_vFile_close,
177 PACKET_vFile_unlink,
178 PACKET_vFile_readlink,
179 PACKET_vFile_fstat,
180 PACKET_qXfer_auxv,
181 PACKET_qXfer_features,
182 PACKET_qXfer_exec_file,
183 PACKET_qXfer_libraries,
184 PACKET_qXfer_libraries_svr4,
185 PACKET_qXfer_memory_map,
186 PACKET_qXfer_osdata,
187 PACKET_qXfer_threads,
188 PACKET_qXfer_statictrace_read,
189 PACKET_qXfer_traceframe_info,
190 PACKET_qXfer_uib,
191 PACKET_qGetTIBAddr,
192 PACKET_qGetTLSAddr,
193 PACKET_qSupported,
194 PACKET_qTStatus,
195 PACKET_QPassSignals,
196 PACKET_QCatchSyscalls,
197 PACKET_QProgramSignals,
198 PACKET_QSetWorkingDir,
199 PACKET_QStartupWithShell,
200 PACKET_QEnvironmentHexEncoded,
201 PACKET_QEnvironmentReset,
202 PACKET_QEnvironmentUnset,
203 PACKET_qCRC,
204 PACKET_qSearch_memory,
205 PACKET_vAttach,
206 PACKET_vRun,
207 PACKET_QStartNoAckMode,
208 PACKET_vKill,
209 PACKET_qXfer_siginfo_read,
210 PACKET_qXfer_siginfo_write,
211 PACKET_qAttached,
212
213 /* Support for conditional tracepoints. */
214 PACKET_ConditionalTracepoints,
215
216 /* Support for target-side breakpoint conditions. */
217 PACKET_ConditionalBreakpoints,
218
219 /* Support for target-side breakpoint commands. */
220 PACKET_BreakpointCommands,
221
222 /* Support for fast tracepoints. */
223 PACKET_FastTracepoints,
224
225 /* Support for static tracepoints. */
226 PACKET_StaticTracepoints,
227
228 /* Support for installing tracepoints while a trace experiment is
229 running. */
230 PACKET_InstallInTrace,
231
232 PACKET_bc,
233 PACKET_bs,
234 PACKET_TracepointSource,
235 PACKET_QAllow,
236 PACKET_qXfer_fdpic,
237 PACKET_QDisableRandomization,
238 PACKET_QAgent,
239 PACKET_QTBuffer_size,
240 PACKET_Qbtrace_off,
241 PACKET_Qbtrace_bts,
242 PACKET_Qbtrace_pt,
243 PACKET_qXfer_btrace,
244
245 /* Support for the QNonStop packet. */
246 PACKET_QNonStop,
247
248 /* Support for the QThreadEvents packet. */
249 PACKET_QThreadEvents,
250
251 /* Support for multi-process extensions. */
252 PACKET_multiprocess_feature,
253
254 /* Support for enabling and disabling tracepoints while a trace
255 experiment is running. */
256 PACKET_EnableDisableTracepoints_feature,
257
258 /* Support for collecting strings using the tracenz bytecode. */
259 PACKET_tracenz_feature,
260
261 /* Support for continuing to run a trace experiment while GDB is
262 disconnected. */
263 PACKET_DisconnectedTracing_feature,
264
265 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
266 PACKET_augmented_libraries_svr4_read_feature,
267
268 /* Support for the qXfer:btrace-conf:read packet. */
269 PACKET_qXfer_btrace_conf,
270
271 /* Support for the Qbtrace-conf:bts:size packet. */
272 PACKET_Qbtrace_conf_bts_size,
273
274 /* Support for swbreak+ feature. */
275 PACKET_swbreak_feature,
276
277 /* Support for hwbreak+ feature. */
278 PACKET_hwbreak_feature,
279
280 /* Support for fork events. */
281 PACKET_fork_event_feature,
282
283 /* Support for vfork events. */
284 PACKET_vfork_event_feature,
285
286 /* Support for the Qbtrace-conf:pt:size packet. */
287 PACKET_Qbtrace_conf_pt_size,
288
289 /* Support for exec events. */
290 PACKET_exec_event_feature,
291
292 /* Support for query supported vCont actions. */
293 PACKET_vContSupported,
294
295 /* Support remote CTRL-C. */
296 PACKET_vCtrlC,
297
298 /* Support TARGET_WAITKIND_NO_RESUMED. */
299 PACKET_no_resumed,
300
301 /* Support for memory tagging, allocation tag fetch/store
302 packets and the tag violation stop replies. */
303 PACKET_memory_tagging_feature,
304
305 PACKET_MAX
306};
307
6b8edb51 308struct threads_listing_context;
3c69da40
PA
309
310/* Stub vCont actions support.
311
312 Each field is a boolean flag indicating whether the stub reports
313 support for the corresponding action. */
314
315struct vCont_action_support
316{
317 /* vCont;t */
318 bool t = false;
319
320 /* vCont;r */
321 bool r = false;
322
323 /* vCont;s */
324 bool s = false;
325
326 /* vCont;S */
327 bool S = false;
328};
329
405feb71 330/* About this many threadids fit in a packet. */
3c69da40
PA
331
332#define MAXTHREADLISTRESULTS 32
333
334/* Data for the vFile:pread readahead cache. */
335
336struct readahead_cache
337{
338 /* Invalidate the readahead cache. */
339 void invalidate ();
340
341 /* Invalidate the readahead cache if it is holding data for FD. */
342 void invalidate_fd (int fd);
343
344 /* Serve pread from the readahead cache. Returns number of bytes
345 read, or 0 if the request can't be served from the cache. */
346 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
347
348 /* The file descriptor for the file that is being cached. -1 if the
349 cache is invalid. */
350 int fd = -1;
351
352 /* The offset into the file that the cache buffer corresponds
353 to. */
354 ULONGEST offset = 0;
355
356 /* The buffer holding the cache contents. */
357 gdb_byte *buf = nullptr;
358 /* The buffer's size. We try to read as much as fits into a packet
359 at a time. */
360 size_t bufsize = 0;
361
362 /* Cache hit and miss counters. */
363 ULONGEST hit_count = 0;
364 ULONGEST miss_count = 0;
365};
366
367/* Description of the remote protocol for a given architecture. */
368
369struct packet_reg
370{
371 long offset; /* Offset into G packet. */
372 long regnum; /* GDB's internal register number. */
373 LONGEST pnum; /* Remote protocol register number. */
374 int in_g_packet; /* Always part of G packet. */
375 /* long size in bytes; == register_size (target_gdbarch (), regnum);
376 at present. */
377 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
378 at present. */
379};
380
381struct remote_arch_state
382{
383 explicit remote_arch_state (struct gdbarch *gdbarch);
384
385 /* Description of the remote protocol registers. */
386 long sizeof_g_packet;
387
388 /* Description of the remote protocol registers indexed by REGNUM
389 (making an array gdbarch_num_regs in size). */
390 std::unique_ptr<packet_reg[]> regs;
391
392 /* This is the size (in chars) of the first response to the ``g''
393 packet. It is used as a heuristic when determining the maximum
394 size of memory-read and memory-write packets. A target will
395 typically only reserve a buffer large enough to hold the ``g''
396 packet. The size does not include packet overhead (headers and
397 trailers). */
398 long actual_register_packet_size;
399
400 /* This is the maximum size (in chars) of a non read/write packet.
401 It is also used as a cap on the size of read/write packets. */
402 long remote_packet_size;
403};
404
405/* Description of the remote protocol state for the currently
406 connected target. This is per-target state, and independent of the
407 selected architecture. */
408
409class remote_state
410{
411public:
412
413 remote_state ();
414 ~remote_state ();
415
416 /* Get the remote arch state for GDBARCH. */
417 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
418
419public: /* data */
420
421 /* A buffer to use for incoming packets, and its current size. The
422 buffer is grown dynamically for larger incoming packets.
423 Outgoing packets may also be constructed in this buffer.
8d64371b 424 The size of the buffer is always at least REMOTE_PACKET_SIZE;
3c69da40
PA
425 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
426 packets. */
8d64371b 427 gdb::char_vector buf;
3c69da40
PA
428
429 /* True if we're going through initial connection setup (finding out
430 about the remote side's threads, relocating symbols, etc.). */
431 bool starting_up = false;
432
433 /* If we negotiated packet size explicitly (and thus can bypass
434 heuristics for the largest packet size that will not overflow
435 a buffer in the stub), this will be set to that packet size.
436 Otherwise zero, meaning to use the guessed size. */
437 long explicit_packet_size = 0;
438
3c69da40
PA
439 /* True, if in no ack mode. That is, neither GDB nor the stub will
440 expect acks from each other. The connection is assumed to be
441 reliable. */
442 bool noack_mode = false;
443
444 /* True if we're connected in extended remote mode. */
445 bool extended = false;
446
447 /* True if we resumed the target and we're waiting for the target to
448 stop. In the mean time, we can't start another command/query.
449 The remote server wouldn't be ready to process it, so we'd
450 timeout waiting for a reply that would never come and eventually
451 we'd close the connection. This can happen in asynchronous mode
452 because we allow GDB commands while the target is running. */
453 bool waiting_for_stop_reply = false;
454
455 /* The status of the stub support for the various vCont actions. */
456 vCont_action_support supports_vCont;
5b6d1e4f
PA
457 /* Whether vCont support was probed already. This is a workaround
458 until packet_support is per-connection. */
459 bool supports_vCont_probed;
3c69da40
PA
460
461 /* True if the user has pressed Ctrl-C, but the target hasn't
462 responded to that. */
463 bool ctrlc_pending_p = false;
464
465 /* True if we saw a Ctrl-C while reading or writing from/to the
466 remote descriptor. At that point it is not safe to send a remote
467 interrupt packet, so we instead remember we saw the Ctrl-C and
468 process it once we're done with sending/receiving the current
469 packet, which should be shortly. If however that takes too long,
470 and the user presses Ctrl-C again, we offer to disconnect. */
471 bool got_ctrlc_during_io = false;
472
473 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
474 remote_open knows that we don't have a file open when the program
475 starts. */
476 struct serial *remote_desc = nullptr;
477
478 /* These are the threads which we last sent to the remote system. The
479 TID member will be -1 for all or -2 for not sent yet. */
480 ptid_t general_thread = null_ptid;
481 ptid_t continue_thread = null_ptid;
482
483 /* This is the traceframe which we last selected on the remote system.
484 It will be -1 if no traceframe is selected. */
485 int remote_traceframe_number = -1;
486
487 char *last_pass_packet = nullptr;
488
489 /* The last QProgramSignals packet sent to the target. We bypass
490 sending a new program signals list down to the target if the new
491 packet is exactly the same as the last we sent. IOW, we only let
492 the target know about program signals list changes. */
493 char *last_program_signals_packet = nullptr;
494
495 gdb_signal last_sent_signal = GDB_SIGNAL_0;
496
497 bool last_sent_step = false;
498
499 /* The execution direction of the last resume we got. */
500 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
501
502 char *finished_object = nullptr;
503 char *finished_annex = nullptr;
504 ULONGEST finished_offset = 0;
505
506 /* Should we try the 'ThreadInfo' query packet?
507
508 This variable (NOT available to the user: auto-detect only!)
509 determines whether GDB will use the new, simpler "ThreadInfo"
510 query or the older, more complex syntax for thread queries.
511 This is an auto-detect variable (set to true at each connect,
512 and set to false when the target fails to recognize it). */
513 bool use_threadinfo_query = false;
514 bool use_threadextra_query = false;
515
516 threadref echo_nextthread {};
517 threadref nextthread {};
518 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
519
520 /* The state of remote notification. */
521 struct remote_notif_state *notif_state = nullptr;
522
523 /* The branch trace configuration. */
524 struct btrace_config btrace_config {};
525
526 /* The argument to the last "vFile:setfs:" packet we sent, used
527 to avoid sending repeated unnecessary "vFile:setfs:" packets.
528 Initialized to -1 to indicate that no "vFile:setfs:" packet
529 has yet been sent. */
530 int fs_pid = -1;
531
532 /* A readahead cache for vFile:pread. Often, reading a binary
533 involves a sequence of small reads. E.g., when parsing an ELF
534 file. A readahead cache helps mostly the case of remote
535 debugging on a connection with higher latency, due to the
536 request/reply nature of the RSP. We only cache data for a single
537 file descriptor at a time. */
538 struct readahead_cache readahead_cache;
539
540 /* The list of already fetched and acknowledged stop events. This
541 queue is used for notification Stop, and other notifications
542 don't need queue for their events, because the notification
543 events of Stop can't be consumed immediately, so that events
544 should be queued first, and be consumed by remote_wait_{ns,as}
545 one per time. Other notifications can consume their events
546 immediately, so queue is not needed for them. */
953edf2b 547 std::vector<stop_reply_up> stop_reply_queue;
3c69da40
PA
548
549 /* Asynchronous signal handle registered as event loop source for
550 when we have pending events ready to be passed to the core. */
551 struct async_event_handler *remote_async_inferior_event_token = nullptr;
552
553 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
554 ``forever'' still use the normal timeout mechanism. This is
555 currently used by the ASYNC code to guarentee that target reads
556 during the initial connect always time-out. Once getpkt has been
557 modified to return a timeout indication and, in turn
558 remote_wait()/wait_for_inferior() have gained a timeout parameter
559 this can go away. */
560 int wait_forever_enabled_p = 1;
561
562private:
563 /* Mapping of remote protocol data for each gdbarch. Usually there
564 is only one entry here, though we may see more with stubs that
565 support multi-process. */
566 std::unordered_map<struct gdbarch *, remote_arch_state>
567 m_arch_states;
568};
6b8edb51 569
d9f719f1
PA
570static const target_info remote_target_info = {
571 "remote",
ae9adb36 572 N_("Remote target using gdb-specific protocol"),
d9f719f1
PA
573 remote_doc
574};
575
ff52c073
CS
576/* Description of a remote packet. */
577
578struct packet_description
579{
580 /* Name of the packet used for gdb output. */
581 const char *name;
582
583 /* Title of the packet, used by the set/show remote name-packet
584 commands to identify the individual packages and gdb output. */
585 const char *title;
586};
587
588/* Configuration of a remote packet. */
589
590struct packet_config
591{
592 /* If auto, GDB auto-detects support for this packet or feature,
593 either through qSupported, or by trying the packet and looking
594 at the response. If true, GDB assumes the target supports this
595 packet. If false, the packet is disabled. Configs that don't
596 have an associated command always have this set to auto. */
597 enum auto_boolean detect;
598
599 /* Does the target support this packet? */
600 enum packet_support support;
601};
602
603/* This global array contains packet descriptions (name and title). */
604static packet_description packets_descriptions[PACKET_MAX];
605/* This global array contains the default configuration for every new
606 per-remote target array. */
607static packet_config remote_protocol_packets[PACKET_MAX];
608
609/* Description of a remote target's features. It stores the configuration
610 and provides functions to determine supported features of the target. */
611
612struct remote_features
613{
614 remote_features ()
615 {
616 std::copy (std::begin (remote_protocol_packets),
617 std::end (remote_protocol_packets),
618 std::begin (m_protocol_packets));
619 }
620 ~remote_features () = default;
621
622 DISABLE_COPY_AND_ASSIGN (remote_features);
623
624 /* Returns whether a given packet defined by its enum value is supported. */
625 enum packet_support packet_support (int) const;
626
627 /* Returns the packet's corresponding "set remote foo-packet" command
628 state. See struct packet_config for more details. */
629 enum auto_boolean packet_set_cmd_state (int packet) const
630 { return m_protocol_packets[packet].detect; }
631
632 /* Returns true if the multi-process extensions are in effect. */
633 int remote_multi_process_p () const
634 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
635
636 /* Returns true if fork events are supported. */
637 int remote_fork_event_p () const
638 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
639
640 /* Returns true if vfork events are supported. */
641 int remote_vfork_event_p () const
642 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
643
644 /* Returns true if exec events are supported. */
645 int remote_exec_event_p () const
646 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
647
648 /* Returns true if memory tagging is supported, false otherwise. */
649 bool remote_memory_tagging_p () const
650 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
651
652 /* Reset all packets back to "unknown support". Called when opening a
653 new connection to a remote target. */
654 void reset_all_packet_configs_support ();
655
656/* Check result value in BUF for packet WHICH_PACKET and update the packet's
657 support configuration accordingly. */
658 packet_result packet_ok (const char *buf, const int which_packet);
659 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
660
661 /* The per-remote target array which stores a remote's packet
662 configurations. */
663 packet_config m_protocol_packets[PACKET_MAX];
664};
665
3b3dac9b 666class remote_target : public process_stratum_target
f6ac5f3d
PA
667{
668public:
3b3dac9b 669 remote_target () = default;
6b8edb51 670 ~remote_target () override;
f6ac5f3d 671
d9f719f1
PA
672 const target_info &info () const override
673 { return remote_target_info; }
f6ac5f3d 674
121b3efd
PA
675 const char *connection_string () override;
676
f6ac5f3d
PA
677 thread_control_capabilities get_thread_control_capabilities () override
678 { return tc_schedlock; }
679
d9f719f1
PA
680 /* Open a remote connection. */
681 static void open (const char *, int);
682
f6ac5f3d
PA
683 void close () override;
684
685 void detach (inferior *, int) override;
686 void disconnect (const char *, int) override;
687
1192f124 688 void commit_resumed () override;
f6ac5f3d 689 void resume (ptid_t, int, enum gdb_signal) override;
b60cea74 690 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
b4b1a226 691 bool has_pending_events () override;
f6ac5f3d
PA
692
693 void fetch_registers (struct regcache *, int) override;
694 void store_registers (struct regcache *, int) override;
695 void prepare_to_store (struct regcache *) override;
696
f6ac5f3d
PA
697 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
698
699 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
700 enum remove_bp_reason) override;
701
702
57810aa7
PA
703 bool stopped_by_sw_breakpoint () override;
704 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 705
57810aa7 706 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 707
57810aa7 708 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 709
57810aa7 710 bool stopped_by_watchpoint () override;
f6ac5f3d 711
57810aa7 712 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 713
57810aa7 714 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
715
716 int can_use_hw_breakpoint (enum bptype, int, int) override;
717
718 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
719
720 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
721
722 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
723
724 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
725 struct expression *) override;
726
727 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
728 struct expression *) override;
729
730 void kill () override;
731
732 void load (const char *, int) override;
733
734 void mourn_inferior () override;
735
adc6a863 736 void pass_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d
PA
737
738 int set_syscall_catchpoint (int, bool, int,
739 gdb::array_view<const int>) override;
740
adc6a863 741 void program_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d 742
57810aa7 743 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
744
745 const char *thread_name (struct thread_info *) override;
746
747 void update_thread_list () override;
748
a068643d 749 std::string pid_to_str (ptid_t) override;
f6ac5f3d
PA
750
751 const char *extra_thread_info (struct thread_info *) override;
752
c80e29db 753 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
f6ac5f3d
PA
754
755 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
756 int handle_len,
757 inferior *inf) override;
758
3d6c6204
KB
759 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
760 override;
761
f6ac5f3d
PA
762 void stop (ptid_t) override;
763
764 void interrupt () override;
765
766 void pass_ctrlc () override;
767
768 enum target_xfer_status xfer_partial (enum target_object object,
769 const char *annex,
770 gdb_byte *readbuf,
771 const gdb_byte *writebuf,
772 ULONGEST offset, ULONGEST len,
773 ULONGEST *xfered_len) override;
774
775 ULONGEST get_memory_xfer_limit () override;
776
777 void rcmd (const char *command, struct ui_file *output) override;
778
0e90c441 779 const char *pid_to_exec_file (int pid) override;
f6ac5f3d
PA
780
781 void log_command (const char *cmd) override
782 {
783 serial_log_command (this, cmd);
784 }
785
786 CORE_ADDR get_thread_local_address (ptid_t ptid,
787 CORE_ADDR load_module_addr,
788 CORE_ADDR offset) override;
789
57810aa7 790 bool can_execute_reverse () override;
f6ac5f3d
PA
791
792 std::vector<mem_region> memory_map () override;
793
794 void flash_erase (ULONGEST address, LONGEST length) override;
795
796 void flash_done () override;
797
798 const struct target_desc *read_description () override;
799
800 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
801 const gdb_byte *pattern, ULONGEST pattern_len,
802 CORE_ADDR *found_addrp) override;
803
57810aa7 804 bool can_async_p () override;
f6ac5f3d 805
57810aa7 806 bool is_async_p () override;
f6ac5f3d 807
4a570176 808 void async (bool) override;
f6ac5f3d 809
5b6d1e4f
PA
810 int async_wait_fd () override;
811
f6ac5f3d
PA
812 void thread_events (int) override;
813
814 int can_do_single_step () override;
815
816 void terminal_inferior () override;
817
818 void terminal_ours () override;
819
57810aa7 820 bool supports_non_stop () override;
f6ac5f3d 821
57810aa7 822 bool supports_multi_process () override;
f6ac5f3d 823
57810aa7 824 bool supports_disable_randomization () override;
f6ac5f3d 825
57810aa7 826 bool filesystem_is_local () override;
f6ac5f3d
PA
827
828
829 int fileio_open (struct inferior *inf, const char *filename,
830 int flags, int mode, int warn_if_slow,
b872057a 831 fileio_error *target_errno) override;
f6ac5f3d
PA
832
833 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 834 ULONGEST offset, fileio_error *target_errno) override;
f6ac5f3d
PA
835
836 int fileio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 837 ULONGEST offset, fileio_error *target_errno) override;
f6ac5f3d 838
b872057a 839 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
f6ac5f3d 840
b872057a 841 int fileio_close (int fd, fileio_error *target_errno) override;
f6ac5f3d
PA
842
843 int fileio_unlink (struct inferior *inf,
844 const char *filename,
b872057a 845 fileio_error *target_errno) override;
f6ac5f3d
PA
846
847 gdb::optional<std::string>
848 fileio_readlink (struct inferior *inf,
849 const char *filename,
b872057a 850 fileio_error *target_errno) override;
f6ac5f3d 851
57810aa7 852 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 853
57810aa7 854 bool supports_string_tracing () override;
f6ac5f3d 855
ff52c073
CS
856 int remote_supports_cond_tracepoints ();
857
57810aa7 858 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 859
ff52c073
CS
860 int remote_supports_fast_tracepoints ();
861
862 int remote_supports_static_tracepoints ();
863
864 int remote_supports_install_in_trace ();
865
57810aa7 866 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
867
868 void trace_init () override;
869
870 void download_tracepoint (struct bp_location *location) override;
871
57810aa7 872 bool can_download_tracepoint () override;
f6ac5f3d
PA
873
874 void download_trace_state_variable (const trace_state_variable &tsv) override;
875
876 void enable_tracepoint (struct bp_location *location) override;
877
878 void disable_tracepoint (struct bp_location *location) override;
879
880 void trace_set_readonly_regions () override;
881
882 void trace_start () override;
883
884 int get_trace_status (struct trace_status *ts) override;
885
886 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
887 override;
888
889 void trace_stop () override;
890
891 int trace_find (enum trace_find_type type, int num,
892 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
893
57810aa7 894 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
895
896 int save_trace_data (const char *filename) override;
897
898 int upload_tracepoints (struct uploaded_tp **utpp) override;
899
900 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
901
902 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
903
904 int get_min_fast_tracepoint_insn_len () override;
905
906 void set_disconnected_tracing (int val) override;
907
908 void set_circular_trace_buffer (int val) override;
909
910 void set_trace_buffer_size (LONGEST val) override;
911
57810aa7
PA
912 bool set_trace_notes (const char *user, const char *notes,
913 const char *stopnotes) override;
f6ac5f3d
PA
914
915 int core_of_thread (ptid_t ptid) override;
916
917 int verify_memory (const gdb_byte *data,
918 CORE_ADDR memaddr, ULONGEST size) override;
919
920
57810aa7 921 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
922
923 void set_permissions () override;
924
925 bool static_tracepoint_marker_at (CORE_ADDR,
926 struct static_tracepoint_marker *marker)
927 override;
928
929 std::vector<static_tracepoint_marker>
930 static_tracepoint_markers_by_strid (const char *id) override;
931
932 traceframe_info_up traceframe_info () override;
933
57810aa7
PA
934 bool use_agent (bool use) override;
935 bool can_use_agent () override;
f6ac5f3d 936
696c0d5e
MM
937 struct btrace_target_info *
938 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
f6ac5f3d
PA
939
940 void disable_btrace (struct btrace_target_info *tinfo) override;
941
942 void teardown_btrace (struct btrace_target_info *tinfo) override;
943
944 enum btrace_error read_btrace (struct btrace_data *data,
945 struct btrace_target_info *btinfo,
946 enum btrace_read_type type) override;
947
948 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 949 bool augmented_libraries_svr4_read () override;
82d1f134 950 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
294c36eb 951 void follow_exec (inferior *, ptid_t, const char *) override;
f6ac5f3d
PA
952 int insert_fork_catchpoint (int) override;
953 int remove_fork_catchpoint (int) override;
954 int insert_vfork_catchpoint (int) override;
955 int remove_vfork_catchpoint (int) override;
956 int insert_exec_catchpoint (int) override;
957 int remove_exec_catchpoint (int) override;
958 enum exec_direction_kind execution_direction () override;
959
dbe692af
LM
960 bool supports_memory_tagging () override;
961
962 bool fetch_memtags (CORE_ADDR address, size_t len,
963 gdb::byte_vector &tags, int type) override;
964
965 bool store_memtags (CORE_ADDR address, size_t len,
966 const gdb::byte_vector &tags, int type) override;
967
6b8edb51
PA
968public: /* Remote specific methods. */
969
970 void remote_download_command_source (int num, ULONGEST addr,
971 struct command_line *cmds);
972
973 void remote_file_put (const char *local_file, const char *remote_file,
974 int from_tty);
975 void remote_file_get (const char *remote_file, const char *local_file,
976 int from_tty);
977 void remote_file_delete (const char *remote_file, int from_tty);
978
979 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 980 ULONGEST offset, fileio_error *remote_errno);
6b8edb51 981 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 982 ULONGEST offset, fileio_error *remote_errno);
6b8edb51 983 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
b872057a 984 ULONGEST offset, fileio_error *remote_errno);
6b8edb51
PA
985
986 int remote_hostio_send_command (int command_bytes, int which_packet,
b872057a 987 fileio_error *remote_errno, const char **attachment,
6b8edb51
PA
988 int *attachment_len);
989 int remote_hostio_set_filesystem (struct inferior *inf,
b872057a 990 fileio_error *remote_errno);
6b8edb51
PA
991 /* We should get rid of this and use fileio_open directly. */
992 int remote_hostio_open (struct inferior *inf, const char *filename,
993 int flags, int mode, int warn_if_slow,
b872057a
SM
994 fileio_error *remote_errno);
995 int remote_hostio_close (int fd, fileio_error *remote_errno);
6b8edb51
PA
996
997 int remote_hostio_unlink (inferior *inf, const char *filename,
b872057a 998 fileio_error *remote_errno);
6b8edb51
PA
999
1000 struct remote_state *get_remote_state ();
1001
1002 long get_remote_packet_size (void);
1003 long get_memory_packet_size (struct memory_packet_config *config);
1004
1005 long get_memory_write_packet_size ();
1006 long get_memory_read_packet_size ();
1007
1008 char *append_pending_thread_resumptions (char *p, char *endp,
1009 ptid_t ptid);
d9f719f1 1010 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d 1011 void start_remote (int from_tty, int extended_p);
00431a78 1012 void remote_detach_1 (struct inferior *inf, int from_tty);
6b8edb51
PA
1013
1014 char *append_resumption (char *p, char *endp,
1015 ptid_t ptid, int step, gdb_signal siggnal);
d51926f0 1016 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
6b8edb51
PA
1017 gdb_signal siggnal);
1018
64d38fdd 1019 thread_info *add_current_inferior_and_thread (const char *wait_status);
6b8edb51
PA
1020
1021 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
b60cea74 1022 target_wait_flags options);
6b8edb51 1023 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
b60cea74 1024 target_wait_flags options);
6b8edb51
PA
1025
1026 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1027 target_waitstatus *status);
1028
8f66807b 1029 ptid_t select_thread_for_ambiguous_stop_reply
c272a98c 1030 (const struct target_waitstatus &status);
8f66807b 1031
8a82de58 1032 void remote_notice_new_inferior (ptid_t currthread, bool executing);
6b8edb51 1033
1edb66d8 1034 void print_one_stopped_thread (thread_info *thread);
6b8edb51
PA
1035 void process_initial_stop_replies (int from_tty);
1036
b622494e
AB
1037 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1038 bool silent_p);
6b8edb51
PA
1039
1040 void btrace_sync_conf (const btrace_config *conf);
1041
1042 void remote_btrace_maybe_reopen ();
1043
1044 void remove_new_fork_children (threads_listing_context *context);
28561a65 1045 void kill_new_fork_children (inferior *inf);
6b8edb51
PA
1046 void discard_pending_stop_replies (struct inferior *inf);
1047 int stop_reply_queue_length ();
1048
1049 void check_pending_events_prevent_wildcard_vcont
2f63ec5c 1050 (bool *may_global_wildcard_vcont);
6b8edb51
PA
1051
1052 void discard_pending_stop_replies_in_queue ();
1053 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1054 struct stop_reply *queued_stop_reply (ptid_t ptid);
1055 int peek_stop_reply (ptid_t ptid);
bb277751 1056 void remote_parse_stop_reply (const char *buf, stop_reply *event);
6b8edb51
PA
1057
1058 void remote_stop_ns (ptid_t ptid);
1059 void remote_interrupt_as ();
1060 void remote_interrupt_ns ();
1061
1062 char *remote_get_noisy_reply ();
1063 int remote_query_attached (int pid);
9ab8741a 1064 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51
PA
1065 int try_open_exec);
1066
1067 ptid_t remote_current_thread (ptid_t oldpid);
e3b2741b 1068 ptid_t get_current_thread (const char *wait_status);
6b8edb51
PA
1069
1070 void set_thread (ptid_t ptid, int gen);
1071 void set_general_thread (ptid_t ptid);
1072 void set_continue_thread (ptid_t ptid);
1073 void set_general_process ();
1074
1075 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1076
cecb1912 1077 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
6b8edb51
PA
1078 gdb_ext_thread_info *info);
1079 int remote_get_threadinfo (threadref *threadid, int fieldset,
1080 gdb_ext_thread_info *info);
1081
cecb1912 1082 int parse_threadlist_response (const char *pkt, int result_limit,
6b8edb51
PA
1083 threadref *original_echo,
1084 threadref *resultlist,
1085 int *doneflag);
1086 int remote_get_threadlist (int startflag, threadref *nextthread,
1087 int result_limit, int *done, int *result_count,
1088 threadref *threadlist);
1089
1090 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1091 void *context, int looplimit);
1092
1093 int remote_get_threads_with_ql (threads_listing_context *context);
1094 int remote_get_threads_with_qxfer (threads_listing_context *context);
1095 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1096
1097 void extended_remote_restart ();
1098
1099 void get_offsets ();
1100
1101 void remote_check_symbols ();
1102
1103 void remote_supported_packet (const struct protocol_feature *feature,
1104 enum packet_support support,
1105 const char *argument);
1106
1107 void remote_query_supported ();
1108
1109 void remote_packet_size (const protocol_feature *feature,
1110 packet_support support, const char *value);
1111
1112 void remote_serial_quit_handler ();
1113
1114 void remote_detach_pid (int pid);
1115
1116 void remote_vcont_probe ();
1117
1118 void remote_resume_with_hc (ptid_t ptid, int step,
1119 gdb_signal siggnal);
1120
1121 void send_interrupt_sequence ();
1122 void interrupt_query ();
1123
42938c1a 1124 void remote_notif_get_pending_events (const notif_client *nc);
6b8edb51
PA
1125
1126 int fetch_register_using_p (struct regcache *regcache,
1127 packet_reg *reg);
1128 int send_g_packet ();
1129 void process_g_packet (struct regcache *regcache);
1130 void fetch_registers_using_g (struct regcache *regcache);
1131 int store_register_using_P (const struct regcache *regcache,
1132 packet_reg *reg);
1133 void store_registers_using_G (const struct regcache *regcache);
1134
1135 void set_remote_traceframe ();
1136
1137 void check_binary_download (CORE_ADDR addr);
1138
1139 target_xfer_status remote_write_bytes_aux (const char *header,
1140 CORE_ADDR memaddr,
1141 const gdb_byte *myaddr,
1142 ULONGEST len_units,
1143 int unit_size,
1144 ULONGEST *xfered_len_units,
1145 char packet_format,
1146 int use_length);
1147
1148 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1149 const gdb_byte *myaddr, ULONGEST len,
1150 int unit_size, ULONGEST *xfered_len);
1151
1152 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1153 ULONGEST len_units,
1154 int unit_size, ULONGEST *xfered_len_units);
1155
1156 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1157 ULONGEST memaddr,
1158 ULONGEST len,
1159 int unit_size,
1160 ULONGEST *xfered_len);
1161
1162 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1163 gdb_byte *myaddr, ULONGEST len,
1164 int unit_size,
1165 ULONGEST *xfered_len);
1166
1167 packet_result remote_send_printf (const char *format, ...)
1168 ATTRIBUTE_PRINTF (2, 3);
1169
1170 target_xfer_status remote_flash_write (ULONGEST address,
1171 ULONGEST length, ULONGEST *xfered_len,
1172 const gdb_byte *data);
1173
1174 int readchar (int timeout);
1175
1176 void remote_serial_write (const char *str, int len);
1177
1178 int putpkt (const char *buf);
1179 int putpkt_binary (const char *buf, int cnt);
1180
8d64371b
TT
1181 int putpkt (const gdb::char_vector &buf)
1182 {
1183 return putpkt (buf.data ());
1184 }
1185
6b8edb51 1186 void skip_frame ();
8d64371b
TT
1187 long read_frame (gdb::char_vector *buf_p);
1188 void getpkt (gdb::char_vector *buf, int forever);
1189 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
6b8edb51 1190 int expecting_notif, int *is_notif);
8d64371b
TT
1191 int getpkt_sane (gdb::char_vector *buf, int forever);
1192 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
6b8edb51
PA
1193 int *is_notif);
1194 int remote_vkill (int pid);
1195 void remote_kill_k ();
1196
1197 void extended_remote_disable_randomization (int val);
1198 int extended_remote_run (const std::string &args);
1199
1200 void send_environment_packet (const char *action,
1201 const char *packet,
1202 const char *value);
1203
1204 void extended_remote_environment_support ();
3c69da40 1205 void extended_remote_set_inferior_cwd ();
80152258 1206
3c69da40
PA
1207 target_xfer_status remote_write_qxfer (const char *object_name,
1208 const char *annex,
1209 const gdb_byte *writebuf,
1210 ULONGEST offset, LONGEST len,
1211 ULONGEST *xfered_len,
ff52c073 1212 const unsigned int which_packet);
43c3a0e4 1213
3c69da40
PA
1214 target_xfer_status remote_read_qxfer (const char *object_name,
1215 const char *annex,
1216 gdb_byte *readbuf, ULONGEST offset,
1217 LONGEST len,
1218 ULONGEST *xfered_len,
ff52c073 1219 const unsigned int which_packet);
43c3a0e4 1220
3c69da40 1221 void push_stop_reply (struct stop_reply *new_event);
43c3a0e4 1222
3c69da40 1223 bool vcont_r_supported ();
43c3a0e4 1224
ff52c073
CS
1225 remote_features m_features;
1226
288712bb
AB
1227private:
1228
1229 bool start_remote_1 (int from_tty, int extended_p);
43c3a0e4 1230
3c69da40
PA
1231 /* The remote state. Don't reference this directly. Use the
1232 get_remote_state method instead. */
1233 remote_state m_remote_state;
43c3a0e4
PA
1234};
1235
3c69da40
PA
1236static const target_info extended_remote_target_info = {
1237 "extended-remote",
ae9adb36 1238 N_("Extended remote target using gdb-specific protocol"),
3c69da40
PA
1239 remote_doc
1240};
ea9c271d 1241
3c69da40
PA
1242/* Set up the extended remote target by extending the standard remote
1243 target and adding to it. */
1244
1245class extended_remote_target final : public remote_target
ea9c271d 1246{
9d6eea31 1247public:
3c69da40
PA
1248 const target_info &info () const override
1249 { return extended_remote_target_info; }
9d6eea31 1250
3c69da40
PA
1251 /* Open an extended-remote connection. */
1252 static void open (const char *, int);
de44f5a7 1253
3c69da40
PA
1254 bool can_create_inferior () override { return true; }
1255 void create_inferior (const char *, const std::string &,
1256 char **, int) override;
9d6eea31 1257
3c69da40 1258 void detach (inferior *, int) override;
9d6eea31 1259
3c69da40
PA
1260 bool can_attach () override { return true; }
1261 void attach (const char *, int) override;
be2a5f71 1262
3c69da40
PA
1263 void post_attach (int) override;
1264 bool supports_disable_randomization () override;
1265};
1e51243a 1266
a4543480
SM
1267struct stop_reply : public notif_event
1268{
1269 ~stop_reply ();
1270
1271 /* The identifier of the thread about this event */
1272 ptid_t ptid;
1273
1274 /* The remote state this event is associated with. When the remote
1275 connection, represented by a remote_state object, is closed,
1276 all the associated stop_reply events should be released. */
1277 struct remote_state *rs;
1278
1279 struct target_waitstatus ws;
1280
1281 /* The architecture associated with the expedited registers. */
1282 gdbarch *arch;
1283
1284 /* Expedited registers. This makes remote debugging a bit more
1285 efficient for those targets that provide critical registers as
1286 part of their normal status mechanism (as another roundtrip to
1287 fetch them is avoided). */
1288 std::vector<cached_reg_t> regcache;
1289
1290 enum target_stop_reason stop_reason;
1291
1292 CORE_ADDR watch_data_address;
1293
1294 int core;
1295};
1296
06c7226e
SM
1297/* Return TARGET as a remote_target if it is one, else nullptr. */
1298
1299static remote_target *
1300as_remote_target (process_stratum_target *target)
1301{
1302 return dynamic_cast<remote_target *> (target);
1303}
1304
24b2de7b
AB
1305/* See remote.h. */
1306
1307bool
1308is_remote_target (process_stratum_target *target)
1309{
06c7226e 1310 return as_remote_target (target) != nullptr;
24b2de7b
AB
1311}
1312
3c69da40 1313/* Per-program-space data key. */
08b8a139 1314static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
7b4a314f 1315 remote_pspace_data;
2d717e4f 1316
3c69da40
PA
1317/* The variable registered as the control variable used by the
1318 remote exec-file commands. While the remote exec-file setting is
1319 per-program-space, the set/show machinery uses this as the
1320 location of the remote exec-file value. */
e0700ba4 1321static std::string remote_exec_file_var;
a6f3e723 1322
3c69da40
PA
1323/* The size to align memory write packets, when practical. The protocol
1324 does not guarantee any alignment, and gdb will generate short
1325 writes and unaligned writes, but even as a best-effort attempt this
1326 can improve bulk transfers. For instance, if a write is misaligned
1327 relative to the target's data bus, the stub may need to make an extra
1328 round trip fetching data from the target. This doesn't make a
1329 huge difference, but it's easy to do, so we try to be helpful.
82f73884 1330
3c69da40
PA
1331 The alignment chosen is arbitrary; usually data bus width is
1332 important here, not the possibly larger cache line size. */
1333enum { REMOTE_ALIGN_WRITES = 16 };
82f73884 1334
3c69da40 1335/* Prototypes for local functions. */
74531fed 1336
3c69da40 1337static int hexnumlen (ULONGEST num);
782b2b07 1338
3c69da40 1339static int stubhex (int ch);
5d93a237 1340
3c69da40 1341static int hexnumstr (char *, ULONGEST);
048094ac 1342
3c69da40 1343static int hexnumnstr (char *, ULONGEST, int);
47f8a51d 1344
3c69da40 1345static CORE_ADDR remote_address_masked (CORE_ADDR);
262e1174 1346
cecb1912 1347static int stub_unpack_int (const char *buff, int fieldlength);
5e4a05c4 1348
ff52c073
CS
1349static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1350 cmd_list_element *c);
1351
1352static void show_packet_config_cmd (ui_file *file,
1353 const unsigned int which_packet,
1354 remote_target *remote);
b73be471 1355
3c69da40
PA
1356static void show_remote_protocol_packet_cmd (struct ui_file *file,
1357 int from_tty,
1358 struct cmd_list_element *c,
1359 const char *value);
8e88304f 1360
3c69da40 1361static ptid_t read_ptid (const char *buf, const char **obuf);
3a00c802 1362
3c69da40 1363static void remote_async_inferior_event_handler (gdb_client_data);
b80fafe3 1364
eefce37f 1365static bool remote_read_description_p (struct target_ops *target);
88b496c3 1366
05be00a8 1367static void remote_console_output (const char *msg);
5965e028 1368
3c69da40 1369static void remote_btrace_reset (remote_state *rs);
f4abbc16 1370
5b6d1e4f 1371static void remote_unpush_and_throw (remote_target *target);
15a201c8 1372
3c69da40 1373/* For "remote". */
80152258 1374
3c69da40 1375static struct cmd_list_element *remote_cmdlist;
9d6eea31 1376
3c69da40 1377/* For "set remote" and "show remote". */
6b8edb51 1378
3c69da40
PA
1379static struct cmd_list_element *remote_set_cmdlist;
1380static struct cmd_list_element *remote_show_cmdlist;
6b8edb51 1381
3c69da40 1382/* Controls whether GDB is willing to use range stepping. */
6b8edb51 1383
491144b5 1384static bool use_range_stepping = true;
3c69da40 1385
c9d22089
SM
1386/* From the remote target's point of view, each thread is in one of these three
1387 states. */
1388enum class resume_state
1389{
1390 /* Not resumed - we haven't been asked to resume this thread. */
1391 NOT_RESUMED,
1392
1393 /* We have been asked to resume this thread, but haven't sent a vCont action
1394 for it yet. We'll need to consider it next time commit_resume is
1395 called. */
1396 RESUMED_PENDING_VCONT,
1397
1398 /* We have been asked to resume this thread, and we have sent a vCont action
1399 for it. */
1400 RESUMED,
1401};
1402
1403/* Information about a thread's pending vCont-resume. Used when a thread is in
1404 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1405 stores this information which is then picked up by
1406 remote_target::commit_resume to know which is the proper action for this
1407 thread to include in the vCont packet. */
1408struct resumed_pending_vcont_info
1409{
1410 /* True if the last resume call for this thread was a step request, false
1411 if a continue request. */
1412 bool step;
1413
1414 /* The signal specified in the last resume call for this thread. */
1415 gdb_signal sig;
1416};
1417
7aabaf9d
SM
1418/* Private data that we'll store in (struct thread_info)->priv. */
1419struct remote_thread_info : public private_thread_info
dc146f7c 1420{
7aabaf9d
SM
1421 std::string extra;
1422 std::string name;
1423 int core = -1;
799a2abe 1424
f6327dcb
KB
1425 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1426 sequence of bytes. */
7aabaf9d 1427 gdb::byte_vector thread_handle;
f6327dcb 1428
799a2abe 1429 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1430 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1431
1432 /* This is set to the data address of the access causing the target
1433 to stop for a watchpoint. */
7aabaf9d 1434 CORE_ADDR watch_data_address = 0;
85ad3aaf 1435
c9d22089 1436 /* Get the thread's resume state. */
a6c11cbb 1437 enum resume_state get_resume_state () const
c9d22089
SM
1438 {
1439 return m_resume_state;
1440 }
1441
1442 /* Put the thread in the NOT_RESUMED state. */
1443 void set_not_resumed ()
1444 {
1445 m_resume_state = resume_state::NOT_RESUMED;
1446 }
85ad3aaf 1447
c9d22089
SM
1448 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1449 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1450 {
1451 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1452 m_resumed_pending_vcont_info.step = step;
1453 m_resumed_pending_vcont_info.sig = sig;
1454 }
85ad3aaf 1455
c9d22089 1456 /* Get the information this thread's pending vCont-resumption.
85ad3aaf 1457
c9d22089
SM
1458 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1459 state. */
1460 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1461 {
1462 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1463
1464 return m_resumed_pending_vcont_info;
1465 }
1466
1467 /* Put the thread in the VCONT_RESUMED state. */
1468 void set_resumed ()
1469 {
1470 m_resume_state = resume_state::RESUMED;
1471 }
1472
1473private:
1474 /* Resume state for this thread. This is used to implement vCont action
1475 coalescing (only when the target operates in non-stop mode).
1476
1477 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1478 which notes that this thread must be considered in the next commit_resume
1479 call.
1480
1481 remote_target::commit_resume sends a vCont packet with actions for the
1482 threads in the RESUMED_PENDING_VCONT state and moves them to the
1483 VCONT_RESUMED state.
1484
1485 When reporting a stop to the core for a thread, that thread is moved back
1486 to the NOT_RESUMED state. */
1487 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1488
1489 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1490 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
dc146f7c
VP
1491};
1492
de44f5a7 1493remote_state::remote_state ()
8d64371b 1494 : buf (400)
de44f5a7 1495{
de44f5a7
PA
1496}
1497
1498remote_state::~remote_state ()
1499{
1500 xfree (this->last_pass_packet);
1501 xfree (this->last_program_signals_packet);
de44f5a7
PA
1502 xfree (this->finished_object);
1503 xfree (this->finished_annex);
cf792862
TT
1504}
1505
35b1e5cc
SS
1506/* Utility: generate error from an incoming stub packet. */
1507static void
1508trace_error (char *buf)
1509{
1510 if (*buf++ != 'E')
1511 return; /* not an error msg */
1512 switch (*buf)
1513 {
1514 case '1': /* malformed packet error */
1515 if (*++buf == '0') /* general case: */
1516 error (_("remote.c: error in outgoing packet."));
1517 else
1518 error (_("remote.c: error in outgoing packet at field #%ld."),
1519 strtol (buf, NULL, 16));
35b1e5cc
SS
1520 default:
1521 error (_("Target returns error code '%s'."), buf);
1522 }
1523}
1524
1525/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1526
6b8edb51
PA
1527char *
1528remote_target::remote_get_noisy_reply ()
35b1e5cc 1529{
b6bb3468
PA
1530 struct remote_state *rs = get_remote_state ();
1531
35b1e5cc
SS
1532 do /* Loop on reply from remote stub. */
1533 {
1534 char *buf;
a744cf53 1535
0df8b418 1536 QUIT; /* Allow user to bail out with ^C. */
8d64371b
TT
1537 getpkt (&rs->buf, 0);
1538 buf = rs->buf.data ();
ad91cd99 1539 if (buf[0] == 'E')
35b1e5cc 1540 trace_error (buf);
61012eef 1541 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1542 {
1543 ULONGEST ul;
1544 CORE_ADDR from, to, org_to;
256642e8 1545 const char *p, *pp;
dde08ee1 1546 int adjusted_size = 0;
7556d4a4 1547 int relocated = 0;
dde08ee1
PA
1548
1549 p = buf + strlen ("qRelocInsn:");
1550 pp = unpack_varlen_hex (p, &ul);
1551 if (*pp != ';')
cb91c06a 1552 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1553 from = ul;
1554
1555 p = pp + 1;
a9cbf802 1556 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1557 to = ul;
1558
1559 org_to = to;
1560
a70b8144 1561 try
dde08ee1 1562 {
f5656ead 1563 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 1564 relocated = 1;
dde08ee1 1565 }
230d2906 1566 catch (const gdb_exception &ex)
7556d4a4
PA
1567 {
1568 if (ex.error == MEMORY_ERROR)
1569 {
1570 /* Propagate memory errors silently back to the
1571 target. The stub may have limited the range of
1572 addresses we can write to, for example. */
1573 }
1574 else
1575 {
1576 /* Something unexpectedly bad happened. Be verbose
1577 so we can tell what, and propagate the error back
1578 to the stub, so it doesn't get stuck waiting for
1579 a response. */
1580 exception_fprintf (gdb_stderr, ex,
1581 _("warning: relocating instruction: "));
1582 }
1583 putpkt ("E01");
1584 }
1585
1586 if (relocated)
dde08ee1
PA
1587 {
1588 adjusted_size = to - org_to;
1589
8d64371b 1590 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1591 putpkt (buf);
1592 }
dde08ee1 1593 }
ad91cd99 1594 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
1595 remote_console_output (buf + 1); /* 'O' message from stub */
1596 else
0df8b418 1597 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1598 }
1599 while (1);
1600}
3c3bea1c 1601
9d6eea31
PA
1602struct remote_arch_state *
1603remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1604{
43c3a0e4
PA
1605 remote_arch_state *rsa;
1606
1607 auto it = this->m_arch_states.find (gdbarch);
1608 if (it == this->m_arch_states.end ())
9d6eea31 1609 {
43c3a0e4
PA
1610 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1611 std::forward_as_tuple (gdbarch),
1612 std::forward_as_tuple (gdbarch));
1613 rsa = &p.first->second;
9d6eea31
PA
1614
1615 /* Make sure that the packet buffer is plenty big enough for
1616 this architecture. */
8d64371b
TT
1617 if (this->buf.size () < rsa->remote_packet_size)
1618 this->buf.resize (2 * rsa->remote_packet_size);
9d6eea31 1619 }
43c3a0e4
PA
1620 else
1621 rsa = &it->second;
1622
1623 return rsa;
d01949b6
AC
1624}
1625
0b83947e
DJ
1626/* Fetch the global remote target state. */
1627
6b8edb51
PA
1628remote_state *
1629remote_target::get_remote_state ()
0b83947e
DJ
1630{
1631 /* Make sure that the remote architecture state has been
1632 initialized, because doing so might reallocate rs->buf. Any
1633 function which calls getpkt also needs to be mindful of changes
1634 to rs->buf, but this call limits the number of places which run
1635 into trouble. */
3c69da40 1636 m_remote_state.get_remote_arch_state (target_gdbarch ());
0b83947e 1637
3c69da40 1638 return &m_remote_state;
0b83947e
DJ
1639}
1640
94585166
DB
1641/* Fetch the remote exec-file from the current program space. */
1642
1643static const char *
1644get_remote_exec_file (void)
1645{
1646 char *remote_exec_file;
1647
7b4a314f 1648 remote_exec_file = remote_pspace_data.get (current_program_space);
94585166
DB
1649 if (remote_exec_file == NULL)
1650 return "";
1651
1652 return remote_exec_file;
1653}
1654
1655/* Set the remote exec file for PSPACE. */
1656
1657static void
1658set_pspace_remote_exec_file (struct program_space *pspace,
7b4a314f 1659 const char *remote_exec_file)
94585166 1660{
7b4a314f 1661 char *old_file = remote_pspace_data.get (pspace);
94585166
DB
1662
1663 xfree (old_file);
7b4a314f 1664 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
94585166
DB
1665}
1666
1667/* The "set/show remote exec-file" set command hook. */
1668
1669static void
eb4c3f4a 1670set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1671 struct cmd_list_element *c)
1672{
e0700ba4
SM
1673 set_pspace_remote_exec_file (current_program_space,
1674 remote_exec_file_var.c_str ());
94585166
DB
1675}
1676
1677/* The "set/show remote exec-file" show command hook. */
1678
1679static void
1680show_remote_exec_file (struct ui_file *file, int from_tty,
1681 struct cmd_list_element *cmd, const char *value)
1682{
6cb06a8c 1683 gdb_printf (file, "%s\n", get_remote_exec_file ());
94585166
DB
1684}
1685
c21236dc
PA
1686static int
1687map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1688{
74ca34ce 1689 int regnum, num_remote_regs, offset;
74ca34ce 1690 struct packet_reg **remote_regs;
ea9c271d 1691
4a22f64d 1692 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1693 {
c21236dc 1694 struct packet_reg *r = &regs[regnum];
baef701f 1695
4a22f64d 1696 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1697 /* Do not try to fetch zero-sized (placeholder) registers. */
1698 r->pnum = -1;
1699 else
1700 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1701
b323314b 1702 r->regnum = regnum;
74ca34ce
DJ
1703 }
1704
1705 /* Define the g/G packet format as the contents of each register
1706 with a remote protocol number, in order of ascending protocol
1707 number. */
1708
224c3ddb 1709 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1710 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1711 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1712 regnum++)
c21236dc
PA
1713 if (regs[regnum].pnum != -1)
1714 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1715
39ef2f62
CB
1716 std::sort (remote_regs, remote_regs + num_remote_regs,
1717 [] (const packet_reg *a, const packet_reg *b)
1718 { return a->pnum < b->pnum; });
74ca34ce
DJ
1719
1720 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1721 {
1722 remote_regs[regnum]->in_g_packet = 1;
1723 remote_regs[regnum]->offset = offset;
4a22f64d 1724 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1725 }
1726
c21236dc
PA
1727 return offset;
1728}
1729
1730/* Given the architecture described by GDBARCH, return the remote
1731 protocol register's number and the register's offset in the g/G
1732 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1733 If the target does not have a mapping for REGNUM, return false,
1734 otherwise, return true. */
1735
1736int
1737remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1738 int *pnum, int *poffset)
1739{
c21236dc
PA
1740 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1741
b80406ac 1742 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1743
b80406ac 1744 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1745
1746 *pnum = regs[regnum].pnum;
1747 *poffset = regs[regnum].offset;
1748
c21236dc
PA
1749 return *pnum != -1;
1750}
1751
9d6eea31 1752remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1753{
c21236dc
PA
1754 /* Use the architecture to build a regnum<->pnum table, which will be
1755 1:1 unless a feature set specifies otherwise. */
9d6eea31 1756 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1757
74ca34ce
DJ
1758 /* Record the maximum possible size of the g packet - it may turn out
1759 to be smaller. */
9d6eea31
PA
1760 this->sizeof_g_packet
1761 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1762
0df8b418 1763 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1764 remote stubs have a hardwired buffer size of 400 bytes
1765 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1766 as the maximum packet-size to ensure that the packet and an extra
1767 NUL character can always fit in the buffer. This stops GDB
1768 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1769 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1770 this->remote_packet_size = 400 - 1;
d01949b6 1771
ea9c271d 1772 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1773 this->actual_register_packet_size = 0;
ea9c271d
DJ
1774
1775 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1776 default, adjust the size accordingly. Remember that each byte is
1777 encoded as two characters. 32 is the overhead for the packet
1778 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1779 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1780 little. */
9d6eea31
PA
1781 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1782 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1783}
1784
6b8edb51
PA
1785/* Get a pointer to the current remote target. If not connected to a
1786 remote target, return NULL. */
1787
1788static remote_target *
1789get_current_remote_target ()
1790{
5b6d1e4f 1791 target_ops *proc_target = current_inferior ()->process_target ();
6b8edb51
PA
1792 return dynamic_cast<remote_target *> (proc_target);
1793}
1794
ea9c271d
DJ
1795/* Return the current allowed size of a remote packet. This is
1796 inferred from the current architecture, and should be used to
1797 limit the length of outgoing packets. */
6b8edb51
PA
1798long
1799remote_target::get_remote_packet_size ()
ea9c271d 1800{
be2a5f71 1801 struct remote_state *rs = get_remote_state ();
9d6eea31 1802 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1803
be2a5f71
DJ
1804 if (rs->explicit_packet_size)
1805 return rs->explicit_packet_size;
1806
ea9c271d 1807 return rsa->remote_packet_size;
d01949b6
AC
1808}
1809
ad10f812 1810static struct packet_reg *
5cd63fda
PA
1811packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1812 long regnum)
ad10f812 1813{
5cd63fda 1814 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1815 return NULL;
1816 else
ad10f812 1817 {
ea9c271d 1818 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1819
b323314b
AC
1820 gdb_assert (r->regnum == regnum);
1821 return r;
ad10f812 1822 }
ad10f812
AC
1823}
1824
1825static struct packet_reg *
5cd63fda
PA
1826packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1827 LONGEST pnum)
ad10f812 1828{
b323314b 1829 int i;
a744cf53 1830
5cd63fda 1831 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1832 {
ea9c271d 1833 struct packet_reg *r = &rsa->regs[i];
a744cf53 1834
b323314b
AC
1835 if (r->pnum == pnum)
1836 return r;
ad10f812
AC
1837 }
1838 return NULL;
d01949b6
AC
1839}
1840
9a7071a8
JB
1841/* Allow the user to specify what sequence to send to the remote
1842 when he requests a program interruption: Although ^C is usually
1843 what remote systems expect (this is the default, here), it is
1844 sometimes preferable to send a break. On other systems such
1845 as the Linux kernel, a break followed by g, which is Magic SysRq g
1846 is required in order to interrupt the execution. */
1847const char interrupt_sequence_control_c[] = "Ctrl-C";
1848const char interrupt_sequence_break[] = "BREAK";
1849const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1850static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1851 {
1852 interrupt_sequence_control_c,
1853 interrupt_sequence_break,
1854 interrupt_sequence_break_g,
1855 NULL
1856 };
1857static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1858
1859static void
1860show_interrupt_sequence (struct ui_file *file, int from_tty,
1861 struct cmd_list_element *c,
1862 const char *value)
1863{
1864 if (interrupt_sequence_mode == interrupt_sequence_control_c)
6cb06a8c
TT
1865 gdb_printf (file,
1866 _("Send the ASCII ETX character (Ctrl-c) "
1867 "to the remote target to interrupt the "
1868 "execution of the program.\n"));
9a7071a8 1869 else if (interrupt_sequence_mode == interrupt_sequence_break)
6cb06a8c
TT
1870 gdb_printf (file,
1871 _("send a break signal to the remote target "
1872 "to interrupt the execution of the program.\n"));
9a7071a8 1873 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
6cb06a8c
TT
1874 gdb_printf (file,
1875 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1876 "the remote target to interrupt the execution "
1877 "of Linux kernel.\n"));
9a7071a8 1878 else
f34652de 1879 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
9a7071a8
JB
1880 interrupt_sequence_mode);
1881}
6426a772 1882
9a7071a8
JB
1883/* This boolean variable specifies whether interrupt_sequence is sent
1884 to the remote target when gdb connects to it.
1885 This is mostly needed when you debug the Linux kernel: The Linux kernel
1886 expects BREAK g which is Magic SysRq g for connecting gdb. */
491144b5 1887static bool interrupt_on_connect = false;
c906108c 1888
9a7071a8
JB
1889/* This variable is used to implement the "set/show remotebreak" commands.
1890 Since these commands are now deprecated in favor of "set/show remote
1891 interrupt-sequence", it no longer has any effect on the code. */
491144b5 1892static bool remote_break;
c906108c 1893
9a7071a8 1894static void
eb4c3f4a 1895set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1896{
1897 if (remote_break)
1898 interrupt_sequence_mode = interrupt_sequence_break;
1899 else
1900 interrupt_sequence_mode = interrupt_sequence_control_c;
1901}
1902
1903static void
1904show_remotebreak (struct ui_file *file, int from_tty,
1905 struct cmd_list_element *c,
1906 const char *value)
1907{
1908}
1909
c906108c
SS
1910/* This variable sets the number of bits in an address that are to be
1911 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1912 leading zeros, the entire address would be sent. This variable
c906108c
SS
1913 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1914 initial implementation of remote.c restricted the address sent in
1915 memory packets to ``host::sizeof long'' bytes - (typically 32
1916 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1917 address was never sent. Since fixing this bug may cause a break in
85102364 1918 some remote targets this variable is principally provided to
23860348 1919 facilitate backward compatibility. */
c906108c 1920
883b9c6c 1921static unsigned int remote_address_size;
c906108c 1922
11cf8741 1923\f
11cf8741 1924/* User configurable variables for the number of characters in a
ea9c271d
DJ
1925 memory read/write packet. MIN (rsa->remote_packet_size,
1926 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1927 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1928 (speed up transfers). The variables ``preferred_*'' (the user
1929 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1930 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1931
1932struct memory_packet_config
1933{
a121b7c1 1934 const char *name;
11cf8741
JM
1935 long size;
1936 int fixed_p;
1937};
1938
cc0be08f
PA
1939/* The default max memory-write-packet-size, when the setting is
1940 "fixed". The 16k is historical. (It came from older GDB's using
1941 alloca for buffers and the knowledge (folklore?) that some hosts
1942 don't cope very well with large alloca calls.) */
1943#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
1944
1945/* The minimum remote packet size for memory transfers. Ensures we
1946 can write at least one byte. */
1947#define MIN_MEMORY_PACKET_SIZE 20
1948
cc0be08f
PA
1949/* Get the memory packet size, assuming it is fixed. */
1950
1951static long
1952get_fixed_memory_packet_size (struct memory_packet_config *config)
1953{
1954 gdb_assert (config->fixed_p);
1955
1956 if (config->size <= 0)
1957 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1958 else
1959 return config->size;
1960}
1961
11cf8741
JM
1962/* Compute the current size of a read/write packet. Since this makes
1963 use of ``actual_register_packet_size'' the computation is dynamic. */
1964
6b8edb51
PA
1965long
1966remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 1967{
d01949b6 1968 struct remote_state *rs = get_remote_state ();
9d6eea31 1969 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1970
11cf8741
JM
1971 long what_they_get;
1972 if (config->fixed_p)
cc0be08f 1973 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
1974 else
1975 {
ea9c271d 1976 what_they_get = get_remote_packet_size ();
23860348 1977 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1978 if (config->size > 0
1979 && what_they_get > config->size)
1980 what_they_get = config->size;
be2a5f71
DJ
1981
1982 /* Limit it to the size of the targets ``g'' response unless we have
1983 permission from the stub to use a larger packet size. */
1984 if (rs->explicit_packet_size == 0
1985 && rsa->actual_register_packet_size > 0
1986 && what_they_get > rsa->actual_register_packet_size)
1987 what_they_get = rsa->actual_register_packet_size;
11cf8741 1988 }
a5c0808e
PA
1989 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1990 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1991
1992 /* Make sure there is room in the global buffer for this packet
1993 (including its trailing NUL byte). */
8d64371b
TT
1994 if (rs->buf.size () < what_they_get + 1)
1995 rs->buf.resize (2 * what_they_get);
6d820c5c 1996
11cf8741
JM
1997 return what_they_get;
1998}
1999
0df8b418 2000/* Update the size of a read/write packet. If they user wants
23860348 2001 something really big then do a sanity check. */
11cf8741
JM
2002
2003static void
ac88e2de 2004set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
2005{
2006 int fixed_p = config->fixed_p;
2007 long size = config->size;
a744cf53 2008
11cf8741 2009 if (args == NULL)
8a3fe4f8 2010 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
2011 else if (strcmp (args, "hard") == 0
2012 || strcmp (args, "fixed") == 0)
2013 fixed_p = 1;
2014 else if (strcmp (args, "soft") == 0
2015 || strcmp (args, "limit") == 0)
2016 fixed_p = 0;
2017 else
2018 {
2019 char *end;
a744cf53 2020
11cf8741
JM
2021 size = strtoul (args, &end, 0);
2022 if (args == end)
8a3fe4f8 2023 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
2024
2025 /* Instead of explicitly capping the size of a packet to or
2026 disallowing it, the user is allowed to set the size to
2027 something arbitrarily large. */
11cf8741 2028 }
a5c0808e 2029
23860348 2030 /* Extra checks? */
11cf8741
JM
2031 if (fixed_p && !config->fixed_p)
2032 {
cc0be08f
PA
2033 /* So that the query shows the correct value. */
2034 long query_size = (size <= 0
2035 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2036 : size);
2037
e2e0b3e5
AC
2038 if (! query (_("The target may not be able to correctly handle a %s\n"
2039 "of %ld bytes. Change the packet size? "),
cc0be08f 2040 config->name, query_size))
8a3fe4f8 2041 error (_("Packet size not changed."));
11cf8741 2042 }
23860348 2043 /* Update the config. */
11cf8741
JM
2044 config->fixed_p = fixed_p;
2045 config->size = size;
2046}
2047
2048static void
2049show_memory_packet_size (struct memory_packet_config *config)
2050{
cc0be08f 2051 if (config->size == 0)
6cb06a8c 2052 gdb_printf (_("The %s is 0 (default). "), config->name);
cc0be08f 2053 else
6cb06a8c 2054 gdb_printf (_("The %s is %ld. "), config->name, config->size);
11cf8741 2055 if (config->fixed_p)
6cb06a8c
TT
2056 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2057 get_fixed_memory_packet_size (config));
11cf8741 2058 else
cc0be08f 2059 {
6b8edb51 2060 remote_target *remote = get_current_remote_target ();
cc0be08f 2061
6b8edb51 2062 if (remote != NULL)
6cb06a8c
TT
2063 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2064 remote->get_memory_packet_size (config));
cc0be08f 2065 else
0426ad51
TT
2066 gdb_puts ("The actual limit will be further reduced "
2067 "dependent on the target.\n");
cc0be08f 2068 }
11cf8741
JM
2069}
2070
5b6d1e4f 2071/* FIXME: needs to be per-remote-target. */
11cf8741
JM
2072static struct memory_packet_config memory_write_packet_config =
2073{
2074 "memory-write-packet-size",
2075};
2076
2077static void
ac88e2de 2078set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
2079{
2080 set_memory_packet_size (args, &memory_write_packet_config);
2081}
2082
2083static void
ac88e2de 2084show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
2085{
2086 show_memory_packet_size (&memory_write_packet_config);
2087}
2088
055303e2
AB
2089/* Show the number of hardware watchpoints that can be used. */
2090
2091static void
2092show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2093 struct cmd_list_element *c,
2094 const char *value)
2095{
6cb06a8c
TT
2096 gdb_printf (file, _("The maximum number of target hardware "
2097 "watchpoints is %s.\n"), value);
055303e2
AB
2098}
2099
2100/* Show the length limit (in bytes) for hardware watchpoints. */
2101
2102static void
2103show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2104 struct cmd_list_element *c,
2105 const char *value)
2106{
6cb06a8c
TT
2107 gdb_printf (file, _("The maximum length (in bytes) of a target "
2108 "hardware watchpoint is %s.\n"), value);
055303e2
AB
2109}
2110
2111/* Show the number of hardware breakpoints that can be used. */
2112
2113static void
2114show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2115 struct cmd_list_element *c,
2116 const char *value)
2117{
6cb06a8c
TT
2118 gdb_printf (file, _("The maximum number of target hardware "
2119 "breakpoints is %s.\n"), value);
055303e2
AB
2120}
2121
6cc8564b
LM
2122/* Controls the maximum number of characters to display in the debug output
2123 for each remote packet. The remaining characters are omitted. */
2124
2125static int remote_packet_max_chars = 512;
2126
2127/* Show the maximum number of characters to display for each remote packet
2128 when remote debugging is enabled. */
2129
2130static void
2131show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2132 struct cmd_list_element *c,
2133 const char *value)
2134{
6cb06a8c
TT
2135 gdb_printf (file, _("Number of remote packet characters to "
2136 "display is %s.\n"), value);
6cc8564b
LM
2137}
2138
6b8edb51
PA
2139long
2140remote_target::get_memory_write_packet_size ()
11cf8741
JM
2141{
2142 return get_memory_packet_size (&memory_write_packet_config);
2143}
2144
5b6d1e4f 2145/* FIXME: needs to be per-remote-target. */
11cf8741
JM
2146static struct memory_packet_config memory_read_packet_config =
2147{
2148 "memory-read-packet-size",
2149};
2150
2151static void
ac88e2de 2152set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
2153{
2154 set_memory_packet_size (args, &memory_read_packet_config);
2155}
2156
2157static void
ac88e2de 2158show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
2159{
2160 show_memory_packet_size (&memory_read_packet_config);
2161}
2162
6b8edb51
PA
2163long
2164remote_target::get_memory_read_packet_size ()
11cf8741
JM
2165{
2166 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 2167
11cf8741
JM
2168 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2169 extra buffer size argument before the memory read size can be
ea9c271d
DJ
2170 increased beyond this. */
2171 if (size > get_remote_packet_size ())
2172 size = get_remote_packet_size ();
11cf8741
JM
2173 return size;
2174}
2175
ff52c073 2176static enum packet_support packet_config_support (const packet_config *config);
5a2468f5 2177
4082afcc 2178
ff52c073
CS
2179static void
2180set_remote_protocol_packet_cmd (const char *args, int from_tty,
2181 cmd_list_element *c)
2182{
2183 remote_target *remote = get_current_remote_target ();
2184 gdb_assert (c->var.has_value ());
4082afcc 2185
ff52c073
CS
2186 auto *default_config = static_cast<packet_config *> (c->context ());
2187 const int packet_idx = std::distance (remote_protocol_packets,
2188 default_config);
fcef6471 2189
ff52c073
CS
2190 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2191 {
2192 const char *name = packets_descriptions[packet_idx].name;
2193 const auto_boolean value = c->var->get<auto_boolean> ();
2194 const char *support = get_packet_support_name (value);
2195 const char *target_type = get_target_type_name (remote != nullptr);
5a2468f5 2196
ff52c073
CS
2197 if (remote != nullptr)
2198 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2199 else
2200 remote_protocol_packets[packet_idx].detect = value;
2201
2202 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2203 target_type, support);
2204 return;
2205 }
2206
2207 internal_error (_("Could not find config for %s"), c->name);
2208}
5a2468f5
JM
2209
2210static void
ff52c073
CS
2211show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2212 remote_target *remote)
5a2468f5 2213{
a121b7c1 2214 const char *support = "internal-error";
ff52c073
CS
2215 const char *target_type = get_target_type_name (remote != nullptr);
2216
2217 packet_config *config;
2218 if (remote != nullptr)
2219 config = &remote->m_features.m_protocol_packets[which_packet];
2220 else
2221 config = &remote_protocol_packets[which_packet];
a744cf53 2222
4082afcc 2223 switch (packet_config_support (config))
5a2468f5
JM
2224 {
2225 case PACKET_ENABLE:
2226 support = "enabled";
2227 break;
2228 case PACKET_DISABLE:
2229 support = "disabled";
2230 break;
2231 case PACKET_SUPPORT_UNKNOWN:
2232 support = "unknown";
2233 break;
2234 }
2235 switch (config->detect)
2236 {
7f19b9a2 2237 case AUTO_BOOLEAN_AUTO:
6cb06a8c 2238 gdb_printf (file,
ff52c073
CS
2239 _("Support for the '%s' packet %s is \"auto\", "
2240 "currently %s.\n"),
2241 packets_descriptions[which_packet].name, target_type,
2242 support);
5a2468f5 2243 break;
7f19b9a2
AC
2244 case AUTO_BOOLEAN_TRUE:
2245 case AUTO_BOOLEAN_FALSE:
6cb06a8c 2246 gdb_printf (file,
ff52c073
CS
2247 _("Support for the '%s' packet %s is \"%s\".\n"),
2248 packets_descriptions[which_packet].name, target_type,
2249 get_packet_support_name (config->detect));
8e248173 2250 break;
5a2468f5
JM
2251 }
2252}
2253
2254static void
ff52c073 2255add_packet_config_cmd (const unsigned int which_packet, const char *name,
bb572ddd 2256 const char *title, int legacy)
d471ea57 2257{
ff52c073
CS
2258 packets_descriptions[which_packet].name = name;
2259 packets_descriptions[which_packet].title = title;
2260
2261 packet_config *config = &remote_protocol_packets[which_packet];
2262
8579fd13
AB
2263 gdb::unique_xmalloc_ptr<char> set_doc
2264 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2265 name, title);
2266 gdb::unique_xmalloc_ptr<char> show_doc
2267 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2268 name, title);
d471ea57 2269 /* set/show TITLE-packet {auto,on,off} */
8579fd13 2270 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
5e84b7ee 2271 set_show_commands cmds
8579fd13
AB
2272 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2273 &config->detect, set_doc.get (),
2274 show_doc.get (), NULL, /* help_doc */
ff52c073 2275 set_remote_protocol_packet_cmd,
5e84b7ee
SM
2276 show_remote_protocol_packet_cmd,
2277 &remote_set_cmdlist, &remote_show_cmdlist);
ff52c073
CS
2278 cmds.show->set_context (config);
2279 cmds.set->set_context (config);
5e84b7ee 2280
23860348 2281 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
2282 if (legacy)
2283 {
5f21c7aa
AB
2284 /* It's not clear who should take ownership of the LEGACY_NAME string
2285 created below, so, for now, place the string into a static vector
2286 which ensures the strings is released when GDB exits. */
2287 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2288 gdb::unique_xmalloc_ptr<char> legacy_name
8579fd13
AB
2289 = xstrprintf ("%s-packet", name);
2290 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
bb572ddd 2291 &remote_set_cmdlist);
8579fd13 2292 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
bb572ddd 2293 &remote_show_cmdlist);
5f21c7aa 2294 legacy_names.emplace_back (std::move (legacy_name));
d471ea57 2295 }
5a2468f5
JM
2296}
2297
d471ea57 2298static enum packet_result
a76d924d 2299packet_check_result (const char *buf)
5a2468f5 2300{
d471ea57 2301 if (buf[0] != '\0')
5a2468f5 2302 {
d471ea57 2303 /* The stub recognized the packet request. Check that the
23860348 2304 operation succeeded. */
a76d924d
DJ
2305 if (buf[0] == 'E'
2306 && isxdigit (buf[1]) && isxdigit (buf[2])
2307 && buf[3] == '\0')
85102364 2308 /* "Enn" - definitely an error. */
a76d924d
DJ
2309 return PACKET_ERROR;
2310
2311 /* Always treat "E." as an error. This will be used for
2312 more verbose error messages, such as E.memtypes. */
2313 if (buf[0] == 'E' && buf[1] == '.')
2314 return PACKET_ERROR;
2315
2316 /* The packet may or may not be OK. Just assume it is. */
2317 return PACKET_OK;
2318 }
2319 else
2320 /* The stub does not support the packet. */
2321 return PACKET_UNKNOWN;
2322}
2323
8d64371b
TT
2324static enum packet_result
2325packet_check_result (const gdb::char_vector &buf)
2326{
2327 return packet_check_result (buf.data ());
2328}
2329
ff52c073
CS
2330packet_result
2331remote_features::packet_ok (const char *buf, const int which_packet)
a76d924d 2332{
ff52c073
CS
2333 packet_config *config = &m_protocol_packets[which_packet];
2334 packet_description *descr = &packets_descriptions[which_packet];
2335
a76d924d
DJ
2336 enum packet_result result;
2337
4082afcc
PA
2338 if (config->detect != AUTO_BOOLEAN_TRUE
2339 && config->support == PACKET_DISABLE)
f34652de 2340 internal_error (_("packet_ok: attempt to use a disabled packet"));
4082afcc 2341
a76d924d
DJ
2342 result = packet_check_result (buf);
2343 switch (result)
2344 {
2345 case PACKET_OK:
2346 case PACKET_ERROR:
2347 /* The stub recognized the packet request. */
4082afcc 2348 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 2349 {
2189c312 2350 remote_debug_printf ("Packet %s (%s) is supported",
ff52c073 2351 descr->name, descr->title);
d471ea57 2352 config->support = PACKET_ENABLE;
d471ea57 2353 }
a76d924d
DJ
2354 break;
2355 case PACKET_UNKNOWN:
23860348 2356 /* The stub does not support the packet. */
4082afcc
PA
2357 if (config->detect == AUTO_BOOLEAN_AUTO
2358 && config->support == PACKET_ENABLE)
d471ea57 2359 {
4082afcc
PA
2360 /* If the stub previously indicated that the packet was
2361 supported then there is a protocol error. */
2362 error (_("Protocol error: %s (%s) conflicting enabled responses."),
ff52c073 2363 descr->name, descr->title);
4082afcc
PA
2364 }
2365 else if (config->detect == AUTO_BOOLEAN_TRUE)
2366 {
2367 /* The user set it wrong. */
2368 error (_("Enabled packet %s (%s) not recognized by stub"),
ff52c073 2369 descr->name, descr->title);
d471ea57 2370 }
4082afcc 2371
ff52c073
CS
2372 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2373 descr->title);
4082afcc 2374 config->support = PACKET_DISABLE;
a76d924d 2375 break;
5a2468f5 2376 }
a76d924d
DJ
2377
2378 return result;
5a2468f5
JM
2379}
2380
ff52c073
CS
2381packet_result
2382remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
f7e6eed5 2383{
ff52c073 2384 return packet_ok (buf.data (), which_packet);
f7e6eed5
PA
2385}
2386
4082afcc
PA
2387/* Returns whether a given packet or feature is supported. This takes
2388 into account the state of the corresponding "set remote foo-packet"
2389 command, which may be used to bypass auto-detection. */
dc8acb97 2390
4082afcc 2391static enum packet_support
ff52c073 2392packet_config_support (const packet_config *config)
4082afcc
PA
2393{
2394 switch (config->detect)
444abaca 2395 {
4082afcc
PA
2396 case AUTO_BOOLEAN_TRUE:
2397 return PACKET_ENABLE;
2398 case AUTO_BOOLEAN_FALSE:
2399 return PACKET_DISABLE;
2400 case AUTO_BOOLEAN_AUTO:
2401 return config->support;
2402 default:
557b4d76 2403 gdb_assert_not_reached ("bad switch");
444abaca 2404 }
4082afcc
PA
2405}
2406
ff52c073
CS
2407packet_support
2408remote_features::packet_support (int packet) const
4082afcc 2409{
ff52c073 2410 const packet_config *config = &m_protocol_packets[packet];
4082afcc 2411 return packet_config_support (config);
dc8acb97
MS
2412}
2413
5a2468f5 2414static void
444abaca
DJ
2415show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2416 struct cmd_list_element *c,
2417 const char *value)
5a2468f5 2418{
ff52c073 2419 remote_target *remote = get_current_remote_target ();
1d7fe7f0 2420 gdb_assert (c->var.has_value ());
5a2468f5 2421
ff52c073
CS
2422 auto *default_config = static_cast<packet_config *> (c->context ());
2423 const int packet_idx = std::distance (remote_protocol_packets,
2424 default_config);
2425
2426 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
444abaca 2427 {
ff52c073
CS
2428 show_packet_config_cmd (file, packet_idx, remote);
2429 return;
444abaca 2430 }
ff52c073 2431 internal_error (_("Could not find config for %s"), c->name);
5a2468f5
JM
2432}
2433
d471ea57
AC
2434/* Should we try one of the 'Z' requests? */
2435
2436enum Z_packet_type
2437{
2438 Z_PACKET_SOFTWARE_BP,
2439 Z_PACKET_HARDWARE_BP,
2440 Z_PACKET_WRITE_WP,
2441 Z_PACKET_READ_WP,
2442 Z_PACKET_ACCESS_WP,
2443 NR_Z_PACKET_TYPES
2444};
96baa820 2445
d471ea57 2446/* For compatibility with older distributions. Provide a ``set remote
23860348 2447 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2448
7f19b9a2 2449static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2450
2451static void
eb4c3f4a 2452set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2453 struct cmd_list_element *c)
96baa820 2454{
ff52c073 2455 remote_target *remote = get_current_remote_target ();
d471ea57 2456 int i;
a744cf53 2457
d471ea57 2458 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
ff52c073
CS
2459 {
2460 if (remote != nullptr)
2461 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2462 = remote_Z_packet_detect;
2463 else
2464 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2465 }
2466
2467 const char *support = get_packet_support_name (remote_Z_packet_detect);
2468 const char *target_type = get_target_type_name (remote != nullptr);
2469 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2470 support);
2471
96baa820
JM
2472}
2473
2474static void
08546159
AC
2475show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2476 struct cmd_list_element *c,
2477 const char *value)
96baa820 2478{
ff52c073 2479 remote_target *remote = get_current_remote_target ();
d471ea57 2480 int i;
a744cf53 2481
d471ea57 2482 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
ff52c073 2483 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2c2e7f87
LM
2484}
2485
cbb8991c
DB
2486/* Insert fork catchpoint target routine. If fork events are enabled
2487 then return success, nothing more to do. */
2488
f6ac5f3d
PA
2489int
2490remote_target::insert_fork_catchpoint (int pid)
cbb8991c 2491{
ff52c073 2492 return !m_features.remote_fork_event_p ();
cbb8991c
DB
2493}
2494
2495/* Remove fork catchpoint target routine. Nothing to do, just
2496 return success. */
2497
f6ac5f3d
PA
2498int
2499remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2500{
2501 return 0;
2502}
2503
2504/* Insert vfork catchpoint target routine. If vfork events are enabled
2505 then return success, nothing more to do. */
2506
f6ac5f3d
PA
2507int
2508remote_target::insert_vfork_catchpoint (int pid)
cbb8991c 2509{
ff52c073 2510 return !m_features.remote_vfork_event_p ();
cbb8991c
DB
2511}
2512
2513/* Remove vfork catchpoint target routine. Nothing to do, just
2514 return success. */
2515
f6ac5f3d
PA
2516int
2517remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2518{
2519 return 0;
2520}
2521
d46addbb
DB
2522/* Insert exec catchpoint target routine. If exec events are
2523 enabled, just return success. */
2524
f6ac5f3d
PA
2525int
2526remote_target::insert_exec_catchpoint (int pid)
d46addbb 2527{
ff52c073 2528 return !m_features.remote_exec_event_p ();
d46addbb
DB
2529}
2530
2531/* Remove exec catchpoint target routine. Nothing to do, just
2532 return success. */
2533
f6ac5f3d
PA
2534int
2535remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2536{
2537 return 0;
2538}
2539
c906108c
SS
2540\f
2541
ffdd69cf
TT
2542/* Take advantage of the fact that the TID field is not used, to tag
2543 special ptids with it set to != 0. */
2544static const ptid_t magic_null_ptid (42000, -1, 1);
2545static const ptid_t not_sent_ptid (42000, -2, 1);
2546static const ptid_t any_thread_ptid (42000, 0, 1);
79d7f229 2547
0b16c5cf
PA
2548/* Find out if the stub attached to PID (and hence GDB should offer to
2549 detach instead of killing it when bailing out). */
2550
6b8edb51
PA
2551int
2552remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2553{
2554 struct remote_state *rs = get_remote_state ();
bba74b36 2555 size_t size = get_remote_packet_size ();
0b16c5cf 2556
ff52c073 2557 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2558 return 0;
2559
ff52c073 2560 if (m_features.remote_multi_process_p ())
8d64371b 2561 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
0b16c5cf 2562 else
8d64371b 2563 xsnprintf (rs->buf.data (), size, "qAttached");
0b16c5cf
PA
2564
2565 putpkt (rs->buf);
8d64371b 2566 getpkt (&rs->buf, 0);
0b16c5cf 2567
ff52c073 2568 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
0b16c5cf
PA
2569 {
2570 case PACKET_OK:
8d64371b 2571 if (strcmp (rs->buf.data (), "1") == 0)
0b16c5cf
PA
2572 return 1;
2573 break;
2574 case PACKET_ERROR:
8d64371b 2575 warning (_("Remote failure reply: %s"), rs->buf.data ());
0b16c5cf
PA
2576 break;
2577 case PACKET_UNKNOWN:
2578 break;
2579 }
2580
2581 return 0;
2582}
2583
49c62f2e
PA
2584/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2585 has been invented by GDB, instead of reported by the target. Since
2586 we can be connected to a remote system before before knowing about
2587 any inferior, mark the target with execution when we find the first
2588 inferior. If ATTACHED is 1, then we had just attached to this
2589 inferior. If it is 0, then we just created this inferior. If it
2590 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2591 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2592 attempt to open this inferior's executable as the main executable
2593 if no main executable is open already. */
1941c569 2594
6b8edb51 2595inferior *
9ab8741a 2596remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51 2597 int try_open_exec)
1941c569 2598{
1941c569
PA
2599 struct inferior *inf;
2600
0b16c5cf
PA
2601 /* Check whether this process we're learning about is to be
2602 considered attached, or if is to be considered to have been
2603 spawned by the stub. */
2604 if (attached == -1)
2605 attached = remote_query_attached (pid);
2606
f5656ead 2607 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2608 {
2609 /* If the target shares code across all inferiors, then every
2610 attach adds a new inferior. */
2611 inf = add_inferior (pid);
2612
2613 /* ... and every inferior is bound to the same program space.
2614 However, each inferior may still have its own address
2615 space. */
2616 inf->aspace = maybe_new_address_space ();
2617 inf->pspace = current_program_space;
2618 }
2619 else
2620 {
2621 /* In the traditional debugging scenario, there's a 1-1 match
2622 between program/address spaces. We simply bind the inferior
2623 to the program space's address space. */
2624 inf = current_inferior ();
78f2c40a
PA
2625
2626 /* However, if the current inferior is already bound to a
2627 process, find some other empty inferior. */
2628 if (inf->pid != 0)
2629 {
2630 inf = nullptr;
2631 for (inferior *it : all_inferiors ())
2632 if (it->pid == 0)
2633 {
2634 inf = it;
2635 break;
2636 }
2637 }
2638 if (inf == nullptr)
2639 {
2640 /* Since all inferiors were already bound to a process, add
2641 a new inferior. */
2642 inf = add_inferior_with_spaces ();
2643 }
2644 switch_to_inferior_no_thread (inf);
02980c56 2645 inf->push_target (this);
6c95b8df
PA
2646 inferior_appeared (inf, pid);
2647 }
1941c569 2648
0b16c5cf 2649 inf->attach_flag = attached;
49c62f2e 2650 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2651
1b6e6f5c
GB
2652 /* If no main executable is currently open then attempt to
2653 open the file that was executed to create this inferior. */
835205d0 2654 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2655 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2656
a2fedca9
PW
2657 /* Check for exec file mismatch, and let the user solve it. */
2658 validate_exec_file (1);
2659
1941c569
PA
2660 return inf;
2661}
2662
7aabaf9d 2663static remote_thread_info *get_remote_thread_info (thread_info *thread);
5b6d1e4f
PA
2664static remote_thread_info *get_remote_thread_info (remote_target *target,
2665 ptid_t ptid);
85ad3aaf 2666
1941c569 2667/* Add thread PTID to GDB's thread list. Tag it as executing/running
b622494e
AB
2668 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2669 remote_state::starting_up flag) is true then the new thread is added
2670 silently, otherwise the new thread will be announced to the user. */
1941c569 2671
00431a78 2672thread_info *
b622494e
AB
2673remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2674 bool silent_p)
c906108c 2675{
b7ea362b 2676 struct remote_state *rs = get_remote_state ();
85ad3aaf 2677 struct thread_info *thread;
b7ea362b
PA
2678
2679 /* GDB historically didn't pull threads in the initial connection
2680 setup. If the remote target doesn't even have a concept of
2681 threads (e.g., a bare-metal target), even if internally we
2682 consider that a single-threaded target, mentioning a new thread
2683 might be confusing to the user. Be silent then, preserving the
2684 age old behavior. */
b622494e 2685 if (rs->starting_up || silent_p)
5b6d1e4f 2686 thread = add_thread_silent (this, ptid);
b7ea362b 2687 else
5b6d1e4f 2688 thread = add_thread (this, ptid);
1941c569 2689
c9d22089
SM
2690 /* We start by assuming threads are resumed. That state then gets updated
2691 when we process a matching stop reply. */
2692 get_remote_thread_info (thread)->set_resumed ();
2693
5b6d1e4f
PA
2694 set_executing (this, ptid, executing);
2695 set_running (this, ptid, running);
00431a78
PA
2696
2697 return thread;
1941c569
PA
2698}
2699
2700/* Come here when we learn about a thread id from the remote target.
2701 It may be the first time we hear about such thread, so take the
2702 opportunity to add it to GDB's thread list. In case this is the
2703 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2704 GDB's inferior list as well. EXECUTING indicates whether the
2705 thread is (internally) executing or stopped. */
1941c569 2706
6b8edb51 2707void
8a82de58 2708remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
1941c569 2709{
0d5b594f
PA
2710 /* In non-stop mode, we assume new found threads are (externally)
2711 running until proven otherwise with a stop reply. In all-stop,
2712 we can only get here if all threads are stopped. */
8a82de58 2713 bool running = target_is_non_stop_p ();
0d5b594f 2714
c906108c
SS
2715 /* If this is a new thread, add it to GDB's thread list.
2716 If we leave it up to WFI to do this, bad things will happen. */
82f73884 2717
5b6d1e4f 2718 thread_info *tp = find_thread_ptid (this, currthread);
00431a78 2719 if (tp != NULL && tp->state == THREAD_EXITED)
82f73884
PA
2720 {
2721 /* We're seeing an event on a thread id we knew had exited.
2722 This has to be a new thread reusing the old id. Add it. */
b622494e 2723 remote_add_thread (currthread, running, executing, false);
82f73884
PA
2724 return;
2725 }
2726
5b6d1e4f 2727 if (!in_thread_list (this, currthread))
c0a2216e 2728 {
1941c569 2729 struct inferior *inf = NULL;
e99b03dc 2730 int pid = currthread.pid ();
1941c569 2731
0e998d96 2732 if (inferior_ptid.is_pid ()
e99b03dc 2733 && pid == inferior_ptid.pid ())
c0a2216e
PA
2734 {
2735 /* inferior_ptid has no thread member yet. This can happen
2736 with the vAttach -> remote_wait,"TAAthread:" path if the
2737 stub doesn't support qC. This is the first stop reported
2738 after an attach, so this is the main thread. Update the
2739 ptid in the thread list. */
5b6d1e4f
PA
2740 if (in_thread_list (this, ptid_t (pid)))
2741 thread_change_ptid (this, inferior_ptid, currthread);
bad34192
PA
2742 else
2743 {
0ac55310 2744 thread_info *thr
b622494e 2745 = remote_add_thread (currthread, running, executing, false);
0ac55310 2746 switch_to_thread (thr);
bad34192 2747 }
dc146f7c 2748 return;
c0a2216e 2749 }
82f73884 2750
d7e15655 2751 if (magic_null_ptid == inferior_ptid)
c0a2216e
PA
2752 {
2753 /* inferior_ptid is not set yet. This can happen with the
2754 vRun -> remote_wait,"TAAthread:" path if the stub
2755 doesn't support qC. This is the first stop reported
2756 after an attach, so this is the main thread. Update the
2757 ptid in the thread list. */
5b6d1e4f 2758 thread_change_ptid (this, inferior_ptid, currthread);
82f73884 2759 return;
c0a2216e 2760 }
82f73884 2761
29c87f7f
PA
2762 /* When connecting to a target remote, or to a target
2763 extended-remote which already was debugging an inferior, we
2764 may not know about it yet. Add it before adding its child
2765 thread, so notifications are emitted in a sensible order. */
5b6d1e4f 2766 if (find_inferior_pid (this, currthread.pid ()) == NULL)
49c62f2e 2767 {
ff52c073 2768 bool fake_pid_p = !m_features.remote_multi_process_p ();
49c62f2e
PA
2769
2770 inf = remote_add_inferior (fake_pid_p,
e99b03dc 2771 currthread.pid (), -1, 1);
49c62f2e 2772 }
29c87f7f 2773
82f73884 2774 /* This is really a new thread. Add it. */
00431a78 2775 thread_info *new_thr
b622494e 2776 = remote_add_thread (currthread, running, executing, false);
1941c569
PA
2777
2778 /* If we found a new inferior, let the common code do whatever
2779 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2780 breakpoints), unless we're just setting up an all-stop
2781 connection. */
1941c569 2782 if (inf != NULL)
b7ea362b
PA
2783 {
2784 struct remote_state *rs = get_remote_state ();
2785
6efcd9a8 2786 if (!rs->starting_up)
00431a78 2787 notice_new_inferior (new_thr, executing, 0);
b7ea362b 2788 }
c0a2216e 2789 }
c906108c
SS
2790}
2791
85ad3aaf 2792/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2793
7aabaf9d
SM
2794static remote_thread_info *
2795get_remote_thread_info (thread_info *thread)
dc146f7c 2796{
85ad3aaf 2797 gdb_assert (thread != NULL);
dc146f7c 2798
85ad3aaf 2799 if (thread->priv == NULL)
7aabaf9d 2800 thread->priv.reset (new remote_thread_info);
dc146f7c 2801
98ed24fb 2802 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2803}
2804
5b6d1e4f
PA
2805/* Return PTID's private thread data, creating it if necessary. */
2806
7aabaf9d 2807static remote_thread_info *
5b6d1e4f 2808get_remote_thread_info (remote_target *target, ptid_t ptid)
85ad3aaf 2809{
5b6d1e4f 2810 thread_info *thr = find_thread_ptid (target, ptid);
00431a78 2811 return get_remote_thread_info (thr);
dc146f7c
VP
2812}
2813
74531fed
PA
2814/* Call this function as a result of
2815 1) A halt indication (T packet) containing a thread id
2816 2) A direct query of currthread
0df8b418 2817 3) Successful execution of set thread */
74531fed
PA
2818
2819static void
47f8a51d 2820record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2821{
47f8a51d 2822 rs->general_thread = currthread;
74531fed
PA
2823}
2824
89be2091
DJ
2825/* If 'QPassSignals' is supported, tell the remote stub what signals
2826 it can simply pass through to the inferior without reporting. */
2827
f6ac5f3d 2828void
adc6a863 2829remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
89be2091 2830{
ff52c073 2831 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2832 {
2833 char *pass_packet, *p;
adc6a863 2834 int count = 0;
747dc59d 2835 struct remote_state *rs = get_remote_state ();
89be2091 2836
adc6a863
PA
2837 gdb_assert (pass_signals.size () < 256);
2838 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2839 {
2455069d 2840 if (pass_signals[i])
89be2091
DJ
2841 count++;
2842 }
224c3ddb 2843 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2844 strcpy (pass_packet, "QPassSignals:");
2845 p = pass_packet + strlen (pass_packet);
adc6a863 2846 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2847 {
2455069d 2848 if (pass_signals[i])
89be2091
DJ
2849 {
2850 if (i >= 16)
2851 *p++ = tohex (i >> 4);
2852 *p++ = tohex (i & 15);
2853 if (count)
2854 *p++ = ';';
2855 else
2856 break;
2857 count--;
2858 }
2859 }
2860 *p = 0;
747dc59d 2861 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2862 {
89be2091 2863 putpkt (pass_packet);
8d64371b 2864 getpkt (&rs->buf, 0);
ff52c073 2865 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
84d53fa9 2866 xfree (rs->last_pass_packet);
747dc59d 2867 rs->last_pass_packet = pass_packet;
89be2091
DJ
2868 }
2869 else
2870 xfree (pass_packet);
2871 }
2872}
2873
82075af2
JS
2874/* If 'QCatchSyscalls' is supported, tell the remote stub
2875 to report syscalls to GDB. */
2876
f6ac5f3d
PA
2877int
2878remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2879 gdb::array_view<const int> syscall_counts)
82075af2 2880{
b80406ac 2881 const char *catch_packet;
82075af2
JS
2882 enum packet_result result;
2883 int n_sysno = 0;
2884
ff52c073 2885 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
82075af2
JS
2886 {
2887 /* Not supported. */
2888 return 1;
2889 }
2890
649a140c 2891 if (needed && any_count == 0)
82075af2 2892 {
649a140c
PA
2893 /* Count how many syscalls are to be caught. */
2894 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2895 {
649a140c 2896 if (syscall_counts[i] != 0)
82075af2
JS
2897 n_sysno++;
2898 }
2899 }
2900
2189c312
SM
2901 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2902 pid, needed, any_count, n_sysno);
82075af2 2903
1b81856f 2904 std::string built_packet;
82075af2
JS
2905 if (needed)
2906 {
2907 /* Prepare a packet with the sysno list, assuming max 8+1
2908 characters for a sysno. If the resulting packet size is too
2909 big, fallback on the non-selective packet. */
2910 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2911 built_packet.reserve (maxpktsz);
2912 built_packet = "QCatchSyscalls:1";
649a140c 2913 if (any_count == 0)
82075af2 2914 {
649a140c
PA
2915 /* Add in each syscall to be caught. */
2916 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2917 {
649a140c
PA
2918 if (syscall_counts[i] != 0)
2919 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2920 }
2921 }
1b81856f 2922 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2923 {
2924 /* catch_packet too big. Fallback to less efficient
2925 non selective mode, with GDB doing the filtering. */
b80406ac 2926 catch_packet = "QCatchSyscalls:1";
82075af2 2927 }
b80406ac 2928 else
1b81856f 2929 catch_packet = built_packet.c_str ();
82075af2
JS
2930 }
2931 else
b80406ac 2932 catch_packet = "QCatchSyscalls:0";
82075af2 2933
b80406ac 2934 struct remote_state *rs = get_remote_state ();
82075af2 2935
b80406ac 2936 putpkt (catch_packet);
8d64371b 2937 getpkt (&rs->buf, 0);
ff52c073 2938 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
b80406ac
TT
2939 if (result == PACKET_OK)
2940 return 0;
2941 else
2942 return -1;
82075af2
JS
2943}
2944
9b224c5e
PA
2945/* If 'QProgramSignals' is supported, tell the remote stub what
2946 signals it should pass through to the inferior when detaching. */
2947
f6ac5f3d 2948void
adc6a863 2949remote_target::program_signals (gdb::array_view<const unsigned char> signals)
9b224c5e 2950{
ff52c073 2951 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2952 {
2953 char *packet, *p;
adc6a863 2954 int count = 0;
5e4a05c4 2955 struct remote_state *rs = get_remote_state ();
9b224c5e 2956
adc6a863
PA
2957 gdb_assert (signals.size () < 256);
2958 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
2959 {
2960 if (signals[i])
2961 count++;
2962 }
224c3ddb 2963 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2964 strcpy (packet, "QProgramSignals:");
2965 p = packet + strlen (packet);
adc6a863 2966 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
2967 {
2968 if (signal_pass_state (i))
2969 {
2970 if (i >= 16)
2971 *p++ = tohex (i >> 4);
2972 *p++ = tohex (i & 15);
2973 if (count)
2974 *p++ = ';';
2975 else
2976 break;
2977 count--;
2978 }
2979 }
2980 *p = 0;
5e4a05c4
TT
2981 if (!rs->last_program_signals_packet
2982 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2983 {
9b224c5e 2984 putpkt (packet);
8d64371b 2985 getpkt (&rs->buf, 0);
ff52c073 2986 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
5e4a05c4
TT
2987 xfree (rs->last_program_signals_packet);
2988 rs->last_program_signals_packet = packet;
9b224c5e
PA
2989 }
2990 else
2991 xfree (packet);
2992 }
2993}
2994
79d7f229
PA
2995/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2996 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2997 thread. If GEN is set, set the general thread, if not, then set
2998 the step/continue thread. */
6b8edb51
PA
2999void
3000remote_target::set_thread (ptid_t ptid, int gen)
c906108c 3001{
d01949b6 3002 struct remote_state *rs = get_remote_state ();
47f8a51d 3003 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
8d64371b
TT
3004 char *buf = rs->buf.data ();
3005 char *endbuf = buf + get_remote_packet_size ();
c906108c 3006
d7e15655 3007 if (state == ptid)
c906108c
SS
3008 return;
3009
79d7f229
PA
3010 *buf++ = 'H';
3011 *buf++ = gen ? 'g' : 'c';
d7e15655 3012 if (ptid == magic_null_ptid)
79d7f229 3013 xsnprintf (buf, endbuf - buf, "0");
d7e15655 3014 else if (ptid == any_thread_ptid)
79d7f229 3015 xsnprintf (buf, endbuf - buf, "0");
d7e15655 3016 else if (ptid == minus_one_ptid)
79d7f229
PA
3017 xsnprintf (buf, endbuf - buf, "-1");
3018 else
82f73884 3019 write_ptid (buf, endbuf, ptid);
79d7f229 3020 putpkt (rs->buf);
8d64371b 3021 getpkt (&rs->buf, 0);
c906108c 3022 if (gen)
47f8a51d 3023 rs->general_thread = ptid;
c906108c 3024 else
47f8a51d 3025 rs->continue_thread = ptid;
c906108c 3026}
79d7f229 3027
6b8edb51
PA
3028void
3029remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
3030{
3031 set_thread (ptid, 1);
3032}
3033
6b8edb51
PA
3034void
3035remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
3036{
3037 set_thread (ptid, 0);
3038}
3039
3c9c4b83
PA
3040/* Change the remote current process. Which thread within the process
3041 ends up selected isn't important, as long as it is the same process
3042 as what INFERIOR_PTID points to.
3043
3044 This comes from that fact that there is no explicit notion of
3045 "selected process" in the protocol. The selected process for
3046 general operations is the process the selected general thread
3047 belongs to. */
3048
6b8edb51
PA
3049void
3050remote_target::set_general_process ()
3c9c4b83 3051{
3c9c4b83 3052 /* If the remote can't handle multiple processes, don't bother. */
ff52c073 3053 if (!m_features.remote_multi_process_p ())
3c9c4b83
PA
3054 return;
3055
ff52c073
CS
3056 remote_state *rs = get_remote_state ();
3057
3c9c4b83
PA
3058 /* We only need to change the remote current thread if it's pointing
3059 at some other process. */
e99b03dc 3060 if (rs->general_thread.pid () != inferior_ptid.pid ())
3c9c4b83
PA
3061 set_general_thread (inferior_ptid);
3062}
3063
c906108c 3064\f
7d1a114c
PA
3065/* Return nonzero if this is the main thread that we made up ourselves
3066 to model non-threaded targets as single-threaded. */
c906108c
SS
3067
3068static int
f6ac5f3d 3069remote_thread_always_alive (ptid_t ptid)
c906108c 3070{
d7e15655 3071 if (ptid == magic_null_ptid)
c0a2216e
PA
3072 /* The main thread is always alive. */
3073 return 1;
3074
e38504b3 3075 if (ptid.pid () != 0 && ptid.lwp () == 0)
c0a2216e
PA
3076 /* The main thread is always alive. This can happen after a
3077 vAttach, if the remote side doesn't support
3078 multi-threading. */
3079 return 1;
3080
7d1a114c
PA
3081 return 0;
3082}
3083
3084/* Return nonzero if the thread PTID is still alive on the remote
3085 system. */
3086
57810aa7 3087bool
f6ac5f3d 3088remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
3089{
3090 struct remote_state *rs = get_remote_state ();
3091 char *p, *endp;
3092
3093 /* Check if this is a thread that we made up ourselves to model
3094 non-threaded targets as single-threaded. */
f6ac5f3d 3095 if (remote_thread_always_alive (ptid))
7d1a114c
PA
3096 return 1;
3097
8d64371b
TT
3098 p = rs->buf.data ();
3099 endp = p + get_remote_packet_size ();
82f73884
PA
3100
3101 *p++ = 'T';
3102 write_ptid (p, endp, ptid);
3103
2e9f7625 3104 putpkt (rs->buf);
8d64371b 3105 getpkt (&rs->buf, 0);
2e9f7625 3106 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
3107}
3108
79efa585
SM
3109/* Return a pointer to a thread name if we know it and NULL otherwise.
3110 The thread_info object owns the memory for the name. */
3111
f6ac5f3d
PA
3112const char *
3113remote_target::thread_name (struct thread_info *info)
79efa585
SM
3114{
3115 if (info->priv != NULL)
a9334058
SM
3116 {
3117 const std::string &name = get_remote_thread_info (info)->name;
3118 return !name.empty () ? name.c_str () : NULL;
3119 }
79efa585
SM
3120
3121 return NULL;
3122}
3123
c906108c
SS
3124/* About these extended threadlist and threadinfo packets. They are
3125 variable length packets but, the fields within them are often fixed
30baf67b 3126 length. They are redundant enough to send over UDP as is the
c906108c
SS
3127 remote protocol in general. There is a matching unit test module
3128 in libstub. */
3129
23860348 3130/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 3131 libstub protocol encoding, and remote.c. It is not particularly
23860348 3132 changable. */
cce74817
JM
3133
3134/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 3135 Plan to fix this. */
cce74817 3136
23860348 3137typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 3138
9d1f7ab2 3139/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 3140 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
3141
3142struct gdb_ext_thread_info
c5aa993b 3143 {
23860348 3144 threadref threadid; /* External form of thread reference. */
2bc416ba 3145 int active; /* Has state interesting to GDB?
23860348 3146 regs, stack. */
2bc416ba 3147 char display[256]; /* Brief state display, name,
cedea757 3148 blocked/suspended. */
23860348 3149 char shortname[32]; /* To be used to name threads. */
2bc416ba 3150 char more_display[256]; /* Long info, statistics, queue depth,
23860348 3151 whatever. */
c5aa993b 3152 };
cce74817
JM
3153
3154/* The volume of remote transfers can be limited by submitting
3155 a mask containing bits specifying the desired information.
3156 Use a union of these values as the 'selection' parameter to
0df8b418 3157 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
3158
3159#define TAG_THREADID 1
3160#define TAG_EXISTS 2
3161#define TAG_DISPLAY 4
3162#define TAG_THREADNAME 8
c5aa993b 3163#define TAG_MOREDISPLAY 16
cce74817 3164
23860348 3165#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 3166
cecb1912 3167static const char *unpack_nibble (const char *buf, int *val);
cce74817 3168
cecb1912 3169static const char *unpack_byte (const char *buf, int *value);
cce74817 3170
a14ed312 3171static char *pack_int (char *buf, int value);
cce74817 3172
cecb1912 3173static const char *unpack_int (const char *buf, int *value);
cce74817 3174
cecb1912 3175static const char *unpack_string (const char *src, char *dest, int length);
cce74817 3176
23860348 3177static char *pack_threadid (char *pkt, threadref *id);
cce74817 3178
cecb1912 3179static const char *unpack_threadid (const char *inbuf, threadref *id);
cce74817 3180
23860348 3181void int_to_threadref (threadref *id, int value);
cce74817 3182
23860348 3183static int threadref_to_int (threadref *ref);
cce74817 3184
23860348 3185static void copy_threadref (threadref *dest, threadref *src);
cce74817 3186
23860348 3187static int threadmatch (threadref *dest, threadref *src);
cce74817 3188
2bc416ba 3189static char *pack_threadinfo_request (char *pkt, int mode,
23860348 3190 threadref *id);
cce74817 3191
a14ed312
KB
3192static char *pack_threadlist_request (char *pkt, int startflag,
3193 int threadcount,
23860348 3194 threadref *nextthread);
cce74817 3195
23860348 3196static int remote_newthread_step (threadref *ref, void *context);
cce74817 3197
82f73884
PA
3198
3199/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3200 buffer we're allowed to write to. Returns
3201 BUF+CHARACTERS_WRITTEN. */
3202
6b8edb51
PA
3203char *
3204remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
3205{
3206 int pid, tid;
82f73884 3207
ff52c073 3208 if (m_features.remote_multi_process_p ())
82f73884 3209 {
e99b03dc 3210 pid = ptid.pid ();
82f73884
PA
3211 if (pid < 0)
3212 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3213 else
3214 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3215 }
e38504b3 3216 tid = ptid.lwp ();
82f73884
PA
3217 if (tid < 0)
3218 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3219 else
3220 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3221
3222 return buf;
3223}
3224
256642e8
PA
3225/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3226 last parsed char. Returns null_ptid if no thread id is found, and
3227 throws an error if the thread id has an invalid format. */
82f73884
PA
3228
3229static ptid_t
256642e8 3230read_ptid (const char *buf, const char **obuf)
82f73884 3231{
256642e8
PA
3232 const char *p = buf;
3233 const char *pp;
82f73884 3234 ULONGEST pid = 0, tid = 0;
82f73884
PA
3235
3236 if (*p == 'p')
3237 {
3238 /* Multi-process ptid. */
3239 pp = unpack_varlen_hex (p + 1, &pid);
3240 if (*pp != '.')
b37520b6 3241 error (_("invalid remote ptid: %s"), p);
82f73884
PA
3242
3243 p = pp;
3244 pp = unpack_varlen_hex (p + 1, &tid);
3245 if (obuf)
3246 *obuf = pp;
184ea2f7 3247 return ptid_t (pid, tid);
82f73884
PA
3248 }
3249
3250 /* No multi-process. Just a tid. */
3251 pp = unpack_varlen_hex (p, &tid);
3252
c9f35b34
KB
3253 /* Return null_ptid when no thread id is found. */
3254 if (p == pp)
3255 {
3256 if (obuf)
3257 *obuf = pp;
3258 return null_ptid;
3259 }
3260
2f761de2
TBA
3261 /* Since the stub is not sending a process id, default to what's
3262 current_inferior, unless it doesn't have a PID yet. If so,
ca19bf23
PA
3263 then since there's no way to know the pid of the reported
3264 threads, use the magic number. */
2f761de2
TBA
3265 inferior *inf = current_inferior ();
3266 if (inf->pid == 0)
e99b03dc 3267 pid = magic_null_ptid.pid ();
ca19bf23 3268 else
2f761de2 3269 pid = inf->pid;
82f73884
PA
3270
3271 if (obuf)
3272 *obuf = pp;
184ea2f7 3273 return ptid_t (pid, tid);
82f73884
PA
3274}
3275
c906108c 3276static int
fba45db2 3277stubhex (int ch)
c906108c
SS
3278{
3279 if (ch >= 'a' && ch <= 'f')
3280 return ch - 'a' + 10;
3281 if (ch >= '0' && ch <= '9')
3282 return ch - '0';
3283 if (ch >= 'A' && ch <= 'F')
3284 return ch - 'A' + 10;
3285 return -1;
3286}
3287
3288static int
cecb1912 3289stub_unpack_int (const char *buff, int fieldlength)
c906108c
SS
3290{
3291 int nibble;
3292 int retval = 0;
3293
3294 while (fieldlength)
3295 {
3296 nibble = stubhex (*buff++);
3297 retval |= nibble;
3298 fieldlength--;
3299 if (fieldlength)
3300 retval = retval << 4;
3301 }
3302 return retval;
3303}
3304
cecb1912
SM
3305static const char *
3306unpack_nibble (const char *buf, int *val)
c906108c 3307{
b7589f7d 3308 *val = fromhex (*buf++);
c906108c
SS
3309 return buf;
3310}
3311
cecb1912
SM
3312static const char *
3313unpack_byte (const char *buf, int *value)
c906108c
SS
3314{
3315 *value = stub_unpack_int (buf, 2);
3316 return buf + 2;
3317}
3318
3319static char *
fba45db2 3320pack_int (char *buf, int value)
c906108c
SS
3321{
3322 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3323 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3324 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3325 buf = pack_hex_byte (buf, (value & 0xff));
3326 return buf;
3327}
3328
cecb1912
SM
3329static const char *
3330unpack_int (const char *buf, int *value)
c906108c
SS
3331{
3332 *value = stub_unpack_int (buf, 8);
3333 return buf + 8;
3334}
3335
23860348 3336#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3337static char *pack_string (char *pkt, char *string);
c906108c
SS
3338
3339static char *
fba45db2 3340pack_string (char *pkt, char *string)
c906108c
SS
3341{
3342 char ch;
3343 int len;
3344
3345 len = strlen (string);
3346 if (len > 200)
23860348 3347 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3348 pkt = pack_hex_byte (pkt, len);
3349 while (len-- > 0)
3350 {
3351 ch = *string++;
3352 if ((ch == '\0') || (ch == '#'))
23860348 3353 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3354 *pkt++ = ch;
3355 }
3356 return pkt;
3357}
3358#endif /* 0 (unused) */
3359
cecb1912
SM
3360static const char *
3361unpack_string (const char *src, char *dest, int length)
c906108c
SS
3362{
3363 while (length--)
3364 *dest++ = *src++;
3365 *dest = '\0';
3366 return src;
3367}
3368
3369static char *
fba45db2 3370pack_threadid (char *pkt, threadref *id)
c906108c
SS
3371{
3372 char *limit;
3373 unsigned char *altid;
3374
3375 altid = (unsigned char *) id;
3376 limit = pkt + BUF_THREAD_ID_SIZE;
3377 while (pkt < limit)
3378 pkt = pack_hex_byte (pkt, *altid++);
3379 return pkt;
3380}
3381
3382
cecb1912
SM
3383static const char *
3384unpack_threadid (const char *inbuf, threadref *id)
c906108c
SS
3385{
3386 char *altref;
cecb1912 3387 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
c906108c
SS
3388 int x, y;
3389
3390 altref = (char *) id;
3391
3392 while (inbuf < limit)
3393 {
3394 x = stubhex (*inbuf++);
3395 y = stubhex (*inbuf++);
3396 *altref++ = (x << 4) | y;
3397 }
3398 return inbuf;
3399}
3400
3401/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3402 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3403 to use 64bit thread references internally. This is an adapter
3404 function. */
3405
3406void
fba45db2 3407int_to_threadref (threadref *id, int value)
c906108c
SS
3408{
3409 unsigned char *scan;
3410
3411 scan = (unsigned char *) id;
3412 {
3413 int i = 4;
3414 while (i--)
3415 *scan++ = 0;
3416 }
3417 *scan++ = (value >> 24) & 0xff;
3418 *scan++ = (value >> 16) & 0xff;
3419 *scan++ = (value >> 8) & 0xff;
3420 *scan++ = (value & 0xff);
3421}
3422
3423static int
fba45db2 3424threadref_to_int (threadref *ref)
c906108c
SS
3425{
3426 int i, value = 0;
3427 unsigned char *scan;
3428
cfd77fa1 3429 scan = *ref;
c906108c
SS
3430 scan += 4;
3431 i = 4;
3432 while (i-- > 0)
3433 value = (value << 8) | ((*scan++) & 0xff);
3434 return value;
3435}
3436
3437static void
fba45db2 3438copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3439{
3440 int i;
3441 unsigned char *csrc, *cdest;
3442
3443 csrc = (unsigned char *) src;
3444 cdest = (unsigned char *) dest;
3445 i = 8;
3446 while (i--)
3447 *cdest++ = *csrc++;
3448}
3449
3450static int
fba45db2 3451threadmatch (threadref *dest, threadref *src)
c906108c 3452{
23860348 3453 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3454#if 0
3455 unsigned char *srcp, *destp;
3456 int i, result;
3457 srcp = (char *) src;
3458 destp = (char *) dest;
3459
3460 result = 1;
3461 while (i-- > 0)
3462 result &= (*srcp++ == *destp++) ? 1 : 0;
3463 return result;
3464#endif
3465 return 1;
3466}
3467
3468/*
c5aa993b
JM
3469 threadid:1, # always request threadid
3470 context_exists:2,
3471 display:4,
3472 unique_name:8,
3473 more_display:16
3474 */
c906108c
SS
3475
3476/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3477
3478static char *
fba45db2 3479pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3480{
23860348
MS
3481 *pkt++ = 'q'; /* Info Query */
3482 *pkt++ = 'P'; /* process or thread info */
3483 pkt = pack_int (pkt, mode); /* mode */
c906108c 3484 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3485 *pkt = '\0'; /* terminate */
c906108c
SS
3486 return pkt;
3487}
3488
23860348 3489/* These values tag the fields in a thread info response packet. */
c906108c 3490/* Tagging the fields allows us to request specific fields and to
23860348 3491 add more fields as time goes by. */
c906108c 3492
23860348 3493#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3494#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3495 fetch registers and its stack? */
c5aa993b 3496#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3497#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3498#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3499 the process. */
c906108c 3500
6b8edb51 3501int
cecb1912 3502remote_target::remote_unpack_thread_info_response (const char *pkt,
6b8edb51
PA
3503 threadref *expectedref,
3504 gdb_ext_thread_info *info)
c906108c 3505{
d01949b6 3506 struct remote_state *rs = get_remote_state ();
c906108c 3507 int mask, length;
cfd77fa1 3508 int tag;
c906108c 3509 threadref ref;
cecb1912 3510 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
c906108c
SS
3511 int retval = 1;
3512
23860348 3513 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3514 info->active = 0;
3515 info->display[0] = '\0';
3516 info->shortname[0] = '\0';
3517 info->more_display[0] = '\0';
3518
23860348
MS
3519 /* Assume the characters indicating the packet type have been
3520 stripped. */
c906108c
SS
3521 pkt = unpack_int (pkt, &mask); /* arg mask */
3522 pkt = unpack_threadid (pkt, &ref);
3523
3524 if (mask == 0)
8a3fe4f8 3525 warning (_("Incomplete response to threadinfo request."));
c906108c 3526 if (!threadmatch (&ref, expectedref))
23860348 3527 { /* This is an answer to a different request. */
8a3fe4f8 3528 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3529 return 0;
3530 }
3531 copy_threadref (&info->threadid, &ref);
3532
405feb71 3533 /* Loop on tagged fields , try to bail if something goes wrong. */
c906108c 3534
23860348
MS
3535 /* Packets are terminated with nulls. */
3536 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3537 {
3538 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3539 pkt = unpack_byte (pkt, &length); /* length */
3540 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3541 {
8a3fe4f8 3542 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3543 retval = 0;
3544 break;
3545 }
3546 if (tag == TAG_THREADID)
3547 {
3548 if (length != 16)
3549 {
8a3fe4f8 3550 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3551 retval = 0;
3552 break;
3553 }
3554 pkt = unpack_threadid (pkt, &ref);
3555 mask = mask & ~TAG_THREADID;
3556 continue;
3557 }
3558 if (tag == TAG_EXISTS)
3559 {
3560 info->active = stub_unpack_int (pkt, length);
3561 pkt += length;
3562 mask = mask & ~(TAG_EXISTS);
3563 if (length > 8)
3564 {
8a3fe4f8 3565 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3566 retval = 0;
3567 break;
3568 }
3569 continue;
3570 }
3571 if (tag == TAG_THREADNAME)
3572 {
3573 pkt = unpack_string (pkt, &info->shortname[0], length);
3574 mask = mask & ~TAG_THREADNAME;
3575 continue;
3576 }
3577 if (tag == TAG_DISPLAY)
3578 {
3579 pkt = unpack_string (pkt, &info->display[0], length);
3580 mask = mask & ~TAG_DISPLAY;
3581 continue;
3582 }
3583 if (tag == TAG_MOREDISPLAY)
3584 {
3585 pkt = unpack_string (pkt, &info->more_display[0], length);
3586 mask = mask & ~TAG_MOREDISPLAY;
3587 continue;
3588 }
8a3fe4f8 3589 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3590 break; /* Not a tag we know about. */
c906108c
SS
3591 }
3592 return retval;
3593}
3594
6b8edb51
PA
3595int
3596remote_target::remote_get_threadinfo (threadref *threadid,
3597 int fieldset,
3598 gdb_ext_thread_info *info)
c906108c 3599{
d01949b6 3600 struct remote_state *rs = get_remote_state ();
c906108c 3601 int result;
c906108c 3602
8d64371b 3603 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
2e9f7625 3604 putpkt (rs->buf);
8d64371b 3605 getpkt (&rs->buf, 0);
3084dd77
PA
3606
3607 if (rs->buf[0] == '\0')
3608 return 0;
3609
8d64371b 3610 result = remote_unpack_thread_info_response (&rs->buf[2],
23860348 3611 threadid, info);
c906108c
SS
3612 return result;
3613}
3614
c906108c
SS
3615/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3616
3617static char *
fba45db2
KB
3618pack_threadlist_request (char *pkt, int startflag, int threadcount,
3619 threadref *nextthread)
c906108c
SS
3620{
3621 *pkt++ = 'q'; /* info query packet */
3622 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3623 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3624 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3625 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3626 *pkt = '\0';
3627 return pkt;
3628}
3629
3630/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3631
6b8edb51 3632int
cecb1912 3633remote_target::parse_threadlist_response (const char *pkt, int result_limit,
6b8edb51
PA
3634 threadref *original_echo,
3635 threadref *resultlist,
3636 int *doneflag)
c906108c 3637{
d01949b6 3638 struct remote_state *rs = get_remote_state ();
c906108c
SS
3639 int count, resultcount, done;
3640
3641 resultcount = 0;
3642 /* Assume the 'q' and 'M chars have been stripped. */
cecb1912 3643 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
23860348 3644 /* done parse past here */
c906108c
SS
3645 pkt = unpack_byte (pkt, &count); /* count field */
3646 pkt = unpack_nibble (pkt, &done);
3647 /* The first threadid is the argument threadid. */
3648 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3649 while ((count-- > 0) && (pkt < limit))
3650 {
3651 pkt = unpack_threadid (pkt, resultlist++);
3652 if (resultcount++ >= result_limit)
3653 break;
3654 }
3655 if (doneflag)
3656 *doneflag = done;
3657 return resultcount;
3658}
3659
6dc54d91
PA
3660/* Fetch the next batch of threads from the remote. Returns -1 if the
3661 qL packet is not supported, 0 on error and 1 on success. */
3662
6b8edb51
PA
3663int
3664remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3665 int result_limit, int *done, int *result_count,
3666 threadref *threadlist)
c906108c 3667{
d01949b6 3668 struct remote_state *rs = get_remote_state ();
c906108c
SS
3669 int result = 1;
3670
405feb71 3671 /* Truncate result limit to be smaller than the packet size. */
3e43a32a
MS
3672 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3673 >= get_remote_packet_size ())
ea9c271d 3674 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3675
8d64371b
TT
3676 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3677 nextthread);
6d820c5c 3678 putpkt (rs->buf);
8d64371b
TT
3679 getpkt (&rs->buf, 0);
3680 if (rs->buf[0] == '\0')
6dc54d91
PA
3681 {
3682 /* Packet not supported. */
3683 return -1;
3684 }
3685
3686 *result_count =
8d64371b 3687 parse_threadlist_response (&rs->buf[2], result_limit,
6dc54d91 3688 &rs->echo_nextthread, threadlist, done);
c906108c 3689
0d031856 3690 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3691 {
23860348 3692 /* FIXME: This is a good reason to drop the packet. */
405feb71
TV
3693 /* Possibly, there is a duplicate response. */
3694 /* Possibilities :
dda83cd7
SM
3695 retransmit immediatly - race conditions
3696 retransmit after timeout - yes
3697 exit
3698 wait for packet, then exit
c906108c 3699 */
8a3fe4f8 3700 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3701 return 0; /* I choose simply exiting. */
c906108c
SS
3702 }
3703 if (*result_count <= 0)
3704 {
3705 if (*done != 1)
3706 {
8a3fe4f8 3707 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3708 result = 0;
3709 }
3710 return result; /* break; */
3711 }
3712 if (*result_count > result_limit)
3713 {
3714 *result_count = 0;
8a3fe4f8 3715 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3716 return 0;
3717 }
3718 return result;
3719}
3720
6dc54d91
PA
3721/* Fetch the list of remote threads, with the qL packet, and call
3722 STEPFUNCTION for each thread found. Stops iterating and returns 1
3723 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3724 STEPFUNCTION returns false. If the packet is not supported,
3725 returns -1. */
c906108c 3726
6b8edb51
PA
3727int
3728remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3729 void *context, int looplimit)
c906108c 3730{
0d031856 3731 struct remote_state *rs = get_remote_state ();
c906108c
SS
3732 int done, i, result_count;
3733 int startflag = 1;
3734 int result = 1;
3735 int loopcount = 0;
c906108c
SS
3736
3737 done = 0;
3738 while (!done)
3739 {
3740 if (loopcount++ > looplimit)
3741 {
3742 result = 0;
8a3fe4f8 3743 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3744 break;
3745 }
6dc54d91
PA
3746 result = remote_get_threadlist (startflag, &rs->nextthread,
3747 MAXTHREADLISTRESULTS,
3748 &done, &result_count,
3749 rs->resultthreadlist);
3750 if (result <= 0)
3751 break;
23860348 3752 /* Clear for later iterations. */
c906108c
SS
3753 startflag = 0;
3754 /* Setup to resume next batch of thread references, set nextthread. */
3755 if (result_count >= 1)
0d031856
TT
3756 copy_threadref (&rs->nextthread,
3757 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3758 i = 0;
3759 while (result_count--)
6dc54d91
PA
3760 {
3761 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3762 {
3763 result = 0;
3764 break;
3765 }
3766 }
c906108c
SS
3767 }
3768 return result;
3769}
3770
6dc54d91
PA
3771/* A thread found on the remote target. */
3772
21fe1c75 3773struct thread_item
6dc54d91 3774{
21fe1c75
SM
3775 explicit thread_item (ptid_t ptid_)
3776 : ptid (ptid_)
3777 {}
3778
3779 thread_item (thread_item &&other) = default;
3780 thread_item &operator= (thread_item &&other) = default;
3781
3782 DISABLE_COPY_AND_ASSIGN (thread_item);
3783
6dc54d91
PA
3784 /* The thread's PTID. */
3785 ptid_t ptid;
3786
21fe1c75
SM
3787 /* The thread's extra info. */
3788 std::string extra;
6dc54d91 3789
21fe1c75
SM
3790 /* The thread's name. */
3791 std::string name;
79efa585 3792
6dc54d91 3793 /* The core the thread was running on. -1 if not known. */
21fe1c75 3794 int core = -1;
f6327dcb
KB
3795
3796 /* The thread handle associated with the thread. */
21fe1c75 3797 gdb::byte_vector thread_handle;
21fe1c75 3798};
6dc54d91
PA
3799
3800/* Context passed around to the various methods listing remote
3801 threads. As new threads are found, they're added to the ITEMS
3802 vector. */
3803
3804struct threads_listing_context
3805{
21fe1c75
SM
3806 /* Return true if this object contains an entry for a thread with ptid
3807 PTID. */
6dc54d91 3808
21fe1c75
SM
3809 bool contains_thread (ptid_t ptid) const
3810 {
3811 auto match_ptid = [&] (const thread_item &item)
3812 {
3813 return item.ptid == ptid;
3814 };
80134cf5 3815
21fe1c75
SM
3816 auto it = std::find_if (this->items.begin (),
3817 this->items.end (),
3818 match_ptid);
80134cf5 3819
21fe1c75
SM
3820 return it != this->items.end ();
3821 }
80134cf5 3822
21fe1c75 3823 /* Remove the thread with ptid PTID. */
80134cf5 3824
21fe1c75
SM
3825 void remove_thread (ptid_t ptid)
3826 {
3827 auto match_ptid = [&] (const thread_item &item)
3828 {
dda83cd7 3829 return item.ptid == ptid;
21fe1c75 3830 };
cbb8991c 3831
21fe1c75
SM
3832 auto it = std::remove_if (this->items.begin (),
3833 this->items.end (),
3834 match_ptid);
cbb8991c 3835
21fe1c75
SM
3836 if (it != this->items.end ())
3837 this->items.erase (it);
3838 }
3839
3840 /* The threads found on the remote target. */
3841 std::vector<thread_item> items;
3842};
cbb8991c 3843
c906108c 3844static int
6dc54d91 3845remote_newthread_step (threadref *ref, void *data)
c906108c 3846{
19ba03f4
SM
3847 struct threads_listing_context *context
3848 = (struct threads_listing_context *) data;
21fe1c75
SM
3849 int pid = inferior_ptid.pid ();
3850 int lwp = threadref_to_int (ref);
3851 ptid_t ptid (pid, lwp);
6dc54d91 3852
21fe1c75 3853 context->items.emplace_back (ptid);
6dc54d91 3854
c906108c
SS
3855 return 1; /* continue iterator */
3856}
3857
3858#define CRAZY_MAX_THREADS 1000
3859
6b8edb51
PA
3860ptid_t
3861remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3862{
d01949b6 3863 struct remote_state *rs = get_remote_state ();
c906108c
SS
3864
3865 putpkt ("qC");
8d64371b 3866 getpkt (&rs->buf, 0);
2e9f7625 3867 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3868 {
256642e8 3869 const char *obuf;
c9f35b34
KB
3870 ptid_t result;
3871
3872 result = read_ptid (&rs->buf[2], &obuf);
2189c312
SM
3873 if (*obuf != '\0')
3874 remote_debug_printf ("warning: garbage in qC reply");
c9f35b34
KB
3875
3876 return result;
3877 }
c906108c
SS
3878 else
3879 return oldpid;
3880}
3881
6dc54d91 3882/* List remote threads using the deprecated qL packet. */
cce74817 3883
6b8edb51
PA
3884int
3885remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3886{
6dc54d91
PA
3887 if (remote_threadlist_iterator (remote_newthread_step, context,
3888 CRAZY_MAX_THREADS) >= 0)
3889 return 1;
3890
3891 return 0;
c906108c
SS
3892}
3893
dc146f7c
VP
3894#if defined(HAVE_LIBEXPAT)
3895
dc146f7c
VP
3896static void
3897start_thread (struct gdb_xml_parser *parser,
3898 const struct gdb_xml_element *element,
4d0fdd9b
SM
3899 void *user_data,
3900 std::vector<gdb_xml_value> &attributes)
dc146f7c 3901{
19ba03f4
SM
3902 struct threads_listing_context *data
3903 = (struct threads_listing_context *) user_data;
3d2c1d41 3904 struct gdb_xml_value *attr;
dc146f7c 3905
4d0fdd9b 3906 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3907 ptid_t ptid = read_ptid (id, NULL);
3908
3909 data->items.emplace_back (ptid);
3910 thread_item &item = data->items.back ();
dc146f7c 3911
3d2c1d41
PA
3912 attr = xml_find_attribute (attributes, "core");
3913 if (attr != NULL)
4d0fdd9b 3914 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3915
79efa585 3916 attr = xml_find_attribute (attributes, "name");
21fe1c75 3917 if (attr != NULL)
4d0fdd9b 3918 item.name = (const char *) attr->value.get ();
79efa585 3919
f6327dcb
KB
3920 attr = xml_find_attribute (attributes, "handle");
3921 if (attr != NULL)
4d0fdd9b 3922 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3923}
3924
3925static void
3926end_thread (struct gdb_xml_parser *parser,
3927 const struct gdb_xml_element *element,
3928 void *user_data, const char *body_text)
3929{
19ba03f4
SM
3930 struct threads_listing_context *data
3931 = (struct threads_listing_context *) user_data;
dc146f7c 3932
21fe1c75
SM
3933 if (body_text != NULL && *body_text != '\0')
3934 data->items.back ().extra = body_text;
dc146f7c
VP
3935}
3936
3937const struct gdb_xml_attribute thread_attributes[] = {
3938 { "id", GDB_XML_AF_NONE, NULL, NULL },
3939 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3940 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3941 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3942 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3943};
3944
3945const struct gdb_xml_element thread_children[] = {
3946 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3947};
3948
3949const struct gdb_xml_element threads_children[] = {
3950 { "thread", thread_attributes, thread_children,
3951 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3952 start_thread, end_thread },
3953 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3954};
3955
3956const struct gdb_xml_element threads_elements[] = {
3957 { "threads", NULL, threads_children,
3958 GDB_XML_EF_NONE, NULL, NULL },
3959 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3960};
3961
3962#endif
3963
6dc54d91 3964/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3965
6b8edb51
PA
3966int
3967remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 3968{
dc146f7c 3969#if defined(HAVE_LIBEXPAT)
ff52c073 3970 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3971 {
9018be22 3972 gdb::optional<gdb::char_vector> xml
6b8edb51 3973 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3974
9018be22 3975 if (xml && (*xml)[0] != '\0')
dc146f7c 3976 {
6dc54d91 3977 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3978 threads_elements, xml->data (), context);
dc146f7c
VP
3979 }
3980
6dc54d91 3981 return 1;
dc146f7c
VP
3982 }
3983#endif
3984
6dc54d91
PA
3985 return 0;
3986}
3987
3988/* List remote threads using qfThreadInfo/qsThreadInfo. */
3989
6b8edb51
PA
3990int
3991remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
3992{
3993 struct remote_state *rs = get_remote_state ();
3994
b80fafe3 3995 if (rs->use_threadinfo_query)
9d1f7ab2 3996 {
256642e8 3997 const char *bufp;
6dc54d91 3998
9d1f7ab2 3999 putpkt ("qfThreadInfo");
8d64371b
TT
4000 getpkt (&rs->buf, 0);
4001 bufp = rs->buf.data ();
9d1f7ab2 4002 if (bufp[0] != '\0') /* q packet recognized */
802188a7 4003 {
9d1f7ab2
MS
4004 while (*bufp++ == 'm') /* reply contains one or more TID */
4005 {
4006 do
4007 {
21fe1c75
SM
4008 ptid_t ptid = read_ptid (bufp, &bufp);
4009 context->items.emplace_back (ptid);
9d1f7ab2
MS
4010 }
4011 while (*bufp++ == ','); /* comma-separated list */
4012 putpkt ("qsThreadInfo");
8d64371b
TT
4013 getpkt (&rs->buf, 0);
4014 bufp = rs->buf.data ();
9d1f7ab2 4015 }
6dc54d91
PA
4016 return 1;
4017 }
4018 else
4019 {
4020 /* Packet not recognized. */
4021 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
4022 }
4023 }
4024
6dc54d91
PA
4025 return 0;
4026}
4027
a05575d3
TBA
4028/* Return true if INF only has one non-exited thread. */
4029
4030static bool
4031has_single_non_exited_thread (inferior *inf)
4032{
4033 int count = 0;
4034 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4035 if (++count > 1)
4036 break;
4037 return count == 1;
4038}
4039
e8032dde 4040/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
4041 targets. */
4042
f6ac5f3d
PA
4043void
4044remote_target::update_thread_list ()
6dc54d91 4045{
6dc54d91 4046 struct threads_listing_context context;
ab970af1 4047 int got_list = 0;
e8032dde 4048
6dc54d91
PA
4049 /* We have a few different mechanisms to fetch the thread list. Try
4050 them all, starting with the most preferred one first, falling
4051 back to older methods. */
6b8edb51
PA
4052 if (remote_get_threads_with_qxfer (&context)
4053 || remote_get_threads_with_qthreadinfo (&context)
4054 || remote_get_threads_with_ql (&context))
6dc54d91 4055 {
ab970af1
PA
4056 got_list = 1;
4057
21fe1c75 4058 if (context.items.empty ()
f6ac5f3d 4059 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
4060 {
4061 /* Some targets don't really support threads, but still
4062 reply an (empty) thread list in response to the thread
4063 listing packets, instead of replying "packet not
4064 supported". Exit early so we don't delete the main
4065 thread. */
7d1a114c
PA
4066 return;
4067 }
4068
ab970af1
PA
4069 /* CONTEXT now holds the current thread list on the remote
4070 target end. Delete GDB-side threads no longer found on the
4071 target. */
08036331 4072 for (thread_info *tp : all_threads_safe ())
cbb8991c 4073 {
5b6d1e4f
PA
4074 if (tp->inf->process_target () != this)
4075 continue;
4076
21fe1c75 4077 if (!context.contains_thread (tp->ptid))
ab970af1 4078 {
a05575d3
TBA
4079 /* Do not remove the thread if it is the last thread in
4080 the inferior. This situation happens when we have a
4081 pending exit process status to process. Otherwise we
4082 may end up with a seemingly live inferior (i.e. pid
4083 != 0) that has no threads. */
4084 if (has_single_non_exited_thread (tp->inf))
4085 continue;
4086
ab970af1 4087 /* Not found. */
00431a78 4088 delete_thread (tp);
ab970af1 4089 }
cbb8991c
DB
4090 }
4091
4092 /* Remove any unreported fork child threads from CONTEXT so
4093 that we don't interfere with follow fork, which is where
4094 creation of such threads is handled. */
4095 remove_new_fork_children (&context);
74531fed 4096
ab970af1 4097 /* And now add threads we don't know about yet to our list. */
21fe1c75 4098 for (thread_item &item : context.items)
6dc54d91 4099 {
21fe1c75 4100 if (item.ptid != null_ptid)
6dc54d91 4101 {
6dc54d91 4102 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
4103 executing until proven otherwise with a stop reply.
4104 In all-stop, we can only get here if all threads are
6dc54d91 4105 stopped. */
8a82de58 4106 bool executing = target_is_non_stop_p ();
6dc54d91 4107
21fe1c75 4108 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 4109
5b6d1e4f 4110 thread_info *tp = find_thread_ptid (this, item.ptid);
00431a78 4111 remote_thread_info *info = get_remote_thread_info (tp);
21fe1c75 4112 info->core = item.core;
7aabaf9d
SM
4113 info->extra = std::move (item.extra);
4114 info->name = std::move (item.name);
4115 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
4116 }
4117 }
4118 }
4119
ab970af1
PA
4120 if (!got_list)
4121 {
4122 /* If no thread listing method is supported, then query whether
4123 each known thread is alive, one by one, with the T packet.
4124 If the target doesn't support threads at all, then this is a
4125 no-op. See remote_thread_alive. */
4126 prune_threads ();
4127 }
9d1f7ab2
MS
4128}
4129
802188a7 4130/*
9d1f7ab2
MS
4131 * Collect a descriptive string about the given thread.
4132 * The target may say anything it wants to about the thread
4133 * (typically info about its blocked / runnable state, name, etc.).
4134 * This string will appear in the info threads display.
802188a7 4135 *
9d1f7ab2
MS
4136 * Optional: targets are not required to implement this function.
4137 */
4138
f6ac5f3d
PA
4139const char *
4140remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 4141{
d01949b6 4142 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
4143 int set;
4144 threadref id;
4145 struct gdb_ext_thread_info threadinfo;
9d1f7ab2 4146
5d93a237 4147 if (rs->remote_desc == 0) /* paranoia */
f34652de 4148 internal_error (_("remote_threads_extra_info"));
9d1f7ab2 4149
d7e15655 4150 if (tp->ptid == magic_null_ptid
e38504b3 4151 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
60e569b9
PA
4152 /* This is the main thread which was added by GDB. The remote
4153 server doesn't know about it. */
4154 return NULL;
4155
c76a8ea3
PA
4156 std::string &extra = get_remote_thread_info (tp)->extra;
4157
4158 /* If already have cached info, use it. */
4159 if (!extra.empty ())
4160 return extra.c_str ();
4161
ff52c073 4162 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 4163 {
c76a8ea3
PA
4164 /* If we're using qXfer:threads:read, then the extra info is
4165 included in the XML. So if we didn't have anything cached,
4166 it's because there's really no extra info. */
4167 return NULL;
dc146f7c
VP
4168 }
4169
b80fafe3 4170 if (rs->use_threadextra_query)
9d1f7ab2 4171 {
8d64371b
TT
4172 char *b = rs->buf.data ();
4173 char *endb = b + get_remote_packet_size ();
82f73884
PA
4174
4175 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4176 b += strlen (b);
4177 write_ptid (b, endb, tp->ptid);
4178
2e9f7625 4179 putpkt (rs->buf);
8d64371b 4180 getpkt (&rs->buf, 0);
2e9f7625 4181 if (rs->buf[0] != 0)
9d1f7ab2 4182 {
8d64371b
TT
4183 extra.resize (strlen (rs->buf.data ()) / 2);
4184 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
c76a8ea3 4185 return extra.c_str ();
9d1f7ab2 4186 }
0f71a2f6 4187 }
9d1f7ab2
MS
4188
4189 /* If the above query fails, fall back to the old method. */
b80fafe3 4190 rs->use_threadextra_query = 0;
9d1f7ab2
MS
4191 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4192 | TAG_MOREDISPLAY | TAG_DISPLAY;
e38504b3 4193 int_to_threadref (&id, tp->ptid.lwp ());
9d1f7ab2
MS
4194 if (remote_get_threadinfo (&id, set, &threadinfo))
4195 if (threadinfo.active)
0f71a2f6 4196 {
9d1f7ab2 4197 if (*threadinfo.shortname)
c76a8ea3 4198 string_appendf (extra, " Name: %s", threadinfo.shortname);
9d1f7ab2 4199 if (*threadinfo.display)
c76a8ea3
PA
4200 {
4201 if (!extra.empty ())
4202 extra += ',';
4203 string_appendf (extra, " State: %s", threadinfo.display);
4204 }
9d1f7ab2 4205 if (*threadinfo.more_display)
c5aa993b 4206 {
c76a8ea3
PA
4207 if (!extra.empty ())
4208 extra += ',';
4209 string_appendf (extra, " Priority: %s", threadinfo.more_display);
c5aa993b 4210 }
c76a8ea3 4211 return extra.c_str ();
0f71a2f6 4212 }
9d1f7ab2 4213 return NULL;
0f71a2f6 4214}
c906108c 4215\f
c5aa993b 4216
f6ac5f3d
PA
4217bool
4218remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4219 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
4220{
4221 struct remote_state *rs = get_remote_state ();
8d64371b 4222 char *p = rs->buf.data ();
0fb4aa4b 4223
bba74b36 4224 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
4225 p += strlen (p);
4226 p += hexnumstr (p, addr);
4227 putpkt (rs->buf);
8d64371b
TT
4228 getpkt (&rs->buf, 0);
4229 p = rs->buf.data ();
0fb4aa4b
PA
4230
4231 if (*p == 'E')
4232 error (_("Remote failure reply: %s"), p);
4233
4234 if (*p++ == 'm')
4235 {
256642e8 4236 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 4237 return true;
0fb4aa4b
PA
4238 }
4239
5d9310c4 4240 return false;
0fb4aa4b
PA
4241}
4242
f6ac5f3d
PA
4243std::vector<static_tracepoint_marker>
4244remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
4245{
4246 struct remote_state *rs = get_remote_state ();
5d9310c4 4247 std::vector<static_tracepoint_marker> markers;
256642e8 4248 const char *p;
5d9310c4 4249 static_tracepoint_marker marker;
0fb4aa4b
PA
4250
4251 /* Ask for a first packet of static tracepoint marker
4252 definition. */
4253 putpkt ("qTfSTM");
8d64371b
TT
4254 getpkt (&rs->buf, 0);
4255 p = rs->buf.data ();
0fb4aa4b
PA
4256 if (*p == 'E')
4257 error (_("Remote failure reply: %s"), p);
4258
0fb4aa4b
PA
4259 while (*p++ == 'm')
4260 {
0fb4aa4b
PA
4261 do
4262 {
5d9310c4 4263 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 4264
5d9310c4
SM
4265 if (strid == NULL || marker.str_id == strid)
4266 markers.push_back (std::move (marker));
0fb4aa4b
PA
4267 }
4268 while (*p++ == ','); /* comma-separated list */
4269 /* Ask for another packet of static tracepoint definition. */
4270 putpkt ("qTsSTM");
8d64371b
TT
4271 getpkt (&rs->buf, 0);
4272 p = rs->buf.data ();
0fb4aa4b
PA
4273 }
4274
0fb4aa4b
PA
4275 return markers;
4276}
4277
4278\f
10760264
JB
4279/* Implement the to_get_ada_task_ptid function for the remote targets. */
4280
f6ac5f3d 4281ptid_t
c80e29db 4282remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
10760264 4283{
184ea2f7 4284 return ptid_t (inferior_ptid.pid (), lwp);
10760264
JB
4285}
4286\f
4287
24b06219 4288/* Restart the remote side; this is an extended protocol operation. */
c906108c 4289
6b8edb51
PA
4290void
4291remote_target::extended_remote_restart ()
c906108c 4292{
d01949b6 4293 struct remote_state *rs = get_remote_state ();
c906108c
SS
4294
4295 /* Send the restart command; for reasons I don't understand the
4296 remote side really expects a number after the "R". */
8d64371b 4297 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
6d820c5c 4298 putpkt (rs->buf);
c906108c 4299
ad9a8f3f 4300 remote_fileio_reset ();
c906108c
SS
4301}
4302\f
4303/* Clean up connection to a remote debugger. */
4304
f6ac5f3d
PA
4305void
4306remote_target::close ()
c906108c 4307{
048094ac 4308 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4309 terminal_ours ();
ce5ce7ed 4310
6b8edb51
PA
4311 trace_reset_local_state ();
4312
4313 delete this;
4314}
4315
4316remote_target::~remote_target ()
4317{
4318 struct remote_state *rs = get_remote_state ();
4319
4320 /* Check for NULL because we may get here with a partially
4321 constructed target/connection. */
4322 if (rs->remote_desc == nullptr)
4323 return;
4324
4325 serial_close (rs->remote_desc);
4326
4327 /* We are destroying the remote target, so we should discard
f48ff2a7 4328 everything of this target. */
6b8edb51 4329 discard_pending_stop_replies_in_queue ();
74531fed 4330
6b8edb51
PA
4331 if (rs->remote_async_inferior_event_token)
4332 delete_async_event_handler (&rs->remote_async_inferior_event_token);
722247f1 4333
97dfbadd 4334 delete rs->notif_state;
c906108c
SS
4335}
4336
23860348 4337/* Query the remote side for the text, data and bss offsets. */
c906108c 4338
6b8edb51
PA
4339void
4340remote_target::get_offsets ()
c906108c 4341{
d01949b6 4342 struct remote_state *rs = get_remote_state ();
2e9f7625 4343 char *buf;
085dd6e6 4344 char *ptr;
31d99776
DJ
4345 int lose, num_segments = 0, do_sections, do_segments;
4346 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
31d99776 4347
a42d7dd8 4348 if (current_program_space->symfile_object_file == NULL)
31d99776 4349 return;
c906108c
SS
4350
4351 putpkt ("qOffsets");
8d64371b
TT
4352 getpkt (&rs->buf, 0);
4353 buf = rs->buf.data ();
c906108c
SS
4354
4355 if (buf[0] == '\000')
4356 return; /* Return silently. Stub doesn't support
23860348 4357 this command. */
c906108c
SS
4358 if (buf[0] == 'E')
4359 {
8a3fe4f8 4360 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4361 return;
4362 }
4363
4364 /* Pick up each field in turn. This used to be done with scanf, but
4365 scanf will make trouble if CORE_ADDR size doesn't match
4366 conversion directives correctly. The following code will work
4367 with any size of CORE_ADDR. */
4368 text_addr = data_addr = bss_addr = 0;
4369 ptr = buf;
4370 lose = 0;
4371
61012eef 4372 if (startswith (ptr, "Text="))
c906108c
SS
4373 {
4374 ptr += 5;
4375 /* Don't use strtol, could lose on big values. */
4376 while (*ptr && *ptr != ';')
4377 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4378
61012eef 4379 if (startswith (ptr, ";Data="))
31d99776
DJ
4380 {
4381 ptr += 6;
4382 while (*ptr && *ptr != ';')
4383 data_addr = (data_addr << 4) + fromhex (*ptr++);
4384 }
4385 else
4386 lose = 1;
4387
61012eef 4388 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4389 {
4390 ptr += 5;
4391 while (*ptr && *ptr != ';')
4392 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4393
31d99776
DJ
4394 if (bss_addr != data_addr)
4395 warning (_("Target reported unsupported offsets: %s"), buf);
4396 }
4397 else
4398 lose = 1;
4399 }
61012eef 4400 else if (startswith (ptr, "TextSeg="))
c906108c 4401 {
31d99776
DJ
4402 ptr += 8;
4403 /* Don't use strtol, could lose on big values. */
c906108c 4404 while (*ptr && *ptr != ';')
31d99776
DJ
4405 text_addr = (text_addr << 4) + fromhex (*ptr++);
4406 num_segments = 1;
4407
61012eef 4408 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4409 {
4410 ptr += 9;
4411 while (*ptr && *ptr != ';')
4412 data_addr = (data_addr << 4) + fromhex (*ptr++);
4413 num_segments++;
4414 }
c906108c
SS
4415 }
4416 else
4417 lose = 1;
4418
4419 if (lose)
8a3fe4f8 4420 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4421 else if (*ptr != '\0')
4422 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4423
a42d7dd8
TT
4424 objfile *objf = current_program_space->symfile_object_file;
4425 section_offsets offs = objf->section_offsets;
c906108c 4426
98badbfd 4427 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
31d99776
DJ
4428 do_segments = (data != NULL);
4429 do_sections = num_segments == 0;
c906108c 4430
28c32713 4431 if (num_segments > 0)
31d99776 4432 {
31d99776
DJ
4433 segments[0] = text_addr;
4434 segments[1] = data_addr;
4435 }
28c32713
JB
4436 /* If we have two segments, we can still try to relocate everything
4437 by assuming that the .text and .data offsets apply to the whole
4438 text and data segments. Convert the offsets given in the packet
4439 to base addresses for symfile_map_offsets_to_segments. */
68b888ff 4440 else if (data != nullptr && data->segments.size () == 2)
28c32713 4441 {
68b888ff
SM
4442 segments[0] = data->segments[0].base + text_addr;
4443 segments[1] = data->segments[1].base + data_addr;
28c32713
JB
4444 num_segments = 2;
4445 }
8d385431
DJ
4446 /* If the object file has only one segment, assume that it is text
4447 rather than data; main programs with no writable data are rare,
4448 but programs with no code are useless. Of course the code might
4449 have ended up in the data segment... to detect that we would need
4450 the permissions here. */
68b888ff 4451 else if (data && data->segments.size () == 1)
8d385431 4452 {
68b888ff 4453 segments[0] = data->segments[0].base + text_addr;
8d385431
DJ
4454 num_segments = 1;
4455 }
28c32713
JB
4456 /* There's no way to relocate by segment. */
4457 else
4458 do_segments = 0;
31d99776
DJ
4459
4460 if (do_segments)
4461 {
98badbfd 4462 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
62982abd
SM
4463 data.get (), offs,
4464 num_segments, segments);
31d99776
DJ
4465
4466 if (ret == 0 && !do_sections)
3e43a32a
MS
4467 error (_("Can not handle qOffsets TextSeg "
4468 "response with this symbol file"));
31d99776
DJ
4469
4470 if (ret > 0)
4471 do_sections = 0;
4472 }
c906108c 4473
31d99776
DJ
4474 if (do_sections)
4475 {
a42d7dd8 4476 offs[SECT_OFF_TEXT (objf)] = text_addr;
31d99776 4477
3e43a32a
MS
4478 /* This is a temporary kludge to force data and bss to use the
4479 same offsets because that's what nlmconv does now. The real
4480 solution requires changes to the stub and remote.c that I
4481 don't have time to do right now. */
31d99776 4482
a42d7dd8
TT
4483 offs[SECT_OFF_DATA (objf)] = data_addr;
4484 offs[SECT_OFF_BSS (objf)] = data_addr;
31d99776 4485 }
c906108c 4486
a42d7dd8 4487 objfile_relocate (objf, offs);
c906108c
SS
4488}
4489
9a7071a8 4490/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4491
4492void
4493remote_target::send_interrupt_sequence ()
9a7071a8 4494{
5d93a237
TT
4495 struct remote_state *rs = get_remote_state ();
4496
9a7071a8 4497 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4498 remote_serial_write ("\x03", 1);
9a7071a8 4499 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4500 serial_send_break (rs->remote_desc);
9a7071a8
JB
4501 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4502 {
5d93a237 4503 serial_send_break (rs->remote_desc);
c33e31fd 4504 remote_serial_write ("g", 1);
9a7071a8
JB
4505 }
4506 else
f34652de 4507 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
9a7071a8
JB
4508 interrupt_sequence_mode);
4509}
4510
3405876a
PA
4511
4512/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4513 and extract the PTID. Returns NULL_PTID if not found. */
4514
4515static ptid_t
e3b2741b 4516stop_reply_extract_thread (const char *stop_reply)
3405876a
PA
4517{
4518 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4519 {
256642e8 4520 const char *p;
3405876a
PA
4521
4522 /* Txx r:val ; r:val (...) */
4523 p = &stop_reply[3];
4524
4525 /* Look for "register" named "thread". */
4526 while (*p != '\0')
4527 {
256642e8 4528 const char *p1;
3405876a
PA
4529
4530 p1 = strchr (p, ':');
4531 if (p1 == NULL)
4532 return null_ptid;
4533
4534 if (strncmp (p, "thread", p1 - p) == 0)
4535 return read_ptid (++p1, &p);
4536
4537 p1 = strchr (p, ';');
4538 if (p1 == NULL)
4539 return null_ptid;
4540 p1++;
4541
4542 p = p1;
4543 }
4544 }
4545
4546 return null_ptid;
4547}
4548
b7ea362b
PA
4549/* Determine the remote side's current thread. If we have a stop
4550 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4551 "thread" register we can extract the current thread from. If not,
4552 ask the remote which is the current thread with qC. The former
4553 method avoids a roundtrip. */
4554
6b8edb51 4555ptid_t
e3b2741b 4556remote_target::get_current_thread (const char *wait_status)
b7ea362b 4557{
6a49a997 4558 ptid_t ptid = null_ptid;
b7ea362b
PA
4559
4560 /* Note we don't use remote_parse_stop_reply as that makes use of
4561 the target architecture, which we haven't yet fully determined at
4562 this point. */
4563 if (wait_status != NULL)
4564 ptid = stop_reply_extract_thread (wait_status);
d7e15655 4565 if (ptid == null_ptid)
b7ea362b
PA
4566 ptid = remote_current_thread (inferior_ptid);
4567
4568 return ptid;
4569}
4570
49c62f2e
PA
4571/* Query the remote target for which is the current thread/process,
4572 add it to our tables, and update INFERIOR_PTID. The caller is
4573 responsible for setting the state such that the remote end is ready
3405876a
PA
4574 to return the current thread.
4575
4576 This function is called after handling the '?' or 'vRun' packets,
4577 whose response is a stop reply from which we can also try
4578 extracting the thread. If the target doesn't support the explicit
4579 qC query, we infer the current thread from that stop reply, passed
64d38fdd 4580 in in WAIT_STATUS, which may be NULL.
49c62f2e 4581
64d38fdd
JM
4582 The function returns pointer to the main thread of the inferior. */
4583
4584thread_info *
e3b2741b 4585remote_target::add_current_inferior_and_thread (const char *wait_status)
49c62f2e 4586{
9ab8741a 4587 bool fake_pid_p = false;
49c62f2e 4588
0ac55310 4589 switch_to_no_thread ();
49c62f2e 4590
0ac55310
PA
4591 /* Now, if we have thread information, update the current thread's
4592 ptid. */
87215ad1 4593 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4594
87215ad1 4595 if (curr_ptid != null_ptid)
49c62f2e 4596 {
ff52c073 4597 if (!m_features.remote_multi_process_p ())
9ab8741a 4598 fake_pid_p = true;
49c62f2e
PA
4599 }
4600 else
4601 {
4602 /* Without this, some commands which require an active target
4603 (such as kill) won't work. This variable serves (at least)
4604 double duty as both the pid of the target process (if it has
4605 such), and as a flag indicating that a target is active. */
87215ad1 4606 curr_ptid = magic_null_ptid;
9ab8741a 4607 fake_pid_p = true;
49c62f2e
PA
4608 }
4609
e99b03dc 4610 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
49c62f2e 4611
87215ad1
SDJ
4612 /* Add the main thread and switch to it. Don't try reading
4613 registers yet, since we haven't fetched the target description
4614 yet. */
5b6d1e4f 4615 thread_info *tp = add_thread_silent (this, curr_ptid);
87215ad1 4616 switch_to_thread_no_regs (tp);
64d38fdd
JM
4617
4618 return tp;
49c62f2e
PA
4619}
4620
6efcd9a8
PA
4621/* Print info about a thread that was found already stopped on
4622 connection. */
4623
1edb66d8
SM
4624void
4625remote_target::print_one_stopped_thread (thread_info *thread)
6efcd9a8 4626{
1edb66d8
SM
4627 target_waitstatus ws;
4628
4629 /* If there is a pending waitstatus, use it. If there isn't it's because
4630 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4631 and process_initial_stop_replies decided it wasn't interesting to save
4632 and report to the core. */
4633 if (thread->has_pending_waitstatus ())
4634 {
4635 ws = thread->pending_waitstatus ();
4636 thread->clear_pending_waitstatus ();
4637 }
4638 else
4639 {
183be222 4640 ws.set_stopped (GDB_SIGNAL_0);
1edb66d8 4641 }
6efcd9a8 4642
00431a78 4643 switch_to_thread (thread);
1edb66d8 4644 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
6efcd9a8
PA
4645 set_current_sal_from_frame (get_current_frame ());
4646
1edb66d8
SM
4647 /* For "info program". */
4648 set_last_target_status (this, thread->ptid, ws);
6efcd9a8 4649
183be222 4650 if (ws.kind () == TARGET_WAITKIND_STOPPED)
6efcd9a8 4651 {
183be222 4652 enum gdb_signal sig = ws.sig ();
6efcd9a8
PA
4653
4654 if (signal_print_state (sig))
76727919 4655 gdb::observers::signal_received.notify (sig);
6efcd9a8 4656 }
76727919 4657 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4658}
4659
221e1a37
PA
4660/* Process all initial stop replies the remote side sent in response
4661 to the ? packet. These indicate threads that were already stopped
4662 on initial connection. We mark these threads as stopped and print
4663 their current frame before giving the user the prompt. */
4664
6b8edb51
PA
4665void
4666remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4667{
4668 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4669 struct thread_info *selected = NULL;
4670 struct thread_info *lowest_stopped = NULL;
4671 struct thread_info *first = NULL;
221e1a37 4672
1edb66d8
SM
4673 /* This is only used when the target is non-stop. */
4674 gdb_assert (target_is_non_stop_p ());
4675
221e1a37
PA
4676 /* Consume the initial pending events. */
4677 while (pending_stop_replies-- > 0)
4678 {
4679 ptid_t waiton_ptid = minus_one_ptid;
4680 ptid_t event_ptid;
4681 struct target_waitstatus ws;
4682 int ignore_event = 0;
4683
221e1a37
PA
4684 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4685 if (remote_debug)
c272a98c 4686 print_target_wait_results (waiton_ptid, event_ptid, ws);
221e1a37 4687
183be222 4688 switch (ws.kind ())
221e1a37
PA
4689 {
4690 case TARGET_WAITKIND_IGNORE:
4691 case TARGET_WAITKIND_NO_RESUMED:
4692 case TARGET_WAITKIND_SIGNALLED:
4693 case TARGET_WAITKIND_EXITED:
4694 /* We shouldn't see these, but if we do, just ignore. */
2189c312 4695 remote_debug_printf ("event ignored");
221e1a37
PA
4696 ignore_event = 1;
4697 break;
4698
221e1a37
PA
4699 default:
4700 break;
4701 }
4702
4703 if (ignore_event)
4704 continue;
4705
5b6d1e4f 4706 thread_info *evthread = find_thread_ptid (this, event_ptid);
221e1a37 4707
183be222 4708 if (ws.kind () == TARGET_WAITKIND_STOPPED)
221e1a37 4709 {
183be222 4710 enum gdb_signal sig = ws.sig ();
221e1a37
PA
4711
4712 /* Stubs traditionally report SIGTRAP as initial signal,
4713 instead of signal 0. Suppress it. */
4714 if (sig == GDB_SIGNAL_TRAP)
4715 sig = GDB_SIGNAL_0;
1edb66d8 4716 evthread->set_stop_signal (sig);
183be222 4717 ws.set_stopped (sig);
6efcd9a8 4718 }
221e1a37 4719
183be222
SM
4720 if (ws.kind () != TARGET_WAITKIND_STOPPED
4721 || ws.sig () != GDB_SIGNAL_0)
1edb66d8 4722 evthread->set_pending_waitstatus (ws);
6efcd9a8 4723
719546c4
SM
4724 set_executing (this, event_ptid, false);
4725 set_running (this, event_ptid, false);
c9d22089 4726 get_remote_thread_info (evthread)->set_not_resumed ();
6efcd9a8
PA
4727 }
4728
4729 /* "Notice" the new inferiors before anything related to
4730 registers/memory. */
5b6d1e4f 4731 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4732 {
30220b46 4733 inf->needs_setup = true;
6efcd9a8
PA
4734
4735 if (non_stop)
4736 {
08036331 4737 thread_info *thread = any_live_thread_of_inferior (inf);
00431a78 4738 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
6efcd9a8
PA
4739 from_tty);
4740 }
4741 }
4742
4743 /* If all-stop on top of non-stop, pause all threads. Note this
4744 records the threads' stop pc, so must be done after "noticing"
4745 the inferiors. */
4746 if (!non_stop)
4747 {
abe8cab7
SM
4748 {
4749 /* At this point, the remote target is not async. It needs to be for
4750 the poll in stop_all_threads to consider events from it, so enable
4751 it temporarily. */
4752 gdb_assert (!this->is_async_p ());
4a570176
TT
4753 SCOPE_EXIT { target_async (false); };
4754 target_async (true);
4f5539f0 4755 stop_all_threads ("remote connect in all-stop");
abe8cab7 4756 }
6efcd9a8
PA
4757
4758 /* If all threads of an inferior were already stopped, we
4759 haven't setup the inferior yet. */
5b6d1e4f 4760 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4761 {
6efcd9a8
PA
4762 if (inf->needs_setup)
4763 {
08036331 4764 thread_info *thread = any_live_thread_of_inferior (inf);
6efcd9a8
PA
4765 switch_to_thread_no_regs (thread);
4766 setup_inferior (0);
4767 }
4768 }
221e1a37 4769 }
6efcd9a8
PA
4770
4771 /* Now go over all threads that are stopped, and print their current
4772 frame. If all-stop, then if there's a signalled thread, pick
4773 that as current. */
5b6d1e4f 4774 for (thread_info *thread : all_non_exited_threads (this))
6efcd9a8 4775 {
6efcd9a8
PA
4776 if (first == NULL)
4777 first = thread;
4778
4779 if (!non_stop)
00431a78 4780 thread->set_running (false);
6efcd9a8
PA
4781 else if (thread->state != THREAD_STOPPED)
4782 continue;
4783
1edb66d8 4784 if (selected == nullptr && thread->has_pending_waitstatus ())
6efcd9a8
PA
4785 selected = thread;
4786
5d5658a1
PA
4787 if (lowest_stopped == NULL
4788 || thread->inf->num < lowest_stopped->inf->num
4789 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4790 lowest_stopped = thread;
4791
4792 if (non_stop)
4793 print_one_stopped_thread (thread);
4794 }
4795
4796 /* In all-stop, we only print the status of one thread, and leave
4797 others with their status pending. */
4798 if (!non_stop)
4799 {
08036331 4800 thread_info *thread = selected;
6efcd9a8
PA
4801 if (thread == NULL)
4802 thread = lowest_stopped;
4803 if (thread == NULL)
4804 thread = first;
4805
4806 print_one_stopped_thread (thread);
4807 }
221e1a37
PA
4808}
4809
45664f16 4810/* Mark a remote_target as starting (by setting the starting_up flag within
7a34f66b
AB
4811 its remote_state) for the lifetime of this object. The reference count
4812 on the remote target is temporarily incremented, to prevent the target
4813 being deleted under our feet. */
4814
4815struct scoped_mark_target_starting
4816{
4817 /* Constructor, TARGET is the target to be marked as starting, its
4818 reference count will be incremented. */
4819 scoped_mark_target_starting (remote_target *target)
45664f16
AB
4820 : m_remote_target (remote_target_ref::new_reference (target)),
4821 m_restore_starting_up (set_starting_up_flag (target))
4822 { /* Nothing. */ }
4823
4824private:
7a34f66b 4825
45664f16
AB
4826 /* Helper function, set the starting_up flag on TARGET and return an
4827 object which, when it goes out of scope, will restore the previous
4828 value of the starting_up flag. */
4829 static scoped_restore_tmpl<bool>
4830 set_starting_up_flag (remote_target *target)
7a34f66b 4831 {
45664f16
AB
4832 remote_state *rs = target->get_remote_state ();
4833 gdb_assert (!rs->starting_up);
4834 return make_scoped_restore (&rs->starting_up, true);
7a34f66b
AB
4835 }
4836
45664f16
AB
4837 /* A gdb::ref_ptr pointer to a remote_target. */
4838 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4839
4840 /* A reference to the target on which we are operating. */
4841 remote_target_ref m_remote_target;
7a34f66b 4842
45664f16
AB
4843 /* An object which restores the previous value of the starting_up flag
4844 when it goes out of scope. */
4845 scoped_restore_tmpl<bool> m_restore_starting_up;
7a34f66b
AB
4846};
4847
288712bb
AB
4848/* Helper for remote_target::start_remote, start the remote connection and
4849 sync state. Return true if everything goes OK, otherwise, return false.
4850 This function exists so that the scoped_restore created within it will
4851 expire before we return to remote_target::start_remote. */
048094ac 4852
288712bb
AB
4853bool
4854remote_target::start_remote_1 (int from_tty, int extended_p)
c906108c 4855{
2189c312
SM
4856 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4857
c8d104ad 4858 struct remote_state *rs = get_remote_state ();
8621d6a9 4859
048094ac
PA
4860 /* Signal other parts that we're going through the initial setup,
4861 and so things may not be stable yet. E.g., we don't try to
4862 install tracepoints until we've relocated symbols. Also, a
4863 Ctrl-C before we're connected and synced up can't interrupt the
4864 target. Instead, it offers to drop the (potentially wedged)
4865 connection. */
7a34f66b 4866 scoped_mark_target_starting target_is_starting (this);
048094ac 4867
522002f9 4868 QUIT;
c906108c 4869
9a7071a8
JB
4870 if (interrupt_on_connect)
4871 send_interrupt_sequence ();
4872
57e12211 4873 /* Ack any packet which the remote side has already sent. */
048094ac 4874 remote_serial_write ("+", 1);
1e51243a 4875
c8d104ad
PA
4876 /* The first packet we send to the target is the optional "supported
4877 packets" request. If the target can answer this, it will tell us
4878 which later probes to skip. */
4879 remote_query_supported ();
4880
d914c394 4881 /* If the stub wants to get a QAllow, compose one and send it. */
ff52c073 4882 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4883 set_permissions ();
d914c394 4884
57809e5e
JK
4885 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4886 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4887 as a reply to known packet. For packet "vFile:setfs:" it is an
4888 invalid reply and GDB would return error in
4889 remote_hostio_set_filesystem, making remote files access impossible.
4890 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4891 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4892 {
4893 const char v_mustreplyempty[] = "vMustReplyEmpty";
4894
4895 putpkt (v_mustreplyempty);
8d64371b
TT
4896 getpkt (&rs->buf, 0);
4897 if (strcmp (rs->buf.data (), "OK") == 0)
ff52c073
CS
4898 {
4899 m_features.m_protocol_packets[PACKET_vFile_setfs].support
4900 = PACKET_DISABLE;
4901 }
8d64371b 4902 else if (strcmp (rs->buf.data (), "") != 0)
57809e5e 4903 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
8d64371b 4904 rs->buf.data ());
57809e5e
JK
4905 }
4906
c8d104ad
PA
4907 /* Next, we possibly activate noack mode.
4908
4909 If the QStartNoAckMode packet configuration is set to AUTO,
4910 enable noack mode if the stub reported a wish for it with
4911 qSupported.
4912
4913 If set to TRUE, then enable noack mode even if the stub didn't
4914 report it in qSupported. If the stub doesn't reply OK, the
4915 session ends with an error.
4916
4917 If FALSE, then don't activate noack mode, regardless of what the
4918 stub claimed should be the default with qSupported. */
4919
ff52c073 4920 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
c8d104ad
PA
4921 {
4922 putpkt ("QStartNoAckMode");
8d64371b 4923 getpkt (&rs->buf, 0);
ff52c073 4924 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
c8d104ad
PA
4925 rs->noack_mode = 1;
4926 }
4927
04bd08de 4928 if (extended_p)
5fe04517
PA
4929 {
4930 /* Tell the remote that we are using the extended protocol. */
4931 putpkt ("!");
8d64371b 4932 getpkt (&rs->buf, 0);
5fe04517
PA
4933 }
4934
9b224c5e
PA
4935 /* Let the target know which signals it is allowed to pass down to
4936 the program. */
4937 update_signals_program_target ();
4938
d962ef82
DJ
4939 /* Next, if the target can specify a description, read it. We do
4940 this before anything involving memory or registers. */
4941 target_find_description ();
4942
6c95b8df
PA
4943 /* Next, now that we know something about the target, update the
4944 address spaces in the program spaces. */
4945 update_address_spaces ();
4946
50c71eaf
PA
4947 /* On OSs where the list of libraries is global to all
4948 processes, we fetch them early. */
f5656ead 4949 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4950 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4951
6efcd9a8 4952 if (target_is_non_stop_p ())
74531fed 4953 {
ff52c073 4954 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4955 error (_("Non-stop mode requested, but remote "
4956 "does not support non-stop"));
74531fed
PA
4957
4958 putpkt ("QNonStop:1");
8d64371b 4959 getpkt (&rs->buf, 0);
74531fed 4960
8d64371b
TT
4961 if (strcmp (rs->buf.data (), "OK") != 0)
4962 error (_("Remote refused setting non-stop mode with: %s"),
4963 rs->buf.data ());
74531fed
PA
4964
4965 /* Find about threads and processes the stub is already
4966 controlling. We default to adding them in the running state.
4967 The '?' query below will then tell us about which threads are
4968 stopped. */
f6ac5f3d 4969 this->update_thread_list ();
74531fed 4970 }
ff52c073 4971 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4972 {
4973 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4974 Request it explicitly. */
74531fed 4975 putpkt ("QNonStop:0");
8d64371b 4976 getpkt (&rs->buf, 0);
74531fed 4977
8d64371b
TT
4978 if (strcmp (rs->buf.data (), "OK") != 0)
4979 error (_("Remote refused setting all-stop mode with: %s"),
4980 rs->buf.data ());
74531fed
PA
4981 }
4982
a0743c90
YQ
4983 /* Upload TSVs regardless of whether the target is running or not. The
4984 remote stub, such as GDBserver, may have some predefined or builtin
4985 TSVs, even if the target is not running. */
f6ac5f3d 4986 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4987 {
4988 struct uploaded_tsv *uploaded_tsvs = NULL;
4989
f6ac5f3d 4990 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4991 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4992 }
4993
2d717e4f
DJ
4994 /* Check whether the target is running now. */
4995 putpkt ("?");
8d64371b 4996 getpkt (&rs->buf, 0);
2d717e4f 4997
6efcd9a8 4998 if (!target_is_non_stop_p ())
2d717e4f 4999 {
b5c8f22d
SM
5000 char *wait_status = NULL;
5001
74531fed 5002 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 5003 {
04bd08de 5004 if (!extended_p)
74531fed 5005 error (_("The target is not running (try extended-remote?)"));
288712bb 5006 return false;
2d717e4f
DJ
5007 }
5008 else
74531fed 5009 {
74531fed 5010 /* Save the reply for later. */
8d64371b
TT
5011 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5012 strcpy (wait_status, rs->buf.data ());
74531fed
PA
5013 }
5014
b7ea362b 5015 /* Fetch thread list. */
e8032dde 5016 target_update_thread_list ();
b7ea362b 5017
74531fed
PA
5018 /* Let the stub know that we want it to return the thread. */
5019 set_continue_thread (minus_one_ptid);
5020
5b6d1e4f 5021 if (thread_count (this) == 0)
b7ea362b
PA
5022 {
5023 /* Target has no concept of threads at all. GDB treats
5024 non-threaded target as single-threaded; add a main
5025 thread. */
64d38fdd
JM
5026 thread_info *tp = add_current_inferior_and_thread (wait_status);
5027 get_remote_thread_info (tp)->set_resumed ();
b7ea362b
PA
5028 }
5029 else
5030 {
5031 /* We have thread information; select the thread the target
5032 says should be current. If we're reconnecting to a
5033 multi-threaded program, this will ideally be the thread
5034 that last reported an event before GDB disconnected. */
75c6c844
PA
5035 ptid_t curr_thread = get_current_thread (wait_status);
5036 if (curr_thread == null_ptid)
b7ea362b
PA
5037 {
5038 /* Odd... The target was able to list threads, but not
5039 tell us which thread was current (no "thread"
5040 register in T stop reply?). Just pick the first
5041 thread in the thread list then. */
2189c312
SM
5042
5043 remote_debug_printf ("warning: couldn't determine remote "
5044 "current thread; picking first in list.");
c9f35b34 5045
5b6d1e4f
PA
5046 for (thread_info *tp : all_non_exited_threads (this,
5047 minus_one_ptid))
75c6c844
PA
5048 {
5049 switch_to_thread (tp);
5050 break;
5051 }
b7ea362b 5052 }
75c6c844 5053 else
5b6d1e4f 5054 switch_to_thread (find_thread_ptid (this, curr_thread));
b7ea362b 5055 }
74531fed 5056
6e586cc5
YQ
5057 /* init_wait_for_inferior should be called before get_offsets in order
5058 to manage `inserted' flag in bp loc in a correct state.
5059 breakpoint_init_inferior, called from init_wait_for_inferior, set
5060 `inserted' flag to 0, while before breakpoint_re_set, called from
5061 start_remote, set `inserted' flag to 1. In the initialization of
5062 inferior, breakpoint_init_inferior should be called first, and then
5063 breakpoint_re_set can be called. If this order is broken, state of
5064 `inserted' flag is wrong, and cause some problems on breakpoint
5065 manipulation. */
5066 init_wait_for_inferior ();
5067
74531fed
PA
5068 get_offsets (); /* Get text, data & bss offsets. */
5069
d962ef82
DJ
5070 /* If we could not find a description using qXfer, and we know
5071 how to do it some other way, try again. This is not
5072 supported for non-stop; it could be, but it is tricky if
5073 there are no stopped threads when we connect. */
f6ac5f3d 5074 if (remote_read_description_p (this)
f5656ead 5075 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
5076 {
5077 target_clear_description ();
5078 target_find_description ();
5079 }
5080
74531fed
PA
5081 /* Use the previously fetched status. */
5082 gdb_assert (wait_status != NULL);
4f626cad
AB
5083 struct notif_event *reply
5084 = remote_notif_parse (this, &notif_client_stop, wait_status);
5085 push_stop_reply ((struct stop_reply *) reply);
74531fed 5086
f6ac5f3d 5087 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
5088 }
5089 else
5090 {
68c97600
PA
5091 /* Clear WFI global state. Do this before finding about new
5092 threads and inferiors, and setting the current inferior.
5093 Otherwise we would clear the proceed status of the current
5094 inferior when we want its stop_soon state to be preserved
5095 (see notice_new_inferior). */
5096 init_wait_for_inferior ();
5097
74531fed
PA
5098 /* In non-stop, we will either get an "OK", meaning that there
5099 are no stopped threads at this time; or, a regular stop
5100 reply. In the latter case, there may be more than one thread
5101 stopped --- we pull them all out using the vStopped
5102 mechanism. */
8d64371b 5103 if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 5104 {
42938c1a 5105 const notif_client *notif = &notif_client_stop;
2d717e4f 5106
722247f1
YQ
5107 /* remote_notif_get_pending_replies acks this one, and gets
5108 the rest out. */
f48ff2a7 5109 rs->notif_state->pending_event[notif_client_stop.id]
8d64371b 5110 = remote_notif_parse (this, notif, rs->buf.data ());
722247f1 5111 remote_notif_get_pending_events (notif);
74531fed 5112 }
2d717e4f 5113
5b6d1e4f 5114 if (thread_count (this) == 0)
74531fed 5115 {
04bd08de 5116 if (!extended_p)
74531fed 5117 error (_("The target is not running (try extended-remote?)"));
288712bb 5118 return false;
c35b1492 5119 }
74531fed 5120
2455069d 5121 /* Report all signals during attach/startup. */
adc6a863 5122 pass_signals ({});
221e1a37
PA
5123
5124 /* If there are already stopped threads, mark them stopped and
5125 report their stops before giving the prompt to the user. */
6efcd9a8 5126 process_initial_stop_replies (from_tty);
221e1a37
PA
5127
5128 if (target_can_async_p ())
4a570176 5129 target_async (true);
74531fed 5130 }
c8d104ad 5131
901e4e8d
SM
5132 /* Give the target a chance to look up symbols. */
5133 for (inferior *inf : all_inferiors (this))
c8d104ad 5134 {
901e4e8d
SM
5135 /* The inferiors that exist at this point were created from what
5136 was found already running on the remote side, so we know they
5137 have execution. */
5138 gdb_assert (this->has_execution (inf));
5139
a42d7dd8 5140 /* No use without a symbol-file. */
901e4e8d
SM
5141 if (inf->pspace->symfile_object_file == nullptr)
5142 continue;
5143
5144 /* Need to switch to a specific thread, because remote_check_symbols
5145 uses INFERIOR_PTID to set the general thread. */
5146 scoped_restore_current_thread restore_thread;
5147 thread_info *thread = any_thread_of_inferior (inf);
5148 switch_to_thread (thread);
5149 this->remote_check_symbols ();
c8d104ad 5150 }
50c71eaf 5151
d5551862
SS
5152 /* Possibly the target has been engaged in a trace run started
5153 previously; find out where things are at. */
f6ac5f3d 5154 if (get_trace_status (current_trace_status ()) != -1)
d5551862 5155 {
00bf0b85 5156 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 5157
00bf0b85 5158 if (current_trace_status ()->running)
6cb06a8c 5159 gdb_printf (_("Trace is already running on the target.\n"));
00bf0b85 5160
f6ac5f3d 5161 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
5162
5163 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
5164 }
5165
c0272db5
TW
5166 /* Possibly the target has been engaged in a btrace record started
5167 previously; find out where things are at. */
5168 remote_btrace_maybe_reopen ();
5169
288712bb
AB
5170 return true;
5171}
5172
5173/* Start the remote connection and sync state. */
1e51243a 5174
288712bb
AB
5175void
5176remote_target::start_remote (int from_tty, int extended_p)
5177{
5178 if (start_remote_1 (from_tty, extended_p)
5179 && breakpoints_should_be_inserted_now ())
50c71eaf 5180 insert_breakpoints ();
c906108c
SS
5181}
5182
121b3efd
PA
5183const char *
5184remote_target::connection_string ()
5185{
5186 remote_state *rs = get_remote_state ();
5187
5188 if (rs->remote_desc->name != NULL)
5189 return rs->remote_desc->name;
5190 else
5191 return NULL;
5192}
5193
c906108c
SS
5194/* Open a connection to a remote debugger.
5195 NAME is the filename used for communication. */
5196
f6ac5f3d
PA
5197void
5198remote_target::open (const char *name, int from_tty)
c906108c 5199{
f6ac5f3d 5200 open_1 (name, from_tty, 0);
43ff13b4
JM
5201}
5202
c906108c
SS
5203/* Open a connection to a remote debugger using the extended
5204 remote gdb protocol. NAME is the filename used for communication. */
5205
f6ac5f3d
PA
5206void
5207extended_remote_target::open (const char *name, int from_tty)
c906108c 5208{
f6ac5f3d 5209 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
5210}
5211
ff52c073
CS
5212void
5213remote_features::reset_all_packet_configs_support ()
d471ea57
AC
5214{
5215 int i;
a744cf53 5216
444abaca 5217 for (i = 0; i < PACKET_MAX; i++)
ff52c073 5218 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
5219}
5220
ca4f7f8b
PA
5221/* Initialize all packet configs. */
5222
5223static void
5224init_all_packet_configs (void)
5225{
5226 int i;
5227
5228 for (i = 0; i < PACKET_MAX; i++)
5229 {
5230 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5231 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5232 }
5233}
5234
23860348 5235/* Symbol look-up. */
dc8acb97 5236
6b8edb51
PA
5237void
5238remote_target::remote_check_symbols ()
dc8acb97 5239{
8d64371b 5240 char *tmp;
dc8acb97
MS
5241 int end;
5242
06c7226e
SM
5243 /* It doesn't make sense to send a qSymbol packet for an inferior that
5244 doesn't have execution, because the remote side doesn't know about
5245 inferiors without execution. */
5246 gdb_assert (target_has_execution ());
63154eca 5247
ff52c073 5248 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
5249 return;
5250
63154eca
PA
5251 /* Make sure the remote is pointing at the right process. Note
5252 there's no way to select "no process". */
3c9c4b83
PA
5253 set_general_process ();
5254
6d820c5c
DJ
5255 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5256 because we need both at the same time. */
66644cd3 5257 gdb::char_vector msg (get_remote_packet_size ());
8d64371b 5258 gdb::char_vector reply (get_remote_packet_size ());
6d820c5c 5259
23860348 5260 /* Invite target to request symbol lookups. */
dc8acb97
MS
5261
5262 putpkt ("qSymbol::");
8d64371b 5263 getpkt (&reply, 0);
ff52c073 5264 m_features.packet_ok (reply, PACKET_qSymbol);
dc8acb97 5265
8d64371b 5266 while (startswith (reply.data (), "qSymbol:"))
dc8acb97 5267 {
77e371c0
TT
5268 struct bound_minimal_symbol sym;
5269
dc8acb97 5270 tmp = &reply[8];
66644cd3
AB
5271 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5272 strlen (tmp) / 2);
dc8acb97 5273 msg[end] = '\0';
66644cd3 5274 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
3b7344d5 5275 if (sym.minsym == NULL)
66644cd3
AB
5276 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5277 &reply[8]);
dc8acb97 5278 else
2bbe3cc1 5279 {
f5656ead 5280 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4aeddc50 5281 CORE_ADDR sym_addr = sym.value_address ();
2bbe3cc1
DJ
5282
5283 /* If this is a function address, return the start of code
5284 instead of any data function descriptor. */
328d42d8
SM
5285 sym_addr = gdbarch_convert_from_func_ptr_addr
5286 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
2bbe3cc1 5287
66644cd3 5288 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 5289 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1 5290 }
66644cd3
AB
5291
5292 putpkt (msg.data ());
8d64371b 5293 getpkt (&reply, 0);
dc8acb97
MS
5294 }
5295}
5296
9db8d71f 5297static struct serial *
baa336ce 5298remote_serial_open (const char *name)
9db8d71f
DJ
5299{
5300 static int udp_warning = 0;
5301
5302 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5303 of in ser-tcp.c, because it is the remote protocol assuming that the
5304 serial connection is reliable and not the serial connection promising
5305 to be. */
61012eef 5306 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 5307 {
3e43a32a
MS
5308 warning (_("The remote protocol may be unreliable over UDP.\n"
5309 "Some events may be lost, rendering further debugging "
5310 "impossible."));
9db8d71f
DJ
5311 udp_warning = 1;
5312 }
5313
5314 return serial_open (name);
5315}
5316
d914c394
SS
5317/* Inform the target of our permission settings. The permission flags
5318 work without this, but if the target knows the settings, it can do
5319 a couple things. First, it can add its own check, to catch cases
5320 that somehow manage to get by the permissions checks in target
5321 methods. Second, if the target is wired to disallow particular
5322 settings (for instance, a system in the field that is not set up to
5323 be able to stop at a breakpoint), it can object to any unavailable
5324 permissions. */
5325
5326void
f6ac5f3d 5327remote_target::set_permissions ()
d914c394
SS
5328{
5329 struct remote_state *rs = get_remote_state ();
5330
8d64371b 5331 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
bba74b36
YQ
5332 "WriteReg:%x;WriteMem:%x;"
5333 "InsertBreak:%x;InsertTrace:%x;"
5334 "InsertFastTrace:%x;Stop:%x",
5335 may_write_registers, may_write_memory,
5336 may_insert_breakpoints, may_insert_tracepoints,
5337 may_insert_fast_tracepoints, may_stop);
d914c394 5338 putpkt (rs->buf);
8d64371b 5339 getpkt (&rs->buf, 0);
d914c394
SS
5340
5341 /* If the target didn't like the packet, warn the user. Do not try
5342 to undo the user's settings, that would just be maddening. */
8d64371b
TT
5343 if (strcmp (rs->buf.data (), "OK") != 0)
5344 warning (_("Remote refused setting permissions with: %s"),
5345 rs->buf.data ());
d914c394
SS
5346}
5347
be2a5f71
DJ
5348/* This type describes each known response to the qSupported
5349 packet. */
5350struct protocol_feature
5351{
5352 /* The name of this protocol feature. */
5353 const char *name;
5354
5355 /* The default for this protocol feature. */
5356 enum packet_support default_support;
5357
5358 /* The function to call when this feature is reported, or after
5359 qSupported processing if the feature is not supported.
5360 The first argument points to this structure. The second
5361 argument indicates whether the packet requested support be
5362 enabled, disabled, or probed (or the default, if this function
5363 is being called at the end of processing and this feature was
5364 not reported). The third argument may be NULL; if not NULL, it
5365 is a NUL-terminated string taken from the packet following
5366 this feature's name and an equals sign. */
6b8edb51
PA
5367 void (*func) (remote_target *remote, const struct protocol_feature *,
5368 enum packet_support, const char *);
be2a5f71
DJ
5369
5370 /* The corresponding packet for this feature. Only used if
5371 FUNC is remote_supported_packet. */
5372 int packet;
5373};
5374
be2a5f71 5375static void
6b8edb51
PA
5376remote_supported_packet (remote_target *remote,
5377 const struct protocol_feature *feature,
be2a5f71
DJ
5378 enum packet_support support,
5379 const char *argument)
5380{
5381 if (argument)
5382 {
5383 warning (_("Remote qSupported response supplied an unexpected value for"
5384 " \"%s\"."), feature->name);
5385 return;
5386 }
5387
ff52c073 5388 remote->m_features.m_protocol_packets[feature->packet].support = support;
be2a5f71 5389}
be2a5f71 5390
6b8edb51
PA
5391void
5392remote_target::remote_packet_size (const protocol_feature *feature,
5393 enum packet_support support, const char *value)
be2a5f71
DJ
5394{
5395 struct remote_state *rs = get_remote_state ();
5396
5397 int packet_size;
5398 char *value_end;
5399
5400 if (support != PACKET_ENABLE)
5401 return;
5402
5403 if (value == NULL || *value == '\0')
5404 {
5405 warning (_("Remote target reported \"%s\" without a size."),
5406 feature->name);
5407 return;
5408 }
5409
5410 errno = 0;
5411 packet_size = strtol (value, &value_end, 16);
5412 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5413 {
5414 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5415 feature->name, value);
5416 return;
5417 }
5418
be2a5f71
DJ
5419 /* Record the new maximum packet size. */
5420 rs->explicit_packet_size = packet_size;
5421}
5422
cb8c24b6 5423static void
6b8edb51
PA
5424remote_packet_size (remote_target *remote, const protocol_feature *feature,
5425 enum packet_support support, const char *value)
5426{
5427 remote->remote_packet_size (feature, support, value);
5428}
5429
dc473cfb 5430static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5431 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5432 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5433 PACKET_qXfer_auxv },
c78fa86a
GB
5434 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5435 PACKET_qXfer_exec_file },
23181151
DJ
5436 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5437 PACKET_qXfer_features },
cfa9d6d9
DJ
5438 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5439 PACKET_qXfer_libraries },
2268b414
JK
5440 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5441 PACKET_qXfer_libraries_svr4 },
ced63ec0 5442 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5443 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5444 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5445 PACKET_qXfer_memory_map },
07e059b5
VP
5446 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5447 PACKET_qXfer_osdata },
dc146f7c
VP
5448 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5449 PACKET_qXfer_threads },
b3b9301e
PA
5450 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5451 PACKET_qXfer_traceframe_info },
89be2091
DJ
5452 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5453 PACKET_QPassSignals },
82075af2
JS
5454 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5455 PACKET_QCatchSyscalls },
9b224c5e
PA
5456 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5457 PACKET_QProgramSignals },
bc3b087d
SDJ
5458 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5459 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5460 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5461 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5462 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5463 PACKET_QEnvironmentHexEncoded },
5464 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5465 PACKET_QEnvironmentReset },
5466 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5467 PACKET_QEnvironmentUnset },
a6f3e723
SL
5468 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5469 PACKET_QStartNoAckMode },
4082afcc
PA
5470 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5471 PACKET_multiprocess_feature },
5472 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5473 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5474 PACKET_qXfer_siginfo_read },
5475 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5476 PACKET_qXfer_siginfo_write },
4082afcc 5477 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5478 PACKET_ConditionalTracepoints },
4082afcc 5479 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5480 PACKET_ConditionalBreakpoints },
4082afcc 5481 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5482 PACKET_BreakpointCommands },
4082afcc 5483 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5484 PACKET_FastTracepoints },
4082afcc 5485 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5486 PACKET_StaticTracepoints },
4082afcc 5487 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5488 PACKET_InstallInTrace},
4082afcc
PA
5489 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5490 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5491 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5492 PACKET_bc },
5493 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5494 PACKET_bs },
409873ef
SS
5495 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5496 PACKET_TracepointSource },
d914c394
SS
5497 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5498 PACKET_QAllow },
4082afcc
PA
5499 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5500 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5501 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5502 PACKET_qXfer_fdpic },
169081d0
TG
5503 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5504 PACKET_qXfer_uib },
03583c20
UW
5505 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5506 PACKET_QDisableRandomization },
d1feda86 5507 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5508 { "QTBuffer:size", PACKET_DISABLE,
5509 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5510 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5511 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5512 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5513 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5514 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5515 PACKET_qXfer_btrace },
5516 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5517 PACKET_qXfer_btrace_conf },
5518 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5519 PACKET_Qbtrace_conf_bts_size },
5520 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5521 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5522 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5523 PACKET_fork_event_feature },
5524 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5525 PACKET_vfork_event_feature },
94585166
DB
5526 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5527 PACKET_exec_event_feature },
b20a6524 5528 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5529 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5530 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5531 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5532 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
2c2e7f87
LM
5533 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5534 PACKET_memory_tagging_feature },
be2a5f71
DJ
5535};
5536
c8d5aac9
L
5537static char *remote_support_xml;
5538
5539/* Register string appended to "xmlRegisters=" in qSupported query. */
5540
5541void
6e39997a 5542register_remote_support_xml (const char *xml)
c8d5aac9
L
5543{
5544#if defined(HAVE_LIBEXPAT)
5545 if (remote_support_xml == NULL)
c4f7c687 5546 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5547 else
5548 {
5549 char *copy = xstrdup (remote_support_xml + 13);
ca3a04f6
CB
5550 char *saveptr;
5551 char *p = strtok_r (copy, ",", &saveptr);
c8d5aac9
L
5552
5553 do
5554 {
5555 if (strcmp (p, xml) == 0)
5556 {
5557 /* already there */
5558 xfree (copy);
5559 return;
5560 }
5561 }
ca3a04f6 5562 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
c8d5aac9
L
5563 xfree (copy);
5564
94b0dee1
PA
5565 remote_support_xml = reconcat (remote_support_xml,
5566 remote_support_xml, ",", xml,
5567 (char *) NULL);
c8d5aac9
L
5568 }
5569#endif
5570}
5571
69b6ecb0
TT
5572static void
5573remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5574{
69b6ecb0
TT
5575 if (!msg->empty ())
5576 msg->append (";");
5577 msg->append (append);
c8d5aac9
L
5578}
5579
6b8edb51
PA
5580void
5581remote_target::remote_query_supported ()
be2a5f71
DJ
5582{
5583 struct remote_state *rs = get_remote_state ();
5584 char *next;
5585 int i;
5586 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5587
5588 /* The packet support flags are handled differently for this packet
5589 than for most others. We treat an error, a disabled packet, and
5590 an empty response identically: any features which must be reported
5591 to be used will be automatically disabled. An empty buffer
5592 accomplishes this, since that is also the representation for a list
5593 containing no features. */
5594
5595 rs->buf[0] = 0;
ff52c073 5596 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5597 {
69b6ecb0 5598 std::string q;
c8d5aac9 5599
ff52c073
CS
5600 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5601 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5602 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5603
ff52c073
CS
5604 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5605 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5606 remote_query_supported_append (&q, "swbreak+");
ff52c073
CS
5607
5608 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5609 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5610 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5611
69b6ecb0 5612 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5613
ff52c073 5614 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
8020350c 5615 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5616 remote_query_supported_append (&q, "fork-events+");
ff52c073
CS
5617
5618 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
8020350c 5619 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5620 remote_query_supported_append (&q, "vfork-events+");
ff52c073
CS
5621
5622 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
8020350c 5623 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5624 remote_query_supported_append (&q, "exec-events+");
89245bc0 5625
ff52c073
CS
5626 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5627 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5628 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5629
ff52c073
CS
5630 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5631 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5632 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5633
ff52c073
CS
5634 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5635 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5636 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5637
ff52c073 5638 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
2c2e7f87
LM
5639 != AUTO_BOOLEAN_FALSE)
5640 remote_query_supported_append (&q, "memory-tagging+");
5641
b35d5edb
PA
5642 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5643 the qSupported:xmlRegisters=i386 handling. */
7cc244de 5644 if (remote_support_xml != NULL
ff52c073
CS
5645 && (m_features.packet_support (PACKET_qXfer_features)
5646 != PACKET_DISABLE))
69b6ecb0 5647 remote_query_supported_append (&q, remote_support_xml);
82f73884 5648
69b6ecb0
TT
5649 q = "qSupported:" + q;
5650 putpkt (q.c_str ());
94b0dee1 5651
8d64371b 5652 getpkt (&rs->buf, 0);
be2a5f71
DJ
5653
5654 /* If an error occured, warn, but do not return - just reset the
5655 buffer to empty and go on to disable features. */
ff52c073 5656 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
be2a5f71 5657 {
8d64371b 5658 warning (_("Remote failure reply: %s"), rs->buf.data ());
be2a5f71
DJ
5659 rs->buf[0] = 0;
5660 }
5661 }
5662
5663 memset (seen, 0, sizeof (seen));
5664
8d64371b 5665 next = rs->buf.data ();
be2a5f71
DJ
5666 while (*next)
5667 {
5668 enum packet_support is_supported;
5669 char *p, *end, *name_end, *value;
5670
5671 /* First separate out this item from the rest of the packet. If
5672 there's another item after this, we overwrite the separator
5673 (terminated strings are much easier to work with). */
5674 p = next;
5675 end = strchr (p, ';');
5676 if (end == NULL)
5677 {
5678 end = p + strlen (p);
5679 next = end;
5680 }
5681 else
5682 {
89be2091
DJ
5683 *end = '\0';
5684 next = end + 1;
5685
be2a5f71
DJ
5686 if (end == p)
5687 {
5688 warning (_("empty item in \"qSupported\" response"));
5689 continue;
5690 }
be2a5f71
DJ
5691 }
5692
5693 name_end = strchr (p, '=');
5694 if (name_end)
5695 {
5696 /* This is a name=value entry. */
5697 is_supported = PACKET_ENABLE;
5698 value = name_end + 1;
5699 *name_end = '\0';
5700 }
5701 else
5702 {
5703 value = NULL;
5704 switch (end[-1])
5705 {
5706 case '+':
5707 is_supported = PACKET_ENABLE;
5708 break;
5709
5710 case '-':
5711 is_supported = PACKET_DISABLE;
5712 break;
5713
5714 case '?':
5715 is_supported = PACKET_SUPPORT_UNKNOWN;
5716 break;
5717
5718 default:
3e43a32a
MS
5719 warning (_("unrecognized item \"%s\" "
5720 "in \"qSupported\" response"), p);
be2a5f71
DJ
5721 continue;
5722 }
5723 end[-1] = '\0';
5724 }
5725
5726 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5727 if (strcmp (remote_protocol_features[i].name, p) == 0)
5728 {
5729 const struct protocol_feature *feature;
5730
5731 seen[i] = 1;
5732 feature = &remote_protocol_features[i];
6b8edb51 5733 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5734 break;
5735 }
5736 }
5737
5738 /* If we increased the packet size, make sure to increase the global
5739 buffer size also. We delay this until after parsing the entire
5740 qSupported packet, because this is the same buffer we were
5741 parsing. */
8d64371b
TT
5742 if (rs->buf.size () < rs->explicit_packet_size)
5743 rs->buf.resize (rs->explicit_packet_size);
be2a5f71
DJ
5744
5745 /* Handle the defaults for unmentioned features. */
5746 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5747 if (!seen[i])
5748 {
5749 const struct protocol_feature *feature;
5750
5751 feature = &remote_protocol_features[i];
6b8edb51 5752 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5753 }
5754}
5755
048094ac
PA
5756/* Serial QUIT handler for the remote serial descriptor.
5757
5758 Defers handling a Ctrl-C until we're done with the current
5759 command/response packet sequence, unless:
5760
5761 - We're setting up the connection. Don't send a remote interrupt
5762 request, as we're not fully synced yet. Quit immediately
5763 instead.
5764
5765 - The target has been resumed in the foreground
223ffa71 5766 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5767 packet, and we're blocked waiting for the stop reply, thus a
5768 Ctrl-C should be immediately sent to the target.
5769
5770 - We get a second Ctrl-C while still within the same serial read or
5771 write. In that case the serial is seemingly wedged --- offer to
5772 quit/disconnect.
5773
5774 - We see a second Ctrl-C without target response, after having
5775 previously interrupted the target. In that case the target/stub
5776 is probably wedged --- offer to quit/disconnect.
5777*/
5778
6b8edb51
PA
5779void
5780remote_target::remote_serial_quit_handler ()
048094ac
PA
5781{
5782 struct remote_state *rs = get_remote_state ();
5783
5784 if (check_quit_flag ())
5785 {
5786 /* If we're starting up, we're not fully synced yet. Quit
5787 immediately. */
5788 if (rs->starting_up)
5789 quit ();
5790 else if (rs->got_ctrlc_during_io)
5791 {
5792 if (query (_("The target is not responding to GDB commands.\n"
5793 "Stop debugging it? ")))
5b6d1e4f 5794 remote_unpush_and_throw (this);
048094ac
PA
5795 }
5796 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5797 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5798 interrupt_query ();
5799 /* All-stop protocol, and blocked waiting for stop reply. Send
5800 an interrupt request. */
223ffa71 5801 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5802 target_interrupt ();
048094ac
PA
5803 else
5804 rs->got_ctrlc_during_io = 1;
5805 }
5806}
5807
6b8edb51
PA
5808/* The remote_target that is current while the quit handler is
5809 overridden with remote_serial_quit_handler. */
5810static remote_target *curr_quit_handler_target;
5811
5812static void
5813remote_serial_quit_handler ()
5814{
5815 curr_quit_handler_target->remote_serial_quit_handler ();
5816}
5817
5b6d1e4f
PA
5818/* Remove the remote target from the target stack of each inferior
5819 that is using it. Upper targets depend on it so remove them
5820 first. */
78a095c3
JK
5821
5822static void
5b6d1e4f 5823remote_unpush_target (remote_target *target)
78a095c3 5824{
5b6d1e4f
PA
5825 /* We have to unpush the target from all inferiors, even those that
5826 aren't running. */
5827 scoped_restore_current_inferior restore_current_inferior;
5828
5829 for (inferior *inf : all_inferiors (target))
5830 {
5831 switch_to_inferior_no_thread (inf);
c8181f70 5832 inf->pop_all_targets_at_and_above (process_stratum);
5b6d1e4f
PA
5833 generic_mourn_inferior ();
5834 }
d7cb0ef3
PA
5835
5836 /* Don't rely on target_close doing this when the target is popped
5837 from the last remote inferior above, because something may be
5838 holding a reference to the target higher up on the stack, meaning
5839 target_close won't be called yet. We lost the connection to the
5840 target, so clear these now, otherwise we may later throw
5841 TARGET_CLOSE_ERROR while trying to tell the remote target to
5842 close the file. */
5843 fileio_handles_invalidate_target (target);
78a095c3 5844}
be2a5f71 5845
048094ac 5846static void
5b6d1e4f 5847remote_unpush_and_throw (remote_target *target)
048094ac 5848{
5b6d1e4f 5849 remote_unpush_target (target);
048094ac
PA
5850 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5851}
5852
f6ac5f3d
PA
5853void
5854remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5855{
6b8edb51 5856 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5857
c906108c 5858 if (name == 0)
8a3fe4f8 5859 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5860 "serial device is attached to the remote system\n"
8a3fe4f8 5861 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5862
2d717e4f 5863 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5864 Ask this question first, before target_preopen has a chance to kill
5865 anything. */
55f6301a 5866 if (curr_remote != NULL && !target_has_execution ())
2d717e4f 5867 {
78a095c3
JK
5868 if (from_tty
5869 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5870 error (_("Still connected."));
5871 }
5872
78a095c3 5873 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5874 target_preopen (from_tty);
5875
ad9a8f3f 5876 remote_fileio_reset ();
1dd41f16 5877 reopen_exec_file ();
9dec38d3 5878 reread_symbols (from_tty);
1dd41f16 5879
6b8edb51
PA
5880 remote_target *remote
5881 = (extended_p ? new extended_remote_target () : new remote_target ());
5882 target_ops_up target_holder (remote);
5883
5884 remote_state *rs = remote->get_remote_state ();
5885
5886 /* See FIXME above. */
5887 if (!target_async_permitted)
5888 rs->wait_forever_enabled_p = 1;
5889
5d93a237
TT
5890 rs->remote_desc = remote_serial_open (name);
5891 if (!rs->remote_desc)
c906108c
SS
5892 perror_with_name (name);
5893
5894 if (baud_rate != -1)
5895 {
5d93a237 5896 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5897 {
9b74d5d3
KB
5898 /* The requested speed could not be set. Error out to
5899 top level after closing remote_desc. Take care to
5900 set remote_desc to NULL to avoid closing remote_desc
5901 more than once. */
5d93a237
TT
5902 serial_close (rs->remote_desc);
5903 rs->remote_desc = NULL;
c906108c
SS
5904 perror_with_name (name);
5905 }
5906 }
5907
236af5e3 5908 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5909 serial_raw (rs->remote_desc);
c906108c
SS
5910
5911 /* If there is something sitting in the buffer we might take it as a
5912 response to a command, which would be bad. */
5d93a237 5913 serial_flush_input (rs->remote_desc);
c906108c
SS
5914
5915 if (from_tty)
5916 {
0426ad51
TT
5917 gdb_puts ("Remote debugging using ");
5918 gdb_puts (name);
5919 gdb_puts ("\n");
c906108c 5920 }
d9f719f1 5921
6b8edb51 5922 /* Switch to using the remote target now. */
02980c56 5923 current_inferior ()->push_target (std::move (target_holder));
c906108c 5924
74531fed 5925 /* Register extra event sources in the event loop. */
6b8edb51 5926 rs->remote_async_inferior_event_token
baa8575b 5927 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
db20ebdf 5928 "remote");
6b8edb51 5929 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 5930
be2a5f71
DJ
5931 /* Reset the target state; these things will be queried either by
5932 remote_query_supported or as they are needed. */
ff52c073 5933 remote->m_features.reset_all_packet_configs_support ();
be2a5f71 5934 rs->explicit_packet_size = 0;
a6f3e723 5935 rs->noack_mode = 0;
82f73884 5936 rs->extended = extended_p;
e24a49d8 5937 rs->waiting_for_stop_reply = 0;
3a29589a 5938 rs->ctrlc_pending_p = 0;
048094ac 5939 rs->got_ctrlc_during_io = 0;
802188a7 5940
47f8a51d
TT
5941 rs->general_thread = not_sent_ptid;
5942 rs->continue_thread = not_sent_ptid;
262e1174 5943 rs->remote_traceframe_number = -1;
c906108c 5944
3a00c802
PA
5945 rs->last_resume_exec_dir = EXEC_FORWARD;
5946
9d1f7ab2 5947 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5948 rs->use_threadinfo_query = 1;
5949 rs->use_threadextra_query = 1;
9d1f7ab2 5950
dd194f6b 5951 rs->readahead_cache.invalidate ();
80152258 5952
c6ebd6cf 5953 if (target_async_permitted)
92d1e331 5954 {
92d1e331
DJ
5955 /* FIXME: cagney/1999-09-23: During the initial connection it is
5956 assumed that the target is already ready and able to respond to
0df8b418 5957 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5958 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5959 around this. Eventually a mechanism that allows
92d1e331 5960 wait_for_inferior() to expect/get timeouts will be
23860348 5961 implemented. */
6b8edb51 5962 rs->wait_forever_enabled_p = 0;
92d1e331
DJ
5963 }
5964
23860348 5965 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5966 no_shared_libraries (NULL, 0);
f78f6cf1 5967
36918e70 5968 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5969 target (we'd otherwise be in an inconsistent state) and then
5970 propogate the error on up the exception chain. This ensures that
5971 the caller doesn't stumble along blindly assuming that the
5972 function succeeded. The CLI doesn't have this problem but other
5973 UI's, such as MI do.
36918e70
AC
5974
5975 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5976 this function should return an error indication letting the
ce2826aa 5977 caller restore the previous state. Unfortunately the command
36918e70
AC
5978 ``target remote'' is directly wired to this function making that
5979 impossible. On a positive note, the CLI side of this problem has
5980 been fixed - the function set_cmd_context() makes it possible for
5981 all the ``target ....'' commands to share a common callback
5982 function. See cli-dump.c. */
109c3e39 5983 {
2d717e4f 5984
a70b8144 5985 try
04bd08de 5986 {
6b8edb51 5987 remote->start_remote (from_tty, extended_p);
04bd08de 5988 }
230d2906 5989 catch (const gdb_exception &ex)
109c3e39 5990 {
c8d104ad
PA
5991 /* Pop the partially set up target - unless something else did
5992 already before throwing the exception. */
6b8edb51 5993 if (ex.error != TARGET_CLOSE_ERROR)
5b6d1e4f 5994 remote_unpush_target (remote);
eedc3f4f 5995 throw;
109c3e39
AC
5996 }
5997 }
c906108c 5998
6b8edb51 5999 remote_btrace_reset (rs);
f4abbc16 6000
c6ebd6cf 6001 if (target_async_permitted)
6b8edb51 6002 rs->wait_forever_enabled_p = 1;
43ff13b4
JM
6003}
6004
28561a65 6005/* Determine if WS represents a fork status. */
a4543480 6006
28561a65
SM
6007static bool
6008is_fork_status (target_waitkind kind)
a4543480 6009{
28561a65
SM
6010 return (kind == TARGET_WAITKIND_FORKED
6011 || kind == TARGET_WAITKIND_VFORKED);
a4543480
SM
6012}
6013
28561a65
SM
6014/* Return THREAD's pending status if it is a pending fork parent, else
6015 return nullptr. */
a4543480 6016
28561a65 6017static const target_waitstatus *
a4543480
SM
6018thread_pending_fork_status (struct thread_info *thread)
6019{
28561a65
SM
6020 const target_waitstatus &ws
6021 = (thread->has_pending_waitstatus ()
6022 ? thread->pending_waitstatus ()
6023 : thread->pending_follow);
a4543480 6024
28561a65
SM
6025 if (!is_fork_status (ws.kind ()))
6026 return nullptr;
a4543480 6027
28561a65 6028 return &ws;
a4543480
SM
6029}
6030
de0d863e
DB
6031/* Detach the specified process. */
6032
6b8edb51
PA
6033void
6034remote_target::remote_detach_pid (int pid)
de0d863e
DB
6035{
6036 struct remote_state *rs = get_remote_state ();
6037
4c7333b3
PA
6038 /* This should not be necessary, but the handling for D;PID in
6039 GDBserver versions prior to 8.2 incorrectly assumes that the
6040 selected process points to the same process we're detaching,
6041 leading to misbehavior (and possibly GDBserver crashing) when it
6042 does not. Since it's easy and cheap, work around it by forcing
6043 GDBserver to select GDB's current process. */
6044 set_general_process ();
6045
ff52c073 6046 if (m_features.remote_multi_process_p ())
8d64371b 6047 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
de0d863e 6048 else
8d64371b 6049 strcpy (rs->buf.data (), "D");
de0d863e
DB
6050
6051 putpkt (rs->buf);
8d64371b 6052 getpkt (&rs->buf, 0);
de0d863e
DB
6053
6054 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6055 ;
6056 else if (rs->buf[0] == '\0')
6057 error (_("Remote doesn't know how to detach"));
6058 else
6059 error (_("Can't detach process."));
6060}
6061
6062/* This detaches a program to which we previously attached, using
6063 inferior_ptid to identify the process. After this is done, GDB
6064 can be used to debug some other program. We better not have left
6065 any breakpoints in the target program or it'll die when it hits
6066 one. */
c906108c 6067
6b8edb51 6068void
00431a78 6069remote_target::remote_detach_1 (inferior *inf, int from_tty)
c906108c 6070{
e99b03dc 6071 int pid = inferior_ptid.pid ();
d01949b6 6072 struct remote_state *rs = get_remote_state ();
de0d863e 6073 int is_fork_parent;
c906108c 6074
55f6301a 6075 if (!target_has_execution ())
2d717e4f
DJ
6076 error (_("No process to detach from."));
6077
0f48b757 6078 target_announce_detach (from_tty);
7cee1e54 6079
e87f0fe8
PA
6080 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
6081 {
6082 /* If we're in breakpoints-always-inserted mode, or the inferior
6083 is running, we have to remove breakpoints before detaching.
6084 We don't do this in common code instead because not all
6085 targets support removing breakpoints while the target is
6086 running. The remote target / gdbserver does, though. */
6087 remove_breakpoints_inf (current_inferior ());
6088 }
6089
c906108c 6090 /* Tell the remote target to detach. */
de0d863e 6091 remote_detach_pid (pid);
82f73884 6092
8020350c 6093 /* Exit only if this is the only active inferior. */
5b6d1e4f 6094 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
0426ad51 6095 gdb_puts (_("Ending remote debugging.\n"));
82f73884 6096
df5ad102
SM
6097 /* See if any thread of the inferior we are detaching has a pending fork
6098 status. In that case, we must detach from the child resulting from
6099 that fork. */
6100 for (thread_info *thread : inf->non_exited_threads ())
6101 {
6102 const target_waitstatus *ws = thread_pending_fork_status (thread);
6103
6104 if (ws == nullptr)
6105 continue;
6106
6107 remote_detach_pid (ws->child_ptid ().pid ());
6108 }
6109
6110 /* Check also for any pending fork events in the stop reply queue. */
6111 remote_notif_get_pending_events (&notif_client_stop);
6112 for (stop_reply_up &reply : rs->stop_reply_queue)
6113 {
6114 if (reply->ptid.pid () != pid)
6115 continue;
6116
6117 if (!is_fork_status (reply->ws.kind ()))
6118 continue;
6119
6120 remote_detach_pid (reply->ws.child_ptid ().pid ());
6121 }
6122
5b6d1e4f 6123 thread_info *tp = find_thread_ptid (this, inferior_ptid);
00431a78 6124
de0d863e
DB
6125 /* Check to see if we are detaching a fork parent. Note that if we
6126 are detaching a fork child, tp == NULL. */
6127 is_fork_parent = (tp != NULL
183be222 6128 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
de0d863e
DB
6129
6130 /* If doing detach-on-fork, we don't mourn, because that will delete
6131 breakpoints that should be available for the followed inferior. */
6132 if (!is_fork_parent)
f67c0c91 6133 {
249b5733
PA
6134 /* Save the pid as a string before mourning, since that will
6135 unpush the remote target, and we need the string after. */
f2907e49 6136 std::string infpid = target_pid_to_str (ptid_t (pid));
f67c0c91
SDJ
6137
6138 target_mourn_inferior (inferior_ptid);
6139 if (print_inferior_events)
6cb06a8c
TT
6140 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6141 inf->num, infpid.c_str ());
f67c0c91 6142 }
de0d863e
DB
6143 else
6144 {
0ac55310 6145 switch_to_no_thread ();
00431a78 6146 detach_inferior (current_inferior ());
de0d863e 6147 }
2d717e4f
DJ
6148}
6149
f6ac5f3d
PA
6150void
6151remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6152{
00431a78 6153 remote_detach_1 (inf, from_tty);
2d717e4f
DJ
6154}
6155
f6ac5f3d
PA
6156void
6157extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6158{
00431a78 6159 remote_detach_1 (inf, from_tty);
de0d863e
DB
6160}
6161
6162/* Target follow-fork function for remote targets. On entry, and
6163 at return, the current inferior is the fork parent.
6164
6165 Note that although this is currently only used for extended-remote,
6166 it is named remote_follow_fork in anticipation of using it for the
6167 remote target as well. */
6168
e97007b6 6169void
82d1f134
SM
6170remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6171 target_waitkind fork_kind, bool follow_child,
6172 bool detach_fork)
de0d863e 6173{
82d1f134
SM
6174 process_stratum_target::follow_fork (child_inf, child_ptid,
6175 fork_kind, follow_child, detach_fork);
6176
ff52c073
CS
6177 if ((fork_kind == TARGET_WAITKIND_FORKED
6178 && m_features.remote_fork_event_p ())
6179 || (fork_kind == TARGET_WAITKIND_VFORKED
6180 && m_features.remote_vfork_event_p ()))
de0d863e
DB
6181 {
6182 /* When following the parent and detaching the child, we detach
6183 the child here. For the case of following the child and
6184 detaching the parent, the detach is done in the target-
6185 independent follow fork code in infrun.c. We can't use
6186 target_detach when detaching an unfollowed child because
6187 the client side doesn't know anything about the child. */
6188 if (detach_fork && !follow_child)
6189 {
6190 /* Detach the fork child. */
3a849a34 6191 remote_detach_pid (child_ptid.pid ());
de0d863e
DB
6192 }
6193 }
c906108c
SS
6194}
6195
94585166 6196/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
294c36eb 6197 in the program space of the new inferior. */
94585166 6198
f6ac5f3d 6199void
294c36eb
SM
6200remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6201 const char *execd_pathname)
94585166 6202{
294c36eb
SM
6203 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6204
94585166
DB
6205 /* We know that this is a target file name, so if it has the "target:"
6206 prefix we strip it off before saving it in the program space. */
6207 if (is_target_filename (execd_pathname))
6208 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6209
294c36eb 6210 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
94585166
DB
6211}
6212
6ad8ae5c
DJ
6213/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6214
f6ac5f3d
PA
6215void
6216remote_target::disconnect (const char *args, int from_tty)
43ff13b4 6217{
43ff13b4 6218 if (args)
2d717e4f 6219 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 6220
8020350c 6221 /* Make sure we unpush even the extended remote targets. Calling
5b6d1e4f
PA
6222 target_mourn_inferior won't unpush, and
6223 remote_target::mourn_inferior won't unpush if there is more than
6224 one inferior left. */
6225 remote_unpush_target (this);
2d717e4f 6226
43ff13b4 6227 if (from_tty)
0426ad51 6228 gdb_puts ("Ending remote debugging.\n");
43ff13b4
JM
6229}
6230
2d717e4f
DJ
6231/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6232 be chatty about it. */
6233
f6ac5f3d
PA
6234void
6235extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
6236{
6237 struct remote_state *rs = get_remote_state ();
be86555c 6238 int pid;
96ef3384 6239 char *wait_status = NULL;
2d717e4f 6240
74164c56 6241 pid = parse_pid_to_attach (args);
2d717e4f 6242
74164c56
JK
6243 /* Remote PID can be freely equal to getpid, do not check it here the same
6244 way as in other targets. */
2d717e4f 6245
ff52c073 6246 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
6247 error (_("This target does not support attaching to a process"));
6248
bc521517 6249 target_announce_attach (from_tty, pid);
7cee1e54 6250
8d64371b 6251 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f 6252 putpkt (rs->buf);
8d64371b 6253 getpkt (&rs->buf, 0);
2d717e4f 6254
ff52c073 6255 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
2d717e4f 6256 {
4082afcc 6257 case PACKET_OK:
6efcd9a8 6258 if (!target_is_non_stop_p ())
74531fed
PA
6259 {
6260 /* Save the reply for later. */
8d64371b
TT
6261 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6262 strcpy (wait_status, rs->buf.data ());
74531fed 6263 }
8d64371b 6264 else if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 6265 error (_("Attaching to %s failed with: %s"),
a068643d 6266 target_pid_to_str (ptid_t (pid)).c_str (),
8d64371b 6267 rs->buf.data ());
4082afcc
PA
6268 break;
6269 case PACKET_UNKNOWN:
6270 error (_("This target does not support attaching to a process"));
6271 default:
50fa3001
SDJ
6272 error (_("Attaching to %s failed"),
6273 target_pid_to_str (ptid_t (pid)).c_str ());
2d717e4f 6274 }
2d717e4f 6275
0ac55310 6276 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
bad34192 6277
f2907e49 6278 inferior_ptid = ptid_t (pid);
79d7f229 6279
6efcd9a8 6280 if (target_is_non_stop_p ())
bad34192 6281 {
bad34192 6282 /* Get list of threads. */
f6ac5f3d 6283 update_thread_list ();
82f73884 6284
0ac55310
PA
6285 thread_info *thread = first_thread_of_inferior (current_inferior ());
6286 if (thread != nullptr)
6287 switch_to_thread (thread);
bad34192
PA
6288
6289 /* Invalidate our notion of the remote current thread. */
47f8a51d 6290 record_currthread (rs, minus_one_ptid);
bad34192 6291 }
74531fed 6292 else
bad34192 6293 {
0ac55310
PA
6294 /* Now, if we have thread information, update the main thread's
6295 ptid. */
6296 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
bad34192 6297
b622494e
AB
6298 /* Add the main thread to the thread list. We add the thread
6299 silently in this case (the final true parameter). */
6300 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
0ac55310
PA
6301
6302 switch_to_thread (thr);
bad34192 6303 }
c0a2216e 6304
96ef3384
UW
6305 /* Next, if the target can specify a description, read it. We do
6306 this before anything involving memory or registers. */
6307 target_find_description ();
6308
6efcd9a8 6309 if (!target_is_non_stop_p ())
74531fed
PA
6310 {
6311 /* Use the previously fetched status. */
6312 gdb_assert (wait_status != NULL);
6313
4f626cad
AB
6314 struct notif_event *reply
6315 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 6316
4f626cad 6317 push_stop_reply ((struct stop_reply *) reply);
74531fed
PA
6318 }
6319 else
621cc310
PA
6320 {
6321 gdb_assert (wait_status == NULL);
6322
6323 gdb_assert (target_can_async_p ());
621cc310 6324 }
2d717e4f
DJ
6325}
6326
b9c1d481
AS
6327/* Implementation of the to_post_attach method. */
6328
f6ac5f3d
PA
6329void
6330extended_remote_target::post_attach (int pid)
b9c1d481 6331{
6efcd9a8
PA
6332 /* Get text, data & bss offsets. */
6333 get_offsets ();
6334
b9c1d481
AS
6335 /* In certain cases GDB might not have had the chance to start
6336 symbol lookup up until now. This could happen if the debugged
6337 binary is not using shared libraries, the vsyscall page is not
6338 present (on Linux) and the binary itself hadn't changed since the
6339 debugging process was started. */
a42d7dd8 6340 if (current_program_space->symfile_object_file != NULL)
b9c1d481
AS
6341 remote_check_symbols();
6342}
6343
c906108c 6344\f
506fb367
DJ
6345/* Check for the availability of vCont. This function should also check
6346 the response. */
c906108c 6347
6b8edb51
PA
6348void
6349remote_target::remote_vcont_probe ()
c906108c 6350{
6b8edb51 6351 remote_state *rs = get_remote_state ();
2e9f7625 6352 char *buf;
6d820c5c 6353
8d64371b 6354 strcpy (rs->buf.data (), "vCont?");
2e9f7625 6355 putpkt (rs->buf);
8d64371b
TT
6356 getpkt (&rs->buf, 0);
6357 buf = rs->buf.data ();
c906108c 6358
506fb367 6359 /* Make sure that the features we assume are supported. */
61012eef 6360 if (startswith (buf, "vCont"))
506fb367
DJ
6361 {
6362 char *p = &buf[5];
750ce8d1 6363 int support_c, support_C;
506fb367 6364
750ce8d1
YQ
6365 rs->supports_vCont.s = 0;
6366 rs->supports_vCont.S = 0;
506fb367
DJ
6367 support_c = 0;
6368 support_C = 0;
d458bd84 6369 rs->supports_vCont.t = 0;
c1e36e3e 6370 rs->supports_vCont.r = 0;
506fb367
DJ
6371 while (p && *p == ';')
6372 {
6373 p++;
6374 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6375 rs->supports_vCont.s = 1;
506fb367 6376 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6377 rs->supports_vCont.S = 1;
506fb367
DJ
6378 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6379 support_c = 1;
6380 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6381 support_C = 1;
74531fed 6382 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 6383 rs->supports_vCont.t = 1;
c1e36e3e
PA
6384 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6385 rs->supports_vCont.r = 1;
506fb367
DJ
6386
6387 p = strchr (p, ';');
6388 }
c906108c 6389
750ce8d1
YQ
6390 /* If c, and C are not all supported, we can't use vCont. Clearing
6391 BUF will make packet_ok disable the packet. */
6392 if (!support_c || !support_C)
506fb367
DJ
6393 buf[0] = 0;
6394 }
c906108c 6395
ff52c073 6396 m_features.packet_ok (rs->buf, PACKET_vCont);
5b6d1e4f 6397 rs->supports_vCont_probed = true;
506fb367 6398}
c906108c 6399
0d8f58ca
PA
6400/* Helper function for building "vCont" resumptions. Write a
6401 resumption to P. ENDP points to one-passed-the-end of the buffer
6402 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6403 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6404 resumed thread should be single-stepped and/or signalled. If PTID
6405 equals minus_one_ptid, then all threads are resumed; if PTID
d51926f0
PA
6406 represents a process, then all threads of the process are
6407 resumed. */
0d8f58ca 6408
6b8edb51
PA
6409char *
6410remote_target::append_resumption (char *p, char *endp,
6411 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
6412{
6413 struct remote_state *rs = get_remote_state ();
6414
a493e3e2 6415 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 6416 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
6417 else if (step
6418 /* GDB is willing to range step. */
6419 && use_range_stepping
6420 /* Target supports range stepping. */
6421 && rs->supports_vCont.r
6422 /* We don't currently support range stepping multiple
6423 threads with a wildcard (though the protocol allows it,
6424 so stubs shouldn't make an active effort to forbid
6425 it). */
ff52c073 6426 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
c1e36e3e
PA
6427 {
6428 struct thread_info *tp;
6429
d7e15655 6430 if (ptid == minus_one_ptid)
c1e36e3e
PA
6431 {
6432 /* If we don't know about the target thread's tid, then
6433 we're resuming magic_null_ptid (see caller). */
5b6d1e4f 6434 tp = find_thread_ptid (this, magic_null_ptid);
c1e36e3e
PA
6435 }
6436 else
5b6d1e4f 6437 tp = find_thread_ptid (this, ptid);
c1e36e3e
PA
6438 gdb_assert (tp != NULL);
6439
6440 if (tp->control.may_range_step)
6441 {
6442 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6443
6444 p += xsnprintf (p, endp - p, ";r%s,%s",
6445 phex_nz (tp->control.step_range_start,
6446 addr_size),
6447 phex_nz (tp->control.step_range_end,
6448 addr_size));
6449 }
6450 else
6451 p += xsnprintf (p, endp - p, ";s");
6452 }
0d8f58ca
PA
6453 else if (step)
6454 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6455 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6456 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6457 else
6458 p += xsnprintf (p, endp - p, ";c");
6459
ff52c073 6460 if (m_features.remote_multi_process_p () && ptid.is_pid ())
0d8f58ca
PA
6461 {
6462 ptid_t nptid;
6463
6464 /* All (-1) threads of process. */
184ea2f7 6465 nptid = ptid_t (ptid.pid (), -1);
0d8f58ca
PA
6466
6467 p += xsnprintf (p, endp - p, ":");
6468 p = write_ptid (p, endp, nptid);
6469 }
d7e15655 6470 else if (ptid != minus_one_ptid)
0d8f58ca
PA
6471 {
6472 p += xsnprintf (p, endp - p, ":");
6473 p = write_ptid (p, endp, ptid);
6474 }
6475
6476 return p;
6477}
6478
799a2abe
PA
6479/* Clear the thread's private info on resume. */
6480
6481static void
6482resume_clear_thread_private_info (struct thread_info *thread)
6483{
6484 if (thread->priv != NULL)
6485 {
7aabaf9d
SM
6486 remote_thread_info *priv = get_remote_thread_info (thread);
6487
6488 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6489 priv->watch_data_address = 0;
799a2abe
PA
6490 }
6491}
6492
e5ef252a
PA
6493/* Append a vCont continue-with-signal action for threads that have a
6494 non-zero stop signal. */
6495
6b8edb51
PA
6496char *
6497remote_target::append_pending_thread_resumptions (char *p, char *endp,
6498 ptid_t ptid)
e5ef252a 6499{
5b6d1e4f 6500 for (thread_info *thread : all_non_exited_threads (this, ptid))
08036331 6501 if (inferior_ptid != thread->ptid
1edb66d8 6502 && thread->stop_signal () != GDB_SIGNAL_0)
e5ef252a
PA
6503 {
6504 p = append_resumption (p, endp, thread->ptid,
1edb66d8
SM
6505 0, thread->stop_signal ());
6506 thread->set_stop_signal (GDB_SIGNAL_0);
799a2abe 6507 resume_clear_thread_private_info (thread);
e5ef252a
PA
6508 }
6509
6510 return p;
6511}
6512
7b68ffbb
PA
6513/* Set the target running, using the packets that use Hc
6514 (c/s/C/S). */
6515
6b8edb51
PA
6516void
6517remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6518 gdb_signal siggnal)
7b68ffbb
PA
6519{
6520 struct remote_state *rs = get_remote_state ();
7b68ffbb
PA
6521 char *buf;
6522
6523 rs->last_sent_signal = siggnal;
6524 rs->last_sent_step = step;
6525
6526 /* The c/s/C/S resume packets use Hc, so set the continue
6527 thread. */
d7e15655 6528 if (ptid == minus_one_ptid)
7b68ffbb
PA
6529 set_continue_thread (any_thread_ptid);
6530 else
6531 set_continue_thread (ptid);
6532
5b6d1e4f 6533 for (thread_info *thread : all_non_exited_threads (this))
7b68ffbb
PA
6534 resume_clear_thread_private_info (thread);
6535
8d64371b 6536 buf = rs->buf.data ();
6b8edb51 6537 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6538 {
6539 /* We don't pass signals to the target in reverse exec mode. */
6540 if (info_verbose && siggnal != GDB_SIGNAL_0)
6541 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6542 siggnal);
6543
ff52c073 6544 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
7b68ffbb 6545 error (_("Remote reverse-step not supported."));
ff52c073 6546 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
7b68ffbb
PA
6547 error (_("Remote reverse-continue not supported."));
6548
6549 strcpy (buf, step ? "bs" : "bc");
6550 }
6551 else if (siggnal != GDB_SIGNAL_0)
6552 {
6553 buf[0] = step ? 'S' : 'C';
6554 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6555 buf[2] = tohex (((int) siggnal) & 0xf);
6556 buf[3] = '\0';
6557 }
6558 else
6559 strcpy (buf, step ? "s" : "c");
6560
6561 putpkt (buf);
6562}
6563
d51926f0
PA
6564/* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6565 STEP, and SIGGNAL have the same meaning as in target_resume. This
6566 function returns non-zero iff it resumes the inferior.
44eaed12 6567
7b68ffbb
PA
6568 This function issues a strict subset of all possible vCont commands
6569 at the moment. */
44eaed12 6570
6b8edb51 6571int
d51926f0 6572remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6b8edb51 6573 enum gdb_signal siggnal)
506fb367
DJ
6574{
6575 struct remote_state *rs = get_remote_state ();
82f73884
PA
6576 char *p;
6577 char *endp;
44eaed12 6578
7b68ffbb 6579 /* No reverse execution actions defined for vCont. */
6b8edb51 6580 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6581 return 0;
6582
ff52c073 6583 if (m_features.packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6584 remote_vcont_probe ();
44eaed12 6585
ff52c073 6586 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6587 return 0;
44eaed12 6588
8d64371b
TT
6589 p = rs->buf.data ();
6590 endp = p + get_remote_packet_size ();
82f73884 6591
506fb367
DJ
6592 /* If we could generate a wider range of packets, we'd have to worry
6593 about overflowing BUF. Should there be a generic
6594 "multi-part-packet" packet? */
6595
0d8f58ca
PA
6596 p += xsnprintf (p, endp - p, "vCont");
6597
d51926f0 6598 if (scope_ptid == magic_null_ptid)
c906108c 6599 {
79d7f229
PA
6600 /* MAGIC_NULL_PTID means that we don't have any active threads,
6601 so we don't have any TID numbers the inferior will
6602 understand. Make sure to only send forms that do not specify
6603 a TID. */
a9cbf802 6604 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6605 }
d51926f0 6606 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
506fb367 6607 {
0d8f58ca
PA
6608 /* Resume all threads (of all processes, or of a single
6609 process), with preference for INFERIOR_PTID. This assumes
6610 inferior_ptid belongs to the set of all threads we are about
6611 to resume. */
a493e3e2 6612 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6613 {
0d8f58ca
PA
6614 /* Step inferior_ptid, with or without signal. */
6615 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6616 }
0d8f58ca 6617
e5ef252a
PA
6618 /* Also pass down any pending signaled resumption for other
6619 threads not the current. */
d51926f0 6620 p = append_pending_thread_resumptions (p, endp, scope_ptid);
e5ef252a 6621
0d8f58ca 6622 /* And continue others without a signal. */
d51926f0 6623 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6624 }
6625 else
506fb367 6626 {
d51926f0
PA
6627 /* Scheduler locking; resume only SCOPE_PTID. */
6628 append_resumption (p, endp, scope_ptid, step, siggnal);
506fb367 6629 }
c906108c 6630
8d64371b 6631 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
82f73884 6632 putpkt (rs->buf);
506fb367 6633
6efcd9a8 6634 if (target_is_non_stop_p ())
74531fed
PA
6635 {
6636 /* In non-stop, the stub replies to vCont with "OK". The stop
6637 reply will be reported asynchronously by means of a `%Stop'
6638 notification. */
8d64371b
TT
6639 getpkt (&rs->buf, 0);
6640 if (strcmp (rs->buf.data (), "OK") != 0)
6641 error (_("Unexpected vCont reply in non-stop mode: %s"),
6642 rs->buf.data ());
74531fed
PA
6643 }
6644
506fb367 6645 return 1;
c906108c 6646}
43ff13b4 6647
506fb367
DJ
6648/* Tell the remote machine to resume. */
6649
f6ac5f3d 6650void
d51926f0 6651remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
43ff13b4 6652{
d01949b6 6653 struct remote_state *rs = get_remote_state ();
43ff13b4 6654
85ad3aaf
PA
6655 /* When connected in non-stop mode, the core resumes threads
6656 individually. Resuming remote threads directly in target_resume
6657 would thus result in sending one packet per thread. Instead, to
6658 minimize roundtrip latency, here we just store the resume
c9d22089
SM
6659 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6660 resumption will be done in remote_target::commit_resume, where we'll be
6661 able to do vCont action coalescing. */
f6ac5f3d 6662 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6663 {
d51926f0
PA
6664 remote_thread_info *remote_thr
6665 = get_remote_thread_info (inferior_thread ());
7aabaf9d 6666
c9d22089
SM
6667 /* We don't expect the core to ask to resume an already resumed (from
6668 its point of view) thread. */
a6c11cbb 6669 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
c9d22089
SM
6670
6671 remote_thr->set_resumed_pending_vcont (step, siggnal);
d51926f0
PA
6672
6673 /* There's actually nothing that says that the core can't
6674 request a wildcard resume in non-stop mode, though. It's
6675 just that we know it doesn't currently, so we don't bother
6676 with it. */
6677 gdb_assert (scope_ptid == inferior_ptid);
85ad3aaf
PA
6678 return;
6679 }
6680
722247f1
YQ
6681 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6682 (explained in remote-notif.c:handle_notification) so
6683 remote_notif_process is not called. We need find a place where
6684 it is safe to start a 'vNotif' sequence. It is good to do it
6685 before resuming inferior, because inferior was stopped and no RSP
6686 traffic at that moment. */
6efcd9a8 6687 if (!target_is_non_stop_p ())
5965e028 6688 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6689
f6ac5f3d 6690 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6691
7b68ffbb 6692 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
d51926f0
PA
6693 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6694 remote_resume_with_hc (scope_ptid, step, siggnal);
43ff13b4 6695
c9d22089 6696 /* Update resumed state tracked by the remote target. */
d51926f0 6697 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
c9d22089
SM
6698 get_remote_thread_info (tp)->set_resumed ();
6699
e24a49d8
PA
6700 /* We've just told the target to resume. The remote server will
6701 wait for the inferior to stop, and then send a stop reply. In
6702 the mean time, we can't start another command/query ourselves
74531fed
PA
6703 because the stub wouldn't be ready to process it. This applies
6704 only to the base all-stop protocol, however. In non-stop (which
6705 only supports vCont), the stub replies with an "OK", and is
6706 immediate able to process further serial input. */
6efcd9a8 6707 if (!target_is_non_stop_p ())
74531fed 6708 rs->waiting_for_stop_reply = 1;
43ff13b4 6709}
85ad3aaf 6710
85ad3aaf
PA
6711/* Private per-inferior info for target remote processes. */
6712
089354bb 6713struct remote_inferior : public private_inferior
85ad3aaf
PA
6714{
6715 /* Whether we can send a wildcard vCont for this process. */
089354bb 6716 bool may_wildcard_vcont = true;
85ad3aaf
PA
6717};
6718
089354bb
SM
6719/* Get the remote private inferior data associated to INF. */
6720
6721static remote_inferior *
6722get_remote_inferior (inferior *inf)
6723{
6724 if (inf->priv == NULL)
6725 inf->priv.reset (new remote_inferior);
6726
98ed24fb 6727 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
089354bb
SM
6728}
6729
f5db4863 6730/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6731 outgoing packet buffer. This is used to send multiple vCont
6732 packets if we have more actions than would fit a single packet. */
6733
f5db4863 6734class vcont_builder
85ad3aaf 6735{
f5db4863 6736public:
6b8edb51
PA
6737 explicit vcont_builder (remote_target *remote)
6738 : m_remote (remote)
f5db4863
PA
6739 {
6740 restart ();
6741 }
6742
6743 void flush ();
6744 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6745
6746private:
6747 void restart ();
6748
6b8edb51
PA
6749 /* The remote target. */
6750 remote_target *m_remote;
6751
85ad3aaf
PA
6752 /* Pointer to the first action. P points here if no action has been
6753 appended yet. */
f5db4863 6754 char *m_first_action;
85ad3aaf
PA
6755
6756 /* Where the next action will be appended. */
f5db4863 6757 char *m_p;
85ad3aaf
PA
6758
6759 /* The end of the buffer. Must never write past this. */
f5db4863 6760 char *m_endp;
85ad3aaf
PA
6761};
6762
6763/* Prepare the outgoing buffer for a new vCont packet. */
6764
f5db4863
PA
6765void
6766vcont_builder::restart ()
85ad3aaf 6767{
6b8edb51 6768 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6769
8d64371b
TT
6770 m_p = rs->buf.data ();
6771 m_endp = m_p + m_remote->get_remote_packet_size ();
f5db4863
PA
6772 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6773 m_first_action = m_p;
85ad3aaf
PA
6774}
6775
6776/* If the vCont packet being built has any action, send it to the
6777 remote end. */
6778
f5db4863
PA
6779void
6780vcont_builder::flush ()
85ad3aaf
PA
6781{
6782 struct remote_state *rs;
6783
f5db4863 6784 if (m_p == m_first_action)
85ad3aaf
PA
6785 return;
6786
6b8edb51
PA
6787 rs = m_remote->get_remote_state ();
6788 m_remote->putpkt (rs->buf);
8d64371b
TT
6789 m_remote->getpkt (&rs->buf, 0);
6790 if (strcmp (rs->buf.data (), "OK") != 0)
6791 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
85ad3aaf
PA
6792}
6793
6794/* The largest action is range-stepping, with its two addresses. This
6795 is more than sufficient. If a new, bigger action is created, it'll
6796 quickly trigger a failed assertion in append_resumption (and we'll
6797 just bump this). */
6798#define MAX_ACTION_SIZE 200
6799
6800/* Append a new vCont action in the outgoing packet being built. If
6801 the action doesn't fit the packet along with previous actions, push
6802 what we've got so far to the remote end and start over a new vCont
6803 packet (with the new action). */
6804
f5db4863
PA
6805void
6806vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6807{
6808 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6809
6b8edb51
PA
6810 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6811 ptid, step, siggnal);
85ad3aaf
PA
6812
6813 /* Check whether this new action would fit in the vCont packet along
6814 with previous actions. If not, send what we've got so far and
6815 start a new vCont packet. */
f5db4863
PA
6816 size_t rsize = endp - buf;
6817 if (rsize > m_endp - m_p)
85ad3aaf 6818 {
f5db4863
PA
6819 flush ();
6820 restart ();
85ad3aaf
PA
6821
6822 /* Should now fit. */
f5db4863 6823 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6824 }
6825
f5db4863
PA
6826 memcpy (m_p, buf, rsize);
6827 m_p += rsize;
6828 *m_p = '\0';
85ad3aaf
PA
6829}
6830
6831/* to_commit_resume implementation. */
6832
f6ac5f3d 6833void
1192f124 6834remote_target::commit_resumed ()
85ad3aaf 6835{
85ad3aaf
PA
6836 /* If connected in all-stop mode, we'd send the remote resume
6837 request directly from remote_resume. Likewise if
6838 reverse-debugging, as there are no defined vCont actions for
6839 reverse execution. */
f6ac5f3d 6840 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6841 return;
6842
6843 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6844 instead of resuming all threads of each process individually.
6845 However, if any thread of a process must remain halted, we can't
6846 send wildcard resumes and must send one action per thread.
6847
6848 Care must be taken to not resume threads/processes the server
6849 side already told us are stopped, but the core doesn't know about
6850 yet, because the events are still in the vStopped notification
6851 queue. For example:
6852
6853 #1 => vCont s:p1.1;c
6854 #2 <= OK
6855 #3 <= %Stopped T05 p1.1
6856 #4 => vStopped
6857 #5 <= T05 p1.2
6858 #6 => vStopped
6859 #7 <= OK
6860 #8 (infrun handles the stop for p1.1 and continues stepping)
6861 #9 => vCont s:p1.1;c
6862
6863 The last vCont above would resume thread p1.2 by mistake, because
6864 the server has no idea that the event for p1.2 had not been
6865 handled yet.
6866
6867 The server side must similarly ignore resume actions for the
6868 thread that has a pending %Stopped notification (and any other
6869 threads with events pending), until GDB acks the notification
6870 with vStopped. Otherwise, e.g., the following case is
6871 mishandled:
6872
6873 #1 => g (or any other packet)
6874 #2 <= [registers]
6875 #3 <= %Stopped T05 p1.2
6876 #4 => vCont s:p1.1;c
6877 #5 <= OK
6878
6879 Above, the server must not resume thread p1.2. GDB can't know
6880 that p1.2 stopped until it acks the %Stopped notification, and
6881 since from GDB's perspective all threads should be running, it
6882 sends a "c" action.
6883
6884 Finally, special care must also be given to handling fork/vfork
6885 events. A (v)fork event actually tells us that two processes
6886 stopped -- the parent and the child. Until we follow the fork,
6887 we must not resume the child. Therefore, if we have a pending
6888 fork follow, we must not send a global wildcard resume action
6889 (vCont;c). We can still send process-wide wildcards though. */
6890
6891 /* Start by assuming a global wildcard (vCont;c) is possible. */
2f63ec5c 6892 bool may_global_wildcard_vcont = true;
85ad3aaf
PA
6893
6894 /* And assume every process is individually wildcard-able too. */
5b6d1e4f 6895 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6896 {
089354bb
SM
6897 remote_inferior *priv = get_remote_inferior (inf);
6898
6899 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6900 }
6901
6902 /* Check for any pending events (not reported or processed yet) and
6903 disable process and global wildcard resumes appropriately. */
6904 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6905
1192f124
SM
6906 bool any_pending_vcont_resume = false;
6907
5b6d1e4f 6908 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 6909 {
c9d22089
SM
6910 remote_thread_info *priv = get_remote_thread_info (tp);
6911
85ad3aaf
PA
6912 /* If a thread of a process is not meant to be resumed, then we
6913 can't wildcard that process. */
a6c11cbb 6914 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
85ad3aaf 6915 {
089354bb 6916 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6917
6918 /* And if we can't wildcard a process, we can't wildcard
6919 everything either. */
2f63ec5c 6920 may_global_wildcard_vcont = false;
85ad3aaf
PA
6921 continue;
6922 }
6923
1192f124
SM
6924 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6925 any_pending_vcont_resume = true;
6926
85ad3aaf
PA
6927 /* If a thread is the parent of an unfollowed fork, then we
6928 can't do a global wildcard, as that would resume the fork
6929 child. */
28561a65 6930 if (thread_pending_fork_status (tp) != nullptr)
2f63ec5c 6931 may_global_wildcard_vcont = false;
85ad3aaf
PA
6932 }
6933
1192f124
SM
6934 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6935 do. */
6936 if (!any_pending_vcont_resume)
6937 return;
6938
85ad3aaf
PA
6939 /* Now let's build the vCont packet(s). Actions must be appended
6940 from narrower to wider scopes (thread -> process -> global). If
6941 we end up with too many actions for a single packet vcont_builder
6942 flushes the current vCont packet to the remote side and starts a
6943 new one. */
6b8edb51 6944 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
6945
6946 /* Threads first. */
5b6d1e4f 6947 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 6948 {
7aabaf9d 6949 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf 6950
c9d22089
SM
6951 /* If the thread was previously vCont-resumed, no need to send a specific
6952 action for it. If we didn't receive a resume request for it, don't
6953 send an action for it either. */
a6c11cbb 6954 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
85ad3aaf
PA
6955 continue;
6956
6957 gdb_assert (!thread_is_in_step_over_chain (tp));
6958
1192f124
SM
6959 /* We should never be commit-resuming a thread that has a stop reply.
6960 Otherwise, we would end up reporting a stop event for a thread while
6961 it is running on the remote target. */
6962 remote_state *rs = get_remote_state ();
6963 for (const auto &stop_reply : rs->stop_reply_queue)
6964 gdb_assert (stop_reply->ptid != tp->ptid);
6965
c9d22089
SM
6966 const resumed_pending_vcont_info &info
6967 = remote_thr->resumed_pending_vcont_info ();
85ad3aaf 6968
c9d22089
SM
6969 /* Check if we need to send a specific action for this thread. If not,
6970 it will be included in a wildcard resume instead. */
6971 if (info.step || info.sig != GDB_SIGNAL_0
6972 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6973 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6974
6975 remote_thr->set_resumed ();
85ad3aaf
PA
6976 }
6977
6978 /* Now check whether we can send any process-wide wildcard. This is
6979 to avoid sending a global wildcard in the case nothing is
6980 supposed to be resumed. */
2f63ec5c 6981 bool any_process_wildcard = false;
85ad3aaf 6982
5b6d1e4f 6983 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6984 {
089354bb 6985 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6986 {
2f63ec5c 6987 any_process_wildcard = true;
85ad3aaf
PA
6988 break;
6989 }
6990 }
6991
6992 if (any_process_wildcard)
6993 {
6994 /* If all processes are wildcard-able, then send a single "c"
6995 action, otherwise, send an "all (-1) threads of process"
6996 continue action for each running process, if any. */
6997 if (may_global_wildcard_vcont)
6998 {
f5db4863
PA
6999 vcont_builder.push_action (minus_one_ptid,
7000 false, GDB_SIGNAL_0);
85ad3aaf
PA
7001 }
7002 else
7003 {
5b6d1e4f 7004 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 7005 {
089354bb 7006 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 7007 {
f2907e49 7008 vcont_builder.push_action (ptid_t (inf->pid),
f5db4863 7009 false, GDB_SIGNAL_0);
85ad3aaf
PA
7010 }
7011 }
7012 }
7013 }
7014
f5db4863 7015 vcont_builder.flush ();
85ad3aaf
PA
7016}
7017
b4b1a226
SM
7018/* Implementation of target_has_pending_events. */
7019
7020bool
7021remote_target::has_pending_events ()
7022{
7023 if (target_can_async_p ())
7024 {
7025 remote_state *rs = get_remote_state ();
7026
7027 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
7028 return true;
7029
7030 /* Note that BUFCNT can be negative, indicating sticky
7031 error. */
7032 if (rs->remote_desc->bufcnt != 0)
7033 return true;
7034 }
7035 return false;
7036}
7037
c906108c 7038\f
43ff13b4 7039
74531fed
PA
7040/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7041 thread, all threads of a remote process, or all threads of all
7042 processes. */
7043
6b8edb51
PA
7044void
7045remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
7046{
7047 struct remote_state *rs = get_remote_state ();
8d64371b
TT
7048 char *p = rs->buf.data ();
7049 char *endp = p + get_remote_packet_size ();
74531fed 7050
1192f124
SM
7051 /* If any thread that needs to stop was resumed but pending a vCont
7052 resume, generate a phony stop_reply. However, first check
7053 whether the thread wasn't resumed with a signal. Generating a
7054 phony stop in that case would result in losing the signal. */
7055 bool needs_commit = false;
7056 for (thread_info *tp : all_non_exited_threads (this, ptid))
7057 {
7058 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7059
7060 if (remote_thr->get_resume_state ()
7061 == resume_state::RESUMED_PENDING_VCONT)
7062 {
7063 const resumed_pending_vcont_info &info
7064 = remote_thr->resumed_pending_vcont_info ();
7065 if (info.sig != GDB_SIGNAL_0)
7066 {
7067 /* This signal must be forwarded to the inferior. We
7068 could commit-resume just this thread, but its simpler
7069 to just commit-resume everything. */
7070 needs_commit = true;
7071 break;
7072 }
7073 }
7074 }
7075
7076 if (needs_commit)
7077 commit_resumed ();
7078 else
7079 for (thread_info *tp : all_non_exited_threads (this, ptid))
7080 {
7081 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7082
7083 if (remote_thr->get_resume_state ()
7084 == resume_state::RESUMED_PENDING_VCONT)
7085 {
7086 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
96bbe3ef
TT
7087 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7088 tp->ptid.lwp (),
7089 pulongest (tp->ptid.tid ()));
1192f124
SM
7090
7091 /* Check that the thread wasn't resumed with a signal.
7092 Generating a phony stop would result in losing the
7093 signal. */
7094 const resumed_pending_vcont_info &info
7095 = remote_thr->resumed_pending_vcont_info ();
7096 gdb_assert (info.sig == GDB_SIGNAL_0);
7097
7098 stop_reply *sr = new stop_reply ();
7099 sr->ptid = tp->ptid;
7100 sr->rs = rs;
183be222 7101 sr->ws.set_stopped (GDB_SIGNAL_0);
1192f124
SM
7102 sr->arch = tp->inf->gdbarch;
7103 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7104 sr->watch_data_address = 0;
7105 sr->core = 0;
7106 this->push_stop_reply (sr);
7107
7108 /* Pretend that this thread was actually resumed on the
7109 remote target, then stopped. If we leave it in the
7110 RESUMED_PENDING_VCONT state and the commit_resumed
7111 method is called while the stop reply is still in the
7112 queue, we'll end up reporting a stop event to the core
7113 for that thread while it is running on the remote
7114 target... that would be bad. */
7115 remote_thr->set_resumed ();
7116 }
7117 }
7118
5b6d1e4f
PA
7119 /* FIXME: This supports_vCont_probed check is a workaround until
7120 packet_support is per-connection. */
ff52c073 7121 if (m_features.packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
5b6d1e4f 7122 || !rs->supports_vCont_probed)
6b8edb51 7123 remote_vcont_probe ();
74531fed 7124
d458bd84 7125 if (!rs->supports_vCont.t)
74531fed
PA
7126 error (_("Remote server does not support stopping threads"));
7127
d7e15655 7128 if (ptid == minus_one_ptid
ff52c073 7129 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
74531fed
PA
7130 p += xsnprintf (p, endp - p, "vCont;t");
7131 else
7132 {
7133 ptid_t nptid;
7134
74531fed
PA
7135 p += xsnprintf (p, endp - p, "vCont;t:");
7136
0e998d96 7137 if (ptid.is_pid ())
74531fed 7138 /* All (-1) threads of process. */
184ea2f7 7139 nptid = ptid_t (ptid.pid (), -1);
74531fed
PA
7140 else
7141 {
7142 /* Small optimization: if we already have a stop reply for
7143 this thread, no use in telling the stub we want this
7144 stopped. */
7145 if (peek_stop_reply (ptid))
7146 return;
7147
7148 nptid = ptid;
7149 }
7150
a9cbf802 7151 write_ptid (p, endp, nptid);
74531fed
PA
7152 }
7153
7154 /* In non-stop, we get an immediate OK reply. The stop reply will
7155 come in asynchronously by notification. */
7156 putpkt (rs->buf);
8d64371b
TT
7157 getpkt (&rs->buf, 0);
7158 if (strcmp (rs->buf.data (), "OK") != 0)
a068643d 7159 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
8d64371b 7160 rs->buf.data ());
74531fed
PA
7161}
7162
bfedc46a
PA
7163/* All-stop version of target_interrupt. Sends a break or a ^C to
7164 interrupt the remote target. It is undefined which thread of which
7165 process reports the interrupt. */
74531fed 7166
6b8edb51
PA
7167void
7168remote_target::remote_interrupt_as ()
74531fed
PA
7169{
7170 struct remote_state *rs = get_remote_state ();
7171
3a29589a
DJ
7172 rs->ctrlc_pending_p = 1;
7173
74531fed 7174 /* If the inferior is stopped already, but the core didn't know
4f626cad 7175 about it yet, just ignore the request. The pending stop events
74531fed 7176 will be collected in remote_wait. */
4f626cad 7177 if (stop_reply_queue_length () > 0)
74531fed
PA
7178 return;
7179
9a7071a8
JB
7180 /* Send interrupt_sequence to remote target. */
7181 send_interrupt_sequence ();
74531fed
PA
7182}
7183
de979965
PA
7184/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7185 the remote target. It is undefined which thread of which process
e42de8c7
PA
7186 reports the interrupt. Throws an error if the packet is not
7187 supported by the server. */
de979965 7188
6b8edb51
PA
7189void
7190remote_target::remote_interrupt_ns ()
de979965
PA
7191{
7192 struct remote_state *rs = get_remote_state ();
8d64371b
TT
7193 char *p = rs->buf.data ();
7194 char *endp = p + get_remote_packet_size ();
de979965
PA
7195
7196 xsnprintf (p, endp - p, "vCtrlC");
7197
7198 /* In non-stop, we get an immediate OK reply. The stop reply will
7199 come in asynchronously by notification. */
7200 putpkt (rs->buf);
8d64371b 7201 getpkt (&rs->buf, 0);
de979965 7202
ff52c073 7203 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
de979965
PA
7204 {
7205 case PACKET_OK:
7206 break;
7207 case PACKET_UNKNOWN:
e42de8c7 7208 error (_("No support for interrupting the remote target."));
de979965 7209 case PACKET_ERROR:
8d64371b 7210 error (_("Interrupting target failed: %s"), rs->buf.data ());
de979965 7211 }
de979965
PA
7212}
7213
bfedc46a 7214/* Implement the to_stop function for the remote targets. */
74531fed 7215
f6ac5f3d
PA
7216void
7217remote_target::stop (ptid_t ptid)
c906108c 7218{
2189c312 7219 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
c906108c 7220
6efcd9a8 7221 if (target_is_non_stop_p ())
74531fed 7222 remote_stop_ns (ptid);
c906108c 7223 else
bfedc46a
PA
7224 {
7225 /* We don't currently have a way to transparently pause the
7226 remote target in all-stop mode. Interrupt it instead. */
de979965 7227 remote_interrupt_as ();
bfedc46a
PA
7228 }
7229}
7230
7231/* Implement the to_interrupt function for the remote targets. */
7232
f6ac5f3d
PA
7233void
7234remote_target::interrupt ()
bfedc46a 7235{
2189c312 7236 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
bfedc46a 7237
e42de8c7
PA
7238 if (target_is_non_stop_p ())
7239 remote_interrupt_ns ();
bfedc46a 7240 else
e42de8c7 7241 remote_interrupt_as ();
c906108c
SS
7242}
7243
93692b58
PA
7244/* Implement the to_pass_ctrlc function for the remote targets. */
7245
f6ac5f3d
PA
7246void
7247remote_target::pass_ctrlc ()
93692b58 7248{
2189c312 7249 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
93692b58 7250
2189c312 7251 struct remote_state *rs = get_remote_state ();
93692b58
PA
7252
7253 /* If we're starting up, we're not fully synced yet. Quit
7254 immediately. */
7255 if (rs->starting_up)
7256 quit ();
7257 /* If ^C has already been sent once, offer to disconnect. */
7258 else if (rs->ctrlc_pending_p)
7259 interrupt_query ();
7260 else
e671cd59 7261 target_interrupt ();
93692b58
PA
7262}
7263
c906108c
SS
7264/* Ask the user what to do when an interrupt is received. */
7265
6b8edb51
PA
7266void
7267remote_target::interrupt_query ()
c906108c 7268{
abc56d60 7269 struct remote_state *rs = get_remote_state ();
c906108c 7270
abc56d60 7271 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 7272 {
abc56d60
PA
7273 if (query (_("The target is not responding to interrupt requests.\n"
7274 "Stop debugging it? ")))
74531fed 7275 {
5b6d1e4f 7276 remote_unpush_target (this);
abc56d60 7277 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
7278 }
7279 }
abc56d60
PA
7280 else
7281 {
7282 if (query (_("Interrupted while waiting for the program.\n"
7283 "Give up waiting? ")))
7284 quit ();
7285 }
c906108c
SS
7286}
7287
6426a772
JM
7288/* Enable/disable target terminal ownership. Most targets can use
7289 terminal groups to control terminal ownership. Remote targets are
7290 different in that explicit transfer of ownership to/from GDB/target
23860348 7291 is required. */
6426a772 7292
f6ac5f3d
PA
7293void
7294remote_target::terminal_inferior ()
6426a772 7295{
6426a772
JM
7296 /* NOTE: At this point we could also register our selves as the
7297 recipient of all input. Any characters typed could then be
23860348 7298 passed on down to the target. */
6426a772
JM
7299}
7300
f6ac5f3d
PA
7301void
7302remote_target::terminal_ours ()
6426a772 7303{
6426a772
JM
7304}
7305
176a6961 7306static void
05be00a8 7307remote_console_output (const char *msg)
c906108c 7308{
05be00a8 7309 const char *p;
c906108c 7310
c5aa993b 7311 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
7312 {
7313 char tb[2];
7314 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 7315
c906108c
SS
7316 tb[0] = c;
7317 tb[1] = 0;
da5bd37e 7318 gdb_stdtarg->puts (tb);
c906108c 7319 }
da5bd37e 7320 gdb_stdtarg->flush ();
00db5b94 7321}
74531fed 7322
221e1a37
PA
7323/* Return the length of the stop reply queue. */
7324
6b8edb51
PA
7325int
7326remote_target::stop_reply_queue_length ()
221e1a37 7327{
6b8edb51 7328 remote_state *rs = get_remote_state ();
953edf2b 7329 return rs->stop_reply_queue.size ();
221e1a37
PA
7330}
7331
cb8c24b6 7332static void
6b8edb51 7333remote_notif_stop_parse (remote_target *remote,
42938c1a 7334 const notif_client *self, const char *buf,
722247f1
YQ
7335 struct notif_event *event)
7336{
6b8edb51 7337 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
7338}
7339
7340static void
6b8edb51 7341remote_notif_stop_ack (remote_target *remote,
42938c1a 7342 const notif_client *self, const char *buf,
722247f1
YQ
7343 struct notif_event *event)
7344{
7345 struct stop_reply *stop_reply = (struct stop_reply *) event;
7346
7347 /* acknowledge */
6b8edb51 7348 putpkt (remote, self->ack_command);
722247f1 7349
b0083dd7
PA
7350 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7351 the notification. It was left in the queue because we need to
7352 acknowledge it and pull the rest of the notifications out. */
183be222 7353 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
b0083dd7 7354 remote->push_stop_reply (stop_reply);
722247f1
YQ
7355}
7356
7357static int
6b8edb51 7358remote_notif_stop_can_get_pending_events (remote_target *remote,
42938c1a 7359 const notif_client *self)
722247f1
YQ
7360{
7361 /* We can't get pending events in remote_notif_process for
7362 notification stop, and we have to do this in remote_wait_ns
7363 instead. If we fetch all queued events from stub, remote stub
7364 may exit and we have no chance to process them back in
7365 remote_wait_ns. */
6b8edb51
PA
7366 remote_state *rs = remote->get_remote_state ();
7367 mark_async_event_handler (rs->remote_async_inferior_event_token);
722247f1
YQ
7368 return 0;
7369}
7370
32603266 7371stop_reply::~stop_reply ()
722247f1 7372{
32603266
TT
7373 for (cached_reg_t &reg : regcache)
7374 xfree (reg.data);
722247f1
YQ
7375}
7376
32603266
TT
7377static notif_event_up
7378remote_notif_stop_alloc_reply ()
722247f1 7379{
32603266 7380 return notif_event_up (new struct stop_reply ());
722247f1
YQ
7381}
7382
7383/* A client of notification Stop. */
7384
42938c1a 7385const notif_client notif_client_stop =
722247f1
YQ
7386{
7387 "Stop",
7388 "vStopped",
7389 remote_notif_stop_parse,
7390 remote_notif_stop_ack,
7391 remote_notif_stop_can_get_pending_events,
7392 remote_notif_stop_alloc_reply,
f48ff2a7 7393 REMOTE_NOTIF_STOP,
722247f1
YQ
7394};
7395
cbb8991c
DB
7396/* If CONTEXT contains any fork child threads that have not been
7397 reported yet, remove them from the CONTEXT list. If such a
7398 thread exists it is because we are stopped at a fork catchpoint
7399 and have not yet called follow_fork, which will set up the
7400 host-side data structures for the new process. */
7401
6b8edb51
PA
7402void
7403remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c 7404{
42938c1a 7405 const notif_client *notif = &notif_client_stop;
cbb8991c
DB
7406
7407 /* For any threads stopped at a fork event, remove the corresponding
7408 fork child threads from the CONTEXT list. */
5b6d1e4f 7409 for (thread_info *thread : all_non_exited_threads (this))
cbb8991c 7410 {
28561a65
SM
7411 const target_waitstatus *ws = thread_pending_fork_status (thread);
7412
7413 if (ws == nullptr)
7414 continue;
cbb8991c 7415
28561a65 7416 context->remove_thread (ws->child_ptid ());
cbb8991c
DB
7417 }
7418
7419 /* Check for any pending fork events (not reported or processed yet)
7420 in process PID and remove those fork child threads from the
7421 CONTEXT list as well. */
7422 remote_notif_get_pending_events (notif);
953edf2b 7423 for (auto &event : get_remote_state ()->stop_reply_queue)
183be222 7424 if (event->ws.kind () == TARGET_WAITKIND_FORKED
3890f02a 7425 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
183be222 7426 context->remove_thread (event->ws.child_ptid ());
3890f02a
SM
7427 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7428 context->remove_thread (event->ptid);
85ad3aaf
PA
7429}
7430
2f63ec5c
AB
7431/* Check whether any event pending in the vStopped queue would prevent a
7432 global or process wildcard vCont action. Set *may_global_wildcard to
7433 false if we can't do a global wildcard (vCont;c), and clear the event
7434 inferior's may_wildcard_vcont flag if we can't do a process-wide
7435 wildcard resume (vCont;c:pPID.-1). */
85ad3aaf 7436
6b8edb51
PA
7437void
7438remote_target::check_pending_events_prevent_wildcard_vcont
2f63ec5c 7439 (bool *may_global_wildcard)
85ad3aaf 7440{
42938c1a 7441 const notif_client *notif = &notif_client_stop;
85ad3aaf
PA
7442
7443 remote_notif_get_pending_events (notif);
953edf2b
TT
7444 for (auto &event : get_remote_state ()->stop_reply_queue)
7445 {
183be222
SM
7446 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7447 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
953edf2b 7448 continue;
85ad3aaf 7449
183be222
SM
7450 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7451 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
2f63ec5c 7452 *may_global_wildcard = false;
722247f1 7453
953edf2b
TT
7454 /* This may be the first time we heard about this process.
7455 Regardless, we must not do a global wildcard resume, otherwise
7456 we'd resume this process too. */
2f63ec5c 7457 *may_global_wildcard = false;
323fd5b9
PA
7458 if (event->ptid != null_ptid)
7459 {
7460 inferior *inf = find_inferior_ptid (this, event->ptid);
7461 if (inf != NULL)
7462 get_remote_inferior (inf)->may_wildcard_vcont = false;
7463 }
722247f1 7464 }
722247f1
YQ
7465}
7466
f48ff2a7 7467/* Discard all pending stop replies of inferior INF. */
c906108c 7468
6b8edb51
PA
7469void
7470remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7471{
f48ff2a7
YQ
7472 struct stop_reply *reply;
7473 struct remote_state *rs = get_remote_state ();
7474 struct remote_notif_state *rns = rs->notif_state;
7475
7476 /* This function can be notified when an inferior exists. When the
7477 target is not remote, the notification state is NULL. */
7478 if (rs->remote_desc == NULL)
7479 return;
7480
7481 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7482
74531fed 7483 /* Discard the in-flight notification. */
e99b03dc 7484 if (reply != NULL && reply->ptid.pid () == inf->pid)
74531fed 7485 {
b0083dd7
PA
7486 /* Leave the notification pending, since the server expects that
7487 we acknowledge it with vStopped. But clear its contents, so
7488 that later on when we acknowledge it, we also discard it. */
df5ad102
SM
7489 remote_debug_printf
7490 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7491 reply->ptid.to_string().c_str(),
7492 reply->ws.to_string ().c_str ());
183be222 7493 reply->ws.set_ignore ();
74531fed 7494 }
c906108c 7495
74531fed
PA
7496 /* Discard the stop replies we have already pulled with
7497 vStopped. */
953edf2b
TT
7498 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7499 rs->stop_reply_queue.end (),
7500 [=] (const stop_reply_up &event)
7501 {
7502 return event->ptid.pid () == inf->pid;
7503 });
df5ad102
SM
7504 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7505 remote_debug_printf
7506 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7507 reply->ptid.to_string().c_str(),
7508 reply->ws.to_string ().c_str ());
953edf2b 7509 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
bcc75809
YQ
7510}
7511
7512/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7513
6b8edb51
PA
7514void
7515remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7516{
6b8edb51 7517 remote_state *rs = get_remote_state ();
f48ff2a7 7518
f48ff2a7
YQ
7519 /* Discard the stop replies we have already pulled with
7520 vStopped. */
953edf2b
TT
7521 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7522 rs->stop_reply_queue.end (),
7523 [=] (const stop_reply_up &event)
7524 {
7525 return event->rs == rs;
7526 });
7527 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
74531fed 7528}
43ff13b4 7529
722247f1
YQ
7530/* Remove the first reply in 'stop_reply_queue' which matches
7531 PTID. */
2e9f7625 7532
6b8edb51
PA
7533struct stop_reply *
7534remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7535{
953edf2b 7536 remote_state *rs = get_remote_state ();
722247f1 7537
953edf2b
TT
7538 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7539 rs->stop_reply_queue.end (),
7540 [=] (const stop_reply_up &event)
7541 {
7542 return event->ptid.matches (ptid);
7543 });
7544 struct stop_reply *result;
7545 if (iter == rs->stop_reply_queue.end ())
7546 result = nullptr;
7547 else
7548 {
7549 result = iter->release ();
7550 rs->stop_reply_queue.erase (iter);
7551 }
722247f1 7552
722247f1 7553 if (notif_debug)
6cb06a8c
TT
7554 gdb_printf (gdb_stdlog,
7555 "notif: discard queued event: 'Stop' in %s\n",
7556 ptid.to_string ().c_str ());
a744cf53 7557
953edf2b 7558 return result;
74531fed 7559}
75c99385 7560
74531fed
PA
7561/* Look for a queued stop reply belonging to PTID. If one is found,
7562 remove it from the queue, and return it. Returns NULL if none is
7563 found. If there are still queued events left to process, tell the
7564 event loop to get back to target_wait soon. */
e24a49d8 7565
6b8edb51
PA
7566struct stop_reply *
7567remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7568{
953edf2b 7569 remote_state *rs = get_remote_state ();
722247f1 7570 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7571
4f626cad 7572 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
6b8edb51 7573 {
6b8edb51
PA
7574 /* There's still at least an event left. */
7575 mark_async_event_handler (rs->remote_async_inferior_event_token);
7576 }
74531fed 7577
722247f1 7578 return r;
74531fed
PA
7579}
7580
7581/* Push a fully parsed stop reply in the stop reply queue. Since we
7582 know that we now have at least one queued event left to pass to the
7583 core side, tell the event loop to get back to target_wait soon. */
7584
6b8edb51
PA
7585void
7586remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7587{
6b8edb51 7588 remote_state *rs = get_remote_state ();
953edf2b 7589 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
74531fed 7590
722247f1 7591 if (notif_debug)
6cb06a8c
TT
7592 gdb_printf (gdb_stdlog,
7593 "notif: push 'Stop' %s to queue %d\n",
7594 new_event->ptid.to_string ().c_str (),
7595 int (rs->stop_reply_queue.size ()));
74531fed 7596
4f626cad
AB
7597 /* Mark the pending event queue only if async mode is currently enabled.
7598 If async mode is not currently enabled, then, if it later becomes
7599 enabled, and there are events in this queue, we will mark the event
7600 token at that point, see remote_target::async. */
7601 if (target_is_async_p ())
7602 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
7603}
7604
7605/* Returns true if we have a stop reply for PTID. */
7606
6b8edb51
PA
7607int
7608remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7609{
6b8edb51 7610 remote_state *rs = get_remote_state ();
953edf2b
TT
7611 for (auto &event : rs->stop_reply_queue)
7612 if (ptid == event->ptid
183be222 7613 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
953edf2b
TT
7614 return 1;
7615 return 0;
74531fed
PA
7616}
7617
26d56a93
SL
7618/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7619 starting with P and ending with PEND matches PREFIX. */
7620
7621static int
7622strprefix (const char *p, const char *pend, const char *prefix)
7623{
7624 for ( ; p < pend; p++, prefix++)
7625 if (*p != *prefix)
7626 return 0;
7627 return *prefix == '\0';
7628}
7629
74531fed
PA
7630/* Parse the stop reply in BUF. Either the function succeeds, and the
7631 result is stored in EVENT, or throws an error. */
7632
6b8edb51 7633void
bb277751 7634remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
74531fed 7635{
5cd63fda 7636 remote_arch_state *rsa = NULL;
74531fed 7637 ULONGEST addr;
256642e8 7638 const char *p;
94585166 7639 int skipregs = 0;
74531fed
PA
7640
7641 event->ptid = null_ptid;
bcc75809 7642 event->rs = get_remote_state ();
183be222 7643 event->ws.set_ignore ();
f7e6eed5 7644 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
32603266 7645 event->regcache.clear ();
dc146f7c 7646 event->core = -1;
74531fed
PA
7647
7648 switch (buf[0])
7649 {
7650 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7651 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7652 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7653 ss = signal number
7654 n... = register number
7655 r... = register contents
7656 */
7657
7658 p = &buf[3]; /* after Txx */
7659 while (*p)
7660 {
256642e8 7661 const char *p1;
cea39f65 7662 int fieldsize;
43ff13b4 7663
1f10ba14
PA
7664 p1 = strchr (p, ':');
7665 if (p1 == NULL)
7666 error (_("Malformed packet(a) (missing colon): %s\n\
7667Packet: '%s'\n"),
7668 p, buf);
7669 if (p == p1)
7670 error (_("Malformed packet(a) (missing register number): %s\n\
7671Packet: '%s'\n"),
7672 p, buf);
3c3bea1c 7673
1f10ba14
PA
7674 /* Some "registers" are actually extended stop information.
7675 Note if you're adding a new entry here: GDB 7.9 and
7676 earlier assume that all register "numbers" that start
7677 with an hex digit are real register numbers. Make sure
7678 the server only sends such a packet if it knows the
7679 client understands it. */
c8e38a49 7680
26d56a93 7681 if (strprefix (p, p1, "thread"))
1f10ba14 7682 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7683 else if (strprefix (p, p1, "syscall_entry"))
7684 {
7685 ULONGEST sysno;
7686
82075af2 7687 p = unpack_varlen_hex (++p1, &sysno);
183be222 7688 event->ws.set_syscall_entry ((int) sysno);
82075af2
JS
7689 }
7690 else if (strprefix (p, p1, "syscall_return"))
7691 {
7692 ULONGEST sysno;
7693
82075af2 7694 p = unpack_varlen_hex (++p1, &sysno);
183be222 7695 event->ws.set_syscall_return ((int) sysno);
82075af2 7696 }
26d56a93
SL
7697 else if (strprefix (p, p1, "watch")
7698 || strprefix (p, p1, "rwatch")
7699 || strprefix (p, p1, "awatch"))
cea39f65 7700 {
f7e6eed5 7701 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7702 p = unpack_varlen_hex (++p1, &addr);
7703 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7704 }
26d56a93 7705 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7706 {
7707 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7708
7709 /* Make sure the stub doesn't forget to indicate support
7710 with qSupported. */
ff52c073
CS
7711 if (m_features.packet_support (PACKET_swbreak_feature)
7712 != PACKET_ENABLE)
f7e6eed5
PA
7713 error (_("Unexpected swbreak stop reason"));
7714
7715 /* The value part is documented as "must be empty",
7716 though we ignore it, in case we ever decide to make
7717 use of it in a backward compatible way. */
8424cc97 7718 p = strchrnul (p1 + 1, ';');
f7e6eed5 7719 }
26d56a93 7720 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7721 {
7722 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7723
7724 /* Make sure the stub doesn't forget to indicate support
7725 with qSupported. */
ff52c073
CS
7726 if (m_features.packet_support (PACKET_hwbreak_feature)
7727 != PACKET_ENABLE)
f7e6eed5
PA
7728 error (_("Unexpected hwbreak stop reason"));
7729
7730 /* See above. */
8424cc97 7731 p = strchrnul (p1 + 1, ';');
f7e6eed5 7732 }
26d56a93 7733 else if (strprefix (p, p1, "library"))
cea39f65 7734 {
183be222 7735 event->ws.set_loaded ();
8424cc97 7736 p = strchrnul (p1 + 1, ';');
1f10ba14 7737 }
26d56a93 7738 else if (strprefix (p, p1, "replaylog"))
1f10ba14 7739 {
183be222 7740 event->ws.set_no_history ();
1f10ba14
PA
7741 /* p1 will indicate "begin" or "end", but it makes
7742 no difference for now, so ignore it. */
8424cc97 7743 p = strchrnul (p1 + 1, ';');
1f10ba14 7744 }
26d56a93 7745 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7746 {
7747 ULONGEST c;
a744cf53 7748
1f10ba14
PA
7749 p = unpack_varlen_hex (++p1, &c);
7750 event->core = c;
cea39f65 7751 }
26d56a93 7752 else if (strprefix (p, p1, "fork"))
183be222 7753 event->ws.set_forked (read_ptid (++p1, &p));
26d56a93 7754 else if (strprefix (p, p1, "vfork"))
183be222 7755 event->ws.set_vforked (read_ptid (++p1, &p));
26d56a93 7756 else if (strprefix (p, p1, "vforkdone"))
c269dbdb 7757 {
183be222 7758 event->ws.set_vfork_done ();
8424cc97 7759 p = strchrnul (p1 + 1, ';');
c269dbdb 7760 }
6ab24463 7761 else if (strprefix (p, p1, "exec"))
94585166
DB
7762 {
7763 ULONGEST ignored;
94585166
DB
7764 int pathlen;
7765
7766 /* Determine the length of the execd pathname. */
7767 p = unpack_varlen_hex (++p1, &ignored);
7768 pathlen = (p - p1) / 2;
7769
7770 /* Save the pathname for event reporting and for
7771 the next run command. */
183be222 7772 gdb::unique_xmalloc_ptr<char> pathname
c6321f19
TT
7773 ((char *) xmalloc (pathlen + 1));
7774 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
183be222 7775 pathname.get ()[pathlen] = '\0';
94585166
DB
7776
7777 /* This is freed during event handling. */
183be222 7778 event->ws.set_execd (std::move (pathname));
94585166
DB
7779
7780 /* Skip the registers included in this packet, since
7781 they may be for an architecture different from the
7782 one used by the original program. */
7783 skipregs = 1;
7784 }
65706a29
PA
7785 else if (strprefix (p, p1, "create"))
7786 {
183be222 7787 event->ws.set_thread_created ();
8424cc97 7788 p = strchrnul (p1 + 1, ';');
65706a29 7789 }
cea39f65
MS
7790 else
7791 {
1f10ba14 7792 ULONGEST pnum;
256642e8 7793 const char *p_temp;
1f10ba14 7794
94585166
DB
7795 if (skipregs)
7796 {
8424cc97 7797 p = strchrnul (p1 + 1, ';');
94585166
DB
7798 p++;
7799 continue;
7800 }
7801
1f10ba14
PA
7802 /* Maybe a real ``P'' register number. */
7803 p_temp = unpack_varlen_hex (p, &pnum);
7804 /* If the first invalid character is the colon, we got a
7805 register number. Otherwise, it's an unknown stop
7806 reason. */
7807 if (p_temp == p1)
7808 {
5cd63fda
PA
7809 /* If we haven't parsed the event's thread yet, find
7810 it now, in order to find the architecture of the
7811 reported expedited registers. */
7812 if (event->ptid == null_ptid)
7813 {
24ed6739
AB
7814 /* If there is no thread-id information then leave
7815 the event->ptid as null_ptid. Later in
7816 process_stop_reply we will pick a suitable
7817 thread. */
5cd63fda
PA
7818 const char *thr = strstr (p1 + 1, ";thread:");
7819 if (thr != NULL)
7820 event->ptid = read_ptid (thr + strlen (";thread:"),
7821 NULL);
5cd63fda
PA
7822 }
7823
7824 if (rsa == NULL)
7825 {
5b6d1e4f
PA
7826 inferior *inf
7827 = (event->ptid == null_ptid
7828 ? NULL
7829 : find_inferior_ptid (this, event->ptid));
5cd63fda
PA
7830 /* If this is the first time we learn anything
7831 about this process, skip the registers
7832 included in this packet, since we don't yet
7833 know which architecture to use to parse them.
7834 We'll determine the architecture later when
7835 we process the stop reply and retrieve the
7836 target description, via
7837 remote_notice_new_inferior ->
7838 post_create_inferior. */
7839 if (inf == NULL)
7840 {
7841 p = strchrnul (p1 + 1, ';');
7842 p++;
7843 continue;
7844 }
7845
7846 event->arch = inf->gdbarch;
9d6eea31 7847 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7848 }
7849
7850 packet_reg *reg
7851 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7852 cached_reg_t cached_reg;
43ff13b4 7853
1f10ba14
PA
7854 if (reg == NULL)
7855 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7856Packet: '%s'\n"),
1f10ba14 7857 hex_string (pnum), p, buf);
c8e38a49 7858
1f10ba14 7859 cached_reg.num = reg->regnum;
d1dff226 7860 cached_reg.data = (gdb_byte *)
5cd63fda 7861 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7862
1f10ba14
PA
7863 p = p1 + 1;
7864 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7865 register_size (event->arch, reg->regnum));
1f10ba14 7866 p += 2 * fieldsize;
5cd63fda 7867 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7868 warning (_("Remote reply is too short: %s"), buf);
74531fed 7869
32603266 7870 event->regcache.push_back (cached_reg);
1f10ba14
PA
7871 }
7872 else
7873 {
7874 /* Not a number. Silently skip unknown optional
7875 info. */
8424cc97 7876 p = strchrnul (p1 + 1, ';');
1f10ba14 7877 }
cea39f65 7878 }
c8e38a49 7879
cea39f65
MS
7880 if (*p != ';')
7881 error (_("Remote register badly formatted: %s\nhere: %s"),
7882 buf, p);
7883 ++p;
7884 }
5b5596ff 7885
183be222 7886 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
5b5596ff
PA
7887 break;
7888
c8e38a49
PA
7889 /* fall through */
7890 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7891 {
7892 int sig;
7893
3a09da41
PA
7894 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7895 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
183be222 7896 event->ws.set_stopped ((enum gdb_signal) sig);
3a09da41 7897 else
183be222 7898 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
3a09da41 7899 }
c8e38a49 7900 break;
65706a29
PA
7901 case 'w': /* Thread exited. */
7902 {
65706a29
PA
7903 ULONGEST value;
7904
65706a29 7905 p = unpack_varlen_hex (&buf[1], &value);
183be222 7906 event->ws.set_thread_exited (value);
65706a29
PA
7907 if (*p != ';')
7908 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7909 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7910 break;
7911 }
c8e38a49
PA
7912 case 'W': /* Target exited. */
7913 case 'X':
7914 {
c8e38a49 7915 ULONGEST value;
82f73884 7916
c8e38a49
PA
7917 /* GDB used to accept only 2 hex chars here. Stubs should
7918 only send more if they detect GDB supports multi-process
7919 support. */
7920 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7921
c8e38a49
PA
7922 if (buf[0] == 'W')
7923 {
7924 /* The remote process exited. */
183be222 7925 event->ws.set_exited (value);
c8e38a49
PA
7926 }
7927 else
7928 {
7929 /* The remote process exited with a signal. */
3a09da41 7930 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
183be222 7931 event->ws.set_signalled ((enum gdb_signal) value);
3a09da41 7932 else
183be222 7933 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
c8e38a49 7934 }
82f73884 7935
e7af6c70
TBA
7936 /* If no process is specified, return null_ptid, and let the
7937 caller figure out the right process to use. */
7938 int pid = 0;
c8e38a49
PA
7939 if (*p == '\0')
7940 ;
7941 else if (*p == ';')
7942 {
7943 p++;
7944
0b24eb2d 7945 if (*p == '\0')
82f73884 7946 ;
61012eef 7947 else if (startswith (p, "process:"))
82f73884 7948 {
c8e38a49 7949 ULONGEST upid;
a744cf53 7950
c8e38a49
PA
7951 p += sizeof ("process:") - 1;
7952 unpack_varlen_hex (p, &upid);
7953 pid = upid;
82f73884
PA
7954 }
7955 else
7956 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7957 }
c8e38a49
PA
7958 else
7959 error (_("unknown stop reply packet: %s"), buf);
f2907e49 7960 event->ptid = ptid_t (pid);
74531fed
PA
7961 }
7962 break;
f2faf941 7963 case 'N':
183be222 7964 event->ws.set_no_resumed ();
f2faf941
PA
7965 event->ptid = minus_one_ptid;
7966 break;
74531fed 7967 }
74531fed
PA
7968}
7969
722247f1
YQ
7970/* When the stub wants to tell GDB about a new notification reply, it
7971 sends a notification (%Stop, for example). Those can come it at
7972 any time, hence, we have to make sure that any pending
7973 putpkt/getpkt sequence we're making is finished, before querying
7974 the stub for more events with the corresponding ack command
7975 (vStopped, for example). E.g., if we started a vStopped sequence
7976 immediately upon receiving the notification, something like this
7977 could happen:
74531fed
PA
7978
7979 1.1) --> Hg 1
7980 1.2) <-- OK
7981 1.3) --> g
7982 1.4) <-- %Stop
7983 1.5) --> vStopped
7984 1.6) <-- (registers reply to step #1.3)
7985
7986 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7987 query.
7988
796cb314 7989 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7990 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7991 doing whatever we were doing:
7992
7993 2.1) --> Hg 1
7994 2.2) <-- OK
7995 2.3) --> g
7996 2.4) <-- %Stop
7997 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7998 2.5) <-- (registers reply to step #2.3)
7999
85102364 8000 Eventually after step #2.5, we return to the event loop, which
74531fed
PA
8001 notices there's an event on the
8002 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8003 associated callback --- the function below. At this point, we're
8004 always safe to start a vStopped sequence. :
8005
8006 2.6) --> vStopped
8007 2.7) <-- T05 thread:2
8008 2.8) --> vStopped
8009 2.9) --> OK
8010*/
8011
722247f1 8012void
42938c1a 8013remote_target::remote_notif_get_pending_events (const notif_client *nc)
74531fed
PA
8014{
8015 struct remote_state *rs = get_remote_state ();
74531fed 8016
f48ff2a7 8017 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 8018 {
722247f1 8019 if (notif_debug)
6cb06a8c
TT
8020 gdb_printf (gdb_stdlog,
8021 "notif: process: '%s' ack pending event\n",
8022 nc->name);
74531fed 8023
722247f1 8024 /* acknowledge */
8d64371b
TT
8025 nc->ack (this, nc, rs->buf.data (),
8026 rs->notif_state->pending_event[nc->id]);
f48ff2a7 8027 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
8028
8029 while (1)
8030 {
8d64371b
TT
8031 getpkt (&rs->buf, 0);
8032 if (strcmp (rs->buf.data (), "OK") == 0)
74531fed
PA
8033 break;
8034 else
8d64371b 8035 remote_notif_ack (this, nc, rs->buf.data ());
74531fed
PA
8036 }
8037 }
722247f1
YQ
8038 else
8039 {
8040 if (notif_debug)
6cb06a8c
TT
8041 gdb_printf (gdb_stdlog,
8042 "notif: process: '%s' no pending reply\n",
8043 nc->name);
722247f1 8044 }
74531fed
PA
8045}
8046
6b8edb51
PA
8047/* Wrapper around remote_target::remote_notif_get_pending_events to
8048 avoid having to export the whole remote_target class. */
8049
8050void
42938c1a 8051remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
6b8edb51
PA
8052{
8053 remote->remote_notif_get_pending_events (nc);
8054}
8055
8f66807b
AB
8056/* Called from process_stop_reply when the stop packet we are responding
8057 to didn't include a process-id or thread-id. STATUS is the stop event
8058 we are responding to.
8059
8060 It is the task of this function to select a suitable thread (or process)
8061 and return its ptid, this is the thread (or process) we will assume the
8062 stop event came from.
8063
8064 In some cases there isn't really any choice about which thread (or
8065 process) is selected, a basic remote with a single process containing a
8066 single thread might choose not to send any process-id or thread-id in
8067 its stop packets, this function will select and return the one and only
8068 thread.
8069
8070 However, if a target supports multiple threads (or processes) and still
8071 doesn't include a thread-id (or process-id) in its stop packet then
8072 first, this is a badly behaving target, and second, we're going to have
8073 to select a thread (or process) at random and use that. This function
8074 will print a warning to the user if it detects that there is the
8075 possibility that GDB is guessing which thread (or process) to
8076 report.
8077
8078 Note that this is called before GDB fetches the updated thread list from the
8079 target. So it's possible for the stop reply to be ambiguous and for GDB to
8080 not realize it. For example, if there's initially one thread, the target
8081 spawns a second thread, and then sends a stop reply without an id that
8082 concerns the first thread. GDB will assume the stop reply is about the
8083 first thread - the only thread it knows about - without printing a warning.
8084 Anyway, if the remote meant for the stop reply to be about the second thread,
8085 then it would be really broken, because GDB doesn't know about that thread
8086 yet. */
74531fed 8087
6b8edb51 8088ptid_t
8f66807b 8089remote_target::select_thread_for_ambiguous_stop_reply
c272a98c 8090 (const target_waitstatus &status)
74531fed 8091{
4351271e
AB
8092 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8093
8f66807b
AB
8094 /* Some stop events apply to all threads in an inferior, while others
8095 only apply to a single thread. */
8096 bool process_wide_stop
c272a98c
SM
8097 = (status.kind () == TARGET_WAITKIND_EXITED
8098 || status.kind () == TARGET_WAITKIND_SIGNALLED);
74531fed 8099
4351271e
AB
8100 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8101
8f66807b
AB
8102 thread_info *first_resumed_thread = nullptr;
8103 bool ambiguous = false;
74531fed 8104
8f66807b
AB
8105 /* Consider all non-exited threads of the target, find the first resumed
8106 one. */
8107 for (thread_info *thr : all_non_exited_threads (this))
24ed6739 8108 {
8f66807b 8109 remote_thread_info *remote_thr = get_remote_thread_info (thr);
cada5fc9 8110
a6c11cbb 8111 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8f66807b 8112 continue;
24ed6739 8113
8f66807b
AB
8114 if (first_resumed_thread == nullptr)
8115 first_resumed_thread = thr;
8116 else if (!process_wide_stop
8117 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8118 ambiguous = true;
8119 }
8120
b622494e
AB
8121 gdb_assert (first_resumed_thread != nullptr);
8122
4351271e
AB
8123 remote_debug_printf ("first resumed thread is %s",
8124 pid_to_str (first_resumed_thread->ptid).c_str ());
8125 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8126
8f66807b
AB
8127 /* Warn if the remote target is sending ambiguous stop replies. */
8128 if (ambiguous)
8129 {
8130 static bool warned = false;
8131
8132 if (!warned)
8133 {
8134 /* If you are seeing this warning then the remote target has
8135 stopped without specifying a thread-id, but the target
8136 does have multiple threads (or inferiors), and so GDB is
8137 having to guess which thread stopped.
8138
8139 Examples of what might cause this are the target sending
8140 and 'S' stop packet, or a 'T' stop packet and not
8141 including a thread-id.
8142
8143 Additionally, the target might send a 'W' or 'X packet
8144 without including a process-id, when the target has
8145 multiple running inferiors. */
8146 if (process_wide_stop)
8147 warning (_("multi-inferior target stopped without "
8148 "sending a process-id, using first "
8149 "non-exited inferior"));
cada5fc9 8150 else
8f66807b
AB
8151 warning (_("multi-threaded target stopped without "
8152 "sending a thread-id, using first "
8153 "non-exited thread"));
8154 warned = true;
24ed6739 8155 }
24ed6739 8156 }
74531fed 8157
8f66807b
AB
8158 /* If this is a stop for all threads then don't use a particular threads
8159 ptid, instead create a new ptid where only the pid field is set. */
8160 if (process_wide_stop)
8161 return ptid_t (first_resumed_thread->ptid.pid ());
8162 else
8163 return first_resumed_thread->ptid;
8164}
8165
8166/* Called when it is decided that STOP_REPLY holds the info of the
8167 event that is to be returned to the core. This function always
8168 destroys STOP_REPLY. */
8169
8170ptid_t
8171remote_target::process_stop_reply (struct stop_reply *stop_reply,
8172 struct target_waitstatus *status)
8173{
8174 *status = stop_reply->ws;
8175 ptid_t ptid = stop_reply->ptid;
8176
8177 /* If no thread/process was reported by the stub then select a suitable
8178 thread/process. */
8179 if (ptid == null_ptid)
c272a98c 8180 ptid = select_thread_for_ambiguous_stop_reply (*status);
8f66807b
AB
8181 gdb_assert (ptid != null_ptid);
8182
183be222
SM
8183 if (status->kind () != TARGET_WAITKIND_EXITED
8184 && status->kind () != TARGET_WAITKIND_SIGNALLED
8185 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
74531fed 8186 {
5f3563ea 8187 /* Expedited registers. */
32603266 8188 if (!stop_reply->regcache.empty ())
5f3563ea 8189 {
217f1f79 8190 struct regcache *regcache
5b6d1e4f 8191 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
5f3563ea 8192
32603266
TT
8193 for (cached_reg_t &reg : stop_reply->regcache)
8194 {
8195 regcache->raw_supply (reg.num, reg.data);
8196 xfree (reg.data);
8197 }
d1dff226 8198
32603266 8199 stop_reply->regcache.clear ();
5f3563ea 8200 }
74531fed 8201
8a82de58 8202 remote_notice_new_inferior (ptid, false);
5b6d1e4f 8203 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
799a2abe
PA
8204 remote_thr->core = stop_reply->core;
8205 remote_thr->stop_reason = stop_reply->stop_reason;
8206 remote_thr->watch_data_address = stop_reply->watch_data_address;
c9d22089
SM
8207
8208 if (target_is_non_stop_p ())
8209 {
8210 /* If the target works in non-stop mode, a stop-reply indicates that
8211 only this thread stopped. */
8212 remote_thr->set_not_resumed ();
8213 }
8214 else
8215 {
8216 /* If the target works in all-stop mode, a stop-reply indicates that
8217 all the target's threads stopped. */
8218 for (thread_info *tp : all_non_exited_threads (this))
8219 get_remote_thread_info (tp)->set_not_resumed ();
8220 }
74531fed
PA
8221 }
8222
32603266 8223 delete stop_reply;
74531fed
PA
8224 return ptid;
8225}
8226
8227/* The non-stop mode version of target_wait. */
8228
6b8edb51 8229ptid_t
b60cea74
TT
8230remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8231 target_wait_flags options)
74531fed
PA
8232{
8233 struct remote_state *rs = get_remote_state ();
74531fed
PA
8234 struct stop_reply *stop_reply;
8235 int ret;
fee9eda9 8236 int is_notif = 0;
74531fed
PA
8237
8238 /* If in non-stop mode, get out of getpkt even if a
8239 notification is received. */
8240
8d64371b 8241 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
74531fed
PA
8242 while (1)
8243 {
fee9eda9 8244 if (ret != -1 && !is_notif)
74531fed
PA
8245 switch (rs->buf[0])
8246 {
8247 case 'E': /* Error of some sort. */
8248 /* We're out of sync with the target now. Did it continue
8249 or not? We can't tell which thread it was in non-stop,
8250 so just ignore this. */
8d64371b 8251 warning (_("Remote failure reply: %s"), rs->buf.data ());
74531fed
PA
8252 break;
8253 case 'O': /* Console output. */
8d64371b 8254 remote_console_output (&rs->buf[1]);
74531fed
PA
8255 break;
8256 default:
8d64371b 8257 warning (_("Invalid remote reply: %s"), rs->buf.data ());
74531fed
PA
8258 break;
8259 }
8260
8261 /* Acknowledge a pending stop reply that may have arrived in the
8262 mean time. */
f48ff2a7 8263 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 8264 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
8265
8266 /* If indeed we noticed a stop reply, we're done. */
8267 stop_reply = queued_stop_reply (ptid);
8268 if (stop_reply != NULL)
8269 return process_stop_reply (stop_reply, status);
8270
47608cb1 8271 /* Still no event. If we're just polling for an event, then
74531fed 8272 return to the event loop. */
47608cb1 8273 if (options & TARGET_WNOHANG)
74531fed 8274 {
183be222 8275 status->set_ignore ();
74531fed
PA
8276 return minus_one_ptid;
8277 }
8278
47608cb1 8279 /* Otherwise do a blocking wait. */
8d64371b 8280 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
74531fed
PA
8281 }
8282}
8283
31ba933e
PA
8284/* Return the first resumed thread. */
8285
8286static ptid_t
5b6d1e4f 8287first_remote_resumed_thread (remote_target *target)
31ba933e 8288{
5b6d1e4f 8289 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
7846f3aa 8290 if (tp->resumed ())
31ba933e
PA
8291 return tp->ptid;
8292 return null_ptid;
8293}
8294
74531fed
PA
8295/* Wait until the remote machine stops, then return, storing status in
8296 STATUS just as `wait' would. */
8297
6b8edb51 8298ptid_t
b60cea74
TT
8299remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8300 target_wait_flags options)
74531fed
PA
8301{
8302 struct remote_state *rs = get_remote_state ();
74531fed 8303 ptid_t event_ptid = null_ptid;
cea39f65 8304 char *buf;
74531fed
PA
8305 struct stop_reply *stop_reply;
8306
47608cb1
PA
8307 again:
8308
183be222 8309 status->set_ignore ();
74531fed
PA
8310
8311 stop_reply = queued_stop_reply (ptid);
8312 if (stop_reply != NULL)
4f626cad
AB
8313 {
8314 /* None of the paths that push a stop reply onto the queue should
8315 have set the waiting_for_stop_reply flag. */
8316 gdb_assert (!rs->waiting_for_stop_reply);
8317 event_ptid = process_stop_reply (stop_reply, status);
8318 }
74531fed
PA
8319 else
8320 {
567420d1 8321 int forever = ((options & TARGET_WNOHANG) == 0
6b8edb51 8322 && rs->wait_forever_enabled_p);
567420d1
PA
8323
8324 if (!rs->waiting_for_stop_reply)
8325 {
183be222 8326 status->set_no_resumed ();
567420d1
PA
8327 return minus_one_ptid;
8328 }
74531fed 8329
74531fed
PA
8330 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8331 _never_ wait for ever -> test on target_is_async_p().
8332 However, before we do that we need to ensure that the caller
8333 knows how to take the target into/out of async mode. */
4f626cad
AB
8334 int is_notif;
8335 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
722247f1
YQ
8336
8337 /* GDB gets a notification. Return to core as this event is
8338 not interesting. */
8339 if (ret != -1 && is_notif)
8340 return minus_one_ptid;
567420d1
PA
8341
8342 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8343 return minus_one_ptid;
74531fed 8344
4f626cad 8345 buf = rs->buf.data ();
74531fed 8346
4f626cad
AB
8347 /* Assume that the target has acknowledged Ctrl-C unless we receive
8348 an 'F' or 'O' packet. */
8349 if (buf[0] != 'F' && buf[0] != 'O')
8350 rs->ctrlc_pending_p = 0;
3a29589a 8351
4f626cad
AB
8352 switch (buf[0])
8353 {
8354 case 'E': /* Error of some sort. */
8355 /* We're out of sync with the target now. Did it continue or
8356 not? Not is more likely, so report a stop. */
8357 rs->waiting_for_stop_reply = 0;
29090fb6 8358
4f626cad
AB
8359 warning (_("Remote failure reply: %s"), buf);
8360 status->set_stopped (GDB_SIGNAL_0);
8361 break;
8362 case 'F': /* File-I/O request. */
8363 /* GDB may access the inferior memory while handling the File-I/O
8364 request, but we don't want GDB accessing memory while waiting
8365 for a stop reply. See the comments in putpkt_binary. Set
8366 waiting_for_stop_reply to 0 temporarily. */
8367 rs->waiting_for_stop_reply = 0;
8368 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8369 rs->ctrlc_pending_p = 0;
8370 /* GDB handled the File-I/O request, and the target is running
8371 again. Keep waiting for events. */
8372 rs->waiting_for_stop_reply = 1;
8373 break;
8374 case 'N': case 'T': case 'S': case 'X': case 'W':
8375 {
8376 /* There is a stop reply to handle. */
8377 rs->waiting_for_stop_reply = 0;
29090fb6 8378
4f626cad
AB
8379 stop_reply
8380 = (struct stop_reply *) remote_notif_parse (this,
8381 &notif_client_stop,
8382 rs->buf.data ());
74531fed 8383
4f626cad
AB
8384 event_ptid = process_stop_reply (stop_reply, status);
8385 break;
8386 }
8387 case 'O': /* Console output. */
8388 remote_console_output (buf + 1);
8389 break;
8390 case '\0':
8391 if (rs->last_sent_signal != GDB_SIGNAL_0)
8392 {
8393 /* Zero length reply means that we tried 'S' or 'C' and the
8394 remote system doesn't support it. */
8395 target_terminal::ours_for_output ();
6cb06a8c 8396 gdb_printf
4f626cad
AB
8397 ("Can't send signals to this remote system. %s not sent.\n",
8398 gdb_signal_to_name (rs->last_sent_signal));
8399 rs->last_sent_signal = GDB_SIGNAL_0;
8400 target_terminal::inferior ();
8401
8402 strcpy (buf, rs->last_sent_step ? "s" : "c");
8403 putpkt (buf);
8404 break;
8405 }
8406 /* fallthrough */
8407 default:
8408 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 8409 break;
43ff13b4
JM
8410 }
8411 }
c8e38a49 8412
183be222 8413 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
f2faf941 8414 return minus_one_ptid;
183be222 8415 else if (status->kind () == TARGET_WAITKIND_IGNORE)
47608cb1
PA
8416 {
8417 /* Nothing interesting happened. If we're doing a non-blocking
8418 poll, we're done. Otherwise, go back to waiting. */
8419 if (options & TARGET_WNOHANG)
8420 return minus_one_ptid;
8421 else
8422 goto again;
8423 }
183be222
SM
8424 else if (status->kind () != TARGET_WAITKIND_EXITED
8425 && status->kind () != TARGET_WAITKIND_SIGNALLED)
82f73884 8426 {
d7e15655 8427 if (event_ptid != null_ptid)
47f8a51d 8428 record_currthread (rs, event_ptid);
82f73884 8429 else
5b6d1e4f 8430 event_ptid = first_remote_resumed_thread (this);
43ff13b4 8431 }
74531fed 8432 else
e7af6c70
TBA
8433 {
8434 /* A process exit. Invalidate our notion of current thread. */
8435 record_currthread (rs, minus_one_ptid);
8436 /* It's possible that the packet did not include a pid. */
8437 if (event_ptid == null_ptid)
5b6d1e4f 8438 event_ptid = first_remote_resumed_thread (this);
e7af6c70
TBA
8439 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8440 if (event_ptid == null_ptid)
8441 event_ptid = magic_null_ptid;
8442 }
79d7f229 8443
82f73884 8444 return event_ptid;
43ff13b4
JM
8445}
8446
74531fed
PA
8447/* Wait until the remote machine stops, then return, storing status in
8448 STATUS just as `wait' would. */
8449
f6ac5f3d 8450ptid_t
b60cea74
TT
8451remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8452 target_wait_flags options)
c8e38a49 8453{
2189c312
SM
8454 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8455
baa8575b
SM
8456 remote_state *rs = get_remote_state ();
8457
8458 /* Start by clearing the flag that asks for our wait method to be called,
8d34471f
AB
8459 we'll mark it again at the end if needed. If the target is not in
8460 async mode then the async token should not be marked. */
baa8575b
SM
8461 if (target_is_async_p ())
8462 clear_async_event_handler (rs->remote_async_inferior_event_token);
8d34471f
AB
8463 else
8464 gdb_assert (!async_event_handler_marked
8465 (rs->remote_async_inferior_event_token));
baa8575b 8466
c8e38a49
PA
8467 ptid_t event_ptid;
8468
6efcd9a8 8469 if (target_is_non_stop_p ())
6b8edb51 8470 event_ptid = wait_ns (ptid, status, options);
74531fed 8471 else
6b8edb51 8472 event_ptid = wait_as (ptid, status, options);
c8e38a49 8473
d9d41e78 8474 if (target_is_async_p ())
c8e38a49 8475 {
baa8575b
SM
8476 /* If there are events left in the queue, or unacknowledged
8477 notifications, then tell the event loop to call us again. */
8478 if (!rs->stop_reply_queue.empty ()
8479 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
6b8edb51 8480 mark_async_event_handler (rs->remote_async_inferior_event_token);
c8e38a49 8481 }
c8e38a49
PA
8482
8483 return event_ptid;
8484}
8485
74ca34ce 8486/* Fetch a single register using a 'p' packet. */
c906108c 8487
6b8edb51
PA
8488int
8489remote_target::fetch_register_using_p (struct regcache *regcache,
8490 packet_reg *reg)
b96ec7ac 8491{
ac7936df 8492 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 8493 struct remote_state *rs = get_remote_state ();
2e9f7625 8494 char *buf, *p;
9890e433 8495 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
8496 int i;
8497
ff52c073 8498 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
8499 return 0;
8500
8501 if (reg->pnum == -1)
8502 return 0;
8503
8d64371b 8504 p = rs->buf.data ();
fcad0fa4 8505 *p++ = 'p';
74ca34ce 8506 p += hexnumstr (p, reg->pnum);
fcad0fa4 8507 *p++ = '\0';
1f4437a4 8508 putpkt (rs->buf);
8d64371b 8509 getpkt (&rs->buf, 0);
3f9a994c 8510
8d64371b 8511 buf = rs->buf.data ();
2e9f7625 8512
ff52c073 8513 switch (m_features.packet_ok (rs->buf, PACKET_p))
74ca34ce
DJ
8514 {
8515 case PACKET_OK:
8516 break;
8517 case PACKET_UNKNOWN:
8518 return 0;
8519 case PACKET_ERROR:
27a9c0bf 8520 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 8521 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
8522 reg->regnum),
8523 buf);
74ca34ce 8524 }
3f9a994c
JB
8525
8526 /* If this register is unfetchable, tell the regcache. */
8527 if (buf[0] == 'x')
8480adf2 8528 {
73e1c03f 8529 regcache->raw_supply (reg->regnum, NULL);
8480adf2 8530 return 1;
b96ec7ac 8531 }
b96ec7ac 8532
3f9a994c
JB
8533 /* Otherwise, parse and supply the value. */
8534 p = buf;
8535 i = 0;
8536 while (p[0] != 0)
8537 {
8538 if (p[1] == 0)
74ca34ce 8539 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
8540
8541 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8542 p += 2;
8543 }
73e1c03f 8544 regcache->raw_supply (reg->regnum, regp);
3f9a994c 8545 return 1;
b96ec7ac
AC
8546}
8547
74ca34ce
DJ
8548/* Fetch the registers included in the target's 'g' packet. */
8549
6b8edb51
PA
8550int
8551remote_target::send_g_packet ()
c906108c 8552{
d01949b6 8553 struct remote_state *rs = get_remote_state ();
cea39f65 8554 int buf_len;
c906108c 8555
8d64371b 8556 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
b75abf5b 8557 putpkt (rs->buf);
8d64371b 8558 getpkt (&rs->buf, 0);
b75abf5b
AK
8559 if (packet_check_result (rs->buf) == PACKET_ERROR)
8560 error (_("Could not read registers; remote failure reply '%s'"),
dda83cd7 8561 rs->buf.data ());
c906108c 8562
29709017
DJ
8563 /* We can get out of synch in various cases. If the first character
8564 in the buffer is not a hex character, assume that has happened
8565 and try to fetch another packet to read. */
8566 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8567 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8568 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8569 && rs->buf[0] != 'x') /* New: unavailable register value. */
8570 {
2189c312 8571 remote_debug_printf ("Bad register packet; fetching a new packet");
8d64371b 8572 getpkt (&rs->buf, 0);
29709017
DJ
8573 }
8574
8d64371b 8575 buf_len = strlen (rs->buf.data ());
74ca34ce
DJ
8576
8577 /* Sanity check the received packet. */
8578 if (buf_len % 2 != 0)
8d64371b 8579 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
29709017
DJ
8580
8581 return buf_len / 2;
8582}
8583
6b8edb51
PA
8584void
8585remote_target::process_g_packet (struct regcache *regcache)
29709017 8586{
ac7936df 8587 struct gdbarch *gdbarch = regcache->arch ();
29709017 8588 struct remote_state *rs = get_remote_state ();
9d6eea31 8589 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8590 int i, buf_len;
8591 char *p;
8592 char *regs;
8593
8d64371b 8594 buf_len = strlen (rs->buf.data ());
29709017
DJ
8595
8596 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8597 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827 8598 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8d64371b
TT
8599 "bytes): %s"),
8600 rsa->sizeof_g_packet, buf_len / 2,
8601 rs->buf.data ());
74ca34ce
DJ
8602
8603 /* Save the size of the packet sent to us by the target. It is used
8604 as a heuristic when determining the max size of packets that the
8605 target can safely receive. */
8606 if (rsa->actual_register_packet_size == 0)
8607 rsa->actual_register_packet_size = buf_len;
8608
8609 /* If this is smaller than we guessed the 'g' packet would be,
8610 update our records. A 'g' reply that doesn't include a register's
8611 value implies either that the register is not available, or that
8612 the 'p' packet must be used. */
8613 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8614 {
9dc193c3 8615 long sizeof_g_packet = buf_len / 2;
74ca34ce 8616
4a22f64d 8617 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8618 {
9dc193c3
LF
8619 long offset = rsa->regs[i].offset;
8620 long reg_size = register_size (gdbarch, i);
8621
74ca34ce
DJ
8622 if (rsa->regs[i].pnum == -1)
8623 continue;
8624
9dc193c3 8625 if (offset >= sizeof_g_packet)
74ca34ce 8626 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8627 else if (offset + reg_size > sizeof_g_packet)
8628 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8629 else
74ca34ce 8630 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8631 }
9dc193c3
LF
8632
8633 /* Looks valid enough, we can assume this is the correct length
dda83cd7
SM
8634 for a 'g' packet. It's important not to adjust
8635 rsa->sizeof_g_packet if we have truncated registers otherwise
8636 this "if" won't be run the next time the method is called
8637 with a packet of the same size and one of the internal errors
8638 below will trigger instead. */
9dc193c3 8639 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8640 }
b323314b 8641
224c3ddb 8642 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8643
8644 /* Unimplemented registers read as all bits zero. */
ea9c271d 8645 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8646
c906108c
SS
8647 /* Reply describes registers byte by byte, each byte encoded as two
8648 hex characters. Suck them all up, then supply them to the
8649 register cacheing/storage mechanism. */
8650
8d64371b 8651 p = rs->buf.data ();
ea9c271d 8652 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8653 {
74ca34ce
DJ
8654 if (p[0] == 0 || p[1] == 0)
8655 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
f34652de 8656 internal_error (_("unexpected end of 'g' packet reply"));
74ca34ce 8657
c906108c 8658 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8659 regs[i] = 0; /* 'x' */
c906108c
SS
8660 else
8661 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8662 p += 2;
8663 }
8664
a744cf53
MS
8665 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8666 {
8667 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8668 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8669
8670 if (r->in_g_packet)
8671 {
8d64371b 8672 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
a744cf53 8673 /* This shouldn't happen - we adjusted in_g_packet above. */
f34652de 8674 internal_error (_("unexpected end of 'g' packet reply"));
a744cf53
MS
8675 else if (rs->buf[r->offset * 2] == 'x')
8676 {
8d64371b 8677 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
a744cf53
MS
8678 /* The register isn't available, mark it as such (at
8679 the same time setting the value to zero). */
73e1c03f 8680 regcache->raw_supply (r->regnum, NULL);
a744cf53
MS
8681 }
8682 else
73e1c03f 8683 regcache->raw_supply (r->regnum, regs + r->offset);
a744cf53
MS
8684 }
8685 }
c906108c
SS
8686}
8687
6b8edb51
PA
8688void
8689remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8690{
8691 send_g_packet ();
56be3814 8692 process_g_packet (regcache);
29709017
DJ
8693}
8694
e6e4e701
PA
8695/* Make the remote selected traceframe match GDB's selected
8696 traceframe. */
8697
6b8edb51
PA
8698void
8699remote_target::set_remote_traceframe ()
e6e4e701
PA
8700{
8701 int newnum;
262e1174 8702 struct remote_state *rs = get_remote_state ();
e6e4e701 8703
262e1174 8704 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8705 return;
8706
8707 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8708 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8709
8710 newnum = target_trace_find (tfind_number,
8711 get_traceframe_number (), 0, 0, NULL);
8712
8713 /* Should not happen. If it does, all bets are off. */
8714 if (newnum != get_traceframe_number ())
8715 warning (_("could not set remote traceframe"));
8716}
8717
f6ac5f3d
PA
8718void
8719remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8720{
ac7936df 8721 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8722 struct remote_state *rs = get_remote_state ();
8723 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8724 int i;
8725
e6e4e701 8726 set_remote_traceframe ();
222312d3 8727 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8728
8729 if (regnum >= 0)
8730 {
5cd63fda 8731 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8732
74ca34ce
DJ
8733 gdb_assert (reg != NULL);
8734
8735 /* If this register might be in the 'g' packet, try that first -
8736 we are likely to read more than one register. If this is the
8737 first 'g' packet, we might be overly optimistic about its
8738 contents, so fall back to 'p'. */
8739 if (reg->in_g_packet)
8740 {
56be3814 8741 fetch_registers_using_g (regcache);
74ca34ce
DJ
8742 if (reg->in_g_packet)
8743 return;
8744 }
8745
56be3814 8746 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8747 return;
8748
8749 /* This register is not available. */
73e1c03f 8750 regcache->raw_supply (reg->regnum, NULL);
74ca34ce
DJ
8751
8752 return;
8753 }
8754
56be3814 8755 fetch_registers_using_g (regcache);
74ca34ce 8756
5cd63fda 8757 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8758 if (!rsa->regs[i].in_g_packet)
56be3814 8759 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8760 {
8761 /* This register is not available. */
73e1c03f 8762 regcache->raw_supply (i, NULL);
74ca34ce
DJ
8763 }
8764}
8765
c906108c
SS
8766/* Prepare to store registers. Since we may send them all (using a
8767 'G' request), we have to read out the ones we don't want to change
8768 first. */
8769
f6ac5f3d
PA
8770void
8771remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8772{
9d6eea31
PA
8773 struct remote_state *rs = get_remote_state ();
8774 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8775 int i;
cf0e1e0d 8776
c906108c 8777 /* Make sure the entire registers array is valid. */
ff52c073 8778 switch (m_features.packet_support (PACKET_P))
5a2468f5
JM
8779 {
8780 case PACKET_DISABLE:
8781 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8782 /* Make sure all the necessary registers are cached. */
ac7936df 8783 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8784 if (rsa->regs[i].in_g_packet)
0b47d985 8785 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
8786 break;
8787 case PACKET_ENABLE:
8788 break;
8789 }
8790}
8791
ad10f812 8792/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8793 packet was not recognized. */
5a2468f5 8794
6b8edb51
PA
8795int
8796remote_target::store_register_using_P (const struct regcache *regcache,
8797 packet_reg *reg)
5a2468f5 8798{
ac7936df 8799 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8800 struct remote_state *rs = get_remote_state ();
5a2468f5 8801 /* Try storing a single register. */
8d64371b 8802 char *buf = rs->buf.data ();
9890e433 8803 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8804 char *p;
5a2468f5 8805
ff52c073 8806 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8807 return 0;
8808
8809 if (reg->pnum == -1)
8810 return 0;
8811
ea9c271d 8812 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8813 p = buf + strlen (buf);
34a79281 8814 regcache->raw_collect (reg->regnum, regp);
4a22f64d 8815 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4 8816 putpkt (rs->buf);
8d64371b 8817 getpkt (&rs->buf, 0);
5a2468f5 8818
ff52c073 8819 switch (m_features.packet_ok (rs->buf, PACKET_P))
74ca34ce
DJ
8820 {
8821 case PACKET_OK:
8822 return 1;
8823 case PACKET_ERROR:
27a9c0bf 8824 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8d64371b 8825 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
74ca34ce
DJ
8826 case PACKET_UNKNOWN:
8827 return 0;
8828 default:
f34652de 8829 internal_error (_("Bad result from packet_ok"));
74ca34ce 8830 }
c906108c
SS
8831}
8832
23860348
MS
8833/* Store register REGNUM, or all registers if REGNUM == -1, from the
8834 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8835
6b8edb51
PA
8836void
8837remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8838{
d01949b6 8839 struct remote_state *rs = get_remote_state ();
9d6eea31 8840 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8841 gdb_byte *regs;
c906108c
SS
8842 char *p;
8843
193cb69f
AC
8844 /* Extract all the registers in the regcache copying them into a
8845 local buffer. */
8846 {
b323314b 8847 int i;
a744cf53 8848
224c3ddb 8849 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8850 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8851 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8852 {
ea9c271d 8853 struct packet_reg *r = &rsa->regs[i];
a744cf53 8854
b323314b 8855 if (r->in_g_packet)
34a79281 8856 regcache->raw_collect (r->regnum, regs + r->offset);
193cb69f
AC
8857 }
8858 }
c906108c
SS
8859
8860 /* Command describes registers byte by byte,
8861 each byte encoded as two hex characters. */
8d64371b 8862 p = rs->buf.data ();
193cb69f 8863 *p++ = 'G';
74ca34ce 8864 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4 8865 putpkt (rs->buf);
8d64371b 8866 getpkt (&rs->buf, 0);
1f4437a4 8867 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf 8868 error (_("Could not write registers; remote failure reply '%s'"),
8d64371b 8869 rs->buf.data ());
c906108c 8870}
74ca34ce
DJ
8871
8872/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8873 of the register cache buffer. FIXME: ignores errors. */
8874
f6ac5f3d
PA
8875void
8876remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8877{
5cd63fda 8878 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8879 struct remote_state *rs = get_remote_state ();
8880 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8881 int i;
8882
e6e4e701 8883 set_remote_traceframe ();
222312d3 8884 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8885
8886 if (regnum >= 0)
8887 {
5cd63fda 8888 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8889
74ca34ce
DJ
8890 gdb_assert (reg != NULL);
8891
8892 /* Always prefer to store registers using the 'P' packet if
8893 possible; we often change only a small number of registers.
8894 Sometimes we change a larger number; we'd need help from a
8895 higher layer to know to use 'G'. */
56be3814 8896 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8897 return;
8898
8899 /* For now, don't complain if we have no way to write the
8900 register. GDB loses track of unavailable registers too
8901 easily. Some day, this may be an error. We don't have
0df8b418 8902 any way to read the register, either... */
74ca34ce
DJ
8903 if (!reg->in_g_packet)
8904 return;
8905
56be3814 8906 store_registers_using_G (regcache);
74ca34ce
DJ
8907 return;
8908 }
8909
56be3814 8910 store_registers_using_G (regcache);
74ca34ce 8911
5cd63fda 8912 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8913 if (!rsa->regs[i].in_g_packet)
56be3814 8914 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8915 /* See above for why we do not issue an error here. */
8916 continue;
8917}
c906108c
SS
8918\f
8919
8920/* Return the number of hex digits in num. */
8921
8922static int
fba45db2 8923hexnumlen (ULONGEST num)
c906108c
SS
8924{
8925 int i;
8926
8927 for (i = 0; num != 0; i++)
8928 num >>= 4;
8929
325fac50 8930 return std::max (i, 1);
c906108c
SS
8931}
8932
2df3850c 8933/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8934
8935static int
fba45db2 8936hexnumstr (char *buf, ULONGEST num)
c906108c 8937{
c906108c 8938 int len = hexnumlen (num);
a744cf53 8939
2df3850c
JM
8940 return hexnumnstr (buf, num, len);
8941}
8942
c906108c 8943
2df3850c 8944/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8945
2df3850c 8946static int
fba45db2 8947hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8948{
8949 int i;
8950
8951 buf[width] = '\0';
8952
8953 for (i = width - 1; i >= 0; i--)
c906108c 8954 {
c5aa993b 8955 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8956 num >>= 4;
8957 }
8958
2df3850c 8959 return width;
c906108c
SS
8960}
8961
23860348 8962/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8963
8964static CORE_ADDR
fba45db2 8965remote_address_masked (CORE_ADDR addr)
c906108c 8966{
883b9c6c 8967 unsigned int address_size = remote_address_size;
a744cf53 8968
911c95a5
UW
8969 /* If "remoteaddresssize" was not set, default to target address size. */
8970 if (!address_size)
f5656ead 8971 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8972
8973 if (address_size > 0
8974 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8975 {
8976 /* Only create a mask when that mask can safely be constructed
dda83cd7 8977 in a ULONGEST variable. */
c906108c 8978 ULONGEST mask = 1;
a744cf53 8979
911c95a5 8980 mask = (mask << address_size) - 1;
c906108c
SS
8981 addr &= mask;
8982 }
8983 return addr;
8984}
8985
8986/* Determine whether the remote target supports binary downloading.
8987 This is accomplished by sending a no-op memory write of zero length
8988 to the target at the specified address. It does not suffice to send
23860348
MS
8989 the whole packet, since many stubs strip the eighth bit and
8990 subsequently compute a wrong checksum, which causes real havoc with
8991 remote_write_bytes.
7a292a7a 8992
96baa820 8993 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8994 clean. In cases like this, the user should clear "remote
23860348 8995 X-packet". */
96baa820 8996
6b8edb51
PA
8997void
8998remote_target::check_binary_download (CORE_ADDR addr)
c906108c 8999{
d01949b6 9000 struct remote_state *rs = get_remote_state ();
24b06219 9001
ff52c073 9002 switch (m_features.packet_support (PACKET_X))
c906108c 9003 {
96baa820
JM
9004 case PACKET_DISABLE:
9005 break;
9006 case PACKET_ENABLE:
9007 break;
9008 case PACKET_SUPPORT_UNKNOWN:
9009 {
96baa820 9010 char *p;
802188a7 9011
8d64371b 9012 p = rs->buf.data ();
96baa820
JM
9013 *p++ = 'X';
9014 p += hexnumstr (p, (ULONGEST) addr);
9015 *p++ = ',';
9016 p += hexnumstr (p, (ULONGEST) 0);
9017 *p++ = ':';
9018 *p = '\0';
802188a7 9019
8d64371b
TT
9020 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9021 getpkt (&rs->buf, 0);
c906108c 9022
2e9f7625 9023 if (rs->buf[0] == '\0')
96baa820 9024 {
2189c312 9025 remote_debug_printf ("binary downloading NOT supported by target");
ff52c073 9026 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
9027 }
9028 else
9029 {
2189c312 9030 remote_debug_printf ("binary downloading supported by target");
ff52c073 9031 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
9032 }
9033 break;
9034 }
c906108c
SS
9035 }
9036}
9037
124e13d9
SM
9038/* Helper function to resize the payload in order to try to get a good
9039 alignment. We try to write an amount of data such that the next write will
9040 start on an address aligned on REMOTE_ALIGN_WRITES. */
9041
9042static int
9043align_for_efficient_write (int todo, CORE_ADDR memaddr)
9044{
9045 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9046}
9047
c906108c
SS
9048/* Write memory data directly to the remote machine.
9049 This does not inform the data cache; the data cache uses this.
a76d924d 9050 HEADER is the starting part of the packet.
c906108c
SS
9051 MEMADDR is the address in the remote memory space.
9052 MYADDR is the address of the buffer in our space.
124e13d9
SM
9053 LEN_UNITS is the number of addressable units to write.
9054 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
9055 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9056 should send data as binary ('X'), or hex-encoded ('M').
9057
9058 The function creates packet of the form
9059 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9060
124e13d9 9061 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
9062
9063 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9064 are omitted.
9065
9b409511 9066 Return the transferred status, error or OK (an
124e13d9
SM
9067 'enum target_xfer_status' value). Save the number of addressable units
9068 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9069
9070 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9071 exchange between gdb and the stub could look like (?? in place of the
9072 checksum):
9073
9074 -> $m1000,4#??
9075 <- aaaabbbbccccdddd
9076
9077 -> $M1000,3:eeeeffffeeee#??
9078 <- OK
9079
9080 -> $m1000,4#??
9081 <- eeeeffffeeeedddd */
c906108c 9082
6b8edb51
PA
9083target_xfer_status
9084remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9085 const gdb_byte *myaddr,
9086 ULONGEST len_units,
9087 int unit_size,
9088 ULONGEST *xfered_len_units,
9089 char packet_format, int use_length)
c906108c 9090{
6d820c5c 9091 struct remote_state *rs = get_remote_state ();
cfd77fa1 9092 char *p;
a76d924d
DJ
9093 char *plen = NULL;
9094 int plenlen = 0;
124e13d9
SM
9095 int todo_units;
9096 int units_written;
9097 int payload_capacity_bytes;
9098 int payload_length_bytes;
a76d924d
DJ
9099
9100 if (packet_format != 'X' && packet_format != 'M')
f34652de 9101 internal_error (_("remote_write_bytes_aux: bad packet format"));
c906108c 9102
124e13d9 9103 if (len_units == 0)
9b409511 9104 return TARGET_XFER_EOF;
b2182ed2 9105
124e13d9 9106 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 9107
6d820c5c
DJ
9108 /* The packet buffer will be large enough for the payload;
9109 get_memory_packet_size ensures this. */
a76d924d 9110 rs->buf[0] = '\0';
c906108c 9111
a257b5bb 9112 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
9113 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9114
124e13d9 9115 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 9116 if (!use_length)
0df8b418 9117 /* The comma won't be used. */
124e13d9
SM
9118 payload_capacity_bytes += 1;
9119 payload_capacity_bytes -= strlen (header);
9120 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 9121
a76d924d 9122 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 9123
8d64371b
TT
9124 strcat (rs->buf.data (), header);
9125 p = rs->buf.data () + strlen (header);
a76d924d
DJ
9126
9127 /* Compute a best guess of the number of bytes actually transfered. */
9128 if (packet_format == 'X')
c906108c 9129 {
23860348 9130 /* Best guess at number of bytes that will fit. */
325fac50
PA
9131 todo_units = std::min (len_units,
9132 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 9133 if (use_length)
124e13d9 9134 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 9135 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
9136 }
9137 else
9138 {
124e13d9 9139 /* Number of bytes that will fit. */
325fac50
PA
9140 todo_units
9141 = std::min (len_units,
9142 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 9143 if (use_length)
124e13d9 9144 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
9145 todo_units = std::min (todo_units,
9146 (payload_capacity_bytes / unit_size) / 2);
917317f4 9147 }
a76d924d 9148
124e13d9 9149 if (todo_units <= 0)
f34652de 9150 internal_error (_("minimum packet size too small to write data"));
802188a7 9151
6765f3e5
DJ
9152 /* If we already need another packet, then try to align the end
9153 of this packet to a useful boundary. */
124e13d9
SM
9154 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9155 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 9156
a257b5bb 9157 /* Append "<memaddr>". */
917317f4
JM
9158 memaddr = remote_address_masked (memaddr);
9159 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 9160
a76d924d
DJ
9161 if (use_length)
9162 {
9163 /* Append ",". */
9164 *p++ = ',';
802188a7 9165
124e13d9 9166 /* Append the length and retain its location and size. It may need to be
dda83cd7 9167 adjusted once the packet body has been created. */
a76d924d 9168 plen = p;
124e13d9 9169 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
9170 p += plenlen;
9171 }
a257b5bb
AC
9172
9173 /* Append ":". */
917317f4
JM
9174 *p++ = ':';
9175 *p = '\0';
802188a7 9176
a257b5bb 9177 /* Append the packet body. */
a76d924d 9178 if (packet_format == 'X')
917317f4 9179 {
917317f4
JM
9180 /* Binary mode. Send target system values byte by byte, in
9181 increasing byte addresses. Only escape certain critical
9182 characters. */
124e13d9
SM
9183 payload_length_bytes =
9184 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9185 &units_written, payload_capacity_bytes);
6765f3e5 9186
124e13d9 9187 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
9188 a second try to keep the end of the packet aligned. Don't do
9189 this if the packet is tiny. */
124e13d9 9190 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 9191 {
124e13d9
SM
9192 int new_todo_units;
9193
9194 new_todo_units = align_for_efficient_write (units_written, memaddr);
9195
9196 if (new_todo_units != units_written)
9197 payload_length_bytes =
9198 remote_escape_output (myaddr, new_todo_units, unit_size,
9199 (gdb_byte *) p, &units_written,
9200 payload_capacity_bytes);
6765f3e5
DJ
9201 }
9202
124e13d9
SM
9203 p += payload_length_bytes;
9204 if (use_length && units_written < todo_units)
c906108c 9205 {
802188a7 9206 /* Escape chars have filled up the buffer prematurely,
124e13d9 9207 and we have actually sent fewer units than planned.
917317f4
JM
9208 Fix-up the length field of the packet. Use the same
9209 number of characters as before. */
124e13d9
SM
9210 plen += hexnumnstr (plen, (ULONGEST) units_written,
9211 plenlen);
917317f4 9212 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 9213 }
a76d924d
DJ
9214 }
9215 else
9216 {
917317f4
JM
9217 /* Normal mode: Send target system values byte by byte, in
9218 increasing byte addresses. Each byte is encoded as a two hex
9219 value. */
124e13d9
SM
9220 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9221 units_written = todo_units;
c906108c 9222 }
802188a7 9223
8d64371b
TT
9224 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9225 getpkt (&rs->buf, 0);
802188a7 9226
2e9f7625 9227 if (rs->buf[0] == 'E')
00d84524 9228 return TARGET_XFER_E_IO;
802188a7 9229
124e13d9
SM
9230 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9231 send fewer units than we'd planned. */
9232 *xfered_len_units = (ULONGEST) units_written;
92ffd475 9233 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
9234}
9235
a76d924d
DJ
9236/* Write memory data directly to the remote machine.
9237 This does not inform the data cache; the data cache uses this.
9238 MEMADDR is the address in the remote memory space.
9239 MYADDR is the address of the buffer in our space.
9240 LEN is the number of bytes.
9241
9b409511
YQ
9242 Return the transferred status, error or OK (an
9243 'enum target_xfer_status' value). Save the number of bytes
9244 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 9245
6b8edb51
PA
9246target_xfer_status
9247remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9248 ULONGEST len, int unit_size,
9249 ULONGEST *xfered_len)
a76d924d 9250{
a121b7c1 9251 const char *packet_format = NULL;
a76d924d
DJ
9252
9253 /* Check whether the target supports binary download. */
9254 check_binary_download (memaddr);
9255
ff52c073 9256 switch (m_features.packet_support (PACKET_X))
a76d924d
DJ
9257 {
9258 case PACKET_ENABLE:
9259 packet_format = "X";
9260 break;
9261 case PACKET_DISABLE:
9262 packet_format = "M";
9263 break;
9264 case PACKET_SUPPORT_UNKNOWN:
f34652de 9265 internal_error (_("remote_write_bytes: bad internal state"));
a76d924d 9266 default:
f34652de 9267 internal_error (_("bad switch"));
a76d924d
DJ
9268 }
9269
9270 return remote_write_bytes_aux (packet_format,
124e13d9 9271 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 9272 packet_format[0], 1);
a76d924d
DJ
9273}
9274
9217e74e
YQ
9275/* Read memory data directly from the remote machine.
9276 This does not use the data cache; the data cache uses this.
9277 MEMADDR is the address in the remote memory space.
9278 MYADDR is the address of the buffer in our space.
124e13d9
SM
9279 LEN_UNITS is the number of addressable memory units to read..
9280 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
9281
9282 Return the transferred status, error or OK (an
9283 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
9284 transferred in *XFERED_LEN_UNITS.
9285
9286 See the comment of remote_write_bytes_aux for an example of
9287 memory read/write exchange between gdb and the stub. */
9217e74e 9288
6b8edb51
PA
9289target_xfer_status
9290remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9291 ULONGEST len_units,
9292 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
9293{
9294 struct remote_state *rs = get_remote_state ();
124e13d9 9295 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 9296 char *p;
124e13d9
SM
9297 int todo_units;
9298 int decoded_bytes;
9217e74e 9299
124e13d9 9300 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
9301 /* The packet buffer will be large enough for the payload;
9302 get_memory_packet_size ensures this. */
9303
124e13d9 9304 /* Number of units that will fit. */
325fac50
PA
9305 todo_units = std::min (len_units,
9306 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
9307
9308 /* Construct "m"<memaddr>","<len>". */
9309 memaddr = remote_address_masked (memaddr);
8d64371b 9310 p = rs->buf.data ();
9217e74e
YQ
9311 *p++ = 'm';
9312 p += hexnumstr (p, (ULONGEST) memaddr);
9313 *p++ = ',';
124e13d9 9314 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
9315 *p = '\0';
9316 putpkt (rs->buf);
8d64371b 9317 getpkt (&rs->buf, 0);
9217e74e
YQ
9318 if (rs->buf[0] == 'E'
9319 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9320 && rs->buf[3] == '\0')
9321 return TARGET_XFER_E_IO;
9322 /* Reply describes memory byte by byte, each byte encoded as two hex
9323 characters. */
8d64371b 9324 p = rs->buf.data ();
124e13d9 9325 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 9326 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 9327 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 9328 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
9329}
9330
b55fbac4
YQ
9331/* Using the set of read-only target sections of remote, read live
9332 read-only memory.
8acf9577
YQ
9333
9334 For interface/parameters/return description see target.h,
9335 to_xfer_partial. */
9336
6b8edb51
PA
9337target_xfer_status
9338remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9339 ULONGEST memaddr,
9340 ULONGEST len,
9341 int unit_size,
9342 ULONGEST *xfered_len)
8acf9577 9343{
19cf757a 9344 const struct target_section *secp;
8acf9577 9345
6b8edb51 9346 secp = target_section_by_addr (this, memaddr);
8acf9577 9347 if (secp != NULL
fd361982 9348 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
8acf9577 9349 {
8acf9577
YQ
9350 ULONGEST memend = memaddr + len;
9351
19cf757a
AB
9352 const target_section_table *table = target_get_section_table (this);
9353 for (const target_section &p : *table)
8acf9577 9354 {
bb2a6777 9355 if (memaddr >= p.addr)
8acf9577 9356 {
bb2a6777 9357 if (memend <= p.endaddr)
8acf9577
YQ
9358 {
9359 /* Entire transfer is within this section. */
124e13d9 9360 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9361 xfered_len);
8acf9577 9362 }
bb2a6777 9363 else if (memaddr >= p.endaddr)
8acf9577
YQ
9364 {
9365 /* This section ends before the transfer starts. */
9366 continue;
9367 }
9368 else
9369 {
9370 /* This section overlaps the transfer. Just do half. */
bb2a6777 9371 len = p.endaddr - memaddr;
124e13d9 9372 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9373 xfered_len);
8acf9577
YQ
9374 }
9375 }
9376 }
9377 }
9378
9379 return TARGET_XFER_EOF;
9380}
9381
9217e74e
YQ
9382/* Similar to remote_read_bytes_1, but it reads from the remote stub
9383 first if the requested memory is unavailable in traceframe.
9384 Otherwise, fall back to remote_read_bytes_1. */
c906108c 9385
6b8edb51
PA
9386target_xfer_status
9387remote_target::remote_read_bytes (CORE_ADDR memaddr,
9388 gdb_byte *myaddr, ULONGEST len, int unit_size,
9389 ULONGEST *xfered_len)
c906108c 9390{
6b6aa828 9391 if (len == 0)
96c4f946 9392 return TARGET_XFER_EOF;
b2182ed2 9393
8acf9577
YQ
9394 if (get_traceframe_number () != -1)
9395 {
a79b1bc6 9396 std::vector<mem_range> available;
8acf9577
YQ
9397
9398 /* If we fail to get the set of available memory, then the
9399 target does not support querying traceframe info, and so we
9400 attempt reading from the traceframe anyway (assuming the
9401 target implements the old QTro packet then). */
9402 if (traceframe_available_memory (&available, memaddr, len))
9403 {
a79b1bc6 9404 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
9405 {
9406 enum target_xfer_status res;
9407
9408 /* Don't read into the traceframe's available
9409 memory. */
a79b1bc6 9410 if (!available.empty ())
8acf9577
YQ
9411 {
9412 LONGEST oldlen = len;
9413
a79b1bc6 9414 len = available[0].start - memaddr;
8acf9577
YQ
9415 gdb_assert (len <= oldlen);
9416 }
9417
8acf9577 9418 /* This goes through the topmost target again. */
6b8edb51 9419 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 9420 len, unit_size, xfered_len);
8acf9577
YQ
9421 if (res == TARGET_XFER_OK)
9422 return TARGET_XFER_OK;
9423 else
9424 {
9425 /* No use trying further, we know some memory starting
9426 at MEMADDR isn't available. */
9427 *xfered_len = len;
92ffd475
PC
9428 return (*xfered_len != 0) ?
9429 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
9430 }
9431 }
9432
9433 /* Don't try to read more than how much is available, in
9434 case the target implements the deprecated QTro packet to
9435 cater for older GDBs (the target's knowledge of read-only
9436 sections may be outdated by now). */
a79b1bc6 9437 len = available[0].length;
8acf9577
YQ
9438 }
9439 }
9440
124e13d9 9441 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 9442}
74531fed 9443
c906108c 9444\f
c906108c 9445
a76d924d
DJ
9446/* Sends a packet with content determined by the printf format string
9447 FORMAT and the remaining arguments, then gets the reply. Returns
9448 whether the packet was a success, a failure, or unknown. */
9449
6b8edb51
PA
9450packet_result
9451remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
9452{
9453 struct remote_state *rs = get_remote_state ();
9454 int max_size = get_remote_packet_size ();
a76d924d 9455 va_list ap;
a744cf53 9456
a76d924d
DJ
9457 va_start (ap, format);
9458
9459 rs->buf[0] = '\0';
8d64371b 9460 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
33b031ce
GB
9461
9462 va_end (ap);
9463
9464 if (size >= max_size)
f34652de 9465 internal_error (_("Too long remote packet."));
a76d924d
DJ
9466
9467 if (putpkt (rs->buf) < 0)
9468 error (_("Communication problem with target."));
9469
9470 rs->buf[0] = '\0';
8d64371b 9471 getpkt (&rs->buf, 0);
a76d924d
DJ
9472
9473 return packet_check_result (rs->buf);
9474}
9475
a76d924d
DJ
9476/* Flash writing can take quite some time. We'll set
9477 effectively infinite timeout for flash operations.
9478 In future, we'll need to decide on a better approach. */
9479static const int remote_flash_timeout = 1000;
9480
f6ac5f3d
PA
9481void
9482remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 9483{
f5656ead 9484 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 9485 enum packet_result ret;
2ec845e7
TT
9486 scoped_restore restore_timeout
9487 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
9488
9489 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 9490 phex (address, addr_size),
a76d924d
DJ
9491 phex (length, 4));
9492 switch (ret)
9493 {
9494 case PACKET_UNKNOWN:
9495 error (_("Remote target does not support flash erase"));
9496 case PACKET_ERROR:
9497 error (_("Error erasing flash with vFlashErase packet"));
9498 default:
9499 break;
9500 }
a76d924d
DJ
9501}
9502
6b8edb51
PA
9503target_xfer_status
9504remote_target::remote_flash_write (ULONGEST address,
9505 ULONGEST length, ULONGEST *xfered_len,
9506 const gdb_byte *data)
a76d924d 9507{
2ec845e7
TT
9508 scoped_restore restore_timeout
9509 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9510 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9511 xfered_len,'X', 0);
a76d924d
DJ
9512}
9513
f6ac5f3d
PA
9514void
9515remote_target::flash_done ()
a76d924d 9516{
a76d924d 9517 int ret;
a76d924d 9518
2ec845e7
TT
9519 scoped_restore restore_timeout
9520 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9521
a76d924d 9522 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
9523
9524 switch (ret)
9525 {
9526 case PACKET_UNKNOWN:
9527 error (_("Remote target does not support vFlashDone"));
9528 case PACKET_ERROR:
9529 error (_("Error finishing flash operation"));
9530 default:
9531 break;
9532 }
9533}
9534
c906108c
SS
9535\f
9536/* Stuff for dealing with the packets which are part of this protocol.
9537 See comment at top of file for details. */
9538
1927e618
PA
9539/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9540 error to higher layers. Called when a serial error is detected.
9541 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
9542 the system error message for errno at function entry and final dot
9543 for output compatibility with throw_perror_with_name. */
1927e618
PA
9544
9545static void
5b6d1e4f 9546unpush_and_perror (remote_target *target, const char *string)
1927e618 9547{
d6cb50a2 9548 int saved_errno = errno;
1927e618 9549
5b6d1e4f 9550 remote_unpush_target (target);
d6cb50a2
JK
9551 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9552 safe_strerror (saved_errno));
1927e618
PA
9553}
9554
048094ac
PA
9555/* Read a single character from the remote end. The current quit
9556 handler is overridden to avoid quitting in the middle of packet
9557 sequence, as that would break communication with the remote server.
9558 See remote_serial_quit_handler for more detail. */
c906108c 9559
6b8edb51
PA
9560int
9561remote_target::readchar (int timeout)
c906108c
SS
9562{
9563 int ch;
5d93a237 9564 struct remote_state *rs = get_remote_state ();
048094ac 9565
2ec845e7 9566 {
6b8edb51
PA
9567 scoped_restore restore_quit_target
9568 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9569 scoped_restore restore_quit
6b8edb51 9570 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9571
2ec845e7 9572 rs->got_ctrlc_during_io = 0;
c906108c 9573
2ec845e7 9574 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9575
2ec845e7
TT
9576 if (rs->got_ctrlc_during_io)
9577 set_quit_flag ();
9578 }
048094ac 9579
2acceee2 9580 if (ch >= 0)
0876f84a 9581 return ch;
2acceee2
JM
9582
9583 switch ((enum serial_rc) ch)
c906108c
SS
9584 {
9585 case SERIAL_EOF:
5b6d1e4f 9586 remote_unpush_target (this);
598d3636 9587 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9588 /* no return */
c906108c 9589 case SERIAL_ERROR:
5b6d1e4f
PA
9590 unpush_and_perror (this, _("Remote communication error. "
9591 "Target disconnected."));
2acceee2 9592 /* no return */
c906108c 9593 case SERIAL_TIMEOUT:
2acceee2 9594 break;
c906108c 9595 }
2acceee2 9596 return ch;
c906108c
SS
9597}
9598
c33e31fd 9599/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9600 writing fails. The current quit handler is overridden to avoid
9601 quitting in the middle of packet sequence, as that would break
9602 communication with the remote server. See
9603 remote_serial_quit_handler for more detail. */
c33e31fd 9604
6b8edb51
PA
9605void
9606remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9607{
5d93a237 9608 struct remote_state *rs = get_remote_state ();
048094ac 9609
6b8edb51
PA
9610 scoped_restore restore_quit_target
9611 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9612 scoped_restore restore_quit
6b8edb51 9613 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9614
9615 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9616
9617 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9618 {
5b6d1e4f
PA
9619 unpush_and_perror (this, _("Remote communication error. "
9620 "Target disconnected."));
c33e31fd 9621 }
048094ac
PA
9622
9623 if (rs->got_ctrlc_during_io)
9624 set_quit_flag ();
c33e31fd
PA
9625}
9626
b3ced9ba
PA
9627/* Return a string representing an escaped version of BUF, of len N.
9628 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9629
b3ced9ba 9630static std::string
6e5abd65
PA
9631escape_buffer (const char *buf, int n)
9632{
d7e74731 9633 string_file stb;
6e5abd65 9634
d7e74731 9635 stb.putstrn (buf, n, '\\');
5d10a204 9636 return stb.release ();
6e5abd65
PA
9637}
9638
c906108c 9639int
6b8edb51 9640remote_target::putpkt (const char *buf)
c906108c
SS
9641{
9642 return putpkt_binary (buf, strlen (buf));
9643}
9644
6b8edb51
PA
9645/* Wrapper around remote_target::putpkt to avoid exporting
9646 remote_target. */
9647
9648int
9649putpkt (remote_target *remote, const char *buf)
9650{
9651 return remote->putpkt (buf);
9652}
9653
c906108c 9654/* Send a packet to the remote machine, with error checking. The data
23860348 9655 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9656 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9657 and for a possible /0 if we are debugging (remote_debug) and want
9658 to print the sent packet as a string. */
c906108c 9659
6b8edb51
PA
9660int
9661remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9662{
2d717e4f 9663 struct remote_state *rs = get_remote_state ();
c906108c
SS
9664 int i;
9665 unsigned char csum = 0;
b80406ac
TT
9666 gdb::def_vector<char> data (cnt + 6);
9667 char *buf2 = data.data ();
085dd6e6 9668
c906108c
SS
9669 int ch;
9670 int tcount = 0;
9671 char *p;
9672
e24a49d8
PA
9673 /* Catch cases like trying to read memory or listing threads while
9674 we're waiting for a stop reply. The remote server wouldn't be
9675 ready to handle this request, so we'd hang and timeout. We don't
9676 have to worry about this in synchronous mode, because in that
9677 case it's not possible to issue a command while the target is
74531fed
PA
9678 running. This is not a problem in non-stop mode, because in that
9679 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9680 if (!target_is_non_stop_p ()
9681 && target_is_async_p ()
9682 && rs->waiting_for_stop_reply)
9597b22a
DE
9683 {
9684 error (_("Cannot execute this command while the target is running.\n"
9685 "Use the \"interrupt\" command to stop the target\n"
9686 "and then try again."));
9687 }
e24a49d8 9688
c906108c
SS
9689 /* Copy the packet into buffer BUF2, encapsulating it
9690 and giving it a checksum. */
9691
c906108c
SS
9692 p = buf2;
9693 *p++ = '$';
9694
9695 for (i = 0; i < cnt; i++)
9696 {
9697 csum += buf[i];
9698 *p++ = buf[i];
9699 }
9700 *p++ = '#';
9701 *p++ = tohex ((csum >> 4) & 0xf);
9702 *p++ = tohex (csum & 0xf);
9703
9704 /* Send it over and over until we get a positive ack. */
9705
9706 while (1)
9707 {
c906108c
SS
9708 if (remote_debug)
9709 {
9710 *p = '\0';
b3ced9ba 9711
6f8976bf 9712 int len = (int) (p - buf2);
6cc8564b
LM
9713 int max_chars;
9714
9715 if (remote_packet_max_chars < 0)
9716 max_chars = len;
9717 else
9718 max_chars = remote_packet_max_chars;
6f8976bf
YQ
9719
9720 std::string str
6cc8564b 9721 = escape_buffer (buf2, std::min (len, max_chars));
6f8976bf 9722
6cc8564b 9723 if (len > max_chars)
2189c312
SM
9724 remote_debug_printf_nofunc
9725 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9726 len - max_chars);
9727 else
9728 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
c906108c 9729 }
c33e31fd 9730 remote_serial_write (buf2, p - buf2);
c906108c 9731
a6f3e723
SL
9732 /* If this is a no acks version of the remote protocol, send the
9733 packet and move on. */
9734 if (rs->noack_mode)
dda83cd7 9735 break;
a6f3e723 9736
74531fed
PA
9737 /* Read until either a timeout occurs (-2) or '+' is read.
9738 Handle any notification that arrives in the mean time. */
c906108c
SS
9739 while (1)
9740 {
9741 ch = readchar (remote_timeout);
9742
c906108c
SS
9743 switch (ch)
9744 {
9745 case '+':
2189c312 9746 remote_debug_printf_nofunc ("Received Ack");
c906108c 9747 return 1;
1216fa2c 9748 case '-':
2189c312 9749 remote_debug_printf_nofunc ("Received Nak");
a17d146e 9750 /* FALLTHROUGH */
c906108c 9751 case SERIAL_TIMEOUT:
c5aa993b 9752 tcount++;
c906108c 9753 if (tcount > 3)
b80406ac 9754 return 0;
23860348 9755 break; /* Retransmit buffer. */
c906108c
SS
9756 case '$':
9757 {
2189c312 9758 remote_debug_printf ("Packet instead of Ack, ignoring it");
d6f7abdf
AC
9759 /* It's probably an old response sent because an ACK
9760 was lost. Gobble up the packet and ack it so it
9761 doesn't get retransmitted when we resend this
9762 packet. */
6d820c5c 9763 skip_frame ();
c33e31fd 9764 remote_serial_write ("+", 1);
23860348 9765 continue; /* Now, go look for +. */
c906108c 9766 }
74531fed
PA
9767
9768 case '%':
9769 {
9770 int val;
9771
9772 /* If we got a notification, handle it, and go back to looking
9773 for an ack. */
9774 /* We've found the start of a notification. Now
9775 collect the data. */
8d64371b 9776 val = read_frame (&rs->buf);
74531fed
PA
9777 if (val >= 0)
9778 {
2189c312
SM
9779 remote_debug_printf_nofunc
9780 (" Notification received: %s",
9781 escape_buffer (rs->buf.data (), val).c_str ());
6e5abd65 9782
8d64371b 9783 handle_notification (rs->notif_state, rs->buf.data ());
74531fed
PA
9784 /* We're in sync now, rewait for the ack. */
9785 tcount = 0;
9786 }
9787 else
2189c312
SM
9788 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9789 rs->buf.data ());
74531fed
PA
9790 continue;
9791 }
9792 /* fall-through */
c906108c 9793 default:
2189c312
SM
9794 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9795 rs->buf.data ());
c906108c
SS
9796 continue;
9797 }
23860348 9798 break; /* Here to retransmit. */
c906108c
SS
9799 }
9800
9801#if 0
9802 /* This is wrong. If doing a long backtrace, the user should be
dda83cd7
SM
9803 able to get out next time we call QUIT, without anything as
9804 violent as interrupt_query. If we want to provide a way out of
9805 here without getting to the next QUIT, it should be based on
9806 hitting ^C twice as in remote_wait. */
c906108c
SS
9807 if (quit_flag)
9808 {
9809 quit_flag = 0;
9810 interrupt_query ();
9811 }
9812#endif
9813 }
a5c0808e 9814
a6f3e723 9815 return 0;
c906108c
SS
9816}
9817
6d820c5c
DJ
9818/* Come here after finding the start of a frame when we expected an
9819 ack. Do our best to discard the rest of this packet. */
9820
6b8edb51
PA
9821void
9822remote_target::skip_frame ()
6d820c5c
DJ
9823{
9824 int c;
9825
9826 while (1)
9827 {
9828 c = readchar (remote_timeout);
9829 switch (c)
9830 {
9831 case SERIAL_TIMEOUT:
9832 /* Nothing we can do. */
9833 return;
9834 case '#':
9835 /* Discard the two bytes of checksum and stop. */
9836 c = readchar (remote_timeout);
9837 if (c >= 0)
9838 c = readchar (remote_timeout);
9839
9840 return;
9841 case '*': /* Run length encoding. */
9842 /* Discard the repeat count. */
9843 c = readchar (remote_timeout);
9844 if (c < 0)
9845 return;
9846 break;
9847 default:
9848 /* A regular character. */
9849 break;
9850 }
9851 }
9852}
9853
c906108c 9854/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9855 into *BUF, verifying the checksum, length, and handling run-length
9856 compression. NUL terminate the buffer. If there is not enough room,
8d64371b 9857 expand *BUF.
c906108c 9858
c2d11a7d
JM
9859 Returns -1 on error, number of characters in buffer (ignoring the
9860 trailing NULL) on success. (could be extended to return one of the
23860348 9861 SERIAL status indications). */
c2d11a7d 9862
6b8edb51 9863long
8d64371b 9864remote_target::read_frame (gdb::char_vector *buf_p)
c906108c
SS
9865{
9866 unsigned char csum;
c2d11a7d 9867 long bc;
c906108c 9868 int c;
8d64371b 9869 char *buf = buf_p->data ();
a6f3e723 9870 struct remote_state *rs = get_remote_state ();
c906108c
SS
9871
9872 csum = 0;
c2d11a7d 9873 bc = 0;
c906108c
SS
9874
9875 while (1)
9876 {
9877 c = readchar (remote_timeout);
c906108c
SS
9878 switch (c)
9879 {
9880 case SERIAL_TIMEOUT:
2189c312 9881 remote_debug_printf ("Timeout in mid-packet, retrying");
c2d11a7d 9882 return -1;
2189c312 9883
c906108c 9884 case '$':
2189c312 9885 remote_debug_printf ("Saw new packet start in middle of old one");
23860348 9886 return -1; /* Start a new packet, count retries. */
2189c312 9887
c906108c
SS
9888 case '#':
9889 {
9890 unsigned char pktcsum;
e1b09194
AC
9891 int check_0 = 0;
9892 int check_1 = 0;
c906108c 9893
c2d11a7d 9894 buf[bc] = '\0';
c906108c 9895
e1b09194
AC
9896 check_0 = readchar (remote_timeout);
9897 if (check_0 >= 0)
9898 check_1 = readchar (remote_timeout);
802188a7 9899
e1b09194
AC
9900 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9901 {
2189c312 9902 remote_debug_printf ("Timeout in checksum, retrying");
e1b09194
AC
9903 return -1;
9904 }
9905 else if (check_0 < 0 || check_1 < 0)
40e3f985 9906 {
2189c312 9907 remote_debug_printf ("Communication error in checksum");
40e3f985
FN
9908 return -1;
9909 }
c906108c 9910
a6f3e723
SL
9911 /* Don't recompute the checksum; with no ack packets we
9912 don't have any way to indicate a packet retransmission
9913 is necessary. */
9914 if (rs->noack_mode)
9915 return bc;
9916
e1b09194 9917 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9918 if (csum == pktcsum)
dda83cd7 9919 return bc;
c906108c 9920
2189c312
SM
9921 remote_debug_printf
9922 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9923 pktcsum, csum, escape_buffer (buf, bc).c_str ());
6e5abd65 9924
c2d11a7d 9925 /* Number of characters in buffer ignoring trailing
dda83cd7 9926 NULL. */
c2d11a7d 9927 return -1;
c906108c 9928 }
23860348 9929 case '*': /* Run length encoding. */
dda83cd7 9930 {
c2c6d25f 9931 int repeat;
c906108c 9932
24b21115 9933 csum += c;
b4501125
AC
9934 c = readchar (remote_timeout);
9935 csum += c;
23860348 9936 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9937
23860348 9938 /* The character before ``*'' is repeated. */
c2d11a7d 9939
6d820c5c 9940 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9941 {
8d64371b 9942 if (bc + repeat - 1 >= buf_p->size () - 1)
6d820c5c
DJ
9943 {
9944 /* Make some more room in the buffer. */
8d64371b
TT
9945 buf_p->resize (buf_p->size () + repeat);
9946 buf = buf_p->data ();
6d820c5c
DJ
9947 }
9948
c2d11a7d
JM
9949 memset (&buf[bc], buf[bc - 1], repeat);
9950 bc += repeat;
c2c6d25f
JM
9951 continue;
9952 }
9953
c2d11a7d 9954 buf[bc] = '\0';
6cb06a8c 9955 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9956 return -1;
c2c6d25f 9957 }
c906108c 9958 default:
8d64371b 9959 if (bc >= buf_p->size () - 1)
c906108c 9960 {
6d820c5c 9961 /* Make some more room in the buffer. */
8d64371b
TT
9962 buf_p->resize (buf_p->size () * 2);
9963 buf = buf_p->data ();
c906108c
SS
9964 }
9965
6d820c5c
DJ
9966 buf[bc++] = c;
9967 csum += c;
9968 continue;
c906108c
SS
9969 }
9970 }
9971}
9972
ed2b7c17
TT
9973/* Set this to the maximum number of seconds to wait instead of waiting forever
9974 in target_wait(). If this timer times out, then it generates an error and
9975 the command is aborted. This replaces most of the need for timeouts in the
9976 GDB test suite, and makes it possible to distinguish between a hung target
9977 and one with slow communications. */
9978
9979static int watchdog = 0;
9980static void
9981show_watchdog (struct ui_file *file, int from_tty,
9982 struct cmd_list_element *c, const char *value)
9983{
6cb06a8c 9984 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
ed2b7c17
TT
9985}
9986
c906108c 9987/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
9988 store it in *BUF. Resize *BUF if necessary to hold the result. If
9989 FOREVER, wait forever rather than timing out; this is used (in
9990 synchronous mode) to wait for a target that is is executing user
9991 code to stop. */
d9fcf2fb
JM
9992/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9993 don't have to change all the calls to getpkt to deal with the
9994 return value, because at the moment I don't know what the right
23860348 9995 thing to do it for those. */
6b8edb51 9996
c906108c 9997void
8d64371b 9998remote_target::getpkt (gdb::char_vector *buf, int forever)
d9fcf2fb 9999{
8d64371b 10000 getpkt_sane (buf, forever);
d9fcf2fb
JM
10001}
10002
10003
10004/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
10005 store it in *BUF. Resize *BUF if necessary to hold the result. If
10006 FOREVER, wait forever rather than timing out; this is used (in
10007 synchronous mode) to wait for a target that is is executing user
10008 code to stop. If FOREVER == 0, this function is allowed to time
10009 out gracefully and return an indication of this to the caller.
10010 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
10011 consider receiving a notification enough reason to return to the
10012 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
10013 holds a notification or not (a regular packet). */
74531fed 10014
6b8edb51 10015int
8d64371b 10016remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
6b8edb51
PA
10017 int forever, int expecting_notif,
10018 int *is_notif)
c906108c 10019{
2d717e4f 10020 struct remote_state *rs = get_remote_state ();
c906108c
SS
10021 int c;
10022 int tries;
10023 int timeout;
df4b58fe 10024 int val = -1;
c906108c 10025
8d64371b 10026 strcpy (buf->data (), "timeout");
c906108c
SS
10027
10028 if (forever)
74531fed
PA
10029 timeout = watchdog > 0 ? watchdog : -1;
10030 else if (expecting_notif)
10031 timeout = 0; /* There should already be a char in the buffer. If
10032 not, bail out. */
c906108c
SS
10033 else
10034 timeout = remote_timeout;
10035
10036#define MAX_TRIES 3
10037
74531fed
PA
10038 /* Process any number of notifications, and then return when
10039 we get a packet. */
10040 for (;;)
c906108c 10041 {
d9c43928 10042 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
10043 times. */
10044 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 10045 {
74531fed
PA
10046 /* This can loop forever if the remote side sends us
10047 characters continuously, but if it pauses, we'll get
10048 SERIAL_TIMEOUT from readchar because of timeout. Then
10049 we'll count that as a retry.
10050
10051 Note that even when forever is set, we will only wait
10052 forever prior to the start of a packet. After that, we
10053 expect characters to arrive at a brisk pace. They should
10054 show up within remote_timeout intervals. */
10055 do
10056 c = readchar (timeout);
10057 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
10058
10059 if (c == SERIAL_TIMEOUT)
10060 {
74531fed
PA
10061 if (expecting_notif)
10062 return -1; /* Don't complain, it's normal to not get
10063 anything in this case. */
10064
23860348 10065 if (forever) /* Watchdog went off? Kill the target. */
c906108c 10066 {
5b6d1e4f 10067 remote_unpush_target (this);
598d3636
JK
10068 throw_error (TARGET_CLOSE_ERROR,
10069 _("Watchdog timeout has expired. "
10070 "Target detached."));
c906108c 10071 }
2189c312
SM
10072
10073 remote_debug_printf ("Timed out.");
c906108c 10074 }
74531fed
PA
10075 else
10076 {
10077 /* We've found the start of a packet or notification.
10078 Now collect the data. */
8d64371b 10079 val = read_frame (buf);
74531fed
PA
10080 if (val >= 0)
10081 break;
10082 }
10083
c33e31fd 10084 remote_serial_write ("-", 1);
c906108c 10085 }
c906108c 10086
74531fed
PA
10087 if (tries > MAX_TRIES)
10088 {
10089 /* We have tried hard enough, and just can't receive the
10090 packet/notification. Give up. */
6cb06a8c 10091 gdb_printf (_("Ignoring packet error, continuing...\n"));
c906108c 10092
74531fed
PA
10093 /* Skip the ack char if we're in no-ack mode. */
10094 if (!rs->noack_mode)
c33e31fd 10095 remote_serial_write ("+", 1);
74531fed
PA
10096 return -1;
10097 }
c906108c 10098
74531fed
PA
10099 /* If we got an ordinary packet, return that to our caller. */
10100 if (c == '$')
c906108c
SS
10101 {
10102 if (remote_debug)
43e526b9 10103 {
6cc8564b
LM
10104 int max_chars;
10105
10106 if (remote_packet_max_chars < 0)
10107 max_chars = val;
10108 else
10109 max_chars = remote_packet_max_chars;
10110
6f8976bf 10111 std::string str
8d64371b 10112 = escape_buffer (buf->data (),
6cc8564b 10113 std::min (val, max_chars));
6f8976bf 10114
6cc8564b 10115 if (val > max_chars)
2189c312
SM
10116 remote_debug_printf_nofunc
10117 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10118 val - max_chars);
10119 else
10120 remote_debug_printf_nofunc ("Packet received: %s",
10121 str.c_str ());
43e526b9 10122 }
a6f3e723
SL
10123
10124 /* Skip the ack char if we're in no-ack mode. */
10125 if (!rs->noack_mode)
c33e31fd 10126 remote_serial_write ("+", 1);
fee9eda9
YQ
10127 if (is_notif != NULL)
10128 *is_notif = 0;
0876f84a 10129 return val;
c906108c
SS
10130 }
10131
74531fed
PA
10132 /* If we got a notification, handle it, and go back to looking
10133 for a packet. */
10134 else
10135 {
10136 gdb_assert (c == '%');
10137
2189c312
SM
10138 remote_debug_printf_nofunc
10139 (" Notification received: %s",
10140 escape_buffer (buf->data (), val).c_str ());
6e5abd65 10141
fee9eda9
YQ
10142 if (is_notif != NULL)
10143 *is_notif = 1;
c906108c 10144
8d64371b 10145 handle_notification (rs->notif_state, buf->data ());
c906108c 10146
74531fed 10147 /* Notifications require no acknowledgement. */
a6f3e723 10148
74531fed 10149 if (expecting_notif)
fee9eda9 10150 return val;
74531fed
PA
10151 }
10152 }
10153}
10154
6b8edb51 10155int
8d64371b 10156remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
74531fed 10157{
8d64371b 10158 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
74531fed
PA
10159}
10160
6b8edb51 10161int
8d64371b 10162remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
6b8edb51 10163 int *is_notif)
74531fed 10164{
8d64371b 10165 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
c906108c 10166}
74531fed 10167
28561a65 10168/* Kill any new fork children of inferior INF that haven't been
cbb8991c
DB
10169 processed by follow_fork. */
10170
6b8edb51 10171void
28561a65 10172remote_target::kill_new_fork_children (inferior *inf)
cbb8991c 10173{
6b8edb51 10174 remote_state *rs = get_remote_state ();
42938c1a 10175 const notif_client *notif = &notif_client_stop;
cbb8991c 10176
28561a65
SM
10177 /* Kill the fork child threads of any threads in inferior INF that are stopped
10178 at a fork event. */
10179 for (thread_info *thread : inf->non_exited_threads ())
cbb8991c 10180 {
28561a65 10181 const target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c 10182
28561a65
SM
10183 if (ws == nullptr)
10184 continue;
cbb8991c 10185
28561a65
SM
10186 int child_pid = ws->child_ptid ().pid ();
10187 int res = remote_vkill (child_pid);
10188
10189 if (res != 0)
10190 error (_("Can't kill fork child process %d"), child_pid);
cbb8991c
DB
10191 }
10192
10193 /* Check for any pending fork events (not reported or processed yet)
28561a65 10194 in inferior INF and kill those fork child threads as well. */
cbb8991c 10195 remote_notif_get_pending_events (notif);
953edf2b 10196 for (auto &event : rs->stop_reply_queue)
28561a65
SM
10197 {
10198 if (event->ptid.pid () != inf->pid)
10199 continue;
953edf2b 10200
28561a65
SM
10201 if (!is_fork_status (event->ws.kind ()))
10202 continue;
10203
10204 int child_pid = event->ws.child_ptid ().pid ();
10205 int res = remote_vkill (child_pid);
10206
10207 if (res != 0)
10208 error (_("Can't kill fork child process %d"), child_pid);
10209 }
cbb8991c
DB
10210}
10211
c906108c 10212\f
8020350c
DB
10213/* Target hook to kill the current inferior. */
10214
f6ac5f3d
PA
10215void
10216remote_target::kill ()
43ff13b4 10217{
8020350c 10218 int res = -1;
28561a65 10219 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
0fdf84ca 10220
28561a65
SM
10221 gdb_assert (inf != nullptr);
10222
ff52c073 10223 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 10224 {
8020350c
DB
10225 /* If we're stopped while forking and we haven't followed yet,
10226 kill the child task. We need to do this before killing the
10227 parent task because if this is a vfork then the parent will
10228 be sleeping. */
28561a65 10229 kill_new_fork_children (inf);
8020350c 10230
28561a65 10231 res = remote_vkill (inf->pid);
8020350c 10232 if (res == 0)
0fdf84ca 10233 {
bc1e6c81 10234 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
10235 return;
10236 }
8020350c 10237 }
0fdf84ca 10238
8020350c
DB
10239 /* If we are in 'target remote' mode and we are killing the only
10240 inferior, then we will tell gdbserver to exit and unpush the
10241 target. */
ff52c073 10242 if (res == -1 && !m_features.remote_multi_process_p ()
5b6d1e4f 10243 && number_of_live_inferiors (this) == 1)
8020350c
DB
10244 {
10245 remote_kill_k ();
10246
10247 /* We've killed the remote end, we get to mourn it. If we are
10248 not in extended mode, mourning the inferior also unpushes
10249 remote_ops from the target stack, which closes the remote
10250 connection. */
bc1e6c81 10251 target_mourn_inferior (inferior_ptid);
8020350c
DB
10252
10253 return;
0fdf84ca 10254 }
43ff13b4 10255
8020350c 10256 error (_("Can't kill process"));
43ff13b4
JM
10257}
10258
8020350c
DB
10259/* Send a kill request to the target using the 'vKill' packet. */
10260
6b8edb51
PA
10261int
10262remote_target::remote_vkill (int pid)
82f73884 10263{
ff52c073 10264 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
10265 return -1;
10266
6b8edb51
PA
10267 remote_state *rs = get_remote_state ();
10268
82f73884 10269 /* Tell the remote target to detach. */
8d64371b 10270 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
82f73884 10271 putpkt (rs->buf);
8d64371b 10272 getpkt (&rs->buf, 0);
82f73884 10273
ff52c073 10274 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
4082afcc
PA
10275 {
10276 case PACKET_OK:
10277 return 0;
10278 case PACKET_ERROR:
10279 return 1;
10280 case PACKET_UNKNOWN:
10281 return -1;
10282 default:
f34652de 10283 internal_error (_("Bad result from packet_ok"));
4082afcc 10284 }
82f73884
PA
10285}
10286
8020350c
DB
10287/* Send a kill request to the target using the 'k' packet. */
10288
6b8edb51
PA
10289void
10290remote_target::remote_kill_k ()
82f73884 10291{
8020350c
DB
10292 /* Catch errors so the user can quit from gdb even when we
10293 aren't on speaking terms with the remote system. */
a70b8144 10294 try
82f73884 10295 {
82f73884 10296 putpkt ("k");
82f73884 10297 }
230d2906 10298 catch (const gdb_exception_error &ex)
8020350c
DB
10299 {
10300 if (ex.error == TARGET_CLOSE_ERROR)
10301 {
10302 /* If we got an (EOF) error that caused the target
10303 to go away, then we're done, that's what we wanted.
10304 "k" is susceptible to cause a premature EOF, given
10305 that the remote server isn't actually required to
10306 reply to "k", and it can happen that it doesn't
10307 even get to reply ACK to the "k". */
10308 return;
10309 }
82f73884 10310
8020350c
DB
10311 /* Otherwise, something went wrong. We didn't actually kill
10312 the target. Just propagate the exception, and let the
10313 user or higher layers decide what to do. */
eedc3f4f 10314 throw;
8020350c 10315 }
82f73884
PA
10316}
10317
f6ac5f3d
PA
10318void
10319remote_target::mourn_inferior ()
c906108c 10320{
8020350c 10321 struct remote_state *rs = get_remote_state ();
ce5ce7ed 10322
9607784a
PA
10323 /* We're no longer interested in notification events of an inferior
10324 that exited or was killed/detached. */
10325 discard_pending_stop_replies (current_inferior ());
10326
8020350c 10327 /* In 'target remote' mode with one inferior, we close the connection. */
5b6d1e4f 10328 if (!rs->extended && number_of_live_inferiors (this) <= 1)
8020350c 10329 {
5b6d1e4f 10330 remote_unpush_target (this);
8020350c
DB
10331 return;
10332 }
c906108c 10333
e24a49d8
PA
10334 /* In case we got here due to an error, but we're going to stay
10335 connected. */
10336 rs->waiting_for_stop_reply = 0;
10337
dc1981d7
PA
10338 /* If the current general thread belonged to the process we just
10339 detached from or has exited, the remote side current general
10340 thread becomes undefined. Considering a case like this:
10341
10342 - We just got here due to a detach.
10343 - The process that we're detaching from happens to immediately
10344 report a global breakpoint being hit in non-stop mode, in the
10345 same thread we had selected before.
10346 - GDB attaches to this process again.
10347 - This event happens to be the next event we handle.
10348
10349 GDB would consider that the current general thread didn't need to
10350 be set on the stub side (with Hg), since for all it knew,
10351 GENERAL_THREAD hadn't changed.
10352
10353 Notice that although in all-stop mode, the remote server always
10354 sets the current thread to the thread reporting the stop event,
10355 that doesn't happen in non-stop mode; in non-stop, the stub *must
10356 not* change the current thread when reporting a breakpoint hit,
10357 due to the decoupling of event reporting and event handling.
10358
10359 To keep things simple, we always invalidate our notion of the
10360 current thread. */
47f8a51d 10361 record_currthread (rs, minus_one_ptid);
dc1981d7 10362
8020350c 10363 /* Call common code to mark the inferior as not running. */
48aa3c27 10364 generic_mourn_inferior ();
2d717e4f 10365}
c906108c 10366
57810aa7 10367bool
f6ac5f3d 10368extended_remote_target::supports_disable_randomization ()
03583c20 10369{
ff52c073
CS
10370 return (m_features.packet_support (PACKET_QDisableRandomization)
10371 == PACKET_ENABLE);
03583c20
UW
10372}
10373
6b8edb51
PA
10374void
10375remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
10376{
10377 struct remote_state *rs = get_remote_state ();
10378 char *reply;
10379
8d64371b
TT
10380 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10381 "QDisableRandomization:%x", val);
03583c20 10382 putpkt (rs->buf);
b6bb3468 10383 reply = remote_get_noisy_reply ();
03583c20
UW
10384 if (*reply == '\0')
10385 error (_("Target does not support QDisableRandomization."));
10386 if (strcmp (reply, "OK") != 0)
10387 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10388}
10389
6b8edb51
PA
10390int
10391remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
10392{
10393 struct remote_state *rs = get_remote_state ();
2d717e4f 10394 int len;
94585166 10395 const char *remote_exec_file = get_remote_exec_file ();
c906108c 10396
2d717e4f
DJ
10397 /* If the user has disabled vRun support, or we have detected that
10398 support is not available, do not try it. */
ff52c073 10399 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 10400 return -1;
424163ea 10401
8d64371b
TT
10402 strcpy (rs->buf.data (), "vRun;");
10403 len = strlen (rs->buf.data ());
c906108c 10404
2d717e4f
DJ
10405 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10406 error (_("Remote file name too long for run packet"));
8d64371b 10407 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
9f1b45b0 10408 strlen (remote_exec_file));
2d717e4f 10409
7c5ded6a 10410 if (!args.empty ())
2d717e4f 10411 {
2d717e4f 10412 int i;
2d717e4f 10413
773a1edc 10414 gdb_argv argv (args.c_str ());
2d717e4f
DJ
10415 for (i = 0; argv[i] != NULL; i++)
10416 {
10417 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10418 error (_("Argument list too long for run packet"));
10419 rs->buf[len++] = ';';
8d64371b 10420 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
9f1b45b0 10421 strlen (argv[i]));
2d717e4f 10422 }
2d717e4f
DJ
10423 }
10424
10425 rs->buf[len++] = '\0';
10426
10427 putpkt (rs->buf);
8d64371b 10428 getpkt (&rs->buf, 0);
2d717e4f 10429
ff52c073 10430 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
2d717e4f 10431 {
4082afcc 10432 case PACKET_OK:
3405876a 10433 /* We have a wait response. All is well. */
2d717e4f 10434 return 0;
4082afcc
PA
10435 case PACKET_UNKNOWN:
10436 return -1;
10437 case PACKET_ERROR:
2d717e4f
DJ
10438 if (remote_exec_file[0] == '\0')
10439 error (_("Running the default executable on the remote target failed; "
10440 "try \"set remote exec-file\"?"));
10441 else
10442 error (_("Running \"%s\" on the remote target failed"),
10443 remote_exec_file);
4082afcc 10444 default:
557b4d76 10445 gdb_assert_not_reached ("bad switch");
2d717e4f 10446 }
c906108c
SS
10447}
10448
0a2dde4a
SDJ
10449/* Helper function to send set/unset environment packets. ACTION is
10450 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10451 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10452 sent. */
10453
6b8edb51
PA
10454void
10455remote_target::send_environment_packet (const char *action,
10456 const char *packet,
10457 const char *value)
0a2dde4a 10458{
6b8edb51
PA
10459 remote_state *rs = get_remote_state ();
10460
0a2dde4a
SDJ
10461 /* Convert the environment variable to an hex string, which
10462 is the best format to be transmitted over the wire. */
10463 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10464 strlen (value));
10465
8d64371b 10466 xsnprintf (rs->buf.data (), get_remote_packet_size (),
0a2dde4a
SDJ
10467 "%s:%s", packet, encoded_value.c_str ());
10468
10469 putpkt (rs->buf);
8d64371b
TT
10470 getpkt (&rs->buf, 0);
10471 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10472 warning (_("Unable to %s environment variable '%s' on remote."),
10473 action, value);
10474}
10475
10476/* Helper function to handle the QEnvironment* packets. */
10477
6b8edb51
PA
10478void
10479remote_target::extended_remote_environment_support ()
0a2dde4a 10480{
6b8edb51
PA
10481 remote_state *rs = get_remote_state ();
10482
ff52c073 10483 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
0a2dde4a
SDJ
10484 {
10485 putpkt ("QEnvironmentReset");
8d64371b
TT
10486 getpkt (&rs->buf, 0);
10487 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10488 warning (_("Unable to reset environment on remote."));
10489 }
10490
10491 gdb_environ *e = &current_inferior ()->environment;
10492
ff52c073
CS
10493 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10494 != PACKET_DISABLE)
10495 {
10496 for (const std::string &el : e->user_set_env ())
10497 send_environment_packet ("set", "QEnvironmentHexEncoded",
10498 el.c_str ());
10499 }
10500
0a2dde4a 10501
ff52c073 10502 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
0a2dde4a 10503 for (const std::string &el : e->user_unset_env ())
6b8edb51 10504 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10505}
10506
bc3b087d
SDJ
10507/* Helper function to set the current working directory for the
10508 inferior in the remote target. */
10509
6b8edb51
PA
10510void
10511remote_target::extended_remote_set_inferior_cwd ()
bc3b087d 10512{
ff52c073 10513 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
bc3b087d 10514 {
11bd012e 10515 const std::string &inferior_cwd = current_inferior ()->cwd ();
6b8edb51 10516 remote_state *rs = get_remote_state ();
bc3b087d 10517
11bd012e 10518 if (!inferior_cwd.empty ())
bc3b087d 10519 {
11bd012e
SM
10520 std::string hexpath
10521 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10522 inferior_cwd.size ());
bc3b087d 10523
8d64371b 10524 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10525 "QSetWorkingDir:%s", hexpath.c_str ());
10526 }
10527 else
10528 {
10529 /* An empty inferior_cwd means that the user wants us to
10530 reset the remote server's inferior's cwd. */
8d64371b 10531 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10532 "QSetWorkingDir:");
10533 }
10534
10535 putpkt (rs->buf);
8d64371b 10536 getpkt (&rs->buf, 0);
ff52c073 10537 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
bc3b087d
SDJ
10538 error (_("\
10539Remote replied unexpectedly while setting the inferior's working\n\
10540directory: %s"),
8d64371b 10541 rs->buf.data ());
bc3b087d
SDJ
10542
10543 }
10544}
10545
2d717e4f
DJ
10546/* In the extended protocol we want to be able to do things like
10547 "run" and have them basically work as expected. So we need
10548 a special create_inferior function. We support changing the
10549 executable file and the command line arguments, but not the
10550 environment. */
10551
f6ac5f3d
PA
10552void
10553extended_remote_target::create_inferior (const char *exec_file,
10554 const std::string &args,
10555 char **env, int from_tty)
43ff13b4 10556{
3405876a
PA
10557 int run_worked;
10558 char *stop_reply;
10559 struct remote_state *rs = get_remote_state ();
94585166 10560 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10561
43ff13b4 10562 /* If running asynchronously, register the target file descriptor
23860348 10563 with the event loop. */
75c99385 10564 if (target_can_async_p ())
4a570176 10565 target_async (true);
43ff13b4 10566
03583c20 10567 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10568 if (supports_disable_randomization ())
03583c20
UW
10569 extended_remote_disable_randomization (disable_randomization);
10570
aefd8b33
SDJ
10571 /* If startup-with-shell is on, we inform gdbserver to start the
10572 remote inferior using a shell. */
ff52c073 10573 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
aefd8b33 10574 {
8d64371b 10575 xsnprintf (rs->buf.data (), get_remote_packet_size (),
aefd8b33
SDJ
10576 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10577 putpkt (rs->buf);
8d64371b
TT
10578 getpkt (&rs->buf, 0);
10579 if (strcmp (rs->buf.data (), "OK") != 0)
aefd8b33
SDJ
10580 error (_("\
10581Remote replied unexpectedly while setting startup-with-shell: %s"),
8d64371b 10582 rs->buf.data ());
aefd8b33
SDJ
10583 }
10584
6b8edb51 10585 extended_remote_environment_support ();
0a2dde4a 10586
6b8edb51 10587 extended_remote_set_inferior_cwd ();
bc3b087d 10588
43ff13b4 10589 /* Now restart the remote server. */
3405876a
PA
10590 run_worked = extended_remote_run (args) != -1;
10591 if (!run_worked)
2d717e4f
DJ
10592 {
10593 /* vRun was not supported. Fail if we need it to do what the
10594 user requested. */
10595 if (remote_exec_file[0])
10596 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10597 if (!args.empty ())
65e65158 10598 error (_("Remote target does not support \"set args\" or run ARGS"));
43ff13b4 10599
2d717e4f
DJ
10600 /* Fall back to "R". */
10601 extended_remote_restart ();
10602 }
424163ea 10603
3405876a 10604 /* vRun's success return is a stop reply. */
8d64371b 10605 stop_reply = run_worked ? rs->buf.data () : NULL;
3405876a 10606 add_current_inferior_and_thread (stop_reply);
c0a2216e 10607
2d717e4f
DJ
10608 /* Get updated offsets, if the stub uses qOffsets. */
10609 get_offsets ();
2d717e4f 10610}
c906108c 10611\f
c5aa993b 10612
b775012e
LM
10613/* Given a location's target info BP_TGT and the packet buffer BUF, output
10614 the list of conditions (in agent expression bytecode format), if any, the
10615 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10616 started from BUF and ended at BUF_END. */
b775012e
LM
10617
10618static int
10619remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10620 struct bp_target_info *bp_tgt, char *buf,
10621 char *buf_end)
b775012e 10622{
3cde5c42 10623 if (bp_tgt->conditions.empty ())
b775012e
LM
10624 return 0;
10625
10626 buf += strlen (buf);
bba74b36 10627 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10628 buf++;
10629
83621223 10630 /* Send conditions to the target. */
d538e36d 10631 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10632 {
bba74b36 10633 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 10634 buf += strlen (buf);
3cde5c42 10635 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
10636 buf = pack_hex_byte (buf, aexpr->buf[i]);
10637 *buf = '\0';
10638 }
b775012e
LM
10639 return 0;
10640}
10641
d3ce09f5
SS
10642static void
10643remote_add_target_side_commands (struct gdbarch *gdbarch,
10644 struct bp_target_info *bp_tgt, char *buf)
10645{
3cde5c42 10646 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10647 return;
10648
10649 buf += strlen (buf);
10650
10651 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10652 buf += strlen (buf);
10653
10654 /* Concatenate all the agent expressions that are commands into the
10655 cmds parameter. */
df97be55 10656 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
10657 {
10658 sprintf (buf, "X%x,", aexpr->len);
10659 buf += strlen (buf);
3cde5c42 10660 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
10661 buf = pack_hex_byte (buf, aexpr->buf[i]);
10662 *buf = '\0';
10663 }
d3ce09f5
SS
10664}
10665
8181d85f
DJ
10666/* Insert a breakpoint. On targets that have software breakpoint
10667 support, we ask the remote target to do the work; on targets
10668 which don't, we insert a traditional memory breakpoint. */
c906108c 10669
f6ac5f3d
PA
10670int
10671remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10672 struct bp_target_info *bp_tgt)
c906108c 10673{
d471ea57
AC
10674 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10675 If it succeeds, then set the support to PACKET_ENABLE. If it
10676 fails, and the user has explicitly requested the Z support then
23860348 10677 report an error, otherwise, mark it disabled and go on. */
802188a7 10678
ff52c073 10679 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10680 {
0d5ed153 10681 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10682 struct remote_state *rs;
bba74b36 10683 char *p, *endbuf;
4fff2411 10684
28439a30
PA
10685 /* Make sure the remote is pointing at the right process, if
10686 necessary. */
10687 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10688 set_general_process ();
10689
4fff2411 10690 rs = get_remote_state ();
8d64371b
TT
10691 p = rs->buf.data ();
10692 endbuf = p + get_remote_packet_size ();
802188a7 10693
96baa820
JM
10694 *(p++) = 'Z';
10695 *(p++) = '0';
10696 *(p++) = ',';
7c0f6dcc 10697 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10698 p += hexnumstr (p, addr);
579c6ad9 10699 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10700
f6ac5f3d 10701 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10702 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10703
f6ac5f3d 10704 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10705 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10706
6d820c5c 10707 putpkt (rs->buf);
8d64371b 10708 getpkt (&rs->buf, 0);
96baa820 10709
ff52c073 10710 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
96baa820 10711 {
d471ea57
AC
10712 case PACKET_ERROR:
10713 return -1;
10714 case PACKET_OK:
10715 return 0;
10716 case PACKET_UNKNOWN:
10717 break;
96baa820
JM
10718 }
10719 }
c906108c 10720
0000e5cc
PA
10721 /* If this breakpoint has target-side commands but this stub doesn't
10722 support Z0 packets, throw error. */
3cde5c42 10723 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10724 throw_error (NOT_SUPPORTED_ERROR, _("\
10725Target doesn't support breakpoints that have target side commands."));
10726
f6ac5f3d 10727 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10728}
10729
f6ac5f3d
PA
10730int
10731remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10732 struct bp_target_info *bp_tgt,
10733 enum remove_bp_reason reason)
c906108c 10734{
8181d85f 10735 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10736 struct remote_state *rs = get_remote_state ();
96baa820 10737
ff52c073 10738 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10739 {
8d64371b
TT
10740 char *p = rs->buf.data ();
10741 char *endbuf = p + get_remote_packet_size ();
802188a7 10742
28439a30
PA
10743 /* Make sure the remote is pointing at the right process, if
10744 necessary. */
10745 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10746 set_general_process ();
10747
96baa820
JM
10748 *(p++) = 'z';
10749 *(p++) = '0';
10750 *(p++) = ',';
10751
8181d85f
DJ
10752 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10753 p += hexnumstr (p, addr);
579c6ad9 10754 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10755
6d820c5c 10756 putpkt (rs->buf);
8d64371b 10757 getpkt (&rs->buf, 0);
96baa820 10758
6d820c5c 10759 return (rs->buf[0] == 'E');
96baa820
JM
10760 }
10761
f6ac5f3d 10762 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10763}
10764
f486487f 10765static enum Z_packet_type
d471ea57
AC
10766watchpoint_to_Z_packet (int type)
10767{
10768 switch (type)
10769 {
10770 case hw_write:
bb858e6a 10771 return Z_PACKET_WRITE_WP;
d471ea57
AC
10772 break;
10773 case hw_read:
bb858e6a 10774 return Z_PACKET_READ_WP;
d471ea57
AC
10775 break;
10776 case hw_access:
bb858e6a 10777 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10778 break;
10779 default:
f34652de 10780 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10781 }
10782}
10783
f6ac5f3d
PA
10784int
10785remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10786 enum target_hw_bp_type type, struct expression *cond)
96baa820 10787{
d01949b6 10788 struct remote_state *rs = get_remote_state ();
8d64371b 10789 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10790 char *p;
d471ea57 10791 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10792
ff52c073 10793 if (m_features.packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10794 return 1;
802188a7 10795
28439a30
PA
10796 /* Make sure the remote is pointing at the right process, if
10797 necessary. */
10798 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10799 set_general_process ();
10800
8d64371b
TT
10801 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10802 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10803 addr = remote_address_masked (addr);
10804 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10805 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10806
6d820c5c 10807 putpkt (rs->buf);
8d64371b 10808 getpkt (&rs->buf, 0);
96baa820 10809
ff52c073 10810 switch (m_features.packet_ok (rs->buf, PACKET_Z0 + packet))
d471ea57
AC
10811 {
10812 case PACKET_ERROR:
d471ea57 10813 return -1;
85d721b8
PA
10814 case PACKET_UNKNOWN:
10815 return 1;
d471ea57
AC
10816 case PACKET_OK:
10817 return 0;
10818 }
f34652de 10819 internal_error (_("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10820}
10821
57810aa7 10822bool
f6ac5f3d
PA
10823remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10824 CORE_ADDR start, int length)
283002cf
MR
10825{
10826 CORE_ADDR diff = remote_address_masked (addr - start);
10827
10828 return diff < length;
10829}
10830
d471ea57 10831
f6ac5f3d
PA
10832int
10833remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10834 enum target_hw_bp_type type, struct expression *cond)
96baa820 10835{
d01949b6 10836 struct remote_state *rs = get_remote_state ();
8d64371b 10837 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10838 char *p;
d471ea57
AC
10839 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10840
ff52c073 10841 if (m_features.packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10842 return -1;
802188a7 10843
28439a30
PA
10844 /* Make sure the remote is pointing at the right process, if
10845 necessary. */
10846 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10847 set_general_process ();
10848
8d64371b
TT
10849 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10850 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10851 addr = remote_address_masked (addr);
10852 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10853 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c 10854 putpkt (rs->buf);
8d64371b 10855 getpkt (&rs->buf, 0);
96baa820 10856
ff52c073 10857 switch (m_features.packet_ok (rs->buf, PACKET_Z0 + packet))
d471ea57
AC
10858 {
10859 case PACKET_ERROR:
10860 case PACKET_UNKNOWN:
10861 return -1;
10862 case PACKET_OK:
10863 return 0;
10864 }
f34652de 10865 internal_error (_("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10866}
10867
3c3bea1c 10868
60fcc1c3
TT
10869static int remote_hw_watchpoint_limit = -1;
10870static int remote_hw_watchpoint_length_limit = -1;
10871static int remote_hw_breakpoint_limit = -1;
d471ea57 10872
f6ac5f3d
PA
10873int
10874remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10875{
10876 if (remote_hw_watchpoint_length_limit == 0)
10877 return 0;
10878 else if (remote_hw_watchpoint_length_limit < 0)
10879 return 1;
10880 else if (len <= remote_hw_watchpoint_length_limit)
10881 return 1;
10882 else
10883 return 0;
10884}
10885
f6ac5f3d
PA
10886int
10887remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10888{
3c3bea1c
GS
10889 if (type == bp_hardware_breakpoint)
10890 {
10891 if (remote_hw_breakpoint_limit == 0)
10892 return 0;
501eef12
AC
10893 else if (remote_hw_breakpoint_limit < 0)
10894 return 1;
3c3bea1c
GS
10895 else if (cnt <= remote_hw_breakpoint_limit)
10896 return 1;
10897 }
10898 else
10899 {
10900 if (remote_hw_watchpoint_limit == 0)
10901 return 0;
501eef12
AC
10902 else if (remote_hw_watchpoint_limit < 0)
10903 return 1;
3c3bea1c
GS
10904 else if (ot)
10905 return -1;
10906 else if (cnt <= remote_hw_watchpoint_limit)
10907 return 1;
10908 }
10909 return -1;
10910}
10911
f7e6eed5
PA
10912/* The to_stopped_by_sw_breakpoint method of target remote. */
10913
57810aa7 10914bool
f6ac5f3d 10915remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10916{
799a2abe 10917 struct thread_info *thread = inferior_thread ();
f7e6eed5 10918
799a2abe 10919 return (thread->priv != NULL
7aabaf9d
SM
10920 && (get_remote_thread_info (thread)->stop_reason
10921 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10922}
10923
10924/* The to_supports_stopped_by_sw_breakpoint method of target
10925 remote. */
10926
57810aa7 10927bool
f6ac5f3d 10928remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10929{
ff52c073 10930 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
f7e6eed5
PA
10931}
10932
10933/* The to_stopped_by_hw_breakpoint method of target remote. */
10934
57810aa7 10935bool
f6ac5f3d 10936remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10937{
799a2abe 10938 struct thread_info *thread = inferior_thread ();
f7e6eed5 10939
799a2abe 10940 return (thread->priv != NULL
7aabaf9d
SM
10941 && (get_remote_thread_info (thread)->stop_reason
10942 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10943}
10944
10945/* The to_supports_stopped_by_hw_breakpoint method of target
10946 remote. */
10947
57810aa7 10948bool
f6ac5f3d 10949remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10950{
ff52c073 10951 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
f7e6eed5
PA
10952}
10953
57810aa7 10954bool
f6ac5f3d 10955remote_target::stopped_by_watchpoint ()
3c3bea1c 10956{
799a2abe 10957 struct thread_info *thread = inferior_thread ();
ee154bee 10958
799a2abe 10959 return (thread->priv != NULL
7aabaf9d
SM
10960 && (get_remote_thread_info (thread)->stop_reason
10961 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10962}
10963
57810aa7 10964bool
f6ac5f3d 10965remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10966{
799a2abe 10967 struct thread_info *thread = inferior_thread ();
a744cf53 10968
799a2abe 10969 if (thread->priv != NULL
7aabaf9d
SM
10970 && (get_remote_thread_info (thread)->stop_reason
10971 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10972 {
7aabaf9d 10973 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 10974 return true;
4aa7a7f5
JJ
10975 }
10976
57810aa7 10977 return false;
3c3bea1c
GS
10978}
10979
10980
f6ac5f3d
PA
10981int
10982remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10983 struct bp_target_info *bp_tgt)
3c3bea1c 10984{
0d5ed153 10985 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10986 struct remote_state *rs;
bba74b36 10987 char *p, *endbuf;
dd61ec5c 10988 char *message;
3c3bea1c 10989
ff52c073 10990 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10991 return -1;
2bc416ba 10992
28439a30
PA
10993 /* Make sure the remote is pointing at the right process, if
10994 necessary. */
10995 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10996 set_general_process ();
10997
4fff2411 10998 rs = get_remote_state ();
8d64371b
TT
10999 p = rs->buf.data ();
11000 endbuf = p + get_remote_packet_size ();
4fff2411 11001
96baa820
JM
11002 *(p++) = 'Z';
11003 *(p++) = '1';
11004 *(p++) = ',';
802188a7 11005
0d5ed153 11006 addr = remote_address_masked (addr);
96baa820 11007 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 11008 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 11009
f6ac5f3d 11010 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 11011 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 11012
f6ac5f3d 11013 if (can_run_breakpoint_commands ())
d3ce09f5
SS
11014 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11015
6d820c5c 11016 putpkt (rs->buf);
8d64371b 11017 getpkt (&rs->buf, 0);
96baa820 11018
ff52c073 11019 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
d471ea57
AC
11020 {
11021 case PACKET_ERROR:
dd61ec5c 11022 if (rs->buf[1] == '.')
dda83cd7
SM
11023 {
11024 message = strchr (&rs->buf[2], '.');
11025 if (message)
11026 error (_("Remote failure reply: %s"), message + 1);
11027 }
dd61ec5c 11028 return -1;
d471ea57
AC
11029 case PACKET_UNKNOWN:
11030 return -1;
11031 case PACKET_OK:
11032 return 0;
11033 }
f34652de 11034 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
11035}
11036
d471ea57 11037
f6ac5f3d
PA
11038int
11039remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11040 struct bp_target_info *bp_tgt)
96baa820 11041{
8181d85f 11042 CORE_ADDR addr;
d01949b6 11043 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11044 char *p = rs->buf.data ();
11045 char *endbuf = p + get_remote_packet_size ();
c8189ed1 11046
ff52c073 11047 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 11048 return -1;
802188a7 11049
28439a30
PA
11050 /* Make sure the remote is pointing at the right process, if
11051 necessary. */
11052 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
11053 set_general_process ();
11054
96baa820
JM
11055 *(p++) = 'z';
11056 *(p++) = '1';
11057 *(p++) = ',';
802188a7 11058
8181d85f 11059 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 11060 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 11061 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 11062
6d820c5c 11063 putpkt (rs->buf);
8d64371b 11064 getpkt (&rs->buf, 0);
802188a7 11065
ff52c073 11066 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
d471ea57
AC
11067 {
11068 case PACKET_ERROR:
11069 case PACKET_UNKNOWN:
11070 return -1;
11071 case PACKET_OK:
11072 return 0;
11073 }
f34652de 11074 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
96baa820 11075}
96baa820 11076
4a5e7a5b
PA
11077/* Verify memory using the "qCRC:" request. */
11078
f6ac5f3d
PA
11079int
11080remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
11081{
11082 struct remote_state *rs = get_remote_state ();
11083 unsigned long host_crc, target_crc;
11084 char *tmp;
11085
936d2992
PA
11086 /* It doesn't make sense to use qCRC if the remote target is
11087 connected but not running. */
55f6301a 11088 if (target_has_execution ()
ff52c073 11089 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
936d2992
PA
11090 {
11091 enum packet_result result;
28439a30 11092
936d2992
PA
11093 /* Make sure the remote is pointing at the right process. */
11094 set_general_process ();
4a5e7a5b 11095
936d2992 11096 /* FIXME: assumes lma can fit into long. */
8d64371b 11097 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
936d2992
PA
11098 (long) lma, (long) size);
11099 putpkt (rs->buf);
4a5e7a5b 11100
936d2992
PA
11101 /* Be clever; compute the host_crc before waiting for target
11102 reply. */
11103 host_crc = xcrc32 (data, size, 0xffffffff);
11104
8d64371b 11105 getpkt (&rs->buf, 0);
4a5e7a5b 11106
ff52c073 11107 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
936d2992
PA
11108 if (result == PACKET_ERROR)
11109 return -1;
11110 else if (result == PACKET_OK)
11111 {
11112 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11113 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 11114
936d2992
PA
11115 return (host_crc == target_crc);
11116 }
11117 }
4a5e7a5b 11118
f6ac5f3d 11119 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
11120}
11121
c906108c
SS
11122/* compare-sections command
11123
11124 With no arguments, compares each loadable section in the exec bfd
11125 with the same memory range on the target, and reports mismatches.
4a5e7a5b 11126 Useful for verifying the image on the target against the exec file. */
e514a9d6 11127
c906108c 11128static void
ac88e2de 11129compare_sections_command (const char *args, int from_tty)
c906108c
SS
11130{
11131 asection *s;
ce359b09 11132 const char *sectname;
c906108c
SS
11133 bfd_size_type size;
11134 bfd_vma lma;
11135 int matched = 0;
11136 int mismatched = 0;
4a5e7a5b 11137 int res;
95cf3b38 11138 int read_only = 0;
c906108c 11139
7e10abd1 11140 if (!current_program_space->exec_bfd ())
8a3fe4f8 11141 error (_("command cannot be used without an exec file"));
c906108c 11142
95cf3b38
DT
11143 if (args != NULL && strcmp (args, "-r") == 0)
11144 {
11145 read_only = 1;
11146 args = NULL;
11147 }
11148
7e10abd1 11149 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
c906108c
SS
11150 {
11151 if (!(s->flags & SEC_LOAD))
0df8b418 11152 continue; /* Skip non-loadable section. */
c906108c 11153
95cf3b38
DT
11154 if (read_only && (s->flags & SEC_READONLY) == 0)
11155 continue; /* Skip writeable sections */
11156
fd361982 11157 size = bfd_section_size (s);
c906108c 11158 if (size == 0)
0df8b418 11159 continue; /* Skip zero-length section. */
c906108c 11160
fd361982 11161 sectname = bfd_section_name (s);
c906108c 11162 if (args && strcmp (args, sectname) != 0)
0df8b418 11163 continue; /* Not the section selected by user. */
c906108c 11164
0df8b418 11165 matched = 1; /* Do this section. */
c906108c 11166 lma = s->lma;
c906108c 11167
b80406ac 11168 gdb::byte_vector sectdata (size);
7e10abd1
TT
11169 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11170 sectdata.data (), 0, size);
c906108c 11171
b80406ac 11172 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
11173
11174 if (res == -1)
5af949e3 11175 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
11176 paddress (target_gdbarch (), lma),
11177 paddress (target_gdbarch (), lma + size));
c906108c 11178
6cb06a8c
TT
11179 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11180 paddress (target_gdbarch (), lma),
11181 paddress (target_gdbarch (), lma + size));
4a5e7a5b 11182 if (res)
6cb06a8c 11183 gdb_printf ("matched.\n");
c906108c 11184 else
c5aa993b 11185 {
6cb06a8c 11186 gdb_printf ("MIS-MATCHED!\n");
c5aa993b
JM
11187 mismatched++;
11188 }
c906108c
SS
11189 }
11190 if (mismatched > 0)
936d2992 11191 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 11192the loaded file\n"));
c906108c 11193 if (args && !matched)
6cb06a8c 11194 gdb_printf (_("No loaded section named '%s'.\n"), args);
c906108c
SS
11195}
11196
0e7f50da
UW
11197/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11198 into remote target. The number of bytes written to the remote
11199 target is returned, or -1 for error. */
11200
6b8edb51
PA
11201target_xfer_status
11202remote_target::remote_write_qxfer (const char *object_name,
11203 const char *annex, const gdb_byte *writebuf,
11204 ULONGEST offset, LONGEST len,
11205 ULONGEST *xfered_len,
ff52c073 11206 const unsigned int which_packet)
0e7f50da
UW
11207{
11208 int i, buf_len;
11209 ULONGEST n;
0e7f50da
UW
11210 struct remote_state *rs = get_remote_state ();
11211 int max_size = get_memory_write_packet_size ();
11212
ff52c073 11213 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
2ed4b548 11214 return TARGET_XFER_E_IO;
0e7f50da
UW
11215
11216 /* Insert header. */
8d64371b 11217 i = snprintf (rs->buf.data (), max_size,
0e7f50da
UW
11218 "qXfer:%s:write:%s:%s:",
11219 object_name, annex ? annex : "",
11220 phex_nz (offset, sizeof offset));
11221 max_size -= (i + 1);
11222
11223 /* Escape as much data as fits into rs->buf. */
11224 buf_len = remote_escape_output
8d64371b 11225 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
0e7f50da 11226
8d64371b
TT
11227 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11228 || getpkt_sane (&rs->buf, 0) < 0
ff52c073 11229 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
2ed4b548 11230 return TARGET_XFER_E_IO;
0e7f50da 11231
8d64371b 11232 unpack_varlen_hex (rs->buf.data (), &n);
9b409511
YQ
11233
11234 *xfered_len = n;
92ffd475 11235 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
11236}
11237
0876f84a
DJ
11238/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11239 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11240 number of bytes read is returned, or 0 for EOF, or -1 for error.
11241 The number of bytes read may be less than LEN without indicating an
11242 EOF. PACKET is checked and updated to indicate whether the remote
11243 target supports this object. */
11244
6b8edb51
PA
11245target_xfer_status
11246remote_target::remote_read_qxfer (const char *object_name,
11247 const char *annex,
11248 gdb_byte *readbuf, ULONGEST offset,
11249 LONGEST len,
11250 ULONGEST *xfered_len,
ff52c073 11251 const unsigned int which_packet)
0876f84a 11252{
0876f84a 11253 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
11254 LONGEST i, n, packet_len;
11255
ff52c073 11256 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
2ed4b548 11257 return TARGET_XFER_E_IO;
0876f84a
DJ
11258
11259 /* Check whether we've cached an end-of-object packet that matches
11260 this request. */
8e88304f 11261 if (rs->finished_object)
0876f84a 11262 {
8e88304f
TT
11263 if (strcmp (object_name, rs->finished_object) == 0
11264 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11265 && offset == rs->finished_offset)
9b409511
YQ
11266 return TARGET_XFER_EOF;
11267
0876f84a
DJ
11268
11269 /* Otherwise, we're now reading something different. Discard
11270 the cache. */
8e88304f
TT
11271 xfree (rs->finished_object);
11272 xfree (rs->finished_annex);
11273 rs->finished_object = NULL;
11274 rs->finished_annex = NULL;
0876f84a
DJ
11275 }
11276
11277 /* Request only enough to fit in a single packet. The actual data
11278 may not, since we don't know how much of it will need to be escaped;
11279 the target is free to respond with slightly less data. We subtract
11280 five to account for the response type and the protocol frame. */
768adc05 11281 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
8d64371b
TT
11282 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11283 "qXfer:%s:read:%s:%s,%s",
0876f84a
DJ
11284 object_name, annex ? annex : "",
11285 phex_nz (offset, sizeof offset),
11286 phex_nz (n, sizeof n));
11287 i = putpkt (rs->buf);
11288 if (i < 0)
2ed4b548 11289 return TARGET_XFER_E_IO;
0876f84a
DJ
11290
11291 rs->buf[0] = '\0';
8d64371b 11292 packet_len = getpkt_sane (&rs->buf, 0);
ff52c073
CS
11293 if (packet_len < 0
11294 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
2ed4b548 11295 return TARGET_XFER_E_IO;
0876f84a
DJ
11296
11297 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8d64371b 11298 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
0876f84a
DJ
11299
11300 /* 'm' means there is (or at least might be) more data after this
11301 batch. That does not make sense unless there's at least one byte
11302 of data in this reply. */
11303 if (rs->buf[0] == 'm' && packet_len == 1)
11304 error (_("Remote qXfer reply contained no data."));
11305
11306 /* Got some data. */
8d64371b 11307 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
bc20a4af 11308 packet_len - 1, readbuf, n);
0876f84a
DJ
11309
11310 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
11311 or possibly empty. If we have the final block of a non-empty
11312 object, record this fact to bypass a subsequent partial read. */
11313 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 11314 {
8e88304f
TT
11315 rs->finished_object = xstrdup (object_name);
11316 rs->finished_annex = xstrdup (annex ? annex : "");
11317 rs->finished_offset = offset + i;
0876f84a
DJ
11318 }
11319
9b409511
YQ
11320 if (i == 0)
11321 return TARGET_XFER_EOF;
11322 else
11323 {
11324 *xfered_len = i;
11325 return TARGET_XFER_OK;
11326 }
0876f84a
DJ
11327}
11328
f6ac5f3d
PA
11329enum target_xfer_status
11330remote_target::xfer_partial (enum target_object object,
11331 const char *annex, gdb_byte *readbuf,
11332 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11333 ULONGEST *xfered_len)
c906108c 11334{
82f73884 11335 struct remote_state *rs;
c906108c 11336 int i;
6d820c5c 11337 char *p2;
1e3ff5ad 11338 char query_type;
124e13d9 11339 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 11340
e6e4e701 11341 set_remote_traceframe ();
82f73884
PA
11342 set_general_thread (inferior_ptid);
11343
11344 rs = get_remote_state ();
11345
b2182ed2 11346 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
11347 if (object == TARGET_OBJECT_MEMORY)
11348 {
2d717e4f
DJ
11349 /* If the remote target is connected but not running, we should
11350 pass this request down to a lower stratum (e.g. the executable
11351 file). */
55f6301a 11352 if (!target_has_execution ())
9b409511 11353 return TARGET_XFER_EOF;
2d717e4f 11354
21e3b9b9 11355 if (writebuf != NULL)
124e13d9
SM
11356 return remote_write_bytes (offset, writebuf, len, unit_size,
11357 xfered_len);
21e3b9b9 11358 else
6b8edb51 11359 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 11360 xfered_len);
21e3b9b9
DJ
11361 }
11362
4aa995e1
PA
11363 /* Handle extra signal info using qxfer packets. */
11364 if (object == TARGET_OBJECT_SIGNAL_INFO)
11365 {
11366 if (readbuf)
f6ac5f3d 11367 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
ff52c073 11368 xfered_len, PACKET_qXfer_siginfo_read);
4aa995e1 11369 else
ff52c073
CS
11370 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11371 xfered_len, PACKET_qXfer_siginfo_write);
4aa995e1
PA
11372 }
11373
0fb4aa4b
PA
11374 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11375 {
11376 if (readbuf)
f6ac5f3d 11377 return remote_read_qxfer ("statictrace", annex,
9b409511 11378 readbuf, offset, len, xfered_len,
ff52c073 11379 PACKET_qXfer_statictrace_read);
0fb4aa4b 11380 else
2ed4b548 11381 return TARGET_XFER_E_IO;
0fb4aa4b
PA
11382 }
11383
a76d924d
DJ
11384 /* Only handle flash writes. */
11385 if (writebuf != NULL)
11386 {
a76d924d
DJ
11387 switch (object)
11388 {
11389 case TARGET_OBJECT_FLASH:
6b8edb51 11390 return remote_flash_write (offset, len, xfered_len,
9b409511 11391 writebuf);
a76d924d
DJ
11392
11393 default:
2ed4b548 11394 return TARGET_XFER_E_IO;
a76d924d
DJ
11395 }
11396 }
4b8a223f 11397
1e3ff5ad
AC
11398 /* Map pre-existing objects onto letters. DO NOT do this for new
11399 objects!!! Instead specify new query packets. */
11400 switch (object)
c906108c 11401 {
1e3ff5ad
AC
11402 case TARGET_OBJECT_AVR:
11403 query_type = 'R';
11404 break;
802188a7
RM
11405
11406 case TARGET_OBJECT_AUXV:
0876f84a 11407 gdb_assert (annex == NULL);
ff52c073
CS
11408 return remote_read_qxfer
11409 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
802188a7 11410
23181151
DJ
11411 case TARGET_OBJECT_AVAILABLE_FEATURES:
11412 return remote_read_qxfer
f6ac5f3d 11413 ("features", annex, readbuf, offset, len, xfered_len,
ff52c073 11414 PACKET_qXfer_features);
23181151 11415
cfa9d6d9
DJ
11416 case TARGET_OBJECT_LIBRARIES:
11417 return remote_read_qxfer
f6ac5f3d 11418 ("libraries", annex, readbuf, offset, len, xfered_len,
ff52c073 11419 PACKET_qXfer_libraries);
cfa9d6d9 11420
2268b414
JK
11421 case TARGET_OBJECT_LIBRARIES_SVR4:
11422 return remote_read_qxfer
f6ac5f3d 11423 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
ff52c073 11424 PACKET_qXfer_libraries_svr4);
2268b414 11425
fd79ecee
DJ
11426 case TARGET_OBJECT_MEMORY_MAP:
11427 gdb_assert (annex == NULL);
ff52c073
CS
11428 return remote_read_qxfer
11429 ("memory-map", annex, readbuf, offset, len, xfered_len,
11430 PACKET_qXfer_memory_map);
fd79ecee 11431
07e059b5
VP
11432 case TARGET_OBJECT_OSDATA:
11433 /* Should only get here if we're connected. */
5d93a237 11434 gdb_assert (rs->remote_desc);
07e059b5 11435 return remote_read_qxfer
f6ac5f3d 11436 ("osdata", annex, readbuf, offset, len, xfered_len,
ff52c073 11437 PACKET_qXfer_osdata);
07e059b5 11438
dc146f7c
VP
11439 case TARGET_OBJECT_THREADS:
11440 gdb_assert (annex == NULL);
ff52c073
CS
11441 return remote_read_qxfer
11442 ("threads", annex, readbuf, offset, len, xfered_len,
11443 PACKET_qXfer_threads);
dc146f7c 11444
b3b9301e
PA
11445 case TARGET_OBJECT_TRACEFRAME_INFO:
11446 gdb_assert (annex == NULL);
11447 return remote_read_qxfer
f6ac5f3d 11448 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
ff52c073 11449 PACKET_qXfer_traceframe_info);
78d85199
YQ
11450
11451 case TARGET_OBJECT_FDPIC:
ff52c073
CS
11452 return remote_read_qxfer
11453 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
169081d0
TG
11454
11455 case TARGET_OBJECT_OPENVMS_UIB:
ff52c073
CS
11456 return remote_read_qxfer
11457 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
169081d0 11458
9accd112 11459 case TARGET_OBJECT_BTRACE:
ff52c073
CS
11460 return remote_read_qxfer
11461 ("btrace", annex, readbuf, offset, len, xfered_len,
11462 PACKET_qXfer_btrace);
9accd112 11463
f4abbc16 11464 case TARGET_OBJECT_BTRACE_CONF:
ff52c073
CS
11465 return remote_read_qxfer
11466 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11467 PACKET_qXfer_btrace_conf);
f4abbc16 11468
c78fa86a 11469 case TARGET_OBJECT_EXEC_FILE:
ff52c073
CS
11470 return remote_read_qxfer
11471 ("exec-file", annex, readbuf, offset, len, xfered_len,
11472 PACKET_qXfer_exec_file);
c78fa86a 11473
1e3ff5ad 11474 default:
2ed4b548 11475 return TARGET_XFER_E_IO;
c906108c
SS
11476 }
11477
0df8b418 11478 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11479 large enough let the caller deal with it. */
ea9c271d 11480 if (len < get_remote_packet_size ())
2ed4b548 11481 return TARGET_XFER_E_IO;
ea9c271d 11482 len = get_remote_packet_size ();
1e3ff5ad 11483
23860348 11484 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11485 if (!rs->remote_desc)
8a3fe4f8 11486 error (_("remote query is only available after target open"));
c906108c 11487
1e3ff5ad 11488 gdb_assert (annex != NULL);
4b8a223f 11489 gdb_assert (readbuf != NULL);
c906108c 11490
8d64371b 11491 p2 = rs->buf.data ();
c906108c
SS
11492 *p2++ = 'q';
11493 *p2++ = query_type;
11494
23860348
MS
11495 /* We used one buffer char for the remote protocol q command and
11496 another for the query type. As the remote protocol encapsulation
11497 uses 4 chars plus one extra in case we are debugging
11498 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11499 string. */
c906108c 11500 i = 0;
ea9c271d 11501 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11502 {
1e3ff5ad
AC
11503 /* Bad caller may have sent forbidden characters. */
11504 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11505 *p2++ = annex[i];
c906108c
SS
11506 i++;
11507 }
1e3ff5ad
AC
11508 *p2 = '\0';
11509 gdb_assert (annex[i] == '\0');
c906108c 11510
6d820c5c 11511 i = putpkt (rs->buf);
c5aa993b 11512 if (i < 0)
2ed4b548 11513 return TARGET_XFER_E_IO;
c906108c 11514
8d64371b
TT
11515 getpkt (&rs->buf, 0);
11516 strcpy ((char *) readbuf, rs->buf.data ());
c906108c 11517
9b409511 11518 *xfered_len = strlen ((char *) readbuf);
92ffd475 11519 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11520}
11521
09c98b44
DB
11522/* Implementation of to_get_memory_xfer_limit. */
11523
f6ac5f3d
PA
11524ULONGEST
11525remote_target::get_memory_xfer_limit ()
09c98b44
DB
11526{
11527 return get_memory_write_packet_size ();
11528}
11529
f6ac5f3d
PA
11530int
11531remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11532 const gdb_byte *pattern, ULONGEST pattern_len,
11533 CORE_ADDR *found_addrp)
08388c79 11534{
f5656ead 11535 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
11536 struct remote_state *rs = get_remote_state ();
11537 int max_size = get_memory_write_packet_size ();
ff52c073 11538
0df8b418
MS
11539 /* Number of packet bytes used to encode the pattern;
11540 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11541 int escaped_pattern_len;
0df8b418 11542 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11543 int used_pattern_len;
11544 int i;
11545 int found;
11546 ULONGEST found_addr;
11547
4a72de73
TT
11548 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11549 {
11550 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11551 == len);
11552 };
11553
7cc244de 11554 /* Don't go to the target if we don't have to. This is done before
ff52c073
CS
11555 checking packet_support to avoid the possibility that a success for this
11556 edge case means the facility works in general. */
08388c79
DE
11557 if (pattern_len > search_space_len)
11558 return 0;
11559 if (pattern_len == 0)
11560 {
11561 *found_addrp = start_addr;
11562 return 1;
11563 }
11564
11565 /* If we already know the packet isn't supported, fall back to the simple
11566 way of searching memory. */
11567
ff52c073 11568 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
08388c79
DE
11569 {
11570 /* Target doesn't provided special support, fall back and use the
11571 standard support (copy memory and do the search here). */
4a72de73 11572 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11573 pattern, pattern_len, found_addrp);
11574 }
11575
28439a30
PA
11576 /* Make sure the remote is pointing at the right process. */
11577 set_general_process ();
11578
08388c79 11579 /* Insert header. */
8d64371b 11580 i = snprintf (rs->buf.data (), max_size,
08388c79 11581 "qSearch:memory:%s;%s;",
5af949e3 11582 phex_nz (start_addr, addr_size),
08388c79
DE
11583 phex_nz (search_space_len, sizeof (search_space_len)));
11584 max_size -= (i + 1);
11585
11586 /* Escape as much data as fits into rs->buf. */
11587 escaped_pattern_len =
8d64371b
TT
11588 remote_escape_output (pattern, pattern_len, 1,
11589 (gdb_byte *) rs->buf.data () + i,
08388c79
DE
11590 &used_pattern_len, max_size);
11591
11592 /* Bail if the pattern is too large. */
11593 if (used_pattern_len != pattern_len)
9b20d036 11594 error (_("Pattern is too large to transmit to remote target."));
08388c79 11595
8d64371b
TT
11596 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11597 || getpkt_sane (&rs->buf, 0) < 0
ff52c073 11598 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
08388c79
DE
11599 {
11600 /* The request may not have worked because the command is not
11601 supported. If so, fall back to the simple way. */
ff52c073 11602 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
08388c79 11603 {
4a72de73 11604 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11605 pattern, pattern_len, found_addrp);
11606 }
11607 return -1;
11608 }
11609
11610 if (rs->buf[0] == '0')
11611 found = 0;
11612 else if (rs->buf[0] == '1')
11613 {
11614 found = 1;
11615 if (rs->buf[1] != ',')
8d64371b
TT
11616 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11617 unpack_varlen_hex (&rs->buf[2], &found_addr);
08388c79
DE
11618 *found_addrp = found_addr;
11619 }
11620 else
8d64371b 11621 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
08388c79
DE
11622
11623 return found;
11624}
11625
f6ac5f3d
PA
11626void
11627remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11628{
d01949b6 11629 struct remote_state *rs = get_remote_state ();
8d64371b 11630 char *p = rs->buf.data ();
96baa820 11631
5d93a237 11632 if (!rs->remote_desc)
8a3fe4f8 11633 error (_("remote rcmd is only available after target open"));
96baa820 11634
23860348 11635 /* Send a NULL command across as an empty command. */
7be570e7
JM
11636 if (command == NULL)
11637 command = "";
11638
23860348 11639 /* The query prefix. */
8d64371b
TT
11640 strcpy (rs->buf.data (), "qRcmd,");
11641 p = strchr (rs->buf.data (), '\0');
96baa820 11642
8d64371b 11643 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
3e43a32a 11644 > get_remote_packet_size ())
8a3fe4f8 11645 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11646
23860348 11647 /* Encode the actual command. */
a30bf1f1 11648 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11649
6d820c5c 11650 if (putpkt (rs->buf) < 0)
8a3fe4f8 11651 error (_("Communication problem with target."));
96baa820
JM
11652
11653 /* get/display the response */
11654 while (1)
11655 {
2e9f7625
DJ
11656 char *buf;
11657
00bf0b85 11658 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11659 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11660 rs->buf[0] = '\0';
8d64371b 11661 if (getpkt_sane (&rs->buf, 0) == -1)
dda83cd7
SM
11662 {
11663 /* Timeout. Continue to (try to) read responses.
11664 This is better than stopping with an error, assuming the stub
11665 is still executing the (long) monitor command.
11666 If needed, the user can interrupt gdb using C-c, obtaining
11667 an effect similar to stop on timeout. */
11668 continue;
11669 }
8d64371b 11670 buf = rs->buf.data ();
96baa820 11671 if (buf[0] == '\0')
8a3fe4f8 11672 error (_("Target does not support this command."));
96baa820
JM
11673 if (buf[0] == 'O' && buf[1] != 'K')
11674 {
23860348 11675 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11676 continue;
11677 }
11678 if (strcmp (buf, "OK") == 0)
11679 break;
7be570e7 11680 if (strlen (buf) == 3 && buf[0] == 'E'
d5ce6f2d 11681 && isxdigit (buf[1]) && isxdigit (buf[2]))
7be570e7 11682 {
8a3fe4f8 11683 error (_("Protocol error with Rcmd"));
7be570e7 11684 }
96baa820
JM
11685 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11686 {
11687 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11688
a11ac3b3 11689 gdb_putc (c, outbuf);
96baa820
JM
11690 }
11691 break;
11692 }
11693}
11694
f6ac5f3d
PA
11695std::vector<mem_region>
11696remote_target::memory_map ()
fd79ecee 11697{
a664f67e 11698 std::vector<mem_region> result;
9018be22 11699 gdb::optional<gdb::char_vector> text
328d42d8
SM
11700 = target_read_stralloc (current_inferior ()->top_target (),
11701 TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11702
11703 if (text)
9018be22 11704 result = parse_memory_map (text->data ());
fd79ecee
DJ
11705
11706 return result;
11707}
11708
e5b176f2
AB
11709/* Set of callbacks used to implement the 'maint packet' command. */
11710
11711struct cli_packet_command_callbacks : public send_remote_packet_callbacks
c906108c 11712{
e5b176f2
AB
11713 /* Called before the packet is sent. BUF is the packet content before
11714 the protocol specific prefix, suffix, and escaping is added. */
c906108c 11715
e5b176f2
AB
11716 void sending (gdb::array_view<const char> &buf) override
11717 {
0426ad51 11718 gdb_puts ("sending: ");
e5b176f2 11719 print_packet (buf);
0426ad51 11720 gdb_puts ("\n");
e5b176f2 11721 }
c906108c 11722
e5b176f2
AB
11723 /* Called with BUF, the reply from the remote target. */
11724
11725 void received (gdb::array_view<const char> &buf) override
11726 {
0426ad51 11727 gdb_puts ("received: \"");
e5b176f2 11728 print_packet (buf);
0426ad51 11729 gdb_puts ("\"\n");
e5b176f2
AB
11730 }
11731
11732private:
11733
11734 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11735 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11736
11737 static void
11738 print_packet (gdb::array_view<const char> &buf)
11739 {
11740 string_file stb;
11741
11742 for (int i = 0; i < buf.size (); ++i)
11743 {
11744 gdb_byte c = buf[i];
11745 if (isprint (c))
a11ac3b3 11746 gdb_putc (c, &stb);
e5b176f2 11747 else
6cb06a8c 11748 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
e5b176f2
AB
11749 }
11750
0426ad51 11751 gdb_puts (stb.string ().c_str ());
e5b176f2
AB
11752 }
11753};
11754
11755/* See remote.h. */
6b8edb51
PA
11756
11757void
e5b176f2
AB
11758send_remote_packet (gdb::array_view<const char> &buf,
11759 send_remote_packet_callbacks *callbacks)
6b8edb51 11760{
e5b176f2
AB
11761 if (buf.size () == 0 || buf.data ()[0] == '\0')
11762 error (_("a remote packet must not be empty"));
c906108c 11763
e5b176f2
AB
11764 remote_target *remote = get_current_remote_target ();
11765 if (remote == nullptr)
11766 error (_("packets can only be sent to a remote target"));
c906108c 11767
e5b176f2 11768 callbacks->sending (buf);
6b8edb51 11769
e5b176f2
AB
11770 remote->putpkt_binary (buf.data (), buf.size ());
11771 remote_state *rs = remote->get_remote_state ();
11772 int bytes = remote->getpkt_sane (&rs->buf, 0);
11773
11774 if (bytes < 0)
11775 error (_("error while fetching packet from remote target"));
11776
11777 gdb::array_view<const char> view (&rs->buf[0], bytes);
11778 callbacks->received (view);
11779}
11780
11781/* Entry point for the 'maint packet' command. */
11782
11783static void
11784cli_packet_command (const char *args, int from_tty)
11785{
11786 cli_packet_command_callbacks cb;
11787 gdb::array_view<const char> view
11788 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11789 send_remote_packet (view, &cb);
c906108c
SS
11790}
11791
11792#if 0
23860348 11793/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11794
a14ed312 11795static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11796
a14ed312 11797static void threadset_test_cmd (char *cmd, int tty);
c906108c 11798
a14ed312 11799static void threadalive_test (char *cmd, int tty);
c906108c 11800
a14ed312 11801static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11802
23860348 11803int get_and_display_threadinfo (threadref *ref);
c906108c 11804
a14ed312 11805static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11806
23860348 11807static int thread_display_step (threadref *ref, void *context);
c906108c 11808
a14ed312 11809static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11810
a14ed312 11811static void init_remote_threadtests (void);
c906108c 11812
23860348 11813#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11814
11815static void
0b39b52e 11816threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11817{
11818 int sample_thread = SAMPLE_THREAD;
11819
6cb06a8c 11820 gdb_printf (_("Remote threadset test\n"));
79d7f229 11821 set_general_thread (sample_thread);
c906108c
SS
11822}
11823
11824
11825static void
0b39b52e 11826threadalive_test (const char *cmd, int tty)
c906108c
SS
11827{
11828 int sample_thread = SAMPLE_THREAD;
e99b03dc 11829 int pid = inferior_ptid.pid ();
fd79271b 11830 ptid_t ptid = ptid_t (pid, sample_thread, 0);
c906108c 11831
79d7f229 11832 if (remote_thread_alive (ptid))
6cb06a8c 11833 gdb_printf ("PASS: Thread alive test\n");
c906108c 11834 else
6cb06a8c 11835 gdb_printf ("FAIL: Thread alive test\n");
c906108c
SS
11836}
11837
23860348 11838void output_threadid (char *title, threadref *ref);
c906108c
SS
11839
11840void
fba45db2 11841output_threadid (char *title, threadref *ref)
c906108c
SS
11842{
11843 char hexid[20];
11844
405feb71 11845 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
c906108c 11846 hexid[16] = 0;
6cb06a8c 11847 gdb_printf ("%s %s\n", title, (&hexid[0]));
c906108c
SS
11848}
11849
11850static void
0b39b52e 11851threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11852{
11853 int startflag = 1;
11854 threadref nextthread;
11855 int done, result_count;
11856 threadref threadlist[3];
11857
6cb06a8c 11858 gdb_printf ("Remote Threadlist test\n");
c906108c
SS
11859 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11860 &result_count, &threadlist[0]))
6cb06a8c 11861 gdb_printf ("FAIL: threadlist test\n");
c906108c
SS
11862 else
11863 {
11864 threadref *scan = threadlist;
11865 threadref *limit = scan + result_count;
11866
11867 while (scan < limit)
11868 output_threadid (" thread ", scan++);
11869 }
11870}
11871
11872void
fba45db2 11873display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11874{
11875 output_threadid ("Threadid: ", &info->threadid);
6cb06a8c
TT
11876 gdb_printf ("Name: %s\n ", info->shortname);
11877 gdb_printf ("State: %s\n", info->display);
11878 gdb_printf ("other: %s\n\n", info->more_display);
c906108c
SS
11879}
11880
11881int
fba45db2 11882get_and_display_threadinfo (threadref *ref)
c906108c
SS
11883{
11884 int result;
11885 int set;
11886 struct gdb_ext_thread_info threadinfo;
11887
11888 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11889 | TAG_MOREDISPLAY | TAG_DISPLAY;
11890 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11891 display_thread_info (&threadinfo);
11892 return result;
11893}
11894
11895static void
0b39b52e 11896threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11897{
11898 int athread = SAMPLE_THREAD;
11899 threadref thread;
11900 int set;
11901
11902 int_to_threadref (&thread, athread);
6cb06a8c 11903 gdb_printf ("Remote Threadinfo test\n");
c906108c 11904 if (!get_and_display_threadinfo (&thread))
6cb06a8c 11905 gdb_printf ("FAIL cannot get thread info\n");
c906108c
SS
11906}
11907
11908static int
fba45db2 11909thread_display_step (threadref *ref, void *context)
c906108c
SS
11910{
11911 /* output_threadid(" threadstep ",ref); *//* simple test */
11912 return get_and_display_threadinfo (ref);
11913}
11914
11915static void
0b39b52e 11916threadlist_update_test_cmd (const char *cmd, int tty)
c906108c 11917{
6cb06a8c 11918 gdb_printf ("Remote Threadlist update test\n");
c906108c
SS
11919 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11920}
11921
11922static void
11923init_remote_threadtests (void)
11924{
3e43a32a
MS
11925 add_com ("tlist", class_obscure, threadlist_test_cmd,
11926 _("Fetch and print the remote list of "
590042fc 11927 "thread identifiers, one pkt only."));
c906108c 11928 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
590042fc 11929 _("Fetch and display info about one thread."));
c906108c 11930 add_com ("tset", class_obscure, threadset_test_cmd,
590042fc 11931 _("Test setting to a different thread."));
c906108c 11932 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
590042fc 11933 _("Iterate through updating all remote thread info."));
c906108c 11934 add_com ("talive", class_obscure, threadalive_test,
590042fc 11935 _("Remote thread alive test."));
c906108c
SS
11936}
11937
11938#endif /* 0 */
11939
a068643d 11940/* Convert a thread ID to a string. */
f3fb8c85 11941
a068643d 11942std::string
f6ac5f3d 11943remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11944{
d7e15655 11945 if (ptid == null_ptid)
7cee1e54 11946 return normal_pid_to_str (ptid);
0e998d96 11947 else if (ptid.is_pid ())
ecd0ada5
PA
11948 {
11949 /* Printing an inferior target id. */
11950
11951 /* When multi-process extensions are off, there's no way in the
11952 remote protocol to know the remote process id, if there's any
11953 at all. There's one exception --- when we're connected with
11954 target extended-remote, and we manually attached to a process
11955 with "attach PID". We don't record anywhere a flag that
11956 allows us to distinguish that case from the case of
11957 connecting with extended-remote and the stub already being
11958 attached to a process, and reporting yes to qAttached, hence
11959 no smart special casing here. */
ff52c073 11960 if (!m_features.remote_multi_process_p ())
a068643d 11961 return "Remote target";
ecd0ada5
PA
11962
11963 return normal_pid_to_str (ptid);
82f73884 11964 }
ecd0ada5 11965 else
79d7f229 11966 {
d7e15655 11967 if (magic_null_ptid == ptid)
a068643d 11968 return "Thread <main>";
ff52c073 11969 else if (m_features.remote_multi_process_p ())
e38504b3 11970 if (ptid.lwp () == 0)
de0d863e
DB
11971 return normal_pid_to_str (ptid);
11972 else
a068643d
TT
11973 return string_printf ("Thread %d.%ld",
11974 ptid.pid (), ptid.lwp ());
ecd0ada5 11975 else
a068643d 11976 return string_printf ("Thread %ld", ptid.lwp ());
79d7f229 11977 }
f3fb8c85
MS
11978}
11979
38691318
KB
11980/* Get the address of the thread local variable in OBJFILE which is
11981 stored at OFFSET within the thread local storage for thread PTID. */
11982
f6ac5f3d
PA
11983CORE_ADDR
11984remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11985 CORE_ADDR offset)
38691318 11986{
ff52c073 11987 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11988 {
11989 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11990 char *p = rs->buf.data ();
11991 char *endp = p + get_remote_packet_size ();
571dd617 11992 enum packet_result result;
38691318
KB
11993
11994 strcpy (p, "qGetTLSAddr:");
11995 p += strlen (p);
82f73884 11996 p = write_ptid (p, endp, ptid);
38691318
KB
11997 *p++ = ',';
11998 p += hexnumstr (p, offset);
11999 *p++ = ',';
12000 p += hexnumstr (p, lm);
12001 *p++ = '\0';
12002
6d820c5c 12003 putpkt (rs->buf);
8d64371b 12004 getpkt (&rs->buf, 0);
ff52c073 12005 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
571dd617 12006 if (result == PACKET_OK)
38691318 12007 {
b926417a 12008 ULONGEST addr;
38691318 12009
8d64371b 12010 unpack_varlen_hex (rs->buf.data (), &addr);
b926417a 12011 return addr;
38691318 12012 }
571dd617 12013 else if (result == PACKET_UNKNOWN)
109c3e39
AC
12014 throw_error (TLS_GENERIC_ERROR,
12015 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 12016 else
109c3e39
AC
12017 throw_error (TLS_GENERIC_ERROR,
12018 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
12019 }
12020 else
109c3e39
AC
12021 throw_error (TLS_GENERIC_ERROR,
12022 _("TLS not supported or disabled on this target"));
38691318
KB
12023 /* Not reached. */
12024 return 0;
12025}
12026
711e434b
PM
12027/* Provide thread local base, i.e. Thread Information Block address.
12028 Returns 1 if ptid is found and thread_local_base is non zero. */
12029
57810aa7 12030bool
f6ac5f3d 12031remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 12032{
ff52c073 12033 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
12034 {
12035 struct remote_state *rs = get_remote_state ();
8d64371b
TT
12036 char *p = rs->buf.data ();
12037 char *endp = p + get_remote_packet_size ();
711e434b
PM
12038 enum packet_result result;
12039
12040 strcpy (p, "qGetTIBAddr:");
12041 p += strlen (p);
12042 p = write_ptid (p, endp, ptid);
12043 *p++ = '\0';
12044
12045 putpkt (rs->buf);
8d64371b 12046 getpkt (&rs->buf, 0);
ff52c073 12047 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
711e434b
PM
12048 if (result == PACKET_OK)
12049 {
b926417a 12050 ULONGEST val;
8d64371b 12051 unpack_varlen_hex (rs->buf.data (), &val);
711e434b 12052 if (addr)
b926417a 12053 *addr = (CORE_ADDR) val;
57810aa7 12054 return true;
711e434b
PM
12055 }
12056 else if (result == PACKET_UNKNOWN)
12057 error (_("Remote target doesn't support qGetTIBAddr packet"));
12058 else
12059 error (_("Remote target failed to process qGetTIBAddr request"));
12060 }
12061 else
12062 error (_("qGetTIBAddr not supported or disabled on this target"));
12063 /* Not reached. */
57810aa7 12064 return false;
711e434b
PM
12065}
12066
29709017
DJ
12067/* Support for inferring a target description based on the current
12068 architecture and the size of a 'g' packet. While the 'g' packet
12069 can have any size (since optional registers can be left off the
12070 end), some sizes are easily recognizable given knowledge of the
12071 approximate architecture. */
12072
12073struct remote_g_packet_guess
12074{
eefce37f
TT
12075 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12076 : bytes (bytes_),
12077 tdesc (tdesc_)
12078 {
12079 }
12080
29709017
DJ
12081 int bytes;
12082 const struct target_desc *tdesc;
12083};
29709017 12084
cb275538 12085struct remote_g_packet_data
29709017 12086{
eefce37f 12087 std::vector<remote_g_packet_guess> guesses;
29709017
DJ
12088};
12089
cb275538
TT
12090static const registry<gdbarch>::key<struct remote_g_packet_data>
12091 remote_g_packet_data_handle;
29709017 12092
cb275538
TT
12093static struct remote_g_packet_data *
12094get_g_packet_data (struct gdbarch *gdbarch)
29709017 12095{
cb275538
TT
12096 struct remote_g_packet_data *data
12097 = remote_g_packet_data_handle.get (gdbarch);
12098 if (data == nullptr)
12099 data = remote_g_packet_data_handle.emplace (gdbarch);
12100 return data;
29709017
DJ
12101}
12102
12103void
12104register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12105 const struct target_desc *tdesc)
12106{
cb275538 12107 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
29709017
DJ
12108
12109 gdb_assert (tdesc != NULL);
12110
eefce37f
TT
12111 for (const remote_g_packet_guess &guess : data->guesses)
12112 if (guess.bytes == bytes)
f34652de 12113 internal_error (_("Duplicate g packet description added for size %d"),
29709017
DJ
12114 bytes);
12115
eefce37f 12116 data->guesses.emplace_back (bytes, tdesc);
29709017
DJ
12117}
12118
eefce37f
TT
12119/* Return true if remote_read_description would do anything on this target
12120 and architecture, false otherwise. */
d962ef82 12121
eefce37f 12122static bool
d962ef82
DJ
12123remote_read_description_p (struct target_ops *target)
12124{
cb275538 12125 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
d962ef82 12126
eefce37f 12127 return !data->guesses.empty ();
d962ef82
DJ
12128}
12129
f6ac5f3d
PA
12130const struct target_desc *
12131remote_target::read_description ()
29709017 12132{
cb275538 12133 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
29709017 12134
d962ef82
DJ
12135 /* Do not try this during initial connection, when we do not know
12136 whether there is a running but stopped thread. */
55f6301a 12137 if (!target_has_execution () || inferior_ptid == null_ptid)
b6a8c27b 12138 return beneath ()->read_description ();
d962ef82 12139
eefce37f 12140 if (!data->guesses.empty ())
29709017 12141 {
29709017
DJ
12142 int bytes = send_g_packet ();
12143
eefce37f
TT
12144 for (const remote_g_packet_guess &guess : data->guesses)
12145 if (guess.bytes == bytes)
12146 return guess.tdesc;
29709017
DJ
12147
12148 /* We discard the g packet. A minor optimization would be to
12149 hold on to it, and fill the register cache once we have selected
12150 an architecture, but it's too tricky to do safely. */
12151 }
12152
b6a8c27b 12153 return beneath ()->read_description ();
29709017
DJ
12154}
12155
a6b151f1
DJ
12156/* Remote file transfer support. This is host-initiated I/O, not
12157 target-initiated; for target-initiated, see remote-fileio.c. */
12158
12159/* If *LEFT is at least the length of STRING, copy STRING to
12160 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12161 decrease *LEFT. Otherwise raise an error. */
12162
12163static void
a121b7c1 12164remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
12165{
12166 int len = strlen (string);
12167
12168 if (len > *left)
12169 error (_("Packet too long for target."));
12170
12171 memcpy (*buffer, string, len);
12172 *buffer += len;
12173 *left -= len;
12174
12175 /* NUL-terminate the buffer as a convenience, if there is
12176 room. */
12177 if (*left)
12178 **buffer = '\0';
12179}
12180
12181/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12182 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12183 decrease *LEFT. Otherwise raise an error. */
12184
12185static void
12186remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12187 int len)
12188{
12189 if (2 * len > *left)
12190 error (_("Packet too long for target."));
12191
12192 bin2hex (bytes, *buffer, len);
12193 *buffer += 2 * len;
12194 *left -= 2 * len;
12195
12196 /* NUL-terminate the buffer as a convenience, if there is
12197 room. */
12198 if (*left)
12199 **buffer = '\0';
12200}
12201
12202/* If *LEFT is large enough, convert VALUE to hex and add it to
12203 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12204 decrease *LEFT. Otherwise raise an error. */
12205
12206static void
12207remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12208{
12209 int len = hexnumlen (value);
12210
12211 if (len > *left)
12212 error (_("Packet too long for target."));
12213
12214 hexnumstr (*buffer, value);
12215 *buffer += len;
12216 *left -= len;
12217
12218 /* NUL-terminate the buffer as a convenience, if there is
12219 room. */
12220 if (*left)
12221 **buffer = '\0';
12222}
12223
12224/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
b872057a 12225 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
a6b151f1
DJ
12226 was included, and *ATTACHMENT to point to the start of the annex
12227 if any. The length of the packet isn't needed here; there may
12228 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12229
12230 Return 0 if the packet could be parsed, -1 if it could not. If
12231 -1 is returned, the other variables may not be initialized. */
12232
12233static int
aa2838cc 12234remote_hostio_parse_result (const char *buffer, int *retcode,
b872057a 12235 fileio_error *remote_errno, const char **attachment)
a6b151f1
DJ
12236{
12237 char *p, *p2;
12238
b872057a 12239 *remote_errno = FILEIO_SUCCESS;
a6b151f1
DJ
12240 *attachment = NULL;
12241
12242 if (buffer[0] != 'F')
12243 return -1;
12244
12245 errno = 0;
12246 *retcode = strtol (&buffer[1], &p, 16);
12247 if (errno != 0 || p == &buffer[1])
12248 return -1;
12249
12250 /* Check for ",errno". */
12251 if (*p == ',')
12252 {
12253 errno = 0;
b872057a 12254 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
a6b151f1
DJ
12255 if (errno != 0 || p + 1 == p2)
12256 return -1;
12257 p = p2;
12258 }
12259
12260 /* Check for ";attachment". If there is no attachment, the
12261 packet should end here. */
12262 if (*p == ';')
12263 {
12264 *attachment = p + 1;
12265 return 0;
12266 }
12267 else if (*p == '\0')
12268 return 0;
12269 else
12270 return -1;
12271}
12272
12273/* Send a prepared I/O packet to the target and read its response.
12274 The prepared packet is in the global RS->BUF before this function
12275 is called, and the answer is there when we return.
12276
12277 COMMAND_BYTES is the length of the request to send, which may include
12278 binary data. WHICH_PACKET is the packet configuration to check
12279 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12280 is set to the error number and -1 is returned. Otherwise the value
12281 returned by the function is returned.
12282
12283 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12284 attachment is expected; an error will be reported if there's a
12285 mismatch. If one is found, *ATTACHMENT will be set to point into
12286 the packet buffer and *ATTACHMENT_LEN will be set to the
12287 attachment's length. */
12288
6b8edb51
PA
12289int
12290remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
b872057a 12291 fileio_error *remote_errno, const char **attachment,
6b8edb51 12292 int *attachment_len)
a6b151f1
DJ
12293{
12294 struct remote_state *rs = get_remote_state ();
12295 int ret, bytes_read;
aa2838cc 12296 const char *attachment_tmp;
a6b151f1 12297
ff52c073 12298 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
12299 {
12300 *remote_errno = FILEIO_ENOSYS;
12301 return -1;
12302 }
12303
8d64371b
TT
12304 putpkt_binary (rs->buf.data (), command_bytes);
12305 bytes_read = getpkt_sane (&rs->buf, 0);
a6b151f1
DJ
12306
12307 /* If it timed out, something is wrong. Don't try to parse the
12308 buffer. */
12309 if (bytes_read < 0)
12310 {
12311 *remote_errno = FILEIO_EINVAL;
12312 return -1;
12313 }
12314
ff52c073 12315 switch (m_features.packet_ok (rs->buf, which_packet))
a6b151f1
DJ
12316 {
12317 case PACKET_ERROR:
12318 *remote_errno = FILEIO_EINVAL;
12319 return -1;
12320 case PACKET_UNKNOWN:
12321 *remote_errno = FILEIO_ENOSYS;
12322 return -1;
12323 case PACKET_OK:
12324 break;
12325 }
12326
8d64371b 12327 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
a6b151f1
DJ
12328 &attachment_tmp))
12329 {
12330 *remote_errno = FILEIO_EINVAL;
12331 return -1;
12332 }
12333
12334 /* Make sure we saw an attachment if and only if we expected one. */
12335 if ((attachment_tmp == NULL && attachment != NULL)
12336 || (attachment_tmp != NULL && attachment == NULL))
12337 {
12338 *remote_errno = FILEIO_EINVAL;
12339 return -1;
12340 }
12341
12342 /* If an attachment was found, it must point into the packet buffer;
12343 work out how many bytes there were. */
12344 if (attachment_tmp != NULL)
12345 {
12346 *attachment = attachment_tmp;
8d64371b 12347 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
a6b151f1
DJ
12348 }
12349
12350 return ret;
12351}
12352
dd194f6b 12353/* See declaration.h. */
80152258 12354
dd194f6b
PA
12355void
12356readahead_cache::invalidate ()
80152258 12357{
dd194f6b 12358 this->fd = -1;
80152258
PA
12359}
12360
dd194f6b 12361/* See declaration.h. */
80152258 12362
dd194f6b
PA
12363void
12364readahead_cache::invalidate_fd (int fd)
80152258 12365{
dd194f6b
PA
12366 if (this->fd == fd)
12367 this->fd = -1;
80152258
PA
12368}
12369
15a201c8
GB
12370/* Set the filesystem remote_hostio functions that take FILENAME
12371 arguments will use. Return 0 on success, or -1 if an error
12372 occurs (and set *REMOTE_ERRNO). */
12373
6b8edb51
PA
12374int
12375remote_target::remote_hostio_set_filesystem (struct inferior *inf,
b872057a 12376 fileio_error *remote_errno)
15a201c8
GB
12377{
12378 struct remote_state *rs = get_remote_state ();
12379 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
8d64371b 12380 char *p = rs->buf.data ();
15a201c8
GB
12381 int left = get_remote_packet_size () - 1;
12382 char arg[9];
12383 int ret;
12384
ff52c073 12385 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
15a201c8
GB
12386 return 0;
12387
12388 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12389 return 0;
12390
12391 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12392
12393 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12394 remote_buffer_add_string (&p, &left, arg);
12395
8d64371b 12396 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
15a201c8
GB
12397 remote_errno, NULL, NULL);
12398
ff52c073 12399 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
15a201c8
GB
12400 return 0;
12401
12402 if (ret == 0)
12403 rs->fs_pid = required_pid;
12404
12405 return ret;
12406}
12407
12e2a5fd 12408/* Implementation of to_fileio_open. */
a6b151f1 12409
6b8edb51
PA
12410int
12411remote_target::remote_hostio_open (inferior *inf, const char *filename,
12412 int flags, int mode, int warn_if_slow,
b872057a 12413 fileio_error *remote_errno)
a6b151f1
DJ
12414{
12415 struct remote_state *rs = get_remote_state ();
8d64371b 12416 char *p = rs->buf.data ();
a6b151f1
DJ
12417 int left = get_remote_packet_size () - 1;
12418
4313b8c0
GB
12419 if (warn_if_slow)
12420 {
12421 static int warning_issued = 0;
12422
6cb06a8c
TT
12423 gdb_printf (_("Reading %s from remote target...\n"),
12424 filename);
4313b8c0
GB
12425
12426 if (!warning_issued)
12427 {
12428 warning (_("File transfers from remote targets can be slow."
12429 " Use \"set sysroot\" to access files locally"
12430 " instead."));
12431 warning_issued = 1;
12432 }
12433 }
12434
15a201c8
GB
12435 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12436 return -1;
12437
a6b151f1
DJ
12438 remote_buffer_add_string (&p, &left, "vFile:open:");
12439
12440 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12441 strlen (filename));
12442 remote_buffer_add_string (&p, &left, ",");
12443
12444 remote_buffer_add_int (&p, &left, flags);
12445 remote_buffer_add_string (&p, &left, ",");
12446
12447 remote_buffer_add_int (&p, &left, mode);
12448
8d64371b 12449 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
a6b151f1
DJ
12450 remote_errno, NULL, NULL);
12451}
12452
f6ac5f3d
PA
12453int
12454remote_target::fileio_open (struct inferior *inf, const char *filename,
12455 int flags, int mode, int warn_if_slow,
b872057a 12456 fileio_error *remote_errno)
f6ac5f3d 12457{
6b8edb51 12458 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
12459 remote_errno);
12460}
12461
12e2a5fd 12462/* Implementation of to_fileio_pwrite. */
a6b151f1 12463
6b8edb51
PA
12464int
12465remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 12466 ULONGEST offset, fileio_error *remote_errno)
a6b151f1
DJ
12467{
12468 struct remote_state *rs = get_remote_state ();
8d64371b 12469 char *p = rs->buf.data ();
a6b151f1
DJ
12470 int left = get_remote_packet_size ();
12471 int out_len;
12472
dd194f6b 12473 rs->readahead_cache.invalidate_fd (fd);
80152258 12474
a6b151f1
DJ
12475 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12476
12477 remote_buffer_add_int (&p, &left, fd);
12478 remote_buffer_add_string (&p, &left, ",");
12479
12480 remote_buffer_add_int (&p, &left, offset);
12481 remote_buffer_add_string (&p, &left, ",");
12482
124e13d9 12483 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
8d64371b
TT
12484 (get_remote_packet_size ()
12485 - (p - rs->buf.data ())));
a6b151f1 12486
8d64371b 12487 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
a6b151f1
DJ
12488 remote_errno, NULL, NULL);
12489}
12490
f6ac5f3d
PA
12491int
12492remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 12493 ULONGEST offset, fileio_error *remote_errno)
f6ac5f3d 12494{
6b8edb51 12495 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12496}
12497
80152258
PA
12498/* Helper for the implementation of to_fileio_pread. Read the file
12499 from the remote side with vFile:pread. */
a6b151f1 12500
6b8edb51
PA
12501int
12502remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
b872057a 12503 ULONGEST offset, fileio_error *remote_errno)
a6b151f1
DJ
12504{
12505 struct remote_state *rs = get_remote_state ();
8d64371b 12506 char *p = rs->buf.data ();
aa2838cc 12507 const char *attachment;
a6b151f1
DJ
12508 int left = get_remote_packet_size ();
12509 int ret, attachment_len;
12510 int read_len;
12511
12512 remote_buffer_add_string (&p, &left, "vFile:pread:");
12513
12514 remote_buffer_add_int (&p, &left, fd);
12515 remote_buffer_add_string (&p, &left, ",");
12516
12517 remote_buffer_add_int (&p, &left, len);
12518 remote_buffer_add_string (&p, &left, ",");
12519
12520 remote_buffer_add_int (&p, &left, offset);
12521
8d64371b 12522 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
a6b151f1
DJ
12523 remote_errno, &attachment,
12524 &attachment_len);
12525
12526 if (ret < 0)
12527 return ret;
12528
bc20a4af 12529 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12530 read_buf, len);
12531 if (read_len != ret)
12532 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12533
12534 return ret;
12535}
12536
dd194f6b 12537/* See declaration.h. */
80152258 12538
dd194f6b
PA
12539int
12540readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12541 ULONGEST offset)
80152258 12542{
dd194f6b
PA
12543 if (this->fd == fd
12544 && this->offset <= offset
12545 && offset < this->offset + this->bufsize)
80152258 12546 {
dd194f6b 12547 ULONGEST max = this->offset + this->bufsize;
80152258
PA
12548
12549 if (offset + len > max)
12550 len = max - offset;
12551
dd194f6b 12552 memcpy (read_buf, this->buf + offset - this->offset, len);
80152258
PA
12553 return len;
12554 }
12555
12556 return 0;
12557}
12558
12559/* Implementation of to_fileio_pread. */
12560
6b8edb51
PA
12561int
12562remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 12563 ULONGEST offset, fileio_error *remote_errno)
80152258
PA
12564{
12565 int ret;
12566 struct remote_state *rs = get_remote_state ();
dd194f6b 12567 readahead_cache *cache = &rs->readahead_cache;
80152258 12568
dd194f6b 12569 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12570 if (ret > 0)
12571 {
12572 cache->hit_count++;
12573
2189c312
SM
12574 remote_debug_printf ("readahead cache hit %s",
12575 pulongest (cache->hit_count));
80152258
PA
12576 return ret;
12577 }
12578
12579 cache->miss_count++;
2189c312
SM
12580
12581 remote_debug_printf ("readahead cache miss %s",
12582 pulongest (cache->miss_count));
80152258
PA
12583
12584 cache->fd = fd;
12585 cache->offset = offset;
12586 cache->bufsize = get_remote_packet_size ();
224c3ddb 12587 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258 12588
6b8edb51 12589 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
80152258
PA
12590 cache->offset, remote_errno);
12591 if (ret <= 0)
12592 {
dd194f6b 12593 cache->invalidate_fd (fd);
80152258
PA
12594 return ret;
12595 }
12596
12597 cache->bufsize = ret;
dd194f6b 12598 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12599}
12600
f6ac5f3d
PA
12601int
12602remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 12603 ULONGEST offset, fileio_error *remote_errno)
f6ac5f3d 12604{
6b8edb51 12605 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12606}
12607
12e2a5fd 12608/* Implementation of to_fileio_close. */
a6b151f1 12609
6b8edb51 12610int
b872057a 12611remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
a6b151f1
DJ
12612{
12613 struct remote_state *rs = get_remote_state ();
8d64371b 12614 char *p = rs->buf.data ();
a6b151f1
DJ
12615 int left = get_remote_packet_size () - 1;
12616
dd194f6b 12617 rs->readahead_cache.invalidate_fd (fd);
80152258 12618
a6b151f1
DJ
12619 remote_buffer_add_string (&p, &left, "vFile:close:");
12620
12621 remote_buffer_add_int (&p, &left, fd);
12622
8d64371b 12623 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
a6b151f1
DJ
12624 remote_errno, NULL, NULL);
12625}
12626
f6ac5f3d 12627int
b872057a 12628remote_target::fileio_close (int fd, fileio_error *remote_errno)
f6ac5f3d 12629{
6b8edb51 12630 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12631}
12632
12e2a5fd 12633/* Implementation of to_fileio_unlink. */
a6b151f1 12634
6b8edb51
PA
12635int
12636remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
b872057a 12637 fileio_error *remote_errno)
a6b151f1
DJ
12638{
12639 struct remote_state *rs = get_remote_state ();
8d64371b 12640 char *p = rs->buf.data ();
a6b151f1
DJ
12641 int left = get_remote_packet_size () - 1;
12642
15a201c8
GB
12643 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12644 return -1;
12645
a6b151f1
DJ
12646 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12647
12648 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12649 strlen (filename));
12650
8d64371b 12651 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
a6b151f1
DJ
12652 remote_errno, NULL, NULL);
12653}
12654
f6ac5f3d
PA
12655int
12656remote_target::fileio_unlink (struct inferior *inf, const char *filename,
b872057a 12657 fileio_error *remote_errno)
f6ac5f3d 12658{
6b8edb51 12659 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12660}
12661
12e2a5fd 12662/* Implementation of to_fileio_readlink. */
b9e7b9c3 12663
f6ac5f3d
PA
12664gdb::optional<std::string>
12665remote_target::fileio_readlink (struct inferior *inf, const char *filename,
b872057a 12666 fileio_error *remote_errno)
b9e7b9c3
UW
12667{
12668 struct remote_state *rs = get_remote_state ();
8d64371b 12669 char *p = rs->buf.data ();
aa2838cc 12670 const char *attachment;
b9e7b9c3
UW
12671 int left = get_remote_packet_size ();
12672 int len, attachment_len;
12673 int read_len;
b9e7b9c3 12674
15a201c8 12675 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12676 return {};
15a201c8 12677
b9e7b9c3
UW
12678 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12679
12680 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12681 strlen (filename));
12682
8d64371b 12683 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
b9e7b9c3
UW
12684 remote_errno, &attachment,
12685 &attachment_len);
12686
12687 if (len < 0)
e0d3522b 12688 return {};
b9e7b9c3 12689
e0d3522b 12690 std::string ret (len, '\0');
b9e7b9c3 12691
bc20a4af 12692 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12693 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12694 if (read_len != len)
12695 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12696
b9e7b9c3
UW
12697 return ret;
12698}
12699
12e2a5fd 12700/* Implementation of to_fileio_fstat. */
0a93529c 12701
f6ac5f3d 12702int
b872057a 12703remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
0a93529c
GB
12704{
12705 struct remote_state *rs = get_remote_state ();
8d64371b 12706 char *p = rs->buf.data ();
0a93529c
GB
12707 int left = get_remote_packet_size ();
12708 int attachment_len, ret;
aa2838cc 12709 const char *attachment;
0a93529c
GB
12710 struct fio_stat fst;
12711 int read_len;
12712
464b0089
GB
12713 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12714
12715 remote_buffer_add_int (&p, &left, fd);
12716
8d64371b 12717 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
464b0089
GB
12718 remote_errno, &attachment,
12719 &attachment_len);
12720 if (ret < 0)
0a93529c 12721 {
464b0089
GB
12722 if (*remote_errno != FILEIO_ENOSYS)
12723 return ret;
12724
0a93529c
GB
12725 /* Strictly we should return -1, ENOSYS here, but when
12726 "set sysroot remote:" was implemented in August 2008
12727 BFD's need for a stat function was sidestepped with
12728 this hack. This was not remedied until March 2015
12729 so we retain the previous behavior to avoid breaking
12730 compatibility.
12731
12732 Note that the memset is a March 2015 addition; older
12733 GDBs set st_size *and nothing else* so the structure
12734 would have garbage in all other fields. This might
12735 break something but retaining the previous behavior
12736 here would be just too wrong. */
12737
12738 memset (st, 0, sizeof (struct stat));
12739 st->st_size = INT_MAX;
12740 return 0;
12741 }
12742
0a93529c
GB
12743 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12744 (gdb_byte *) &fst, sizeof (fst));
12745
12746 if (read_len != ret)
12747 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12748
12749 if (read_len != sizeof (fst))
12750 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12751 read_len, (int) sizeof (fst));
12752
12753 remote_fileio_to_host_stat (&fst, st);
12754
12755 return 0;
12756}
12757
12e2a5fd 12758/* Implementation of to_filesystem_is_local. */
e3dd7556 12759
57810aa7 12760bool
f6ac5f3d 12761remote_target::filesystem_is_local ()
e3dd7556
GB
12762{
12763 /* Valgrind GDB presents itself as a remote target but works
12764 on the local filesystem: it does not implement remote get
12765 and users are not expected to set a sysroot. To handle
12766 this case we treat the remote filesystem as local if the
12767 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12768 does not support vFile:open. */
e0700ba4 12769 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
e3dd7556 12770 {
ff52c073 12771 packet_support ps = m_features.packet_support (PACKET_vFile_open);
e3dd7556
GB
12772
12773 if (ps == PACKET_SUPPORT_UNKNOWN)
12774 {
b872057a
SM
12775 int fd;
12776 fileio_error remote_errno;
e3dd7556
GB
12777
12778 /* Try opening a file to probe support. The supplied
12779 filename is irrelevant, we only care about whether
12780 the stub recognizes the packet or not. */
6b8edb51 12781 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12782 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12783 &remote_errno);
12784
12785 if (fd >= 0)
6b8edb51 12786 remote_hostio_close (fd, &remote_errno);
e3dd7556 12787
ff52c073 12788 ps = m_features.packet_support (PACKET_vFile_open);
e3dd7556
GB
12789 }
12790
12791 if (ps == PACKET_DISABLE)
12792 {
12793 static int warning_issued = 0;
12794
12795 if (!warning_issued)
12796 {
12797 warning (_("remote target does not support file"
12798 " transfer, attempting to access files"
12799 " from local filesystem."));
12800 warning_issued = 1;
12801 }
12802
57810aa7 12803 return true;
e3dd7556
GB
12804 }
12805 }
12806
57810aa7 12807 return false;
e3dd7556
GB
12808}
12809
a6b151f1 12810static char *
b872057a 12811remote_hostio_error (fileio_error errnum)
a6b151f1 12812{
517a63c2 12813 int host_error = fileio_error_to_host (errnum);
a6b151f1
DJ
12814
12815 if (host_error == -1)
12816 error (_("Unknown remote I/O error %d"), errnum);
12817 else
12818 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12819}
12820
440b7aec
PA
12821/* A RAII wrapper around a remote file descriptor. */
12822
12823class scoped_remote_fd
a6b151f1 12824{
440b7aec 12825public:
6b8edb51
PA
12826 scoped_remote_fd (remote_target *remote, int fd)
12827 : m_remote (remote), m_fd (fd)
440b7aec
PA
12828 {
12829 }
a6b151f1 12830
440b7aec
PA
12831 ~scoped_remote_fd ()
12832 {
12833 if (m_fd != -1)
12834 {
12835 try
12836 {
b872057a 12837 fileio_error remote_errno;
6b8edb51 12838 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12839 }
12840 catch (...)
12841 {
12842 /* Swallow exception before it escapes the dtor. If
12843 something goes wrong, likely the connection is gone,
12844 and there's nothing else that can be done. */
12845 }
12846 }
12847 }
12848
12849 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12850
12851 /* Release ownership of the file descriptor, and return it. */
88a774b9 12852 ATTRIBUTE_UNUSED_RESULT int release () noexcept
440b7aec
PA
12853 {
12854 int fd = m_fd;
12855 m_fd = -1;
12856 return fd;
12857 }
12858
12859 /* Return the owned file descriptor. */
12860 int get () const noexcept
12861 {
12862 return m_fd;
12863 }
12864
12865private:
6b8edb51
PA
12866 /* The remote target. */
12867 remote_target *m_remote;
12868
440b7aec
PA
12869 /* The owned remote I/O file descriptor. */
12870 int m_fd;
12871};
a6b151f1
DJ
12872
12873void
12874remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12875{
12876 remote_target *remote = get_current_remote_target ();
12877
12878 if (remote == nullptr)
12879 error (_("command can only be used with remote target"));
12880
12881 remote->remote_file_put (local_file, remote_file, from_tty);
12882}
12883
12884void
12885remote_target::remote_file_put (const char *local_file, const char *remote_file,
12886 int from_tty)
a6b151f1 12887{
b872057a
SM
12888 int retcode, bytes, io_size;
12889 fileio_error remote_errno;
a6b151f1
DJ
12890 int bytes_in_buffer;
12891 int saw_eof;
12892 ULONGEST offset;
a6b151f1 12893
d419f42d 12894 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12895 if (file == NULL)
12896 perror_with_name (local_file);
a6b151f1 12897
440b7aec 12898 scoped_remote_fd fd
6b8edb51
PA
12899 (this, remote_hostio_open (NULL,
12900 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12901 | FILEIO_O_TRUNC),
12902 0700, 0, &remote_errno));
440b7aec 12903 if (fd.get () == -1)
a6b151f1
DJ
12904 remote_hostio_error (remote_errno);
12905
12906 /* Send up to this many bytes at once. They won't all fit in the
12907 remote packet limit, so we'll transfer slightly fewer. */
12908 io_size = get_remote_packet_size ();
5ca3b260 12909 gdb::byte_vector buffer (io_size);
a6b151f1 12910
a6b151f1
DJ
12911 bytes_in_buffer = 0;
12912 saw_eof = 0;
12913 offset = 0;
12914 while (bytes_in_buffer || !saw_eof)
12915 {
12916 if (!saw_eof)
12917 {
5ca3b260 12918 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 12919 io_size - bytes_in_buffer,
d419f42d 12920 file.get ());
a6b151f1
DJ
12921 if (bytes == 0)
12922 {
d419f42d 12923 if (ferror (file.get ()))
a6b151f1
DJ
12924 error (_("Error reading %s."), local_file);
12925 else
12926 {
12927 /* EOF. Unless there is something still in the
12928 buffer from the last iteration, we are done. */
12929 saw_eof = 1;
12930 if (bytes_in_buffer == 0)
12931 break;
12932 }
12933 }
12934 }
12935 else
12936 bytes = 0;
12937
12938 bytes += bytes_in_buffer;
12939 bytes_in_buffer = 0;
12940
5ca3b260 12941 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 12942 offset, &remote_errno);
a6b151f1
DJ
12943
12944 if (retcode < 0)
12945 remote_hostio_error (remote_errno);
12946 else if (retcode == 0)
12947 error (_("Remote write of %d bytes returned 0!"), bytes);
12948 else if (retcode < bytes)
12949 {
12950 /* Short write. Save the rest of the read data for the next
12951 write. */
12952 bytes_in_buffer = bytes - retcode;
5ca3b260 12953 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
12954 }
12955
12956 offset += retcode;
12957 }
12958
6b8edb51 12959 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12960 remote_hostio_error (remote_errno);
12961
12962 if (from_tty)
6cb06a8c 12963 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
a6b151f1
DJ
12964}
12965
12966void
12967remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
12968{
12969 remote_target *remote = get_current_remote_target ();
12970
12971 if (remote == nullptr)
12972 error (_("command can only be used with remote target"));
12973
12974 remote->remote_file_get (remote_file, local_file, from_tty);
12975}
12976
12977void
12978remote_target::remote_file_get (const char *remote_file, const char *local_file,
12979 int from_tty)
a6b151f1 12980{
b872057a
SM
12981 fileio_error remote_errno;
12982 int bytes, io_size;
a6b151f1 12983 ULONGEST offset;
a6b151f1 12984
440b7aec 12985 scoped_remote_fd fd
6b8edb51
PA
12986 (this, remote_hostio_open (NULL,
12987 remote_file, FILEIO_O_RDONLY, 0, 0,
12988 &remote_errno));
440b7aec 12989 if (fd.get () == -1)
a6b151f1
DJ
12990 remote_hostio_error (remote_errno);
12991
d419f42d 12992 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12993 if (file == NULL)
12994 perror_with_name (local_file);
a6b151f1
DJ
12995
12996 /* Send up to this many bytes at once. They won't all fit in the
12997 remote packet limit, so we'll transfer slightly fewer. */
12998 io_size = get_remote_packet_size ();
5ca3b260 12999 gdb::byte_vector buffer (io_size);
a6b151f1 13000
a6b151f1
DJ
13001 offset = 0;
13002 while (1)
13003 {
5ca3b260 13004 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 13005 &remote_errno);
a6b151f1
DJ
13006 if (bytes == 0)
13007 /* Success, but no bytes, means end-of-file. */
13008 break;
13009 if (bytes == -1)
13010 remote_hostio_error (remote_errno);
13011
13012 offset += bytes;
13013
5ca3b260 13014 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
13015 if (bytes == 0)
13016 perror_with_name (local_file);
13017 }
13018
6b8edb51 13019 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
13020 remote_hostio_error (remote_errno);
13021
13022 if (from_tty)
6cb06a8c 13023 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
a6b151f1
DJ
13024}
13025
13026void
13027remote_file_delete (const char *remote_file, int from_tty)
13028{
6b8edb51 13029 remote_target *remote = get_current_remote_target ();
a6b151f1 13030
6b8edb51 13031 if (remote == nullptr)
a6b151f1
DJ
13032 error (_("command can only be used with remote target"));
13033
6b8edb51
PA
13034 remote->remote_file_delete (remote_file, from_tty);
13035}
13036
13037void
13038remote_target::remote_file_delete (const char *remote_file, int from_tty)
13039{
b872057a
SM
13040 int retcode;
13041 fileio_error remote_errno;
6b8edb51
PA
13042
13043 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
13044 if (retcode == -1)
13045 remote_hostio_error (remote_errno);
13046
13047 if (from_tty)
6cb06a8c 13048 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
a6b151f1
DJ
13049}
13050
13051static void
ac88e2de 13052remote_put_command (const char *args, int from_tty)
a6b151f1 13053{
d1a41061
PP
13054 if (args == NULL)
13055 error_no_arg (_("file to put"));
13056
773a1edc 13057 gdb_argv argv (args);
a6b151f1
DJ
13058 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13059 error (_("Invalid parameters to remote put"));
13060
13061 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
13062}
13063
13064static void
ac88e2de 13065remote_get_command (const char *args, int from_tty)
a6b151f1 13066{
d1a41061
PP
13067 if (args == NULL)
13068 error_no_arg (_("file to get"));
13069
773a1edc 13070 gdb_argv argv (args);
a6b151f1
DJ
13071 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13072 error (_("Invalid parameters to remote get"));
13073
13074 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
13075}
13076
13077static void
ac88e2de 13078remote_delete_command (const char *args, int from_tty)
a6b151f1 13079{
d1a41061
PP
13080 if (args == NULL)
13081 error_no_arg (_("file to delete"));
13082
773a1edc 13083 gdb_argv argv (args);
a6b151f1
DJ
13084 if (argv[0] == NULL || argv[1] != NULL)
13085 error (_("Invalid parameters to remote delete"));
13086
13087 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
13088}
13089
57810aa7 13090bool
f6ac5f3d 13091remote_target::can_execute_reverse ()
b2175913 13092{
ff52c073
CS
13093 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13094 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 13095 return true;
40ab02ce 13096 else
57810aa7 13097 return false;
b2175913
MS
13098}
13099
57810aa7 13100bool
f6ac5f3d 13101remote_target::supports_non_stop ()
74531fed 13102{
57810aa7 13103 return true;
74531fed
PA
13104}
13105
57810aa7 13106bool
f6ac5f3d 13107remote_target::supports_disable_randomization ()
03583c20
UW
13108{
13109 /* Only supported in extended mode. */
57810aa7 13110 return false;
03583c20
UW
13111}
13112
57810aa7 13113bool
f6ac5f3d 13114remote_target::supports_multi_process ()
8a305172 13115{
ff52c073 13116 return m_features.remote_multi_process_p ();
8a305172
PA
13117}
13118
ff52c073
CS
13119int
13120remote_target::remote_supports_cond_tracepoints ()
782b2b07 13121{
ff52c073
CS
13122 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13123 == PACKET_ENABLE);
782b2b07
SS
13124}
13125
57810aa7 13126bool
f6ac5f3d 13127remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 13128{
ff52c073
CS
13129 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13130 == PACKET_ENABLE);
3788aec7
LM
13131}
13132
ff52c073
CS
13133int
13134remote_target::remote_supports_fast_tracepoints ()
7a697b8d 13135{
ff52c073 13136 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
13137}
13138
ff52c073
CS
13139int
13140remote_target::remote_supports_static_tracepoints ()
0fb4aa4b 13141{
ff52c073 13142 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
13143}
13144
ff52c073
CS
13145int
13146remote_target::remote_supports_install_in_trace ()
1e4d1764 13147{
ff52c073 13148 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
13149}
13150
57810aa7 13151bool
f6ac5f3d 13152remote_target::supports_enable_disable_tracepoint ()
d248b706 13153{
ff52c073 13154 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
4082afcc 13155 == PACKET_ENABLE);
d248b706
KY
13156}
13157
57810aa7 13158bool
f6ac5f3d 13159remote_target::supports_string_tracing ()
3065dfb6 13160{
ff52c073 13161 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
13162}
13163
57810aa7 13164bool
f6ac5f3d 13165remote_target::can_run_breakpoint_commands ()
d3ce09f5 13166{
ff52c073 13167 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
13168}
13169
f6ac5f3d
PA
13170void
13171remote_target::trace_init ()
35b1e5cc 13172{
b6bb3468
PA
13173 struct remote_state *rs = get_remote_state ();
13174
35b1e5cc 13175 putpkt ("QTinit");
b6bb3468 13176 remote_get_noisy_reply ();
8d64371b 13177 if (strcmp (rs->buf.data (), "OK") != 0)
35b1e5cc
SS
13178 error (_("Target does not support this command."));
13179}
13180
409873ef
SS
13181/* Recursive routine to walk through command list including loops, and
13182 download packets for each command. */
13183
6b8edb51
PA
13184void
13185remote_target::remote_download_command_source (int num, ULONGEST addr,
13186 struct command_line *cmds)
409873ef
SS
13187{
13188 struct remote_state *rs = get_remote_state ();
13189 struct command_line *cmd;
13190
13191 for (cmd = cmds; cmd; cmd = cmd->next)
13192 {
0df8b418 13193 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13194 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13195 encode_source_string (num, addr, "cmd", cmd->line,
8d64371b
TT
13196 rs->buf.data () + strlen (rs->buf.data ()),
13197 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13198 putpkt (rs->buf);
b6bb3468 13199 remote_get_noisy_reply ();
8d64371b 13200 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13201 warning (_("Target does not support source download."));
13202
13203 if (cmd->control_type == while_control
13204 || cmd->control_type == while_stepping_control)
13205 {
12973681 13206 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 13207
0df8b418 13208 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13209 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13210 encode_source_string (num, addr, "cmd", "end",
8d64371b
TT
13211 rs->buf.data () + strlen (rs->buf.data ()),
13212 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13213 putpkt (rs->buf);
b6bb3468 13214 remote_get_noisy_reply ();
8d64371b 13215 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13216 warning (_("Target does not support source download."));
13217 }
13218 }
13219}
13220
f6ac5f3d
PA
13221void
13222remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc
SS
13223{
13224 CORE_ADDR tpaddr;
409873ef 13225 char addrbuf[40];
b44ec619
SM
13226 std::vector<std::string> tdp_actions;
13227 std::vector<std::string> stepping_actions;
35b1e5cc 13228 char *pkt;
e8ba3115 13229 struct breakpoint *b = loc->owner;
d9b3f62e 13230 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 13231 struct remote_state *rs = get_remote_state ();
3df3a985 13232 int ret;
ff36536c 13233 const char *err_msg = _("Tracepoint packet too large for target.");
3df3a985
PFC
13234 size_t size_left;
13235
13236 /* We use a buffer other than rs->buf because we'll build strings
13237 across multiple statements, and other statements in between could
13238 modify rs->buf. */
13239 gdb::char_vector buf (get_remote_packet_size ());
35b1e5cc 13240
dc673c81 13241 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
13242
13243 tpaddr = loc->address;
53807e9f 13244 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
3df3a985
PFC
13245 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13246 b->number, addrbuf, /* address */
13247 (b->enable_state == bp_enabled ? 'E' : 'D'),
13248 t->step_count, t->pass_count);
13249
13250 if (ret < 0 || ret >= buf.size ())
a7f25a84 13251 error ("%s", err_msg);
3df3a985 13252
e8ba3115
YQ
13253 /* Fast tracepoints are mostly handled by the target, but we can
13254 tell the target how big of an instruction block should be moved
13255 around. */
13256 if (b->type == bp_fast_tracepoint)
13257 {
13258 /* Only test for support at download time; we may not know
13259 target capabilities at definition time. */
13260 if (remote_supports_fast_tracepoints ())
35b1e5cc 13261 {
6b940e6a
PL
13262 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13263 NULL))
3df3a985
PFC
13264 {
13265 size_left = buf.size () - strlen (buf.data ());
13266 ret = snprintf (buf.data () + strlen (buf.data ()),
13267 size_left, ":F%x",
13268 gdb_insn_length (loc->gdbarch, tpaddr));
13269
13270 if (ret < 0 || ret >= size_left)
a7f25a84 13271 error ("%s", err_msg);
3df3a985 13272 }
35b1e5cc 13273 else
e8ba3115
YQ
13274 /* If it passed validation at definition but fails now,
13275 something is very wrong. */
f34652de 13276 internal_error (_("Fast tracepoint not valid during download"));
35b1e5cc 13277 }
e8ba3115
YQ
13278 else
13279 /* Fast tracepoints are functionally identical to regular
13280 tracepoints, so don't take lack of support as a reason to
13281 give up on the trace run. */
13282 warning (_("Target does not support fast tracepoints, "
13283 "downloading %d as regular tracepoint"), b->number);
13284 }
7b572efb
TT
13285 else if (b->type == bp_static_tracepoint
13286 || b->type == bp_static_marker_tracepoint)
e8ba3115
YQ
13287 {
13288 /* Only test for support at download time; we may not know
13289 target capabilities at definition time. */
13290 if (remote_supports_static_tracepoints ())
0fb4aa4b 13291 {
e8ba3115 13292 struct static_tracepoint_marker marker;
0fb4aa4b 13293
e8ba3115 13294 if (target_static_tracepoint_marker_at (tpaddr, &marker))
3df3a985
PFC
13295 {
13296 size_left = buf.size () - strlen (buf.data ());
13297 ret = snprintf (buf.data () + strlen (buf.data ()),
13298 size_left, ":S");
13299
13300 if (ret < 0 || ret >= size_left)
a7f25a84 13301 error ("%s", err_msg);
3df3a985 13302 }
0fb4aa4b 13303 else
e8ba3115 13304 error (_("Static tracepoint not valid during download"));
0fb4aa4b 13305 }
e8ba3115
YQ
13306 else
13307 /* Fast tracepoints are functionally identical to regular
13308 tracepoints, so don't take lack of support as a reason
13309 to give up on the trace run. */
13310 error (_("Target does not support static tracepoints"));
13311 }
13312 /* If the tracepoint has a conditional, make it into an agent
13313 expression and append to the definition. */
13314 if (loc->cond)
13315 {
13316 /* Only test support at download time, we may not know target
13317 capabilities at definition time. */
13318 if (remote_supports_cond_tracepoints ())
35b1e5cc 13319 {
3df3a985
PFC
13320 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13321 loc->cond.get ());
13322
13323 size_left = buf.size () - strlen (buf.data ());
13324
13325 ret = snprintf (buf.data () + strlen (buf.data ()),
13326 size_left, ":X%x,", aexpr->len);
13327
13328 if (ret < 0 || ret >= size_left)
a7f25a84 13329 error ("%s", err_msg);
3df3a985
PFC
13330
13331 size_left = buf.size () - strlen (buf.data ());
13332
13333 /* Two bytes to encode each aexpr byte, plus the terminating
13334 null byte. */
13335 if (aexpr->len * 2 + 1 > size_left)
a7f25a84 13336 error ("%s", err_msg);
3df3a985
PFC
13337
13338 pkt = buf.data () + strlen (buf.data ());
13339
b44ec619 13340 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
13341 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13342 *pkt = '\0';
35b1e5cc 13343 }
e8ba3115
YQ
13344 else
13345 warning (_("Target does not support conditional tracepoints, "
13346 "ignoring tp %d cond"), b->number);
13347 }
35b1e5cc 13348
e0700ba4 13349 if (b->commands || !default_collect.empty ())
3df3a985
PFC
13350 {
13351 size_left = buf.size () - strlen (buf.data ());
13352
13353 ret = snprintf (buf.data () + strlen (buf.data ()),
13354 size_left, "-");
13355
13356 if (ret < 0 || ret >= size_left)
a7f25a84 13357 error ("%s", err_msg);
3df3a985
PFC
13358 }
13359
13360 putpkt (buf.data ());
b6bb3468 13361 remote_get_noisy_reply ();
8d64371b 13362 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13363 error (_("Target does not support tracepoints."));
35b1e5cc 13364
e8ba3115 13365 /* do_single_steps (t); */
b44ec619
SM
13366 for (auto action_it = tdp_actions.begin ();
13367 action_it != tdp_actions.end (); action_it++)
e8ba3115 13368 {
b44ec619
SM
13369 QUIT; /* Allow user to bail out with ^C. */
13370
aa6f3694 13371 bool has_more = ((action_it + 1) != tdp_actions.end ()
b44ec619
SM
13372 || !stepping_actions.empty ());
13373
3df3a985
PFC
13374 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13375 b->number, addrbuf, /* address */
13376 action_it->c_str (),
13377 has_more ? '-' : 0);
13378
13379 if (ret < 0 || ret >= buf.size ())
a7f25a84 13380 error ("%s", err_msg);
3df3a985
PFC
13381
13382 putpkt (buf.data ());
b44ec619 13383 remote_get_noisy_reply ();
8d64371b 13384 if (strcmp (rs->buf.data (), "OK"))
b44ec619 13385 error (_("Error on target while setting tracepoints."));
e8ba3115 13386 }
409873ef 13387
05abfc39
PFC
13388 for (auto action_it = stepping_actions.begin ();
13389 action_it != stepping_actions.end (); action_it++)
13390 {
13391 QUIT; /* Allow user to bail out with ^C. */
13392
13393 bool is_first = action_it == stepping_actions.begin ();
aa6f3694 13394 bool has_more = (action_it + 1) != stepping_actions.end ();
05abfc39 13395
3df3a985
PFC
13396 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13397 b->number, addrbuf, /* address */
13398 is_first ? "S" : "",
13399 action_it->c_str (),
13400 has_more ? "-" : "");
13401
13402 if (ret < 0 || ret >= buf.size ())
a7f25a84 13403 error ("%s", err_msg);
3df3a985
PFC
13404
13405 putpkt (buf.data ());
05abfc39 13406 remote_get_noisy_reply ();
8d64371b 13407 if (strcmp (rs->buf.data (), "OK"))
05abfc39
PFC
13408 error (_("Error on target while setting tracepoints."));
13409 }
b44ec619 13410
ff52c073 13411 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 13412 {
264f9890 13413 if (b->locspec != nullptr)
409873ef 13414 {
3df3a985
PFC
13415 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13416
13417 if (ret < 0 || ret >= buf.size ())
a7f25a84 13418 error ("%s", err_msg);
3df3a985 13419
709438c7 13420 const char *str = b->locspec->to_string ();
264f9890 13421 encode_source_string (b->number, loc->address, "at", str,
3df3a985
PFC
13422 buf.data () + strlen (buf.data ()),
13423 buf.size () - strlen (buf.data ()));
13424 putpkt (buf.data ());
b6bb3468 13425 remote_get_noisy_reply ();
8d64371b 13426 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13427 warning (_("Target does not support source download."));
409873ef 13428 }
e8ba3115
YQ
13429 if (b->cond_string)
13430 {
3df3a985
PFC
13431 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13432
13433 if (ret < 0 || ret >= buf.size ())
a7f25a84 13434 error ("%s", err_msg);
3df3a985 13435
e8ba3115 13436 encode_source_string (b->number, loc->address,
6f781ee3 13437 "cond", b->cond_string.get (),
3df3a985
PFC
13438 buf.data () + strlen (buf.data ()),
13439 buf.size () - strlen (buf.data ()));
13440 putpkt (buf.data ());
b6bb3468 13441 remote_get_noisy_reply ();
8d64371b 13442 if (strcmp (rs->buf.data (), "OK"))
e8ba3115
YQ
13443 warning (_("Target does not support source download."));
13444 }
13445 remote_download_command_source (b->number, loc->address,
13446 breakpoint_commands (b));
35b1e5cc 13447 }
35b1e5cc
SS
13448}
13449
57810aa7 13450bool
f6ac5f3d 13451remote_target::can_download_tracepoint ()
1e4d1764 13452{
1e51243a
PA
13453 struct remote_state *rs = get_remote_state ();
13454 struct trace_status *ts;
13455 int status;
13456
13457 /* Don't try to install tracepoints until we've relocated our
13458 symbols, and fetched and merged the target's tracepoint list with
13459 ours. */
13460 if (rs->starting_up)
57810aa7 13461 return false;
1e51243a
PA
13462
13463 ts = current_trace_status ();
f6ac5f3d 13464 status = get_trace_status (ts);
1e4d1764
YQ
13465
13466 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13467 return false;
1e4d1764
YQ
13468
13469 /* If we are in a tracing experiment, but remote stub doesn't support
13470 installing tracepoint in trace, we have to return. */
13471 if (!remote_supports_install_in_trace ())
57810aa7 13472 return false;
1e4d1764 13473
57810aa7 13474 return true;
1e4d1764
YQ
13475}
13476
13477
f6ac5f3d
PA
13478void
13479remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
13480{
13481 struct remote_state *rs = get_remote_state ();
00bf0b85 13482 char *p;
35b1e5cc 13483
8d64371b 13484 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
13485 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13486 tsv.builtin);
8d64371b
TT
13487 p = rs->buf.data () + strlen (rs->buf.data ());
13488 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13489 >= get_remote_packet_size ())
00bf0b85 13490 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 13491 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 13492 *p++ = '\0';
35b1e5cc 13493 putpkt (rs->buf);
b6bb3468 13494 remote_get_noisy_reply ();
8d64371b 13495 if (rs->buf[0] == '\0')
ad91cd99 13496 error (_("Target does not support this command."));
8d64371b 13497 if (strcmp (rs->buf.data (), "OK") != 0)
ad91cd99 13498 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13499}
13500
f6ac5f3d
PA
13501void
13502remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13503{
13504 struct remote_state *rs = get_remote_state ();
d248b706 13505
8d64371b 13506 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
53807e9f
TT
13507 location->owner->number,
13508 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13509 putpkt (rs->buf);
b6bb3468 13510 remote_get_noisy_reply ();
8d64371b 13511 if (rs->buf[0] == '\0')
d248b706 13512 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
8d64371b 13513 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13514 error (_("Error on target while enabling tracepoint."));
13515}
13516
f6ac5f3d
PA
13517void
13518remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13519{
13520 struct remote_state *rs = get_remote_state ();
d248b706 13521
8d64371b 13522 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
53807e9f
TT
13523 location->owner->number,
13524 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13525 putpkt (rs->buf);
b6bb3468 13526 remote_get_noisy_reply ();
8d64371b 13527 if (rs->buf[0] == '\0')
d248b706 13528 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
8d64371b 13529 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13530 error (_("Error on target while disabling tracepoint."));
13531}
13532
f6ac5f3d
PA
13533void
13534remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13535{
13536 asection *s;
13537 bfd_size_type size;
608bcef2 13538 bfd_vma vma;
35b1e5cc 13539 int anysecs = 0;
c2fa21f1 13540 int offset = 0;
f493c217 13541 bfd *abfd = current_program_space->exec_bfd ();
35b1e5cc 13542
f493c217 13543 if (!abfd)
35b1e5cc
SS
13544 return; /* No information to give. */
13545
b6bb3468
PA
13546 struct remote_state *rs = get_remote_state ();
13547
8d64371b
TT
13548 strcpy (rs->buf.data (), "QTro");
13549 offset = strlen (rs->buf.data ());
f493c217 13550 for (s = abfd->sections; s; s = s->next)
35b1e5cc
SS
13551 {
13552 char tmp1[40], tmp2[40];
c2fa21f1 13553 int sec_length;
35b1e5cc 13554
f493c217
AM
13555 if ((s->flags & SEC_LOAD) == 0
13556 /* || (s->flags & SEC_CODE) == 0 */
13557 || (s->flags & SEC_READONLY) == 0)
35b1e5cc
SS
13558 continue;
13559
13560 anysecs = 1;
fd361982
AM
13561 vma = bfd_section_vma (s);
13562 size = bfd_section_size (s);
f493c217
AM
13563 bfd_sprintf_vma (abfd, tmp1, vma);
13564 bfd_sprintf_vma (abfd, tmp2, vma + size);
c2fa21f1 13565 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
8d64371b 13566 if (offset + sec_length + 1 > rs->buf.size ())
c2fa21f1 13567 {
ff52c073
CS
13568 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13569 != PACKET_ENABLE)
864ac8a7 13570 warning (_("\
c2fa21f1
HZ
13571Too many sections for read-only sections definition packet."));
13572 break;
13573 }
8d64371b 13574 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
bba74b36 13575 tmp1, tmp2);
c2fa21f1 13576 offset += sec_length;
35b1e5cc
SS
13577 }
13578 if (anysecs)
13579 {
b6bb3468 13580 putpkt (rs->buf);
8d64371b 13581 getpkt (&rs->buf, 0);
35b1e5cc
SS
13582 }
13583}
13584
f6ac5f3d
PA
13585void
13586remote_target::trace_start ()
35b1e5cc 13587{
b6bb3468
PA
13588 struct remote_state *rs = get_remote_state ();
13589
35b1e5cc 13590 putpkt ("QTStart");
b6bb3468 13591 remote_get_noisy_reply ();
8d64371b 13592 if (rs->buf[0] == '\0')
ad91cd99 13593 error (_("Target does not support this command."));
8d64371b
TT
13594 if (strcmp (rs->buf.data (), "OK") != 0)
13595 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13596}
13597
f6ac5f3d
PA
13598int
13599remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13600{
953b98d1 13601 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13602 char *p = NULL;
bd3eecc3 13603 enum packet_result result;
b6bb3468 13604 struct remote_state *rs = get_remote_state ();
bd3eecc3 13605
ff52c073 13606 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13607 return -1;
a744cf53 13608
7b9a15e1 13609 /* FIXME we need to get register block size some other way. */
5cd63fda 13610 trace_regblock_size
9d6eea31 13611 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 13612
049dc89b
JK
13613 putpkt ("qTStatus");
13614
a70b8144 13615 try
67f41397 13616 {
b6bb3468 13617 p = remote_get_noisy_reply ();
67f41397 13618 }
230d2906 13619 catch (const gdb_exception_error &ex)
67f41397 13620 {
598d3636
JK
13621 if (ex.error != TARGET_CLOSE_ERROR)
13622 {
13623 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13624 return -1;
13625 }
eedc3f4f 13626 throw;
67f41397 13627 }
00bf0b85 13628
ff52c073 13629 result = m_features.packet_ok (p, PACKET_qTStatus);
bd3eecc3 13630
00bf0b85 13631 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13632 if (result == PACKET_UNKNOWN)
00bf0b85 13633 return -1;
35b1e5cc 13634
00bf0b85 13635 /* We're working with a live target. */
f5911ea1 13636 ts->filename = NULL;
00bf0b85 13637
00bf0b85 13638 if (*p++ != 'T')
8d64371b 13639 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
35b1e5cc 13640
84cebc4a
YQ
13641 /* Function 'parse_trace_status' sets default value of each field of
13642 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13643 parse_trace_status (p, ts);
13644
13645 return ts->running;
35b1e5cc
SS
13646}
13647
f6ac5f3d
PA
13648void
13649remote_target::get_tracepoint_status (struct breakpoint *bp,
13650 struct uploaded_tp *utp)
f196051f
SS
13651{
13652 struct remote_state *rs = get_remote_state ();
f196051f 13653 char *reply;
f196051f 13654 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 13655 size_t size = get_remote_packet_size ();
f196051f
SS
13656
13657 if (tp)
13658 {
c1fc2657 13659 tp->hit_count = 0;
f196051f 13660 tp->traceframe_usage = 0;
40cb8ca5 13661 for (bp_location *loc : tp->locations ())
f196051f
SS
13662 {
13663 /* If the tracepoint was never downloaded, don't go asking for
13664 any status. */
13665 if (tp->number_on_target == 0)
13666 continue;
8d64371b 13667 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
bba74b36 13668 phex_nz (loc->address, 0));
f196051f 13669 putpkt (rs->buf);
b6bb3468 13670 reply = remote_get_noisy_reply ();
f196051f
SS
13671 if (reply && *reply)
13672 {
13673 if (*reply == 'V')
13674 parse_tracepoint_status (reply + 1, bp, utp);
13675 }
13676 }
13677 }
13678 else if (utp)
13679 {
13680 utp->hit_count = 0;
13681 utp->traceframe_usage = 0;
8d64371b 13682 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
bba74b36 13683 phex_nz (utp->addr, 0));
f196051f 13684 putpkt (rs->buf);
b6bb3468 13685 reply = remote_get_noisy_reply ();
f196051f
SS
13686 if (reply && *reply)
13687 {
13688 if (*reply == 'V')
13689 parse_tracepoint_status (reply + 1, bp, utp);
13690 }
13691 }
13692}
13693
f6ac5f3d
PA
13694void
13695remote_target::trace_stop ()
35b1e5cc 13696{
b6bb3468
PA
13697 struct remote_state *rs = get_remote_state ();
13698
35b1e5cc 13699 putpkt ("QTStop");
b6bb3468 13700 remote_get_noisy_reply ();
8d64371b 13701 if (rs->buf[0] == '\0')
ad91cd99 13702 error (_("Target does not support this command."));
8d64371b
TT
13703 if (strcmp (rs->buf.data (), "OK") != 0)
13704 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13705}
13706
f6ac5f3d
PA
13707int
13708remote_target::trace_find (enum trace_find_type type, int num,
13709 CORE_ADDR addr1, CORE_ADDR addr2,
13710 int *tpp)
35b1e5cc
SS
13711{
13712 struct remote_state *rs = get_remote_state ();
8d64371b 13713 char *endbuf = rs->buf.data () + get_remote_packet_size ();
35b1e5cc
SS
13714 char *p, *reply;
13715 int target_frameno = -1, target_tracept = -1;
13716
e6e4e701
PA
13717 /* Lookups other than by absolute frame number depend on the current
13718 trace selected, so make sure it is correct on the remote end
13719 first. */
13720 if (type != tfind_number)
13721 set_remote_traceframe ();
13722
8d64371b 13723 p = rs->buf.data ();
35b1e5cc
SS
13724 strcpy (p, "QTFrame:");
13725 p = strchr (p, '\0');
13726 switch (type)
13727 {
13728 case tfind_number:
bba74b36 13729 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13730 break;
13731 case tfind_pc:
bba74b36 13732 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13733 break;
13734 case tfind_tp:
bba74b36 13735 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13736 break;
13737 case tfind_range:
bba74b36
YQ
13738 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13739 phex_nz (addr2, 0));
35b1e5cc
SS
13740 break;
13741 case tfind_outside:
bba74b36
YQ
13742 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13743 phex_nz (addr2, 0));
35b1e5cc
SS
13744 break;
13745 default:
9b20d036 13746 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13747 }
13748
13749 putpkt (rs->buf);
b6bb3468 13750 reply = remote_get_noisy_reply ();
ad91cd99
PA
13751 if (*reply == '\0')
13752 error (_("Target does not support this command."));
35b1e5cc
SS
13753
13754 while (reply && *reply)
13755 switch (*reply)
13756 {
13757 case 'F':
f197e0f1
VP
13758 p = ++reply;
13759 target_frameno = (int) strtol (p, &reply, 16);
13760 if (reply == p)
13761 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13762 /* Don't update our remote traceframe number cache on failure
13763 to select a remote traceframe. */
f197e0f1
VP
13764 if (target_frameno == -1)
13765 return -1;
35b1e5cc
SS
13766 break;
13767 case 'T':
f197e0f1
VP
13768 p = ++reply;
13769 target_tracept = (int) strtol (p, &reply, 16);
13770 if (reply == p)
13771 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13772 break;
13773 case 'O': /* "OK"? */
13774 if (reply[1] == 'K' && reply[2] == '\0')
13775 reply += 2;
13776 else
13777 error (_("Bogus reply from target: %s"), reply);
13778 break;
13779 default:
13780 error (_("Bogus reply from target: %s"), reply);
13781 }
13782 if (tpp)
13783 *tpp = target_tracept;
e6e4e701 13784
262e1174 13785 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13786 return target_frameno;
13787}
13788
57810aa7 13789bool
f6ac5f3d 13790remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13791{
13792 struct remote_state *rs = get_remote_state ();
13793 char *reply;
13794 ULONGEST uval;
13795
e6e4e701
PA
13796 set_remote_traceframe ();
13797
8d64371b 13798 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13799 putpkt (rs->buf);
b6bb3468 13800 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13801 if (reply && *reply)
13802 {
13803 if (*reply == 'V')
13804 {
13805 unpack_varlen_hex (reply + 1, &uval);
13806 *val = (LONGEST) uval;
57810aa7 13807 return true;
35b1e5cc
SS
13808 }
13809 }
57810aa7 13810 return false;
35b1e5cc
SS
13811}
13812
f6ac5f3d
PA
13813int
13814remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13815{
13816 struct remote_state *rs = get_remote_state ();
13817 char *p, *reply;
13818
8d64371b 13819 p = rs->buf.data ();
00bf0b85
SS
13820 strcpy (p, "QTSave:");
13821 p += strlen (p);
8d64371b
TT
13822 if ((p - rs->buf.data ()) + strlen (filename) * 2
13823 >= get_remote_packet_size ())
00bf0b85 13824 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13825 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13826 *p++ = '\0';
13827 putpkt (rs->buf);
b6bb3468 13828 reply = remote_get_noisy_reply ();
d6c5869f 13829 if (*reply == '\0')
ad91cd99
PA
13830 error (_("Target does not support this command."));
13831 if (strcmp (reply, "OK") != 0)
13832 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13833 return 0;
13834}
13835
13836/* This is basically a memory transfer, but needs to be its own packet
13837 because we don't know how the target actually organizes its trace
13838 memory, plus we want to be able to ask for as much as possible, but
13839 not be unhappy if we don't get as much as we ask for. */
13840
f6ac5f3d
PA
13841LONGEST
13842remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13843{
13844 struct remote_state *rs = get_remote_state ();
13845 char *reply;
13846 char *p;
13847 int rslt;
13848
8d64371b 13849 p = rs->buf.data ();
00bf0b85
SS
13850 strcpy (p, "qTBuffer:");
13851 p += strlen (p);
13852 p += hexnumstr (p, offset);
13853 *p++ = ',';
13854 p += hexnumstr (p, len);
13855 *p++ = '\0';
13856
13857 putpkt (rs->buf);
b6bb3468 13858 reply = remote_get_noisy_reply ();
00bf0b85
SS
13859 if (reply && *reply)
13860 {
13861 /* 'l' by itself means we're at the end of the buffer and
13862 there is nothing more to get. */
13863 if (*reply == 'l')
13864 return 0;
13865
13866 /* Convert the reply into binary. Limit the number of bytes to
13867 convert according to our passed-in buffer size, rather than
13868 what was returned in the packet; if the target is
13869 unexpectedly generous and gives us a bigger reply than we
13870 asked for, we don't want to crash. */
b6bb3468 13871 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13872 return rslt;
13873 }
13874
13875 /* Something went wrong, flag as an error. */
13876 return -1;
13877}
13878
f6ac5f3d
PA
13879void
13880remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13881{
13882 struct remote_state *rs = get_remote_state ();
13883
ff52c073
CS
13884 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
13885 == PACKET_ENABLE)
33da3f1c 13886 {
ad91cd99
PA
13887 char *reply;
13888
8d64371b
TT
13889 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13890 "QTDisconnected:%x", val);
33da3f1c 13891 putpkt (rs->buf);
b6bb3468 13892 reply = remote_get_noisy_reply ();
ad91cd99 13893 if (*reply == '\0')
33da3f1c 13894 error (_("Target does not support this command."));
ad91cd99 13895 if (strcmp (reply, "OK") != 0)
dda83cd7 13896 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13897 }
13898 else if (val)
13899 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13900}
13901
f6ac5f3d
PA
13902int
13903remote_target::core_of_thread (ptid_t ptid)
dc146f7c 13904{
5b6d1e4f 13905 thread_info *info = find_thread_ptid (this, ptid);
a744cf53 13906
7aabaf9d
SM
13907 if (info != NULL && info->priv != NULL)
13908 return get_remote_thread_info (info)->core;
13909
dc146f7c
VP
13910 return -1;
13911}
13912
f6ac5f3d
PA
13913void
13914remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13915{
13916 struct remote_state *rs = get_remote_state ();
ad91cd99 13917 char *reply;
4daf5ac0 13918
8d64371b
TT
13919 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13920 "QTBuffer:circular:%x", val);
4daf5ac0 13921 putpkt (rs->buf);
b6bb3468 13922 reply = remote_get_noisy_reply ();
ad91cd99 13923 if (*reply == '\0')
4daf5ac0 13924 error (_("Target does not support this command."));
ad91cd99
PA
13925 if (strcmp (reply, "OK") != 0)
13926 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13927}
13928
f6ac5f3d
PA
13929traceframe_info_up
13930remote_target::traceframe_info ()
b3b9301e 13931{
9018be22 13932 gdb::optional<gdb::char_vector> text
328d42d8
SM
13933 = target_read_stralloc (current_inferior ()->top_target (),
13934 TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13935 NULL);
9018be22
SM
13936 if (text)
13937 return parse_traceframe_info (text->data ());
b3b9301e
PA
13938
13939 return NULL;
13940}
13941
405f8e94
SS
13942/* Handle the qTMinFTPILen packet. Returns the minimum length of
13943 instruction on which a fast tracepoint may be placed. Returns -1
13944 if the packet is not supported, and 0 if the minimum instruction
13945 length is unknown. */
13946
f6ac5f3d
PA
13947int
13948remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13949{
13950 struct remote_state *rs = get_remote_state ();
13951 char *reply;
13952
e886a173
PA
13953 /* If we're not debugging a process yet, the IPA can't be
13954 loaded. */
55f6301a 13955 if (!target_has_execution ())
e886a173
PA
13956 return 0;
13957
13958 /* Make sure the remote is pointing at the right process. */
13959 set_general_process ();
13960
8d64371b 13961 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13962 putpkt (rs->buf);
b6bb3468 13963 reply = remote_get_noisy_reply ();
405f8e94
SS
13964 if (*reply == '\0')
13965 return -1;
13966 else
13967 {
13968 ULONGEST min_insn_len;
13969
13970 unpack_varlen_hex (reply, &min_insn_len);
13971
13972 return (int) min_insn_len;
13973 }
13974}
13975
f6ac5f3d
PA
13976void
13977remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13978{
ff52c073 13979 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13980 {
13981 struct remote_state *rs = get_remote_state ();
8d64371b
TT
13982 char *buf = rs->buf.data ();
13983 char *endbuf = buf + get_remote_packet_size ();
f6f899bf
HAQ
13984 enum packet_result result;
13985
13986 gdb_assert (val >= 0 || val == -1);
13987 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13988 /* Send -1 as literal "-1" to avoid host size dependency. */
13989 if (val < 0)
13990 {
13991 *buf++ = '-';
dda83cd7 13992 buf += hexnumstr (buf, (ULONGEST) -val);
f6f899bf
HAQ
13993 }
13994 else
13995 buf += hexnumstr (buf, (ULONGEST) val);
13996
13997 putpkt (rs->buf);
b6bb3468 13998 remote_get_noisy_reply ();
ff52c073 13999 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
f6f899bf
HAQ
14000
14001 if (result != PACKET_OK)
8d64371b 14002 warning (_("Bogus reply from target: %s"), rs->buf.data ());
f6f899bf
HAQ
14003 }
14004}
14005
57810aa7 14006bool
f6ac5f3d
PA
14007remote_target::set_trace_notes (const char *user, const char *notes,
14008 const char *stop_notes)
f196051f
SS
14009{
14010 struct remote_state *rs = get_remote_state ();
14011 char *reply;
8d64371b
TT
14012 char *buf = rs->buf.data ();
14013 char *endbuf = buf + get_remote_packet_size ();
f196051f
SS
14014 int nbytes;
14015
14016 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14017 if (user)
14018 {
14019 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 14020 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
14021 buf += 2 * nbytes;
14022 *buf++ = ';';
14023 }
14024 if (notes)
14025 {
14026 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 14027 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
14028 buf += 2 * nbytes;
14029 *buf++ = ';';
14030 }
14031 if (stop_notes)
14032 {
14033 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 14034 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
14035 buf += 2 * nbytes;
14036 *buf++ = ';';
14037 }
14038 /* Ensure the buffer is terminated. */
14039 *buf = '\0';
14040
14041 putpkt (rs->buf);
b6bb3468 14042 reply = remote_get_noisy_reply ();
f196051f 14043 if (*reply == '\0')
57810aa7 14044 return false;
f196051f
SS
14045
14046 if (strcmp (reply, "OK") != 0)
14047 error (_("Bogus reply from target: %s"), reply);
14048
57810aa7 14049 return true;
f196051f
SS
14050}
14051
57810aa7
PA
14052bool
14053remote_target::use_agent (bool use)
d1feda86 14054{
ff52c073 14055 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
14056 {
14057 struct remote_state *rs = get_remote_state ();
14058
14059 /* If the stub supports QAgent. */
8d64371b 14060 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
d1feda86 14061 putpkt (rs->buf);
8d64371b 14062 getpkt (&rs->buf, 0);
d1feda86 14063
8d64371b 14064 if (strcmp (rs->buf.data (), "OK") == 0)
d1feda86 14065 {
f6ac5f3d 14066 ::use_agent = use;
57810aa7 14067 return true;
d1feda86
YQ
14068 }
14069 }
14070
57810aa7 14071 return false;
d1feda86
YQ
14072}
14073
57810aa7 14074bool
f6ac5f3d 14075remote_target::can_use_agent ()
d1feda86 14076{
ff52c073 14077 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
14078}
14079
9accd112
MM
14080struct btrace_target_info
14081{
14082 /* The ptid of the traced thread. */
14083 ptid_t ptid;
f4abbc16
MM
14084
14085 /* The obtained branch trace configuration. */
14086 struct btrace_config conf;
9accd112
MM
14087};
14088
f4abbc16
MM
14089/* Reset our idea of our target's btrace configuration. */
14090
14091static void
6b8edb51 14092remote_btrace_reset (remote_state *rs)
f4abbc16 14093{
f4abbc16
MM
14094 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14095}
14096
f4abbc16
MM
14097/* Synchronize the configuration with the target. */
14098
6b8edb51
PA
14099void
14100remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 14101{
d33501a5
MM
14102 struct remote_state *rs;
14103 char *buf, *pos, *endbuf;
14104
14105 rs = get_remote_state ();
8d64371b 14106 buf = rs->buf.data ();
d33501a5
MM
14107 endbuf = buf + get_remote_packet_size ();
14108
ff52c073 14109 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
d33501a5
MM
14110 && conf->bts.size != rs->btrace_config.bts.size)
14111 {
14112 pos = buf;
ff52c073
CS
14113 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14114 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
dda83cd7 14115 conf->bts.size);
d33501a5
MM
14116
14117 putpkt (buf);
8d64371b 14118 getpkt (&rs->buf, 0);
d33501a5 14119
ff52c073
CS
14120 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14121 == PACKET_ERROR)
d33501a5
MM
14122 {
14123 if (buf[0] == 'E' && buf[1] == '.')
14124 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14125 else
14126 error (_("Failed to configure the BTS buffer size."));
14127 }
14128
14129 rs->btrace_config.bts.size = conf->bts.size;
14130 }
b20a6524 14131
ff52c073 14132 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
b20a6524
MM
14133 && conf->pt.size != rs->btrace_config.pt.size)
14134 {
14135 pos = buf;
ff52c073
CS
14136 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14137 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
dda83cd7 14138 conf->pt.size);
b20a6524
MM
14139
14140 putpkt (buf);
8d64371b 14141 getpkt (&rs->buf, 0);
b20a6524 14142
ff52c073
CS
14143 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14144 == PACKET_ERROR)
b20a6524
MM
14145 {
14146 if (buf[0] == 'E' && buf[1] == '.')
14147 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14148 else
14149 error (_("Failed to configure the trace buffer size."));
14150 }
14151
14152 rs->btrace_config.pt.size = conf->pt.size;
14153 }
f4abbc16
MM
14154}
14155
0d8cbc5f 14156/* Read TP's btrace configuration from the target and store it into CONF. */
f4abbc16
MM
14157
14158static void
0d8cbc5f 14159btrace_read_config (thread_info *tp, struct btrace_config *conf)
f4abbc16 14160{
0d8cbc5f
MM
14161 /* target_read_stralloc relies on INFERIOR_PTID. */
14162 scoped_restore_current_thread restore_thread;
14163 switch_to_thread (tp);
14164
9018be22 14165 gdb::optional<gdb::char_vector> xml
328d42d8
SM
14166 = target_read_stralloc (current_inferior ()->top_target (),
14167 TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
14168 if (xml)
14169 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
14170}
14171
c0272db5
TW
14172/* Maybe reopen target btrace. */
14173
6b8edb51
PA
14174void
14175remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
14176{
14177 struct remote_state *rs = get_remote_state ();
c0272db5 14178 int btrace_target_pushed = 0;
15766370 14179#if !defined (HAVE_LIBIPT)
c0272db5 14180 int warned = 0;
15766370 14181#endif
c0272db5 14182
aedbe3bb
CM
14183 /* Don't bother walking the entirety of the remote thread list when
14184 we know the feature isn't supported by the remote. */
ff52c073 14185 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
aedbe3bb
CM
14186 return;
14187
5b6d1e4f 14188 for (thread_info *tp : all_non_exited_threads (this))
c0272db5 14189 {
c0272db5 14190 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
0d8cbc5f 14191 btrace_read_config (tp, &rs->btrace_config);
c0272db5
TW
14192
14193 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14194 continue;
14195
14196#if !defined (HAVE_LIBIPT)
14197 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14198 {
14199 if (!warned)
14200 {
14201 warned = 1;
c4e12631
MM
14202 warning (_("Target is recording using Intel Processor Trace "
14203 "but support was disabled at compile time."));
c0272db5
TW
14204 }
14205
14206 continue;
14207 }
14208#endif /* !defined (HAVE_LIBIPT) */
14209
14210 /* Push target, once, but before anything else happens. This way our
14211 changes to the threads will be cleaned up by unpushing the target
14212 in case btrace_read_config () throws. */
14213 if (!btrace_target_pushed)
14214 {
14215 btrace_target_pushed = 1;
14216 record_btrace_push_target ();
6cb06a8c
TT
14217 gdb_printf (_("Target is recording using %s.\n"),
14218 btrace_format_string (rs->btrace_config.format));
c0272db5
TW
14219 }
14220
14221 tp->btrace.target = XCNEW (struct btrace_target_info);
14222 tp->btrace.target->ptid = tp->ptid;
14223 tp->btrace.target->conf = rs->btrace_config;
14224 }
c0272db5
TW
14225}
14226
9accd112
MM
14227/* Enable branch tracing. */
14228
f6ac5f3d 14229struct btrace_target_info *
696c0d5e
MM
14230remote_target::enable_btrace (thread_info *tp,
14231 const struct btrace_config *conf)
9accd112
MM
14232{
14233 struct btrace_target_info *tinfo = NULL;
b20a6524 14234 struct packet_config *packet = NULL;
9accd112 14235 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14236 char *buf = rs->buf.data ();
14237 char *endbuf = buf + get_remote_packet_size ();
9accd112 14238
ff52c073 14239 unsigned int which_packet;
b20a6524
MM
14240 switch (conf->format)
14241 {
14242 case BTRACE_FORMAT_BTS:
ff52c073 14243 which_packet = PACKET_Qbtrace_bts;
b20a6524 14244 break;
b20a6524 14245 case BTRACE_FORMAT_PT:
ff52c073 14246 which_packet = PACKET_Qbtrace_pt;
b20a6524 14247 break;
ff52c073
CS
14248 default:
14249 internal_error (_("Bad branch btrace format: %u."),
14250 (unsigned int) conf->format);
b20a6524
MM
14251 }
14252
ff52c073 14253 packet = &m_features.m_protocol_packets[which_packet];
b20a6524 14254 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
14255 error (_("Target does not support branch tracing."));
14256
f4abbc16
MM
14257 btrace_sync_conf (conf);
14258
696c0d5e 14259 ptid_t ptid = tp->ptid;
9accd112
MM
14260 set_general_thread (ptid);
14261
ff52c073
CS
14262 buf += xsnprintf (buf, endbuf - buf, "%s",
14263 packets_descriptions[which_packet].name);
9accd112 14264 putpkt (rs->buf);
8d64371b 14265 getpkt (&rs->buf, 0);
9accd112 14266
ff52c073 14267 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
9accd112
MM
14268 {
14269 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14270 error (_("Could not enable branch tracing for %s: %s"),
a068643d 14271 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
9accd112
MM
14272 else
14273 error (_("Could not enable branch tracing for %s."),
a068643d 14274 target_pid_to_str (ptid).c_str ());
9accd112
MM
14275 }
14276
8d749320 14277 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
14278 tinfo->ptid = ptid;
14279
f4abbc16
MM
14280 /* If we fail to read the configuration, we lose some information, but the
14281 tracing itself is not impacted. */
a70b8144 14282 try
492d29ea 14283 {
0d8cbc5f 14284 btrace_read_config (tp, &tinfo->conf);
492d29ea 14285 }
230d2906 14286 catch (const gdb_exception_error &err)
492d29ea
PA
14287 {
14288 if (err.message != NULL)
3d6e9d23 14289 warning ("%s", err.what ());
492d29ea 14290 }
f4abbc16 14291
9accd112
MM
14292 return tinfo;
14293}
14294
14295/* Disable branch tracing. */
14296
f6ac5f3d
PA
14297void
14298remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112 14299{
9accd112 14300 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14301 char *buf = rs->buf.data ();
14302 char *endbuf = buf + get_remote_packet_size ();
9accd112 14303
ff52c073 14304 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112
MM
14305 error (_("Target does not support branch tracing."));
14306
14307 set_general_thread (tinfo->ptid);
14308
ff52c073
CS
14309 buf += xsnprintf (buf, endbuf - buf, "%s",
14310 packets_descriptions[PACKET_Qbtrace_off].name);
9accd112 14311 putpkt (rs->buf);
8d64371b 14312 getpkt (&rs->buf, 0);
9accd112 14313
ff52c073 14314 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
9accd112
MM
14315 {
14316 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14317 error (_("Could not disable branch tracing for %s: %s"),
a068643d 14318 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
9accd112
MM
14319 else
14320 error (_("Could not disable branch tracing for %s."),
a068643d 14321 target_pid_to_str (tinfo->ptid).c_str ());
9accd112
MM
14322 }
14323
14324 xfree (tinfo);
14325}
14326
14327/* Teardown branch tracing. */
14328
f6ac5f3d
PA
14329void
14330remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
14331{
14332 /* We must not talk to the target during teardown. */
14333 xfree (tinfo);
14334}
14335
14336/* Read the branch trace. */
14337
f6ac5f3d
PA
14338enum btrace_error
14339remote_target::read_btrace (struct btrace_data *btrace,
14340 struct btrace_target_info *tinfo,
14341 enum btrace_read_type type)
9accd112 14342{
9accd112 14343 const char *annex;
9accd112 14344
ff52c073 14345 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
14346 error (_("Target does not support branch tracing."));
14347
14348#if !defined(HAVE_LIBEXPAT)
14349 error (_("Cannot process branch tracing result. XML parsing not supported."));
14350#endif
14351
14352 switch (type)
14353 {
864089d2 14354 case BTRACE_READ_ALL:
9accd112
MM
14355 annex = "all";
14356 break;
864089d2 14357 case BTRACE_READ_NEW:
9accd112
MM
14358 annex = "new";
14359 break;
969c39fb
MM
14360 case BTRACE_READ_DELTA:
14361 annex = "delta";
14362 break;
9accd112 14363 default:
f34652de 14364 internal_error (_("Bad branch tracing read type: %u."),
9accd112
MM
14365 (unsigned int) type);
14366 }
14367
9018be22 14368 gdb::optional<gdb::char_vector> xml
328d42d8
SM
14369 = target_read_stralloc (current_inferior ()->top_target (),
14370 TARGET_OBJECT_BTRACE, annex);
9018be22 14371 if (!xml)
969c39fb 14372 return BTRACE_ERR_UNKNOWN;
9accd112 14373
9018be22 14374 parse_xml_btrace (btrace, xml->data ());
9accd112 14375
969c39fb 14376 return BTRACE_ERR_NONE;
9accd112
MM
14377}
14378
f6ac5f3d
PA
14379const struct btrace_config *
14380remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
14381{
14382 return &tinfo->conf;
14383}
14384
57810aa7 14385bool
f6ac5f3d 14386remote_target::augmented_libraries_svr4_read ()
ced63ec0 14387{
ff52c073
CS
14388 return
14389 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14390 == PACKET_ENABLE);
ced63ec0
GB
14391}
14392
9dd130a0
TT
14393/* Implementation of to_load. */
14394
f6ac5f3d
PA
14395void
14396remote_target::load (const char *name, int from_tty)
9dd130a0
TT
14397{
14398 generic_load (name, from_tty);
14399}
14400
c78fa86a
GB
14401/* Accepts an integer PID; returns a string representing a file that
14402 can be opened on the remote side to get the symbols for the child
14403 process. Returns NULL if the operation is not supported. */
14404
0e90c441 14405const char *
f6ac5f3d 14406remote_target::pid_to_exec_file (int pid)
c78fa86a 14407{
9018be22 14408 static gdb::optional<gdb::char_vector> filename;
835205d0 14409 char *annex = NULL;
c78fa86a 14410
ff52c073 14411 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
c78fa86a
GB
14412 return NULL;
14413
5b6d1e4f 14414 inferior *inf = find_inferior_pid (this, pid);
835205d0 14415 if (inf == NULL)
f34652de 14416 internal_error (_("not currently attached to process %d"), pid);
835205d0
GB
14417
14418 if (!inf->fake_pid_p)
14419 {
14420 const int annex_size = 9;
14421
224c3ddb 14422 annex = (char *) alloca (annex_size);
835205d0
GB
14423 xsnprintf (annex, annex_size, "%x", pid);
14424 }
14425
328d42d8 14426 filename = target_read_stralloc (current_inferior ()->top_target (),
c78fa86a
GB
14427 TARGET_OBJECT_EXEC_FILE, annex);
14428
9018be22 14429 return filename ? filename->data () : nullptr;
c78fa86a
GB
14430}
14431
750ce8d1
YQ
14432/* Implement the to_can_do_single_step target_ops method. */
14433
f6ac5f3d
PA
14434int
14435remote_target::can_do_single_step ()
750ce8d1
YQ
14436{
14437 /* We can only tell whether target supports single step or not by
14438 supported s and S vCont actions if the stub supports vContSupported
14439 feature. If the stub doesn't support vContSupported feature,
14440 we have conservatively to think target doesn't supports single
14441 step. */
ff52c073 14442 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
750ce8d1
YQ
14443 {
14444 struct remote_state *rs = get_remote_state ();
14445
ff52c073 14446 if (m_features.packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 14447 remote_vcont_probe ();
750ce8d1
YQ
14448
14449 return rs->supports_vCont.s && rs->supports_vCont.S;
14450 }
14451 else
14452 return 0;
14453}
14454
3a00c802
PA
14455/* Implementation of the to_execution_direction method for the remote
14456 target. */
14457
f6ac5f3d
PA
14458enum exec_direction_kind
14459remote_target::execution_direction ()
3a00c802
PA
14460{
14461 struct remote_state *rs = get_remote_state ();
14462
14463 return rs->last_resume_exec_dir;
14464}
14465
f6327dcb
KB
14466/* Return pointer to the thread_info struct which corresponds to
14467 THREAD_HANDLE (having length HANDLE_LEN). */
14468
f6ac5f3d
PA
14469thread_info *
14470remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14471 int handle_len,
14472 inferior *inf)
f6327dcb 14473{
5b6d1e4f 14474 for (thread_info *tp : all_non_exited_threads (this))
f6327dcb 14475 {
7aabaf9d 14476 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
14477
14478 if (tp->inf == inf && priv != NULL)
dda83cd7 14479 {
7aabaf9d 14480 if (handle_len != priv->thread_handle.size ())
f6327dcb 14481 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
dda83cd7 14482 handle_len, priv->thread_handle.size ());
7aabaf9d 14483 if (memcmp (thread_handle, priv->thread_handle.data (),
dda83cd7 14484 handle_len) == 0)
f6327dcb
KB
14485 return tp;
14486 }
14487 }
14488
14489 return NULL;
14490}
14491
3d6c6204
KB
14492gdb::byte_vector
14493remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14494{
14495 remote_thread_info *priv = get_remote_thread_info (tp);
14496 return priv->thread_handle;
14497}
14498
57810aa7 14499bool
f6ac5f3d 14500remote_target::can_async_p ()
6426a772 14501{
fce6cd34
AB
14502 /* This flag should be checked in the common target.c code. */
14503 gdb_assert (target_async_permitted);
75c99385 14504
fce6cd34
AB
14505 /* We're async whenever the serial device can. */
14506 struct remote_state *rs = get_remote_state ();
5d93a237 14507 return serial_can_async_p (rs->remote_desc);
6426a772
JM
14508}
14509
57810aa7 14510bool
f6ac5f3d 14511remote_target::is_async_p ()
6426a772 14512{
23860348 14513 /* We're async whenever the serial device is. */
7054fa5b 14514 struct remote_state *rs = get_remote_state ();
5d93a237 14515 return serial_is_async_p (rs->remote_desc);
6426a772
JM
14516}
14517
2acceee2
JM
14518/* Pass the SERIAL event on and up to the client. One day this code
14519 will be able to delay notifying the client of an event until the
23860348 14520 point where an entire packet has been received. */
2acceee2 14521
2acceee2
JM
14522static serial_event_ftype remote_async_serial_handler;
14523
6426a772 14524static void
819cc324 14525remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14526{
2acceee2
JM
14527 /* Don't propogate error information up to the client. Instead let
14528 the client find out about the error by querying the target. */
b1a35af2 14529 inferior_event_handler (INF_REG_EVENT);
2acceee2
JM
14530}
14531
74531fed
PA
14532static void
14533remote_async_inferior_event_handler (gdb_client_data data)
14534{
6b36ddeb 14535 inferior_event_handler (INF_REG_EVENT);
74531fed
PA
14536}
14537
5b6d1e4f
PA
14538int
14539remote_target::async_wait_fd ()
14540{
14541 struct remote_state *rs = get_remote_state ();
14542 return rs->remote_desc->fd;
14543}
14544
f6ac5f3d 14545void
4a570176 14546remote_target::async (bool enable)
2acceee2 14547{
5d93a237
TT
14548 struct remote_state *rs = get_remote_state ();
14549
6a3753b3 14550 if (enable)
2acceee2 14551 {
88b496c3 14552 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14553
14554 /* If there are pending events in the stop reply queue tell the
14555 event loop to process them. */
953edf2b 14556 if (!rs->stop_reply_queue.empty ())
6b8edb51 14557 mark_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14558 /* For simplicity, below we clear the pending events token
14559 without remembering whether it is marked, so here we always
14560 mark it. If there's actually no pending notification to
14561 process, this ends up being a no-op (other than a spurious
14562 event-loop wakeup). */
14563 if (target_is_non_stop_p ())
14564 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14565 }
14566 else
b7d2e916
PA
14567 {
14568 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14569 /* If the core is disabling async, it doesn't want to be
14570 disturbed with target events. Clear all async event sources
14571 too. */
6b8edb51 14572 clear_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14573 if (target_is_non_stop_p ())
14574 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14575 }
6426a772
JM
14576}
14577
65706a29
PA
14578/* Implementation of the to_thread_events method. */
14579
f6ac5f3d
PA
14580void
14581remote_target::thread_events (int enable)
65706a29
PA
14582{
14583 struct remote_state *rs = get_remote_state ();
14584 size_t size = get_remote_packet_size ();
65706a29 14585
ff52c073 14586 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
65706a29
PA
14587 return;
14588
8d64371b 14589 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
65706a29 14590 putpkt (rs->buf);
8d64371b 14591 getpkt (&rs->buf, 0);
65706a29 14592
ff52c073 14593 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
65706a29
PA
14594 {
14595 case PACKET_OK:
8d64371b
TT
14596 if (strcmp (rs->buf.data (), "OK") != 0)
14597 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
65706a29
PA
14598 break;
14599 case PACKET_ERROR:
8d64371b 14600 warning (_("Remote failure reply: %s"), rs->buf.data ());
65706a29
PA
14601 break;
14602 case PACKET_UNKNOWN:
14603 break;
14604 }
14605}
14606
d471ea57 14607static void
981a3fb3 14608show_remote_cmd (const char *args, int from_tty)
d471ea57 14609{
37a105a1 14610 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14611 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14612 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14613 struct ui_out *uiout = current_uiout;
37a105a1 14614
2e783024 14615 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14616 for (; list != NULL; list = list->next)
14617 if (strcmp (list->name, "Z-packet") == 0)
14618 continue;
427c3a89
DJ
14619 else if (list->type == not_set_cmd)
14620 /* Alias commands are exactly like the original, except they
14621 don't have the normal type. */
14622 continue;
14623 else
37a105a1 14624 {
2e783024 14625 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14626
112e8700
SM
14627 uiout->field_string ("name", list->name);
14628 uiout->text (": ");
427c3a89 14629 if (list->type == show_cmd)
f5c4fcd9 14630 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14631 else
14632 cmd_func (list, NULL, from_tty);
37a105a1 14633 }
d471ea57 14634}
5a2468f5 14635
0f71a2f6 14636
23860348 14637/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
14638static void
14639remote_new_objfile (struct objfile *objfile)
14640{
06c7226e
SM
14641 /* The objfile change happened in that program space. */
14642 program_space *pspace = current_program_space;
5d93a237 14643
06c7226e
SM
14644 /* The affected program space is possibly shared by multiple inferiors.
14645 Consider sending a qSymbol packet for each of the inferiors using that
14646 program space. */
14647 for (inferior *inf : all_inferiors ())
14648 {
14649 if (inf->pspace != pspace)
14650 continue;
122373f7 14651
06c7226e
SM
14652 /* Check whether the inferior's process target is a remote target. */
14653 remote_target *remote = as_remote_target (inf->process_target ());
14654 if (remote == nullptr)
14655 continue;
14656
14657 /* When we are attaching or handling a fork child and the shared library
14658 subsystem reads the list of loaded libraries, we receive new objfile
14659 events in between each found library. The libraries are read in an
14660 undefined order, so if we gave the remote side a chance to look up
14661 symbols between each objfile, we might give it an inconsistent picture
14662 of the inferior. It could appear that a library A appears loaded but
14663 a library B does not, even though library A requires library B. That
14664 would present a state that couldn't normally exist in the inferior.
14665
14666 So, skip these events, we'll give the remote a chance to look up
14667 symbols once all the loaded libraries and their symbols are known to
14668 GDB. */
14669 if (inf->in_initial_library_scan)
14670 continue;
14671
14672 if (!remote->has_execution (inf))
14673 continue;
14674
14675 /* Need to switch to a specific thread, because remote_check_symbols will
14676 set the general thread using INFERIOR_PTID.
122373f7 14677
06c7226e
SM
14678 It's possible to have inferiors with no thread here, because we are
14679 called very early in the connection process, while the inferior is
14680 being set up, before threads are added. Just skip it, start_remote_1
14681 also calls remote_check_symbols when it's done setting things up. */
14682 thread_info *thread = any_thread_of_inferior (inf);
14683 if (thread != nullptr)
14684 {
14685 scoped_restore_current_thread restore_thread;
14686 switch_to_thread (thread);
14687 remote->remote_check_symbols ();
14688 }
14689 }
dc8acb97
MS
14690}
14691
00bf0b85
SS
14692/* Pull all the tracepoints defined on the target and create local
14693 data structures representing them. We don't want to create real
14694 tracepoints yet, we don't want to mess up the user's existing
14695 collection. */
14696
f6ac5f3d
PA
14697int
14698remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 14699{
00bf0b85
SS
14700 struct remote_state *rs = get_remote_state ();
14701 char *p;
d5551862 14702
00bf0b85
SS
14703 /* Ask for a first packet of tracepoint definition. */
14704 putpkt ("qTfP");
8d64371b
TT
14705 getpkt (&rs->buf, 0);
14706 p = rs->buf.data ();
00bf0b85 14707 while (*p && *p != 'l')
d5551862 14708 {
00bf0b85
SS
14709 parse_tracepoint_definition (p, utpp);
14710 /* Ask for another packet of tracepoint definition. */
14711 putpkt ("qTsP");
8d64371b
TT
14712 getpkt (&rs->buf, 0);
14713 p = rs->buf.data ();
d5551862 14714 }
00bf0b85 14715 return 0;
d5551862
SS
14716}
14717
f6ac5f3d
PA
14718int
14719remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 14720{
00bf0b85 14721 struct remote_state *rs = get_remote_state ();
d5551862 14722 char *p;
d5551862 14723
00bf0b85
SS
14724 /* Ask for a first packet of variable definition. */
14725 putpkt ("qTfV");
8d64371b
TT
14726 getpkt (&rs->buf, 0);
14727 p = rs->buf.data ();
00bf0b85 14728 while (*p && *p != 'l')
d5551862 14729 {
00bf0b85
SS
14730 parse_tsv_definition (p, utsvp);
14731 /* Ask for another packet of variable definition. */
14732 putpkt ("qTsV");
8d64371b
TT
14733 getpkt (&rs->buf, 0);
14734 p = rs->buf.data ();
d5551862 14735 }
00bf0b85 14736 return 0;
d5551862
SS
14737}
14738
c1e36e3e
PA
14739/* The "set/show range-stepping" show hook. */
14740
14741static void
14742show_range_stepping (struct ui_file *file, int from_tty,
14743 struct cmd_list_element *c,
14744 const char *value)
14745{
6cb06a8c
TT
14746 gdb_printf (file,
14747 _("Debugger's willingness to use range stepping "
14748 "is %s.\n"), value);
c1e36e3e
PA
14749}
14750
6b8edb51
PA
14751/* Return true if the vCont;r action is supported by the remote
14752 stub. */
14753
14754bool
14755remote_target::vcont_r_supported ()
14756{
ff52c073 14757 if (m_features.packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51
PA
14758 remote_vcont_probe ();
14759
ff52c073 14760 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
6b8edb51
PA
14761 && get_remote_state ()->supports_vCont.r);
14762}
14763
c1e36e3e
PA
14764/* The "set/show range-stepping" set hook. */
14765
14766static void
eb4c3f4a 14767set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
14768 struct cmd_list_element *c)
14769{
6b8edb51
PA
14770 /* When enabling, check whether range stepping is actually supported
14771 by the target, and warn if not. */
c1e36e3e
PA
14772 if (use_range_stepping)
14773 {
6b8edb51
PA
14774 remote_target *remote = get_current_remote_target ();
14775 if (remote == NULL
14776 || !remote->vcont_r_supported ())
14777 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
14778 }
14779}
14780
baf2b57f
SM
14781static void
14782show_remote_debug (struct ui_file *file, int from_tty,
14783 struct cmd_list_element *c, const char *value)
14784{
6cb06a8c
TT
14785 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14786 value);
baf2b57f
SM
14787}
14788
14789static void
14790show_remote_timeout (struct ui_file *file, int from_tty,
14791 struct cmd_list_element *c, const char *value)
14792{
6cb06a8c
TT
14793 gdb_printf (file,
14794 _("Timeout limit to wait for target to respond is %s.\n"),
14795 value);
baf2b57f
SM
14796}
14797
dbe692af
LM
14798/* Implement the "supports_memory_tagging" target_ops method. */
14799
14800bool
14801remote_target::supports_memory_tagging ()
14802{
ff52c073 14803 return m_features.remote_memory_tagging_p ();
2c2e7f87
LM
14804}
14805
14806/* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14807
14808static void
14809create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14810 size_t len, int type)
14811{
14812 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14813
14814 std::string request = string_printf ("qMemTags:%s,%s:%s",
14815 phex_nz (address, addr_size),
14816 phex_nz (len, sizeof (len)),
14817 phex_nz (type, sizeof (type)));
14818
14819 strcpy (packet.data (), request.c_str ());
14820}
14821
14822/* Parse the qMemTags packet reply into TAGS.
14823
14824 Return true if successful, false otherwise. */
14825
14826static bool
14827parse_fetch_memtags_reply (const gdb::char_vector &reply,
14828 gdb::byte_vector &tags)
14829{
14830 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14831 return false;
14832
14833 /* Copy the tag data. */
14834 tags = hex2bin (reply.data () + 1);
14835
14836 return true;
14837}
14838
14839/* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14840
14841static void
14842create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14843 size_t len, int type,
14844 const gdb::byte_vector &tags)
14845{
14846 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14847
14848 /* Put together the main packet, address and length. */
14849 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14850 phex_nz (address, addr_size),
14851 phex_nz (len, sizeof (len)),
14852 phex_nz (type, sizeof (type)));
14853 request += bin2hex (tags.data (), tags.size ());
14854
14855 /* Check if we have exceeded the maximum packet size. */
14856 if (packet.size () < request.length ())
14857 error (_("Contents too big for packet QMemTags."));
14858
14859 strcpy (packet.data (), request.c_str ());
dbe692af
LM
14860}
14861
14862/* Implement the "fetch_memtags" target_ops method. */
14863
14864bool
14865remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14866 gdb::byte_vector &tags, int type)
14867{
2c2e7f87 14868 /* Make sure the qMemTags packet is supported. */
ff52c073 14869 if (!m_features.remote_memory_tagging_p ())
2c2e7f87
LM
14870 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14871
14872 struct remote_state *rs = get_remote_state ();
14873
14874 create_fetch_memtags_request (rs->buf, address, len, type);
14875
14876 putpkt (rs->buf);
14877 getpkt (&rs->buf, 0);
14878
14879 return parse_fetch_memtags_reply (rs->buf, tags);
dbe692af
LM
14880}
14881
14882/* Implement the "store_memtags" target_ops method. */
14883
14884bool
14885remote_target::store_memtags (CORE_ADDR address, size_t len,
14886 const gdb::byte_vector &tags, int type)
14887{
2c2e7f87 14888 /* Make sure the QMemTags packet is supported. */
ff52c073 14889 if (!m_features.remote_memory_tagging_p ())
2c2e7f87
LM
14890 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14891
14892 struct remote_state *rs = get_remote_state ();
14893
14894 create_store_memtags_request (rs->buf, address, len, type, tags);
14895
14896 putpkt (rs->buf);
14897 getpkt (&rs->buf, 0);
14898
14899 /* Verify if the request was successful. */
14900 return packet_check_result (rs->buf.data ()) == PACKET_OK;
dbe692af
LM
14901}
14902
c39ebbf4
TV
14903/* Return true if remote target T is non-stop. */
14904
14905bool
14906remote_target_is_non_stop_p (remote_target *t)
14907{
14908 scoped_restore_current_thread restore_thread;
14909 switch_to_target_no_thread (t);
14910
14911 return target_is_non_stop_p ();
14912}
14913
754487e2
LM
14914#if GDB_SELF_TEST
14915
14916namespace selftests {
14917
14918static void
14919test_memory_tagging_functions ()
14920{
14921 remote_target remote;
14922
14923 struct packet_config *config
ff52c073 14924 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
754487e2
LM
14925
14926 scoped_restore restore_memtag_support_
14927 = make_scoped_restore (&config->support);
14928
14929 /* Test memory tagging packet support. */
14930 config->support = PACKET_SUPPORT_UNKNOWN;
14931 SELF_CHECK (remote.supports_memory_tagging () == false);
14932 config->support = PACKET_DISABLE;
14933 SELF_CHECK (remote.supports_memory_tagging () == false);
14934 config->support = PACKET_ENABLE;
14935 SELF_CHECK (remote.supports_memory_tagging () == true);
14936
14937 /* Setup testing. */
14938 gdb::char_vector packet;
14939 gdb::byte_vector tags, bv;
14940 std::string expected, reply;
14941 packet.resize (32000);
14942
14943 /* Test creating a qMemTags request. */
14944
14945 expected = "qMemTags:0,0:0";
14946 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14947 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14948
14949 expected = "qMemTags:deadbeef,10:1";
14950 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14951 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14952
14953 /* Test parsing a qMemTags reply. */
14954
14955 /* Error reply, tags vector unmodified. */
14956 reply = "E00";
14957 strcpy (packet.data (), reply.c_str ());
14958 tags.resize (0);
14959 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14960 SELF_CHECK (tags.size () == 0);
14961
14962 /* Valid reply, tags vector updated. */
14963 tags.resize (0);
14964 bv.resize (0);
14965
14966 for (int i = 0; i < 5; i++)
14967 bv.push_back (i);
14968
14969 reply = "m" + bin2hex (bv.data (), bv.size ());
14970 strcpy (packet.data (), reply.c_str ());
14971
14972 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14973 SELF_CHECK (tags.size () == 5);
14974
14975 for (int i = 0; i < 5; i++)
14976 SELF_CHECK (tags[i] == i);
14977
14978 /* Test creating a QMemTags request. */
14979
14980 /* Empty tag data. */
14981 tags.resize (0);
14982 expected = "QMemTags:0,0:0:";
14983 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14984 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14985 expected.length ()) == 0);
14986
14987 /* Non-empty tag data. */
14988 tags.resize (0);
14989 for (int i = 0; i < 5; i++)
14990 tags.push_back (i);
14991 expected = "QMemTags:deadbeef,ff:1:0001020304";
14992 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14993 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14994 expected.length ()) == 0);
14995}
14996
14997} // namespace selftests
14998#endif /* GDB_SELF_TEST */
14999
6c265988 15000void _initialize_remote ();
c906108c 15001void
6c265988 15002_initialize_remote ()
c906108c 15003{
d9f719f1
PA
15004 add_target (remote_target_info, remote_target::open);
15005 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 15006
dc8acb97 15007 /* Hook into new objfile notification. */
c90e7d63 15008 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
dc8acb97 15009
c906108c
SS
15010#if 0
15011 init_remote_threadtests ();
15012#endif
15013
23860348 15014 /* set/show remote ... */
d471ea57 15015
0743fc83 15016 add_basic_prefix_cmd ("remote", class_maintenance, _("\
590042fc 15017Remote protocol specific variables.\n\
5a2468f5 15018Configure various remote-protocol specific variables such as\n\
590042fc 15019the packets being used."),
2f822da5 15020 &remote_set_cmdlist,
0743fc83 15021 0 /* allow-unknown */, &setlist);
1bedd215 15022 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
590042fc 15023Remote protocol specific variables.\n\
5a2468f5 15024Configure various remote-protocol specific variables such as\n\
590042fc 15025the packets being used."),
2f822da5 15026 &remote_show_cmdlist,
23860348 15027 0 /* allow-unknown */, &showlist);
5a2468f5 15028
1a966eab
AC
15029 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15030Compare section data on target to the exec file.\n\
95cf3b38
DT
15031Argument is a single section name (default: all loaded sections).\n\
15032To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
15033 &cmdlist);
15034
e5b176f2 15035 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
1a966eab 15036Send an arbitrary packet to a remote target.\n\
c906108c
SS
15037 maintenance packet TEXT\n\
15038If GDB is talking to an inferior via the GDB serial protocol, then\n\
15039this command sends the string TEXT to the inferior, and displays the\n\
15040response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 15041terminating `#' character and checksum."),
c906108c
SS
15042 &maintenancelist);
15043
9f260536
SM
15044 set_show_commands remotebreak_cmds
15045 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7915a72c
AC
15046Set whether to send break if interrupted."), _("\
15047Show whether to send break if interrupted."), _("\
15048If set, a break, instead of a cntrl-c, is sent to the remote target."),
9f260536
SM
15049 set_remotebreak, show_remotebreak,
15050 &setlist, &showlist);
15051 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15052 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
9a7071a8
JB
15053
15054 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
15055 interrupt_sequence_modes, &interrupt_sequence_mode,
15056 _("\
9a7071a8
JB
15057Set interrupt sequence to remote target."), _("\
15058Show interrupt sequence to remote target."), _("\
15059Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15060 NULL, show_interrupt_sequence,
15061 &remote_set_cmdlist,
15062 &remote_show_cmdlist);
15063
15064 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15065 &interrupt_on_connect, _("\
590042fc
PW
15066Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15067Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
9a7071a8
JB
15068If set, interrupt sequence is sent to remote target."),
15069 NULL, NULL,
15070 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 15071
23860348 15072 /* Install commands for configuring memory read/write packets. */
11cf8741 15073
1a966eab
AC
15074 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15075Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 15076 &setlist);
1a966eab
AC
15077 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15078Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
15079 &showlist);
15080 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
15081 set_memory_write_packet_size, _("\
15082Set the maximum number of bytes per memory-write packet.\n\
15083Specify the number of bytes in a packet or 0 (zero) for the\n\
15084default packet size. The actual limit is further reduced\n\
15085dependent on the target. Specify ``fixed'' to disable the\n\
15086further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
15087 &remote_set_cmdlist);
15088 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
15089 set_memory_read_packet_size, _("\
15090Set the maximum number of bytes per memory-read packet.\n\
15091Specify the number of bytes in a packet or 0 (zero) for the\n\
15092default packet size. The actual limit is further reduced\n\
15093dependent on the target. Specify ``fixed'' to disable the\n\
15094further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
15095 &remote_set_cmdlist);
15096 add_cmd ("memory-write-packet-size", no_class,
15097 show_memory_write_packet_size,
1a966eab 15098 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
15099 &remote_show_cmdlist);
15100 add_cmd ("memory-read-packet-size", no_class,
15101 show_memory_read_packet_size,
1a966eab 15102 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 15103 &remote_show_cmdlist);
c906108c 15104
055303e2 15105 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
15106 &remote_hw_watchpoint_limit, _("\
15107Set the maximum number of target hardware watchpoints."), _("\
15108Show the maximum number of target hardware watchpoints."), _("\
055303e2
AB
15109Specify \"unlimited\" for unlimited hardware watchpoints."),
15110 NULL, show_hardware_watchpoint_limit,
15111 &remote_set_cmdlist,
15112 &remote_show_cmdlist);
15113 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15114 no_class,
480a3f21
PW
15115 &remote_hw_watchpoint_length_limit, _("\
15116Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15117Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
055303e2
AB
15118Specify \"unlimited\" to allow watchpoints of unlimited size."),
15119 NULL, show_hardware_watchpoint_length_limit,
480a3f21 15120 &remote_set_cmdlist, &remote_show_cmdlist);
055303e2 15121 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
15122 &remote_hw_breakpoint_limit, _("\
15123Set the maximum number of target hardware breakpoints."), _("\
15124Show the maximum number of target hardware breakpoints."), _("\
055303e2
AB
15125Specify \"unlimited\" for unlimited hardware breakpoints."),
15126 NULL, show_hardware_breakpoint_limit,
b3f42336 15127 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 15128
1b493192
PA
15129 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15130 &remote_address_size, _("\
4d28ad1e
AC
15131Set the maximum size of the address (in bits) in a memory packet."), _("\
15132Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
15133 NULL,
15134 NULL, /* FIXME: i18n: */
15135 &setlist, &showlist);
c906108c 15136
ca4f7f8b
PA
15137 init_all_packet_configs ();
15138
ff52c073 15139 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
0f71a2f6 15140
ff52c073 15141 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
506fb367 15142
ff52c073
CS
15143 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15144 0);
89be2091 15145
ff52c073
CS
15146 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15147 "catch-syscalls", 0);
82075af2 15148
ff52c073
CS
15149 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15150 "program-signals", 0);
9b224c5e 15151
ff52c073
CS
15152 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15153 "set-working-dir", 0);
bc3b087d 15154
ff52c073
CS
15155 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15156 "startup-with-shell", 0);
aefd8b33 15157
ff52c073
CS
15158 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15159 "environment-hex-encoded", 0);
0a2dde4a 15160
ff52c073
CS
15161 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15162 "environment-reset", 0);
0a2dde4a 15163
ff52c073
CS
15164 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15165 "environment-unset", 0);
0a2dde4a 15166
ff52c073 15167 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
dc8acb97 15168
ff52c073 15169 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
d471ea57 15170
ff52c073 15171 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
b96ec7ac 15172
ff52c073 15173 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
d471ea57 15174
ff52c073 15175 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
d471ea57 15176
ff52c073 15177 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
d471ea57 15178
ff52c073 15179 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
d471ea57 15180
ff52c073 15181 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
d471ea57 15182
ff52c073
CS
15183 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15184 "read-aux-vector", 0);
802188a7 15185
ff52c073
CS
15186 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15187 "pid-to-exec-file", 0);
c78fa86a 15188
ff52c073 15189 add_packet_config_cmd (PACKET_qXfer_features,
23181151
DJ
15190 "qXfer:features:read", "target-features", 0);
15191
ff52c073
CS
15192 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15193 "library-info", 0);
cfa9d6d9 15194
ff52c073 15195 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
2268b414
JK
15196 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15197
ff52c073
CS
15198 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15199 "memory-map", 0);
fd79ecee 15200
ff52c073 15201 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
07e059b5 15202
ff52c073
CS
15203 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15204 0);
dc146f7c 15205
ff52c073
CS
15206 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15207 "read-siginfo-object", 0);
4aa995e1 15208
ff52c073
CS
15209 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15210 "write-siginfo-object", 0);
4aa995e1 15211
ff52c073
CS
15212 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15213 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 15214
ff52c073
CS
15215 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15216 "unwind-info-block", 0);
169081d0 15217
ff52c073
CS
15218 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15219 "get-thread-local-storage-address", 0);
38691318 15220
ff52c073
CS
15221 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15222 "get-thread-information-block-address", 0);
711e434b 15223
ff52c073 15224 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
40ab02ce 15225
ff52c073 15226 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
40ab02ce 15227
ff52c073
CS
15228 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15229 0);
be2a5f71 15230
ff52c073
CS
15231 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15232 "search-memory", 0);
08388c79 15233
ff52c073 15234 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
bd3eecc3 15235
ff52c073 15236 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15a201c8 15237
ff52c073 15238 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
a6b151f1 15239
ff52c073 15240 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
a6b151f1 15241
ff52c073
CS
15242 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15243 0);
a6b151f1 15244
ff52c073 15245 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
a6b151f1 15246
ff52c073
CS
15247 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15248 0);
a6b151f1 15249
ff52c073
CS
15250 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15251 "hostio-readlink", 0);
b9e7b9c3 15252
ff52c073 15253 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
0a93529c 15254
ff52c073 15255 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
2d717e4f 15256
ff52c073 15257 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
2d717e4f 15258
ff52c073 15259 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
a6f3e723 15260
ff52c073 15261 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
82f73884 15262
ff52c073 15263 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
0b16c5cf 15264
ff52c073
CS
15265 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15266 "ConditionalTracepoints", "conditional-tracepoints",
15267 0);
3788aec7 15268
ff52c073
CS
15269 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15270 "ConditionalBreakpoints", "conditional-breakpoints",
15271 0);
3788aec7 15272
ff52c073 15273 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
d3ce09f5
SS
15274 "breakpoint-commands", 0);
15275
ff52c073
CS
15276 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15277 "fast-tracepoints", 0);
782b2b07 15278
ff52c073
CS
15279 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15280 "TracepointSource", 0);
409873ef 15281
ff52c073 15282 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
d914c394 15283
ff52c073
CS
15284 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15285 "static-tracepoints", 0);
0fb4aa4b 15286
ff52c073
CS
15287 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15288 "install-in-trace", 0);
1e4d1764 15289
ff52c073 15290 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
dda83cd7 15291 "qXfer:statictrace:read", "read-sdata-object", 0);
0fb4aa4b 15292
ff52c073
CS
15293 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15294 "read-fdpic-loadmap", 0);
78d85199 15295
ff52c073
CS
15296 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15297 "disable-randomization", 0);
03583c20 15298
ff52c073 15299 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
d1feda86 15300
ff52c073
CS
15301 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15302 "trace-buffer-size", 0);
f6f899bf 15303
ff52c073
CS
15304 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15305 0);
9accd112 15306
ff52c073
CS
15307 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15308 0);
b20a6524 15309
ff52c073
CS
15310 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15311 0);
9accd112 15312
ff52c073 15313 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
9accd112 15314
ff52c073
CS
15315 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15316 "read-btrace-conf", 0);
f4abbc16 15317
ff52c073
CS
15318 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15319 "btrace-conf-bts-size", 0);
d33501a5 15320
ff52c073
CS
15321 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15322 "multiprocess-feature", 0);
73b8c1fd 15323
ff52c073
CS
15324 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15325 "swbreak-feature", 0);
f7e6eed5 15326
ff52c073
CS
15327 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15328 "hwbreak-feature", 0);
f7e6eed5 15329
ff52c073
CS
15330 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15331 "fork-event-feature", 0);
89245bc0 15332
ff52c073
CS
15333 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15334 "vfork-event-feature", 0);
89245bc0 15335
ff52c073
CS
15336 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15337 "btrace-conf-pt-size", 0);
b20a6524 15338
ff52c073
CS
15339 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15340 "verbose-resume-supported", 0);
750ce8d1 15341
ff52c073
CS
15342 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15343 "exec-event-feature", 0);
94585166 15344
ff52c073 15345 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
de979965 15346
ff52c073
CS
15347 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15348 0);
65706a29 15349
ff52c073
CS
15350 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15351 "no-resumed-stop-reply", 0);
f2faf941 15352
ff52c073 15353 add_packet_config_cmd (PACKET_memory_tagging_feature,
2c2e7f87
LM
15354 "memory-tagging-feature", "memory-tagging-feature", 0);
15355
0b736949
DB
15356 /* Assert that we've registered "set remote foo-packet" commands
15357 for all packet configs. */
ca4f7f8b
PA
15358 {
15359 int i;
15360
15361 for (i = 0; i < PACKET_MAX; i++)
15362 {
15363 /* Ideally all configs would have a command associated. Some
15364 still don't though. */
15365 int excepted;
15366
15367 switch (i)
15368 {
15369 case PACKET_QNonStop:
ca4f7f8b
PA
15370 case PACKET_EnableDisableTracepoints_feature:
15371 case PACKET_tracenz_feature:
15372 case PACKET_DisconnectedTracing_feature:
15373 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
15374 case PACKET_qCRC:
15375 /* Additions to this list need to be well justified:
15376 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
15377 excepted = 1;
15378 break;
15379 default:
15380 excepted = 0;
15381 break;
15382 }
15383
15384 /* This catches both forgetting to add a config command, and
15385 forgetting to remove a packet from the exception list. */
ff52c073 15386 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
ca4f7f8b
PA
15387 }
15388 }
15389
37a105a1
DJ
15390 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15391 Z sub-packet has its own set and show commands, but users may
15392 have sets to this variable in their .gdbinit files (or in their
15393 documentation). */
e9e68a56 15394 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c 15395 &remote_Z_packet_detect, _("\
590042fc
PW
15396Set use of remote protocol `Z' packets."), _("\
15397Show use of remote protocol `Z' packets."), _("\
3b64bf98 15398When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 15399packets."),
e9e68a56 15400 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
15401 show_remote_protocol_Z_packet_cmd,
15402 /* FIXME: i18n: Use of remote protocol
15403 `Z' packets is %s. */
e9e68a56 15404 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 15405
0743fc83 15406 add_basic_prefix_cmd ("remote", class_files, _("\
590042fc 15407Manipulate files on the remote system.\n\
a6b151f1 15408Transfer files to and from the remote target system."),
2f822da5 15409 &remote_cmdlist,
0743fc83 15410 0 /* allow-unknown */, &cmdlist);
a6b151f1
DJ
15411
15412 add_cmd ("put", class_files, remote_put_command,
15413 _("Copy a local file to the remote system."),
15414 &remote_cmdlist);
15415
15416 add_cmd ("get", class_files, remote_get_command,
15417 _("Copy a remote file to the local system."),
15418 &remote_cmdlist);
15419
15420 add_cmd ("delete", class_files, remote_delete_command,
15421 _("Delete a remote file."),
15422 &remote_cmdlist);
15423
2d717e4f 15424 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 15425 &remote_exec_file_var, _("\
590042fc
PW
15426Set the remote pathname for \"run\"."), _("\
15427Show the remote pathname for \"run\"."), NULL,
94585166
DB
15428 set_remote_exec_file,
15429 show_remote_exec_file,
15430 &remote_set_cmdlist,
15431 &remote_show_cmdlist);
2d717e4f 15432
c1e36e3e
PA
15433 add_setshow_boolean_cmd ("range-stepping", class_run,
15434 &use_range_stepping, _("\
15435Enable or disable range stepping."), _("\
15436Show whether target-assisted range stepping is enabled."), _("\
15437If on, and the target supports it, when stepping a source line, GDB\n\
15438tells the target to step the corresponding range of addresses itself instead\n\
15439of issuing multiple single-steps. This speeds up source level\n\
15440stepping. If off, GDB always issues single-steps, even if range\n\
15441stepping is supported by the target. The default is on."),
15442 set_range_stepping,
15443 show_range_stepping,
15444 &setlist,
15445 &showlist);
15446
ed2b7c17
TT
15447 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15448Set watchdog timer."), _("\
15449Show watchdog timer."), _("\
15450When non-zero, this timeout is used instead of waiting forever for a target\n\
15451to finish a low-level step or continue operation. If the specified amount\n\
15452of time passes without a response from the target, an error occurs."),
15453 NULL,
15454 show_watchdog,
15455 &setlist, &showlist);
15456
6cc8564b
LM
15457 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15458 &remote_packet_max_chars, _("\
15459Set the maximum number of characters to display for each remote packet."), _("\
15460Show the maximum number of characters to display for each remote packet."), _("\
15461Specify \"unlimited\" to display all the characters."),
15462 NULL, show_remote_packet_max_chars,
15463 &setdebuglist, &showdebuglist);
15464
02349803
SM
15465 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15466 _("Set debugging of remote protocol."),
15467 _("Show debugging of remote protocol."),
15468 _("\
baf2b57f
SM
15469When enabled, each packet sent or received with the remote target\n\
15470is displayed."),
02349803
SM
15471 NULL,
15472 show_remote_debug,
15473 &setdebuglist, &showdebuglist);
baf2b57f
SM
15474
15475 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15476 &remote_timeout, _("\
15477Set timeout limit to wait for target to respond."), _("\
15478Show timeout limit to wait for target to respond."), _("\
15479This value is used to set the time limit for gdb to wait for a response\n\
15480from the target."),
15481 NULL,
15482 show_remote_timeout,
15483 &setlist, &showlist);
15484
449092f6 15485 /* Eventually initialize fileio. See fileio.c */
3f4d92eb 15486 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
754487e2
LM
15487
15488#if GDB_SELF_TEST
15489 selftests::register_test ("remote_memory_tagging",
15490 selftests::test_memory_tagging_functions);
15491#endif
c906108c 15492}